geometryc.cpp 26 KB

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