0

I'm printing a triangle in OpenGL like this :

glBegin(GL_TRIANGLES);
glVertex3f(1,2,3);
glVertex3f(4,6,8);
glVertex3f(5,7,9);
glEnd();

I want to calculate normal of each vertex of the triangle and I want to print triangle like this :

glBegin(GL_TRIANGLES);
glNormal3f(?,?,?);
glVertex3f(1,2,3);
glNormal3f(?,?,?);
glVertex3f(4,6,8);
glNormal3f(?,?,?);
glVertex3f(5,7,9);
glEnd();

In short, how can I calculate normals for each vertex for this triangle?

genpfault
  • 51,148
  • 11
  • 85
  • 139
jason
  • 6,962
  • 36
  • 117
  • 198

1 Answers1

2

You need to calculate cross product of 2 edges vectors.

Nx = Ay*Bz-Az*By;
Ny = Az*Bx-Ax*Bz;
Nz = Ax*By-Ay*Bx;

Where A and B are: P1-P0 and P2-P1 Where P0, P1, P2 arę vertex coords.

N should be normalized and assigned to every vertex.

float len=sqrt(Nx*Nx+Ny*Ny+Nz*Nz);
Nx/=len;
Ny/=len;
Nz/=len;

Please note that sign of the N normal will be flipped if P0 P1 P2 arę provided in reverse order (clock wise).

Anonymous
  • 2,122
  • 19
  • 26
  • Should I give the same normal for each vertex? Thank you. – jason Dec 29 '14 at 14:11
  • It should be mentioned, that the result has to be normalized. – BDL Dec 29 '14 at 14:11
  • @jason: If you only have one triangle, than yes, the normal will be the same for each vertex. A normal is defined as being orthogonal to the underlying surface. In case of a triangle this surface is flat and thus has the same normal in each point. In a triangle mesh (multiple connected triangles), this will in many cases only be a approximation for a more complex (curved) surface. In this case the normal can be different over the triangles. – BDL Dec 29 '14 at 14:14
  • 1
    in such complex surface case it is also possible to average normals on given vertex from all triangles sharing it. – Anonymous Dec 29 '14 at 14:31
  • @BDL Thank you for your comment. In fact, I have 6 triangles which compose a simple shape.So, I would be good to go if I apply the formula above? – jason Dec 29 '14 at 14:50
  • 1
    @jason: Depends on the shape. A cube for example has one specific normal for each side. A sphere approximated by the same number of triangles will have different normal in each point. To sum it up: If you want smoot transitions between triangles, you have to use a more complex technique. If you want hard edges, than using one normal per triangle is fine. A more detailed explanation can be found in [this post](http://stackoverflow.com/questions/6656358/calculating-normals-in-a-triangle-mesh). – BDL Dec 29 '14 at 14:57