geometryc.cpp 25 KB

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