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