I have modified the HitBoundingBox algorithm that can be found on some sources (link) to suit my structs and API:
Point rayaabbintersection(Point minB, Point maxB, Point origin, Point dir) {
char inside = TRUE;
char quadrant[2];
register int i;
int whichPlane;
double maxT[2];
double candidatePlane[2];
/* Find candidate planes; this loop can be avoided if
rays cast all from the eye(assume perpsective view) */
for (i=0; i<2; i++)
if(origin.arr[i] < minB.arr[i]) {
quadrant[i] = LEFT;
candidatePlane[i] = minB.arr[i];
inside = FALSE;
}else if (origin.arr[i] > maxB.arr[i]) {
quadrant[i] = RIGHT;
candidatePlane[i] = maxB.arr[i];
inside = FALSE;
}else {
quadrant[i] = MIDDLE;
}
/* Ray origin inside bounding box */
if(inside) {
return origin;
}
/* Calculate T distances to candidate planes */
for (i = 0; i < 2; i++)
if (quadrant[i] != MIDDLE && dir.arr[i] !=0.)
maxT[i] = (candidatePlane[i] - origin.arr[i]) / dir.arr[i];
else
maxT[i] = -1.;
/* Get largest of the maxT's for final choice of intersection */
whichPlane = 0;
for (i = 1; i < 2; i++)
if (maxT[whichPlane] < maxT[i])
whichPlane = i;
float coord[2];
/* Check final candidate actually inside box */
if (maxT[whichPlane] < 0.) return (Point) {.x = NAN, .y = NAN};
for (i = 0; i < 2; i++)
if (whichPlane != i) {
coord[i] = origin.arr[i] + maxT[whichPlane] * dir.arr[i];
if (coord[i] < minB.arr[i] || coord[i] > maxB.arr[i])
return (Point) {.x = NAN, .y = NAN};
} else {
coord[i] = candidatePlane[i];
}
return (Point) {.x = coord[0], .y = coord[1]}; /* ray hits box */
}
Excuse the bad code, it's a copy paste of the original with a few changes :P. The reason for all those iterations over i is because the original was designed allow technically any amount of dimensions.
Anyway, I'm terribly bad at geometry, does anyone know how I can get the angle of the intersection?