tinyrenderer
tinyrenderer copied to clipboard
Linear sampling and texture wrapping
Here is some code that adds linear sampling and texture wrapping:
TGAColor TGAImage::sample(const float x, const float y) const {
float u = fmodf(x,1.0f);
float v = 1.0f- fmodf(y,1.0f);
int x0 = floor(u * float(width));
int x1 = ceil(u * float(width));
int y0 = floor(v * float(height));
int y1 = ceil(v * float(height));
TGAColor sample00 = get(x0, y0);
TGAColor sample01 = get(x0, y1);
TGAColor sample11 = get(x1, y1);
TGAColor sample10 = get(x1, y0);
float mx = u * float(width) - float(x0);
float my = v * float(height) - float(y0);
float sample0[4], sample1[4];
TGAColor color;
for (int n = 0; n < bytespp; ++n)
{
sample0[n] = float(sample10[n]) * mx + float(sample00[n]) * (1.0f - mx);
sample1[n] = float(sample11[n]) * mx + float(sample01[n]) * (1.0f - mx);
color[n] = sample1[n] * my + sample0[n] * (1.0f - my);
}
return color;
}
TGAColor TGAImage::get(const int x, const int y) const {
//if (!data.size() || x < 0 || y < 0 || x >= width || y >= height)
// return {};
return TGAColor(data.data() + ((x % width) + (y % height) * width) * bytespp, bytespp);
}
This kind of sampling is usually called bilinear texture mapping, right?