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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#pragma once
#ifndef TEXTURE_H #define TEXTURE_H
#include "Global.h"
class Texture {
public: int width; int height; int channels; unsigned char* data;
Texture() : width(-1), height(-1), channels(-1), data(nullptr) {} Texture(const std::string& Path) { LoadTexture(Path); }
virtual ~Texture() { if (data) free(data); }
Texture(const Texture& t) { width = t.width; height = t.height; channels = t.channels; if (t.data) { data = (unsigned char*)malloc(width * height * channels); memcpy(data, t.data, width * height * channels); } }
Texture& operator=(const Texture& t) { width = t.width; height = t.height; channels = t.channels; if (t.data) { data = (unsigned char*)malloc(width * height * channels); memcpy(data, t.data, width * height * channels); } return *this; }
virtual void LoadTexture(const std::string& Path) { stbi_set_flip_vertically_on_load(false); if (data) free(data); data = stbi_load(Path.c_str(), &width, &height, &channels, 0); }
virtual glm::vec4 Sample2D(const glm::vec2& texcoord) { float x = texcoord.x - (float)floor(texcoord.x); float y = texcoord.y - (float)floor(texcoord.y); x = x < 0 ? -x : x; y = y < 0 ? -y : y; return GetColor(x * (width - 1), y * (height - 1)) / 255.0f; }
glm::vec4 GetColor(int x, int y) { if (x < 0 || x >= width || y < 0 || y >= height) return glm::vec4(0, 0, 0, 255); switch (channels) { case 1: return GetColor1(x, y); break; case 2: return GetColor2(x, y); break; case 3: return GetColor3(x, y); break; case 4: return GetColor4(x, y); break; default: return glm::vec4(0, 0, 0, 255); } } glm::vec4 GetColor1(int x, int y) { int xy = y * width + x; return glm::vec4(*(data + xy), 0, 0, 255); } glm::vec4 GetColor2(int x, int y) { int xy = 2 * (y * width + x); return glm::vec4(*(data + xy), *(data + xy + 1), 0, 255); } glm::vec4 GetColor3(int x, int y) { int xy = 3 * (y * width + x); return glm::vec4(*(data + xy), *(data + xy + 1), *(data + xy + 2), 255); } glm::vec4 GetColor4(int x, int y) { int xy = 4 * (y * width + x); return glm::vec4(*(data + xy), *(data + xy + 1), *(data + xy + 2), *(data + xy + 3)); } };
#endif
|