Files
VoxelEngine/Rendering/Frustum.cs

62 lines
2.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using OpenTK.Mathematics;
namespace VoxelEngine.Rendering;
// View-frustum for culling chunk AABBs. Built from a world→clip matrix in this
// engine's row-vector convention (clip = worldPos * view * projection, matching
// the chunk vertex shader). Planes point inward; a point is inside when it is on
// the positive side of all six.
public readonly struct Frustum
{
// Each Vector4 is (a, b, c, d) for plane a*x + b*y + c*z + d = 0, normalized.
private readonly Vector4 _left, _right, _bottom, _top, _near, _far;
private Frustum(Vector4 l, Vector4 r, Vector4 b, Vector4 t, Vector4 n, Vector4 f)
{
this._left = l; this._right = r; this._bottom = b;
this._top = t; this._near = n; this._far = f;
}
// `vp` maps a world-space row vector p to clip space via p * vp. In that
// convention clip.x = p · column0, clip.w = p · column3, etc., so each plane
// is a combination of vp's columns (Gribb–Hartmann, row-vector form).
public static Frustum FromViewProjection(Matrix4 vp)
{
Vector4 c0 = vp.Column0, c1 = vp.Column1, c2 = vp.Column2, c3 = vp.Column3;
return new Frustum(
Normalize(c3 + c0), // left: clip.w + clip.x >= 0
Normalize(c3 - c0), // right: clip.w - clip.x >= 0
Normalize(c3 + c1), // bottom: clip.w + clip.y >= 0
Normalize(c3 - c1), // top: clip.w - clip.y >= 0
Normalize(c3 + c2), // near: clip.w + clip.z >= 0 (GL NDC z in [-1,1])
Normalize(c3 - c2)); // far: clip.w - clip.z >= 0
}
// True if the axis-aligned box [min,max] is at least partially inside.
public bool Intersects(Vector3 min, Vector3 max)
{
return InsideOrCrossing(this._left, min, max)
&& InsideOrCrossing(this._right, min, max)
&& InsideOrCrossing(this._bottom, min, max)
&& InsideOrCrossing(this._top, min, max)
&& InsideOrCrossing(this._near, min, max)
&& InsideOrCrossing(this._far, min, max);
}
// The box is fully outside a plane only if its most-positive vertex (the
// corner farthest along the plane normal) is still behind the plane.
private static bool InsideOrCrossing(Vector4 plane, Vector3 min, Vector3 max)
{
float px = plane.X >= 0 ? max.X : min.X;
float py = plane.Y >= 0 ? max.Y : min.Y;
float pz = plane.Z >= 0 ? max.Z : min.Z;
return plane.X * px + plane.Y * py + plane.Z * pz + plane.W >= 0f;
}
private static Vector4 Normalize(Vector4 p)
{
float len = new Vector3(p.X, p.Y, p.Z).Length;
return len > 0f ? p / len : p;
}
}