How do I compute the linear index of a 3D coordinate and vice versa?

前端 未结 2 643
长情又很酷
长情又很酷 2021-02-06 00:30

If I have a point (x, y z), how do I find the linear index, i for that point? My numbering scheme would be (0,0,0) is 0, (1, 0, 0) is 1, . . ., (0, 1, 0) is the max-x-dimension,

2条回答
  •  借酒劲吻你
    2021-02-06 01:01

    There are a few ways to map a 3d coordinate to a single number. Here's one way.

    some function f(x,y,z) gives the linear index of coordinate(x,y,z). It has some constants a,b,c,d which we want to derive so we can write a useful conversion function.

    f(x,y,z) = a*x + b*y + c*z + d
    

    You've specified that (0,0,0) maps to 0. So:

    f(0,0,0) = a*0 + b*0 + c*0 + d = 0
    d = 0
    f(x,y,z) = a*x + b*y + c*z
    

    That's d solved. You've specified that (1,0,0) maps to 1. So:

    f(1,0,0) = a*1 + b*0 + c*0 = 1
    a = 1
    f(x,y,z) = x + b*y + c*z
    

    That's a solved. Let's arbitrarily decide that the next highest number after (MAX_X, 0, 0) is (0,1,0).

    f(MAX_X, 0, 0) = MAX_X
    f(0, 1, 0) = 0 + b*1 + c*0 = MAX_X + 1
    b = MAX_X + 1
    f(x,y,z) = x + (MAX_X + 1)*y + c*z
    

    That's b solved. Let's arbitrarily decide that the next highest number after (MAX_X, MAX_Y, 0) is (0,0,1).

    f(MAX_X, MAX_Y, 0) = MAX_X + MAX_Y * (MAX_X + 1)
    f(0,0,1) = 0 + (MAX_X + 1) * 0  + c*1 = MAX_X + MAX_Y * (MAX_X + 1) + 1
    c = MAX_X + MAX_Y * (MAX_X + 1) + 1
    c = (MAX_X + 1) + MAX_Y * (MAX_X + 1)
    c = (MAX_X + 1) * (MAX_Y + 1)
    

    now that we know a, b, c, and d, we can write your function as follows:

    function linearIndexFromCoordinate(x,y,z, max_x, max_y){
        a = 1
        b = max_x + 1
        c = (max_x + 1) * (max_y + 1)
        d = 0
        return a*x + b*y + c*z + d
    }
    

    You can get the coordinate from the linear index by similar logic. I have a truly marvelous demonstration of this, which this page is too small to contain. So I'll skip the math lecture and just give you the final method.

    function coordinateFromLinearIndex(idx, max_x, max_y){
        x =  idx % (max_x+1)
        idx /= (max_x+1)
        y = idx % (max_y+1)
        idx /= (max_y+1)
        z = idx
        return (x,y,z)
    }
    

提交回复
热议问题