diff options
Diffstat (limited to 'src/libjin/Render/Texture.cpp')
-rw-r--r-- | src/libjin/Render/Texture.cpp | 99 |
1 files changed, 99 insertions, 0 deletions
diff --git a/src/libjin/Render/Texture.cpp b/src/libjin/Render/Texture.cpp new file mode 100644 index 0000000..cee3552 --- /dev/null +++ b/src/libjin/Render/Texture.cpp @@ -0,0 +1,99 @@ +#include "../modules.h" +#if JIN_MODULES_RENDER + +#include <fstream> +#include "texture.h" +#include "3rdparty/stb/stb_image.h" +#include "../utils/utils.h" +#include "../math/math.h" + +namespace jin +{ +namespace render +{ + + Texture* Texture::createTexture(const char* file) + { + std::ifstream fs; + fs.open(file, std::ios::binary); + Texture* tex = nullptr; + if (fs.is_open()) + { + fs.seekg(0, std::ios::end); + int size = fs.tellg(); + fs.seekg(0, std::ios::beg); + char* buffer = (char*)malloc(size); + memset(buffer, 0, size); + fs.read(buffer, size); + tex = createTexture(buffer, size); + free(buffer); + } + fs.close(); + return tex; + } + + Texture* Texture::createTexture(const void* mem, size_t size) + { + Texture* tex = new Texture(); + if(!tex->loadb(mem, size)) + { + delete tex; + tex = nullptr; + } + return tex; + } + + Texture::Texture() + : Drawable(), pixels(0) + { + } + + Texture::~Texture() + { + stbi_image_free(pixels); + } + + color Texture::getPixel(int x, int y) + { + if (without(x, 0, width) || without(y, 0, height)) + { + return { 0 }; + } + return pixels[x + y * width]; + } + + bool Texture::loadb(const void* b, size_t size) + { + // ʹstbi_load_from_memory + unsigned char* textureData = stbi_load_from_memory((unsigned char *)b, size, &width, &height, NULL, STBI_rgb_alpha); + if (textureData == 0) return false; + pixels = (color*)textureData; + + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, + height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData); + + // set render vertices + Drawable::setVertices( + new float [DRAWABLE_V_SIZE] { + 0, 0, + 0, (float)height, + (float)width, (float)height, + (float)width, 0, + }, + new float [DRAWABLE_V_SIZE] { + 0, 0, + 0, 1, + 1, 1, + 1, 0 + } + ); + + return true; + } +} +} +#endif // JIN_MODULES_RENDER
\ No newline at end of file |