geometryc.cpp 27 KB

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