geometryc.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/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.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/readerwriter.h>
  53. #include <bx/hash.h>
  54. #include <bx/uint32_t.h>
  55. #include <bx/fpumath.h>
  56. #include <bx/tokenizecmd.h>
  57. #include "bounds.h"
  58. struct Vector3
  59. {
  60. float x;
  61. float y;
  62. float z;
  63. };
  64. typedef std::vector<Vector3> Vector3Array;
  65. struct Index3
  66. {
  67. int32_t m_position;
  68. int32_t m_texcoord;
  69. int32_t m_normal;
  70. int32_t m_vertexIndex;
  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, ICBF_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. calcAabb(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-2015 Branimir Karadzic. All rights reserved.\n"
  300. "License: http://www.opensource.org/licenses/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. " -c, --compress Compress indices.\n"
  325. "\n"
  326. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  327. );
  328. }
  329. inline uint32_t rgbaToAbgr(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a)
  330. {
  331. return (uint32_t(_r)<<0)
  332. | (uint32_t(_g)<<8)
  333. | (uint32_t(_b)<<16)
  334. | (uint32_t(_a)<<24)
  335. ;
  336. }
  337. struct GroupSortByMaterial
  338. {
  339. bool operator()(const Group& _lhs, const Group& _rhs)
  340. {
  341. return _lhs.m_material < _rhs.m_material;
  342. }
  343. };
  344. int main(int _argc, const char* _argv[])
  345. {
  346. bx::CommandLine cmdLine(_argc, _argv);
  347. const char* filePath = cmdLine.findOption('f');
  348. if (NULL == filePath)
  349. {
  350. help("Input file name must be specified.");
  351. return EXIT_FAILURE;
  352. }
  353. const char* outFilePath = cmdLine.findOption('o');
  354. if (NULL == outFilePath)
  355. {
  356. help("Output file name must be specified.");
  357. return EXIT_FAILURE;
  358. }
  359. float scale = 1.0f;
  360. const char* scaleArg = cmdLine.findOption('s', "scale");
  361. if (NULL != scaleArg)
  362. {
  363. scale = (float)atof(scaleArg);
  364. }
  365. bool compress = cmdLine.hasArg('c', "compress");
  366. cmdLine.hasArg(s_obbSteps, '\0', "obb");
  367. s_obbSteps = bx::uint32_min(bx::uint32_max(s_obbSteps, 1), 90);
  368. uint32_t packNormal = 0;
  369. cmdLine.hasArg(packNormal, '\0', "packnormal");
  370. uint32_t packUv = 0;
  371. cmdLine.hasArg(packUv, '\0', "packuv");
  372. bool ccw = cmdLine.hasArg("ccw");
  373. bool flipV = cmdLine.hasArg("flipv");
  374. bool hasTangent = cmdLine.hasArg("tangent");
  375. FILE* file = fopen(filePath, "r");
  376. if (NULL == file)
  377. {
  378. printf("Unable to open input file '%s'.", filePath);
  379. exit(EXIT_FAILURE);
  380. }
  381. int64_t parseElapsed = -bx::getHPCounter();
  382. int64_t triReorderElapsed = 0;
  383. uint32_t size = (uint32_t)fsize(file);
  384. char* data = new char[size+1];
  385. size = (uint32_t)fread(data, 1, size, file);
  386. data[size] = '\0';
  387. fclose(file);
  388. // https://en.wikipedia.org/wiki/Wavefront_.obj_file
  389. Vector3Array positions;
  390. Vector3Array normals;
  391. Vector3Array texcoords;
  392. Index3Map indexMap;
  393. TriangleArray triangles;
  394. GroupArray groups;
  395. uint32_t num = 0;
  396. Group group;
  397. group.m_startTriangle = 0;
  398. group.m_numTriangles = 0;
  399. char commandLine[2048];
  400. uint32_t len = sizeof(commandLine);
  401. int argc;
  402. char* argv[64];
  403. const char* next = data;
  404. do
  405. {
  406. next = bx::tokenizeCommandLine(next, commandLine, len, argc, argv, BX_COUNTOF(argv), '\n');
  407. if (0 < argc)
  408. {
  409. if (0 == strcmp(argv[0], "#") )
  410. {
  411. if (2 < argc
  412. && 0 == strcmp(argv[2], "polygons") )
  413. {
  414. }
  415. }
  416. else if (0 == strcmp(argv[0], "f") )
  417. {
  418. Triangle triangle;
  419. memset(&triangle, 0, sizeof(Triangle) );
  420. for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge)
  421. {
  422. Index3 index;
  423. index.m_texcoord = -1;
  424. index.m_normal = -1;
  425. index.m_vertexIndex = -1;
  426. char* vertex = argv[edge+1];
  427. char* texcoord = strchr(vertex, '/');
  428. if (NULL != texcoord)
  429. {
  430. *texcoord++ = '\0';
  431. char* normal = strchr(texcoord, '/');
  432. if (NULL != normal)
  433. {
  434. *normal++ = '\0';
  435. index.m_normal = atoi(normal)-1;
  436. }
  437. index.m_texcoord = atoi(texcoord)-1;
  438. }
  439. index.m_position = atoi(vertex)-1;
  440. uint64_t hash0 = index.m_position;
  441. uint64_t hash1 = uint64_t(index.m_texcoord)<<20;
  442. uint64_t hash2 = uint64_t(index.m_normal)<<40;
  443. uint64_t hash = hash0^hash1^hash2;
  444. stl::pair<Index3Map::iterator, bool> result = indexMap.insert(stl::make_pair(hash, index) );
  445. if (!result.second)
  446. {
  447. Index3& oldIndex = result.first->second;
  448. BX_UNUSED(oldIndex);
  449. BX_CHECK(oldIndex.m_position == index.m_position
  450. && oldIndex.m_texcoord == index.m_texcoord
  451. && oldIndex.m_normal == index.m_normal
  452. , "Hash collision!"
  453. );
  454. }
  455. switch (edge)
  456. {
  457. case 0:
  458. case 1:
  459. case 2:
  460. triangle.m_index[edge] = hash;
  461. if (2 == edge)
  462. {
  463. if (ccw)
  464. {
  465. std::swap(triangle.m_index[1], triangle.m_index[2]);
  466. }
  467. triangles.push_back(triangle);
  468. }
  469. break;
  470. default:
  471. if (ccw)
  472. {
  473. triangle.m_index[2] = triangle.m_index[1];
  474. triangle.m_index[1] = hash;
  475. }
  476. else
  477. {
  478. triangle.m_index[1] = triangle.m_index[2];
  479. triangle.m_index[2] = hash;
  480. }
  481. triangles.push_back(triangle);
  482. break;
  483. }
  484. }
  485. }
  486. else if (0 == strcmp(argv[0], "g") )
  487. {
  488. EXPECT(1 < argc);
  489. group.m_name = argv[1];
  490. }
  491. else if (*argv[0] == 'v')
  492. {
  493. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  494. if (0 < group.m_numTriangles)
  495. {
  496. groups.push_back(group);
  497. group.m_startTriangle = (uint32_t)(triangles.size() );
  498. group.m_numTriangles = 0;
  499. }
  500. if (0 == strcmp(argv[0], "vn") )
  501. {
  502. Vector3 normal;
  503. normal.x = (float)atof(argv[1]);
  504. normal.y = (float)atof(argv[2]);
  505. normal.z = (float)atof(argv[3]);
  506. normals.push_back(normal);
  507. }
  508. else if (0 == strcmp(argv[0], "vp") )
  509. {
  510. static bool once = true;
  511. if (once)
  512. {
  513. once = false;
  514. printf("warning: 'parameter space vertices' are unsupported.\n");
  515. }
  516. }
  517. else if (0 == strcmp(argv[0], "vt") )
  518. {
  519. Vector3 texcoord;
  520. texcoord.x = (float)atof(argv[1]);
  521. texcoord.y = 0.0f;
  522. texcoord.z = 0.0f;
  523. switch (argc)
  524. {
  525. case 4:
  526. texcoord.z = (float)atof(argv[3]);
  527. // fallthrough
  528. case 3:
  529. texcoord.y = (float)atof(argv[2]);
  530. break;
  531. default:
  532. break;
  533. }
  534. texcoords.push_back(texcoord);
  535. }
  536. else
  537. {
  538. float px = (float)atof(argv[1]);
  539. float py = (float)atof(argv[2]);
  540. float pz = (float)atof(argv[3]);
  541. float pw = 1.0f;
  542. if (argc > 4)
  543. {
  544. pw = (float)atof(argv[4]);
  545. }
  546. float invW = scale/pw;
  547. px *= invW;
  548. py *= invW;
  549. pz *= invW;
  550. Vector3 pos;
  551. pos.x = px;
  552. pos.y = py;
  553. pos.z = pz;
  554. positions.push_back(pos);
  555. }
  556. }
  557. else if (0 == strcmp(argv[0], "usemtl") )
  558. {
  559. std::string material(argv[1]);
  560. if (material != group.m_material)
  561. {
  562. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  563. if (0 < group.m_numTriangles)
  564. {
  565. groups.push_back(group);
  566. group.m_startTriangle = (uint32_t)(triangles.size() );
  567. group.m_numTriangles = 0;
  568. }
  569. }
  570. group.m_material = material;
  571. }
  572. // unsupported tags
  573. // else if (0 == strcmp(argv[0], "mtllib") )
  574. // {
  575. // }
  576. // else if (0 == strcmp(argv[0], "o") )
  577. // {
  578. // }
  579. // else if (0 == strcmp(argv[0], "s") )
  580. // {
  581. // }
  582. }
  583. ++num;
  584. }
  585. while ('\0' != *next);
  586. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  587. if (0 < group.m_numTriangles)
  588. {
  589. groups.push_back(group);
  590. group.m_startTriangle = (uint32_t)(triangles.size() );
  591. group.m_numTriangles = 0;
  592. }
  593. delete [] data;
  594. int64_t now = bx::getHPCounter();
  595. parseElapsed += now;
  596. int64_t convertElapsed = -now;
  597. std::sort(groups.begin(), groups.end(), GroupSortByMaterial() );
  598. bool hasColor = false;
  599. bool hasNormal;
  600. bool hasTexcoord;
  601. {
  602. Index3Map::const_iterator it = indexMap.begin();
  603. hasNormal = -1 != it->second.m_normal;
  604. hasTexcoord = -1 != it->second.m_texcoord;
  605. if (!hasTexcoord
  606. && texcoords.size() == positions.size() )
  607. {
  608. hasTexcoord = true;
  609. for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
  610. {
  611. it->second.m_texcoord = it->second.m_position;
  612. }
  613. }
  614. if (!hasNormal
  615. && normals.size() == positions.size() )
  616. {
  617. hasNormal = true;
  618. for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
  619. {
  620. it->second.m_normal = it->second.m_position;
  621. }
  622. }
  623. }
  624. bgfx::VertexDecl decl;
  625. decl.begin();
  626. decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  627. if (hasColor)
  628. {
  629. decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  630. }
  631. if (hasTexcoord)
  632. {
  633. switch (packUv)
  634. {
  635. default:
  636. case 0:
  637. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  638. break;
  639. case 1:
  640. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
  641. break;
  642. }
  643. }
  644. if (hasNormal)
  645. {
  646. hasTangent &= hasTexcoord;
  647. switch (packNormal)
  648. {
  649. default:
  650. case 0:
  651. decl.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
  652. if (hasTangent)
  653. {
  654. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float);
  655. }
  656. break;
  657. case 1:
  658. decl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
  659. if (hasTangent)
  660. {
  661. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true);
  662. }
  663. break;
  664. }
  665. }
  666. decl.end();
  667. uint32_t stride = decl.getStride();
  668. uint8_t* vertexData = new uint8_t[triangles.size() * 3 * stride];
  669. uint16_t* indexData = new uint16_t[triangles.size() * 3];
  670. int32_t numVertices = 0;
  671. int32_t numIndices = 0;
  672. int32_t numPrimitives = 0;
  673. uint8_t* vertices = vertexData;
  674. uint16_t* indices = indexData;
  675. std::string material = groups.begin()->m_material;
  676. PrimitiveArray primitives;
  677. bx::CrtFileWriter writer;
  678. if (0 != writer.open(outFilePath) )
  679. {
  680. printf("Unable to open output file '%s'.", outFilePath);
  681. exit(EXIT_FAILURE);
  682. }
  683. Primitive prim;
  684. prim.m_startVertex = 0;
  685. prim.m_startIndex = 0;
  686. uint32_t positionOffset = decl.getOffset(bgfx::Attrib::Position);
  687. uint32_t color0Offset = decl.getOffset(bgfx::Attrib::Color0);
  688. bx::CrtAllocator crtAllocator;
  689. bx::MemoryBlock memBlock(&crtAllocator);
  690. uint32_t ii = 0;
  691. for (GroupArray::const_iterator groupIt = groups.begin(); groupIt != groups.end(); ++groupIt, ++ii)
  692. {
  693. for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
  694. {
  695. if (material != groupIt->m_material
  696. || 65533 < numVertices)
  697. {
  698. prim.m_numVertices = numVertices - prim.m_startVertex;
  699. prim.m_numIndices = numIndices - prim.m_startIndex;
  700. if (0 < prim.m_numVertices)
  701. {
  702. primitives.push_back(prim);
  703. }
  704. if (hasTangent)
  705. {
  706. calcTangents(vertexData, numVertices, decl, indexData, numIndices);
  707. }
  708. bx::MemoryWriter memWriter(&memBlock);
  709. triReorderElapsed -= bx::getHPCounter();
  710. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  711. {
  712. const Primitive& prim = *primIt;
  713. triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
  714. if (compress)
  715. {
  716. triangleCompress(&memWriter
  717. , indexData + prim.m_startIndex
  718. , prim.m_numIndices
  719. , vertexData + prim.m_startVertex
  720. , numVertices
  721. , stride
  722. );
  723. }
  724. }
  725. triReorderElapsed += bx::getHPCounter();
  726. write(&writer
  727. , vertexData
  728. , numVertices
  729. , decl
  730. , indexData
  731. , numIndices
  732. , (uint8_t*)memBlock.more()
  733. , memBlock.getSize()
  734. , material
  735. , primitives
  736. );
  737. primitives.clear();
  738. for (Index3Map::iterator indexIt = indexMap.begin(); indexIt != indexMap.end(); ++indexIt)
  739. {
  740. indexIt->second.m_vertexIndex = -1;
  741. }
  742. vertices = vertexData;
  743. indices = indexData;
  744. numVertices = 0;
  745. numIndices = 0;
  746. prim.m_startVertex = 0;
  747. prim.m_startIndex = 0;
  748. ++numPrimitives;
  749. material = groupIt->m_material;
  750. }
  751. Triangle& triangle = triangles[tri];
  752. for (uint32_t edge = 0; edge < 3; ++edge)
  753. {
  754. uint64_t hash = triangle.m_index[edge];
  755. Index3& index = indexMap[hash];
  756. if (index.m_vertexIndex == -1)
  757. {
  758. index.m_vertexIndex = numVertices++;
  759. float* position = (float*)(vertices + positionOffset);
  760. memcpy(position, &positions[index.m_position], 3*sizeof(float) );
  761. if (hasColor)
  762. {
  763. uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
  764. *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
  765. }
  766. if (hasTexcoord)
  767. {
  768. float uv[2];
  769. memcpy(uv, &texcoords[index.m_texcoord], 2*sizeof(float) );
  770. if (flipV)
  771. {
  772. uv[1] = -uv[1];
  773. }
  774. bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, decl, vertices);
  775. }
  776. if (hasNormal)
  777. {
  778. float normal[4];
  779. bx::vec3Norm(normal, (float*)&normals[index.m_normal]);
  780. bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, decl, vertices);
  781. }
  782. vertices += stride;
  783. }
  784. *indices++ = (uint16_t)index.m_vertexIndex;
  785. ++numIndices;
  786. }
  787. }
  788. if (0 < numVertices)
  789. {
  790. prim.m_numVertices = numVertices - prim.m_startVertex;
  791. prim.m_numIndices = numIndices - prim.m_startIndex;
  792. prim.m_name = groupIt->m_name;
  793. primitives.push_back(prim);
  794. prim.m_startVertex = numVertices;
  795. prim.m_startIndex = numIndices;
  796. }
  797. BX_TRACE("%3d: s %5d, n %5d, %s\n"
  798. , ii
  799. , groupIt->m_startTriangle
  800. , groupIt->m_numTriangles
  801. , groupIt->m_material.c_str()
  802. );
  803. }
  804. if (0 < primitives.size() )
  805. {
  806. if (hasTangent)
  807. {
  808. calcTangents(vertexData, numVertices, decl, indexData, numIndices);
  809. }
  810. bx::MemoryWriter memWriter(&memBlock);
  811. triReorderElapsed -= bx::getHPCounter();
  812. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  813. {
  814. const Primitive& prim = *primIt;
  815. triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
  816. if (compress)
  817. {
  818. triangleCompress(&memWriter
  819. , indexData + prim.m_startIndex
  820. , prim.m_numIndices
  821. , vertexData + prim.m_startVertex
  822. , numVertices
  823. , stride
  824. );
  825. }
  826. }
  827. triReorderElapsed += bx::getHPCounter();
  828. write(&writer
  829. , vertexData
  830. , numVertices
  831. , decl
  832. , indexData
  833. , numIndices
  834. , (uint8_t*)memBlock.more()
  835. , memBlock.getSize()
  836. , material
  837. , primitives
  838. );
  839. }
  840. printf("size: %d\n", uint32_t(writer.seek() ) );
  841. writer.close();
  842. delete [] indexData;
  843. delete [] vertexData;
  844. now = bx::getHPCounter();
  845. convertElapsed += now;
  846. printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\n# %d, g %d, p %d, v %d, i %d\n"
  847. , double(parseElapsed)/bx::getHPFrequency()
  848. , double(triReorderElapsed)/bx::getHPFrequency()
  849. , double(convertElapsed)/bx::getHPFrequency()
  850. , num
  851. , uint32_t(groups.size() )
  852. , numPrimitives
  853. , numVertices
  854. , numIndices
  855. );
  856. return EXIT_SUCCESS;
  857. }