Question

I have an array of positions:

float positions[] = {
-42.5806f, 27.8838f, 49.9729f,
-14.9092f, 26.1262f, 54.3193f,
-28.5149f, 32.7642f, 59.4234f,
-28.4439f, 23.9779f, 55.7947f,
21.8174f, 27.4106f, 54.9496f,
48.8382f, 28.1005f, 50.7636f,
34.1595f, 33.8675f, 58.1264f,
35.4594f, 24.8225f, 56.0585f,
-55.9764f, 36.8791f, 42.2097f,
-9.83348f, 39.9998f, 70.2909f,
};

I would like to transform each position using three glm::mat4 matrices; model, view and projection. In order to transform each position, I need to take each row and multiply it to the matrices:

tPositions = proj * view * model * glm::vec4(position[0], position[1], position[2], 1.0);

Note that I have to convert each position to a vec4 in order to get the multiplication correct.

What I have tried:

float tPositions;
for( unsigned int i=0; i < 9; i++ ){

    glm::vec4 v = glm::vec4(positions[0], positions[1], positions[2], 1.0);
    tPositions[i] = proj * view * model * v;

}

But this won't work since the index of positions is wrong (and properbly more).

My question is:

How do I loop through the array in C++, do the transformation for each position and then output the transformed positions in a new array, the best possible way?

Was it helpful?

Solution

you need to skip three numbers each iteration, plus the result is a glm::vec4 not a float

std::vector<glm::vec4> tPositions;
for( unsigned int i=0; i < sizeof(positions)/sizeof(float); i+=3 ){

    glm::vec4 v = glm::vec4(positions[i], positions[i+1], positions[i+2], 1.0);
    tPositions.push_back( proj * view * model * v );

}

OTHER TIPS

An alternate answer just for fun. Performing these repeated multiplications for the index is probably not as efficient.

std::vector<glm::vec4> tPositions;
const int numVecs = sizeof(positions)/(3 * sizeof(float));
for( unsigned int i=0; i < numVecs; ++i ){
    glm::vec4 v = glm::vec4(positions[(3 * i)], positions[(3 * i) + 1], positions[(3 * i) + 2], 1.0);
    tPositions.push_back( proj * view * model * v );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top