geometryc.cpp 22 KB

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