geometryc.cpp 27 KB

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