simplifier.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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. #if TRACE
  14. #define TRACESTATS(i) stats[i]++;
  15. #else
  16. #define TRACESTATS(i) (void)0
  17. #endif
  18. // This work is based on:
  19. // Michael Garland and Paul S. Heckbert. Surface simplification using quadric error metrics. 1997
  20. // Michael Garland. Quadric-based polygonal surface simplification. 1999
  21. // Peter Lindstrom. Out-of-Core Simplification of Large Polygonal Models. 2000
  22. // Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 2003
  23. // Peter Van Sandt, Yannis Chronis, Jignesh M. Patel. Efficiently Searching In-Memory Sorted Arrays: Revenge of the Interpolation Search? 2019
  24. namespace meshopt
  25. {
  26. struct EdgeAdjacency
  27. {
  28. struct Edge
  29. {
  30. unsigned int next;
  31. unsigned int prev;
  32. };
  33. unsigned int* counts;
  34. unsigned int* offsets;
  35. Edge* data;
  36. };
  37. static void prepareEdgeAdjacency(EdgeAdjacency& adjacency, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)
  38. {
  39. adjacency.counts = allocator.allocate<unsigned int>(vertex_count);
  40. adjacency.offsets = allocator.allocate<unsigned int>(vertex_count);
  41. adjacency.data = allocator.allocate<EdgeAdjacency::Edge>(index_count);
  42. }
  43. static void updateEdgeAdjacency(EdgeAdjacency& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, const unsigned int* remap)
  44. {
  45. size_t face_count = index_count / 3;
  46. // fill edge counts
  47. memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int));
  48. for (size_t i = 0; i < index_count; ++i)
  49. {
  50. unsigned int v = remap ? remap[indices[i]] : indices[i];
  51. assert(v < vertex_count);
  52. adjacency.counts[v]++;
  53. }
  54. // fill offset table
  55. unsigned int offset = 0;
  56. for (size_t i = 0; i < vertex_count; ++i)
  57. {
  58. adjacency.offsets[i] = offset;
  59. offset += adjacency.counts[i];
  60. }
  61. assert(offset == index_count);
  62. // fill edge data
  63. for (size_t i = 0; i < face_count; ++i)
  64. {
  65. unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];
  66. if (remap)
  67. {
  68. a = remap[a];
  69. b = remap[b];
  70. c = remap[c];
  71. }
  72. adjacency.data[adjacency.offsets[a]].next = b;
  73. adjacency.data[adjacency.offsets[a]].prev = c;
  74. adjacency.offsets[a]++;
  75. adjacency.data[adjacency.offsets[b]].next = c;
  76. adjacency.data[adjacency.offsets[b]].prev = a;
  77. adjacency.offsets[b]++;
  78. adjacency.data[adjacency.offsets[c]].next = a;
  79. adjacency.data[adjacency.offsets[c]].prev = b;
  80. adjacency.offsets[c]++;
  81. }
  82. // fix offsets that have been disturbed by the previous pass
  83. for (size_t i = 0; i < vertex_count; ++i)
  84. {
  85. assert(adjacency.offsets[i] >= adjacency.counts[i]);
  86. adjacency.offsets[i] -= adjacency.counts[i];
  87. }
  88. }
  89. struct PositionHasher
  90. {
  91. const float* vertex_positions;
  92. size_t vertex_stride_float;
  93. size_t hash(unsigned int index) const
  94. {
  95. const unsigned int* key = reinterpret_cast<const unsigned int*>(vertex_positions + index * vertex_stride_float);
  96. // scramble bits to make sure that integer coordinates have entropy in lower bits
  97. unsigned int x = key[0] ^ (key[0] >> 17);
  98. unsigned int y = key[1] ^ (key[1] >> 17);
  99. unsigned int z = key[2] ^ (key[2] >> 17);
  100. // Optimized Spatial Hashing for Collision Detection of Deformable Objects
  101. return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791);
  102. }
  103. bool equal(unsigned int lhs, unsigned int rhs) const
  104. {
  105. return memcmp(vertex_positions + lhs * vertex_stride_float, vertex_positions + rhs * vertex_stride_float, sizeof(float) * 3) == 0;
  106. }
  107. };
  108. static size_t hashBuckets2(size_t count)
  109. {
  110. size_t buckets = 1;
  111. while (buckets < count + count / 4)
  112. buckets *= 2;
  113. return buckets;
  114. }
  115. template <typename T, typename Hash>
  116. static T* hashLookup2(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty)
  117. {
  118. assert(buckets > 0);
  119. assert((buckets & (buckets - 1)) == 0);
  120. size_t hashmod = buckets - 1;
  121. size_t bucket = hash.hash(key) & hashmod;
  122. for (size_t probe = 0; probe <= hashmod; ++probe)
  123. {
  124. T& item = table[bucket];
  125. if (item == empty)
  126. return &item;
  127. if (hash.equal(item, key))
  128. return &item;
  129. // hash collision, quadratic probing
  130. bucket = (bucket + probe + 1) & hashmod;
  131. }
  132. assert(false && "Hash table is full"); // unreachable
  133. return 0;
  134. }
  135. 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)
  136. {
  137. PositionHasher hasher = {vertex_positions_data, vertex_positions_stride / sizeof(float)};
  138. size_t table_size = hashBuckets2(vertex_count);
  139. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  140. memset(table, -1, table_size * sizeof(unsigned int));
  141. // build forward remap: for each vertex, which other (canonical) vertex does it map to?
  142. // we use position equivalence for this, and remap vertices to other existing vertices
  143. for (size_t i = 0; i < vertex_count; ++i)
  144. {
  145. unsigned int index = unsigned(i);
  146. unsigned int* entry = hashLookup2(table, table_size, hasher, index, ~0u);
  147. if (*entry == ~0u)
  148. *entry = index;
  149. remap[index] = *entry;
  150. }
  151. // build wedge table: for each vertex, which other vertex is the next wedge that also maps to the same vertex?
  152. // entries in table form a (cyclic) wedge loop per vertex; for manifold vertices, wedge[i] == remap[i] == i
  153. for (size_t i = 0; i < vertex_count; ++i)
  154. wedge[i] = unsigned(i);
  155. for (size_t i = 0; i < vertex_count; ++i)
  156. if (remap[i] != i)
  157. {
  158. unsigned int r = remap[i];
  159. wedge[i] = wedge[r];
  160. wedge[r] = unsigned(i);
  161. }
  162. }
  163. enum VertexKind
  164. {
  165. Kind_Manifold, // not on an attribute seam, not on any boundary
  166. Kind_Border, // not on an attribute seam, has exactly two open edges
  167. Kind_Seam, // on an attribute seam with exactly two attribute seam edges
  168. Kind_Complex, // none of the above; these vertices can move as long as all wedges move to the target vertex
  169. Kind_Locked, // none of the above; these vertices can't move
  170. Kind_Count
  171. };
  172. // manifold vertices can collapse onto anything
  173. // border/seam vertices can only be collapsed onto border/seam respectively
  174. // complex vertices can collapse onto complex/locked
  175. // a rule of thumb is that collapsing kind A into kind B preserves the kind B in the target vertex
  176. // for example, while we could collapse Complex into Manifold, this would mean the target vertex isn't Manifold anymore
  177. const unsigned char kCanCollapse[Kind_Count][Kind_Count] = {
  178. {1, 1, 1, 1, 1},
  179. {0, 1, 0, 0, 0},
  180. {0, 0, 1, 0, 0},
  181. {0, 0, 0, 1, 1},
  182. {0, 0, 0, 0, 0},
  183. };
  184. // if a vertex is manifold or seam, adjoining edges are guaranteed to have an opposite edge
  185. // note that for seam edges, the opposite edge isn't present in the attribute-based topology
  186. // but is present if you consider a position-only mesh variant
  187. const unsigned char kHasOpposite[Kind_Count][Kind_Count] = {
  188. {1, 1, 1, 0, 1},
  189. {1, 0, 1, 0, 0},
  190. {1, 1, 1, 0, 1},
  191. {0, 0, 0, 0, 0},
  192. {1, 0, 1, 0, 0},
  193. };
  194. static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b)
  195. {
  196. unsigned int count = adjacency.counts[a];
  197. const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[a];
  198. for (size_t i = 0; i < count; ++i)
  199. if (edges[i].next == b)
  200. return true;
  201. return false;
  202. }
  203. static void classifyVertices(unsigned char* result, unsigned int* loop, unsigned int* loopback, size_t vertex_count, const EdgeAdjacency& adjacency, const unsigned int* remap, const unsigned int* wedge, unsigned int options)
  204. {
  205. memset(loop, -1, vertex_count * sizeof(unsigned int));
  206. memset(loopback, -1, vertex_count * sizeof(unsigned int));
  207. // incoming & outgoing open edges: ~0u if no open edges, i if there are more than 1
  208. // note that this is the same data as required in loop[] arrays; loop[] data is only valid for border/seam
  209. // but here it's okay to fill the data out for other types of vertices as well
  210. unsigned int* openinc = loopback;
  211. unsigned int* openout = loop;
  212. for (size_t i = 0; i < vertex_count; ++i)
  213. {
  214. unsigned int vertex = unsigned(i);
  215. unsigned int count = adjacency.counts[vertex];
  216. const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[vertex];
  217. for (size_t j = 0; j < count; ++j)
  218. {
  219. unsigned int target = edges[j].next;
  220. if (target == vertex)
  221. {
  222. // degenerate triangles have two distinct edges instead of three, and the self edge
  223. // is bi-directional by definition; this can break border/seam classification by "closing"
  224. // the open edge from another triangle and falsely marking the vertex as manifold
  225. // instead we mark the vertex as having >1 open edges which turns it into locked/complex
  226. openinc[vertex] = openout[vertex] = vertex;
  227. }
  228. else if (!hasEdge(adjacency, target, vertex))
  229. {
  230. openinc[target] = (openinc[target] == ~0u) ? vertex : target;
  231. openout[vertex] = (openout[vertex] == ~0u) ? target : vertex;
  232. }
  233. }
  234. }
  235. #if TRACE
  236. size_t stats[4] = {};
  237. #endif
  238. for (size_t i = 0; i < vertex_count; ++i)
  239. {
  240. if (remap[i] == i)
  241. {
  242. if (wedge[i] == i)
  243. {
  244. // no attribute seam, need to check if it's manifold
  245. unsigned int openi = openinc[i], openo = openout[i];
  246. // note: we classify any vertices with no open edges as manifold
  247. // this is technically incorrect - if 4 triangles share an edge, we'll classify vertices as manifold
  248. // it's unclear if this is a problem in practice
  249. if (openi == ~0u && openo == ~0u)
  250. {
  251. result[i] = Kind_Manifold;
  252. }
  253. else if (openi != i && openo != i)
  254. {
  255. result[i] = Kind_Border;
  256. }
  257. else
  258. {
  259. result[i] = Kind_Locked;
  260. TRACESTATS(0);
  261. }
  262. }
  263. else if (wedge[wedge[i]] == i)
  264. {
  265. // attribute seam; need to distinguish between Seam and Locked
  266. unsigned int w = wedge[i];
  267. unsigned int openiv = openinc[i], openov = openout[i];
  268. unsigned int openiw = openinc[w], openow = openout[w];
  269. // seam should have one open half-edge for each vertex, and the edges need to "connect" - point to the same vertex post-remap
  270. if (openiv != ~0u && openiv != i && openov != ~0u && openov != i &&
  271. openiw != ~0u && openiw != w && openow != ~0u && openow != w)
  272. {
  273. if (remap[openiv] == remap[openow] && remap[openov] == remap[openiw])
  274. {
  275. result[i] = Kind_Seam;
  276. }
  277. else
  278. {
  279. result[i] = Kind_Locked;
  280. TRACESTATS(1);
  281. }
  282. }
  283. else
  284. {
  285. result[i] = Kind_Locked;
  286. TRACESTATS(2);
  287. }
  288. }
  289. else
  290. {
  291. // more than one vertex maps to this one; we don't have classification available
  292. result[i] = Kind_Locked;
  293. TRACESTATS(3);
  294. }
  295. }
  296. else
  297. {
  298. assert(remap[i] < i);
  299. result[i] = result[remap[i]];
  300. }
  301. }
  302. if (options & meshopt_SimplifyLockBorder)
  303. for (size_t i = 0; i < vertex_count; ++i)
  304. if (result[i] == Kind_Border)
  305. result[i] = Kind_Locked;
  306. #if TRACE
  307. printf("locked: many open edges %d, disconnected seam %d, many seam edges %d, many wedges %d\n",
  308. int(stats[0]), int(stats[1]), int(stats[2]), int(stats[3]));
  309. #endif
  310. }
  311. struct Vector3
  312. {
  313. float x, y, z;
  314. };
  315. static float rescalePositions(Vector3* result, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride)
  316. {
  317. size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
  318. float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};
  319. float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
  320. for (size_t i = 0; i < vertex_count; ++i)
  321. {
  322. const float* v = vertex_positions_data + i * vertex_stride_float;
  323. if (result)
  324. {
  325. result[i].x = v[0];
  326. result[i].y = v[1];
  327. result[i].z = v[2];
  328. }
  329. for (int j = 0; j < 3; ++j)
  330. {
  331. float vj = v[j];
  332. minv[j] = minv[j] > vj ? vj : minv[j];
  333. maxv[j] = maxv[j] < vj ? vj : maxv[j];
  334. }
  335. }
  336. float extent = 0.f;
  337. extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]);
  338. extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]);
  339. extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]);
  340. if (result)
  341. {
  342. float scale = extent == 0 ? 0.f : 1.f / extent;
  343. for (size_t i = 0; i < vertex_count; ++i)
  344. {
  345. result[i].x = (result[i].x - minv[0]) * scale;
  346. result[i].y = (result[i].y - minv[1]) * scale;
  347. result[i].z = (result[i].z - minv[2]) * scale;
  348. }
  349. }
  350. return extent;
  351. }
  352. struct Quadric
  353. {
  354. float a00, a11, a22;
  355. float a10, a20, a21;
  356. float b0, b1, b2, c;
  357. float w;
  358. };
  359. struct Collapse
  360. {
  361. unsigned int v0;
  362. unsigned int v1;
  363. union
  364. {
  365. unsigned int bidi;
  366. float error;
  367. unsigned int errorui;
  368. };
  369. };
  370. static float normalize(Vector3& v)
  371. {
  372. float length = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
  373. if (length > 0)
  374. {
  375. v.x /= length;
  376. v.y /= length;
  377. v.z /= length;
  378. }
  379. return length;
  380. }
  381. static void quadricAdd(Quadric& Q, const Quadric& R)
  382. {
  383. Q.a00 += R.a00;
  384. Q.a11 += R.a11;
  385. Q.a22 += R.a22;
  386. Q.a10 += R.a10;
  387. Q.a20 += R.a20;
  388. Q.a21 += R.a21;
  389. Q.b0 += R.b0;
  390. Q.b1 += R.b1;
  391. Q.b2 += R.b2;
  392. Q.c += R.c;
  393. Q.w += R.w;
  394. }
  395. static float quadricError(const Quadric& Q, const Vector3& v)
  396. {
  397. float rx = Q.b0;
  398. float ry = Q.b1;
  399. float rz = Q.b2;
  400. rx += Q.a10 * v.y;
  401. ry += Q.a21 * v.z;
  402. rz += Q.a20 * v.x;
  403. rx *= 2;
  404. ry *= 2;
  405. rz *= 2;
  406. rx += Q.a00 * v.x;
  407. ry += Q.a11 * v.y;
  408. rz += Q.a22 * v.z;
  409. float r = Q.c;
  410. r += rx * v.x;
  411. r += ry * v.y;
  412. r += rz * v.z;
  413. float s = Q.w == 0.f ? 0.f : 1.f / Q.w;
  414. return fabsf(r) * s;
  415. }
  416. static void quadricFromPlane(Quadric& Q, float a, float b, float c, float d, float w)
  417. {
  418. float aw = a * w;
  419. float bw = b * w;
  420. float cw = c * w;
  421. float dw = d * w;
  422. Q.a00 = a * aw;
  423. Q.a11 = b * bw;
  424. Q.a22 = c * cw;
  425. Q.a10 = a * bw;
  426. Q.a20 = a * cw;
  427. Q.a21 = b * cw;
  428. Q.b0 = a * dw;
  429. Q.b1 = b * dw;
  430. Q.b2 = c * dw;
  431. Q.c = d * dw;
  432. Q.w = w;
  433. }
  434. static void quadricFromPoint(Quadric& Q, float x, float y, float z, float w)
  435. {
  436. // we need to encode (x - X) ^ 2 + (y - Y)^2 + (z - Z)^2 into the quadric
  437. Q.a00 = w;
  438. Q.a11 = w;
  439. Q.a22 = w;
  440. Q.a10 = 0.f;
  441. Q.a20 = 0.f;
  442. Q.a21 = 0.f;
  443. Q.b0 = -2.f * x * w;
  444. Q.b1 = -2.f * y * w;
  445. Q.b2 = -2.f * z * w;
  446. Q.c = (x * x + y * y + z * z) * w;
  447. Q.w = w;
  448. }
  449. static void quadricFromTriangle(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)
  450. {
  451. Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};
  452. Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};
  453. // normal = cross(p1 - p0, p2 - p0)
  454. 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};
  455. float area = normalize(normal);
  456. float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;
  457. // we use sqrtf(area) so that the error is scaled linearly; this tends to improve silhouettes
  458. quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, sqrtf(area) * weight);
  459. }
  460. static void quadricFromTriangleEdge(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)
  461. {
  462. Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};
  463. float length = normalize(p10);
  464. // p20p = length of projection of p2-p0 onto normalize(p1 - p0)
  465. Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};
  466. float p20p = p20.x * p10.x + p20.y * p10.y + p20.z * p10.z;
  467. // normal = altitude of triangle from point p2 onto edge p1-p0
  468. Vector3 normal = {p20.x - p10.x * p20p, p20.y - p10.y * p20p, p20.z - p10.z * p20p};
  469. normalize(normal);
  470. float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;
  471. // note: the weight is scaled linearly with edge length; this has to match the triangle weight
  472. quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, length * weight);
  473. }
  474. static void fillFaceQuadrics(Quadric* vertex_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap)
  475. {
  476. for (size_t i = 0; i < index_count; i += 3)
  477. {
  478. unsigned int i0 = indices[i + 0];
  479. unsigned int i1 = indices[i + 1];
  480. unsigned int i2 = indices[i + 2];
  481. Quadric Q;
  482. quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], 1.f);
  483. quadricAdd(vertex_quadrics[remap[i0]], Q);
  484. quadricAdd(vertex_quadrics[remap[i1]], Q);
  485. quadricAdd(vertex_quadrics[remap[i2]], Q);
  486. }
  487. }
  488. 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, const unsigned int* loopback)
  489. {
  490. for (size_t i = 0; i < index_count; i += 3)
  491. {
  492. static const int next[3] = {1, 2, 0};
  493. for (int e = 0; e < 3; ++e)
  494. {
  495. unsigned int i0 = indices[i + e];
  496. unsigned int i1 = indices[i + next[e]];
  497. unsigned char k0 = vertex_kind[i0];
  498. unsigned char k1 = vertex_kind[i1];
  499. // check that either i0 or i1 are border/seam and are on the same edge loop
  500. // note that we need to add the error even for edged that connect e.g. border & locked
  501. // if we don't do that, the adjacent border->border edge won't have correct errors for corners
  502. if (k0 != Kind_Border && k0 != Kind_Seam && k1 != Kind_Border && k1 != Kind_Seam)
  503. continue;
  504. if ((k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)
  505. continue;
  506. if ((k1 == Kind_Border || k1 == Kind_Seam) && loopback[i1] != i0)
  507. continue;
  508. // seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges
  509. if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])
  510. continue;
  511. unsigned int i2 = indices[i + next[next[e]]];
  512. // we try hard to maintain border edge geometry; seam edges can move more freely
  513. // due to topological restrictions on collapses, seam quadrics slightly improves collapse structure but aren't critical
  514. const float kEdgeWeightSeam = 1.f;
  515. const float kEdgeWeightBorder = 10.f;
  516. float edgeWeight = (k0 == Kind_Border || k1 == Kind_Border) ? kEdgeWeightBorder : kEdgeWeightSeam;
  517. Quadric Q;
  518. quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight);
  519. quadricAdd(vertex_quadrics[remap[i0]], Q);
  520. quadricAdd(vertex_quadrics[remap[i1]], Q);
  521. }
  522. }
  523. }
  524. // does triangle ABC flip when C is replaced with D?
  525. static bool hasTriangleFlip(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d)
  526. {
  527. Vector3 eb = {b.x - a.x, b.y - a.y, b.z - a.z};
  528. Vector3 ec = {c.x - a.x, c.y - a.y, c.z - a.z};
  529. Vector3 ed = {d.x - a.x, d.y - a.y, d.z - a.z};
  530. Vector3 nbc = {eb.y * ec.z - eb.z * ec.y, eb.z * ec.x - eb.x * ec.z, eb.x * ec.y - eb.y * ec.x};
  531. Vector3 nbd = {eb.y * ed.z - eb.z * ed.y, eb.z * ed.x - eb.x * ed.z, eb.x * ed.y - eb.y * ed.x};
  532. return nbc.x * nbd.x + nbc.y * nbd.y + nbc.z * nbd.z < 0;
  533. }
  534. static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, const unsigned int* collapse_remap, unsigned int i0, unsigned int i1)
  535. {
  536. assert(collapse_remap[i0] == i0);
  537. assert(collapse_remap[i1] == i1);
  538. const Vector3& v0 = vertex_positions[i0];
  539. const Vector3& v1 = vertex_positions[i1];
  540. const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]];
  541. size_t count = adjacency.counts[i0];
  542. for (size_t i = 0; i < count; ++i)
  543. {
  544. unsigned int a = collapse_remap[edges[i].next];
  545. unsigned int b = collapse_remap[edges[i].prev];
  546. // skip triangles that get collapsed
  547. // note: this is mathematically redundant as if either of these is true, the dot product in hasTriangleFlip should be 0
  548. if (a == i1 || b == i1)
  549. continue;
  550. // early-out when at least one triangle flips due to a collapse
  551. if (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1))
  552. return true;
  553. }
  554. return false;
  555. }
  556. 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)
  557. {
  558. size_t collapse_count = 0;
  559. for (size_t i = 0; i < index_count; i += 3)
  560. {
  561. static const int next[3] = {1, 2, 0};
  562. for (int e = 0; e < 3; ++e)
  563. {
  564. unsigned int i0 = indices[i + e];
  565. unsigned int i1 = indices[i + next[e]];
  566. // this can happen either when input has a zero-length edge, or when we perform collapses for complex
  567. // topology w/seams and collapse a manifold vertex that connects to both wedges onto one of them
  568. // we leave edges like this alone since they may be important for preserving mesh integrity
  569. if (remap[i0] == remap[i1])
  570. continue;
  571. unsigned char k0 = vertex_kind[i0];
  572. unsigned char k1 = vertex_kind[i1];
  573. // the edge has to be collapsible in at least one direction
  574. if (!(kCanCollapse[k0][k1] | kCanCollapse[k1][k0]))
  575. continue;
  576. // manifold and seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges
  577. if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])
  578. continue;
  579. // two vertices are on a border or a seam, but there's no direct edge between them
  580. // this indicates that they belong to two different edge loops and we should not collapse this edge
  581. // loop[] tracks half edges so we only need to check i0->i1
  582. if (k0 == k1 && (k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)
  583. continue;
  584. // edge can be collapsed in either direction - we will pick the one with minimum error
  585. // note: we evaluate error later during collapse ranking, here we just tag the edge as bidirectional
  586. if (kCanCollapse[k0][k1] & kCanCollapse[k1][k0])
  587. {
  588. Collapse c = {i0, i1, {/* bidi= */ 1}};
  589. collapses[collapse_count++] = c;
  590. }
  591. else
  592. {
  593. // edge can only be collapsed in one direction
  594. unsigned int e0 = kCanCollapse[k0][k1] ? i0 : i1;
  595. unsigned int e1 = kCanCollapse[k0][k1] ? i1 : i0;
  596. Collapse c = {e0, e1, {/* bidi= */ 0}};
  597. collapses[collapse_count++] = c;
  598. }
  599. }
  600. }
  601. return collapse_count;
  602. }
  603. static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const Quadric* vertex_quadrics, const unsigned int* remap)
  604. {
  605. for (size_t i = 0; i < collapse_count; ++i)
  606. {
  607. Collapse& c = collapses[i];
  608. unsigned int i0 = c.v0;
  609. unsigned int i1 = c.v1;
  610. // most edges are bidirectional which means we need to evaluate errors for two collapses
  611. // to keep this code branchless we just use the same edge for unidirectional edges
  612. unsigned int j0 = c.bidi ? i1 : i0;
  613. unsigned int j1 = c.bidi ? i0 : i1;
  614. const Quadric& qi = vertex_quadrics[remap[i0]];
  615. const Quadric& qj = vertex_quadrics[remap[j0]];
  616. float ei = quadricError(qi, vertex_positions[i1]);
  617. float ej = quadricError(qj, vertex_positions[j1]);
  618. // pick edge direction with minimal error
  619. c.v0 = ei <= ej ? i0 : j0;
  620. c.v1 = ei <= ej ? i1 : j1;
  621. c.error = ei <= ej ? ei : ej;
  622. }
  623. }
  624. #if TRACE > 1
  625. static void dumpEdgeCollapses(const Collapse* collapses, size_t collapse_count, const unsigned char* vertex_kind)
  626. {
  627. size_t ckinds[Kind_Count][Kind_Count] = {};
  628. float cerrors[Kind_Count][Kind_Count] = {};
  629. for (int k0 = 0; k0 < Kind_Count; ++k0)
  630. for (int k1 = 0; k1 < Kind_Count; ++k1)
  631. cerrors[k0][k1] = FLT_MAX;
  632. for (size_t i = 0; i < collapse_count; ++i)
  633. {
  634. unsigned int i0 = collapses[i].v0;
  635. unsigned int i1 = collapses[i].v1;
  636. unsigned char k0 = vertex_kind[i0];
  637. unsigned char k1 = vertex_kind[i1];
  638. ckinds[k0][k1]++;
  639. cerrors[k0][k1] = (collapses[i].error < cerrors[k0][k1]) ? collapses[i].error : cerrors[k0][k1];
  640. }
  641. for (int k0 = 0; k0 < Kind_Count; ++k0)
  642. for (int k1 = 0; k1 < Kind_Count; ++k1)
  643. if (ckinds[k0][k1])
  644. printf("collapses %d -> %d: %d, min error %e\n", k0, k1, int(ckinds[k0][k1]), ckinds[k0][k1] ? sqrtf(cerrors[k0][k1]) : 0.f);
  645. }
  646. static void dumpLockedCollapses(const unsigned int* indices, size_t index_count, const unsigned char* vertex_kind)
  647. {
  648. size_t locked_collapses[Kind_Count][Kind_Count] = {};
  649. for (size_t i = 0; i < index_count; i += 3)
  650. {
  651. static const int next[3] = {1, 2, 0};
  652. for (int e = 0; e < 3; ++e)
  653. {
  654. unsigned int i0 = indices[i + e];
  655. unsigned int i1 = indices[i + next[e]];
  656. unsigned char k0 = vertex_kind[i0];
  657. unsigned char k1 = vertex_kind[i1];
  658. locked_collapses[k0][k1] += !kCanCollapse[k0][k1] && !kCanCollapse[k1][k0];
  659. }
  660. }
  661. for (int k0 = 0; k0 < Kind_Count; ++k0)
  662. for (int k1 = 0; k1 < Kind_Count; ++k1)
  663. if (locked_collapses[k0][k1])
  664. printf("locked collapses %d -> %d: %d\n", k0, k1, int(locked_collapses[k0][k1]));
  665. }
  666. #endif
  667. static void sortEdgeCollapses(unsigned int* sort_order, const Collapse* collapses, size_t collapse_count)
  668. {
  669. const int sort_bits = 11;
  670. // fill histogram for counting sort
  671. unsigned int histogram[1 << sort_bits];
  672. memset(histogram, 0, sizeof(histogram));
  673. for (size_t i = 0; i < collapse_count; ++i)
  674. {
  675. // skip sign bit since error is non-negative
  676. unsigned int key = (collapses[i].errorui << 1) >> (32 - sort_bits);
  677. histogram[key]++;
  678. }
  679. // compute offsets based on histogram data
  680. size_t histogram_sum = 0;
  681. for (size_t i = 0; i < 1 << sort_bits; ++i)
  682. {
  683. size_t count = histogram[i];
  684. histogram[i] = unsigned(histogram_sum);
  685. histogram_sum += count;
  686. }
  687. assert(histogram_sum == collapse_count);
  688. // compute sort order based on offsets
  689. for (size_t i = 0; i < collapse_count; ++i)
  690. {
  691. // skip sign bit since error is non-negative
  692. unsigned int key = (collapses[i].errorui << 1) >> (32 - sort_bits);
  693. sort_order[histogram[key]++] = unsigned(i);
  694. }
  695. }
  696. 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, const Vector3* vertex_positions, const EdgeAdjacency& adjacency, size_t triangle_collapse_goal, float error_limit, float& result_error)
  697. {
  698. size_t edge_collapses = 0;
  699. size_t triangle_collapses = 0;
  700. // most collapses remove 2 triangles; use this to establish a bound on the pass in terms of error limit
  701. // note that edge_collapse_goal is an estimate; triangle_collapse_goal will be used to actually limit collapses
  702. size_t edge_collapse_goal = triangle_collapse_goal / 2;
  703. #if TRACE
  704. size_t stats[4] = {};
  705. #endif
  706. for (size_t i = 0; i < collapse_count; ++i)
  707. {
  708. const Collapse& c = collapses[collapse_order[i]];
  709. TRACESTATS(0);
  710. if (c.error > error_limit)
  711. break;
  712. if (triangle_collapses >= triangle_collapse_goal)
  713. break;
  714. // we limit the error in each pass based on the error of optimal last collapse; since many collapses will be locked
  715. // as they will share vertices with other successfull collapses, we need to increase the acceptable error by some factor
  716. float error_goal = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX;
  717. // on average, each collapse is expected to lock 6 other collapses; to avoid degenerate passes on meshes with odd
  718. // topology, we only abort if we got over 1/6 collapses accordingly.
  719. if (c.error > error_goal && triangle_collapses > triangle_collapse_goal / 6)
  720. break;
  721. unsigned int i0 = c.v0;
  722. unsigned int i1 = c.v1;
  723. unsigned int r0 = remap[i0];
  724. unsigned int r1 = remap[i1];
  725. // we don't collapse vertices that had source or target vertex involved in a collapse
  726. // it's important to not move the vertices twice since it complicates the tracking/remapping logic
  727. // it's important to not move other vertices towards a moved vertex to preserve error since we don't re-rank collapses mid-pass
  728. if (collapse_locked[r0] | collapse_locked[r1])
  729. {
  730. TRACESTATS(1);
  731. continue;
  732. }
  733. if (hasTriangleFlips(adjacency, vertex_positions, collapse_remap, r0, r1))
  734. {
  735. // adjust collapse goal since this collapse is invalid and shouldn't factor into error goal
  736. edge_collapse_goal++;
  737. TRACESTATS(2);
  738. continue;
  739. }
  740. assert(collapse_remap[r0] == r0);
  741. assert(collapse_remap[r1] == r1);
  742. quadricAdd(vertex_quadrics[r1], vertex_quadrics[r0]);
  743. if (vertex_kind[i0] == Kind_Complex)
  744. {
  745. unsigned int v = i0;
  746. do
  747. {
  748. collapse_remap[v] = r1;
  749. v = wedge[v];
  750. } while (v != i0);
  751. }
  752. else if (vertex_kind[i0] == Kind_Seam)
  753. {
  754. // remap v0 to v1 and seam pair of v0 to seam pair of v1
  755. unsigned int s0 = wedge[i0];
  756. unsigned int s1 = wedge[i1];
  757. assert(s0 != i0 && s1 != i1);
  758. assert(wedge[s0] == i0 && wedge[s1] == i1);
  759. collapse_remap[i0] = i1;
  760. collapse_remap[s0] = s1;
  761. }
  762. else
  763. {
  764. assert(wedge[i0] == i0);
  765. collapse_remap[i0] = i1;
  766. }
  767. collapse_locked[r0] = 1;
  768. collapse_locked[r1] = 1;
  769. // border edges collapse 1 triangle, other edges collapse 2 or more
  770. triangle_collapses += (vertex_kind[i0] == Kind_Border) ? 1 : 2;
  771. edge_collapses++;
  772. result_error = result_error < c.error ? c.error : result_error;
  773. }
  774. #if TRACE
  775. float error_goal_perfect = edge_collapse_goal < collapse_count ? collapses[collapse_order[edge_collapse_goal]].error : 0.f;
  776. printf("removed %d triangles, error %e (goal %e); evaluated %d/%d collapses (done %d, skipped %d, invalid %d)\n",
  777. int(triangle_collapses), sqrtf(result_error), sqrtf(error_goal_perfect),
  778. int(stats[0]), int(collapse_count), int(edge_collapses), int(stats[1]), int(stats[2]));
  779. #endif
  780. return edge_collapses;
  781. }
  782. static size_t remapIndexBuffer(unsigned int* indices, size_t index_count, const unsigned int* collapse_remap)
  783. {
  784. size_t write = 0;
  785. for (size_t i = 0; i < index_count; i += 3)
  786. {
  787. unsigned int v0 = collapse_remap[indices[i + 0]];
  788. unsigned int v1 = collapse_remap[indices[i + 1]];
  789. unsigned int v2 = collapse_remap[indices[i + 2]];
  790. // we never move the vertex twice during a single pass
  791. assert(collapse_remap[v0] == v0);
  792. assert(collapse_remap[v1] == v1);
  793. assert(collapse_remap[v2] == v2);
  794. if (v0 != v1 && v0 != v2 && v1 != v2)
  795. {
  796. indices[write + 0] = v0;
  797. indices[write + 1] = v1;
  798. indices[write + 2] = v2;
  799. write += 3;
  800. }
  801. }
  802. return write;
  803. }
  804. static void remapEdgeLoops(unsigned int* loop, size_t vertex_count, const unsigned int* collapse_remap)
  805. {
  806. for (size_t i = 0; i < vertex_count; ++i)
  807. {
  808. if (loop[i] != ~0u)
  809. {
  810. unsigned int l = loop[i];
  811. unsigned int r = collapse_remap[l];
  812. // i == r is a special case when the seam edge is collapsed in a direction opposite to where loop goes
  813. loop[i] = (i == r) ? loop[l] : r;
  814. }
  815. }
  816. }
  817. struct CellHasher
  818. {
  819. const unsigned int* vertex_ids;
  820. size_t hash(unsigned int i) const
  821. {
  822. unsigned int h = vertex_ids[i];
  823. // MurmurHash2 finalizer
  824. h ^= h >> 13;
  825. h *= 0x5bd1e995;
  826. h ^= h >> 15;
  827. return h;
  828. }
  829. bool equal(unsigned int lhs, unsigned int rhs) const
  830. {
  831. return vertex_ids[lhs] == vertex_ids[rhs];
  832. }
  833. };
  834. struct IdHasher
  835. {
  836. size_t hash(unsigned int id) const
  837. {
  838. unsigned int h = id;
  839. // MurmurHash2 finalizer
  840. h ^= h >> 13;
  841. h *= 0x5bd1e995;
  842. h ^= h >> 15;
  843. return h;
  844. }
  845. bool equal(unsigned int lhs, unsigned int rhs) const
  846. {
  847. return lhs == rhs;
  848. }
  849. };
  850. struct TriangleHasher
  851. {
  852. const unsigned int* indices;
  853. size_t hash(unsigned int i) const
  854. {
  855. const unsigned int* tri = indices + i * 3;
  856. // Optimized Spatial Hashing for Collision Detection of Deformable Objects
  857. return (tri[0] * 73856093) ^ (tri[1] * 19349663) ^ (tri[2] * 83492791);
  858. }
  859. bool equal(unsigned int lhs, unsigned int rhs) const
  860. {
  861. const unsigned int* lt = indices + lhs * 3;
  862. const unsigned int* rt = indices + rhs * 3;
  863. return lt[0] == rt[0] && lt[1] == rt[1] && lt[2] == rt[2];
  864. }
  865. };
  866. static void computeVertexIds(unsigned int* vertex_ids, const Vector3* vertex_positions, size_t vertex_count, int grid_size)
  867. {
  868. assert(grid_size >= 1 && grid_size <= 1024);
  869. float cell_scale = float(grid_size - 1);
  870. for (size_t i = 0; i < vertex_count; ++i)
  871. {
  872. const Vector3& v = vertex_positions[i];
  873. int xi = int(v.x * cell_scale + 0.5f);
  874. int yi = int(v.y * cell_scale + 0.5f);
  875. int zi = int(v.z * cell_scale + 0.5f);
  876. vertex_ids[i] = (xi << 20) | (yi << 10) | zi;
  877. }
  878. }
  879. static size_t countTriangles(const unsigned int* vertex_ids, const unsigned int* indices, size_t index_count)
  880. {
  881. size_t result = 0;
  882. for (size_t i = 0; i < index_count; i += 3)
  883. {
  884. unsigned int id0 = vertex_ids[indices[i + 0]];
  885. unsigned int id1 = vertex_ids[indices[i + 1]];
  886. unsigned int id2 = vertex_ids[indices[i + 2]];
  887. result += (id0 != id1) & (id0 != id2) & (id1 != id2);
  888. }
  889. return result;
  890. }
  891. static size_t fillVertexCells(unsigned int* table, size_t table_size, unsigned int* vertex_cells, const unsigned int* vertex_ids, size_t vertex_count)
  892. {
  893. CellHasher hasher = {vertex_ids};
  894. memset(table, -1, table_size * sizeof(unsigned int));
  895. size_t result = 0;
  896. for (size_t i = 0; i < vertex_count; ++i)
  897. {
  898. unsigned int* entry = hashLookup2(table, table_size, hasher, unsigned(i), ~0u);
  899. if (*entry == ~0u)
  900. {
  901. *entry = unsigned(i);
  902. vertex_cells[i] = unsigned(result++);
  903. }
  904. else
  905. {
  906. vertex_cells[i] = vertex_cells[*entry];
  907. }
  908. }
  909. return result;
  910. }
  911. static size_t countVertexCells(unsigned int* table, size_t table_size, const unsigned int* vertex_ids, size_t vertex_count)
  912. {
  913. IdHasher hasher;
  914. memset(table, -1, table_size * sizeof(unsigned int));
  915. size_t result = 0;
  916. for (size_t i = 0; i < vertex_count; ++i)
  917. {
  918. unsigned int id = vertex_ids[i];
  919. unsigned int* entry = hashLookup2(table, table_size, hasher, id, ~0u);
  920. result += (*entry == ~0u);
  921. *entry = id;
  922. }
  923. return result;
  924. }
  925. static void fillCellQuadrics(Quadric* cell_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* vertex_cells)
  926. {
  927. for (size_t i = 0; i < index_count; i += 3)
  928. {
  929. unsigned int i0 = indices[i + 0];
  930. unsigned int i1 = indices[i + 1];
  931. unsigned int i2 = indices[i + 2];
  932. unsigned int c0 = vertex_cells[i0];
  933. unsigned int c1 = vertex_cells[i1];
  934. unsigned int c2 = vertex_cells[i2];
  935. bool single_cell = (c0 == c1) & (c0 == c2);
  936. Quadric Q;
  937. quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], single_cell ? 3.f : 1.f);
  938. if (single_cell)
  939. {
  940. quadricAdd(cell_quadrics[c0], Q);
  941. }
  942. else
  943. {
  944. quadricAdd(cell_quadrics[c0], Q);
  945. quadricAdd(cell_quadrics[c1], Q);
  946. quadricAdd(cell_quadrics[c2], Q);
  947. }
  948. }
  949. }
  950. static void fillCellQuadrics(Quadric* cell_quadrics, const Vector3* vertex_positions, size_t vertex_count, const unsigned int* vertex_cells)
  951. {
  952. for (size_t i = 0; i < vertex_count; ++i)
  953. {
  954. unsigned int c = vertex_cells[i];
  955. const Vector3& v = vertex_positions[i];
  956. Quadric Q;
  957. quadricFromPoint(Q, v.x, v.y, v.z, 1.f);
  958. quadricAdd(cell_quadrics[c], Q);
  959. }
  960. }
  961. 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)
  962. {
  963. memset(cell_remap, -1, cell_count * sizeof(unsigned int));
  964. for (size_t i = 0; i < vertex_count; ++i)
  965. {
  966. unsigned int cell = vertex_cells[i];
  967. float error = quadricError(cell_quadrics[cell], vertex_positions[i]);
  968. if (cell_remap[cell] == ~0u || cell_errors[cell] > error)
  969. {
  970. cell_remap[cell] = unsigned(i);
  971. cell_errors[cell] = error;
  972. }
  973. }
  974. }
  975. 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)
  976. {
  977. TriangleHasher hasher = {destination};
  978. memset(tritable, -1, tritable_size * sizeof(unsigned int));
  979. size_t result = 0;
  980. for (size_t i = 0; i < index_count; i += 3)
  981. {
  982. unsigned int c0 = vertex_cells[indices[i + 0]];
  983. unsigned int c1 = vertex_cells[indices[i + 1]];
  984. unsigned int c2 = vertex_cells[indices[i + 2]];
  985. if (c0 != c1 && c0 != c2 && c1 != c2)
  986. {
  987. unsigned int a = cell_remap[c0];
  988. unsigned int b = cell_remap[c1];
  989. unsigned int c = cell_remap[c2];
  990. if (b < a && b < c)
  991. {
  992. unsigned int t = a;
  993. a = b, b = c, c = t;
  994. }
  995. else if (c < a && c < b)
  996. {
  997. unsigned int t = c;
  998. c = b, b = a, a = t;
  999. }
  1000. destination[result * 3 + 0] = a;
  1001. destination[result * 3 + 1] = b;
  1002. destination[result * 3 + 2] = c;
  1003. unsigned int* entry = hashLookup2(tritable, tritable_size, hasher, unsigned(result), ~0u);
  1004. if (*entry == ~0u)
  1005. *entry = unsigned(result++);
  1006. }
  1007. }
  1008. return result * 3;
  1009. }
  1010. static float interpolate(float y, float x0, float y0, float x1, float y1, float x2, float y2)
  1011. {
  1012. // three point interpolation from "revenge of interpolation search" paper
  1013. float num = (y1 - y) * (x1 - x2) * (x1 - x0) * (y2 - y0);
  1014. float den = (y2 - y) * (x1 - x2) * (y0 - y1) + (y0 - y) * (x1 - x0) * (y1 - y2);
  1015. return x1 + num / den;
  1016. }
  1017. } // namespace meshopt
  1018. #ifndef NDEBUG
  1019. // Note: this is only exposed for debug visualization purposes; do *not* use these in debug builds
  1020. MESHOPTIMIZER_API unsigned char* meshopt_simplifyDebugKind = 0;
  1021. MESHOPTIMIZER_API unsigned int* meshopt_simplifyDebugLoop = 0;
  1022. MESHOPTIMIZER_API unsigned int* meshopt_simplifyDebugLoopBack = 0;
  1023. #endif
  1024. 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, unsigned int options, float* out_result_error)
  1025. {
  1026. using namespace meshopt;
  1027. assert(index_count % 3 == 0);
  1028. assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
  1029. assert(vertex_positions_stride % sizeof(float) == 0);
  1030. assert(target_index_count <= index_count);
  1031. assert((options & ~(meshopt_SimplifyLockBorder)) == 0);
  1032. meshopt_Allocator allocator;
  1033. unsigned int* result = destination;
  1034. // build adjacency information
  1035. EdgeAdjacency adjacency = {};
  1036. prepareEdgeAdjacency(adjacency, index_count, vertex_count, allocator);
  1037. updateEdgeAdjacency(adjacency, indices, index_count, vertex_count, NULL);
  1038. // build position remap that maps each vertex to the one with identical position
  1039. unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);
  1040. unsigned int* wedge = allocator.allocate<unsigned int>(vertex_count);
  1041. buildPositionRemap(remap, wedge, vertex_positions_data, vertex_count, vertex_positions_stride, allocator);
  1042. // classify vertices; vertex kind determines collapse rules, see kCanCollapse
  1043. unsigned char* vertex_kind = allocator.allocate<unsigned char>(vertex_count);
  1044. unsigned int* loop = allocator.allocate<unsigned int>(vertex_count);
  1045. unsigned int* loopback = allocator.allocate<unsigned int>(vertex_count);
  1046. classifyVertices(vertex_kind, loop, loopback, vertex_count, adjacency, remap, wedge, options);
  1047. #if TRACE
  1048. size_t unique_positions = 0;
  1049. for (size_t i = 0; i < vertex_count; ++i)
  1050. unique_positions += remap[i] == i;
  1051. printf("position remap: %d vertices => %d positions\n", int(vertex_count), int(unique_positions));
  1052. size_t kinds[Kind_Count] = {};
  1053. for (size_t i = 0; i < vertex_count; ++i)
  1054. kinds[vertex_kind[i]] += remap[i] == i;
  1055. printf("kinds: manifold %d, border %d, seam %d, complex %d, locked %d\n",
  1056. int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Locked]));
  1057. #endif
  1058. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  1059. rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);
  1060. Quadric* vertex_quadrics = allocator.allocate<Quadric>(vertex_count);
  1061. memset(vertex_quadrics, 0, vertex_count * sizeof(Quadric));
  1062. fillFaceQuadrics(vertex_quadrics, indices, index_count, vertex_positions, remap);
  1063. fillEdgeQuadrics(vertex_quadrics, indices, index_count, vertex_positions, remap, vertex_kind, loop, loopback);
  1064. if (result != indices)
  1065. memcpy(result, indices, index_count * sizeof(unsigned int));
  1066. #if TRACE
  1067. size_t pass_count = 0;
  1068. #endif
  1069. Collapse* edge_collapses = allocator.allocate<Collapse>(index_count);
  1070. unsigned int* collapse_order = allocator.allocate<unsigned int>(index_count);
  1071. unsigned int* collapse_remap = allocator.allocate<unsigned int>(vertex_count);
  1072. unsigned char* collapse_locked = allocator.allocate<unsigned char>(vertex_count);
  1073. size_t result_count = index_count;
  1074. float result_error = 0;
  1075. // target_error input is linear; we need to adjust it to match quadricError units
  1076. float error_limit = target_error * target_error;
  1077. while (result_count > target_index_count)
  1078. {
  1079. // note: throughout the simplification process adjacency structure reflects welded topology for result-in-progress
  1080. updateEdgeAdjacency(adjacency, result, result_count, vertex_count, remap);
  1081. size_t edge_collapse_count = pickEdgeCollapses(edge_collapses, result, result_count, remap, vertex_kind, loop);
  1082. // no edges can be collapsed any more due to topology restrictions
  1083. if (edge_collapse_count == 0)
  1084. break;
  1085. rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_quadrics, remap);
  1086. #if TRACE > 1
  1087. dumpEdgeCollapses(edge_collapses, edge_collapse_count, vertex_kind);
  1088. #endif
  1089. sortEdgeCollapses(collapse_order, edge_collapses, edge_collapse_count);
  1090. size_t triangle_collapse_goal = (result_count - target_index_count) / 3;
  1091. for (size_t i = 0; i < vertex_count; ++i)
  1092. collapse_remap[i] = unsigned(i);
  1093. memset(collapse_locked, 0, vertex_count);
  1094. #if TRACE
  1095. printf("pass %d: ", int(pass_count++));
  1096. #endif
  1097. size_t collapses = performEdgeCollapses(collapse_remap, collapse_locked, vertex_quadrics, edge_collapses, edge_collapse_count, collapse_order, remap, wedge, vertex_kind, vertex_positions, adjacency, triangle_collapse_goal, error_limit, result_error);
  1098. // no edges can be collapsed any more due to hitting the error limit or triangle collapse limit
  1099. if (collapses == 0)
  1100. break;
  1101. remapEdgeLoops(loop, vertex_count, collapse_remap);
  1102. remapEdgeLoops(loopback, vertex_count, collapse_remap);
  1103. size_t new_count = remapIndexBuffer(result, result_count, collapse_remap);
  1104. assert(new_count < result_count);
  1105. result_count = new_count;
  1106. }
  1107. #if TRACE
  1108. printf("result: %d triangles, error: %e; total %d passes\n", int(result_count), sqrtf(result_error), int(pass_count));
  1109. #endif
  1110. #if TRACE > 1
  1111. dumpLockedCollapses(result, result_count, vertex_kind);
  1112. #endif
  1113. #ifndef NDEBUG
  1114. if (meshopt_simplifyDebugKind)
  1115. memcpy(meshopt_simplifyDebugKind, vertex_kind, vertex_count);
  1116. if (meshopt_simplifyDebugLoop)
  1117. memcpy(meshopt_simplifyDebugLoop, loop, vertex_count * sizeof(unsigned int));
  1118. if (meshopt_simplifyDebugLoopBack)
  1119. memcpy(meshopt_simplifyDebugLoopBack, loopback, vertex_count * sizeof(unsigned int));
  1120. #endif
  1121. // result_error is quadratic; we need to remap it back to linear
  1122. if (out_result_error)
  1123. *out_result_error = sqrtf(result_error);
  1124. return result_count;
  1125. }
  1126. 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, float target_error, float* out_result_error)
  1127. {
  1128. using namespace meshopt;
  1129. assert(index_count % 3 == 0);
  1130. assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
  1131. assert(vertex_positions_stride % sizeof(float) == 0);
  1132. assert(target_index_count <= index_count);
  1133. // we expect to get ~2 triangles/vertex in the output
  1134. size_t target_cell_count = target_index_count / 6;
  1135. meshopt_Allocator allocator;
  1136. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  1137. rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);
  1138. // find the optimal grid size using guided binary search
  1139. #if TRACE
  1140. printf("source: %d vertices, %d triangles\n", int(vertex_count), int(index_count / 3));
  1141. printf("target: %d cells, %d triangles\n", int(target_cell_count), int(target_index_count / 3));
  1142. #endif
  1143. unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);
  1144. const int kInterpolationPasses = 5;
  1145. // invariant: # of triangles in min_grid <= target_count
  1146. int min_grid = int(1.f / (target_error < 1e-3f ? 1e-3f : target_error));
  1147. int max_grid = 1025;
  1148. size_t min_triangles = 0;
  1149. size_t max_triangles = index_count / 3;
  1150. // when we're error-limited, we compute the triangle count for the min. size; this accelerates convergence and provides the correct answer when we can't use a larger grid
  1151. if (min_grid > 1)
  1152. {
  1153. computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);
  1154. min_triangles = countTriangles(vertex_ids, indices, index_count);
  1155. }
  1156. // 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...
  1157. int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);
  1158. for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)
  1159. {
  1160. if (min_triangles >= target_index_count / 3 || max_grid - min_grid <= 1)
  1161. break;
  1162. // we clamp the prediction of the grid size to make sure that the search converges
  1163. int grid_size = next_grid_size;
  1164. grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid) ? max_grid - 1 : grid_size;
  1165. computeVertexIds(vertex_ids, vertex_positions, vertex_count, grid_size);
  1166. size_t triangles = countTriangles(vertex_ids, indices, index_count);
  1167. #if TRACE
  1168. printf("pass %d (%s): grid size %d, triangles %d, %s\n",
  1169. pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses) ? "lerp" : "binary",
  1170. grid_size, int(triangles),
  1171. (triangles <= target_index_count / 3) ? "under" : "over");
  1172. #endif
  1173. float tip = interpolate(float(target_index_count / 3), float(min_grid), float(min_triangles), float(grid_size), float(triangles), float(max_grid), float(max_triangles));
  1174. if (triangles <= target_index_count / 3)
  1175. {
  1176. min_grid = grid_size;
  1177. min_triangles = triangles;
  1178. }
  1179. else
  1180. {
  1181. max_grid = grid_size;
  1182. max_triangles = triangles;
  1183. }
  1184. // we start by using interpolation search - it usually converges faster
  1185. // however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)
  1186. next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;
  1187. }
  1188. if (min_triangles == 0)
  1189. {
  1190. if (out_result_error)
  1191. *out_result_error = 1.f;
  1192. return 0;
  1193. }
  1194. // build vertex->cell association by mapping all vertices with the same quantized position to the same cell
  1195. size_t table_size = hashBuckets2(vertex_count);
  1196. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  1197. unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);
  1198. computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);
  1199. size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);
  1200. // build a quadric for each target cell
  1201. Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count);
  1202. memset(cell_quadrics, 0, cell_count * sizeof(Quadric));
  1203. fillCellQuadrics(cell_quadrics, indices, index_count, vertex_positions, vertex_cells);
  1204. // for each target cell, find the vertex with the minimal error
  1205. unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);
  1206. float* cell_errors = allocator.allocate<float>(cell_count);
  1207. fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count);
  1208. // compute error
  1209. float result_error = 0.f;
  1210. for (size_t i = 0; i < cell_count; ++i)
  1211. result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error;
  1212. // collapse triangles!
  1213. // note that we need to filter out triangles that we've already output because we very frequently generate redundant triangles between cells :(
  1214. size_t tritable_size = hashBuckets2(min_triangles);
  1215. unsigned int* tritable = allocator.allocate<unsigned int>(tritable_size);
  1216. size_t write = filterTriangles(destination, tritable, tritable_size, indices, index_count, vertex_cells, cell_remap);
  1217. #if TRACE
  1218. printf("result: %d cells, %d triangles (%d unfiltered), error %e\n", int(cell_count), int(write / 3), int(min_triangles), sqrtf(result_error));
  1219. #endif
  1220. if (out_result_error)
  1221. *out_result_error = sqrtf(result_error);
  1222. return write;
  1223. }
  1224. size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_vertex_count)
  1225. {
  1226. using namespace meshopt;
  1227. assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
  1228. assert(vertex_positions_stride % sizeof(float) == 0);
  1229. assert(target_vertex_count <= vertex_count);
  1230. size_t target_cell_count = target_vertex_count;
  1231. if (target_cell_count == 0)
  1232. return 0;
  1233. meshopt_Allocator allocator;
  1234. Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);
  1235. rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);
  1236. // find the optimal grid size using guided binary search
  1237. #if TRACE
  1238. printf("source: %d vertices\n", int(vertex_count));
  1239. printf("target: %d cells\n", int(target_cell_count));
  1240. #endif
  1241. unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);
  1242. size_t table_size = hashBuckets2(vertex_count);
  1243. unsigned int* table = allocator.allocate<unsigned int>(table_size);
  1244. const int kInterpolationPasses = 5;
  1245. // invariant: # of vertices in min_grid <= target_count
  1246. int min_grid = 0;
  1247. int max_grid = 1025;
  1248. size_t min_vertices = 0;
  1249. size_t max_vertices = vertex_count;
  1250. // 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...
  1251. int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);
  1252. for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)
  1253. {
  1254. assert(min_vertices < target_vertex_count);
  1255. assert(max_grid - min_grid > 1);
  1256. // we clamp the prediction of the grid size to make sure that the search converges
  1257. int grid_size = next_grid_size;
  1258. grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid) ? max_grid - 1 : grid_size;
  1259. computeVertexIds(vertex_ids, vertex_positions, vertex_count, grid_size);
  1260. size_t vertices = countVertexCells(table, table_size, vertex_ids, vertex_count);
  1261. #if TRACE
  1262. printf("pass %d (%s): grid size %d, vertices %d, %s\n",
  1263. pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses) ? "lerp" : "binary",
  1264. grid_size, int(vertices),
  1265. (vertices <= target_vertex_count) ? "under" : "over");
  1266. #endif
  1267. float tip = interpolate(float(target_vertex_count), float(min_grid), float(min_vertices), float(grid_size), float(vertices), float(max_grid), float(max_vertices));
  1268. if (vertices <= target_vertex_count)
  1269. {
  1270. min_grid = grid_size;
  1271. min_vertices = vertices;
  1272. }
  1273. else
  1274. {
  1275. max_grid = grid_size;
  1276. max_vertices = vertices;
  1277. }
  1278. if (vertices == target_vertex_count || max_grid - min_grid <= 1)
  1279. break;
  1280. // we start by using interpolation search - it usually converges faster
  1281. // however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)
  1282. next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;
  1283. }
  1284. if (min_vertices == 0)
  1285. return 0;
  1286. // build vertex->cell association by mapping all vertices with the same quantized position to the same cell
  1287. unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);
  1288. computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);
  1289. size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);
  1290. // build a quadric for each target cell
  1291. Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count);
  1292. memset(cell_quadrics, 0, cell_count * sizeof(Quadric));
  1293. fillCellQuadrics(cell_quadrics, vertex_positions, vertex_count, vertex_cells);
  1294. // for each target cell, find the vertex with the minimal error
  1295. unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);
  1296. float* cell_errors = allocator.allocate<float>(cell_count);
  1297. fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count);
  1298. // copy results to the output
  1299. assert(cell_count <= target_vertex_count);
  1300. memcpy(destination, cell_remap, sizeof(unsigned int) * cell_count);
  1301. #if TRACE
  1302. printf("result: %d cells\n", int(cell_count));
  1303. #endif
  1304. return cell_count;
  1305. }
  1306. float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  1307. {
  1308. using namespace meshopt;
  1309. assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);
  1310. assert(vertex_positions_stride % sizeof(float) == 0);
  1311. float extent = rescalePositions(NULL, vertex_positions, vertex_count, vertex_positions_stride);
  1312. return extent;
  1313. }