package graphics; //clips triangle against plane public class ClipPlane { private double a, b, c, d; //plane coordinates public ClipPlane(double _a, double _b, double _c, double _d) { a = _a; b = _b; c = _c; d = _d; } //plane function for a point private double planeFunction(double x, double y, double z) { return a*x + b*y + c*z + d; } public int clipTriangle(double[][] triangle, double[][] poly) { int numVerts = 0; for (int i = 0; i< 3; i++) //go thru each vertex { double[] a = triangle[i], b = triangle[(i+1)%3]; double fA = planeFunction(a[0], a[1], a[2]); double fB = planeFunction(b[0], b[1], b[2]); if (fA <= 0) //is vertex in front of camera? poly[numVerts++] = (double[])a.clone(); //are points on opposite side of plane? if (fA * fB < 0) { //interpolate between points a and b double t = -fA / (fB - fA); if (t > 1 || t < 0) System.err.println("Warning: In ClipPlane.clipTriangle - t seems off... t = " + t); //create new vertex double[] newVert = (double[])a.clone(); for (int j=0; j 0 && fB > 0) return false; //each vertex is on opposite sides of the camera if (fA * fB < 0) { //interpolate between points a and b double t = -fA / (fB - fA); if (t > 1 || t < 0) System.err.println("Warning: In ClipPlane.clipTriangle - t seems off... t = " + t); //create new vertex double[] newVert = new double[a.length]; for (int i=0; i 0) a[i] = newVert[i]; else b[i] = newVert[i]; } } return true; } //linear interpolation public double lerp(double t, double a, double b) { return a + (b-a)*t; } public void dumpVertices(double[][] vertices) { for (int i = 0; i < vertices.length; i++) System.err.println("("+vertices[i][0]+", "+vertices[i][1]+", "+vertices[i][2]+")"); } }