| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- //
- // texture.cpp
- // graphics
- //
- // Created by Sam Jaffe on 7/5/16.
- //
- #include "game/graphics/texture.hpp"
- #include <unordered_map>
- #include "scope_guard/scope_guard.hpp"
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wcomma"
- #define STB_IMAGE_IMPLEMENTATION
- #include "stb/stb_image.h"
- #pragma clang diagnostic pop
- #include "game/util/hash.hpp"
- #include "helper.hpp"
- unsigned char * stbi_load(char const *, int *, int *, int *, int);
- void stbi_image_free(void *);
- using namespace graphics;
- namespace {
- std::unordered_map<std::string, flyweight<texture>> g_textures;
- }
- static textures::format format(int comps) {
- switch (comps) {
- case 3:
- return textures::format::RGB;
- case 4:
- return textures::format::RGBA;
- default:
- throw;
- }
- }
- flyweight<texture> texture::create(std::string const & imagefile) {
- auto found = g_textures.find(imagefile);
- if (found != g_textures.end()) { return found->second; }
- int components = 0;
- math::vec2i size;
- unsigned char * data =
- stbi_load(imagefile.c_str(), &size.x(), &size.y(), &components, 0);
- scope(exit) { stbi_image_free(data); };
- auto id = textures::init(format(components), size, data);
- flyweight<texture> fly{id, {id, size}};
- return g_textures.emplace(imagefile, fly).first->second;
- }
- texture texture::create(char const * data, math::vec2i size) {
- return {textures::init(format(4), size, data), size};
- }
- texture::texture(unsigned int id, math::vec2i sz)
- : identity<texture>(id), size(sz) {}
- texture const texture::WHITE = texture::create("\xFF\xFF\xFF\xFF", {{1, 1}});
- texture const texture::DARK_YELLOW =
- texture::create("\x80\x80\x00\xFF", {{1, 1}});
- texture const texture::LIGHT_BLUE =
- texture::create("\x80\x80\xFF\xFF", {{1, 1}});
|