clusterizer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. // This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
  2. #include "meshoptimizer.h"
  3. #include <assert.h>
  4. #include <float.h>
  5. #include <math.h>
  6. #include <string.h>
  7. // This work is based on:
  8. // Graham Wihlidal. Optimizing the Graphics Pipeline with Compute. 2016
  9. // Matthaeus Chajdas. GeometryFX 1.2 - Cluster Culling. 2016
  10. // Jack Ritter. An Efficient Bounding Sphere. 1990
  11. namespace meshopt
  12. {
  13. // This must be <= 255 since index 0xff is used internally to indice a vertex that doesn't belong to a meshlet
  14. const size_t kMeshletMaxVertices = 255;
  15. // A reasonable limit is around 2*max_vertices or less
  16. const size_t kMeshletMaxTriangles = 512;
  17. struct TriangleAdjacency2
  18. {
  19. unsigned int* counts;
  20. unsigned int* offsets;
  21. unsigned int* data;
  22. };
  23. static void buildTriangleAdjacency(TriangleAdjacency2& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)
  24. {
  25. size_t face_count = index_count / 3;
  26. // allocate arrays
  27. adjacency.counts = allocator.allocate<unsigned int>(vertex_count);
  28. adjacency.offsets = allocator.allocate<unsigned int>(vertex_count);
  29. adjacency.data = allocator.allocate<unsigned int>(index_count);
  30. // fill triangle counts
  31. memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int));
  32. for (size_t i = 0; i < index_count; ++i)
  33. {
  34. assert(indices[i] < vertex_count);
  35. adjacency.counts[indices[i]]++;
  36. }
  37. // fill offset table
  38. unsigned int offset = 0;
  39. for (size_t i = 0; i < vertex_count; ++i)
  40. {
  41. adjacency.offsets[i] = offset;
  42. offset += adjacency.counts[i];
  43. }
  44. assert(offset == index_count);
  45. // fill triangle data
  46. for (size_t i = 0; i < face_count; ++i)
  47. {
  48. unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
  49. adjacency.data[adjacency.offsets[a]++] = unsigned(i);
  50. adjacency.data[adjacency.offsets[b]++] = unsigned(i);
  51. adjacency.data[adjacency.offsets[c]++] = unsigned(i);
  52. }
  53. // fix offsets that have been disturbed by the previous pass
  54. for (size_t i = 0; i < vertex_count; ++i)
  55. {
  56. assert(adjacency.offsets[i] >= adjacency.counts[i]);
  57. adjacency.offsets[i] -= adjacency.counts[i];
  58. }
  59. }
  60. static void computeBoundingSphere(float result[4], const float points[][3], size_t count)
  61. {
  62. assert(count > 0);
  63. // find extremum points along all 3 axes; for each axis we get a pair of points with min/max coordinates
  64. size_t pmin[3] = {0, 0, 0};
  65. size_t pmax[3] = {0, 0, 0};
  66. for (size_t i = 0; i < count; ++i)
  67. {
  68. const float* p = points[i];
  69. for (int axis = 0; axis < 3; ++axis)
  70. {
  71. pmin[axis] = (p[axis] < points[pmin[axis]][axis]) ? i : pmin[axis];
  72. pmax[axis] = (p[axis] > points[pmax[axis]][axis]) ? i : pmax[axis];
  73. }
  74. }
  75. // find the pair of points with largest distance
  76. float paxisd2 = 0;
  77. int paxis = 0;
  78. for (int axis = 0; axis < 3; ++axis)
  79. {
  80. const float* p1 = points[pmin[axis]];
  81. const float* p2 = points[pmax[axis]];
  82. float d2 = (p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[2] - p1[2]) * (p2[2] - p1[2]);
  83. if (d2 > paxisd2)
  84. {
  85. paxisd2 = d2;
  86. paxis = axis;
  87. }
  88. }
  89. // use the longest segment as the initial sphere diameter
  90. const float* p1 = points[pmin[paxis]];
  91. const float* p2 = points[pmax[paxis]];
  92. float center[3] = {(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2, (p1[2] + p2[2]) / 2};
  93. float radius = sqrtf(paxisd2) / 2;
  94. // iteratively adjust the sphere up until all points fit
  95. for (size_t i = 0; i < count; ++i)
  96. {
  97. const float* p = points[i];
  98. float d2 = (p[0] - center[0]) * (p[0] - center[0]) + (p[1] - center[1]) * (p[1] - center[1]) + (p[2] - center[2]) * (p[2] - center[2]);
  99. if (d2 > radius * radius)
  100. {
  101. float d = sqrtf(d2);
  102. assert(d > 0);
  103. float k = 0.5f + (radius / d) / 2;
  104. center[0] = center[0] * k + p[0] * (1 - k);
  105. center[1] = center[1] * k + p[1] * (1 - k);
  106. center[2] = center[2] * k + p[2] * (1 - k);
  107. radius = (radius + d) / 2;
  108. }
  109. }
  110. result[0] = center[0];
  111. result[1] = center[1];
  112. result[2] = center[2];
  113. result[3] = radius;
  114. }
  115. struct Cone
  116. {
  117. float px, py, pz;
  118. float nx, ny, nz;
  119. };
  120. static float getMeshletScore(float distance2, float spread, float cone_weight, float expected_radius)
  121. {
  122. float cone = 1.f - spread * cone_weight;
  123. float cone_clamped = cone < 1e-3f ? 1e-3f : cone;
  124. return (1 + sqrtf(distance2) / expected_radius * (1 - cone_weight)) * cone_clamped;
  125. }
  126. static Cone getMeshletCone(const Cone& acc, unsigned int triangle_count)
  127. {
  128. Cone result = acc;
  129. float center_scale = triangle_count == 0 ? 0.f : 1.f / float(triangle_count);
  130. result.px *= center_scale;
  131. result.py *= center_scale;
  132. result.pz *= center_scale;
  133. float axis_length = result.nx * result.nx + result.ny * result.ny + result.nz * result.nz;
  134. float axis_scale = axis_length == 0.f ? 0.f : 1.f / sqrtf(axis_length);
  135. result.nx *= axis_scale;
  136. result.ny *= axis_scale;
  137. result.nz *= axis_scale;
  138. return result;
  139. }
  140. static float computeTriangleCones(Cone* triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  141. {
  142. (void)vertex_count;
  143. size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
  144. size_t face_count = index_count / 3;
  145. float mesh_area = 0;
  146. for (size_t i = 0; i < face_count; ++i)
  147. {
  148. unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
  149. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  150. const float* p0 = vertex_positions + vertex_stride_float * a;
  151. const float* p1 = vertex_positions + vertex_stride_float * b;
  152. const float* p2 = vertex_positions + vertex_stride_float * c;
  153. float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]};
  154. float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]};
  155. float normalx = p10[1] * p20[2] - p10[2] * p20[1];
  156. float normaly = p10[2] * p20[0] - p10[0] * p20[2];
  157. float normalz = p10[0] * p20[1] - p10[1] * p20[0];
  158. float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz);
  159. float invarea = (area == 0.f) ? 0.f : 1.f / area;
  160. triangles[i].px = (p0[0] + p1[0] + p2[0]) / 3.f;
  161. triangles[i].py = (p0[1] + p1[1] + p2[1]) / 3.f;
  162. triangles[i].pz = (p0[2] + p1[2] + p2[2]) / 3.f;
  163. triangles[i].nx = normalx * invarea;
  164. triangles[i].ny = normaly * invarea;
  165. triangles[i].nz = normalz * invarea;
  166. mesh_area += area;
  167. }
  168. return mesh_area;
  169. }
  170. static void finishMeshlet(meshopt_Meshlet& meshlet, unsigned char* meshlet_triangles)
  171. {
  172. size_t offset = meshlet.triangle_offset + meshlet.triangle_count * 3;
  173. // fill 4b padding with 0
  174. while (offset & 3)
  175. meshlet_triangles[offset++] = 0;
  176. }
  177. static bool appendMeshlet(meshopt_Meshlet& meshlet, unsigned int a, unsigned int b, unsigned int c, unsigned char* used, meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t meshlet_offset, size_t max_vertices, size_t max_triangles)
  178. {
  179. unsigned char& av = used[a];
  180. unsigned char& bv = used[b];
  181. unsigned char& cv = used[c];
  182. bool result = false;
  183. unsigned int used_extra = (av == 0xff) + (bv == 0xff) + (cv == 0xff);
  184. if (meshlet.vertex_count + used_extra > max_vertices || meshlet.triangle_count >= max_triangles)
  185. {
  186. meshlets[meshlet_offset] = meshlet;
  187. for (size_t j = 0; j < meshlet.vertex_count; ++j)
  188. used[meshlet_vertices[meshlet.vertex_offset + j]] = 0xff;
  189. finishMeshlet(meshlet, meshlet_triangles);
  190. meshlet.vertex_offset += meshlet.vertex_count;
  191. meshlet.triangle_offset += (meshlet.triangle_count * 3 + 3) & ~3; // 4b padding
  192. meshlet.vertex_count = 0;
  193. meshlet.triangle_count = 0;
  194. result = true;
  195. }
  196. if (av == 0xff)
  197. {
  198. av = (unsigned char)meshlet.vertex_count;
  199. meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = a;
  200. }
  201. if (bv == 0xff)
  202. {
  203. bv = (unsigned char)meshlet.vertex_count;
  204. meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = b;
  205. }
  206. if (cv == 0xff)
  207. {
  208. cv = (unsigned char)meshlet.vertex_count;
  209. meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = c;
  210. }
  211. meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 0] = av;
  212. meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 1] = bv;
  213. meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 2] = cv;
  214. meshlet.triangle_count++;
  215. return result;
  216. }
  217. static unsigned int getNeighborTriangle(const meshopt_Meshlet& meshlet, const Cone* meshlet_cone, unsigned int* meshlet_vertices, const unsigned int* indices, const TriangleAdjacency2& adjacency, const Cone* triangles, const unsigned int* live_triangles, const unsigned char* used, float meshlet_expected_radius, float cone_weight, unsigned int* out_extra)
  218. {
  219. unsigned int best_triangle = ~0u;
  220. unsigned int best_extra = 5;
  221. float best_score = FLT_MAX;
  222. for (size_t i = 0; i < meshlet.vertex_count; ++i)
  223. {
  224. unsigned int index = meshlet_vertices[meshlet.vertex_offset + i];
  225. unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index];
  226. size_t neighbors_size = adjacency.counts[index];
  227. for (size_t j = 0; j < neighbors_size; ++j)
  228. {
  229. unsigned int triangle = neighbors[j];
  230. unsigned int a = indices[triangle * 3 + 0], b = indices[triangle * 3 + 1], c = indices[triangle * 3 + 2];
  231. unsigned int extra = (used[a] == 0xff) + (used[b] == 0xff) + (used[c] == 0xff);
  232. // triangles that don't add new vertices to meshlets are max. priority
  233. if (extra != 0)
  234. {
  235. // artificially increase the priority of dangling triangles as they're expensive to add to new meshlets
  236. if (live_triangles[a] == 1 || live_triangles[b] == 1 || live_triangles[c] == 1)
  237. extra = 0;
  238. extra++;
  239. }
  240. // since topology-based priority is always more important than the score, we can skip scoring in some cases
  241. if (extra > best_extra)
  242. continue;
  243. float score = 0;
  244. // caller selects one of two scoring functions: geometrical (based on meshlet cone) or topological (based on remaining triangles)
  245. if (meshlet_cone)
  246. {
  247. const Cone& tri_cone = triangles[triangle];
  248. float distance2 =
  249. (tri_cone.px - meshlet_cone->px) * (tri_cone.px - meshlet_cone->px) +
  250. (tri_cone.py - meshlet_cone->py) * (tri_cone.py - meshlet_cone->py) +
  251. (tri_cone.pz - meshlet_cone->pz) * (tri_cone.pz - meshlet_cone->pz);
  252. float spread = tri_cone.nx * meshlet_cone->nx + tri_cone.ny * meshlet_cone->ny + tri_cone.nz * meshlet_cone->nz;
  253. score = getMeshletScore(distance2, spread, cone_weight, meshlet_expected_radius);
  254. }
  255. else
  256. {
  257. // each live_triangles entry is >= 1 since it includes the current triangle we're processing
  258. score = float(live_triangles[a] + live_triangles[b] + live_triangles[c] - 3);
  259. }
  260. // note that topology-based priority is always more important than the score
  261. // this helps maintain reasonable effectiveness of meshlet data and reduces scoring cost
  262. if (extra < best_extra || score < best_score)
  263. {
  264. best_triangle = triangle;
  265. best_extra = extra;
  266. best_score = score;
  267. }
  268. }
  269. }
  270. if (out_extra)
  271. *out_extra = best_extra;
  272. return best_triangle;
  273. }
  274. struct KDNode
  275. {
  276. union
  277. {
  278. float split;
  279. unsigned int index;
  280. };
  281. // leaves: axis = 3, children = number of extra points after this one (0 if 'index' is the only point)
  282. // branches: axis != 3, left subtree = skip 1, right subtree = skip 1+children
  283. unsigned int axis : 2;
  284. unsigned int children : 30;
  285. };
  286. static size_t kdtreePartition(unsigned int* indices, size_t count, const float* points, size_t stride, unsigned int axis, float pivot)
  287. {
  288. size_t m = 0;
  289. // invariant: elements in range [0, m) are < pivot, elements in range [m, i) are >= pivot
  290. for (size_t i = 0; i < count; ++i)
  291. {
  292. float v = points[indices[i] * stride + axis];
  293. // swap(m, i) unconditionally
  294. unsigned int t = indices[m];
  295. indices[m] = indices[i];
  296. indices[i] = t;
  297. // when v >= pivot, we swap i with m without advancing it, preserving invariants
  298. m += v < pivot;
  299. }
  300. return m;
  301. }
  302. static size_t kdtreeBuildLeaf(size_t offset, KDNode* nodes, size_t node_count, unsigned int* indices, size_t count)
  303. {
  304. assert(offset + count <= node_count);
  305. (void)node_count;
  306. KDNode& result = nodes[offset];
  307. result.index = indices[0];
  308. result.axis = 3;
  309. result.children = unsigned(count - 1);
  310. // all remaining points are stored in nodes immediately following the leaf
  311. for (size_t i = 1; i < count; ++i)
  312. {
  313. KDNode& tail = nodes[offset + i];
  314. tail.index = indices[i];
  315. tail.axis = 3;
  316. tail.children = ~0u >> 2; // bogus value to prevent misuse
  317. }
  318. return offset + count;
  319. }
  320. static size_t kdtreeBuild(size_t offset, KDNode* nodes, size_t node_count, const float* points, size_t stride, unsigned int* indices, size_t count, size_t leaf_size)
  321. {
  322. assert(count > 0);
  323. assert(offset < node_count);
  324. if (count <= leaf_size)
  325. return kdtreeBuildLeaf(offset, nodes, node_count, indices, count);
  326. float mean[3] = {};
  327. float vars[3] = {};
  328. float runc = 1, runs = 1;
  329. // gather statistics on the points in the subtree using Welford's algorithm
  330. for (size_t i = 0; i < count; ++i, runc += 1.f, runs = 1.f / runc)
  331. {
  332. const float* point = points + indices[i] * stride;
  333. for (int k = 0; k < 3; ++k)
  334. {
  335. float delta = point[k] - mean[k];
  336. mean[k] += delta * runs;
  337. vars[k] += delta * (point[k] - mean[k]);
  338. }
  339. }
  340. // split axis is one where the variance is largest
  341. unsigned int axis = vars[0] >= vars[1] && vars[0] >= vars[2] ? 0 : vars[1] >= vars[2] ? 1 : 2;
  342. float split = mean[axis];
  343. size_t middle = kdtreePartition(indices, count, points, stride, axis, split);
  344. // when the partition is degenerate simply consolidate the points into a single node
  345. if (middle <= leaf_size / 2 || middle >= count - leaf_size / 2)
  346. return kdtreeBuildLeaf(offset, nodes, node_count, indices, count);
  347. KDNode& result = nodes[offset];
  348. result.split = split;
  349. result.axis = axis;
  350. // left subtree is right after our node
  351. size_t next_offset = kdtreeBuild(offset + 1, nodes, node_count, points, stride, indices, middle, leaf_size);
  352. // distance to the right subtree is represented explicitly
  353. result.children = unsigned(next_offset - offset - 1);
  354. return kdtreeBuild(next_offset, nodes, node_count, points, stride, indices + middle, count - middle, leaf_size);
  355. }
  356. static void kdtreeNearest(KDNode* nodes, unsigned int root, const float* points, size_t stride, const unsigned char* emitted_flags, const float* position, unsigned int& result, float& limit)
  357. {
  358. const KDNode& node = nodes[root];
  359. if (node.axis == 3)
  360. {
  361. // leaf
  362. for (unsigned int i = 0; i <= node.children; ++i)
  363. {
  364. unsigned int index = nodes[root + i].index;
  365. if (emitted_flags[index])
  366. continue;
  367. const float* point = points + index * stride;
  368. float distance2 =
  369. (point[0] - position[0]) * (point[0] - position[0]) +
  370. (point[1] - position[1]) * (point[1] - position[1]) +
  371. (point[2] - position[2]) * (point[2] - position[2]);
  372. float distance = sqrtf(distance2);
  373. if (distance < limit)
  374. {
  375. result = index;
  376. limit = distance;
  377. }
  378. }
  379. }
  380. else
  381. {
  382. // branch; we order recursion to process the node that search position is in first
  383. float delta = position[node.axis] - node.split;
  384. unsigned int first = (delta <= 0) ? 0 : node.children;
  385. unsigned int second = first ^ node.children;
  386. kdtreeNearest(nodes, root + 1 + first, points, stride, emitted_flags, position, result, limit);
  387. // only process the other node if it can have a match based on closest distance so far
  388. if (fabsf(delta) <= limit)
  389. kdtreeNearest(nodes, root + 1 + second, points, stride, emitted_flags, position, result, limit);
  390. }
  391. }
  392. } // namespace meshopt
  393. size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles)
  394. {
  395. using namespace meshopt;
  396. assert(index_count % 3 == 0);
  397. assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices);
  398. assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles);
  399. assert(max_triangles % 4 == 0); // ensures the caller will compute output space properly as index data is 4b aligned
  400. (void)kMeshletMaxVertices;
  401. (void)kMeshletMaxTriangles;
  402. // meshlet construction is limited by max vertices and max triangles per meshlet
  403. // the worst case is that the input is an unindexed stream since this equally stresses both limits
  404. // note that we assume that in the worst case, we leave 2 vertices unpacked in each meshlet - if we have space for 3 we can pack any triangle
  405. size_t max_vertices_conservative = max_vertices - 2;
  406. size_t meshlet_limit_vertices = (index_count + max_vertices_conservative - 1) / max_vertices_conservative;
  407. size_t meshlet_limit_triangles = (index_count / 3 + max_triangles - 1) / max_triangles;
  408. return meshlet_limit_vertices > meshlet_limit_triangles ? meshlet_limit_vertices : meshlet_limit_triangles;
  409. }
  410. size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight)
  411. {
  412. using namespace meshopt;
  413. assert(index_count % 3 == 0);
  414. assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
  415. assert(vertex_positions_stride % sizeof(float) == 0);
  416. assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices);
  417. assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles);
  418. assert(max_triangles % 4 == 0); // ensures the caller will compute output space properly as index data is 4b aligned
  419. assert(cone_weight >= 0 && cone_weight <= 1);
  420. meshopt_Allocator allocator;
  421. TriangleAdjacency2 adjacency = {};
  422. buildTriangleAdjacency(adjacency, indices, index_count, vertex_count, allocator);
  423. unsigned int* live_triangles = allocator.allocate<unsigned int>(vertex_count);
  424. memcpy(live_triangles, adjacency.counts, vertex_count * sizeof(unsigned int));
  425. size_t face_count = index_count / 3;
  426. unsigned char* emitted_flags = allocator.allocate<unsigned char>(face_count);
  427. memset(emitted_flags, 0, face_count);
  428. // for each triangle, precompute centroid & normal to use for scoring
  429. Cone* triangles = allocator.allocate<Cone>(face_count);
  430. float mesh_area = computeTriangleCones(triangles, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  431. // assuming each meshlet is a square patch, expected radius is sqrt(expected area)
  432. float triangle_area_avg = face_count == 0 ? 0.f : mesh_area / float(face_count) * 0.5f;
  433. float meshlet_expected_radius = sqrtf(triangle_area_avg * max_triangles) * 0.5f;
  434. // build a kd-tree for nearest neighbor lookup
  435. unsigned int* kdindices = allocator.allocate<unsigned int>(face_count);
  436. for (size_t i = 0; i < face_count; ++i)
  437. kdindices[i] = unsigned(i);
  438. KDNode* nodes = allocator.allocate<KDNode>(face_count * 2);
  439. kdtreeBuild(0, nodes, face_count * 2, &triangles[0].px, sizeof(Cone) / sizeof(float), kdindices, face_count, /* leaf_size= */ 8);
  440. // index of the vertex in the meshlet, 0xff if the vertex isn't used
  441. unsigned char* used = allocator.allocate<unsigned char>(vertex_count);
  442. memset(used, -1, vertex_count);
  443. meshopt_Meshlet meshlet = {};
  444. size_t meshlet_offset = 0;
  445. Cone meshlet_cone_acc = {};
  446. for (;;)
  447. {
  448. Cone meshlet_cone = getMeshletCone(meshlet_cone_acc, meshlet.triangle_count);
  449. unsigned int best_extra = 0;
  450. unsigned int best_triangle = getNeighborTriangle(meshlet, &meshlet_cone, meshlet_vertices, indices, adjacency, triangles, live_triangles, used, meshlet_expected_radius, cone_weight, &best_extra);
  451. // if the best triangle doesn't fit into current meshlet, the spatial scoring we've used is not very meaningful, so we re-select using topological scoring
  452. if (best_triangle != ~0u && (meshlet.vertex_count + best_extra > max_vertices || meshlet.triangle_count >= max_triangles))
  453. {
  454. best_triangle = getNeighborTriangle(meshlet, NULL, meshlet_vertices, indices, adjacency, triangles, live_triangles, used, meshlet_expected_radius, 0.f, NULL);
  455. }
  456. // when we run out of neighboring triangles we need to switch to spatial search; we currently just pick the closest triangle irrespective of connectivity
  457. if (best_triangle == ~0u)
  458. {
  459. float position[3] = {meshlet_cone.px, meshlet_cone.py, meshlet_cone.pz};
  460. unsigned int index = ~0u;
  461. float limit = FLT_MAX;
  462. kdtreeNearest(nodes, 0, &triangles[0].px, sizeof(Cone) / sizeof(float), emitted_flags, position, index, limit);
  463. best_triangle = index;
  464. }
  465. if (best_triangle == ~0u)
  466. break;
  467. unsigned int a = indices[best_triangle * 3 + 0], b = indices[best_triangle * 3 + 1], c = indices[best_triangle * 3 + 2];
  468. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  469. // add meshlet to the output; when the current meshlet is full we reset the accumulated bounds
  470. if (appendMeshlet(meshlet, a, b, c, used, meshlets, meshlet_vertices, meshlet_triangles, meshlet_offset, max_vertices, max_triangles))
  471. {
  472. meshlet_offset++;
  473. memset(&meshlet_cone_acc, 0, sizeof(meshlet_cone_acc));
  474. }
  475. live_triangles[a]--;
  476. live_triangles[b]--;
  477. live_triangles[c]--;
  478. // remove emitted triangle from adjacency data
  479. // this makes sure that we spend less time traversing these lists on subsequent iterations
  480. for (size_t k = 0; k < 3; ++k)
  481. {
  482. unsigned int index = indices[best_triangle * 3 + k];
  483. unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index];
  484. size_t neighbors_size = adjacency.counts[index];
  485. for (size_t i = 0; i < neighbors_size; ++i)
  486. {
  487. unsigned int tri = neighbors[i];
  488. if (tri == best_triangle)
  489. {
  490. neighbors[i] = neighbors[neighbors_size - 1];
  491. adjacency.counts[index]--;
  492. break;
  493. }
  494. }
  495. }
  496. // update aggregated meshlet cone data for scoring subsequent triangles
  497. meshlet_cone_acc.px += triangles[best_triangle].px;
  498. meshlet_cone_acc.py += triangles[best_triangle].py;
  499. meshlet_cone_acc.pz += triangles[best_triangle].pz;
  500. meshlet_cone_acc.nx += triangles[best_triangle].nx;
  501. meshlet_cone_acc.ny += triangles[best_triangle].ny;
  502. meshlet_cone_acc.nz += triangles[best_triangle].nz;
  503. emitted_flags[best_triangle] = 1;
  504. }
  505. if (meshlet.triangle_count)
  506. {
  507. finishMeshlet(meshlet, meshlet_triangles);
  508. meshlets[meshlet_offset++] = meshlet;
  509. }
  510. assert(meshlet_offset <= meshopt_buildMeshletsBound(index_count, max_vertices, max_triangles));
  511. return meshlet_offset;
  512. }
  513. size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles)
  514. {
  515. using namespace meshopt;
  516. assert(index_count % 3 == 0);
  517. assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices);
  518. assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles);
  519. assert(max_triangles % 4 == 0); // ensures the caller will compute output space properly as index data is 4b aligned
  520. meshopt_Allocator allocator;
  521. // index of the vertex in the meshlet, 0xff if the vertex isn't used
  522. unsigned char* used = allocator.allocate<unsigned char>(vertex_count);
  523. memset(used, -1, vertex_count);
  524. meshopt_Meshlet meshlet = {};
  525. size_t meshlet_offset = 0;
  526. for (size_t i = 0; i < index_count; i += 3)
  527. {
  528. unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];
  529. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  530. // appends triangle to the meshlet and writes previous meshlet to the output if full
  531. meshlet_offset += appendMeshlet(meshlet, a, b, c, used, meshlets, meshlet_vertices, meshlet_triangles, meshlet_offset, max_vertices, max_triangles);
  532. }
  533. if (meshlet.triangle_count)
  534. {
  535. finishMeshlet(meshlet, meshlet_triangles);
  536. meshlets[meshlet_offset++] = meshlet;
  537. }
  538. assert(meshlet_offset <= meshopt_buildMeshletsBound(index_count, max_vertices, max_triangles));
  539. return meshlet_offset;
  540. }
  541. meshopt_Bounds meshopt_computeClusterBounds(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  542. {
  543. using namespace meshopt;
  544. assert(index_count % 3 == 0);
  545. assert(index_count / 3 <= kMeshletMaxTriangles);
  546. assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
  547. assert(vertex_positions_stride % sizeof(float) == 0);
  548. (void)vertex_count;
  549. size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
  550. // compute triangle normals and gather triangle corners
  551. float normals[kMeshletMaxTriangles][3];
  552. float corners[kMeshletMaxTriangles][3][3];
  553. size_t triangles = 0;
  554. for (size_t i = 0; i < index_count; i += 3)
  555. {
  556. unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];
  557. assert(a < vertex_count && b < vertex_count && c < vertex_count);
  558. const float* p0 = vertex_positions + vertex_stride_float * a;
  559. const float* p1 = vertex_positions + vertex_stride_float * b;
  560. const float* p2 = vertex_positions + vertex_stride_float * c;
  561. float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]};
  562. float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]};
  563. float normalx = p10[1] * p20[2] - p10[2] * p20[1];
  564. float normaly = p10[2] * p20[0] - p10[0] * p20[2];
  565. float normalz = p10[0] * p20[1] - p10[1] * p20[0];
  566. float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz);
  567. // no need to include degenerate triangles - they will be invisible anyway
  568. if (area == 0.f)
  569. continue;
  570. // record triangle normals & corners for future use; normal and corner 0 define a plane equation
  571. normals[triangles][0] = normalx / area;
  572. normals[triangles][1] = normaly / area;
  573. normals[triangles][2] = normalz / area;
  574. memcpy(corners[triangles][0], p0, 3 * sizeof(float));
  575. memcpy(corners[triangles][1], p1, 3 * sizeof(float));
  576. memcpy(corners[triangles][2], p2, 3 * sizeof(float));
  577. triangles++;
  578. }
  579. meshopt_Bounds bounds = {};
  580. // degenerate cluster, no valid triangles => trivial reject (cone data is 0)
  581. if (triangles == 0)
  582. return bounds;
  583. // compute cluster bounding sphere; we'll use the center to determine normal cone apex as well
  584. float psphere[4] = {};
  585. computeBoundingSphere(psphere, corners[0], triangles * 3);
  586. float center[3] = {psphere[0], psphere[1], psphere[2]};
  587. // treating triangle normals as points, find the bounding sphere - the sphere center determines the optimal cone axis
  588. float nsphere[4] = {};
  589. computeBoundingSphere(nsphere, normals, triangles);
  590. float axis[3] = {nsphere[0], nsphere[1], nsphere[2]};
  591. float axislength = sqrtf(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]);
  592. float invaxislength = axislength == 0.f ? 0.f : 1.f / axislength;
  593. axis[0] *= invaxislength;
  594. axis[1] *= invaxislength;
  595. axis[2] *= invaxislength;
  596. // compute a tight cone around all normals, mindp = cos(angle/2)
  597. float mindp = 1.f;
  598. for (size_t i = 0; i < triangles; ++i)
  599. {
  600. float dp = normals[i][0] * axis[0] + normals[i][1] * axis[1] + normals[i][2] * axis[2];
  601. mindp = (dp < mindp) ? dp : mindp;
  602. }
  603. // fill bounding sphere info; note that below we can return bounds without cone information for degenerate cones
  604. bounds.center[0] = center[0];
  605. bounds.center[1] = center[1];
  606. bounds.center[2] = center[2];
  607. bounds.radius = psphere[3];
  608. // degenerate cluster, normal cone is larger than a hemisphere => trivial accept
  609. // note that if mindp is positive but close to 0, the triangle intersection code below gets less stable
  610. // we arbitrarily decide that if a normal cone is ~168 degrees wide or more, the cone isn't useful
  611. if (mindp <= 0.1f)
  612. {
  613. bounds.cone_cutoff = 1;
  614. bounds.cone_cutoff_s8 = 127;
  615. return bounds;
  616. }
  617. float maxt = 0;
  618. // we need to find the point on center-t*axis ray that lies in negative half-space of all triangles
  619. for (size_t i = 0; i < triangles; ++i)
  620. {
  621. // dot(center-t*axis-corner, trinormal) = 0
  622. // dot(center-corner, trinormal) - t * dot(axis, trinormal) = 0
  623. float cx = center[0] - corners[i][0][0];
  624. float cy = center[1] - corners[i][0][1];
  625. float cz = center[2] - corners[i][0][2];
  626. float dc = cx * normals[i][0] + cy * normals[i][1] + cz * normals[i][2];
  627. float dn = axis[0] * normals[i][0] + axis[1] * normals[i][1] + axis[2] * normals[i][2];
  628. // dn should be larger than mindp cutoff above
  629. assert(dn > 0.f);
  630. float t = dc / dn;
  631. maxt = (t > maxt) ? t : maxt;
  632. }
  633. // cone apex should be in the negative half-space of all cluster triangles by construction
  634. bounds.cone_apex[0] = center[0] - axis[0] * maxt;
  635. bounds.cone_apex[1] = center[1] - axis[1] * maxt;
  636. bounds.cone_apex[2] = center[2] - axis[2] * maxt;
  637. // note: this axis is the axis of the normal cone, but our test for perspective camera effectively negates the axis
  638. bounds.cone_axis[0] = axis[0];
  639. bounds.cone_axis[1] = axis[1];
  640. bounds.cone_axis[2] = axis[2];
  641. // cos(a) for normal cone is mindp; we need to add 90 degrees on both sides and invert the cone
  642. // which gives us -cos(a+90) = -(-sin(a)) = sin(a) = sqrt(1 - cos^2(a))
  643. bounds.cone_cutoff = sqrtf(1 - mindp * mindp);
  644. // quantize axis & cutoff to 8-bit SNORM format
  645. bounds.cone_axis_s8[0] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[0], 8));
  646. bounds.cone_axis_s8[1] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[1], 8));
  647. bounds.cone_axis_s8[2] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[2], 8));
  648. // for the 8-bit test to be conservative, we need to adjust the cutoff by measuring the max. error
  649. float cone_axis_s8_e0 = fabsf(bounds.cone_axis_s8[0] / 127.f - bounds.cone_axis[0]);
  650. float cone_axis_s8_e1 = fabsf(bounds.cone_axis_s8[1] / 127.f - bounds.cone_axis[1]);
  651. float cone_axis_s8_e2 = fabsf(bounds.cone_axis_s8[2] / 127.f - bounds.cone_axis[2]);
  652. // note that we need to round this up instead of rounding to nearest, hence +1
  653. int cone_cutoff_s8 = int(127 * (bounds.cone_cutoff + cone_axis_s8_e0 + cone_axis_s8_e1 + cone_axis_s8_e2) + 1);
  654. bounds.cone_cutoff_s8 = (cone_cutoff_s8 > 127) ? 127 : (signed char)(cone_cutoff_s8);
  655. return bounds;
  656. }
  657. meshopt_Bounds meshopt_computeMeshletBounds(const unsigned int* meshlet_vertices, const unsigned char* meshlet_triangles, size_t triangle_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  658. {
  659. using namespace meshopt;
  660. assert(triangle_count <= kMeshletMaxTriangles);
  661. assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
  662. assert(vertex_positions_stride % sizeof(float) == 0);
  663. unsigned int indices[kMeshletMaxTriangles * 3];
  664. for (size_t i = 0; i < triangle_count * 3; ++i)
  665. {
  666. unsigned int index = meshlet_vertices[meshlet_triangles[i]];
  667. assert(index < vertex_count);
  668. indices[i] = index;
  669. }
  670. return meshopt_computeClusterBounds(indices, triangle_count * 3, vertex_positions, vertex_count, vertex_positions_stride);
  671. }