For fun I am writing a software rasterizer. I am projecting a point through the main camera matrices:
Matrix4x4 V = Camera.main.worldToCameraMatrix;
Matrix4x4 P = Camera.main.projectionMatrix;
and then MVP.MultiplyPoint
I can normalize the screen positions just fine, but I have some problems getting the z value right.
Straight from the MultiplyPoint method the values range from: +1.0f when the camera is about FarClippingDistance away and exactly -1.0f when NearClipping away. Which is what it should I guess.
Now my question, how can I normalize this value to get exactly the same number as in a shaders COMPUTE_EYEDEPTH? Or am I confusing some terms here?
Edit: just looked into the UnityCG
#define COMPUTE_EYEDEPTH(o) o = -UnityObjectToViewPos( v.vertex ).z
This doesn’t take into consideration the projection matrix right? That’s why it’s calculating a “different depth” than my software rasterizer?
Edit: I just can’t get this to work, here is my code:
Vector4 projectedPoint = MVP.MultiplyPoint(coord);
projectedPoint = new Vector3(projectedPoint.x + 1f, projectedPoint.y + 1f, projectedPoint.z + 1f) / 2f;
float depth = projectedPoint.z; // this works perfectly
Then in the shader:
v2f vert(appdata_base v) {
v2f o;
float4 position = UnityObjectToClipPos(v.vertex);
o.pos = position;
float depth = (1+position.z)/2;
o.color = depth;
return o;
}
When login the values and comparing the pixel color value, these are completely off.
My question boils down to:
What is the z value range of UnityObjectToClipPos and what does it represnt? Because it sure doesn’t represent the same matrix-based value as in software. It kinda works when i multiply it by 10, but what gives?