lodviewer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include "../src/meshoptimizer.h"
  3. #include "objparser.h"
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <ctime>
  8. #include <vector>
  9. #include <GLFW/glfw3.h>
  10. #ifdef GLTF
  11. #define CGLTF_IMPLEMENTATION
  12. #include "cgltf.h"
  13. #endif
  14. #ifdef _WIN32
  15. #pragma comment(lib, "opengl32.lib")
  16. #endif
  17. extern unsigned char* meshopt_simplifyDebugKind;
  18. extern unsigned int* meshopt_simplifyDebugLoop;
  19. #ifndef TRACE
  20. unsigned char* meshopt_simplifyDebugKind;
  21. unsigned int* meshopt_simplifyDebugLoop;
  22. #endif
  23. struct Options
  24. {
  25. bool wireframe;
  26. enum
  27. {
  28. Mode_Default,
  29. Mode_Texture,
  30. Mode_Normals,
  31. Mode_UV,
  32. Mode_Kind,
  33. } mode;
  34. };
  35. struct Vertex
  36. {
  37. float px, py, pz;
  38. float nx, ny, nz;
  39. float tx, ty;
  40. };
  41. struct Mesh
  42. {
  43. std::vector<Vertex> vertices;
  44. std::vector<unsigned int> indices;
  45. // TODO: this is debug only visualization and will go away at some point
  46. std::vector<unsigned char> kinds;
  47. std::vector<unsigned int> loop;
  48. };
  49. Mesh parseObj(const char* path)
  50. {
  51. ObjFile file;
  52. if (!objParseFile(file, path) || !objValidate(file))
  53. {
  54. printf("Error loading %s\n", path);
  55. return Mesh();
  56. }
  57. size_t total_indices = file.f_size / 3;
  58. std::vector<Vertex> vertices(total_indices);
  59. for (size_t i = 0; i < total_indices; ++i)
  60. {
  61. int vi = file.f[i * 3 + 0];
  62. int vti = file.f[i * 3 + 1];
  63. int vni = file.f[i * 3 + 2];
  64. Vertex v =
  65. {
  66. file.v[vi * 3 + 0],
  67. file.v[vi * 3 + 1],
  68. file.v[vi * 3 + 2],
  69. vni >= 0 ? file.vn[vni * 3 + 0] : 0,
  70. vni >= 0 ? file.vn[vni * 3 + 1] : 0,
  71. vni >= 0 ? file.vn[vni * 3 + 2] : 0,
  72. vti >= 0 ? file.vt[vti * 3 + 0] : 0,
  73. vti >= 0 ? file.vt[vti * 3 + 1] : 0,
  74. };
  75. vertices[i] = v;
  76. }
  77. Mesh result;
  78. std::vector<unsigned int> remap(total_indices);
  79. size_t total_vertices = meshopt_generateVertexRemap(&remap[0], NULL, total_indices, &vertices[0], total_indices, sizeof(Vertex));
  80. result.indices.resize(total_indices);
  81. meshopt_remapIndexBuffer(&result.indices[0], NULL, total_indices, &remap[0]);
  82. result.vertices.resize(total_vertices);
  83. meshopt_remapVertexBuffer(&result.vertices[0], &vertices[0], total_indices, sizeof(Vertex), &remap[0]);
  84. return result;
  85. }
  86. #ifdef GLTF
  87. cgltf_accessor* getAccessor(const cgltf_attribute* attributes, size_t attribute_count, cgltf_attribute_type type, int index = 0)
  88. {
  89. for (size_t i = 0; i < attribute_count; ++i)
  90. if (attributes[i].type == type && attributes[i].index == index)
  91. return attributes[i].data;
  92. return 0;
  93. }
  94. template <typename T>
  95. const T* getComponentPtr(const cgltf_accessor* a)
  96. {
  97. const char* buffer = (char*)a->buffer_view->buffer->data;
  98. size_t offset = a->offset + a->buffer_view->offset;
  99. return reinterpret_cast<const T*>(&buffer[offset]);
  100. }
  101. Mesh parseGltf(const char* path)
  102. {
  103. cgltf_options options = {};
  104. cgltf_data* data = 0;
  105. cgltf_result res = cgltf_parse_file(&options, path, &data);
  106. if (res != cgltf_result_success)
  107. {
  108. return Mesh();
  109. }
  110. res = cgltf_load_buffers(&options, data, path);
  111. if (res != cgltf_result_success)
  112. {
  113. cgltf_free(data);
  114. return Mesh();
  115. }
  116. res = cgltf_validate(data);
  117. if (res != cgltf_result_success)
  118. {
  119. cgltf_free(data);
  120. return Mesh();
  121. }
  122. size_t total_vertices = 0;
  123. size_t total_indices = 0;
  124. for (size_t ni = 0; ni < data->nodes_count; ++ni)
  125. {
  126. if (!data->nodes[ni].mesh)
  127. continue;
  128. const cgltf_mesh& mesh = *data->nodes[ni].mesh;
  129. for (size_t pi = 0; pi < mesh.primitives_count; ++pi)
  130. {
  131. const cgltf_primitive& primitive = mesh.primitives[pi];
  132. cgltf_accessor* ai = primitive.indices;
  133. cgltf_accessor* ap = getAccessor(primitive.attributes, primitive.attributes_count, cgltf_attribute_type_position);
  134. if (!ai || !ap)
  135. continue;
  136. total_vertices += ap->count;
  137. total_indices += ai->count;
  138. }
  139. }
  140. Mesh result;
  141. result.vertices.resize(total_vertices);
  142. result.indices.resize(total_indices);
  143. size_t vertex_offset = 0;
  144. size_t index_offset = 0;
  145. for (size_t ni = 0; ni < data->nodes_count; ++ni)
  146. {
  147. if (!data->nodes[ni].mesh)
  148. continue;
  149. const cgltf_mesh& mesh = *data->nodes[ni].mesh;
  150. float transform[16];
  151. cgltf_node_transform_world(&data->nodes[ni], transform);
  152. for (size_t pi = 0; pi < mesh.primitives_count; ++pi)
  153. {
  154. const cgltf_primitive& primitive = mesh.primitives[pi];
  155. cgltf_accessor* ai = primitive.indices;
  156. cgltf_accessor* ap = getAccessor(primitive.attributes, primitive.attributes_count, cgltf_attribute_type_position);
  157. if (!ai || !ap)
  158. continue;
  159. if (ai->component_type == cgltf_component_type_r_32u)
  160. {
  161. const unsigned int* ptr = getComponentPtr<unsigned int>(ai);
  162. for (size_t i = 0; i < ai->count; ++i)
  163. result.indices[index_offset + i] = unsigned(vertex_offset + ptr[i]);
  164. }
  165. else
  166. {
  167. const unsigned short* ptr = getComponentPtr<unsigned short>(ai);
  168. for (size_t i = 0; i < ai->count; ++i)
  169. result.indices[index_offset + i] = unsigned(vertex_offset + ptr[i]);
  170. }
  171. {
  172. const float* ptr = getComponentPtr<float>(ap);
  173. for (size_t i = 0; i < ap->count; ++i)
  174. {
  175. result.vertices[vertex_offset + i].px = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8] + transform[12];
  176. result.vertices[vertex_offset + i].py = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9] + transform[13];
  177. result.vertices[vertex_offset + i].pz = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10] + transform[14];
  178. ptr += ap->stride / 4;
  179. }
  180. }
  181. if (cgltf_accessor* an = getAccessor(primitive.attributes, primitive.attributes_count, cgltf_attribute_type_normal))
  182. {
  183. const float* ptr = getComponentPtr<float>(an);
  184. for (size_t i = 0; i < ap->count; ++i)
  185. {
  186. result.vertices[vertex_offset + i].nx = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8];
  187. result.vertices[vertex_offset + i].ny = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9];
  188. result.vertices[vertex_offset + i].nz = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10];
  189. ptr += an->stride / 4;
  190. }
  191. }
  192. if (cgltf_accessor* at = getAccessor(primitive.attributes, primitive.attributes_count, cgltf_attribute_type_texcoord))
  193. {
  194. const float* ptr = getComponentPtr<float>(at);
  195. for (size_t i = 0; i < ap->count; ++i)
  196. {
  197. result.vertices[vertex_offset + i].tx = ptr[0];
  198. result.vertices[vertex_offset + i].ty = ptr[1];
  199. ptr += at->stride / 4;
  200. }
  201. }
  202. vertex_offset += ap->count;
  203. index_offset += ai->count;
  204. }
  205. }
  206. std::vector<unsigned int> remap(total_indices);
  207. size_t unique_vertices = meshopt_generateVertexRemap(&remap[0], &result.indices[0], total_indices, &result.vertices[0], total_vertices, sizeof(Vertex));
  208. meshopt_remapIndexBuffer(&result.indices[0], &result.indices[0], total_indices, &remap[0]);
  209. meshopt_remapVertexBuffer(&result.vertices[0], &result.vertices[0], total_vertices, sizeof(Vertex), &remap[0]);
  210. result.vertices.resize(unique_vertices);
  211. cgltf_free(data);
  212. return result;
  213. }
  214. #endif
  215. Mesh loadMesh(const char* path)
  216. {
  217. if (strstr(path, ".obj"))
  218. return parseObj(path);
  219. #ifdef GLTF
  220. if (strstr(path, ".gltf") || strstr(path, ".glb"))
  221. return parseGltf(path);
  222. #endif
  223. return Mesh();
  224. }
  225. bool saveObj(const Mesh& mesh, const char* path)
  226. {
  227. std::vector<Vertex> verts = mesh.vertices;
  228. std::vector<unsigned int> tris = mesh.indices;
  229. size_t vertcount = meshopt_optimizeVertexFetch(verts.data(), tris.data(), tris.size(), verts.data(), verts.size(), sizeof(Vertex));
  230. FILE* obj = fopen(path, "w");
  231. if (!obj)
  232. return false;
  233. for (size_t i = 0; i < vertcount; ++i)
  234. {
  235. fprintf(obj, "v %f %f %f\n", verts[i].px, verts[i].py, verts[i].pz);
  236. fprintf(obj, "vn %f %f %f\n", verts[i].nx, verts[i].ny, verts[i].nz);
  237. fprintf(obj, "vt %f %f %f\n", verts[i].tx, verts[i].ty, 0.f);
  238. }
  239. for (size_t i = 0; i < tris.size(); i += 3)
  240. {
  241. unsigned int i0 = tris[i + 0] + 1;
  242. unsigned int i1 = tris[i + 1] + 1;
  243. unsigned int i2 = tris[i + 2] + 1;
  244. fprintf(obj, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", i0, i0, i0, i1, i1, i1, i2, i2, i2);
  245. }
  246. fclose(obj);
  247. return true;
  248. }
  249. Mesh optimize(const Mesh& mesh, int lod)
  250. {
  251. float threshold = powf(0.5f, float(lod));
  252. size_t target_index_count = size_t(mesh.indices.size() * threshold);
  253. float target_error = 1e-2f;
  254. Mesh result = mesh;
  255. result.kinds.resize(result.vertices.size());
  256. result.loop.resize(result.vertices.size());
  257. meshopt_simplifyDebugKind = &result.kinds[0];
  258. meshopt_simplifyDebugLoop = &result.loop[0];
  259. result.indices.resize(meshopt_simplify(&result.indices[0], &result.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_index_count, target_error));
  260. return result;
  261. }
  262. void display(int x, int y, int width, int height, const Mesh& mesh, const Options& options)
  263. {
  264. glViewport(x, y, width, height);
  265. glEnable(GL_DEPTH_TEST);
  266. glDepthFunc(GL_LESS);
  267. glDepthMask(GL_TRUE);
  268. glMatrixMode(GL_MODELVIEW);
  269. glLoadIdentity();
  270. glRotatef(0.f, 0.f, 1.f, 0.f);
  271. glPolygonMode(GL_FRONT_AND_BACK, options.wireframe ? GL_LINE : GL_FILL);
  272. float centerx = 0;
  273. float centery = 0;
  274. float centerz = 0;
  275. float centeru = 0;
  276. float centerv = 0;
  277. for (size_t i = 0; i < mesh.vertices.size(); ++i)
  278. {
  279. const Vertex& v = mesh.vertices[i];
  280. centerx += v.px;
  281. centery += v.py;
  282. centerz += v.pz;
  283. centeru += v.tx;
  284. centerv += v.ty;
  285. }
  286. centerx /= float(mesh.vertices.size());
  287. centery /= float(mesh.vertices.size());
  288. centerz /= float(mesh.vertices.size());
  289. centeru /= float(mesh.vertices.size());
  290. centerv /= float(mesh.vertices.size());
  291. float extent = 0;
  292. float extentuv = 0;
  293. for (size_t i = 0; i < mesh.vertices.size(); ++i)
  294. {
  295. const Vertex& v = mesh.vertices[i];
  296. extent = std::max(extent, fabsf(v.px - centerx));
  297. extent = std::max(extent, fabsf(v.py - centery));
  298. extent = std::max(extent, fabsf(v.pz - centerz));
  299. extentuv = std::max(extentuv, fabsf(v.tx - centeru));
  300. extentuv = std::max(extentuv, fabsf(v.ty - centerv));
  301. }
  302. extent *= 1.1f;
  303. extentuv *= 1.1f;
  304. float scalex = width > height ? float(height) / float(width) : 1;
  305. float scaley = height > width ? float(width) / float(height) : 1;
  306. glBegin(GL_TRIANGLES);
  307. for (size_t i = 0; i < mesh.indices.size(); ++i)
  308. {
  309. const Vertex& v = mesh.vertices[mesh.indices[i]];
  310. float intensity = -(v.pz - centerz) / extent * 0.5f + 0.5f;
  311. switch (options.mode)
  312. {
  313. case Options::Mode_UV:
  314. glColor3f(intensity, intensity, intensity);
  315. glVertex3f((v.tx - centeru) / extentuv * scalex, (v.ty - centerv) / extentuv * scaley, 0);
  316. break;
  317. case Options::Mode_Texture:
  318. glColor3f(v.tx - floorf(v.tx), v.ty - floorf(v.ty), 0.5f);
  319. glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent);
  320. break;
  321. case Options::Mode_Normals:
  322. glColor3f(v.nx * 0.5f + 0.5f, v.ny * 0.5f + 0.5f, v.nz * 0.5f + 0.5f);
  323. glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent);
  324. break;
  325. default:
  326. glColor3f(intensity, intensity, intensity);
  327. glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent);
  328. }
  329. }
  330. glEnd();
  331. float zbias = 1e-3f;
  332. if (options.mode == Options::Mode_Kind && !mesh.kinds.empty() && !mesh.loop.empty())
  333. {
  334. glLineWidth(1);
  335. glBegin(GL_LINES);
  336. for (size_t i = 0; i < mesh.indices.size(); ++i)
  337. {
  338. unsigned int a = mesh.indices[i];
  339. unsigned int b = mesh.loop[a];
  340. if (b != ~0u)
  341. {
  342. const Vertex& v0 = mesh.vertices[a];
  343. const Vertex& v1 = mesh.vertices[b];
  344. unsigned char kind = mesh.kinds[a];
  345. glColor3f(kind == 0 || kind == 4, kind == 0 || kind == 2 || kind == 3, kind == 0 || kind == 1 || kind == 3);
  346. glVertex3f((v0.px - centerx) / extent * scalex, (v0.py - centery) / extent * scaley, (v0.pz - centerz) / extent - zbias);
  347. glVertex3f((v1.px - centerx) / extent * scalex, (v1.py - centery) / extent * scaley, (v1.pz - centerz) / extent - zbias);
  348. }
  349. }
  350. glEnd();
  351. glPointSize(3);
  352. glBegin(GL_POINTS);
  353. for (size_t i = 0; i < mesh.indices.size(); ++i)
  354. {
  355. const Vertex& v = mesh.vertices[mesh.indices[i]];
  356. unsigned char kind = mesh.kinds[mesh.indices[i]];
  357. if (kind != 0)
  358. {
  359. glColor3f(kind == 0 || kind == 4, kind == 0 || kind == 2 || kind == 3, kind == 0 || kind == 1 || kind == 3);
  360. glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent - zbias * 2);
  361. }
  362. }
  363. glEnd();
  364. }
  365. }
  366. void stats(GLFWwindow* window, const char* path, unsigned int triangles, int lod, double time)
  367. {
  368. char title[256];
  369. snprintf(title, sizeof(title), "%s: LOD %d - %d triangles (%.1f msec)", path, lod, triangles, time * 1000);
  370. glfwSetWindowTitle(window, title);
  371. }
  372. struct File
  373. {
  374. Mesh basemesh;
  375. Mesh lodmesh;
  376. const char* path;
  377. };
  378. std::vector<File> files;
  379. Options options;
  380. bool redraw;
  381. void keyhandler(GLFWwindow* window, int key, int scancode, int action, int mods)
  382. {
  383. if (action == GLFW_PRESS)
  384. {
  385. if (key == GLFW_KEY_W)
  386. {
  387. options.wireframe = !options.wireframe;
  388. redraw = true;
  389. }
  390. else if (key == GLFW_KEY_T)
  391. {
  392. options.mode = options.mode == Options::Mode_Texture ? Options::Mode_Default : Options::Mode_Texture;
  393. redraw = true;
  394. }
  395. else if (key == GLFW_KEY_N)
  396. {
  397. options.mode = options.mode == Options::Mode_Normals ? Options::Mode_Default : Options::Mode_Normals;
  398. redraw = true;
  399. }
  400. else if (key == GLFW_KEY_U)
  401. {
  402. options.mode = options.mode == Options::Mode_UV ? Options::Mode_Default : Options::Mode_UV;
  403. redraw = true;
  404. }
  405. else if (key == GLFW_KEY_K)
  406. {
  407. options.mode = options.mode == Options::Mode_Kind ? Options::Mode_Default : Options::Mode_Kind;
  408. redraw = true;
  409. }
  410. else if (key >= GLFW_KEY_0 && key <= GLFW_KEY_9)
  411. {
  412. int lod = int(key - GLFW_KEY_0);
  413. unsigned int triangles = 0;
  414. clock_t start = clock();
  415. for (auto& f : files)
  416. {
  417. f.lodmesh = optimize(f.basemesh, lod);
  418. triangles += unsigned(f.lodmesh.indices.size() / 3);
  419. }
  420. clock_t end = clock();
  421. stats(window, files[0].path, triangles, lod, double(end - start) / CLOCKS_PER_SEC);
  422. redraw = true;
  423. }
  424. else if (key == GLFW_KEY_S)
  425. {
  426. int i = 0;
  427. for (auto& f : files)
  428. {
  429. char path[32];
  430. sprintf(path, "result%d.obj", i);
  431. saveObj(f.lodmesh, path);
  432. printf("Saved LOD of %s to %s\n", f.path, path);
  433. }
  434. }
  435. }
  436. }
  437. void sizehandler(GLFWwindow* window, int width, int height)
  438. {
  439. redraw = true;
  440. }
  441. int main(int argc, char** argv)
  442. {
  443. if (argc <= 1)
  444. {
  445. printf("Usage: %s [.obj files]\n", argv[0]);
  446. return 0;
  447. }
  448. unsigned int basetriangles = 0;
  449. for (int i = 1; i < argc; ++i)
  450. {
  451. files.emplace_back();
  452. File& f = files.back();
  453. f.path = argv[i];
  454. f.basemesh = loadMesh(f.path);
  455. f.lodmesh = optimize(f.basemesh, 0);
  456. basetriangles += unsigned(f.basemesh.indices.size() / 3);
  457. }
  458. glfwInit();
  459. GLFWwindow* window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
  460. glfwMakeContextCurrent(window);
  461. stats(window, files[0].path, basetriangles, 0, 0);
  462. glfwSetKeyCallback(window, keyhandler);
  463. glfwSetWindowSizeCallback(window, sizehandler);
  464. redraw = true;
  465. while (!glfwWindowShouldClose(window))
  466. {
  467. if (redraw)
  468. {
  469. redraw = false;
  470. int width, height;
  471. glfwGetFramebufferSize(window, &width, &height);
  472. glViewport(0, 0, width, height);
  473. glClearDepth(1.f);
  474. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  475. int cols = int(ceil(sqrt(double(files.size()))));
  476. int rows = int(ceil(double(files.size()) / cols));
  477. int tilew = width / cols;
  478. int tileh = height / rows;
  479. for (size_t i = 0; i < files.size(); ++i)
  480. {
  481. File& f = files[i];
  482. int x = int(i) % cols;
  483. int y = int(i) / cols;
  484. display(x * tilew, y * tileh, tilew, tileh, f.lodmesh, options);
  485. }
  486. glfwSwapBuffers(window);
  487. }
  488. glfwWaitEvents();
  489. }
  490. }