#include "Subtract.h" #include using namespace std; Subtract::Subtract(const vector< refptr > & shapes) { int num_shapes = shapes.size(); if (num_shapes > 2) { m_shape2 = shapes[num_shapes - 1]; vector< refptr > rest = shapes; rest.pop_back(); m_shape1 = new Subtract(rest); } else if (num_shapes == 2) { m_shape1 = shapes[0]; m_shape2 = shapes[1]; } else { cerr << __FILE__ << ": " << __LINE__ << ": error: Subtract::Subtract() called with only " << num_shapes << " sub-shapes!" << endl; exit(4); } } Shape::IntersectionList Subtract::intersect(refptr _this, const Ray & ray) { IntersectionList res1 = m_shape1->intersect(m_shape1, ray); IntersectionList res2 = m_shape2->intersect(m_shape2, ray); BoolIntersectionList merged(res1, res2, ray.getOrigin()); IntersectionList res; bool in1 = false, in2 = false; /* initially go through the merged intersections to see whether * the ray started inside one of the sub-objects */ for (int i = 0, sz = merged.size(), saw1 = 0, saw2 = 0; i < sz && (!saw1 || !saw2); i++) { Vector normal = merged[i].intersection.normal; double dot = - (ray.getDirection() % normal); bool back = dot < 0.0; bool left = merged[i].left; if (back) { if (left && !saw1) in1 = true; else if (!left && !saw2) in2 = true; } if (left) saw1 = 1; else saw2 = 1; } bool in_bool = in1 && !in2; for (int i = 0, sz = merged.size(); i < sz; i++) { Vector normal = merged[i].intersection.normal; double dot = - (ray.getDirection() % normal); bool front = dot > 0.0; bool left = merged[i].left; if (left) in1 = front; else in2 = front; if (!in_bool && in1 && !in2) { /* we found an intersection point * to get into the boolean object */ in_bool = true; BoolIntersection bi = merged[i]; Intersection i = bi.intersection; if ( ! left ) /* if this point came from object B (A - B) */ i.normal = - i.normal; res.add(i); } else if (in_bool && !(in1 && !in2)) { /* we found an intersection point * to get out of the boolean object */ BoolIntersection bi = merged[i]; Intersection i = bi.intersection; if ( ! left ) /* if this point came from object B (A - B) */ i.normal = - i.normal; res.add(i); in_bool = false; } } return res; }