8f450ad7331e6e2669fd65fdb68234aac1fa9381
[tar-legacy.git] / MCDV / Texture.hpp
1 #pragma once
2 #include <string>
3 #include <iostream>
4 #include <string>
5
6 #include <glad\glad.h>
7 #include <GLFW\glfw3.h>
8
9 #define STB_IMAGE_IMPLEMENTATION
10 #include "stb_image.h"
11
12
13 class Texture
14 {
15 public:
16 unsigned int texture_id;
17 Texture(std::string filepath, bool clamp = false);
18
19 void bind();
20 void bindOnSlot(int slot);
21
22 ~Texture();
23 };
24
25
26
27 bool USE_DEBUG2 = false;
28
29
30 Texture::Texture(std::string filepath, bool clamp)
31 {
32 stbi_set_flip_vertically_on_load(true);
33
34 glGenTextures(1, &this->texture_id);
35
36 //Load texture using stb_image
37 int width, height, nrChannels;
38 unsigned char* data = stbi_load(filepath.c_str(), &width, &height, &nrChannels, 0);
39 if (data)
40 {
41 GLenum format;
42 if (nrChannels == 1)
43 format = GL_RED;
44 else if (nrChannels == 3)
45 format = GL_RGB;
46 else if (nrChannels == 4)
47 format = GL_RGBA;
48
49 glBindTexture(GL_TEXTURE_2D, this->texture_id);
50 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, format, GL_UNSIGNED_BYTE, data);
51 glGenerateMipmap(GL_TEXTURE_2D);
52
53 if (!clamp) {
54 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
55 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
56 }
57 else {
58 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
59 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
60 }
61 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
62 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
63
64 //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
65 //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
66
67 stbi_image_free(data);
68
69 if (USE_DEBUG2)
70 {
71 std::cout << "Texture loaded, info:" << std::endl;
72 std::cout << filepath << std::endl;
73 std::cout << "width: " << width << std::endl;
74 std::cout << "height: " << height << std::endl;
75 }
76 else
77 {
78 std::cout << "Loading texture: " << filepath << std::endl;
79 }
80 }
81 else
82 {
83 std::cout << "ERROR::IMAGE::LOAD_FAILED" << std::endl;
84 }
85 }
86
87 Texture::~Texture()
88 {
89 }
90
91 void Texture::bind()
92 {
93 glBindTexture(GL_TEXTURE_2D, this->texture_id);
94 }
95
96 void Texture::bindOnSlot(int slot = 0) {
97 glActiveTexture(GL_TEXTURE0 + slot);
98 glBindTexture(GL_TEXTURE_2D, this->texture_id);
99 }