Texture.cpp
author František Kučera <franta-hg@frantovo.cz>
Wed, 27 Dec 2023 23:25:06 +0100
branchv_0
changeset 33 4620bba4fa40
parent 31 ed3caeea978a
permissions -rw-r--r--
import functions from the private prototype: goPage(), goHome(), goEnd(), goPageMouse()

/**
 * OHP3D
 * Copyright © 2023 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program 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, version 3 of the License.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <string>
#include <stdexcept>

#include "opengl.h"
#include "Texture.h"

class Texture::Impl {
public:
	GLuint id;
	std::string fileName;
	int width;
	int height;
	GLfloat scale = 1.;
};

Texture::Texture(
		int width,
		int height,
		const Buffer& img,
		const std::string& fileName) : impl(new Impl()) {
	impl->fileName = fileName;
	glGenTextures(1, &impl->id);
	update(width, height, img);
}

Texture::~Texture() {
	glDeleteTextures(1, &impl->id);
	delete impl;
}

GLuint Texture::getId() const {
	return impl->id;
}

const std::string Texture::getFileName() const {
	return impl->fileName;
}

int Texture::getWidth() const {
	return impl->width;
}

int Texture::getHeight() const {
	return impl->height;
}

GLfloat Texture::getRatio() const {
	return (GLfloat) impl->width / (GLfloat) impl->height;
}

GLfloat Texture::getScale() const {
	return impl->scale;
}

void Texture::setScale(GLfloat scale) {
	impl->scale = scale;
}

void Texture::update(int width, int height, const Buffer& img) {
	impl->width = width;
	impl->height = height;

	if (img.getSize() != impl->width * impl->height * 3)
		throw std::invalid_argument("invalid image size");

	glBindTexture(GL_TEXTURE_2D, impl->id);
	auto GLT2D = GL_TEXTURE_2D;
	glTexImage2D(GLT2D, 0, GL_RGB,
			impl->width, impl->height,
			0, GL_RGB, GL_UNSIGNED_BYTE,
			img.getData());
	glTexParameteri(GLT2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GLT2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GLT2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // blurry upscale
	// glTexParameteri(GLT2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); sharp upscale
	glTexParameteri(GLT2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glGenerateMipmap(GLT2D);
	checkError(&std::cerr);
}

void Texture::bind() {
	glBindTexture(GL_TEXTURE_2D, impl->id);
}