Question

Although my current project is XNA, this question is about the basic mathematics of 3D to 2D mapping. In fact, and for the same reason, let's assume a WinForms graphics surface to draw on.

I have the following configuration:

  • Camera position of (x=0, y=0, z=0) and direction vector of (x=0, y=0, z=0).
  • A line segment in 3D with the following points: (10, 10, 10), (100, 100, 100).

I want to transform these coordinates and draw them on a 2D surface. So depending on the camera, the line segment should transform from (x1, y1, z1),(x2, y2, z2) to (x1, y1),(x2, y2).

Was it helpful?

Solution

I think you are looking for an orthogonal or perspective projection. There is a lot of information online if you search for it but here is the gist.

A camera looking at the origin, located a distance d along the z-axis will project a point at (x,y,z) onto a plane as:

// Orthogonal
planar_x = x
planar_y = y

// Perspective
planar_x = x*d/(d-z)
planar_y = y*d/(d-z)

Example

A point at (10,10,10) with the camera located a distance of 500 along the z axis will have planar coordinates (10*500/(500-10), 10*500/(500-10)) = (10.204, 10.204)

A point at (10,10,100) with the camera located a distance of 500 along the z axis will have planar coordinates (10*500/(500-100), 10*500/(500-100)) = (12.5, 12.5)

So the closer a shape is to the camera the larger it appears.

To transform the planar model coordinates to pixel coordinates I use the following scaling

scale = max_model_size/Math.Min(Height,Width);
pixel_x = Width/2 + x/scale;
pixel_y = Height/2- y/scale;

This is how I can use GDI to draw 3D shapes on a windows form.

Form

Of course if you want to use OpenGL then look here for a similar question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top