4 void free_bvh_tree(struct bvhnode *tree)
6 struct bvhnode *node, *tmp;
20 int ray_triangle(cgm_ray *ray, struct triangle *tri, float tmax, struct rayhit *hit)
23 cgm_vec3 vdir, bc, pos;
25 if(fabs(ndotdir = cgm_vdot(&ray->dir, &tri->norm)) <= 1e-6) {
30 cgm_vsub(&vdir, &ray->origin);
32 if((t = cgm_vdot(&tri->norm, &vdir) / ndotdir) <= 1e-6 || t > tmax) {
36 cgm_raypos(&pos, ray, t);
37 cgm_bary(&bc, &tri->v[0].pos, &tri->v[1].pos, &tri->v[2].pos, &pos);
39 if(bc.x < 0.0f || bc.x > 1.0f) return 0;
40 if(bc.y < 0.0f || bc.y > 1.0f) return 0;
41 if(bc.z < 0.0f || bc.z > 1.0f) return 0;
50 hit->v.norm.x = tri->v[0].norm.x * bc.x + tri->v[1].norm.x * bc.y + tri->v[2].norm.x * bc.z;
51 hit->v.norm.y = tri->v[0].norm.y * bc.x + tri->v[1].norm.y * bc.y + tri->v[2].norm.y * bc.z;
52 hit->v.norm.z = tri->v[0].norm.z * bc.x + tri->v[1].norm.z * bc.y + tri->v[2].norm.z * bc.z;
54 hit->v.tex.x = tri->v[0].tex.x * bc.x + tri->v[1].tex.x * bc.y + tri->v[2].tex.x * bc.z;
55 hit->v.tex.y = tri->v[0].tex.y * bc.x + tri->v[1].tex.y * bc.y + tri->v[2].tex.y * bc.z;
60 #define SLABCHECK(dim) \
62 invdir = 1.0f / ray->dir.dim; \
63 t0 = (box->vmin.dim - ray->origin.dim) * invdir; \
64 t1 = (box->vmax.dim - ray->origin.dim) * invdir; \
70 tmin = t0 > tmin ? t0 : tmin; \
71 tmax = t1 < tmax ? t1 : tmax; \
72 if(tmax <= tmin) return 0; \
75 int ray_aabox_any(cgm_ray *ray, struct aabox *box, float tmax)
77 float invdir, t0, t1, tmp;
87 int ray_bvhnode(cgm_ray *ray, struct bvhnode *bn, float tmax, struct rayhit *hit)
92 if(!ray_aabox_any(ray, &bn->aabb, tmax)) {
97 for(i=0; i<bn->num_faces; i++) {
98 if(ray_triangle(ray, bn->faces + i, tmax, 0)) {
106 for(i=0; i<bn->num_faces; i++) {
107 if(ray_triangle(ray, bn->faces + i, tmax, hit) && hit->t < hit0.t) {