geometryc.cpp 25 KB

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