0

I'm working on a 3d engine and implementing a triangle sorting system by distance between the triangle's normal + the triangle's position and <0,0,0>. But the problem is that some triangles are counter-clockwise and others clockwise, so I made two normals that are on opposite direction. But now I have to determine which normal to use.

Here is the necessary code:

// executes this code for every triangle that has to be drawn
for (int i = 0; i < tridrawcount; i++)
{
    triangle &listtri = tridrawlist[i];
   
    vec3 pnorm;
    vec3 norm; 
    vec3 norm2;
    vec3 line;
    vec3 line2;
    vec3 apos;
    vec3 ppos;
    vec3 ppos2;
    
    line = listtri.vpos2 - listtri.vpos;
    line2 = listtri.vpos3 - listtri.vpos;
    norm = line.cross(line2);
    norm2 = line2.cross(line);
    apos = (listtri.vpos + listtri.vpos2 + listtri.vpos3)/3; // basically the center of the triangle
    float length = norm.mag();
    float length2 = norm2.mag();
  
    norm = norm / length; 
    norm2 = norm2 / length2;

    ppos = norm + apos; 
    ppos2 = norm2 + apos;

    float dist = sqrt(pow(0 - ppos.x,2) + pow(0 - ppos.y, 2) + pow(0 - ppos.z, 2)); 
    float dist2 = sqrt(pow(0 - ppos2.x, 2) + pow(0 - ppos2.y, 2) + pow(0 - ppos2.z, 2));
}
trincot
  • 317,000
  • 35
  • 244
  • 286

1 Answers1

2

Given three vertices {a, b, c} of a triangle the next formula

orientation = (ax-cx)*(by-cy) - (ay-cy)*(bx-cx)

returns:

  • a positive value if vertices a, b, and c are arranged in a counter-clockwise order
  • zero if they are collinear
  • a negative value otherwise

Depending on this value you use your norm or norm2 normals

Ripi2
  • 7,031
  • 1
  • 17
  • 33
  • does this formula work in 3d if so I'm experiencing problems with it – user18504606 Aug 05 '23 at 20:37
  • The problem is consistency between neighboring triangles when the orientation of the triangles can be CW or CCW (usually as viewed from outside the mesh if the mesh represents the boundary of a solid). This is actually a difficult problem and there have been research papers written on it. – wcochran Aug 07 '23 at 04:06
  • @user18504606 If the triangle is not vertical (a,b,c projected over plane z=0 are not co-linear) using the formula (without "z" coord) works well... depending if you look a the triangle from ceil or from floor, as it changes the sign. – Ripi2 Aug 07 '23 at 17:16