111 lines
2.9 KiB
C++
111 lines
2.9 KiB
C++
|
|
#include "Union.h"
|
|
#include <iostream>
|
|
#include <vector>
|
|
using namespace std;
|
|
|
|
Union::Union(const vector< refptr<Shape> > & shapes)
|
|
{
|
|
int num_shapes = shapes.size();
|
|
if (num_shapes > 2)
|
|
{
|
|
m_shape2 = shapes[num_shapes - 1];
|
|
vector< refptr<Shape> > rest = shapes;
|
|
rest.pop_back();
|
|
m_shape1 = new Union(rest);
|
|
}
|
|
else if (num_shapes == 2)
|
|
{
|
|
m_shape1 = shapes[0];
|
|
m_shape2 = shapes[1];
|
|
}
|
|
else
|
|
{
|
|
cerr << __FILE__ << ": " << __LINE__
|
|
<< ": error: Union::Union() called with only "
|
|
<< num_shapes
|
|
<< " sub-shapes!"
|
|
<< endl;
|
|
exit(4);
|
|
}
|
|
}
|
|
|
|
Shape::IntersectionList Union::intersect(refptr<Shape> _this, const Ray & ray)
|
|
{
|
|
Ray ray_inv = m_inverse.transform_ray(ray);
|
|
IntersectionList res1 = m_shape1->intersect(m_shape1, ray_inv);
|
|
IntersectionList res2 = m_shape2->intersect(m_shape2, ray_inv);
|
|
BoolIntersectionList merged(res1, res2, ray_inv.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_inv.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_inv.getDirection() % normal);
|
|
bool front = dot > 0.0;
|
|
bool left = merged[i].left;
|
|
if (front)
|
|
{
|
|
if (left)
|
|
in1 = true;
|
|
else
|
|
in2 = true;
|
|
if (!in_bool && (in1 || in2))
|
|
{
|
|
/* we found an intersection point with the boolean object */
|
|
in_bool = true;
|
|
res.add( merged[i].intersection.transform(m_transform) );
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (left)
|
|
in1 = false;
|
|
else
|
|
in2 = false;
|
|
if (in_bool && !(in1 || in2))
|
|
{
|
|
/* we found an intersection point with the boolean object */
|
|
res.add( merged[i].intersection.transform(m_transform) );
|
|
in_bool = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
return res;
|
|
}
|
|
|
|
refptr<Shape> Union::clone()
|
|
{
|
|
Union * s = new Union(*this);
|
|
s->m_shape1 = m_shape1->clone();
|
|
s->m_shape2 = m_shape2->clone();
|
|
return refptr<Shape>(s);
|
|
}
|