c0op
c0op

Reputation: 15

Compute z-Value (Distance to Camera) of Vertex with given Projection Matrix

I've created a 3D-Scene with Blender and computed the Projection Matrix P (Also have information about the Translation T- and Rotation-Matrix R). Like I mentioned in the title I try to calculate the z-Value or depth to an Vertex (x,y,z) from my given camera C with these Matrices.

Example: Vertex v = [1.4,1,2.3] and position of camera c = [0,-0.7,10]. The Result should be anything around 10-2.3 = 7.7. Thank you for your help!

Upvotes: 0

Views: 1769

Answers (2)

c0op
c0op

Reputation: 15

Thanks for your help, here is what I was looking for:

Data setup

  • R rotation matrix 4x4
  • T translation matrix 4x4
  • v any vertex in with [x,y,z,1] 4x1

Result

  • vec4 vector 4x1 (x,y,z,w)

vec4 = R * T * v

The vec4.z value is the result I was looking for. Thanks!

Upvotes: 1

CoffeDeveloper
CoffeDeveloper

Reputation: 8325

Usually rotation matrix is applied before translation. So

transform = R * T 
  • R is the rotation matrix (usually 4 rows and 4 columns)
  • T is the translation matrix (4 rows and 4 columns)
  • * is the matrix multiplication wich apply first T and then R

of course I'm assuming you already know how to perform matrix multiplication, I'm not providing anycode because it is not clear if you need python snippet or you are using the exported model somehwere else.

After that you apply the final projection matrix (I'm assuming your projection matrix is already multiplied by view matrix)

final = P * transform
  • P is the projection matrix ( 4 rows and 4 columns)
  • transform is your previously obtained (4 rows and 4 columns) matrix

the final matrix is the one that will transform every vector of your 3D model, again here you do a matrix multiplication (but in this case the second operand is a colum vector wich 4th element is 1)

transformedVertex = final * Vec4(originalVertex,1)
  • transformedVertex is a column vector ( 4x1 matrix)
  • final is the final matrix (4x4)
  • a vertex is onl 3 coordinates, so we add 1 to make it (4x1)
  • * is still matrix multiplication

once transformed the vertex Z value is the one that gets directly mapped into Z buffer and ence into a Depth value.

At this point there is one operation that is done "by convention" and is dividing Z by W to normalize it, then values outside range [0..1] are discarded (nearest than near clip plane or farest than far clip plane).

See also this question: Why do I divide Z by W?

EDIT:

I may have misinterpreted your question, if you need distance between camera and a point it is simply

function computeDistance( cam, pos)
    dx = cam.x-pos.x
    dy = cam.y-pos.y
    dz = cam.z-pos.z
    distance = sqrt( dx*dx + dy*dy + dz*dz)
end function

example

cameraposition = 10,0,0
vertexposition = 2,0,0

the above code

computeDistance ( cameraposition, vertexposition)

outputs

8

Upvotes: 1

Related Questions