public class Frustum {
// View frustum planes
private Plane[] _frustumPlanes;
public Frustum(Matrix4x4 viewProjectionMatrix) {
_frustumPlanes = ExtractPlanes(viewProjectionMatrix);
}
public bool IsSphereInFrustum(Vector3 center, float radius) {
foreach (var plane in _frustumPlanes) {
float distance = Vector3.Dot(plane.Normal, center) + plane.D;
if (distance < -radius) {
// The sphere is entirely behind this plane, it is outside the frustum
return false;
}
}
// The sphere is not entirely behind any plane, it is partially or fully inside the frustum
return true;
}
private Plane[] ExtractPlanes(Matrix4x4 viewProjectionMatrix) {
// Extract view frustum planes from the view-projection matrix
Plane[] planes = new Plane[6];
// Left plane
planes[0] = new Plane(
viewProjectionMatrix.M14 + viewProjectionMatrix.M11,
viewProjectionMatrix.M24 + viewProjectionMatrix.M21,
viewProjectionMatrix.M34 + viewProjectionMatrix.M31,
viewProjectionMatrix.M44 + viewProjectionMatrix.M41
);
// Right plane
planes[1] = new Plane(
viewProjectionMatrix.M14 - viewProjectionMatrix.M11,
viewProjectionMatrix.M24 - viewProjectionMatrix.M21,
viewProjectionMatrix.M34 - viewProjectionMatrix.M31,
viewProjectionMatrix.M44 - viewProjectionMatrix.M41
);
// Bottom plane
planes[2] = new Plane(
viewProjectionMatrix.M14 + viewProjectionMatrix.M12,
viewProjectionMatrix.M24 + viewProjectionMatrix.M22,
viewProjectionMatrix.M34 + viewProjectionMatrix.M32,
viewProjectionMatrix.M44 + viewProjectionMatrix.M42
);
// Top plane
planes[3] = new Plane(
viewProjectionMatrix.M14 - viewProjectionMatrix.M12,
viewProjectionMatrix.M24 - viewProjectionMatrix.M22,
viewProjectionMatrix.M34 - viewProjectionMatrix.M32,
viewProjectionMatrix.M44 - viewProjectionMatrix.M42
);
// Near plane
planes[4] = new Plane(
viewProjectionMatrix.M13,
viewProjectionMatrix.M23,
viewProjectionMatrix.M33,
viewProjectionMatrix.M43
);
// Far plane
planes[5] = new Plane(
viewProjectionMatrix.M14 - viewProjectionMatrix.M13,
viewProjectionMatrix.M24 - viewProjectionMatrix.M23,
viewProjectionMatrix.M34 - viewProjectionMatrix.M33,
viewProjectionMatrix.M44 - viewProjectionMatrix.M43
);
// Normalize the planes
for (int i = 0; i < 6; i++) {
planes[i] = Plane.Normalize(planes[i]);
}
return planes;
}
}