TomTom
TomTom

Reputation: 321

How to correct for perspective when plotting a 3D triangle with texture?

I have been working on a 3D rendering project as a technical excersise to see if I can replicate what a lot of the 3D frameworks do already: all the way from loading the model to plotting the triangles to a buffer ready to be drawn.

Here is a sample of what I have managed to produce Render of program output

As you can see from the screenshot I have hit a snag plotting the textures on the surface. This Wikipedia link I have found explains about affine vs non-affine. Some other links similar to this one about perspective correct texture mapping go into it in more detail.

I still do not understand how I can correct my UV coordinates when plotting a pixel.

How my engine currently works with a triangle: Convert 3D vertex data into 2D screen data call draw triangle passing depth between 0 & 1 and texture details within draw triangle each vertical line is draw by interpolating along the 3 edges of the triangle

I have made the changes in the links but I get divide by zero errors. If I ignore them nothing is drawn.

The question

How can I correct the UV co-ordinate selected at each pixel. Currently at each pixel I know the depth between 0.0 and 1.0, the apparent UV.

Any help would be much appreciated. Thank you in advance.

Tom :)

UPDATE:

Solution, use Andreas Brinck's answer. It works fine. Below is a screenshot of it now working.

working correct perspective texture mapping

Upvotes: 5

Views: 1426

Answers (1)

Andreas Brinck
Andreas Brinck

Reputation: 52519

Instead of interpolating u and v over the triangle, interpolate u/z, v/z and 1/z (calculated at the vertices) and retrieve the perspective correct coordinates as (u/z) / (1/z) and (v/z) / (1/z).

Upvotes: 3

Related Questions