This is part of the Rendering Tutorial

Mapping 3D to 2D

In this section, I'll explain how the data of the house is projected on a 2D viewport.

All faces of the house can be kept in data structures, and they're mainly containers of 3D coordinates. I won't go into explaining how I did it, or how you could keep these 3 dimensional objects in a data structure in your rendering engine. The main goal of a renderer is to tranform and project the 3D coordinates of the objects to the 2D screen. Connecting the dots, and displaying faces and such, is up to you. I'll explain what can go wrong and what you should look after when displaying faces later. It's not as easy as simply connecting the dots, but we will assume everything will go right for now.

So the main thing we want to do is to transform the 3 dimensional coordinates to coordinates in a 2 dimensional plane. And oh boy, this is easy. At least, this is true if we make a very important assumption, an assumption I'll keep during this introduction in rendering. We'll keep the camera at a fixed position. the camera always looks up the Z direction, and always looks perpendicular to the XY plane. The camera is placed in such a position that it sees the axes on the XY plane similar to the X and Y axes on a computer screen. Namely, the X direction on a computer screen goes from left to right, where the Y direction goes from the top of your screen to the bottom of your screen. This latter is different from Y directions you've met in math classes, as those Y axes always point upwards. The camera thus perceives the XY plane similarly as we're looking at a computer screen. That makes things easy.

Now think along with me for a minute. As we're looking along the Z axis, all objects that should be rendered on our screen appear smaller as their coordinates have bigger Z values. Similarly, objects appear bigger as their Z values are smaller, since their coordinates are closer to the camera. In order to transform 3D coordinates to 2D coordinates, we can thus simply divide the X and Y values in the coordinates by the Z value in order to display them as X and Y coordinates in a 2 dimensional view.

In code, this becomes something like

x2d = x3d / z3d;
y2d = y3d / z3d;

Told you this was easy.

But there are some snappy details you should take care off, or your projection of the 3D data will look pretty skewed.

Putting it all together, your resulting code for projecting a 3D coordinate to a 2D coordinate using a camera following our assumption will look like the following:

x2d = xOffset + scale * x3d / ( z3d + distance );
y2d = yOffset + scale * y3d / ( z3d + distance );

Next

Rotating objects to acquire a better viewing angle


comments powered by Disqus