-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTexture.cpp
40 lines (29 loc) · 1.24 KB
/
Texture.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "Texture.hpp"
#include "stb_image/stb_image_include.h"
ImageTexture::ImageTexture(const char * filename)
{
auto components_per_pixel = bytes_per_pixel;
data_ = stbi_load(filename, &width_, &height_, &components_per_pixel, components_per_pixel);
if (!data_) {
std::cerr << "ERROR: Could not load texture image file '" << filename << "'.\n";
width_ = height_ = 0;
}
bytes_per_scanline_ = bytes_per_pixel * width_;
}
Color ImageTexture::value(Real u, Real v, const Vector3 & p) const
{
// If we have no texture data, then return solid cyan as a debugging aid.
if (data_ == nullptr)
return Color(0, 1, 1);
// Clamp input texture coordinates to [0,1] x [1,0]
u = clamp(u, 0.0, 1.0);
v = 1.0 - clamp(v, 0.0, 1.0); // Flip V to image coordinates
auto i = static_cast<int>(u * width_);
auto j = static_cast<int>(v * height_);
// Clamp integer mapping, since actual coordinates should be less than 1.0
if (i >= width_) i = width_ - 1;
if (j >= height_) j = height_ - 1;
const auto color_scale = 1.0 / 255.0;
auto pixel = data_ + j * bytes_per_scanline_ + i * bytes_per_pixel;
return Color(color_scale*pixel[0], color_scale*pixel[1], color_scale*pixel[2]);
}