Home > Mobile >  Better way to do coordinate "transform"?
Better way to do coordinate "transform"?

Time:04-26

I have a bunch of vertices - e.g., (321, -190, 475). I need to apply a "transform" to each vertex. For example, if I apply the transform (-3, 1, -2) to the preceding vertex I would get (-475, 321, 190). Transforms can be any permutation of (1, 2, 3) - list(itertools.permutations((1, 2, 3))). In addition, each number can be positive or negative. In other words I could have (3, 2, 1) or (3, -2, -1) or (-3, 2, 1), ...

This seems pretty straight forward, but I feel like my solution is still sub-optimal:

def vert_transform(vertex, offsets):
    x_index = offsets.index(1) if offsets.count(1) else offsets.index(-1)
    y_index = offsets.index(2) if offsets.count(2) else offsets.index(-2)
    z_index = offsets.index(3) if offsets.count(3) else offsets.index(-3)

    match (x_index, y_index, z_index):
        case 0, 1, 2:
            new_vertex = [vertex[0], vertex[1], vertex[2]]
        case 0, 2, 1:
            new_vertex = [vertex[0], vertex[2], vertex[1]]
        case 1, 0, 2:
            new_vertex = [vertex[1], vertex[0], vertex[2]]
        case 1, 2, 0:
            new_vertex = [vertex[2], vertex[0], vertex[1]]
        case 2, 0, 1:
            new_vertex = [vertex[1], vertex[2], vertex[0]]
        case 2, 1, 0:
            new_vertex = [vertex[2], vertex[1], vertex[0]]

    xoff = offsets[x_index]
    yoff = offsets[y_index]
    zoff = offsets[z_index]

    if xoff == -1:
        new_vertex[x_index] = -new_vertex[x_index]
    if yoff == -2:
        new_vertex[y_index] = -new_vertex[y_index]
    if zoff == -3:
        new_vertex[z_index] = -new_vertex[z_index]

    return new_vertex

I feel like there should be a better/simpler way to do this - any suggestions?

Thanks in advance,

--Jim

CodePudding user response:

This can be accomplished through a simple loop:

# from https://stackoverflow.com/q/1986152/#comment90218429_16726462
def sign(a):
    return -1 if x < 0 else 1

def vert_transform(vertex, offsets):
    return tuple(vertex[abs(offset)   1] * sign(offset) for offset in offsets)

CodePudding user response:

You could do it the following way:

vertex = [321, -190, 475]
offset = [-3, 1, -2]

sign = [-1 if e < 0 else 1 for e in offset]
indices = [abs(e) for e in offset]

new_vertex = [vertex[e-1]*s for e, s in zip(indices, sign)]

  • Related