Reputation: 321
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
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.
Upvotes: 5
Views: 1426
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