Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Triangle class
- // defines a Triangle shape
- import javax.vecmath.*;
- public class Triangle extends Shape {
- private Vector3f p0, p1, p2; // three vertices make a triangle
- private Vector3f n0, n1, n2; // normal at each vertex
- public Triangle() {
- }
- public Triangle(Vector3f _p0, Vector3f _p1, Vector3f _p2, Material mat) {
- p0 = new Vector3f(_p0);
- p1 = new Vector3f(_p1);
- p2 = new Vector3f(_p2);
- material = mat;
- Vector3f normal = new Vector3f();
- Vector3f v1 = new Vector3f();
- Vector3f v2 = new Vector3f();
- v1.sub(p1, p0);
- v2.sub(p2, p0);
- normal.cross(v1, v2);
- normal.normalize(); // compute default normal:
- n0 = new Vector3f(normal); // the normal of the plane defined by the triangle
- n1 = new Vector3f(normal);
- n2 = new Vector3f(normal);
- }
- public Triangle(Vector3f _p0, Vector3f _p1, Vector3f _p2,
- Vector3f _n0, Vector3f _n1, Vector3f _n2,
- Material mat) {
- p0 = new Vector3f(_p0);
- p1 = new Vector3f(_p1);
- p2 = new Vector3f(_p2);
- material = mat;
- n0 = new Vector3f(_n0); // the normal of the plane defined by the triangle
- n1 = new Vector3f(_n1);
- n2 = new Vector3f(_n2);
- }
- public HitRecord hit(Ray ray, float tmin, float tmax) {
- /* YOUR WORK HERE: complete the triangle's intersection routine
- * Normal should be computed by a bilinear interpolation from n0, n1 and n2
- * using the barycentric coordinates: alpha, beta, (1.0 - alpha - beta) */
- Vector3f o = ray.getOrigin();
- Vector3f d = ray.getDirection();
- Matrix3f matrix = new Matrix3f(-d.x, p1.x - p0.x, p2.x - p0.x, -d.y, p1.y - p0.y, p2.y - p0.y, -d.z, p1.z - p0.z, p2.z - p0.z);
- Vector3f finalcol = new Vector3f(o.x - p0.x, o.y - p0.y, o.z - p0.z);
- Matrix3f matrixT = new Matrix3f(matrix);
- matrixT.setColumn(0, finalcol);
- Matrix3f matrixB = new Matrix3f(matrix);
- matrixB.setColumn(1, finalcol);
- Matrix3f matrixG = new Matrix3f(matrix);
- matrixG.setColumn(2, finalcol);
- float det = matrix.determinant();
- if (det == 0) {
- return null;
- }
- float t = matrixT.determinant() / det;
- float beta = matrixB.determinant() / det;
- float gamma = matrixG.determinant() / det;
- float alpha = 1.0f - beta - gamma;
- if (t < tmin || t > tmax) {
- return null;
- }
- if (alpha < 0 || alpha > 1 || beta < 0 || beta > 1 || gamma < 0 || gamma > 1) {
- return null;
- }
- Vector3f p = ray.pointAt(t);
- HitRecord rec = new HitRecord();
- rec.pos = p;
- rec.t = t;
- rec.material = material;
- Vector3f scaledAlpha = new Vector3f(n0);
- scaledAlpha.scale(alpha);
- Vector3f scaledBeta = new Vector3f(n1);
- scaledBeta.scale(beta);
- Vector3f scaledGamma = new Vector3f(n2);
- scaledGamma.scale(gamma);
- rec.normal = new Vector3f();
- rec.normal.add(scaledAlpha);
- rec.normal.add(scaledBeta);
- rec.normal.add(scaledGamma);
- rec.normal.normalize();
- return rec;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement