geometryc.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. /*
  2. * Copyright 2011-2012 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <bgfx.h>
  6. #include "../../src/vertexdecl.h"
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <algorithm>
  11. #include <vector>
  12. namespace std { namespace tr1 {} using namespace tr1; } // namespace std
  13. #include <unordered_map>
  14. #include <forsythtriangleorderoptimizer.h>
  15. #if 0
  16. # define BX_TRACE(_format, ...) \
  17. do { \
  18. printf(BX_FILE_LINE_LITERAL "BGFX " _format "\n", ##__VA_ARGS__); \
  19. } while(0)
  20. # define BX_WARN(_condition, _format, ...) \
  21. do { \
  22. if (!(_condition) ) \
  23. { \
  24. BX_TRACE(BX_FILE_LINE_LITERAL "WARN " _format, ##__VA_ARGS__); \
  25. } \
  26. } while(0)
  27. # define BX_CHECK(_condition, _format, ...) \
  28. do { \
  29. if (!(_condition) ) \
  30. { \
  31. BX_TRACE(BX_FILE_LINE_LITERAL "CHECK " _format, ##__VA_ARGS__); \
  32. bx::debugBreak(); \
  33. } \
  34. } while(0)
  35. #endif // 0
  36. #define EXPECT(_condition) \
  37. do { \
  38. if (!(_condition) ) \
  39. { \
  40. printf("Error parsing at:\n" BX_FILE_LINE_LITERAL "\nExpected: " #_condition "\n"); \
  41. exit(EXIT_FAILURE); \
  42. } \
  43. } while(0)
  44. #include <bx/bx.h>
  45. #include <bx/debug.h>
  46. #include <bx/countof.h>
  47. #include <bx/commandline.h>
  48. #include <bx/timer.h>
  49. #include <bx/readerwriter.h>
  50. #include <bx/hash.h>
  51. #include <bx/uint32_t.h>
  52. #include "tokenizecmd.h"
  53. #include "bounds.h"
  54. #include "math.h"
  55. struct Vector3
  56. {
  57. float x;
  58. float y;
  59. float z;
  60. };
  61. typedef std::vector<Vector3> Vector3Array;
  62. struct Index3
  63. {
  64. int32_t m_position;
  65. int32_t m_texcoord;
  66. int32_t m_normal;
  67. int32_t m_vertexIndex;
  68. };
  69. typedef std::unordered_map<uint64_t, Index3> Index3Map;
  70. struct Triangle
  71. {
  72. uint64_t m_index[3];
  73. };
  74. typedef std::vector<Triangle> TriangleArray;
  75. struct Group
  76. {
  77. uint32_t m_startTriangle;
  78. uint32_t m_numTriangles;
  79. std::string m_name;
  80. std::string m_material;
  81. };
  82. typedef std::vector<Group> GroupArray;
  83. struct Primitive
  84. {
  85. uint32_t m_startVertex;
  86. uint32_t m_startIndex;
  87. uint32_t m_numVertices;
  88. uint32_t m_numIndices;
  89. std::string m_name;
  90. };
  91. typedef std::vector<Primitive> PrimitiveArray;
  92. static uint32_t s_obbSteps = 17;
  93. #define BGFX_CHUNK_MAGIC_GEO BX_MAKEFOURCC('G', 'E', 'O', 0x0)
  94. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x0)
  95. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  96. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  97. long int fsize(FILE* _file)
  98. {
  99. long int pos = ftell(_file);
  100. fseek(_file, 0L, SEEK_END);
  101. long int size = ftell(_file);
  102. fseek(_file, pos, SEEK_SET);
  103. return size;
  104. }
  105. void triangleReorder(uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices, uint16_t _cacheSize)
  106. {
  107. uint16_t* newIndexList = new uint16_t[_numIndices];
  108. Forsyth::OptimizeFaces(_indices, _numIndices, _numVertices, newIndexList, _cacheSize);
  109. memcpy(_indices, newIndexList, _numIndices*2);
  110. delete [] newIndexList;
  111. }
  112. uint32_t packUint32(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w)
  113. {
  114. union
  115. {
  116. uint32_t ui32;
  117. uint8_t arr[4];
  118. } un;
  119. un.arr[0] = _x;
  120. un.arr[1] = _y;
  121. un.arr[2] = _z;
  122. un.arr[3] = _w;
  123. return un.ui32;
  124. }
  125. void unpackUint32(uint8_t _result[4], uint32_t _packed)
  126. {
  127. union
  128. {
  129. uint32_t ui32;
  130. uint8_t arr[4];
  131. } un;
  132. un.ui32 = _packed;
  133. _result[0] = un.arr[0];
  134. _result[1] = un.arr[1];
  135. _result[2] = un.arr[2];
  136. _result[3] = un.arr[3];
  137. }
  138. uint32_t packF4u(float _x, float _y = 0.0f, float _z = 0.0f, float _w = 0.0f)
  139. {
  140. const uint8_t xx = uint8_t(_x*127.0f + 128.0f);
  141. const uint8_t yy = uint8_t(_y*127.0f + 128.0f);
  142. const uint8_t zz = uint8_t(_z*127.0f + 128.0f);
  143. const uint8_t ww = uint8_t(_w*127.0f + 128.0f);
  144. return packUint32(xx, yy, zz, ww);
  145. }
  146. void unpackF4u(float _result[4], uint32_t _packed)
  147. {
  148. uint8_t unpacked[4];
  149. unpackUint32(unpacked, _packed);
  150. _result[0] = (float(unpacked[0]) - 128.0f)/127.0f;
  151. _result[1] = (float(unpacked[1]) - 128.0f)/127.0f;
  152. _result[2] = (float(unpacked[2]) - 128.0f)/127.0f;
  153. _result[3] = (float(unpacked[3]) - 128.0f)/127.0f;
  154. }
  155. uint32_t packF2h(float _x, float _y)
  156. {
  157. union
  158. {
  159. uint32_t ui32;
  160. uint16_t arr[2];
  161. } un;
  162. un.arr[0] = bx::halfFromFloat(_x);
  163. un.arr[1] = bx::halfFromFloat(_y);
  164. return un.ui32;
  165. }
  166. void unpackF2h(float _result[2], uint32_t _packed)
  167. {
  168. union
  169. {
  170. uint32_t ui32;
  171. uint16_t arr[2];
  172. } un;
  173. un.ui32 = _packed;
  174. _result[0] = bx::halfToFloat(un.arr[0]);
  175. _result[1] = bx::halfToFloat(un.arr[1]);
  176. }
  177. template<typename Ty>
  178. void calcTangents(const uint16_t* _indices, uint32_t _numIndices, Ty* _vertices, uint16_t _numVertices)
  179. {
  180. float* tangents = new float[6*_numVertices];
  181. memset(tangents, 0, 6*_numVertices*sizeof(float) );
  182. for (uint32_t ii = 0, num = _numIndices/3; ii < num; ++ii)
  183. {
  184. const uint16_t* indices = &_indices[ii*3];
  185. const Ty& v0 = _vertices[indices[0] ];
  186. const Ty& v1 = _vertices[indices[1] ];
  187. const Ty& v2 = _vertices[indices[2] ];
  188. const float bax = v1.m_x - v0.m_x;
  189. const float bay = v1.m_y - v0.m_y;
  190. const float baz = v1.m_z - v0.m_z;
  191. const float bau = v1.m_u - v0.m_u;
  192. const float bav = v1.m_v - v0.m_v;
  193. const float cax = v2.m_x - v0.m_x;
  194. const float cay = v2.m_y - v0.m_y;
  195. const float caz = v2.m_z - v0.m_z;
  196. const float cau = v2.m_u - v0.m_u;
  197. const float cav = v2.m_v - v0.m_v;
  198. const float det = (bau * cav - bav * cau);
  199. const float invDet = 1.0f / det;
  200. const float tx = (bax * cav - cax * bav) * invDet;
  201. const float ty = (bay * cav - cay * bav) * invDet;
  202. const float tz = (baz * cav - caz * bav) * invDet;
  203. const float bx = (cax * bau - bax * cau) * invDet;
  204. const float by = (cay * bau - bay * cau) * invDet;
  205. const float bz = (caz * bau - baz * cau) * invDet;
  206. for (uint32_t jj = 0; jj < 3; ++jj)
  207. {
  208. float* tanu = &tangents[indices[jj]*6];
  209. float* tanv = &tanu[3];
  210. tanu[0] += tx;
  211. tanu[1] += ty;
  212. tanu[2] += tz;
  213. tanv[0] += bx;
  214. tanv[1] += by;
  215. tanv[2] += bz;
  216. }
  217. }
  218. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  219. {
  220. Ty& v0 = _vertices[ii];
  221. const float* tanu = &tangents[ii*6];
  222. const float* tanv = &tangents[ii*6 + 3];
  223. float normal[4];
  224. unpackF4u(normal, v0.m_normal);
  225. float ndt = vec3Dot(normal, tanu);
  226. float nxt[3];
  227. vec3Cross(nxt, normal, tanu);
  228. float tmp[3];
  229. tmp[0] = tanu[0] - normal[0] * ndt;
  230. tmp[1] = tanu[1] - normal[1] * ndt;
  231. tmp[2] = tanu[2] - normal[2] * ndt;
  232. float tangent[3];
  233. vec3Norm(tangent, tmp);
  234. float tw = vec3Dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  235. v0.m_tangent = packF4u(tangent[0], tangent[1], tangent[2], tw);
  236. }
  237. }
  238. void writeBounds(bx::WriterI* _writer, const void* _vertices, uint32_t _numVertices, uint32_t _stride)
  239. {
  240. Sphere maxSphere;
  241. calcMaxBoundingSphere(maxSphere, _vertices, _numVertices, _stride);
  242. Sphere minSphere;
  243. calcMinBoundingSphere(minSphere, _vertices, _numVertices, _stride);
  244. if (minSphere.m_radius > maxSphere.m_radius)
  245. {
  246. bx::write(_writer, maxSphere);
  247. }
  248. else
  249. {
  250. bx::write(_writer, minSphere);
  251. }
  252. Aabb aabb;
  253. calcAabb(aabb, _vertices, _numVertices, _stride);
  254. bx::write(_writer, aabb);
  255. Obb obb;
  256. calcObb(obb, _vertices, _numVertices, _stride, s_obbSteps);
  257. bx::write(_writer, obb);
  258. }
  259. void write(bx::WriterI* _writer, const uint8_t* _vertices, uint32_t _numVertices, const bgfx::VertexDecl& _decl, const uint16_t* _indices, uint32_t _numIndices, const std::string& _material, const PrimitiveArray& _primitives)
  260. {
  261. uint32_t stride = _decl.getStride();
  262. bx::write(_writer, BGFX_CHUNK_MAGIC_VB);
  263. writeBounds(_writer, _vertices, _numVertices, stride);
  264. bx::write(_writer, _decl);
  265. bx::write(_writer, uint16_t(_numVertices) );
  266. bx::write(_writer, _vertices, _numVertices*stride);
  267. bx::write(_writer, BGFX_CHUNK_MAGIC_IB);
  268. bx::write(_writer, _numIndices);
  269. bx::write(_writer, _indices, _numIndices*2);
  270. bx::write(_writer, BGFX_CHUNK_MAGIC_PRI);
  271. uint16_t nameLen = uint16_t(_material.size() );
  272. bx::write(_writer, nameLen);
  273. bx::write(_writer, _material.c_str(), nameLen);
  274. bx::write(_writer, uint16_t(_primitives.size() ) );
  275. for (PrimitiveArray::const_iterator primIt = _primitives.begin(); primIt != _primitives.end(); ++primIt)
  276. {
  277. const Primitive& prim = *primIt;
  278. nameLen = uint16_t(prim.m_name.size() );
  279. bx::write(_writer, nameLen);
  280. bx::write(_writer, prim.m_name.c_str(), nameLen);
  281. bx::write(_writer, prim.m_startIndex);
  282. bx::write(_writer, prim.m_numIndices);
  283. bx::write(_writer, prim.m_startVertex);
  284. bx::write(_writer, prim.m_numVertices);
  285. writeBounds(_writer, &_vertices[prim.m_startVertex*stride], prim.m_numVertices, stride);
  286. }
  287. }
  288. void help(const char* _error = NULL)
  289. {
  290. if (NULL != _error)
  291. {
  292. fprintf(stderr, "Error:\n%s\n\n", _error);
  293. }
  294. fprintf(stderr
  295. , "geometryc, bgfx geometry compiler tool\n"
  296. "Copyright 2011-2012 Branimir Karadzic. All rights reserved.\n"
  297. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  298. );
  299. fprintf(stderr
  300. , "Usage: geometryc -f <in> -o <out>\n"
  301. "\n"
  302. "Supported input file types:\n"
  303. " *.obj Wavefront\n"
  304. "\n"
  305. "Options:\n"
  306. " -f <file path> Input file path.\n"
  307. " -o <file path> Output file path.\n"
  308. " -s, --scale <num> Scale factor.\n"
  309. " --ccw Counter-clockwise winding order.\n"
  310. " --flipv Flip texture coordinate V.\n"
  311. " --obb <num> Number of steps for calculating oriented bounding box.\n"
  312. " Default value is 17. Less steps less precise OBB is.\n"
  313. " More steps slower calculation.\n"
  314. " --packnormal <num> Normal packing.\n"
  315. " 0 - unpacked 12 bytes (default).\n"
  316. " 1 - packed 4 bytes.\n"
  317. " --packuv <num> Texture coordinate packing.\n"
  318. " 0 - unpacked 8 bytes (default).\n"
  319. " 1 - packed 4 bytes.\n"
  320. " --tangent Calculate tangent vectors (packing mode is the same as normal).\n"
  321. "\n"
  322. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  323. );
  324. }
  325. inline uint32_t rgbaToAbgr(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a)
  326. {
  327. return (uint32_t(_r)<<0)
  328. | (uint32_t(_g)<<8)
  329. | (uint32_t(_b)<<16)
  330. | (uint32_t(_a)<<24)
  331. ;
  332. }
  333. int main(int _argc, const char* _argv[])
  334. {
  335. bx::CommandLine cmdLine(_argc, _argv);
  336. const char* filePath = cmdLine.findOption('f');
  337. if (NULL == filePath)
  338. {
  339. help("Input file name must be specified.");
  340. return EXIT_FAILURE;
  341. }
  342. const char* outFilePath = cmdLine.findOption('o');
  343. if (NULL == outFilePath)
  344. {
  345. help("Output file name must be specified.");
  346. return EXIT_FAILURE;
  347. }
  348. float scale = 1.0f;
  349. const char* scaleArg = cmdLine.findOption('s', "scale");
  350. if (NULL != scaleArg)
  351. {
  352. scale = (float)atof(scaleArg);
  353. }
  354. cmdLine.hasArg(s_obbSteps, '\0', "obb");
  355. s_obbSteps = bx::uint32_min(bx::uint32_max(s_obbSteps, 1), 90);
  356. uint32_t packNormal = 0;
  357. cmdLine.hasArg(packNormal, '\0', "packnormal");
  358. uint32_t packUv = 0;
  359. cmdLine.hasArg(packNormal, '\0', "packuv");
  360. bool ccw = cmdLine.hasArg("ccw");
  361. bool flipV = cmdLine.hasArg("flipv");
  362. bool hasTangent = cmdLine.hasArg("tangent");
  363. FILE* file = fopen(filePath, "r");
  364. if (NULL == file)
  365. {
  366. printf("Unable to open input file '%s'.", filePath);
  367. exit(EXIT_FAILURE);
  368. }
  369. int64_t parseElapsed = -bx::getHPCounter();
  370. int64_t triReorderElapsed = 0;
  371. uint32_t size = (uint32_t)fsize(file);
  372. char* data = new char[size+1];
  373. size = (uint32_t)fread(data, 1, size, file);
  374. data[size] = '\0';
  375. fclose(file);
  376. // https://en.wikipedia.org/wiki/Wavefront_.obj_file
  377. Vector3Array positions;
  378. Vector3Array normals;
  379. Vector3Array texcoords;
  380. Index3Map indexMap;
  381. TriangleArray triangles;
  382. GroupArray groups;
  383. uint32_t num = 0;
  384. Group group;
  385. group.m_startTriangle = 0;
  386. group.m_numTriangles = 0;
  387. char commandLine[2048];
  388. uint32_t len = sizeof(commandLine);
  389. int argc;
  390. char* argv[64];
  391. const char* next = data;
  392. do
  393. {
  394. next = tokenizeCommandLine(next, commandLine, len, argc, argv, countof(argv), '\n');
  395. if (0 < argc)
  396. {
  397. if (0 == strcmp(argv[0], "#") )
  398. {
  399. if (2 < argc
  400. && 0 == strcmp(argv[2], "polygons") )
  401. {
  402. }
  403. }
  404. else if (0 == strcmp(argv[0], "f") )
  405. {
  406. Triangle triangle;
  407. for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge)
  408. {
  409. Index3 index;
  410. index.m_texcoord = -1;
  411. index.m_normal = -1;
  412. index.m_vertexIndex = -1;
  413. char* vertex = argv[edge+1];
  414. char* texcoord = strchr(vertex, '/');
  415. if (NULL != texcoord)
  416. {
  417. *texcoord++ = '\0';
  418. char* normal = strchr(texcoord, '/');
  419. if (NULL != normal)
  420. {
  421. *normal++ = '\0';
  422. index.m_normal = atoi(normal)-1;
  423. }
  424. index.m_texcoord = atoi(texcoord)-1;
  425. }
  426. index.m_position = atoi(vertex)-1;
  427. uint64_t hash0 = index.m_position;
  428. uint64_t hash1 = uint64_t(index.m_texcoord)<<20;
  429. uint64_t hash2 = uint64_t(index.m_normal)<<40;
  430. uint64_t hash = hash0^hash1^hash2;
  431. std::pair<Index3Map::iterator, bool> result = indexMap.insert(std::make_pair(hash, index) );
  432. if (!result.second)
  433. {
  434. Index3& oldIndex = result.first->second;
  435. BX_UNUSED(oldIndex);
  436. BX_CHECK(oldIndex.m_position == index.m_position
  437. && oldIndex.m_texcoord == index.m_texcoord
  438. && oldIndex.m_normal == index.m_normal
  439. , "Hash collision!"
  440. );
  441. }
  442. switch (edge)
  443. {
  444. case 0:
  445. case 1:
  446. case 2:
  447. triangle.m_index[edge] = hash;
  448. if (2 == edge)
  449. {
  450. if (ccw)
  451. {
  452. std::swap(triangle.m_index[1], triangle.m_index[2]);
  453. }
  454. triangles.push_back(triangle);
  455. }
  456. break;
  457. default:
  458. if (ccw)
  459. {
  460. triangle.m_index[2] = triangle.m_index[1];
  461. triangle.m_index[1] = hash;
  462. }
  463. else
  464. {
  465. triangle.m_index[1] = triangle.m_index[2];
  466. triangle.m_index[2] = hash;
  467. }
  468. triangles.push_back(triangle);
  469. break;
  470. }
  471. }
  472. }
  473. else if (0 == strcmp(argv[0], "g") )
  474. {
  475. EXPECT(1 < argc);
  476. group.m_name = argv[1];
  477. }
  478. else if (*argv[0] == 'v')
  479. {
  480. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  481. if (0 < group.m_numTriangles)
  482. {
  483. groups.push_back(group);
  484. group.m_startTriangle = (uint32_t)(triangles.size() );
  485. group.m_numTriangles = 0;
  486. }
  487. if (0 == strcmp(argv[0], "vn") )
  488. {
  489. Vector3 normal;
  490. normal.x = (float)atof(argv[1]);
  491. normal.y = (float)atof(argv[2]);
  492. normal.z = (float)atof(argv[3]);
  493. normals.push_back(normal);
  494. }
  495. else if (0 == strcmp(argv[0], "vp") )
  496. {
  497. static bool once = true;
  498. if (once)
  499. {
  500. once = false;
  501. printf("warning: 'parameter space vertices' are unsupported.\n");
  502. }
  503. }
  504. else if (0 == strcmp(argv[0], "vt") )
  505. {
  506. Vector3 texcoord;
  507. texcoord.x = (float)atof(argv[1]);
  508. texcoord.y = 0.0f;
  509. texcoord.z = 0.0f;
  510. switch (argc)
  511. {
  512. case 4:
  513. texcoord.z = (float)atof(argv[3]);
  514. // fallthrough
  515. case 3:
  516. texcoord.y = (float)atof(argv[2]);
  517. break;
  518. default:
  519. break;
  520. }
  521. texcoords.push_back(texcoord);
  522. }
  523. else
  524. {
  525. float px = (float)atof(argv[1]);
  526. float py = (float)atof(argv[2]);
  527. float pz = (float)atof(argv[3]);
  528. float pw = 1.0f;
  529. if (argc > 4)
  530. {
  531. pw = (float)atof(argv[4]);
  532. }
  533. float invW = scale/pw;
  534. px *= invW;
  535. py *= invW;
  536. pz *= invW;
  537. Vector3 pos;
  538. pos.x = px;
  539. pos.y = py;
  540. pos.z = pz;
  541. positions.push_back(pos);
  542. }
  543. }
  544. else if (0 == strcmp(argv[0], "usemtl") )
  545. {
  546. std::string material(argv[1]);
  547. if (material != group.m_material)
  548. {
  549. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  550. if (0 < group.m_numTriangles)
  551. {
  552. groups.push_back(group);
  553. group.m_startTriangle = (uint32_t)(triangles.size() );
  554. group.m_numTriangles = 0;
  555. }
  556. }
  557. group.m_material = material;
  558. }
  559. // unsupported tags
  560. // else if (0 == strcmp(argv[0], "mtllib") )
  561. // {
  562. // }
  563. // else if (0 == strcmp(argv[0], "o") )
  564. // {
  565. // }
  566. // else if (0 == strcmp(argv[0], "s") )
  567. // {
  568. // }
  569. }
  570. ++num;
  571. }
  572. while ('\0' != *next);
  573. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  574. if (0 < group.m_numTriangles)
  575. {
  576. groups.push_back(group);
  577. group.m_startTriangle = (uint32_t)(triangles.size() );
  578. group.m_numTriangles = 0;
  579. }
  580. delete [] data;
  581. int64_t now = bx::getHPCounter();
  582. parseElapsed += now;
  583. int64_t convertElapsed = -now;
  584. struct GroupSortByMaterial
  585. {
  586. bool operator()(const Group& _lhs, const Group& _rhs)
  587. {
  588. return _lhs.m_material < _rhs.m_material;
  589. }
  590. };
  591. std::sort(groups.begin(), groups.end(), GroupSortByMaterial() );
  592. bool hasColor = false;
  593. bool hasNormal;
  594. bool hasTexcoord;
  595. {
  596. Index3Map::const_iterator it = indexMap.begin();
  597. hasNormal = -1 != it->second.m_normal;
  598. hasTexcoord = -1 != it->second.m_texcoord;
  599. if (!hasTexcoord
  600. && texcoords.size() == positions.size() )
  601. {
  602. hasTexcoord = true;
  603. for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
  604. {
  605. it->second.m_texcoord = it->second.m_position;
  606. }
  607. }
  608. if (!hasNormal
  609. && normals.size() == positions.size() )
  610. {
  611. hasNormal = true;
  612. for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
  613. {
  614. it->second.m_normal = it->second.m_position;
  615. }
  616. }
  617. }
  618. bgfx::VertexDecl decl;
  619. decl.begin();
  620. decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  621. if (hasColor)
  622. {
  623. decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  624. }
  625. if (hasTexcoord)
  626. {
  627. switch (packUv)
  628. {
  629. default:
  630. case 0:
  631. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  632. break;
  633. case 1:
  634. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
  635. break;
  636. }
  637. }
  638. if (hasNormal)
  639. {
  640. switch (packNormal)
  641. {
  642. default:
  643. case 0:
  644. decl.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
  645. if (hasTangent)
  646. {
  647. decl.add(bgfx::Attrib::Tangent, 3, bgfx::AttribType::Float);
  648. }
  649. break;
  650. case 1:
  651. decl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true);
  652. if (hasTangent)
  653. {
  654. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true);
  655. }
  656. break;
  657. }
  658. }
  659. decl.end();
  660. uint32_t stride = decl.getStride();
  661. uint8_t* vertexData = new uint8_t[triangles.size() * 3 * stride];
  662. uint16_t* indexData = new uint16_t[triangles.size() * 3];
  663. int32_t numVertices = 0;
  664. int32_t numIndices = 0;
  665. int32_t numPrimitives = 0;
  666. uint8_t* vertices = vertexData;
  667. uint16_t* indices = indexData;
  668. std::string material = groups.begin()->m_material;
  669. PrimitiveArray primitives;
  670. bx::CrtFileWriter writer;
  671. if (0 != writer.open(outFilePath) )
  672. {
  673. printf("Unable to open output file '%s'.", outFilePath);
  674. exit(EXIT_FAILURE);
  675. }
  676. Primitive prim;
  677. prim.m_startVertex = 0;
  678. prim.m_startIndex = 0;
  679. uint32_t positionOffset = decl.getOffset(bgfx::Attrib::Position);
  680. uint32_t color0Offset = decl.getOffset(bgfx::Attrib::Color0);
  681. uint32_t normalOffset = decl.getOffset(bgfx::Attrib::Normal);
  682. uint32_t tangentOffset = decl.getOffset(bgfx::Attrib::Tangent);
  683. uint32_t texcoord0Offset = decl.getOffset(bgfx::Attrib::TexCoord0);
  684. uint32_t ii = 0;
  685. for (GroupArray::const_iterator groupIt = groups.begin(); groupIt != groups.end(); ++groupIt, ++ii)
  686. {
  687. for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
  688. {
  689. if (material != groupIt->m_material
  690. || 65533 < numVertices)
  691. {
  692. prim.m_numVertices = numVertices - prim.m_startVertex;
  693. prim.m_numIndices = numIndices - prim.m_startIndex;
  694. if (0 < prim.m_numVertices)
  695. {
  696. primitives.push_back(prim);
  697. }
  698. triReorderElapsed -= bx::getHPCounter();
  699. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  700. {
  701. const Primitive& prim = *primIt;
  702. triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
  703. }
  704. triReorderElapsed += bx::getHPCounter();
  705. write(&writer, vertexData, numVertices, decl, indexData, numIndices, material, primitives);
  706. primitives.clear();
  707. for (Index3Map::iterator indexIt = indexMap.begin(); indexIt != indexMap.end(); ++indexIt)
  708. {
  709. indexIt->second.m_vertexIndex = -1;
  710. }
  711. vertices = vertexData;
  712. indices = indexData;
  713. numVertices = 0;
  714. numIndices = 0;
  715. prim.m_startVertex = 0;
  716. prim.m_startIndex = 0;
  717. ++numPrimitives;
  718. material = groupIt->m_material;
  719. }
  720. Triangle& triangle = triangles[tri];
  721. for (uint32_t edge = 0; edge < 3; ++edge)
  722. {
  723. uint64_t hash = triangle.m_index[edge];
  724. Index3& index = indexMap[hash];
  725. if (index.m_vertexIndex == -1)
  726. {
  727. index.m_vertexIndex = numVertices++;
  728. float* position = (float*)(vertices + positionOffset);
  729. memcpy(position, &positions[index.m_position], 3*sizeof(float) );
  730. if (hasColor)
  731. {
  732. uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
  733. *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
  734. }
  735. if (hasTexcoord)
  736. {
  737. float uv[2];
  738. memcpy(uv, &texcoords[index.m_texcoord], 2*sizeof(float) );
  739. if (flipV)
  740. {
  741. uv[1] = -uv[1];
  742. }
  743. switch (packUv)
  744. {
  745. default:
  746. case 0:
  747. {
  748. float* texcoord0 = (float*)(vertices + texcoord0Offset);
  749. memcpy(texcoord0, uv, 2*sizeof(float) );
  750. }
  751. break;
  752. case 1:
  753. {
  754. uint32_t* texcoord0 = (uint32_t*)(vertices + texcoord0Offset);
  755. *texcoord0 = packF2h(uv[0], uv[1]);
  756. }
  757. break;
  758. }
  759. }
  760. if (hasNormal)
  761. {
  762. switch (packNormal)
  763. {
  764. default:
  765. case 0:
  766. {
  767. float* normal = (float*)(vertices + normalOffset);
  768. vec3Norm(normal, (float*)&normals[index.m_normal]);
  769. if (hasTangent)
  770. {
  771. float* tangent = (float*)(vertices + tangentOffset);
  772. memset(tangent, 0, 3*sizeof(float) );
  773. }
  774. }
  775. break;
  776. case 1:
  777. {
  778. float normal[3];
  779. vec3Norm(normal, (float*)&normals[index.m_normal]);
  780. uint32_t* nxyz0 = (uint32_t*)(vertices + normalOffset);
  781. *nxyz0 = packF4u(normal[0], normal[1], normal[2]);
  782. if (hasTangent)
  783. {
  784. uint32_t* txyz0 = (uint32_t*)(vertices + tangentOffset);
  785. *txyz0 = packF4u(0.0f);
  786. }
  787. }
  788. break;
  789. }
  790. }
  791. vertices += stride;
  792. }
  793. *indices++ = (uint16_t)index.m_vertexIndex;
  794. ++numIndices;
  795. }
  796. }
  797. if (0 < numVertices)
  798. {
  799. prim.m_numVertices = numVertices - prim.m_startVertex;
  800. prim.m_numIndices = numIndices - prim.m_startIndex;
  801. prim.m_name = groupIt->m_name;
  802. primitives.push_back(prim);
  803. prim.m_startVertex = numVertices;
  804. prim.m_startIndex = numIndices;
  805. }
  806. BX_TRACE("%3d: s %5d, n %5d, %s\n"
  807. , ii
  808. , groupIt->m_startTriangle
  809. , groupIt->m_numTriangles
  810. , groupIt->m_material.c_str()
  811. );
  812. }
  813. if (0 < primitives.size() )
  814. {
  815. triReorderElapsed -= bx::getHPCounter();
  816. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  817. {
  818. const Primitive& prim = *primIt;
  819. triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
  820. }
  821. triReorderElapsed += bx::getHPCounter();
  822. write(&writer, vertexData, numVertices, decl, indexData, numIndices, material, primitives);
  823. }
  824. printf("size: %d\n", uint32_t(writer.seek() ) );
  825. writer.close();
  826. delete [] indexData;
  827. delete [] vertexData;
  828. now = bx::getHPCounter();
  829. convertElapsed += now;
  830. printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\n# %d, g %d, p %d, v %d, i %d\n"
  831. , double(parseElapsed)/bx::getHPFrequency()
  832. , double(triReorderElapsed)/bx::getHPFrequency()
  833. , double(convertElapsed)/bx::getHPFrequency()
  834. , num
  835. , uint32_t(groups.size() )
  836. , numPrimitives
  837. , numVertices
  838. , numIndices
  839. );
  840. return EXIT_SUCCESS;
  841. }