optimize.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Copyright 2011 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"); you
  4. // may not use this file except in compliance with the License. You
  5. // may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License.
  14. #ifndef WEBGL_LOADER_OPTIMIZE_H_
  15. #define WEBGL_LOADER_OPTIMIZE_H_
  16. #include <math.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include "base.h"
  20. // TODO: since most vertices are part of 6 faces, you can optimize
  21. // this by using a small inline buffer.
  22. typedef std::vector<int> FaceList;
  23. // Linear-Speed Vertex Cache Optimisation, via:
  24. // http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
  25. class VertexOptimizer {
  26. public:
  27. struct TriangleData {
  28. bool active; // true iff triangle has not been optimized and emitted.
  29. // TODO: eliminate some wasted computation by using this cache.
  30. // float score;
  31. };
  32. VertexOptimizer(const QuantizedAttribList& attribs)
  33. : attribs_(attribs),
  34. per_vertex_(attribs_.size() / 8),
  35. next_unused_index_(0)
  36. {
  37. // The cache has an extra slot allocated to simplify the logic in
  38. // InsertIndexToCache.
  39. for (unsigned int i = 0; i < kCacheSize + 1; ++i) {
  40. cache_[i] = kUnknownIndex;
  41. }
  42. // Initialize per-vertex state.
  43. for (size_t i = 0; i < per_vertex_.size(); ++i) {
  44. VertexData& vertex_data = per_vertex_[i];
  45. vertex_data.cache_tag = kCacheSize;
  46. vertex_data.output_index = kMaxOutputIndex;
  47. }
  48. }
  49. void AddTriangles(const int* indices, size_t length,
  50. WebGLMeshList* meshes) {
  51. std::vector<TriangleData> per_tri(length / 3);
  52. // Loop through the triangles, updating vertex->face lists.
  53. for (size_t i = 0; i < per_tri.size(); ++i) {
  54. per_tri[i].active = true;
  55. per_vertex_[indices[3*i + 0]].faces.push_back(i);
  56. per_vertex_[indices[3*i + 1]].faces.push_back(i);
  57. per_vertex_[indices[3*i + 2]].faces.push_back(i);
  58. }
  59. // TODO: with index bounds, no need to recompute everything.
  60. // Compute initial vertex scores.
  61. for (size_t i = 0; i < per_vertex_.size(); ++i) {
  62. VertexData& vertex_data = per_vertex_[i];
  63. vertex_data.cache_tag = kCacheSize;
  64. vertex_data.output_index = kMaxOutputIndex;
  65. vertex_data.UpdateScore();
  66. }
  67. // Prepare output.
  68. if (meshes->empty()) {
  69. meshes->push_back(WebGLMesh());
  70. }
  71. WebGLMesh* mesh = &meshes->back();
  72. // Consume indices, one triangle at a time.
  73. for (size_t c = 0; c < per_tri.size(); ++c) {
  74. const int best_triangle = FindBestTriangle(indices, per_tri);
  75. per_tri[best_triangle].active = false;
  76. // Iterate through triangle indices.
  77. for (size_t i = 0; i < 3; ++i) {
  78. const int index = indices[3*best_triangle + i];
  79. VertexData& vertex_data = per_vertex_[index];
  80. vertex_data.RemoveFace(best_triangle);
  81. InsertIndexToCache(index);
  82. const int cached_output_index = per_vertex_[index].output_index;
  83. // Have we seen this index before?
  84. if (cached_output_index != kMaxOutputIndex) {
  85. mesh->indices.push_back(cached_output_index);
  86. continue;
  87. }
  88. // The first time we see an index, not only do we increment
  89. // next_unused_index_ counter, but we must also copy the
  90. // corresponding attributes. TODO: do quantization here?
  91. per_vertex_[index].output_index = next_unused_index_;
  92. for (size_t j = 0; j < 8; ++j) {
  93. mesh->attribs.push_back(attribs_[8*index + j]);
  94. }
  95. mesh->indices.push_back(next_unused_index_++);
  96. }
  97. // Check if there is room for another triangle.
  98. if (next_unused_index_ > kMaxOutputIndex - 3) {
  99. // Is it worth figuring out which other triangles can be added
  100. // given the verties already added? Then, perhaps
  101. // re-optimizing?
  102. next_unused_index_ = 0;
  103. meshes->push_back(WebGLMesh());
  104. mesh = &meshes->back();
  105. for (size_t i = 0; i <= kCacheSize; ++i) {
  106. cache_[i] = kUnknownIndex;
  107. }
  108. for (size_t i = 0; i < per_vertex_.size(); ++i) {
  109. per_vertex_[i].output_index = kMaxOutputIndex;
  110. }
  111. }
  112. }
  113. }
  114. private:
  115. static const int kUnknownIndex = -1;
  116. static const uint16 kMaxOutputIndex = 0xD800;
  117. static const size_t kCacheSize = 32; // Does larger improve compression?
  118. struct VertexData {
  119. // Should this also update scores for incident triangles?
  120. void UpdateScore() {
  121. const size_t active_tris = faces.size();
  122. if (active_tris <= 0) {
  123. score = -1.f;
  124. return;
  125. }
  126. // TODO: build initial score table.
  127. if (cache_tag < 3) {
  128. // The most recent triangle should has a fixed score to
  129. // discourage generating nothing but really long strips. If we
  130. // want strips, we should use a different optimizer.
  131. const float kLastTriScore = 0.75f;
  132. score = kLastTriScore;
  133. } else if (cache_tag < kCacheSize) {
  134. // Points for being recently used.
  135. const float kScale = 1.f / (kCacheSize - 3);
  136. const float kCacheDecayPower = 1.5f;
  137. score = powf(1.f - kScale * (cache_tag - 3), kCacheDecayPower);
  138. } else {
  139. // Not in cache.
  140. score = 0.f;
  141. }
  142. // Bonus points for having a low number of tris still to use the
  143. // vert, so we get rid of lone verts quickly.
  144. const float kValenceBoostScale = 2.0f;
  145. const float kValenceBoostPower = 0.5f;
  146. // rsqrt?
  147. const float valence_boost = powf(active_tris, -kValenceBoostPower);
  148. score += valence_boost * kValenceBoostScale;
  149. }
  150. // TODO: this assumes that "tri" is in the list!
  151. void RemoveFace(int tri) {
  152. FaceList::iterator face = faces.begin();
  153. while (*face != tri) ++face;
  154. *face = faces.back();
  155. faces.pop_back();
  156. }
  157. FaceList faces;
  158. unsigned int cache_tag; // kCacheSize means not in cache.
  159. float score;
  160. uint16 output_index;
  161. };
  162. int FindBestTriangle(const int* indices,
  163. const std::vector<TriangleData>& per_tri) {
  164. float best_score = -HUGE_VALF;
  165. int best_triangle = -1;
  166. // The trick to making this algorithm run in linear time (with
  167. // respect to the vertices) is to only scan the triangles incident
  168. // on the simulated cache for the next triangle. It is an
  169. // approximation, but the score is heuristic. Anyway, most of the
  170. // time the best triangle will be found this way.
  171. for (size_t i = 0; i < kCacheSize; ++i) {
  172. if (cache_[i] == kUnknownIndex) {
  173. break;
  174. }
  175. const VertexData& vertex_data = per_vertex_[cache_[i]];
  176. for (size_t j = 0; j < vertex_data.faces.size(); ++j) {
  177. const int tri_index = vertex_data.faces[j];
  178. if (per_tri[tri_index].active) {
  179. const float score =
  180. per_vertex_[indices[3*tri_index + 0]].score +
  181. per_vertex_[indices[3*tri_index + 1]].score +
  182. per_vertex_[indices[3*tri_index + 2]].score;
  183. if (score > best_score) {
  184. best_score = score;
  185. best_triangle = tri_index;
  186. }
  187. }
  188. }
  189. }
  190. // TODO: keep a range of active triangles to make the slow scan a
  191. // little faster. Does this ever happen?
  192. if (best_triangle == -1) {
  193. // If no triangles can be found through the cache (e.g. for the
  194. // first triangle) go through all the active triangles and find
  195. // the best one.
  196. for (size_t i = 0; i < per_tri.size(); ++i) {
  197. if (per_tri[i].active) {
  198. const float score =
  199. per_vertex_[indices[3*i + 0]].score +
  200. per_vertex_[indices[3*i + 1]].score +
  201. per_vertex_[indices[3*i + 2]].score;
  202. if (score > best_score) {
  203. best_score = score;
  204. best_triangle = i;
  205. }
  206. }
  207. }
  208. CHECK(-1 != best_triangle);
  209. }
  210. return best_triangle;
  211. }
  212. // TODO: faster to update an entire triangle.
  213. // This also updates the vertex scores!
  214. void InsertIndexToCache(int index) {
  215. // Find how recently the vertex was used.
  216. const unsigned int cache_tag = per_vertex_[index].cache_tag;
  217. // Don't do anything if the vertex is already at the head of the
  218. // LRU list.
  219. if (cache_tag == 0) return;
  220. // Loop through the cache, inserting the index at the front, and
  221. // bubbling down to where the index was originally found. If the
  222. // index was not originally in the cache, then it claims to be at
  223. // the (kCacheSize + 1)th entry, and we use an extra slot to make
  224. // that case simpler.
  225. int to_insert = index;
  226. for (unsigned int i = 0; i <= cache_tag; ++i) {
  227. const int current_index = cache_[i];
  228. // Update cross references between the entry of the cache and
  229. // the per-vertex data.
  230. cache_[i] = to_insert;
  231. per_vertex_[to_insert].cache_tag = i;
  232. per_vertex_[to_insert].UpdateScore();
  233. // No need to continue if we find an empty entry.
  234. if (current_index == kUnknownIndex) {
  235. break;
  236. }
  237. to_insert = current_index;
  238. }
  239. }
  240. const QuantizedAttribList& attribs_;
  241. std::vector<VertexData> per_vertex_;
  242. int cache_[kCacheSize + 1];
  243. uint16 next_unused_index_;
  244. };
  245. #endif // WEBGL_LOADER_OPTIMIZE_H_