- Home /
Question by
spraycanmansam · Aug 07, 2013 at 05:42 AM ·
cameraclippingfrustum
Oblique Frustum Clipping
Hi there,
I've been implementing oblique frustum clipping for our water to clip everything above water level. It works great :) For some reason, I can't for the life of me get it to work the other way around, ie: clip everything below water level. I can get it to work with the main camera at 0, but as soon as I try and incorporate the camera's position in any way, it screws up. The draw order reverses and it's almost like the frustum stays at 0 while the camera's moving.
Here's an example of the code I'm using for below, which works fine with clipping everything below the plane.
public class Clipper : MonoBehaviour
{
Matrix4x4 projection;
Camera offscreenCam;
void Start ()
{
projection = camera.projectionMatrix;
}
void OnPreRender()
{
camera.projectionMatrix = projection;
Matrix4x4 obliqueProjection = projection;
Vector4 cameraSpaceClipPlane = CameraSpacePlane(camera, new Vector3(0.0f, 0.0f, 0.0f), Vector3.up, 1.0f);
CalculateObliqueMatrix(ref obliqueProjection, cameraSpaceClipPlane);
camera.projectionMatrix = obliqueProjection;
}
static Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * 0.07f;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint(offsetPos);
Vector3 point = m.inverse.MultiplyPoint(new Vector3(0.0f, 0.0f, 0.0f));
cpos -= new Vector3(0.0f, point.y, 0.0f);
Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal));
}
static void CalculateObliqueMatrix(ref Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
sgn(clipPlane.x),
sgn(clipPlane.y),
1.0f,
1.0f
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
}
}
Any help would be much appreciated!
Thanks! Sam
Comment