geometryc.cpp 22 KB

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