geometryc.cpp 26 KB

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