Hi, could you please post the final working code? I have the very same problem and would appreciate it very much :)
Update: Using the posted code I did some tests. First, to make the code run/compile without errors I had to change it as follows:
d3d = SystemInfo.graphicsDeviceVersion.IndexOf("Direct3D") > -1;
M = transform.localToWorldMatrix;
V = camera.worldToCameraMatrix;
P = camera.projectionMatrix;
if (d3d) {
// Invert Y for rendering to a render texture
for ( i = 0; i < 4; i++) { P[1,i] = -P[1,i]; }
// Scale and bias from OpenGL -> D3D depth range
for ( i = 0; i < 4; i++) { P[2,i] = P[2,i]*0.5 + P[3,i]*0.5;}
}
MVP = P*V*M;
Just let me briefly explain what I am trying to do. In order to make a Cg shader work properly in Unity, I absolutely need the ModelViewProjection.Inverse matrix. It is not available in Unity (for compatibility reasons with D3D if I understand correctly). So what I am trying to do is to calculate this matrix in a script and then provide it to my shader. The shader has a simple cube as input mesh and ray-casts a sphere from this. So my precise question is, what has transform and camera to be in my case. I tried the following, but I do not get the expected result (eg the sphere, which works fine outside of unity using mvp.inverse):
function Update () {
d3d = SystemInfo.graphicsDeviceVersion.IndexOf("Direct3D") > -1;
M = GameObject.Find("Cube1").transform.localToWorldMatrix;
V = Camera.main.worldToCameraMatrix;
P = Camera.main.projectionMatrix;
if (d3d) {
// Invert Y for rendering to a render texture
for ( i = 0; i < 4; i++) { P[1,i] = -P[1,i]; }
// Scale and bias from OpenGL -> D3D depth range
for ( i = 0; i < 4; i++) { P[2,i] = P[2,i]*0.5 + P[3,i]*0.5;}
}
MVP = P*V*M;
Shader.SetGlobalMatrix("_matMVPI", MVP.inverse);
}
This code is run in a script attached to the main camera, but I guess it doesn't matter to what I attach the script. The Cg shader accesses _matMVPI in its vertex shader using
float4x4 ModelViewProjI = _matMVPI;
I wonder whether I use the right M, V and P matrices, eg M from the cube's transform and V, P from the main camera. Of course it's always difficult to debug what's going on inside the shader. I tried to multiply mvp and its (supposed) inverse, and change the color if eg the 1st matrix element is 1.0, but that doesn't work out (which is in agreement with the fact that the sphere doesn't render as it should).