texture.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // texture.cpp
  3. // graphics
  4. //
  5. // Created by Sam Jaffe on 7/5/16.
  6. //
  7. #include "game/graphics/texture.hpp"
  8. #include <unordered_map>
  9. #include "scope_guard/scope_guard.hpp"
  10. #pragma clang diagnostic push
  11. #pragma clang diagnostic ignored "-Wcomma"
  12. #define STB_IMAGE_IMPLEMENTATION
  13. #include "stb/stb_image.h"
  14. #pragma clang diagnostic pop
  15. #include "game/graphics/exception.h"
  16. #include "game/util/env.hpp"
  17. #include "game/util/hash.hpp"
  18. #include "helper.hpp"
  19. unsigned char * stbi_load(char const *, int *, int *, int *, int);
  20. void stbi_image_free(void *);
  21. using namespace graphics;
  22. using namespace textures;
  23. static format as_format(int comps) {
  24. switch (comps) {
  25. case 3:
  26. return format::RGB;
  27. case 4:
  28. return format::RGBA;
  29. default:
  30. throw unknown_texture_format(comps);
  31. }
  32. }
  33. external_data::external_data(std::string const & rel_path) {
  34. std::string abs_path = env::resource_file(rel_path);
  35. int components = 0;
  36. buffer = stbi_load(abs_path.c_str(), &size.x(), &size.y(), &components, 0);
  37. if (!buffer) { throw file_read_error("texture", rel_path); }
  38. color = as_format(components);
  39. }
  40. external_data::~external_data() {
  41. if (buffer) { stbi_image_free(buffer); }
  42. }
  43. texture::texture(unsigned int id, math::vec2i const & size)
  44. : identity<texture>(id), size(size) {}