Learning C, Day 16 (Texture Mapping 2)

Barycentric coordinates: they’re great for squishing squares into triangles. Here’s a wobbly textured cube:

Amazingly, this only took about an hour. (Texture from tutorialsforblender3d.com)

An overview of how it works

The goal is to draw a triangle on the screen with pixels from a texture. I have three vertices and a texture in memory. The vertices describe two triangles: a triangle in the screen with X and Y, and a triangle in the texture, with U and V. The X and Y values can be anywhere in the screen, like (100, 200). The U and V values are in the range of 0 to 1. What I’m trying to do is, for each X and Y point in the triangle, find the point’s U and V. To find them, I interpolate the UV coordinates of the three vertices using barycentric coordinates. Barycentric coordinates are kind of like a percentage of how close the point is to each of the vertices. Finding the percentages is beyond the scope of this overview, so I’ll skip it. Then for each vertex, I have a percentage of how close the point is to it. The percentage determines how much of that vertex’s UV coordinates I use. I think of it as taking a sum of each vertices’ UV coordinates and adding them together to get the point’s UV coordinates. Then all I have to do is convert the UV coordinates to texture X and Y, which is easy: U and V are percentages of the texture width and height. So I just multiply U times the texture width and V times the texture height, and I’m done! I can draw the pixel on the screen with the color from texture[X][Y] and repeat the process for the other pixels in the triangle.

Conclusion

I’ll be back tomorrow with perspective correct interpolation and a less wobbly cube!

Edit 7/27/2022 (1 year, 3 months later): Spelling. Some and sum do sound similar.

Leave a comment

Your email address will not be published. Required fields are marked *

Your data is processed in accordance with my privacy policy. Comments are manually approved and may take a while to appear.