material.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // material.cpp
  3. // graphics
  4. //
  5. // Created by Sam Jaffe on 7/5/16.
  6. //
  7. #include "game/graphics/material.hpp"
  8. #include "game/graphics/texture.hpp"
  9. #include "helper.hpp"
  10. using namespace graphics;
  11. namespace {
  12. using key_t = std::tuple<flyweight<shader_program>, std::string, std::string>;
  13. std::unordered_map<key_t, flyweight<material>> g_materials;
  14. }
  15. static math::vec2i ZERO{{0, 0}};
  16. flyweight<texture> get_texture(std::string const & texture,
  17. std::string const & uniform) {
  18. if (!texture.empty()) {
  19. try {
  20. return texture::create(texture);
  21. } catch (std::exception const & e) {
  22. // TODO: Logging
  23. }
  24. }
  25. if (uniform == "u_normalMap") {
  26. return texture::LIGHT_BLUE;
  27. } else if (uniform == "u_specularMap") {
  28. return texture::DARK_YELLOW;
  29. } else if (uniform == "u_diffuseMap") {
  30. return texture::WHITE;
  31. }
  32. throw;
  33. }
  34. flyweight<material> material::create(shader_program const & sp,
  35. std::string const & texture,
  36. std::string const & uniform) {
  37. key_t key = std::make_tuple(sp, texture, uniform);
  38. auto found = g_materials.find(key);
  39. if (found != g_materials.end()) { return found->second; }
  40. static unsigned int id{0};
  41. material mat{++id, sp};
  42. mat.uniforms.push_back({get_texture(texture, uniform),
  43. shaders::uniform_location(sp.id, uniform)});
  44. flyweight<material> fly{id, mat};
  45. return g_materials.emplace(key, fly).first->second;
  46. }
  47. material::material(unsigned int id, shader_program const & sp)
  48. : identity<material>(id), shaders(sp) {}
  49. math::vec2i material::size() const {
  50. return uniforms.empty() ? ZERO : uniforms.front().texture.actual().size;
  51. }