main.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. #include "../src/meshoptimizer.h"
  2. #include <assert.h>
  3. #include <math.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <time.h>
  7. #include <vector>
  8. #include "../tools/fast_obj.h"
  9. #include "miniz.h"
  10. // This file uses assert() to verify algorithm correctness
  11. #undef NDEBUG
  12. #include <assert.h>
  13. #if defined(__linux__)
  14. double timestamp()
  15. {
  16. timespec ts;
  17. clock_gettime(CLOCK_MONOTONIC, &ts);
  18. return double(ts.tv_sec) + 1e-9 * double(ts.tv_nsec);
  19. }
  20. #elif defined(_WIN32)
  21. struct LARGE_INTEGER
  22. {
  23. __int64 QuadPart;
  24. };
  25. extern "C" __declspec(dllimport) int __stdcall QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount);
  26. extern "C" __declspec(dllimport) int __stdcall QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency);
  27. double timestamp()
  28. {
  29. LARGE_INTEGER freq, counter;
  30. QueryPerformanceFrequency(&freq);
  31. QueryPerformanceCounter(&counter);
  32. return double(counter.QuadPart) / double(freq.QuadPart);
  33. }
  34. #else
  35. double timestamp()
  36. {
  37. return double(clock()) / double(CLOCKS_PER_SEC);
  38. }
  39. #endif
  40. const size_t kCacheSize = 16;
  41. struct Vertex
  42. {
  43. float px, py, pz;
  44. float nx, ny, nz;
  45. float tx, ty;
  46. };
  47. struct Mesh
  48. {
  49. std::vector<Vertex> vertices;
  50. std::vector<unsigned int> indices;
  51. };
  52. union Triangle {
  53. Vertex v[3];
  54. char data[sizeof(Vertex) * 3];
  55. };
  56. Mesh parseObj(const char* path, double& reindex)
  57. {
  58. fastObjMesh* obj = fast_obj_read(path);
  59. if (!obj)
  60. {
  61. printf("Error loading %s: file not found\n", path);
  62. return Mesh();
  63. }
  64. size_t total_indices = 0;
  65. for (unsigned int i = 0; i < obj->face_count; ++i)
  66. total_indices += 3 * (obj->face_vertices[i] - 2);
  67. std::vector<Vertex> vertices(total_indices);
  68. size_t vertex_offset = 0;
  69. size_t index_offset = 0;
  70. for (unsigned int i = 0; i < obj->face_count; ++i)
  71. {
  72. for (unsigned int j = 0; j < obj->face_vertices[i]; ++j)
  73. {
  74. fastObjIndex gi = obj->indices[index_offset + j];
  75. Vertex v =
  76. {
  77. obj->positions[gi.p * 3 + 0],
  78. obj->positions[gi.p * 3 + 1],
  79. obj->positions[gi.p * 3 + 2],
  80. obj->normals[gi.n * 3 + 0],
  81. obj->normals[gi.n * 3 + 1],
  82. obj->normals[gi.n * 3 + 2],
  83. obj->texcoords[gi.t * 2 + 0],
  84. obj->texcoords[gi.t * 2 + 1],
  85. };
  86. // triangulate polygon on the fly; offset-3 is always the first polygon vertex
  87. if (j >= 3)
  88. {
  89. vertices[vertex_offset + 0] = vertices[vertex_offset - 3];
  90. vertices[vertex_offset + 1] = vertices[vertex_offset - 1];
  91. vertex_offset += 2;
  92. }
  93. vertices[vertex_offset] = v;
  94. vertex_offset++;
  95. }
  96. index_offset += obj->face_vertices[i];
  97. }
  98. fast_obj_destroy(obj);
  99. reindex = timestamp();
  100. Mesh result;
  101. std::vector<unsigned int> remap(total_indices);
  102. size_t total_vertices = meshopt_generateVertexRemap(&remap[0], NULL, total_indices, &vertices[0], total_indices, sizeof(Vertex));
  103. result.indices.resize(total_indices);
  104. meshopt_remapIndexBuffer(&result.indices[0], NULL, total_indices, &remap[0]);
  105. result.vertices.resize(total_vertices);
  106. meshopt_remapVertexBuffer(&result.vertices[0], &vertices[0], total_indices, sizeof(Vertex), &remap[0]);
  107. return result;
  108. }
  109. bool isMeshValid(const Mesh& mesh)
  110. {
  111. size_t index_count = mesh.indices.size();
  112. size_t vertex_count = mesh.vertices.size();
  113. if (index_count % 3 != 0)
  114. return false;
  115. const unsigned int* indices = &mesh.indices[0];
  116. for (size_t i = 0; i < index_count; ++i)
  117. if (indices[i] >= vertex_count)
  118. return false;
  119. return true;
  120. }
  121. bool rotateTriangle(Triangle& t)
  122. {
  123. int c01 = memcmp(&t.v[0], &t.v[1], sizeof(Vertex));
  124. int c02 = memcmp(&t.v[0], &t.v[2], sizeof(Vertex));
  125. int c12 = memcmp(&t.v[1], &t.v[2], sizeof(Vertex));
  126. if (c12 < 0 && c01 > 0)
  127. {
  128. // 1 is minimum, rotate 012 => 120
  129. Vertex tv = t.v[0];
  130. t.v[0] = t.v[1], t.v[1] = t.v[2], t.v[2] = tv;
  131. }
  132. else if (c02 > 0 && c12 > 0)
  133. {
  134. // 2 is minimum, rotate 012 => 201
  135. Vertex tv = t.v[2];
  136. t.v[2] = t.v[1], t.v[1] = t.v[0], t.v[0] = tv;
  137. }
  138. return c01 != 0 && c02 != 0 && c12 != 0;
  139. }
  140. unsigned int hashRange(const char* key, size_t len)
  141. {
  142. // MurmurHash2
  143. const unsigned int m = 0x5bd1e995;
  144. const int r = 24;
  145. unsigned int h = 0;
  146. while (len >= 4)
  147. {
  148. unsigned int k = *reinterpret_cast<const unsigned int*>(key);
  149. k *= m;
  150. k ^= k >> r;
  151. k *= m;
  152. h *= m;
  153. h ^= k;
  154. key += 4;
  155. len -= 4;
  156. }
  157. return h;
  158. }
  159. unsigned int hashMesh(const Mesh& mesh)
  160. {
  161. size_t triangle_count = mesh.indices.size() / 3;
  162. const Vertex* vertices = &mesh.vertices[0];
  163. const unsigned int* indices = &mesh.indices[0];
  164. unsigned int h1 = 0;
  165. unsigned int h2 = 0;
  166. for (size_t i = 0; i < triangle_count; ++i)
  167. {
  168. Triangle t;
  169. t.v[0] = vertices[indices[i * 3 + 0]];
  170. t.v[1] = vertices[indices[i * 3 + 1]];
  171. t.v[2] = vertices[indices[i * 3 + 2]];
  172. // skip degenerate triangles since some algorithms don't preserve them
  173. if (rotateTriangle(t))
  174. {
  175. unsigned int hash = hashRange(t.data, sizeof(t.data));
  176. h1 ^= hash;
  177. h2 += hash;
  178. }
  179. }
  180. return h1 * 0x5bd1e995 + h2;
  181. }
  182. void optNone(Mesh& mesh)
  183. {
  184. (void)mesh;
  185. }
  186. void optRandomShuffle(Mesh& mesh)
  187. {
  188. size_t triangle_count = mesh.indices.size() / 3;
  189. unsigned int* indices = &mesh.indices[0];
  190. unsigned int rng = 0;
  191. for (size_t i = triangle_count - 1; i > 0; --i)
  192. {
  193. // Fisher-Yates shuffle
  194. size_t j = rng % (i + 1);
  195. unsigned int t;
  196. t = indices[3 * j + 0], indices[3 * j + 0] = indices[3 * i + 0], indices[3 * i + 0] = t;
  197. t = indices[3 * j + 1], indices[3 * j + 1] = indices[3 * i + 1], indices[3 * i + 1] = t;
  198. t = indices[3 * j + 2], indices[3 * j + 2] = indices[3 * i + 2], indices[3 * i + 2] = t;
  199. // LCG RNG, constants from Numerical Recipes
  200. rng = rng * 1664525 + 1013904223;
  201. }
  202. }
  203. void optCache(Mesh& mesh)
  204. {
  205. meshopt_optimizeVertexCache(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size());
  206. }
  207. void optCacheFifo(Mesh& mesh)
  208. {
  209. meshopt_optimizeVertexCacheFifo(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size(), kCacheSize);
  210. }
  211. void optOverdraw(Mesh& mesh)
  212. {
  213. // use worst-case ACMR threshold so that overdraw optimizer can sort *all* triangles
  214. // warning: this significantly deteriorates the vertex cache efficiency so it is not advised; look at optComplete for the recommended method
  215. const float kThreshold = 3.f;
  216. meshopt_optimizeOverdraw(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), kThreshold);
  217. }
  218. void optFetch(Mesh& mesh)
  219. {
  220. meshopt_optimizeVertexFetch(&mesh.vertices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex));
  221. }
  222. void optFetchRemap(Mesh& mesh)
  223. {
  224. // this produces results equivalent to optFetch, but can be used to remap multiple vertex streams
  225. std::vector<unsigned int> remap(mesh.vertices.size());
  226. meshopt_optimizeVertexFetchRemap(&remap[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size());
  227. meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), &remap[0]);
  228. meshopt_remapVertexBuffer(&mesh.vertices[0], &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex), &remap[0]);
  229. }
  230. void optComplete(Mesh& mesh)
  231. {
  232. // vertex cache optimization should go first as it provides starting order for overdraw
  233. meshopt_optimizeVertexCache(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size());
  234. // reorder indices for overdraw, balancing overdraw and vertex cache efficiency
  235. const float kThreshold = 1.01f; // allow up to 1% worse ACMR to get more reordering opportunities for overdraw
  236. meshopt_optimizeOverdraw(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), kThreshold);
  237. // vertex fetch optimization should go last as it depends on the final index order
  238. meshopt_optimizeVertexFetch(&mesh.vertices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex));
  239. }
  240. struct PackedVertex
  241. {
  242. unsigned short px, py, pz;
  243. unsigned short pw; // padding to 4b boundary
  244. signed char nx, ny, nz, nw;
  245. unsigned short tx, ty;
  246. };
  247. void packMesh(std::vector<PackedVertex>& pv, const std::vector<Vertex>& vertices)
  248. {
  249. for (size_t i = 0; i < vertices.size(); ++i)
  250. {
  251. const Vertex& vi = vertices[i];
  252. PackedVertex& pvi = pv[i];
  253. pvi.px = meshopt_quantizeHalf(vi.px);
  254. pvi.py = meshopt_quantizeHalf(vi.py);
  255. pvi.pz = meshopt_quantizeHalf(vi.pz);
  256. pvi.pw = 0;
  257. pvi.nx = char(meshopt_quantizeSnorm(vi.nx, 8));
  258. pvi.ny = char(meshopt_quantizeSnorm(vi.ny, 8));
  259. pvi.nz = char(meshopt_quantizeSnorm(vi.nz, 8));
  260. pvi.nw = 0;
  261. pvi.tx = meshopt_quantizeHalf(vi.tx);
  262. pvi.ty = meshopt_quantizeHalf(vi.ty);
  263. }
  264. }
  265. struct PackedVertexOct
  266. {
  267. unsigned short px, py, pz;
  268. signed char nu, nv; // octahedron encoded normal, aliases .pw
  269. unsigned short tx, ty;
  270. };
  271. void packMesh(std::vector<PackedVertexOct>& pv, const std::vector<Vertex>& vertices)
  272. {
  273. for (size_t i = 0; i < vertices.size(); ++i)
  274. {
  275. const Vertex& vi = vertices[i];
  276. PackedVertexOct& pvi = pv[i];
  277. pvi.px = meshopt_quantizeHalf(vi.px);
  278. pvi.py = meshopt_quantizeHalf(vi.py);
  279. pvi.pz = meshopt_quantizeHalf(vi.pz);
  280. float nsum = fabsf(vi.nx) + fabsf(vi.ny) + fabsf(vi.nz);
  281. float nx = vi.nx / nsum;
  282. float ny = vi.ny / nsum;
  283. float nz = vi.nz;
  284. float nu = nz >= 0 ? nx : (1 - fabsf(ny)) * (nx >= 0 ? 1 : -1);
  285. float nv = nz >= 0 ? ny : (1 - fabsf(nx)) * (ny >= 0 ? 1 : -1);
  286. pvi.nu = char(meshopt_quantizeSnorm(nu, 8));
  287. pvi.nv = char(meshopt_quantizeSnorm(nv, 8));
  288. pvi.tx = meshopt_quantizeHalf(vi.tx);
  289. pvi.ty = meshopt_quantizeHalf(vi.ty);
  290. }
  291. }
  292. void simplify(const Mesh& mesh, float threshold = 0.2f)
  293. {
  294. Mesh lod;
  295. double start = timestamp();
  296. size_t target_index_count = size_t(mesh.indices.size() * threshold);
  297. float target_error = 1e-2f;
  298. lod.indices.resize(mesh.indices.size()); // note: simplify needs space for index_count elements in the destination array, not target_index_count
  299. lod.indices.resize(meshopt_simplify(&lod.indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_index_count, target_error));
  300. lod.vertices.resize(lod.indices.size() < mesh.vertices.size() ? lod.indices.size() : mesh.vertices.size()); // note: this is just to reduce the cost of resize()
  301. lod.vertices.resize(meshopt_optimizeVertexFetch(&lod.vertices[0], &lod.indices[0], lod.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex)));
  302. double end = timestamp();
  303. printf("%-9s: %d triangles => %d triangles in %.2f msec\n",
  304. "Simplify",
  305. int(mesh.indices.size() / 3), int(lod.indices.size() / 3), (end - start) * 1000);
  306. }
  307. void simplifySloppy(const Mesh& mesh, float threshold = 0.2f)
  308. {
  309. Mesh lod;
  310. double start = timestamp();
  311. size_t target_index_count = size_t(mesh.indices.size() * threshold);
  312. lod.indices.resize(target_index_count); // note: simplifySloppy, unlike simplify, is guaranteed to output results that don't exceed the requested target_index_count
  313. lod.indices.resize(meshopt_simplifySloppy(&lod.indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_index_count));
  314. lod.vertices.resize(lod.indices.size() < mesh.vertices.size() ? lod.indices.size() : mesh.vertices.size()); // note: this is just to reduce the cost of resize()
  315. lod.vertices.resize(meshopt_optimizeVertexFetch(&lod.vertices[0], &lod.indices[0], lod.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex)));
  316. double end = timestamp();
  317. printf("%-9s: %d triangles => %d triangles in %.2f msec\n",
  318. "SimplifyS",
  319. int(mesh.indices.size() / 3), int(lod.indices.size() / 3), (end - start) * 1000);
  320. }
  321. void simplifyPoints(const Mesh& mesh, float threshold = 0.2f)
  322. {
  323. double start = timestamp();
  324. size_t target_vertex_count = size_t(mesh.vertices.size() * threshold);
  325. std::vector<unsigned int> indices(target_vertex_count);
  326. indices.resize(meshopt_simplifyPoints(&indices[0], &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_vertex_count));
  327. double end = timestamp();
  328. printf("%-9s: %d points => %d points in %.2f msec\n",
  329. "SimplifyP",
  330. int(mesh.vertices.size()), int(indices.size()), (end - start) * 1000);
  331. }
  332. void simplifyComplete(const Mesh& mesh)
  333. {
  334. static const size_t lod_count = 5;
  335. double start = timestamp();
  336. // generate 4 LOD levels (1-4), with each subsequent LOD using 70% triangles
  337. // note that each LOD uses the same (shared) vertex buffer
  338. std::vector<unsigned int> lods[lod_count];
  339. lods[0] = mesh.indices;
  340. for (size_t i = 1; i < lod_count; ++i)
  341. {
  342. std::vector<unsigned int>& lod = lods[i];
  343. float threshold = powf(0.7f, float(i));
  344. size_t target_index_count = size_t(mesh.indices.size() * threshold) / 3 * 3;
  345. float target_error = 1e-2f;
  346. // we can simplify all the way from base level or from the last result
  347. // simplifying from the base level sometimes produces better results, but simplifying from last level is faster
  348. const std::vector<unsigned int>& source = lods[i - 1];
  349. if (source.size() < target_index_count)
  350. target_index_count = source.size();
  351. lod.resize(source.size());
  352. lod.resize(meshopt_simplify(&lod[0], &source[0], source.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_index_count, target_error));
  353. }
  354. double middle = timestamp();
  355. // optimize each individual LOD for vertex cache & overdraw
  356. for (size_t i = 0; i < lod_count; ++i)
  357. {
  358. std::vector<unsigned int>& lod = lods[i];
  359. meshopt_optimizeVertexCache(&lod[0], &lod[0], lod.size(), mesh.vertices.size());
  360. meshopt_optimizeOverdraw(&lod[0], &lod[0], lod.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), 1.0f);
  361. }
  362. // concatenate all LODs into one IB
  363. // note: the order of concatenation is important - since we optimize the entire IB for vertex fetch,
  364. // putting coarse LODs first makes sure that the vertex range referenced by them is as small as possible
  365. // some GPUs process the entire range referenced by the index buffer region so doing this optimizes the vertex transform
  366. // cost for coarse LODs
  367. // this order also produces much better vertex fetch cache coherency for coarse LODs (since they're essentially optimized first)
  368. // somewhat surprisingly, the vertex fetch cache coherency for fine LODs doesn't seem to suffer that much.
  369. size_t lod_index_offsets[lod_count] = {};
  370. size_t lod_index_counts[lod_count] = {};
  371. size_t total_index_count = 0;
  372. for (int i = lod_count - 1; i >= 0; --i)
  373. {
  374. lod_index_offsets[i] = total_index_count;
  375. lod_index_counts[i] = lods[i].size();
  376. total_index_count += lods[i].size();
  377. }
  378. std::vector<unsigned int> indices(total_index_count);
  379. for (size_t i = 0; i < lod_count; ++i)
  380. {
  381. memcpy(&indices[lod_index_offsets[i]], &lods[i][0], lods[i].size() * sizeof(lods[i][0]));
  382. }
  383. std::vector<Vertex> vertices = mesh.vertices;
  384. // vertex fetch optimization should go last as it depends on the final index order
  385. // note that the order of LODs above affects vertex fetch results
  386. meshopt_optimizeVertexFetch(&vertices[0], &indices[0], indices.size(), &vertices[0], vertices.size(), sizeof(Vertex));
  387. double end = timestamp();
  388. printf("%-9s: %d triangles => %d LOD levels down to %d triangles in %.2f msec, optimized in %.2f msec\n",
  389. "SimplifyC",
  390. int(lod_index_counts[0]) / 3, int(lod_count), int(lod_index_counts[lod_count - 1]) / 3,
  391. (middle - start) * 1000, (end - middle) * 1000);
  392. // for using LOD data at runtime, in addition to vertices and indices you have to save lod_index_offsets/lod_index_counts.
  393. {
  394. meshopt_VertexCacheStatistics vcs0 = meshopt_analyzeVertexCache(&indices[lod_index_offsets[0]], lod_index_counts[0], vertices.size(), kCacheSize, 0, 0);
  395. meshopt_VertexFetchStatistics vfs0 = meshopt_analyzeVertexFetch(&indices[lod_index_offsets[0]], lod_index_counts[0], vertices.size(), sizeof(Vertex));
  396. meshopt_VertexCacheStatistics vcsN = meshopt_analyzeVertexCache(&indices[lod_index_offsets[lod_count - 1]], lod_index_counts[lod_count - 1], vertices.size(), kCacheSize, 0, 0);
  397. meshopt_VertexFetchStatistics vfsN = meshopt_analyzeVertexFetch(&indices[lod_index_offsets[lod_count - 1]], lod_index_counts[lod_count - 1], vertices.size(), sizeof(Vertex));
  398. typedef PackedVertexOct PV;
  399. std::vector<PV> pv(vertices.size());
  400. packMesh(pv, vertices);
  401. std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(vertices.size(), sizeof(PV)));
  402. vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pv[0], vertices.size(), sizeof(PV)));
  403. std::vector<unsigned char> ibuf(meshopt_encodeIndexBufferBound(indices.size(), vertices.size()));
  404. ibuf.resize(meshopt_encodeIndexBuffer(&ibuf[0], ibuf.size(), &indices[0], indices.size()));
  405. printf("%-9s ACMR %f...%f Overfetch %f..%f Codec VB %.1f bits/vertex IB %.1f bits/triangle\n",
  406. "",
  407. vcs0.acmr, vcsN.acmr, vfs0.overfetch, vfsN.overfetch,
  408. double(vbuf.size()) / double(vertices.size()) * 8,
  409. double(ibuf.size()) / double(indices.size() / 3) * 8);
  410. }
  411. }
  412. void optimize(const Mesh& mesh, const char* name, void (*optf)(Mesh& mesh))
  413. {
  414. Mesh copy = mesh;
  415. double start = timestamp();
  416. optf(copy);
  417. double end = timestamp();
  418. assert(isMeshValid(copy));
  419. assert(hashMesh(mesh) == hashMesh(copy));
  420. meshopt_VertexCacheStatistics vcs = meshopt_analyzeVertexCache(&copy.indices[0], copy.indices.size(), copy.vertices.size(), kCacheSize, 0, 0);
  421. meshopt_VertexFetchStatistics vfs = meshopt_analyzeVertexFetch(&copy.indices[0], copy.indices.size(), copy.vertices.size(), sizeof(Vertex));
  422. meshopt_OverdrawStatistics os = meshopt_analyzeOverdraw(&copy.indices[0], copy.indices.size(), &copy.vertices[0].px, copy.vertices.size(), sizeof(Vertex));
  423. meshopt_VertexCacheStatistics vcs_nv = meshopt_analyzeVertexCache(&copy.indices[0], copy.indices.size(), copy.vertices.size(), 32, 32, 32);
  424. meshopt_VertexCacheStatistics vcs_amd = meshopt_analyzeVertexCache(&copy.indices[0], copy.indices.size(), copy.vertices.size(), 14, 64, 128);
  425. meshopt_VertexCacheStatistics vcs_intel = meshopt_analyzeVertexCache(&copy.indices[0], copy.indices.size(), copy.vertices.size(), 128, 0, 0);
  426. printf("%-9s: ACMR %f ATVR %f (NV %f AMD %f Intel %f) Overfetch %f Overdraw %f in %.2f msec\n", name, vcs.acmr, vcs.atvr, vcs_nv.atvr, vcs_amd.atvr, vcs_intel.atvr, vfs.overfetch, os.overdraw, (end - start) * 1000);
  427. }
  428. template <typename T>
  429. size_t compress(const std::vector<T>& data)
  430. {
  431. std::vector<unsigned char> cbuf(tdefl_compress_bound(data.size() * sizeof(T)));
  432. unsigned int flags = tdefl_create_comp_flags_from_zip_params(MZ_DEFAULT_LEVEL, 15, MZ_DEFAULT_STRATEGY);
  433. return tdefl_compress_mem_to_mem(&cbuf[0], cbuf.size(), &data[0], data.size() * sizeof(T), flags);
  434. }
  435. void encodeIndex(const Mesh& mesh)
  436. {
  437. // allocate result outside of the timing loop to exclude memset() from decode timing
  438. std::vector<unsigned int> result(mesh.indices.size());
  439. double start = timestamp();
  440. std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(mesh.indices.size(), mesh.vertices.size()));
  441. buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), &mesh.indices[0], mesh.indices.size()));
  442. double middle = timestamp();
  443. int res = meshopt_decodeIndexBuffer(&result[0], mesh.indices.size(), &buffer[0], buffer.size());
  444. assert(res == 0);
  445. (void)res;
  446. double end = timestamp();
  447. size_t csize = compress(buffer);
  448. for (size_t i = 0; i < mesh.indices.size(); i += 3)
  449. {
  450. assert(
  451. (result[i + 0] == mesh.indices[i + 0] && result[i + 1] == mesh.indices[i + 1] && result[i + 2] == mesh.indices[i + 2]) ||
  452. (result[i + 1] == mesh.indices[i + 0] && result[i + 2] == mesh.indices[i + 1] && result[i + 0] == mesh.indices[i + 2]) ||
  453. (result[i + 2] == mesh.indices[i + 0] && result[i + 0] == mesh.indices[i + 1] && result[i + 1] == mesh.indices[i + 2]));
  454. }
  455. printf("IdxCodec : %.1f bits/triangle (post-deflate %.1f bits/triangle); encode %.2f msec, decode %.2f msec (%.2f GB/s)\n",
  456. double(buffer.size() * 8) / double(mesh.indices.size() / 3),
  457. double(csize * 8) / double(mesh.indices.size() / 3),
  458. (middle - start) * 1000,
  459. (end - middle) * 1000,
  460. (double(result.size() * 4) / (1 << 30)) / (end - middle));
  461. }
  462. template <typename PV>
  463. void packVertex(const Mesh& mesh, const char* pvn)
  464. {
  465. std::vector<PV> pv(mesh.vertices.size());
  466. packMesh(pv, mesh.vertices);
  467. size_t csize = compress(pv);
  468. printf("VtxPack%s : %.1f bits/vertex (post-deflate %.1f bits/vertex)\n", pvn,
  469. double(pv.size() * sizeof(PV) * 8) / double(mesh.vertices.size()),
  470. double(csize * 8) / double(mesh.vertices.size()));
  471. }
  472. template <typename PV>
  473. void encodeVertex(const Mesh& mesh, const char* pvn)
  474. {
  475. std::vector<PV> pv(mesh.vertices.size());
  476. packMesh(pv, mesh.vertices);
  477. // allocate result outside of the timing loop to exclude memset() from decode timing
  478. std::vector<PV> result(mesh.vertices.size());
  479. double start = timestamp();
  480. std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(mesh.vertices.size(), sizeof(PV)));
  481. vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pv[0], mesh.vertices.size(), sizeof(PV)));
  482. double middle = timestamp();
  483. int res = meshopt_decodeVertexBuffer(&result[0], mesh.vertices.size(), sizeof(PV), &vbuf[0], vbuf.size());
  484. assert(res == 0);
  485. (void)res;
  486. double end = timestamp();
  487. assert(memcmp(&pv[0], &result[0], pv.size() * sizeof(PV)) == 0);
  488. size_t csize = compress(vbuf);
  489. printf("VtxCodec%1s: %.1f bits/vertex (post-deflate %.1f bits/vertex); encode %.2f msec, decode %.2f msec (%.2f GB/s)\n", pvn,
  490. double(vbuf.size() * 8) / double(mesh.vertices.size()),
  491. double(csize * 8) / double(mesh.vertices.size()),
  492. (middle - start) * 1000,
  493. (end - middle) * 1000,
  494. (double(result.size() * sizeof(PV)) / (1 << 30)) / (end - middle));
  495. }
  496. void stripify(const Mesh& mesh, bool use_restart)
  497. {
  498. unsigned int restart_index = use_restart ? ~0u : 0;
  499. // note: input mesh is assumed to be optimized for vertex cache and vertex fetch
  500. double start = timestamp();
  501. std::vector<unsigned int> strip(meshopt_stripifyBound(mesh.indices.size()));
  502. strip.resize(meshopt_stripify(&strip[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size(), restart_index));
  503. double end = timestamp();
  504. Mesh copy = mesh;
  505. copy.indices.resize(meshopt_unstripify(&copy.indices[0], &strip[0], strip.size(), restart_index));
  506. assert(copy.indices.size() <= meshopt_unstripifyBound(strip.size()));
  507. assert(isMeshValid(copy));
  508. assert(hashMesh(mesh) == hashMesh(copy));
  509. meshopt_VertexCacheStatistics vcs = meshopt_analyzeVertexCache(&copy.indices[0], mesh.indices.size(), mesh.vertices.size(), kCacheSize, 0, 0);
  510. meshopt_VertexCacheStatistics vcs_nv = meshopt_analyzeVertexCache(&copy.indices[0], mesh.indices.size(), mesh.vertices.size(), 32, 32, 32);
  511. meshopt_VertexCacheStatistics vcs_amd = meshopt_analyzeVertexCache(&copy.indices[0], mesh.indices.size(), mesh.vertices.size(), 14, 64, 128);
  512. meshopt_VertexCacheStatistics vcs_intel = meshopt_analyzeVertexCache(&copy.indices[0], mesh.indices.size(), mesh.vertices.size(), 128, 0, 0);
  513. printf("Stripify%c: ACMR %f ATVR %f (NV %f AMD %f Intel %f); %d strip indices (%.1f%%) in %.2f msec\n",
  514. use_restart ? 'R' : ' ',
  515. vcs.acmr, vcs.atvr, vcs_nv.atvr, vcs_amd.atvr, vcs_intel.atvr,
  516. int(strip.size()), double(strip.size()) / double(mesh.indices.size()) * 100,
  517. (end - start) * 1000);
  518. }
  519. void shadow(const Mesh& mesh)
  520. {
  521. // note: input mesh is assumed to be optimized for vertex cache and vertex fetch
  522. double start = timestamp();
  523. // this index buffer can be used for position-only rendering using the same vertex data that the original index buffer uses
  524. std::vector<unsigned int> shadow_indices(mesh.indices.size());
  525. meshopt_generateShadowIndexBuffer(&shadow_indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(float) * 3, sizeof(Vertex));
  526. double end = timestamp();
  527. // while you can't optimize the vertex data after shadow IB was constructed, you can and should optimize the shadow IB for vertex cache
  528. // this is valuable even if the original indices array was optimized for vertex cache!
  529. meshopt_optimizeVertexCache(&shadow_indices[0], &shadow_indices[0], shadow_indices.size(), mesh.vertices.size());
  530. meshopt_VertexCacheStatistics vcs = meshopt_analyzeVertexCache(&mesh.indices[0], mesh.indices.size(), mesh.vertices.size(), kCacheSize, 0, 0);
  531. meshopt_VertexCacheStatistics vcss = meshopt_analyzeVertexCache(&shadow_indices[0], shadow_indices.size(), mesh.vertices.size(), kCacheSize, 0, 0);
  532. std::vector<char> shadow_flags(mesh.vertices.size());
  533. size_t shadow_vertices = 0;
  534. for (size_t i = 0; i < shadow_indices.size(); ++i)
  535. {
  536. unsigned int index = shadow_indices[i];
  537. shadow_vertices += 1 - shadow_flags[index];
  538. shadow_flags[index] = 1;
  539. }
  540. printf("ShadowIB : ACMR %f (%.2fx improvement); %d shadow vertices (%.2fx improvement) in %.2f msec\n",
  541. vcss.acmr, double(vcs.vertices_transformed) / double(vcss.vertices_transformed),
  542. int(shadow_vertices), double(mesh.vertices.size()) / double(shadow_vertices),
  543. (end - start) * 1000);
  544. }
  545. void meshlets(const Mesh& mesh)
  546. {
  547. const size_t max_vertices = 64;
  548. const size_t max_triangles = 126;
  549. // note: input mesh is assumed to be optimized for vertex cache and vertex fetch
  550. double start = timestamp();
  551. std::vector<meshopt_Meshlet> meshlets(meshopt_buildMeshletsBound(mesh.indices.size(), max_vertices, max_triangles));
  552. meshlets.resize(meshopt_buildMeshlets(&meshlets[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size(), max_vertices, max_triangles));
  553. double end = timestamp();
  554. double avg_vertices = 0;
  555. double avg_triangles = 0;
  556. size_t not_full = 0;
  557. for (size_t i = 0; i < meshlets.size(); ++i)
  558. {
  559. const meshopt_Meshlet& m = meshlets[i];
  560. avg_vertices += m.vertex_count;
  561. avg_triangles += m.triangle_count;
  562. not_full += m.vertex_count < max_vertices;
  563. }
  564. avg_vertices /= double(meshlets.size());
  565. avg_triangles /= double(meshlets.size());
  566. printf("Meshlets : %d meshlets (avg vertices %.1f, avg triangles %.1f, not full %d) in %.2f msec\n",
  567. int(meshlets.size()), avg_vertices, avg_triangles, int(not_full), (end - start) * 1000);
  568. float camera[3] = {100, 100, 100};
  569. size_t rejected = 0;
  570. size_t rejected_s8 = 0;
  571. size_t rejected_alt = 0;
  572. size_t rejected_alt_s8 = 0;
  573. size_t accepted = 0;
  574. size_t accepted_s8 = 0;
  575. double startc = timestamp();
  576. for (size_t i = 0; i < meshlets.size(); ++i)
  577. {
  578. meshopt_Bounds bounds = meshopt_computeMeshletBounds(&meshlets[i], &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
  579. // trivial accept: we can't ever backface cull this meshlet
  580. accepted += (bounds.cone_cutoff >= 1);
  581. accepted_s8 += (bounds.cone_cutoff_s8 >= 127);
  582. // perspective projection: dot(normalize(cone_apex - camera_position), cone_axis) > cone_cutoff
  583. float mview[3] = {bounds.cone_apex[0] - camera[0], bounds.cone_apex[1] - camera[1], bounds.cone_apex[2] - camera[2]};
  584. float mviewlength = sqrtf(mview[0] * mview[0] + mview[1] * mview[1] + mview[2] * mview[2]);
  585. rejected += mview[0] * bounds.cone_axis[0] + mview[1] * bounds.cone_axis[1] + mview[2] * bounds.cone_axis[2] >= bounds.cone_cutoff * mviewlength;
  586. rejected_s8 += mview[0] * (bounds.cone_axis_s8[0] / 127.f) + mview[1] * (bounds.cone_axis_s8[1] / 127.f) + mview[2] * (bounds.cone_axis_s8[2] / 127.f) >= (bounds.cone_cutoff_s8 / 127.f) * mviewlength;
  587. // alternative formulation for perspective projection that doesn't use apex (and uses cluster bounding sphere instead):
  588. // dot(normalize(center - camera_position), cone_axis) > cone_cutoff + radius / length(center - camera_position)
  589. float cview[3] = {bounds.center[0] - camera[0], bounds.center[1] - camera[1], bounds.center[2] - camera[2]};
  590. float cviewlength = sqrtf(cview[0] * cview[0] + cview[1] * cview[1] + cview[2] * cview[2]);
  591. rejected_alt += cview[0] * bounds.cone_axis[0] + cview[1] * bounds.cone_axis[1] + cview[2] * bounds.cone_axis[2] >= bounds.cone_cutoff * cviewlength + bounds.radius;
  592. rejected_alt_s8 += cview[0] * (bounds.cone_axis_s8[0] / 127.f) + cview[1] * (bounds.cone_axis_s8[1] / 127.f) + cview[2] * (bounds.cone_axis_s8[2] / 127.f) >= (bounds.cone_cutoff_s8 / 127.f) * cviewlength + bounds.radius;
  593. }
  594. double endc = timestamp();
  595. printf("ConeCull : rejected apex %d (%.1f%%) / center %d (%.1f%%), trivially accepted %d (%.1f%%) in %.2f msec\n",
  596. int(rejected), double(rejected) / double(meshlets.size()) * 100,
  597. int(rejected_alt), double(rejected_alt) / double(meshlets.size()) * 100,
  598. int(accepted), double(accepted) / double(meshlets.size()) * 100,
  599. (endc - startc) * 1000);
  600. printf("ConeCull8: rejected apex %d (%.1f%%) / center %d (%.1f%%), trivially accepted %d (%.1f%%) in %.2f msec\n",
  601. int(rejected_s8), double(rejected_s8) / double(meshlets.size()) * 100,
  602. int(rejected_alt_s8), double(rejected_alt_s8) / double(meshlets.size()) * 100,
  603. int(accepted_s8), double(accepted_s8) / double(meshlets.size()) * 100,
  604. (endc - startc) * 1000);
  605. }
  606. void spatialSort(const Mesh& mesh)
  607. {
  608. typedef PackedVertexOct PV;
  609. std::vector<PV> pv(mesh.vertices.size());
  610. packMesh(pv, mesh.vertices);
  611. double start = timestamp();
  612. std::vector<unsigned int> remap(mesh.vertices.size());
  613. meshopt_spatialSortRemap(&remap[0], &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
  614. double end = timestamp();
  615. meshopt_remapVertexBuffer(&pv[0], &pv[0], mesh.vertices.size(), sizeof(PV), &remap[0]);
  616. std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(mesh.vertices.size(), sizeof(PV)));
  617. vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pv[0], mesh.vertices.size(), sizeof(PV)));
  618. size_t csize = compress(vbuf);
  619. printf("Spatial : %.1f bits/vertex (post-deflate %.1f bits/vertex); sort %.2f msec\n",
  620. double(vbuf.size() * 8) / double(mesh.vertices.size()),
  621. double(csize * 8) / double(mesh.vertices.size()),
  622. (end - start) * 1000);
  623. }
  624. void spatialSortTriangles(const Mesh& mesh)
  625. {
  626. typedef PackedVertexOct PV;
  627. Mesh copy = mesh;
  628. double start = timestamp();
  629. meshopt_spatialSortTriangles(&copy.indices[0], &copy.indices[0], mesh.indices.size(), &copy.vertices[0].px, copy.vertices.size(), sizeof(Vertex));
  630. double end = timestamp();
  631. meshopt_optimizeVertexCache(&copy.indices[0], &copy.indices[0], copy.indices.size(), copy.vertices.size());
  632. meshopt_optimizeVertexFetch(&copy.vertices[0], &copy.indices[0], copy.indices.size(), &copy.vertices[0], copy.vertices.size(), sizeof(Vertex));
  633. std::vector<PV> pv(mesh.vertices.size());
  634. packMesh(pv, copy.vertices);
  635. std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(mesh.vertices.size(), sizeof(PV)));
  636. vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pv[0], mesh.vertices.size(), sizeof(PV)));
  637. std::vector<unsigned char> ibuf(meshopt_encodeIndexBufferBound(mesh.indices.size(), mesh.vertices.size()));
  638. ibuf.resize(meshopt_encodeIndexBuffer(&ibuf[0], ibuf.size(), &copy.indices[0], mesh.indices.size()));
  639. size_t csizev = compress(vbuf);
  640. size_t csizei = compress(ibuf);
  641. printf("SpatialT : %.1f bits/vertex (post-deflate %.1f bits/vertex); %.1f bits/triangle (post-deflate %.1f bits/triangle); sort %.2f msec\n",
  642. double(vbuf.size() * 8) / double(mesh.vertices.size()),
  643. double(csizev * 8) / double(mesh.vertices.size()),
  644. double(ibuf.size() * 8) / double(mesh.indices.size() / 3),
  645. double(csizei * 8) / double(mesh.indices.size() / 3),
  646. (end - start) * 1000);
  647. }
  648. bool loadMesh(Mesh& mesh, const char* path)
  649. {
  650. double start = timestamp();
  651. double middle;
  652. mesh = parseObj(path, middle);
  653. double end = timestamp();
  654. if (mesh.vertices.empty())
  655. {
  656. printf("Mesh %s is empty, skipping\n", path);
  657. return false;
  658. }
  659. printf("# %s: %d vertices, %d triangles; read in %.2f msec; indexed in %.2f msec\n", path, int(mesh.vertices.size()), int(mesh.indices.size() / 3), (middle - start) * 1000, (end - middle) * 1000);
  660. return true;
  661. }
  662. void processDeinterleaved(const char* path)
  663. {
  664. // Most algorithms in the library work out of the box with deinterleaved geometry, but some require slightly special treatment;
  665. // this code runs a simplified version of complete opt. pipeline using deinterleaved geo. There's no compression performed but you
  666. // can trivially run it by quantizing all elements and running meshopt_encodeVertexBuffer once for each vertex stream.
  667. fastObjMesh* obj = fast_obj_read(path);
  668. if (!obj)
  669. {
  670. printf("Error loading %s: file not found\n", path);
  671. return;
  672. }
  673. size_t total_indices = 0;
  674. for (unsigned int i = 0; i < obj->face_count; ++i)
  675. total_indices += 3 * (obj->face_vertices[i] - 2);
  676. std::vector<float> unindexed_pos(total_indices * 3);
  677. std::vector<float> unindexed_nrm(total_indices * 3);
  678. std::vector<float> unindexed_uv(total_indices * 2);
  679. size_t vertex_offset = 0;
  680. size_t index_offset = 0;
  681. for (unsigned int i = 0; i < obj->face_count; ++i)
  682. {
  683. for (unsigned int j = 0; j < obj->face_vertices[i]; ++j)
  684. {
  685. fastObjIndex gi = obj->indices[index_offset + j];
  686. // triangulate polygon on the fly; offset-3 is always the first polygon vertex
  687. if (j >= 3)
  688. {
  689. memcpy(&unindexed_pos[(vertex_offset + 0) * 3], &unindexed_pos[(vertex_offset - 3) * 3], 3 * sizeof(float));
  690. memcpy(&unindexed_nrm[(vertex_offset + 0) * 3], &unindexed_nrm[(vertex_offset - 3) * 3], 3 * sizeof(float));
  691. memcpy(&unindexed_uv[(vertex_offset + 0) * 2], &unindexed_uv[(vertex_offset - 3) * 2], 2 * sizeof(float));
  692. memcpy(&unindexed_pos[(vertex_offset + 1) * 3], &unindexed_pos[(vertex_offset - 1) * 3], 3 * sizeof(float));
  693. memcpy(&unindexed_nrm[(vertex_offset + 1) * 3], &unindexed_nrm[(vertex_offset - 1) * 3], 3 * sizeof(float));
  694. memcpy(&unindexed_uv[(vertex_offset + 1) * 2], &unindexed_uv[(vertex_offset - 1) * 2], 2 * sizeof(float));
  695. vertex_offset += 2;
  696. }
  697. memcpy(&unindexed_pos[vertex_offset * 3], &obj->positions[gi.p * 3], 3 * sizeof(float));
  698. memcpy(&unindexed_nrm[vertex_offset * 3], &obj->normals[gi.n * 3], 3 * sizeof(float));
  699. memcpy(&unindexed_uv[vertex_offset * 2], &obj->texcoords[gi.t * 2], 2 * sizeof(float));
  700. vertex_offset++;
  701. }
  702. index_offset += obj->face_vertices[i];
  703. }
  704. fast_obj_destroy(obj);
  705. double start = timestamp();
  706. meshopt_Stream streams[] = {
  707. {&unindexed_pos[0], sizeof(float) * 3, sizeof(float) * 3},
  708. {&unindexed_nrm[0], sizeof(float) * 3, sizeof(float) * 3},
  709. {&unindexed_uv[0], sizeof(float) * 2, sizeof(float) * 2},
  710. };
  711. std::vector<unsigned int> remap(total_indices);
  712. size_t total_vertices = meshopt_generateVertexRemapMulti(&remap[0], NULL, total_indices, total_indices, streams, sizeof(streams) / sizeof(streams[0]));
  713. std::vector<unsigned int> indices(total_indices);
  714. meshopt_remapIndexBuffer(&indices[0], NULL, total_indices, &remap[0]);
  715. std::vector<float> pos(total_vertices * 3);
  716. meshopt_remapVertexBuffer(&pos[0], &unindexed_pos[0], total_indices, sizeof(float) * 3, &remap[0]);
  717. std::vector<float> nrm(total_vertices * 3);
  718. meshopt_remapVertexBuffer(&nrm[0], &unindexed_nrm[0], total_indices, sizeof(float) * 3, &remap[0]);
  719. std::vector<float> uv(total_vertices * 2);
  720. meshopt_remapVertexBuffer(&uv[0], &unindexed_uv[0], total_indices, sizeof(float) * 2, &remap[0]);
  721. double reindex = timestamp();
  722. meshopt_optimizeVertexCache(&indices[0], &indices[0], total_indices, total_vertices);
  723. meshopt_optimizeVertexFetchRemap(&remap[0], &indices[0], total_indices, total_vertices);
  724. meshopt_remapVertexBuffer(&pos[0], &pos[0], total_vertices, sizeof(float) * 3, &remap[0]);
  725. meshopt_remapVertexBuffer(&nrm[0], &nrm[0], total_vertices, sizeof(float) * 3, &remap[0]);
  726. meshopt_remapVertexBuffer(&uv[0], &uv[0], total_vertices, sizeof(float) * 2, &remap[0]);
  727. double optimize = timestamp();
  728. // note: since shadow index buffer is computed based on regular vertex/index buffer, the stream points at the indexed data - not unindexed_pos
  729. meshopt_Stream shadow_stream = {&pos[0], sizeof(float) * 3, sizeof(float) * 3};
  730. std::vector<unsigned int> shadow_indices(total_indices);
  731. meshopt_generateShadowIndexBufferMulti(&shadow_indices[0], &indices[0], total_indices, total_vertices, &shadow_stream, 1);
  732. meshopt_optimizeVertexCache(&shadow_indices[0], &shadow_indices[0], total_indices, total_vertices);
  733. double shadow = timestamp();
  734. printf("Deintrlvd: %d vertices, reindexed in %.2f msec, optimized in %.2f msec, generated & optimized shadow indices in %.2f msec\n",
  735. int(total_vertices), (reindex - start) * 1000, (optimize - reindex) * 1000, (shadow - optimize) * 1000);
  736. }
  737. void process(const char* path)
  738. {
  739. Mesh mesh;
  740. if (!loadMesh(mesh, path))
  741. return;
  742. optimize(mesh, "Original", optNone);
  743. optimize(mesh, "Random", optRandomShuffle);
  744. optimize(mesh, "Cache", optCache);
  745. optimize(mesh, "CacheFifo", optCacheFifo);
  746. optimize(mesh, "Overdraw", optOverdraw);
  747. optimize(mesh, "Fetch", optFetch);
  748. optimize(mesh, "FetchMap", optFetchRemap);
  749. optimize(mesh, "Complete", optComplete);
  750. Mesh copy = mesh;
  751. meshopt_optimizeVertexCache(&copy.indices[0], &copy.indices[0], copy.indices.size(), copy.vertices.size());
  752. meshopt_optimizeVertexFetch(&copy.vertices[0], &copy.indices[0], copy.indices.size(), &copy.vertices[0], copy.vertices.size(), sizeof(Vertex));
  753. stripify(copy, false);
  754. stripify(copy, true);
  755. meshlets(copy);
  756. shadow(copy);
  757. encodeIndex(copy);
  758. packVertex<PackedVertex>(copy, "");
  759. encodeVertex<PackedVertex>(copy, "");
  760. encodeVertex<PackedVertexOct>(copy, "O");
  761. simplify(mesh);
  762. simplifySloppy(mesh);
  763. simplifyComplete(mesh);
  764. simplifyPoints(mesh);
  765. spatialSort(mesh);
  766. spatialSortTriangles(mesh);
  767. if (path)
  768. processDeinterleaved(path);
  769. }
  770. void processDev(const char* path)
  771. {
  772. Mesh mesh;
  773. if (!loadMesh(mesh, path))
  774. return;
  775. Mesh copy = mesh;
  776. meshopt_optimizeVertexCache(&copy.indices[0], &copy.indices[0], copy.indices.size(), copy.vertices.size());
  777. meshopt_optimizeVertexFetch(&copy.vertices[0], &copy.indices[0], copy.indices.size(), &copy.vertices[0], copy.vertices.size(), sizeof(Vertex));
  778. encodeIndex(copy);
  779. encodeVertex<PackedVertex>(copy, "");
  780. encodeVertex<PackedVertexOct>(copy, "O");
  781. }
  782. int main(int argc, char** argv)
  783. {
  784. void runTests();
  785. if (argc == 1)
  786. {
  787. runTests();
  788. }
  789. else
  790. {
  791. if (strcmp(argv[1], "-d") == 0)
  792. {
  793. for (int i = 2; i < argc; ++i)
  794. {
  795. processDev(argv[i]);
  796. }
  797. }
  798. else
  799. {
  800. for (int i = 1; i < argc; ++i)
  801. {
  802. process(argv[i]);
  803. }
  804. runTests();
  805. }
  806. }
  807. }