// 3D Engine // // Triangle primative // // Stores triangle of vectors produced after transformation and associated colour. // // Author Matthew Caryl // Created 5.5.97 package ADT; import java.awt.Color; import java.awt.Graphics; public class Triangle { // // Public interface // public Triangle(Vector V1, Vector V2, Vector V3, Vector normal, Color color) { v1 = V1; v2 = V2; v3 = V3; display_red = basic_red = color.getRed() / 255f; display_green = basic_green = color.getGreen() / 255f; display_blue = basic_blue = color.getBlue() / 255f; display_color = color; triangle_normal = normal; } public void light(Vector light) { NdotL = Math.min(1f, Math.max(0f, triangle_normal.dot(light))); } public boolean forwardFacing() { return v1.x * (v2.y - v3.y) + v2.x * (v3.y - v1.y) + v3.x * (v1.y - v2.y) > 0; } public boolean inFront() { return v1.z < 0 || v2.z < 0 || v3.z < 0; } public boolean aheadTriangle(Triangle triangle) { //return Math.max(v1.z, Math.max(v2.z, v3.z)) > Math.max(triangle.v1.z, Math.max(triangle.v2.z, triangle.v3.z)); return (v1.z + v2.z + v3.z) > (triangle.v1.z + triangle.v2.z + triangle.v3.z); } public void draw(Graphics graphics, int[] xs, int[] ys, float ambient, float diffuse) { xs[0] = (int) v1.x; ys[0] = (int) v1.y; xs[1] = (int) v2.x; ys[1] = (int) v2.y; xs[2] = (int) v3.x; ys[2] = (int) v3.y; float d = diffuse * NdotL; float this_red = ambient * basic_red + d * basic_red; float this_green = ambient * basic_green + d * basic_green; float this_blue = ambient * basic_blue + d * basic_blue; if (this_red != display_red || this_green != display_green || this_blue != display_blue) { display_red = this_red; display_green = this_green; display_blue = this_blue; display_color = new Color(this_red, this_green, this_blue); } graphics.setColor(display_color); graphics.fillPolygon(xs, ys, 3); } // // Private interface // private Vector v1, v2, v3; private Vector triangle_normal; private float NdotL; private float basic_red, basic_green, basic_blue; private float display_red, display_green, display_blue; private Color display_color; }