erebus

diff liberebus/src/geomobj.cc @ 4:93894c232d65

more changes across the board
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 29 Apr 2014 07:38:40 +0300
parents
children e2d9bf168a41
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/liberebus/src/geomobj.cc	Tue Apr 29 07:38:40 2014 +0300
     1.3 @@ -0,0 +1,87 @@
     1.4 +#include <float.h>
     1.5 +#include "geomobj.h"
     1.6 +
     1.7 +static LambertRefl lambert;
     1.8 +
     1.9 +GeomObject::GeomObject()
    1.10 +{
    1.11 +	brdf = &lambert;
    1.12 +}
    1.13 +
    1.14 +ObjType GeomObject::get_type() const
    1.15 +{
    1.16 +	return ObjType::geom;
    1.17 +}
    1.18 +
    1.19 +bool GeomObject::intersect(const Ray &ray, RayHit *hit) const
    1.20 +{
    1.21 +	return false;
    1.22 +}
    1.23 +
    1.24 +// --- class Sphere ---
    1.25 +
    1.26 +bool Sphere::intersect(const Ray &ray, RayHit *hit) const
    1.27 +{
    1.28 +	// assumes center is the origin and radius is 1
    1.29 +	float a = dot_product(ray.dir, ray.dir);
    1.30 +	float b = 2.0 * dot_product(ray.dir, ray.origin);
    1.31 +	float c = dot_product(ray.origin, ray.origin) - 1.0;
    1.32 +
    1.33 +	float d = b * b - 4.0 * a * c;
    1.34 +	if(d < 1e-4) return false;
    1.35 +
    1.36 +	float sqrt_d = sqrt(d);
    1.37 +	float t0 = (-b + sqrt_d) / (2.0 * a);
    1.38 +	float t1 = (-b - sqrt_d) / (2.0 * a);
    1.39 +
    1.40 +	if(t0 < 1e-4) t0 = t1;
    1.41 +	if(t1 < 1e-4) t1 = t0;
    1.42 +	float t = t0 < t1 ? t0 : t1;
    1.43 +	if(t < 1e-4) return false;
    1.44 +
    1.45 +	if(hit) {
    1.46 +		hit->dist = t;
    1.47 +		hit->obj = this;
    1.48 +		hit->subobj = 0;
    1.49 +	}
    1.50 +	return true;
    1.51 +}
    1.52 +
    1.53 +// --- class Box ---
    1.54 +
    1.55 +bool Box::intersect(const Ray &ray, RayHit *hit) const
    1.56 +{
    1.57 +	return false;
    1.58 +}
    1.59 +
    1.60 +// --- class Triangle ---
    1.61 +
    1.62 +bool Triangle::intersect(const Ray &ray, RayHit *hit) const
    1.63 +{
    1.64 +	return false;
    1.65 +}
    1.66 +
    1.67 +// --- class Mesh ---
    1.68 +
    1.69 +bool Mesh::intersect(const Ray &ray, RayHit *hit) const
    1.70 +{
    1.71 +	RayHit nearest;
    1.72 +	nearest.dist = FLT_MAX;
    1.73 +
    1.74 +	for(size_t i=0; i<faces.size(); i++) {
    1.75 +		if(faces[i].intersect(ray, hit)) {
    1.76 +			if(!hit) return true;
    1.77 +			if(hit->dist < nearest.dist) {
    1.78 +				nearest = *hit;
    1.79 +			}
    1.80 +		}
    1.81 +	}
    1.82 +
    1.83 +	if(nearest.dist < FLT_MAX) {
    1.84 +		*hit = nearest;
    1.85 +		hit->subobj = hit->obj;
    1.86 +		hit->obj = this;
    1.87 +		return true;
    1.88 +	}
    1.89 +	return false;
    1.90 +}