geometryc.cpp 27 KB

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