Skip to main content
gamedev.net
🔒 Locked

clipping help

Started by staticVoid2 0 replies 400+ views
Original Post
staticVoid2
staticVoid2
I'm trying to implement the sutherland hodgman algorithm in code but it seems to be giving me inaccurate results - It work's sometimes, here's the code I use:


Vector finito[] = new Vector[4];
Vector P = vertices[vertices.length-1];
Vector C;
int tracker = 0;

// P = previous vertex
// C = current vertex

for(int c = 0; c < vertices.length; c++) {

   C = vertices[c];

      if(C.z < 0) { // current point inside
         if(P.z < 0) { // both points inside
            finito[tracker] = C;
               tracker++;
         } else { // current point inside but previous not
            finito[tracker] = Clipping.calculateIntersection(P, C, new Vector(0, 0, -1));
               tracker++;
            finito[tracker] = C;
               tracker++;
         }

      } else if(P.z < 0) { // previous point inside but current not
         finito[tracker] = Clipping.calculateIntersection(C, P, new Vector(0, 0, -1));
         tracker++;
      }

   P = C; 

}




and heres the calculateIntersection function:


   public static Vector calculateIntersection(Vector v1, Vector v2, Vector planeNormal) {
      double dist1 = Vectors.dotProduct(v1, planeNormal);
      double dist2 = Vectors.dotProduct(v2, planeNormal);

      if(dist1 < 0)
         dist1 = -dist1;

      if(dist2 < 0)
         dist2 = -dist2;

      double totalDistance = dist1 + dist2;
      double ratio;

      if(totalDistance != 0)
         ratio = dist1/totalDistance;
      else
         ratio = 0;



      return new Vector(v1.x + (ratio * (v2.x - v1.x)),
                        v1.y + (ratio * (v2.y - v1.y)),
                        v1.z + (ratio * (v2.z - v1.z)) );
   }





firstly I loop through all the faces/triangles, then convert their vertices into camera space. the vertices array is just the 3 converted points of the triangle and the finito array is just to store the final output points of the poly. I thought it might have been the calculateIntersection function but i've tested this a few times and it seems to be giving the correct results, and ideas what might be wrong? [Edited by - staticVoid2 on January 20, 2008 4:18:48 PM]
staticVoid2
staticVoid2
sorted - It was one of those divide by 0 errors - when i found the intersection it gave me somthing like(x, y, 0) then I converted it, but it works fine now when i use (x, y, -1).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.