# How to transform world space vertex to camera space position in Cycles OSL

I used blender as CG generation tool for Computer Vision research. I tried to render depth (z) value of each surface instead of its color. So I make simple shader, like this

shader depth_shader(
vector Position = vector(1,0,0),
output closure color Color = emission())
{
vector lp = transform("world","camera",Position);
Color= color(lp, lp, lp) * emission();
}


"Position" is input from Geometry node. But when I tried this, It returns odd results, and some pixel has negative value. How to get camera space position, which only applied by rotation, scale and translation? (Before projection matrix multiplication)

• you can use P which is already defined and it is the position in world coordinates, i think that Z has to be negative if you look at the local axis of the camera in the 3D view – Chebhou Feb 16 '15 at 10:23

for transforming the position you should use point type because according to the OSL Language Specs :

Depending on the type of the passed point p, different transformation semantics will be used. A point will transform as a position, a vector as a direction without regard to positioning

just change the type of the Position variable to point or use the P variable that holds the current position then use the transform function as you did ; even after that the whole objects will be bright white, so i have tried to normalize the Z coordinate using two variables which act as near and far planes that limits the depth range :

shader depth_shader(
float minZ = 0,
float maxZ = 1,
output closure color Color = emission())
{
point lP = transform("camera", P);
float Z = lP;
if( (Z>minZ) && (Z<maxZ))
Z = (Z-minZ)/(maxZ-minZ);
else
Z = 0;
Color= color(Z, Z, Z) * emission();
}

• Oh, point! Thanks for reply. After changing vector to point, my shader works well! – Kichang Kim Feb 19 '15 at 10:31
• oops, when I set camera position to (0,0,2) and make plane to (0,0,0) which facing camera, depths is not 2.(I removed normalization term of your code, directly set lP to output). It seems be not pure depth from camera. Is blender camera space that someting normalized space like view frustrum? – Kichang Kim Feb 21 '15 at 2:32
• @KichangKim i think it should be 2, here is how to test it connect the z depth to "greater than" math node then to emission node and change the value "in math node" to see the clipping, AFAIK camera space is is just a rotated & translated version of world space in which the camera is the origin – Chebhou Feb 21 '15 at 10:18
• I recheck my code and scene, found small errors :( now, all of results are correct, very thanks! – Kichang Kim Feb 24 '15 at 6:36