-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtexture2d.cpp
86 lines (65 loc) · 2.08 KB
/
texture2d.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "texture2d.h"
#include "drawcontext.h"
#include "shader.h"
#include <QImage>
#include <QFile>
#include <QGLWidget>
Texture2D::Texture2D()
{
}
Texture2D::~Texture2D()
{
delete image_;
}
void Texture2D::load(string filename)
{
string path = filename + ".png";
QFile file(path.c_str());
if(!file.exists()) {
path = filename + ".jpg";
file.setFileName(path.c_str());
if (!file.exists()) {
assert(false);
return;
}
}
delete image_;
image_ = new QImage();
image_->load(path.c_str());
*image_ = QGLWidget::convertToGLFormat(*image_);
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &textureID_);
glBindTexture(GL_TEXTURE_2D, textureID_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_->width(), image_->height(),
0, GL_RGBA, GL_UNSIGNED_BYTE, image_->bits());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindTexture(GL_TEXTURE_2D, 0);
}
vec4 Texture2D::sample(const vec3 &uvw)
{
struct Color32 {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
float u = uvw.x();
float v = uvw.y();
int x = (int)(u * image_->width()) % image_->width();
int y = image_->height() - (int)(v * image_->height()) % image_->height() - 1;
Color32 *data = (Color32 *)image_->bits();
assert(x < image_->width() && x >= 0);
assert(y < image_->height() && y >= 0);
Color32 color = data[y * image_->width() + x];
return vec4(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
}
void Texture2D::apply(DrawContext &context, string name, int binding) const
{
assert(textureID_);
glActiveTexture(GL_TEXTURE0 + binding);
glBindTexture(GL_TEXTURE_2D, textureID_);
context.shader->setUniformValue(name.c_str(), binding);
}