PDA

View Full Version : Am I calculating normal for cube correctly?

paul_g_griffiths
01-22-2017, 04:30 AM
Heres the code:

glm::f32 x = size.x / 2.0f;
glm::f32 y = size.y / 2.0f;
glm::f32 z = size.z / 2.0f;

glm::vec3 a0 = glm::vec3(+x, +y, +z);
glm::vec3 a1 = glm::vec3(-x, +y, +z);
glm::vec3 a2 = glm::vec3(-x, -y, +z);
glm::vec3 a3 = glm::vec3(+x, -y, +z);
glm::vec3 a4 = glm::vec3(+x, +y, -z);
glm::vec3 a5 = glm::vec3(-x, +y, -z);
glm::vec3 a6 = glm::vec3(-x, -y, -z);
glm::vec3 a7 = glm::vec3(+x, -y, -z);

glm::vec3 verts[] = {
a1, a2, a3, a3, a0, a1,
a2, a6, a7, a7, a3, a2,
a6, a5, a4, a4, a7, a6,
a5, a1, a0, a0, a4, a5,
a0, a3, a7, a7, a4, a0,
a5, a6, a2, a2, a1, a5
};

glm::vec3 norm[36];

for (int i = 0; i < 36; i += 3)
{
glm::vec3 normal = glm::normalize(
glm::cross(
glm::vec3(verts[i + 1]) - glm::vec3(verts[i]),
glm::vec3(verts[i + 2]) - glm::vec3(verts[i])));

norm[i] = normal;
norm[i + 1] = normal;
norm[i + 2] = normal;
}

paul_g_griffiths
01-22-2017, 12:20 PM
I believe I am because it looks ok.

BBeck1
01-23-2017, 04:40 AM
It's hard to argue with success. You can calculate the normals of a cube any way you like. But there are two ways that come to my mind.

You can use a vector cross product between two edges of a triangle to get a normal for the facing of that triangle. When 3 triangles share a corner, you can either use that if you want it basically flat shaded or you can average the three vectors.

If the 3 triangles share a single vertex, you pretty much have no choice but to average them and store a single value. With this averaged normal, you can feed it to a shader and the shader has settings that control whether it will smooth shade the triangle or flat shade it. So, this is not necessarily a bad thing.

If you want however, you can separate the three triangles so that they no longer share a common vertex and give them all 3 separate normals forcing flat shading and such.

But the basic rule of software is that "if the user is happy, you did it right." Efficient code is something to strive for. Readable code makes it easier to debug and continue to work on the code. But once it's compiled, all that matters is that the user is happy. So don't get too hung up on the "correct way" to do it. Find a way that works and learn as you go to increase efficiency, your knowledge of the subject, and your control over the code. The way I see it, it's a journey and I'm not sure you ever reach the destination.