Basic render 3D perspective projection onto 2D screen with camera (without opengl)

后端 未结 8 1024
南方客
南方客 2020-12-04 10:21

Let\'s say I have a data structure like the following:

Camera {
   double x, y, z

   /** ideally the camera angle is positioned to aim at the 0,0,0 point */         


        
8条回答
  •  青春惊慌失措
    2020-12-04 10:51

    @BerlinBrown just as a general comment, you ought not to store your camera rotation as X,Y,Z angles, as this can lead to an ambiguity.

    For instance, x=60degrees is the same as -300 degrees. When using x,y and z the number of ambiguous possibilities are very high.

    Instead, try using two points in 3D space, x1,y1,z1 for camera location and x2,y2,z2 for camera "target". The angles can be backward computed to/from the location/target but in my opinion this is not recommended. Using a camera location/target allows you to construct a "LookAt" vector which is a unit vector in the direction of the camera (v'). From this you can also construct a LookAt matrix which is a 4x4 matrix used to project objects in 3D space to pixels in 2D space.

    Please see this related question, where I discuss how to compute a vector R, which is in the plane orthogonal to the camera.

    Given a vector of your camera to target, v = xi, yj, zk
    Normalise the vector, v' = xi, yj, zk / sqrt(xi^2 + yj^2 + zk^2)
    Let U = global world up vector u = 0, 0, 1
    Then we can compute R = Horizontal Vector that is parallel to the camera's view direction R = v' ^ U,
    where ^ is the cross product, given by
    a ^ b = (a2b3 - a3b2)i + (a3b1 - a1b3)j + (a1b2 - a2b1)k

    This will give you a vector that looks like this.

    Computing a vector orthogonal to the camera

    This could be of use for your question, as once you have the LookAt Vector v', the orthogonal vector R you can start to project from the point in 3D space onto the camera's plane.

    Basically all these 3D manipulation problems boil down to transforming a point in world space to local space, where the local x,y,z axes are in orientation with the camera. Does that make sense? So if you have a point, Q=x,y,z and you know R and v' (camera axes) then you can project it to the "screen" using simple vector manipulations. The angles involved can be found out using the dot product operator on Vectors.

    Projecting Q onto the screen

提交回复
热议问题