Reputation: 587
I'm trying to calculate lighting in a fragment shader, and I've defined my light sources as axis-aligned bounding boxes (AABB) in order to simulate "area lights" -- light-emitting volumes, rather than simple point lights.
I found and adapted this code on StackOverflow which correctly calculates the distance from the point to the bounds. But I was wondering if there's a clever way to extract the directional vector from this calculation as well?
/**
* @return The distance from `p` to the bounding box.
* @see https://stackoverflow.com/a/18157551/1982239
*/
float distance_to_bounds(in vec3 mins, in vec3 maxs, in vec3 p) {
float dx = max(max(mins.x - p.x, 0.0), p.x - maxs.x);
float dy = max(max(mins.y - p.y, 0.0), p.y - maxs.y);
float dz = max(max(mins.z - p.z, 0.0), p.z - maxs.z);
return sqrt(dx * dx + dy * dy + dz * dz);
}
I tried refactoring this as:
/**
* @return The directional vector from `p` to the bounding box.
* @see https://stackoverflow.com/a/18157551/1982239
*/
vec3 direction_to_bounds(in vec3 mins, in vec3 maxs, in vec3 p) {
float dx = max(max(mins.x - p.x, 0.0), p.x - maxs.x);
float dy = max(max(mins.y - p.y, 0.0), p.y - maxs.y);
float dz = max(max(mins.z - p.z, 0.0), p.z - maxs.z);
return vec3(dx, dy, dz);
}
Thinking that the length of the vector would be distance, but this produces incorrect looking results for both distance and direction. I tried negating the vector as well.
Upvotes: -1
Views: 27