Hey, I had already implemented AABB raypicking using slab intersection, but I couldn't get it working with rotation to create OBB raypicking.
bool TestAABBIntersection(XMFLOAT3 lb, XMFLOAT3 rt, XMFLOAT3 origin, XMFLOAT3 dirfrac, float& distance)
{
assert(lb.x <= rt.x);
assert(lb.y <= rt.y);
assert(lb.z <= rt.z);
const float t1 = (lb.x - origin.x)*dirfrac.x;
const float t2 = (rt.x - origin.x)*dirfrac.x;
const float t3 = (lb.y - origin.y)*dirfrac.y;
const float t4 = (rt.y - origin.y)*dirfrac.y;
const float t5 = (lb.z - origin.z)*dirfrac.z;
const float t6 = (rt.z - origin.z)*dirfrac.z;
const float tmin = max(max(min(t1, t2), min(t3, t4)), min(t5, t6));
const float tmax = min(min(max(t1, t2), max(t3, t4)), max(t5, t6));
// if tmax < 0, ray (line) is intersecting AABB, but the whole AABB is behind us
if (tmax < 0)
{
return false;
}
// if tmin > tmax, ray doesn't intersect AABB
if (tmin > tmax)
{
return false;
}
distance = tmin;
return true;
}
bool TestOBBIntersection(ModelClass* model, XMFLOAT3 origin, XMFLOAT3 dir, XMFLOAT3 lb, XMFLOAT3 rt, float & dist)
{
XMMATRIX worldMatrix = XMMatrixIdentity();
worldMatrix = DirectX::XMMatrixMultiply(worldMatrix, DirectX::XMMatrixRotationX(model->GetRotation().x * 0.0174532925f));
worldMatrix = DirectX::XMMatrixMultiply(worldMatrix, DirectX::XMMatrixRotationY(model->GetRotation().y * 0.0174532925f));
worldMatrix = DirectX::XMMatrixMultiply(worldMatrix, DirectX::XMMatrixRotationZ(model->GetRotation().z * 0.0174532925f));
worldMatrix = XMMatrixInverse(NULL, worldMatrix);
const XMVECTOR originTransformed = XMVector3Transform({ origin.x, origin.y, origin.z }, worldMatrix);
const XMVECTOR dirTransformed = XMVector3Transform({ dir.x, dir.y, dir.z }, worldMatrix);
origin = { originTransformed.m128_f32[0],originTransformed.m128_f32[1],originTransformed.m128_f32[2] };
dir = { dirTransformed.m128_f32[0], dirTransformed.m128_f32[1], dirTransformed.m128_f32[2] };
return TestAABBIntersection(lb, rt, origin, dir, dist);
}
What I am doing is multiplying ray origin and ray direction by inverse rotation matrix and then perform Ray-AABB test in OBB-space. It works only for 0, 90 and 180 degrees rotation. Where might be a problem?