Monad Engine da02fba2
> Undercity Codex_
Loading...
Searching...
No Matches
Texture.cpp
Go to the documentation of this file.
1#include "graphics/Texture.h"
2#include "Engine.h"
3
4#define STB_IMAGE_IMPLEMENTATION
5#include <stb_image.h>
6
7namespace eng
8{
9 Texture::Texture(int width, int height, int numChannels, unsigned char* data)
10 : m_width(width), m_height(height), m_numChannels(numChannels)
11 {
12 Init(width, height, numChannels, data);
13 }
14
16 {
17 if (m_textureID > 0)
18 {
19 glDeleteTextures(1, &m_textureID);
20 }
21 }
22
24 {
25 return m_textureID;
26 }
27
28 void Texture::Init(int width, int height, int numChannels, unsigned char* data)
29 {
30 glGenTextures(1, &m_textureID);
31 glBindTexture(GL_TEXTURE_2D, m_textureID);
32
33 GLint internalFormat = GL_RGB;
34 GLenum format = GL_RGB;
35
36 if (numChannels == 4)
37 {
38 internalFormat = GL_RGBA;
39 format = GL_RGBA;
40 }
41
42 glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, data);
43
44 glGenerateMipmap(GL_TEXTURE_2D);
45
46 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
47 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
48
49 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
50 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
51 }
52
53 std::shared_ptr<Texture> Texture::Load(const std::string& path)
54 {
55 int width, height, numChannels;
56
58 auto fullPath = fs.GetAssetsFolder() / path;
59
60 if (!std::filesystem::exists(fullPath))
61 {
62 return nullptr;
63 }
64
65 std::shared_ptr<Texture> result;
66
67 unsigned char* data = stbi_load(fullPath.string().c_str(), &width, &height, &numChannels, 0);
68
69 if (data)
70 {
71 result = std::make_shared<Texture>(width, height, numChannels, data);
72 stbi_image_free(data);
73 }
74
75 return result;
76 }
77
78 std::shared_ptr<Texture> TextureManager::GetOrLoadTexture(const std::string& path)
79 {
80 auto it = m_textures.find(path);
81 if (it != m_textures.end())
82 {
83 return it->second;
84 }
85
86 auto texture = Texture::Load(path);
87 m_textures[path] = texture;
88 return texture;
89 }
90}
int GLint
Definition GLForward.h:13
unsigned int GLenum
Definition GLForward.h:12
unsigned int GLuint
Definition GLForward.h:11
FileSystem & GetFileSystem()
Definition Engine.cpp:205
static Engine & GetInstance()
Definition Engine.cpp:50
std::filesystem::path GetAssetsFolder() const
std::shared_ptr< Texture > GetOrLoadTexture(const std::string &path)
Definition Texture.cpp:78
GLuint GetID() const
Definition Texture.cpp:23
Texture(int width, int height, int numChannels, unsigned char *data)
Definition Texture.cpp:9
static std::shared_ptr< Texture > Load(const std::string &path)
Definition Texture.cpp:53
void Init(int width, int height, int numChannels, unsigned char *data)
Definition Texture.cpp:28