7#include <smk/Texture.hpp>
11#include "StbImage.hpp"
14extern bool g_invalidate_textures;
16int next_power_of_2(
int v) {
36 FILE* file = fopen(filename.c_str(),
"rb");
38 std::cerr <<
"File " << filename <<
" not found" << std::endl;
44 unsigned char* data = stbi_load_from_file(file, &width_, &height_, &comp, 0);
48 int width_b = next_power_of_2(width_);
49 int height_b = next_power_of_2(height_);
50 std::vector<uint8_t> transformed(width_b * height_b * 4, 0);
51 for (
int y = 0; y < height_; ++y) {
52 for (
int x = 0; x < width_; ++x) {
53 for (
int c = 0; c < 4; ++c) {
55 transformed[c + 4 * (x + width_b * y)] =
57 (c == 3 && comp != 4) ? 255 : data[c + comp * (x + width_ * y)];
61 Load(transformed.data(), width_b, height_b, option);
62 stbi_image_free(data);
84 Load(data, width_, height_, option);
87void Texture::Load(
const uint8_t* data,
90 const Option& option) {
91 glGenTextures(1, &id_);
92 glBindTexture(GL_TEXTURE_2D, id_);
93 glTexImage2D(GL_TEXTURE_2D, 0, option.internal_format,
width,
height, 0,
94 option.format, option.type, data);
95 if (option.generate_mipmap) {
96 glGenerateMipmap(GL_TEXTURE_2D);
98 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, option.min_filter);
99 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, option.mag_filter);
100 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, option.wrap_s);
101 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, option.wrap_t);
102 glBindTexture(GL_TEXTURE_2D, GL_NONE);
103 g_invalidate_textures =
true;
111 : id_(id), width_(width), height_(height) {}
119void Texture::Release() {
120 int* ref_count = ref_count_;
138 glDeleteTextures(1, &id_);
142 operator=(std::move(other));
149Texture& Texture::operator=(Texture&& other)
noexcept {
151 std::swap(id_, other.id_);
152 std::swap(width_, other.width_);
153 std::swap(height_, other.height_);
154 std::swap(ref_count_, other.ref_count_);
158Texture& Texture::operator=(
const Texture& other) {
159 if (&other ==
this) {
164 width_ = other.width_;
165 height_ = other.height_;
171 if (!other.ref_count_) {
172 other.ref_count_ =
new int(1);
175 ref_count_ = other.ref_count_;
180void Texture::Bind(GLuint active_texture)
const {
181 glActiveTexture(active_texture);
182 glBindTexture(GL_TEXTURE_2D, id_);
185bool Texture::operator==(
const Texture& other)
const {
186 return id_ == other.id_;
189bool Texture::operator!=(
const Texture& other)
const {
190 return id_ != other.id_;
GLuint id() const
Access the ID of the texture.
int height() const
Access the height of the texture.
int width() const
Access the width of the texture.
Texture()
The null texture.