texture.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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/util/env.hpp"
  16. #include "game/util/hash.hpp"
  17. #include "helper.hpp"
  18. unsigned char * stbi_load(char const *, int *, int *, int *, int);
  19. void stbi_image_free(void *);
  20. using namespace graphics;
  21. using namespace textures;
  22. static format as_format(int comps) {
  23. switch (comps) {
  24. case 3:
  25. return format::RGB;
  26. case 4:
  27. return format::RGBA;
  28. default:
  29. throw;
  30. }
  31. }
  32. external_data::external_data(std::string const & rel_path) {
  33. std::string abs_path = env::resource_file(rel_path);
  34. int components = 0;
  35. buffer = stbi_load(abs_path.c_str(), &size.x(), &size.y(), &components, 0);
  36. if (!buffer) {
  37. throw std::runtime_error("Unable to read file: '" + rel_path + "'");
  38. }
  39. color = as_format(components);
  40. }
  41. external_data::~external_data() {
  42. if (buffer) { stbi_image_free(buffer); }
  43. }
  44. texture::texture(unsigned int id, math::vec2i const & size)
  45. : identity<texture>(id), size(size) {}