All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
UnityMaterialToTextureMap.h
1 #pragma once
2 
3 #include "MessageQueue.h"
4 #include "Graphics.h"
5 #include <vector>
6 #include <string>
7 #include <unordered_map>
8 
9 namespace Eegeo
10 {
11  namespace Unity
12  {
14  {
15  private:
16 
17  struct MaterialTexturePairing
18  {
19  std::string materialName;
20  GLuint textureID;
21  };
22 
23  public:
24 
25  void SetTextureForMaterial(const std::string& materialName, GLuint textureID) // called from bg threads
26  {
27  m_messageQueue.Enqueue(MaterialTexturePairing{ materialName, textureID });
28  }
29 
30  GLuint GetTextureForMaterial(const std::string& materialName) // called on main thread
31  {
32  GLuint result = 0;
33 
34  auto it = m_materials.find(materialName);
35 
36  if (it == m_materials.end())
37  {
38  DrainQueue();
39  it = m_materials.find(materialName);
40  }
41 
42  if (it != m_materials.end())
43  {
44  result = it->second;
45  }
46 
47  return result;
48  }
49 
50  void ReleaseTexture(GLuint id) // ultimately called on main thread
51  {
52  auto it = m_reverseMaterialMapping.find(id);
53 
54  if (it == m_reverseMaterialMapping.end())
55  {
56  DrainQueue();
57  it = m_reverseMaterialMapping.find(id);
58  }
59 
60  if (it != m_reverseMaterialMapping.end())
61  {
62  for (const auto& materialName : it->second)
63  {
64  m_materials.erase(materialName);
65  }
66 
67  m_reverseMaterialMapping.erase(it);
68  }
69  }
70 
71  private:
72 
73  void DrainQueue()
74  {
75  MaterialTexturePairing pairing;
76 
77  while (m_messageQueue.TryDequeue(pairing))
78  {
79  m_materials.insert({ pairing.materialName, pairing.textureID });
80  auto existingReverseEntry = m_reverseMaterialMapping.find(pairing.textureID);
81 
82  if (existingReverseEntry != m_reverseMaterialMapping.end())
83  {
84  existingReverseEntry->second.push_back(pairing.materialName);
85  }
86  else
87  {
88  m_reverseMaterialMapping.insert({ pairing.textureID, { pairing.materialName } });
89  }
90  }
91  }
92 
94  std::unordered_map<std::string, GLuint> m_materials;
95  std::unordered_map<GLuint, std::vector<std::string>> m_reverseMaterialMapping;
96  };
97  }
98 }
99 
100