I recently made an application with C# and OpenGL using OpenTK. I've integrated a frustum culling system in order to improve performance, but for some reasons, objects aren't culled correctly. What I mean is that instead of showing all visibles objects nicely, it just cull random objects and when I rotate the camera, some objects appears and disappears. I know it's normal but not when I should see them. The actual frustum culling code is a C# port of my working C++/DirectXMath code used in something else.
Here's how I create the six frustum planes :
// Create a new view-projection matrices.
var vp = viewMatrix * projMatrix;
// Left plane.
frustumPlanes[0] = new Vector4
{
X = vp.M14 + vp.M11,
Y = vp.M24 + vp.M21,
Z = vp.M34 + vp.M31,
W = vp.M44 + vp.M41
};
// Right plane.
frustumPlanes[1] = new Vector4
{
X = vp.M14 - vp.M11,
Y = vp.M24 - vp.M21,
Z = vp.M34 - vp.M31,
W = vp.M44 - vp.M41
};
// Top plane.
frustumPlanes[2] = new Vector4
{
X = vp.M14 - vp.M12,
Y = vp.M24 - vp.M22,
Z = vp.M34 - vp.M32,
W = vp.M44 - vp.M42
};
// Bottom plane.
frustumPlanes[3] = new Vector4
{
X = vp.M14 + vp.M12,
Y = vp.M24 + vp.M22,
Z = vp.M34 + vp.M32,
W = vp.M44 + vp.M42
};
// Near plane.
frustumPlanes[4] = new Vector4
{
X = vp.M13,
Y = vp.M23,
Z = vp.M33,
W = vp.M43,
};
// Far plane.
frustumPlanes[5] = new Vector4
{
X = vp.M14 - vp.M13,
Y = vp.M24 - vp.M23,
Z = vp.M34 - vp.M33,
W = vp.M44 - vp.M43
};
// Normalize all the planes.
for (int i = 0; i < 6; i++)
frustumPlanes[i] = Vector4.Normalize(frustumPlanes[i]);
And I check if a sphere should be culled here :
public bool CullSphere(Vector3 position, float radius = 0.0f)
{
foreach (var plane in frustumPlanes)
{
// Verify if the point is behind the plane.
if (Vector3.Dot(plane.Xyz, position) + plane.W < -radius)
return true;
}
return false;
}
I saw on some other posts people multiplying the view and projection matrices manually, but I'm not sure that it's the cause of the problem. What I did wrong ? Thanks