mesh_decoder.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "mesh_decoder.h"
  2. #include "mesh_codec.hpp"
  3. #include "third_party/static_block.hpp"
  4. #include "impl/main_impl.h"
  5. #include <unordered_map>
  6. using namespace mesh_codec;
  7. namespace mesh_decoder_impl {
  8. using mesh_map_type =
  9. std::unordered_map<size_t, mesh_ptr>;
  10. mesh_map_type mesh_pool;
  11. static_block {
  12. register_cleanup_func([] { mesh_pool.clear(); });
  13. }
  14. using hasher_type = std::hash<std::string>;
  15. hasher_type name_hasher;
  16. mesh_ptr get_no_transfer_mesh(size_t name) {
  17. assert(mesh_pool.contains(name));
  18. return mesh_pool.at(name);
  19. }
  20. }
  21. using namespace mesh_decoder_impl;
  22. struct mesh_decoder::impl {
  23. using cache_map_type =
  24. std::unordered_map<hash_type, mesh_ptr>;
  25. cache_map_type cache_map;
  26. static mesh_ptr decode_mesh(const data_type &data) {
  27. auto ret = mesh_type::raw_info_type();
  28. auto reader = network_reader(data);
  29. reader >> ret.num_triangles;
  30. auto vbo_size = reader.read_value<size_t>();
  31. ret.vbo_data = reader.read_data(vbo_size);
  32. auto ebo_size = reader.read_value<size_t>();
  33. ret.ebo_data = reader.read_data(ebo_size);
  34. assert(reader.empty());
  35. return mesh_type::from_raw(ret);
  36. }
  37. mesh_ptr decode(const data_type &data) {
  38. auto reader = network_reader(data);
  39. auto flag = reader.read_value<flag_type>();
  40. if (flag == FLAG_NO_TRANSFER) {
  41. auto name = reader.read_value<size_t>();
  42. return get_no_transfer_mesh(name);
  43. }
  44. auto id = reader.read_value<hash_type>();
  45. if (cache_map.contains(id)) {
  46. return cache_map.at(id);
  47. }
  48. // assert(!reader.empty());
  49. if (reader.empty()) return nullptr; // TODO: mesh IDR may not be handled???
  50. auto mesh = decode_mesh(reader.read_remain());
  51. if (flag != FLAG_NO_CACHE) {
  52. assert(!cache_map.contains(id));
  53. cache_map.emplace(id, mesh);
  54. }
  55. return mesh;
  56. }
  57. };
  58. mesh_decoder::mesh_decoder(create_config _)
  59. : pimpl(std::make_unique<impl>()) {
  60. }
  61. mesh_decoder::~mesh_decoder() = default;
  62. mesh_ptr mesh_decoder::decode(const data_type &data) {
  63. return pimpl->decode(data);
  64. }
  65. void register_mesh_file(const std::string &name,
  66. const std::string &path) {
  67. auto mesh = mesh_type::create({.path = path});
  68. auto name_id = name_hasher(name);
  69. assert(!mesh_pool.contains(name_id));
  70. mesh_pool.emplace(name_id, mesh);
  71. }
  72. void register_mesh_list(const YAML::Node &conf_list) {
  73. for (auto &conf: conf_list) {
  74. register_mesh_file(LOAD_STR("name"), LOAD_STR("path"));
  75. }
  76. }