// Texture loader implementation
// Copyright (C) 2021 Nguyễn Gia Phong
//
// This file is part of Black Shades.
//
// Black Shades is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Black Shades is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Black Shades. If not, see .
#include
#define STB_IMAGE_IMPLEMENTATION
#include
#include
#include "Textures.h"
GLuint loadTexture(const char* filename_, GLenum minFilter,
GLenum magFilter, bool mipmaps)
{
// TODO: get rid of the :Data: thing
char filename[1024];
strcpy(filename, filename_+1);
while (true) {
char *c = strchr(filename, ':');
if (!c) break;
*c = '/';
}
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
unsigned char* data = stbi_load(filename, &width, &height,
&orig_format, req_format);
if (data == nullptr) {
fprintf(stderr, "Loading image failed: %s\n",
stbi_failure_reason());
return 0;
}
GLuint tex = 0;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
GLint internal_format;
GLenum pixel_format;
if (req_format == STBI_rgb) {
internal_format = 3;
pixel_format = GL_RGB;
} else { // STBI_rgb_alpha (RGBA)
internal_format = 4;
pixel_format = GL_RGBA;
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0,
pixel_format, GL_UNSIGNED_BYTE, data);
if (mipmaps)
gluBuild2DMipmaps(GL_TEXTURE_2D, internal_format, width, height,
pixel_format, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
return tex;
}