simplifier.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  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. #ifndef TRACE
  8. #define TRACE 0
  9. #endif
  10. #if TRACE
  11. #include <stdio.h>
  12. #endif
  13. // This work is based on:
  14. // Michael Garland and Paul S. Heckbert. Surface simplification using quadric error metrics. 1997
  15. // Michael Garland. Quadric-based polygonal surface simplification. 1999
  16. // Peter Lindstrom. Out-of-Core Simplification of Large Polygonal Models. 2000
  17. // Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 2003
  18. namespace meshopt
  19. {
  20. struct EdgeAdjacency
  21. {
  22. unsigned int* counts;
  23. unsigned int* offsets;
  24. unsigned int* data;
  25. };
  26. static void buildEdgeAdjacency(EdgeAdjacency& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)
  27. {
  28. size_t face_count = index_count / 3;
  29. // allocate arrays
  30. adjacency.counts = allocator.allocate<unsigned int>(vertex_count);
  31. adjacency.offsets = allocator.allocate<unsigned int>(vertex_count);
  32. adjacency.data = allocator.allocate<unsigned int>(index_count);
  33. // fill edge counts
  34. memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int));
  35. for (size_t i = 0; i < index_count; ++i)
  36. {
  37. assert(indices[i] < vertex_count);
  38. adjacency.counts[indices[i]]++;
  39. }
  40. // fill offset table
  41. unsigned int offset = 0;
  42. for (size_t i = 0; i < vertex_count; ++i)
  43. {
  44. adjacency.offsets[i] = offset;
  45. offset += adjacency.counts[i];
  46. }
  47. assert(offset == index_count);
  48. // fill edge data
  49. for (size_t i = 0; i < face_count; ++i)
  50. {
  51. unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
  52. adjacency.data[adjacency.offsets[a]++] = b;
  53. adjacency.data[adjacency.offsets[b]++] = c;
  54. adjacency.data[adjacency.offsets[c]++] = a;
  55. }
  56. // fix offsets that have been disturbed by the previous pass
  57. for (size_t i = 0; i < vertex_count; ++i)
  58. {
  59. assert(adjacency.offsets[i] >= adjacency.counts[i]);
  60. adjacency.offsets[i] -= adjacency.counts[i];
  61. }
  62. }
  63. struct PositionHasher
  64. {
  65. const float* vertex_positions;
  66. size_t vertex_stride_float;
  67. size_t hash(unsigned int index) const
  68. {
  69. // MurmurHash2
  70. const unsigned int m = 0x5bd1e995;
  71. const int r = 24;
  72. unsigned int h = 0;
  73. const unsigned int* key = reinterpret_cast<const unsigned int*>(vertex_positions + index * vertex_stride_float);
  74. for (size_t i = 0; i < 3; ++i)
  75. {
  76. unsigned int k = key[i];
  77. k *= m;
  78. k ^= k >> r;
  79. k *= m;
  80. h *= m;
  81. h ^= k;
  82. }
  83. return h;
  84. }
  85. bool equal(unsigned int lhs, unsigned int rhs) const
  86. {
  87. return memcmp(vertex_positions + lhs * vertex_stride_float, vertex_positions + rhs * vertex_stride_float, sizeof(float) * 3) == 0;
  88. }
  89. };
  90. static size_t hashBuckets2(size_t count)
  91. {
  92. size_t buckets = 1;
  93. while (buckets < count)
  94. buckets *= 2;
  95. return buckets;
  96. }
  97. template <typename T, typename Hash>
  98. static T* hashLookup2(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty)
  99. {
  100. assert(buckets > 0);
  101. assert((buckets & (buckets - 1)) == 0);
  102. size_t hashmod = buckets - 1;
  103. size_t bucket = hash.hash(key) & hashmod;
  104. for (size_t probe = 0; probe <= hashmod; ++probe)
  105. {
  106. T& item = table[bucket];
  107. if (item == empty)
  108. return &item;
  109. if (hash.equal(item, key))
  110. return &item;
  111. // hash collision, quadratic probing
  112. bucket = (bucket + probe + 1) & hashmod;
  113. }
  114. assert(false && "Hash table is full"); // unreachable
  115. return 0;
  116. }
  117. static void buildPositionRemap(unsigned int* remap, unsigned int* wedge, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, meshopt_Allocator& allocator)
  118. {
  119. PositionHasher hasher = {vertex_positions_data, vertex_positions_stride / sizeof(float)};
  120. size_t table_size = hashBuckets2(vertex_count);
  121. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  122. memset(table, -1, table_size * sizeof(unsigned int));
  123. // build forward remap: for each vertex, which other (canonical) vertex does it map to?
  124. // we use position equivalence for this, and remap vertices to other existing vertices
  125. for (size_t i = 0; i < vertex_count; ++i)
  126. {
  127. unsigned int index = unsigned(i);
  128. unsigned int* entry = hashLookup2(table, table_size, hasher, index, ~0u);
  129. if (*entry == ~0u)
  130. *entry = index;
  131. remap[index] = *entry;
  132. }
  133. // build wedge table: for each vertex, which other vertex is the next wedge that also maps to the same vertex?
  134. // entries in table form a (cyclic) wedge loop per vertex; for manifold vertices, wedge[i] == remap[i] == i
  135. for (size_t i = 0; i < vertex_count; ++i)
  136. wedge[i] = unsigned(i);
  137. for (size_t i = 0; i < vertex_count; ++i)
  138. if (remap[i] != i)
  139. {
  140. unsigned int r = remap[i];
  141. wedge[i] = wedge[r];
  142. wedge[r] = unsigned(i);
  143. }
  144. }
  145. enum VertexKind
  146. {
  147. Kind_Manifold, // not on an attribute seam, not on any boundary
  148. Kind_Border, // not on an attribute seam, has exactly two open edges
  149. Kind_Seam, // on an attribute seam with exactly two attribute seam edges
  150. Kind_Complex, // none of the above; these vertices can move as long as all wedges move to the target vertex
  151. Kind_Locked, // none of the above; these vertices can't move
  152. Kind_Count
  153. };
  154. // manifold vertices can collapse onto anything
  155. // border/seam vertices can only be collapsed onto border/seam respectively
  156. // complex vertices can collapse onto complex/locked
  157. // a rule of thumb is that collapsing kind A into kind B preserves the kind B in the target vertex
  158. // for example, while we could collapse Complex into Manifold, this would mean the target vertex isn't Manifold anymore
  159. const unsigned char kCanCollapse[Kind_Count][Kind_Count] = {
  160. {1, 1, 1, 1, 1},
  161. {0, 1, 0, 0, 0},
  162. {0, 0, 1, 0, 0},
  163. {0, 0, 0, 1, 1},
  164. {0, 0, 0, 0, 0},
  165. };
  166. // if a vertex is manifold or seam, adjoining edges are guaranteed to have an opposite edge
  167. // note that for seam edges, the opposite edge isn't present in the attribute-based topology
  168. // but is present if you consider a position-only mesh variant
  169. const unsigned char kHasOpposite[Kind_Count][Kind_Count] = {
  170. {1, 1, 1, 0, 1},
  171. {1, 0, 1, 0, 0},
  172. {1, 1, 1, 0, 1},
  173. {0, 0, 0, 0, 0},
  174. {1, 0, 1, 0, 0},
  175. };
  176. static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b)
  177. {
  178. unsigned int count = adjacency.counts[a];
  179. const unsigned int* data = adjacency.data + adjacency.offsets[a];
  180. for (size_t i = 0; i < count; ++i)
  181. if (data[i] == b)
  182. return true;
  183. return false;
  184. }
  185. static unsigned int findWedgeEdge(const EdgeAdjacency& adjacency, const unsigned int* wedge, unsigned int a, unsigned int b)
  186. {
  187. unsigned int v = a;
  188. do
  189. {
  190. if (hasEdge(adjacency, v, b))
  191. return v;
  192. v = wedge[v];
  193. } while (v != a);
  194. return ~0u;
  195. }
  196. static size_t countOpenEdges(const EdgeAdjacency& adjacency, unsigned int vertex, unsigned int* last = 0)
  197. {
  198. size_t result = 0;
  199. unsigned int count = adjacency.counts[vertex];
  200. const unsigned int* data = adjacency.data + adjacency.offsets[vertex];
  201. for (size_t i = 0; i < count; ++i)
  202. if (!hasEdge(adjacency, data[i], vertex))
  203. {
  204. result++;
  205. if (last)
  206. *last = data[i];
  207. }
  208. return result;
  209. }
  210. static void classifyVertices(unsigned char* result, unsigned int* loop, size_t vertex_count, const EdgeAdjacency& adjacency, const unsigned int* remap, const unsigned int* wedge)
  211. {
  212. for (size_t i = 0; i < vertex_count; ++i)
  213. loop[i] = ~0u;
  214. #if TRACE
  215. size_t lockedstats[4] = {};
  216. #define TRACELOCKED(i) lockedstats[i]++;
  217. #else
  218. #define TRACELOCKED(i) (void)0
  219. #endif
  220. for (size_t i = 0; i < vertex_count; ++i)
  221. {
  222. if (remap[i] == i)
  223. {
  224. if (wedge[i] == i)
  225. {
  226. // no attribute seam, need to check if it's manifold
  227. unsigned int v = 0;
  228. size_t edges = countOpenEdges(adjacency, unsigned(i), &v);
  229. // note: we classify any vertices with no open edges as manifold
  230. // this is technically incorrect - if 4 triangles share an edge, we'll classify vertices as manifold
  231. // it's unclear if this is a problem in practice
  232. // also note that we classify vertices as border if they have *one* open edge, not two
  233. // this is because we only have half-edges - so a border vertex would have one incoming and one outgoing edge
  234. if (edges == 0)
  235. {
  236. result[i] = Kind_Manifold;
  237. }
  238. else if (edges == 1)
  239. {
  240. result[i] = Kind_Border;
  241. loop[i] = v;
  242. }
  243. else
  244. {
  245. result[i] = Kind_Locked;
  246. TRACELOCKED(0);
  247. }
  248. }
  249. else if (wedge[wedge[i]] == i)
  250. {
  251. // attribute seam; need to distinguish between Seam and Locked
  252. unsigned int a = 0;
  253. size_t a_count = countOpenEdges(adjacency, unsigned(i), &a);
  254. unsigned int b = 0;
  255. size_t b_count = countOpenEdges(adjacency, wedge[i], &b);
  256. // seam should have one open half-edge for each vertex, and the edges need to "connect" - point to the same vertex post-remap
  257. if (a_count == 1 && b_count == 1)
  258. {
  259. unsigned int ao = findWedgeEdge(adjacency, wedge, a, wedge[i]);
  260. unsigned int bo = findWedgeEdge(adjacency, wedge, b, unsigned(i));
  261. if (ao != ~0u && bo != ~0u)
  262. {
  263. result[i] = Kind_Seam;
  264. loop[i] = a;
  265. loop[wedge[i]] = b;
  266. }
  267. else
  268. {
  269. result[i] = Kind_Locked;
  270. TRACELOCKED(1);
  271. }
  272. }
  273. else
  274. {
  275. result[i] = Kind_Locked;
  276. TRACELOCKED(2);
  277. }
  278. }
  279. else
  280. {
  281. // more than one vertex maps to this one; we don't have classification available
  282. result[i] = Kind_Locked;
  283. TRACELOCKED(3);
  284. }
  285. }
  286. else
  287. {
  288. assert(remap[i] < i);
  289. result[i] = result[remap[i]];
  290. }
  291. }
  292. #if TRACE
  293. printf("locked: many open edges %d, disconnected seam %d, many seam edges %d, many wedges %d\n",
  294. int(lockedstats[0]), int(lockedstats[1]), int(lockedstats[2]), int(lockedstats[3]));
  295. #endif
  296. }
  297. struct Vector3
  298. {
  299. float x, y, z;
  300. };
  301. static void rescalePositions(Vector3* result, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride)
  302. {
  303. size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
  304. float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};
  305. float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
  306. for (size_t i = 0; i < vertex_count; ++i)
  307. {
  308. const float* v = vertex_positions_data + i * vertex_stride_float;
  309. result[i].x = v[0];
  310. result[i].y = v[1];
  311. result[i].z = v[2];
  312. for (int j = 0; j < 3; ++j)
  313. {
  314. float vj = v[j];
  315. minv[j] = minv[j] > vj ? vj : minv[j];
  316. maxv[j] = maxv[j] < vj ? vj : maxv[j];
  317. }
  318. }
  319. float extent = 0.f;
  320. extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]);
  321. extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]);
  322. extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]);
  323. float scale = extent == 0 ? 0.f : 1.f / extent;
  324. for (size_t i = 0; i < vertex_count; ++i)
  325. {
  326. result[i].x = (result[i].x - minv[0]) * scale;
  327. result[i].y = (result[i].y - minv[1]) * scale;
  328. result[i].z = (result[i].z - minv[2]) * scale;
  329. }
  330. }
  331. struct Quadric
  332. {
  333. float a00, a11, a22;
  334. float a10, a20, a21;
  335. float b0, b1, b2, c;
  336. float w;
  337. };
  338. struct Collapse
  339. {
  340. unsigned int v0;
  341. unsigned int v1;
  342. union {
  343. unsigned int bidi;
  344. float error;
  345. unsigned int errorui;
  346. };
  347. };
  348. static float normalize(Vector3& v)
  349. {
  350. float length = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
  351. if (length > 0)
  352. {
  353. v.x /= length;
  354. v.y /= length;
  355. v.z /= length;
  356. }
  357. return length;
  358. }
  359. static void quadricAdd(Quadric& Q, const Quadric& R)
  360. {
  361. Q.a00 += R.a00;
  362. Q.a11 += R.a11;
  363. Q.a22 += R.a22;
  364. Q.a10 += R.a10;
  365. Q.a20 += R.a20;
  366. Q.a21 += R.a21;
  367. Q.b0 += R.b0;
  368. Q.b1 += R.b1;
  369. Q.b2 += R.b2;
  370. Q.c += R.c;
  371. Q.w += R.w;
  372. }
  373. static float quadricError(const Quadric& Q, const Vector3& v)
  374. {
  375. float rx = Q.b0;
  376. float ry = Q.b1;
  377. float rz = Q.b2;
  378. rx += Q.a10 * v.y;
  379. ry += Q.a21 * v.z;
  380. rz += Q.a20 * v.x;
  381. rx *= 2;
  382. ry *= 2;
  383. rz *= 2;
  384. rx += Q.a00 * v.x;
  385. ry += Q.a11 * v.y;
  386. rz += Q.a22 * v.z;
  387. float r = Q.c;
  388. r += rx * v.x;
  389. r += ry * v.y;
  390. r += rz * v.z;
  391. float s = Q.w == 0.f ? 0.f : 1.f / Q.w;
  392. return fabsf(r) * s;
  393. }
  394. static void quadricFromPlane(Quadric& Q, float a, float b, float c, float d, float w)
  395. {
  396. float aw = a * w;
  397. float bw = b * w;
  398. float cw = c * w;
  399. float dw = d * w;
  400. Q.a00 = a * aw;
  401. Q.a11 = b * bw;
  402. Q.a22 = c * cw;
  403. Q.a10 = a * bw;
  404. Q.a20 = a * cw;
  405. Q.a21 = b * cw;
  406. Q.b0 = a * dw;
  407. Q.b1 = b * dw;
  408. Q.b2 = c * dw;
  409. Q.c = d * dw;
  410. Q.w = w;
  411. }
  412. static void quadricFromTriangle(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)
  413. {
  414. Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};
  415. Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};
  416. // normal = cross(p1 - p0, p2 - p0)
  417. Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};
  418. float area = normalize(normal);
  419. float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;
  420. // we use sqrtf(area) so that the error is scaled linearly; this tends to improve silhouettes
  421. quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, sqrtf(area) * weight);
  422. }
  423. static void quadricFromTriangleEdge(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)
  424. {
  425. Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};
  426. float length = normalize(p10);
  427. // p20p = length of projection of p2-p0 onto normalize(p1 - p0)
  428. Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};
  429. float p20p = p20.x * p10.x + p20.y * p10.y + p20.z * p10.z;
  430. // normal = altitude of triangle from point p2 onto edge p1-p0
  431. Vector3 normal = {p20.x - p10.x * p20p, p20.y - p10.y * p20p, p20.z - p10.z * p20p};
  432. normalize(normal);
  433. float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;
  434. // note: the weight is scaled linearly with edge length; this has to match the triangle weight
  435. quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, length * weight);
  436. }
  437. static void fillFaceQuadrics(Quadric* vertex_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap)
  438. {
  439. for (size_t i = 0; i < index_count; i += 3)
  440. {
  441. unsigned int i0 = indices[i + 0];
  442. unsigned int i1 = indices[i + 1];
  443. unsigned int i2 = indices[i + 2];
  444. Quadric Q;
  445. quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], 1.f);
  446. quadricAdd(vertex_quadrics[remap[i0]], Q);
  447. quadricAdd(vertex_quadrics[remap[i1]], Q);
  448. quadricAdd(vertex_quadrics[remap[i2]], Q);
  449. }
  450. }
  451. static void fillEdgeQuadrics(Quadric* vertex_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop)
  452. {
  453. for (size_t i = 0; i < index_count; i += 3)
  454. {
  455. static const int next[3] = {1, 2, 0};
  456. for (int e = 0; e < 3; ++e)
  457. {
  458. unsigned int i0 = indices[i + e];
  459. unsigned int i1 = indices[i + next[e]];
  460. unsigned char k0 = vertex_kind[i0];
  461. unsigned char k1 = vertex_kind[i1];
  462. // check that i0 and i1 are border/seam and are on the same edge loop
  463. // loop[] tracks half edges so we only need to check i0->i1
  464. if (k0 != k1 || (k0 != Kind_Border && k0 != Kind_Seam) || loop[i0] != i1)
  465. continue;
  466. unsigned int i2 = indices[i + next[next[e]]];
  467. // we try hard to maintain border edge geometry; seam edges can move more freely
  468. // due to topological restrictions on collapses, seam quadrics slightly improves collapse structure but aren't critical
  469. const float kEdgeWeightSeam = 1.f;
  470. const float kEdgeWeightBorder = 10.f;
  471. float edgeWeight = (k0 == Kind_Seam) ? kEdgeWeightSeam : kEdgeWeightBorder;
  472. Quadric Q;
  473. quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight);
  474. quadricAdd(vertex_quadrics[remap[i0]], Q);
  475. quadricAdd(vertex_quadrics[remap[i1]], Q);
  476. }
  477. }
  478. }
  479. static size_t pickEdgeCollapses(Collapse* collapses, const unsigned int* indices, size_t index_count, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop)
  480. {
  481. size_t collapse_count = 0;
  482. for (size_t i = 0; i < index_count; i += 3)
  483. {
  484. static const int next[3] = {1, 2, 0};
  485. for (int e = 0; e < 3; ++e)
  486. {
  487. unsigned int i0 = indices[i + e];
  488. unsigned int i1 = indices[i + next[e]];
  489. // this can happen either when input has a zero-length edge, or when we perform collapses for complex
  490. // topology w/seams and collapse a manifold vertex that connects to both wedges onto one of them
  491. // we leave edges like this alone since they may be important for preserving mesh integrity
  492. if (remap[i0] == remap[i1])
  493. continue;
  494. unsigned char k0 = vertex_kind[i0];
  495. unsigned char k1 = vertex_kind[i1];
  496. // the edge has to be collapsible in at least one direction
  497. if (!(kCanCollapse[k0][k1] | kCanCollapse[k1][k0]))
  498. continue;
  499. // manifold and seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges
  500. if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])
  501. continue;
  502. // two vertices are on a border or a seam, but there's no direct edge between them
  503. // this indicates that they belong to two different edge loops and we should not collapse this edge
  504. // loop[] tracks half edges so we only need to check i0->i1
  505. if (k0 == k1 && (k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)
  506. continue;
  507. // edge can be collapsed in either direction - we will pick the one with minimum error
  508. // note: we evaluate error later during collapse ranking, here we just tag the edge as bidirectional
  509. if (kCanCollapse[k0][k1] & kCanCollapse[k1][k0])
  510. {
  511. Collapse c = {i0, i1, {/* bidi= */ 1}};
  512. collapses[collapse_count++] = c;
  513. }
  514. else
  515. {
  516. // edge can only be collapsed in one direction
  517. unsigned int e0 = kCanCollapse[k0][k1] ? i0 : i1;
  518. unsigned int e1 = kCanCollapse[k0][k1] ? i1 : i0;
  519. Collapse c = {e0, e1, {/* bidi= */ 0}};
  520. collapses[collapse_count++] = c;
  521. }
  522. }
  523. }
  524. return collapse_count;
  525. }
  526. static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const Quadric* vertex_quadrics, const unsigned int* remap)
  527. {
  528. for (size_t i = 0; i < collapse_count; ++i)
  529. {
  530. Collapse& c = collapses[i];
  531. unsigned int i0 = c.v0;
  532. unsigned int i1 = c.v1;
  533. // most edges are bidirectional which means we need to evaluate errors for two collapses
  534. // to keep this code branchless we just use the same edge for unidirectional edges
  535. unsigned int j0 = c.bidi ? i1 : i0;
  536. unsigned int j1 = c.bidi ? i0 : i1;
  537. const Quadric& qi = vertex_quadrics[remap[i0]];
  538. const Quadric& qj = vertex_quadrics[remap[j0]];
  539. float ei = quadricError(qi, vertex_positions[i1]);
  540. float ej = quadricError(qj, vertex_positions[j1]);
  541. // pick edge direction with minimal error
  542. c.v0 = ei <= ej ? i0 : j0;
  543. c.v1 = ei <= ej ? i1 : j1;
  544. c.error = ei <= ej ? ei : ej;
  545. }
  546. }
  547. #if TRACE > 1
  548. static void dumpEdgeCollapses(const Collapse* collapses, size_t collapse_count, const unsigned char* vertex_kind)
  549. {
  550. size_t ckinds[Kind_Count][Kind_Count] = {};
  551. float cerrors[Kind_Count][Kind_Count] = {};
  552. for (int k0 = 0; k0 < Kind_Count; ++k0)
  553. for (int k1 = 0; k1 < Kind_Count; ++k1)
  554. cerrors[k0][k1] = FLT_MAX;
  555. for (size_t i = 0; i < collapse_count; ++i)
  556. {
  557. unsigned int i0 = collapses[i].v0;
  558. unsigned int i1 = collapses[i].v1;
  559. unsigned char k0 = vertex_kind[i0];
  560. unsigned char k1 = vertex_kind[i1];
  561. ckinds[k0][k1]++;
  562. cerrors[k0][k1] = (collapses[i].error < cerrors[k0][k1]) ? collapses[i].error : cerrors[k0][k1];
  563. }
  564. for (int k0 = 0; k0 < Kind_Count; ++k0)
  565. for (int k1 = 0; k1 < Kind_Count; ++k1)
  566. if (ckinds[k0][k1])
  567. printf("collapses %d -> %d: %d, min error %e\n", k0, k1, int(ckinds[k0][k1]), cerrors[k0][k1]);
  568. }
  569. static void dumpLockedCollapses(const unsigned int* indices, size_t index_count, const unsigned char* vertex_kind)
  570. {
  571. size_t locked_collapses[Kind_Count][Kind_Count] = {};
  572. for (size_t i = 0; i < index_count; i += 3)
  573. {
  574. static const int next[3] = {1, 2, 0};
  575. for (int e = 0; e < 3; ++e)
  576. {
  577. unsigned int i0 = indices[i + e];
  578. unsigned int i1 = indices[i + next[e]];
  579. unsigned char k0 = vertex_kind[i0];
  580. unsigned char k1 = vertex_kind[i1];
  581. locked_collapses[k0][k1] += !kCanCollapse[k0][k1] && !kCanCollapse[k1][k0];
  582. }
  583. }
  584. for (int k0 = 0; k0 < Kind_Count; ++k0)
  585. for (int k1 = 0; k1 < Kind_Count; ++k1)
  586. if (locked_collapses[k0][k1])
  587. printf("locked collapses %d -> %d: %d\n", k0, k1, int(locked_collapses[k0][k1]));
  588. }
  589. #endif
  590. static void sortEdgeCollapses(unsigned int* sort_order, const Collapse* collapses, size_t collapse_count)
  591. {
  592. const int sort_bits = 11;
  593. // fill histogram for counting sort
  594. unsigned int histogram[1 << sort_bits];
  595. memset(histogram, 0, sizeof(histogram));
  596. for (size_t i = 0; i < collapse_count; ++i)
  597. {
  598. // skip sign bit since error is non-negative
  599. unsigned int key = (collapses[i].errorui << 1) >> (32 - sort_bits);
  600. histogram[key]++;
  601. }
  602. // compute offsets based on histogram data
  603. size_t histogram_sum = 0;
  604. for (size_t i = 0; i < 1 << sort_bits; ++i)
  605. {
  606. size_t count = histogram[i];
  607. histogram[i] = unsigned(histogram_sum);
  608. histogram_sum += count;
  609. }
  610. assert(histogram_sum == collapse_count);
  611. // compute sort order based on offsets
  612. for (size_t i = 0; i < collapse_count; ++i)
  613. {
  614. // skip sign bit since error is non-negative
  615. unsigned int key = (collapses[i].errorui << 1) >> (32 - sort_bits);
  616. sort_order[histogram[key]++] = unsigned(i);
  617. }
  618. }
  619. static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char* collapse_locked, Quadric* vertex_quadrics, const Collapse* collapses, size_t collapse_count, const unsigned int* collapse_order, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, size_t triangle_collapse_goal, float error_goal, float error_limit)
  620. {
  621. size_t edge_collapses = 0;
  622. size_t triangle_collapses = 0;
  623. for (size_t i = 0; i < collapse_count; ++i)
  624. {
  625. const Collapse& c = collapses[collapse_order[i]];
  626. if (c.error > error_limit)
  627. break;
  628. if (c.error > error_goal && triangle_collapses > triangle_collapse_goal / 10)
  629. break;
  630. if (triangle_collapses >= triangle_collapse_goal)
  631. break;
  632. unsigned int i0 = c.v0;
  633. unsigned int i1 = c.v1;
  634. unsigned int r0 = remap[i0];
  635. unsigned int r1 = remap[i1];
  636. // we don't collapse vertices that had source or target vertex involved in a collapse
  637. // it's important to not move the vertices twice since it complicates the tracking/remapping logic
  638. // it's important to not move other vertices towards a moved vertex to preserve error since we don't re-rank collapses mid-pass
  639. if (collapse_locked[r0] | collapse_locked[r1])
  640. continue;
  641. assert(collapse_remap[r0] == r0);
  642. assert(collapse_remap[r1] == r1);
  643. quadricAdd(vertex_quadrics[r1], vertex_quadrics[r0]);
  644. if (vertex_kind[i0] == Kind_Complex)
  645. {
  646. unsigned int v = i0;
  647. do
  648. {
  649. collapse_remap[v] = r1;
  650. v = wedge[v];
  651. } while (v != i0);
  652. }
  653. else if (vertex_kind[i0] == Kind_Seam)
  654. {
  655. // remap v0 to v1 and seam pair of v0 to seam pair of v1
  656. unsigned int s0 = wedge[i0];
  657. unsigned int s1 = wedge[i1];
  658. assert(s0 != i0 && s1 != i1);
  659. assert(wedge[s0] == i0 && wedge[s1] == i1);
  660. collapse_remap[i0] = i1;
  661. collapse_remap[s0] = s1;
  662. }
  663. else
  664. {
  665. assert(wedge[i0] == i0);
  666. collapse_remap[i0] = i1;
  667. }
  668. collapse_locked[r0] = 1;
  669. collapse_locked[r1] = 1;
  670. // border edges collapse 1 triangle, other edges collapse 2 or more
  671. triangle_collapses += (vertex_kind[i0] == Kind_Border) ? 1 : 2;
  672. edge_collapses++;
  673. }
  674. return edge_collapses;
  675. }
  676. static size_t remapIndexBuffer(unsigned int* indices, size_t index_count, const unsigned int* collapse_remap)
  677. {
  678. size_t write = 0;
  679. for (size_t i = 0; i < index_count; i += 3)
  680. {
  681. unsigned int v0 = collapse_remap[indices[i + 0]];
  682. unsigned int v1 = collapse_remap[indices[i + 1]];
  683. unsigned int v2 = collapse_remap[indices[i + 2]];
  684. // we never move the vertex twice during a single pass
  685. assert(collapse_remap[v0] == v0);
  686. assert(collapse_remap[v1] == v1);
  687. assert(collapse_remap[v2] == v2);
  688. if (v0 != v1 && v0 != v2 && v1 != v2)
  689. {
  690. indices[write + 0] = v0;
  691. indices[write + 1] = v1;
  692. indices[write + 2] = v2;
  693. write += 3;
  694. }
  695. }
  696. return write;
  697. }
  698. static void remapEdgeLoops(unsigned int* loop, size_t vertex_count, const unsigned int* collapse_remap)
  699. {
  700. for (size_t i = 0; i < vertex_count; ++i)
  701. {
  702. if (loop[i] != ~0u)
  703. {
  704. unsigned int l = loop[i];
  705. unsigned int r = collapse_remap[l];
  706. // i == r is a special case when the seam edge is collapsed in a direction opposite to where loop goes
  707. loop[i] = (i == r) ? loop[l] : r;
  708. }
  709. }
  710. }
  711. struct CellHasher
  712. {
  713. const unsigned int* vertex_ids;
  714. size_t hash(unsigned int i) const
  715. {
  716. unsigned int h = vertex_ids[i];
  717. // MurmurHash2 finalizer
  718. h ^= h >> 13;
  719. h *= 0x5bd1e995;
  720. h ^= h >> 15;
  721. return h;
  722. }
  723. bool equal(unsigned int lhs, unsigned int rhs) const
  724. {
  725. return vertex_ids[lhs] == vertex_ids[rhs];
  726. }
  727. };
  728. struct TriangleHasher
  729. {
  730. unsigned int* indices;
  731. size_t hash(unsigned int i) const
  732. {
  733. const unsigned int* tri = indices + i * 3;
  734. // Optimized Spatial Hashing for Collision Detection of Deformable Objects
  735. return (tri[0] * 73856093) ^ (tri[1] * 19349663) ^ (tri[2] * 83492791);
  736. }
  737. bool equal(unsigned int lhs, unsigned int rhs) const
  738. {
  739. const unsigned int* lt = indices + lhs * 3;
  740. const unsigned int* rt = indices + rhs * 3;
  741. return lt[0] == rt[0] && lt[1] == rt[1] && lt[2] == rt[2];
  742. }
  743. };
  744. static void computeVertexIds(unsigned int* vertex_ids, const Vector3* vertex_positions, size_t vertex_count, int grid_size)
  745. {
  746. assert(grid_size >= 1 && grid_size <= 1024);
  747. float cell_scale = float(grid_size - 1);
  748. for (size_t i = 0; i < vertex_count; ++i)
  749. {
  750. const Vector3& v = vertex_positions[i];
  751. int xi = int(v.x * cell_scale + 0.5f);
  752. int yi = int(v.y * cell_scale + 0.5f);
  753. int zi = int(v.z * cell_scale + 0.5f);
  754. vertex_ids[i] = (xi << 20) | (yi << 10) | zi;
  755. }
  756. }
  757. static size_t countTriangles(const unsigned int* vertex_ids, const unsigned int* indices, size_t index_count)
  758. {
  759. size_t result = 0;
  760. for (size_t i = 0; i < index_count; i += 3)
  761. {
  762. unsigned int id0 = vertex_ids[indices[i + 0]];
  763. unsigned int id1 = vertex_ids[indices[i + 1]];
  764. unsigned int id2 = vertex_ids[indices[i + 2]];
  765. result += (id0 != id1) & (id0 != id2) & (id1 != id2);
  766. }
  767. return result;
  768. }
  769. static size_t fillVertexCells(unsigned int* table, size_t table_size, unsigned int* vertex_cells, const unsigned int* vertex_ids, size_t vertex_count)
  770. {
  771. CellHasher hasher = {vertex_ids};
  772. memset(table, -1, table_size * sizeof(unsigned int));
  773. size_t result = 0;
  774. for (size_t i = 0; i < vertex_count; ++i)
  775. {
  776. unsigned int* entry = hashLookup2(table, table_size, hasher, unsigned(i), ~0u);
  777. if (*entry == ~0u)
  778. {
  779. *entry = unsigned(i);
  780. vertex_cells[i] = unsigned(result++);
  781. }
  782. else
  783. {
  784. vertex_cells[i] = vertex_cells[*entry];
  785. }
  786. }
  787. return result;
  788. }
  789. static void fillCellQuadrics(Quadric* cell_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* vertex_cells)
  790. {
  791. for (size_t i = 0; i < index_count; i += 3)
  792. {
  793. unsigned int i0 = indices[i + 0];
  794. unsigned int i1 = indices[i + 1];
  795. unsigned int i2 = indices[i + 2];
  796. unsigned int c0 = vertex_cells[i0];
  797. unsigned int c1 = vertex_cells[i1];
  798. unsigned int c2 = vertex_cells[i2];
  799. bool single_cell = (c0 == c1) & (c0 == c2);
  800. Quadric Q;
  801. quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], single_cell ? 3.f : 1.f);
  802. if (single_cell)
  803. {
  804. quadricAdd(cell_quadrics[c0], Q);
  805. }
  806. else
  807. {
  808. quadricAdd(cell_quadrics[c0], Q);
  809. quadricAdd(cell_quadrics[c1], Q);
  810. quadricAdd(cell_quadrics[c2], Q);
  811. }
  812. }
  813. }
  814. static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Quadric* cell_quadrics, const Vector3* vertex_positions, size_t vertex_count)
  815. {
  816. memset(cell_remap, -1, cell_count * sizeof(unsigned int));
  817. for (size_t i = 0; i < vertex_count; ++i)
  818. {
  819. unsigned int cell = vertex_cells[i];
  820. float error = quadricError(cell_quadrics[cell], vertex_positions[i]);
  821. if (cell_remap[cell] == ~0u || cell_errors[cell] > error)
  822. {
  823. cell_remap[cell] = unsigned(i);
  824. cell_errors[cell] = error;
  825. }
  826. }
  827. }
  828. static size_t filterTriangles(unsigned int* destination, unsigned int* tritable, size_t tritable_size, const unsigned int* indices, size_t index_count, const unsigned int* vertex_cells, const unsigned int* cell_remap)
  829. {
  830. TriangleHasher hasher = {destination};
  831. memset(tritable, -1, tritable_size * sizeof(unsigned int));
  832. size_t result = 0;
  833. for (size_t i = 0; i < index_count; i += 3)
  834. {
  835. unsigned int c0 = vertex_cells[indices[i + 0]];
  836. unsigned int c1 = vertex_cells[indices[i + 1]];
  837. unsigned int c2 = vertex_cells[indices[i + 2]];
  838. if (c0 != c1 && c0 != c2 && c1 != c2)
  839. {
  840. unsigned int a = cell_remap[c0];
  841. unsigned int b = cell_remap[c1];
  842. unsigned int c = cell_remap[c2];
  843. if (b < a && b < c)
  844. {
  845. unsigned int t = a;
  846. a = b, b = c, c = t;
  847. }
  848. else if (c < a && c < b)
  849. {
  850. unsigned int t = c;
  851. c = b, b = a, a = t;
  852. }
  853. destination[result * 3 + 0] = a;
  854. destination[result * 3 + 1] = b;
  855. destination[result * 3 + 2] = c;
  856. unsigned int* entry = hashLookup2(tritable, tritable_size, hasher, unsigned(result), ~0u);
  857. if (*entry == ~0u)
  858. *entry = unsigned(result++);
  859. }
  860. }
  861. return result * 3;
  862. }
  863. } // namespace meshopt
  864. #if TRACE
  865. unsigned char* meshopt_simplifyDebugKind = 0;
  866. unsigned int* meshopt_simplifyDebugLoop = 0;
  867. #endif
  868. size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error)
  869. {
  870. using namespace meshopt;
  871. assert(index_count % 3 == 0);
  872. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  873. assert(vertex_positions_stride % sizeof(float) == 0);
  874. assert(target_index_count <= index_count);
  875. meshopt_Allocator allocator;
  876. unsigned int* result = destination;
  877. // build adjacency information
  878. EdgeAdjacency adjacency = {};
  879. buildEdgeAdjacency(adjacency, indices, index_count, vertex_count, allocator);
  880. // build position remap that maps each vertex to the one with identical position
  881. unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);
  882. unsigned int* wedge = allocator.allocate<unsigned int>(vertex_count);
  883. buildPositionRemap(remap, wedge, vertex_positions_data, vertex_count, vertex_positions_stride, allocator);
  884. // classify vertices; vertex kind determines collapse rules, see kCanCollapse
  885. unsigned char* vertex_kind = allocator.allocate<unsigned char>(vertex_count);
  886. unsigned int* loop = allocator.allocate<unsigned int>(vertex_count);
  887. classifyVertices(vertex_kind, loop, vertex_count, adjacency, remap, wedge);
  888. #if TRACE
  889. size_t unique_positions = 0;
  890. for (size_t i = 0; i < vertex_count; ++i)
  891. unique_positions += remap[i] == i;
  892. printf("position remap: %d vertices => %d positions\n", int(vertex_count), int(unique_positions));
  893. size_t kinds[Kind_Count] = {};
  894. for (size_t i = 0; i < vertex_count; ++i)
  895. kinds[vertex_kind[i]] += remap[i] == i;
  896. printf("kinds: manifold %d, border %d, seam %d, complex %d, locked %d\n",
  897. int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Locked]));
  898. #endif
  899. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  900. rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);
  901. Quadric* vertex_quadrics = allocator.allocate<Quadric>(vertex_count);
  902. memset(vertex_quadrics, 0, vertex_count * sizeof(Quadric));
  903. fillFaceQuadrics(vertex_quadrics, indices, index_count, vertex_positions, remap);
  904. fillEdgeQuadrics(vertex_quadrics, indices, index_count, vertex_positions, remap, vertex_kind, loop);
  905. if (result != indices)
  906. memcpy(result, indices, index_count * sizeof(unsigned int));
  907. #if TRACE
  908. size_t pass_count = 0;
  909. float worst_error = 0;
  910. #endif
  911. Collapse* edge_collapses = allocator.allocate<Collapse>(index_count);
  912. unsigned int* collapse_order = allocator.allocate<unsigned int>(index_count);
  913. unsigned int* collapse_remap = allocator.allocate<unsigned int>(vertex_count);
  914. unsigned char* collapse_locked = allocator.allocate<unsigned char>(vertex_count);
  915. size_t result_count = index_count;
  916. // target_error input is linear; we need to adjust it to match quadricError units
  917. float error_limit = target_error * target_error;
  918. while (result_count > target_index_count)
  919. {
  920. size_t edge_collapse_count = pickEdgeCollapses(edge_collapses, result, result_count, remap, vertex_kind, loop);
  921. // no edges can be collapsed any more due to topology restrictions
  922. if (edge_collapse_count == 0)
  923. break;
  924. rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_quadrics, remap);
  925. #if TRACE > 1
  926. dumpEdgeCollapses(edge_collapses, edge_collapse_count, vertex_kind);
  927. #endif
  928. sortEdgeCollapses(collapse_order, edge_collapses, edge_collapse_count);
  929. // most collapses remove 2 triangles; use this to establish a bound on the pass in terms of error limit
  930. // note that edge_collapse_goal is an estimate; triangle_collapse_goal will be used to actually limit collapses
  931. size_t triangle_collapse_goal = (result_count - target_index_count) / 3;
  932. size_t edge_collapse_goal = triangle_collapse_goal / 2;
  933. // we limit the error in each pass based on the error of optimal last collapse; since many collapses will be locked
  934. // as they will share vertices with other successfull collapses, we need to increase the acceptable error by this factor
  935. const float kPassErrorBound = 1.5f;
  936. float error_goal = edge_collapse_goal < edge_collapse_count ? edge_collapses[collapse_order[edge_collapse_goal]].error * kPassErrorBound : FLT_MAX;
  937. for (size_t i = 0; i < vertex_count; ++i)
  938. collapse_remap[i] = unsigned(i);
  939. memset(collapse_locked, 0, vertex_count);
  940. size_t collapses = performEdgeCollapses(collapse_remap, collapse_locked, vertex_quadrics, edge_collapses, edge_collapse_count, collapse_order, remap, wedge, vertex_kind, triangle_collapse_goal, error_goal, error_limit);
  941. // no edges can be collapsed any more due to hitting the error limit or triangle collapse limit
  942. if (collapses == 0)
  943. break;
  944. remapEdgeLoops(loop, vertex_count, collapse_remap);
  945. size_t new_count = remapIndexBuffer(result, result_count, collapse_remap);
  946. assert(new_count < result_count);
  947. #if TRACE
  948. float pass_error = 0.f;
  949. for (size_t i = 0; i < edge_collapse_count; ++i)
  950. {
  951. Collapse& c = edge_collapses[collapse_order[i]];
  952. if (collapse_remap[c.v0] == c.v1)
  953. pass_error = c.error;
  954. }
  955. pass_count++;
  956. worst_error = (worst_error < pass_error) ? pass_error : worst_error;
  957. printf("pass %d: triangles: %d -> %d, collapses: %d/%d (goal: %d), error: %e (limit %e goal %e)\n", int(pass_count), int(result_count / 3), int(new_count / 3), int(collapses), int(edge_collapse_count), int(edge_collapse_goal), pass_error, error_limit, error_goal);
  958. #endif
  959. result_count = new_count;
  960. }
  961. #if TRACE
  962. printf("passes: %d, worst error: %e\n", int(pass_count), worst_error);
  963. #endif
  964. #if TRACE > 1
  965. dumpLockedCollapses(result, result_count, vertex_kind);
  966. #endif
  967. #if TRACE
  968. if (meshopt_simplifyDebugKind)
  969. memcpy(meshopt_simplifyDebugKind, vertex_kind, vertex_count);
  970. if (meshopt_simplifyDebugLoop)
  971. memcpy(meshopt_simplifyDebugLoop, loop, vertex_count * sizeof(unsigned int));
  972. #endif
  973. return result_count;
  974. }
  975. size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count)
  976. {
  977. using namespace meshopt;
  978. assert(index_count % 3 == 0);
  979. assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
  980. assert(vertex_positions_stride % sizeof(float) == 0);
  981. assert(target_index_count <= index_count);
  982. // we expect to get ~2 triangles/vertex in the output
  983. size_t target_cell_count = target_index_count / 6;
  984. if (target_cell_count == 0)
  985. return 0;
  986. meshopt_Allocator allocator;
  987. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  988. rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);
  989. // find the optimal grid size using guided binary search
  990. #if TRACE
  991. printf("source: %d vertices, %d triangles\n", int(vertex_count), int(index_count / 3));
  992. printf("target: %d cells, %d triangles\n", int(target_cell_count), int(target_index_count / 3));
  993. #endif
  994. unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);
  995. // invariant: # of triangles in min_grid <= target_count
  996. int min_grid = 0;
  997. int max_grid = 1025;
  998. size_t min_triangles = 0;
  999. size_t max_triangles = index_count / 3;
  1000. const int kInterpolationPasses = 5;
  1001. for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)
  1002. {
  1003. assert(min_triangles < target_index_count / 3);
  1004. assert(max_grid - min_grid > 1);
  1005. int grid_size = 0;
  1006. if (pass == 0)
  1007. {
  1008. // instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...
  1009. grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);
  1010. grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid) ? max_grid - 1 : grid_size;
  1011. }
  1012. else if (pass <= kInterpolationPasses)
  1013. {
  1014. float k = (float(target_index_count / 3) - float(min_triangles)) / (float(max_triangles) - float(min_triangles));
  1015. grid_size = int(float(min_grid) * (1 - k) + float(max_grid) * k + 0.5f);
  1016. grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid) ? max_grid - 1 : grid_size;
  1017. }
  1018. else
  1019. {
  1020. grid_size = (min_grid + max_grid) / 2;
  1021. assert(grid_size > min_grid && grid_size < max_grid);
  1022. }
  1023. computeVertexIds(vertex_ids, vertex_positions, vertex_count, grid_size);
  1024. size_t triangles = countTriangles(vertex_ids, indices, index_count);
  1025. #if TRACE
  1026. printf("pass %d (%s): grid size %d, triangles %d, %s\n",
  1027. pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses) ? "lerp" : "binary",
  1028. grid_size, int(triangles),
  1029. (triangles <= target_index_count / 3) ? "under" : "over");
  1030. #endif
  1031. if (triangles <= target_index_count / 3)
  1032. {
  1033. min_grid = grid_size;
  1034. min_triangles = triangles;
  1035. }
  1036. else
  1037. {
  1038. max_grid = grid_size;
  1039. max_triangles = triangles;
  1040. }
  1041. if (triangles == target_index_count / 3 || max_grid - min_grid <= 1)
  1042. break;
  1043. }
  1044. if (min_triangles == 0)
  1045. return 0;
  1046. // build vertex->cell association by mapping all vertices with the same quantized position to the same cell
  1047. size_t table_size = hashBuckets2(vertex_count);
  1048. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  1049. unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);
  1050. computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);
  1051. size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);
  1052. // build a quadric for each target cell
  1053. Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count);
  1054. memset(cell_quadrics, 0, cell_count * sizeof(Quadric));
  1055. fillCellQuadrics(cell_quadrics, indices, index_count, vertex_positions, vertex_cells);
  1056. // for each target cell, find the vertex with the minimal error
  1057. unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);
  1058. float* cell_errors = allocator.allocate<float>(cell_count);
  1059. fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count);
  1060. // collapse triangles!
  1061. // note that we need to filter out triangles that we've already output because we very frequently generate redundant triangles between cells :(
  1062. size_t tritable_size = hashBuckets2(min_triangles);
  1063. unsigned int* tritable = allocator.allocate<unsigned int>(tritable_size);
  1064. size_t write = filterTriangles(destination, tritable, tritable_size, indices, index_count, vertex_cells, cell_remap);
  1065. assert(write <= target_index_count);
  1066. #if TRACE
  1067. printf("result: %d cells, %d triangles (%d unfiltered)\n", int(cell_count), int(write / 3), int(min_triangles));
  1068. #endif
  1069. return write;
  1070. }