geometryc.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. /*
  2. * Copyright 2011-2020 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <algorithm>
  6. #include <bx/string.h>
  7. #include <bgfx/bgfx.h>
  8. #include "../../src/vertexlayout.h"
  9. #include <tinystl/allocator.h>
  10. #include <tinystl/string.h>
  11. #include <tinystl/vector.h>
  12. namespace stl = tinystl;
  13. #include <meshoptimizer/src/meshoptimizer.h>
  14. #define CGLTF_IMPLEMENTATION
  15. #include <cgltf/cgltf.h>
  16. #define BGFX_GEOMETRYC_VERSION_MAJOR 1
  17. #define BGFX_GEOMETRYC_VERSION_MINOR 0
  18. #if 0
  19. # define BX_TRACE(_format, ...) \
  20. do { \
  21. bx::printf(BX_FILE_LINE_LITERAL "BGFX " _format "\n", ##__VA_ARGS__); \
  22. } while(0)
  23. # define BX_WARN(_condition, _format, ...) \
  24. do { \
  25. if (!(_condition) ) \
  26. { \
  27. BX_TRACE(BX_FILE_LINE_LITERAL "WARN " _format, ##__VA_ARGS__); \
  28. } \
  29. } while(0)
  30. # define BX_CHECK(_condition, _format, ...) \
  31. do { \
  32. if (!(_condition) ) \
  33. { \
  34. BX_TRACE(BX_FILE_LINE_LITERAL "CHECK " _format, ##__VA_ARGS__); \
  35. bx::debugBreak(); \
  36. } \
  37. } while(0)
  38. #endif // 0
  39. #include <bx/bx.h>
  40. #include <bx/debug.h>
  41. #include <bx/commandline.h>
  42. #include <bx/timer.h>
  43. #include <bx/hash.h>
  44. #include <bx/uint32_t.h>
  45. #include <bx/math.h>
  46. #include <bx/file.h>
  47. #include "bounds.h"
  48. typedef stl::vector<bx::Vec3> Vec3Array;
  49. struct Index3
  50. {
  51. int32_t m_position;
  52. int32_t m_texcoord;
  53. int32_t m_normal;
  54. int32_t m_vbc; // Barycentric ID. Holds either 0, 1 or 2.
  55. };
  56. struct TriIndices
  57. {
  58. Index3 m_index[3];
  59. };
  60. typedef stl::vector<TriIndices> TriangleArray;
  61. struct Group
  62. {
  63. uint32_t m_startTriangle;
  64. uint32_t m_numTriangles;
  65. stl::string m_name;
  66. stl::string m_material;
  67. };
  68. typedef stl::vector<Group> GroupArray;
  69. struct Primitive
  70. {
  71. uint32_t m_startVertex;
  72. uint32_t m_startIndex;
  73. uint32_t m_numVertices;
  74. uint32_t m_numIndices;
  75. stl::string m_name;
  76. };
  77. typedef stl::vector<Primitive> PrimitiveArray;
  78. struct Axis
  79. {
  80. enum Enum
  81. {
  82. NegativeX,
  83. PositiveX,
  84. NegativeY,
  85. PositiveY,
  86. NegativeZ,
  87. PositiveZ,
  88. };
  89. };
  90. static bx::Vec3 s_axisVectors[6] =
  91. {
  92. bx::Vec3(-1.0f, 0.0f, 0.0f),
  93. bx::Vec3( 1.0f, 0.0f, 0.0f),
  94. bx::Vec3( 0.0f,-1.0f, 0.0f),
  95. bx::Vec3( 0.0f, 1.0f, 0.0f),
  96. bx::Vec3( 0.0f, 0.0f,-1.0f),
  97. bx::Vec3( 0.0f, 0.0f, 1.0f),
  98. };
  99. struct CoordinateSystem
  100. {
  101. bx::Handness::Enum m_handness;
  102. Axis::Enum m_up;
  103. Axis::Enum m_forward;
  104. };
  105. struct CoordinateSystemMapping
  106. {
  107. const char* m_param;
  108. CoordinateSystem m_coordinateSystem;
  109. };
  110. static const CoordinateSystemMapping s_coordinateSystemMappings[] =
  111. {
  112. { "lh-up+y", { bx::Handness::Left, Axis::PositiveY, Axis::PositiveZ } } ,
  113. { "lh-up+z", { bx::Handness::Left, Axis::PositiveZ, Axis::PositiveY } },
  114. { "rh-up+y", { bx::Handness::Right, Axis::PositiveY, Axis::PositiveZ } },
  115. { "rh-up+z", { bx::Handness::Right, Axis::PositiveZ, Axis::PositiveY } },
  116. };
  117. struct Mesh
  118. {
  119. Vec3Array m_positions;
  120. Vec3Array m_normals;
  121. Vec3Array m_texcoords;
  122. TriangleArray m_triangles;
  123. GroupArray m_groups;
  124. CoordinateSystem m_coordinateSystem;
  125. };
  126. static uint32_t s_obbSteps = 17;
  127. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x1)
  128. #define BGFX_CHUNK_MAGIC_VBC BX_MAKEFOURCC('V', 'B', 'C', 0x0)
  129. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  130. #define BGFX_CHUNK_MAGIC_IBC BX_MAKEFOURCC('I', 'B', 'C', 0x1)
  131. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  132. void optimizeVertexCache(uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices)
  133. {
  134. uint16_t* newIndexList = new uint16_t[_numIndices];
  135. meshopt_optimizeVertexCache(newIndexList, _indices, _numIndices, _numVertices);
  136. bx::memCopy(_indices, newIndexList, _numIndices * 2);
  137. delete[] newIndexList;
  138. }
  139. uint32_t optimizeVertexFetch(uint16_t* _indices, uint32_t _numIndices, uint8_t* _vertexData, uint32_t _numVertices, uint16_t _stride)
  140. {
  141. unsigned char* newVertices = (unsigned char*)malloc(_numVertices * _stride );
  142. size_t vertexCount = meshopt_optimizeVertexFetch(newVertices, _indices, _numIndices, _vertexData, _numVertices, _stride);
  143. bx::memCopy(_vertexData, newVertices, _numVertices * _stride);
  144. free(newVertices);
  145. return uint32_t(vertexCount);
  146. }
  147. void writeCompressedIndices(bx::WriterI* _writer, const uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices)
  148. {
  149. size_t maxSize = meshopt_encodeIndexBufferBound(_numIndices, _numVertices);
  150. unsigned char* compressedIndices = (unsigned char*)malloc(maxSize);
  151. size_t compressedSize = meshopt_encodeIndexBuffer(compressedIndices, maxSize, _indices, _numIndices);
  152. bx::printf( "indices uncompressed: %10d, compressed: %10d, ratio: %0.2f%%\n"
  153. , _numIndices*2
  154. , (uint32_t)compressedSize
  155. , 100.0f - float(compressedSize ) / float(_numIndices*2)*100.0f
  156. );
  157. bx::write(_writer, (uint32_t)compressedSize);
  158. bx::write(_writer, compressedIndices, (uint32_t)compressedSize );
  159. free(compressedIndices);
  160. }
  161. void writeCompressedVertices(bx::WriterI* _writer, const uint8_t* _vertices, uint32_t _numVertices, uint16_t _stride)
  162. {
  163. size_t maxSize = meshopt_encodeVertexBufferBound(_numVertices, _stride);
  164. unsigned char* compressedVertices = (unsigned char*)malloc(maxSize);
  165. size_t compressedSize = meshopt_encodeVertexBuffer(compressedVertices, maxSize, _vertices, _numVertices, _stride);
  166. bx::printf("vertices uncompressed: %10d, compressed: %10d, ratio: %0.2f%%\n"
  167. , _numVertices * _stride
  168. , (uint32_t)compressedSize
  169. , 100.0f - float(compressedSize) / float(_numVertices * _stride)*100.0f
  170. );
  171. bx::write(_writer, (uint32_t)compressedSize);
  172. bx::write(_writer, compressedVertices, (uint32_t)compressedSize );
  173. free(compressedVertices);
  174. }
  175. void calcTangents(void* _vertices, uint16_t _numVertices, bgfx::VertexLayout _layout, const uint16_t* _indices, uint32_t _numIndices)
  176. {
  177. struct PosTexcoord
  178. {
  179. float m_x;
  180. float m_y;
  181. float m_z;
  182. float m_pad0;
  183. float m_u;
  184. float m_v;
  185. float m_pad1;
  186. float m_pad2;
  187. };
  188. float* tangents = new float[6*_numVertices];
  189. bx::memSet(tangents, 0, 6*_numVertices*sizeof(float) );
  190. PosTexcoord v0;
  191. PosTexcoord v1;
  192. PosTexcoord v2;
  193. for (uint32_t ii = 0, num = _numIndices/3; ii < num; ++ii)
  194. {
  195. const uint16_t* indices = &_indices[ii*3];
  196. uint32_t i0 = indices[0];
  197. uint32_t i1 = indices[1];
  198. uint32_t i2 = indices[2];
  199. bgfx::vertexUnpack(&v0.m_x, bgfx::Attrib::Position, _layout, _vertices, i0);
  200. bgfx::vertexUnpack(&v0.m_u, bgfx::Attrib::TexCoord0, _layout, _vertices, i0);
  201. bgfx::vertexUnpack(&v1.m_x, bgfx::Attrib::Position, _layout, _vertices, i1);
  202. bgfx::vertexUnpack(&v1.m_u, bgfx::Attrib::TexCoord0, _layout, _vertices, i1);
  203. bgfx::vertexUnpack(&v2.m_x, bgfx::Attrib::Position, _layout, _vertices, i2);
  204. bgfx::vertexUnpack(&v2.m_u, bgfx::Attrib::TexCoord0, _layout, _vertices, i2);
  205. const float bax = v1.m_x - v0.m_x;
  206. const float bay = v1.m_y - v0.m_y;
  207. const float baz = v1.m_z - v0.m_z;
  208. const float bau = v1.m_u - v0.m_u;
  209. const float bav = v1.m_v - v0.m_v;
  210. const float cax = v2.m_x - v0.m_x;
  211. const float cay = v2.m_y - v0.m_y;
  212. const float caz = v2.m_z - v0.m_z;
  213. const float cau = v2.m_u - v0.m_u;
  214. const float cav = v2.m_v - v0.m_v;
  215. const float det = (bau * cav - bav * cau);
  216. const float invDet = 1.0f / det;
  217. const float tx = (bax * cav - cax * bav) * invDet;
  218. const float ty = (bay * cav - cay * bav) * invDet;
  219. const float tz = (baz * cav - caz * bav) * invDet;
  220. const float bx = (cax * bau - bax * cau) * invDet;
  221. const float by = (cay * bau - bay * cau) * invDet;
  222. const float bz = (caz * bau - baz * cau) * invDet;
  223. for (uint32_t jj = 0; jj < 3; ++jj)
  224. {
  225. float* tanu = &tangents[indices[jj]*6];
  226. float* tanv = &tanu[3];
  227. tanu[0] += tx;
  228. tanu[1] += ty;
  229. tanu[2] += tz;
  230. tanv[0] += bx;
  231. tanv[1] += by;
  232. tanv[2] += bz;
  233. }
  234. }
  235. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  236. {
  237. const bx::Vec3 tanu = bx::load<bx::Vec3>(&tangents[ii*6]);
  238. const bx::Vec3 tanv = bx::load<bx::Vec3>(&tangents[ii*6 + 3]);
  239. float nxyzw[4];
  240. bgfx::vertexUnpack(nxyzw, bgfx::Attrib::Normal, _layout, _vertices, ii);
  241. const bx::Vec3 normal = bx::load<bx::Vec3>(nxyzw);
  242. const float ndt = bx::dot(normal, tanu);
  243. const bx::Vec3 nxt = bx::cross(normal, tanu);
  244. const bx::Vec3 tmp = bx::sub(tanu, bx::mul(normal, ndt) );
  245. float tangent[4];
  246. bx::store(tangent, bx::normalize(tmp) );
  247. tangent[3] = bx::dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  248. bgfx::vertexPack(tangent, true, bgfx::Attrib::Tangent, _layout, _vertices, ii);
  249. }
  250. delete [] tangents;
  251. }
  252. void write(bx::WriterI* _writer, const void* _vertices, uint32_t _numVertices, uint32_t _stride)
  253. {
  254. Sphere maxSphere;
  255. calcMaxBoundingSphere(maxSphere, _vertices, _numVertices, _stride);
  256. Sphere minSphere;
  257. calcMinBoundingSphere(minSphere, _vertices, _numVertices, _stride);
  258. if (minSphere.radius > maxSphere.radius)
  259. {
  260. bx::write(_writer, maxSphere);
  261. }
  262. else
  263. {
  264. bx::write(_writer, minSphere);
  265. }
  266. Aabb aabb;
  267. toAabb(aabb, _vertices, _numVertices, _stride);
  268. bx::write(_writer, aabb);
  269. Obb obb;
  270. calcObb(obb, _vertices, _numVertices, _stride, s_obbSteps);
  271. bx::write(_writer, obb);
  272. }
  273. void write(bx::WriterI* _writer
  274. , const uint8_t* _vertices
  275. , uint32_t _numVertices
  276. , const bgfx::VertexLayout& _layout
  277. , const uint16_t* _indices
  278. , uint32_t _numIndices
  279. , bool _compress
  280. , const stl::string& _material
  281. , const PrimitiveArray& _primitives
  282. )
  283. {
  284. using namespace bx;
  285. using namespace bgfx;
  286. uint32_t stride = _layout.getStride();
  287. if (_compress)
  288. {
  289. write(_writer, BGFX_CHUNK_MAGIC_VBC);
  290. write(_writer, _vertices, _numVertices, stride);
  291. write(_writer, _layout);
  292. write(_writer, uint16_t(_numVertices) );
  293. writeCompressedVertices(_writer, _vertices, _numVertices, uint16_t(stride));
  294. }
  295. else
  296. {
  297. write(_writer, BGFX_CHUNK_MAGIC_VB);
  298. write(_writer, _vertices, _numVertices, stride);
  299. write(_writer, _layout);
  300. write(_writer, uint16_t(_numVertices) );
  301. write(_writer, _vertices, _numVertices*stride);
  302. }
  303. if (_compress)
  304. {
  305. write(_writer, BGFX_CHUNK_MAGIC_IBC);
  306. write(_writer, _numIndices);
  307. writeCompressedIndices(_writer, _indices, _numIndices, _numVertices);
  308. }
  309. else
  310. {
  311. write(_writer, BGFX_CHUNK_MAGIC_IB);
  312. write(_writer, _numIndices);
  313. write(_writer, _indices, _numIndices*2);
  314. }
  315. write(_writer, BGFX_CHUNK_MAGIC_PRI);
  316. uint16_t nameLen = uint16_t(_material.size() );
  317. write(_writer, nameLen);
  318. write(_writer, _material.c_str(), nameLen);
  319. write(_writer, uint16_t(_primitives.size() ) );
  320. for (PrimitiveArray::const_iterator primIt = _primitives.begin(); primIt != _primitives.end(); ++primIt)
  321. {
  322. const Primitive& prim = *primIt;
  323. nameLen = uint16_t(prim.m_name.size() );
  324. write(_writer, nameLen);
  325. write(_writer, prim.m_name.c_str(), nameLen);
  326. write(_writer, prim.m_startIndex);
  327. write(_writer, prim.m_numIndices);
  328. write(_writer, prim.m_startVertex);
  329. write(_writer, prim.m_numVertices);
  330. write(_writer, &_vertices[prim.m_startVertex*stride], prim.m_numVertices, stride);
  331. }
  332. }
  333. inline uint32_t rgbaToAbgr(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a)
  334. {
  335. return (uint32_t(_r)<<0)
  336. | (uint32_t(_g)<<8)
  337. | (uint32_t(_b)<<16)
  338. | (uint32_t(_a)<<24)
  339. ;
  340. }
  341. struct GroupSortByMaterial
  342. {
  343. bool operator()(const Group& _lhs, const Group& _rhs)
  344. {
  345. return 0 < bx::strCmp(_lhs.m_material.c_str(), _rhs.m_material.c_str() );
  346. }
  347. };
  348. void mtxCoordinateTransform(float* _result, const CoordinateSystem& _cs)
  349. {
  350. bx::Vec3 up = s_axisVectors[_cs.m_up];
  351. bx::Vec3 forward = s_axisVectors[_cs.m_forward];
  352. bx::Vec3 right = cross(forward,up);
  353. if ( _cs.m_handness == bx::Handness::Left)
  354. {
  355. right = bx::mul(right, -1.0f);
  356. }
  357. bx::mtxIdentity(_result);
  358. bx::store(&_result[0], right);
  359. bx::store(&_result[4], forward);
  360. bx::store(&_result[8], up);
  361. }
  362. float mtxDeterminant(const float* _a)
  363. {
  364. const float xx = _a[ 0];
  365. const float xy = _a[ 1];
  366. const float xz = _a[ 2];
  367. const float xw = _a[ 3];
  368. const float yx = _a[ 4];
  369. const float yy = _a[ 5];
  370. const float yz = _a[ 6];
  371. const float yw = _a[ 7];
  372. const float zx = _a[ 8];
  373. const float zy = _a[ 9];
  374. const float zz = _a[10];
  375. const float zw = _a[11];
  376. const float wx = _a[12];
  377. const float wy = _a[13];
  378. const float wz = _a[14];
  379. const float ww = _a[15];
  380. float det = 0.0f;
  381. det += xx * (yy*(zz*ww - zw*wz) - yz*(zy*ww - zw*wy) + yw*(zy*wz - zz*wy) );
  382. det -= xy * (yx*(zz*ww - zw*wz) - yz*(zx*ww - zw*wx) + yw*(zx*wz - zz*wx) );
  383. det += xz * (yx*(zy*ww - zw*wy) - yy*(zx*ww - zw*wx) + yw*(zx*wy - zy*wx) );
  384. det -= xw * (yx*(zy*wz - zz*wy) - yy*(zx*wz - zz*wx) + yz*(zx*wy - zy*wx) );
  385. return det;
  386. }
  387. void parseObj(char* _data, uint32_t _size, Mesh* _mesh, bool _hasBc)
  388. {
  389. // Reference(s):
  390. // - Wavefront .obj file
  391. // https://en.wikipedia.org/wiki/Wavefront_.obj_file
  392. // Coordinate system is right-handed, but up/forward is not defined, but +Y Up, +Z Forward seems to be a common default
  393. _mesh->m_coordinateSystem.m_handness = bx::Handness::Right;
  394. _mesh->m_coordinateSystem.m_up = Axis::PositiveY;
  395. _mesh->m_coordinateSystem.m_forward = Axis::PositiveZ;
  396. uint32_t num = 0;
  397. Group group;
  398. group.m_startTriangle = 0;
  399. group.m_numTriangles = 0;
  400. char commandLine[2048];
  401. uint32_t len = sizeof(commandLine);
  402. int argc;
  403. char* argv[64];
  404. for (bx::StringView next(_data, _size); !next.isEmpty(); )
  405. {
  406. next = bx::tokenizeCommandLine(next, commandLine, len, argc, argv, BX_COUNTOF(argv), '\n');
  407. if (0 < argc)
  408. {
  409. if (0 == bx::strCmp(argv[0], "#") )
  410. {
  411. if (2 < argc
  412. && 0 == bx::strCmp(argv[2], "polygons") )
  413. {
  414. }
  415. }
  416. else if (0 == bx::strCmp(argv[0], "f") )
  417. {
  418. TriIndices triangle;
  419. bx::memSet(&triangle, 0, sizeof(TriIndices) );
  420. const int numNormals = (int)_mesh->m_normals.size();
  421. const int numTexcoords = (int)_mesh->m_texcoords.size();
  422. const int numPositions = (int)_mesh->m_positions.size();
  423. for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge)
  424. {
  425. Index3 index;
  426. index.m_texcoord = -1;
  427. index.m_normal = -1;
  428. if (_hasBc)
  429. {
  430. index.m_vbc = edge < 3 ? edge : (1+(edge+1) )&1;
  431. }
  432. else
  433. {
  434. index.m_vbc = 0;
  435. }
  436. {
  437. bx::StringView triplet(argv[edge + 1]);
  438. bx::StringView vertex(triplet);
  439. bx::StringView texcoord = bx::strFind(triplet, '/');
  440. if (!texcoord.isEmpty())
  441. {
  442. vertex.set(vertex.getPtr(), texcoord.getPtr());
  443. const bx::StringView normal = bx::strFind(bx::StringView(texcoord.getPtr() + 1, triplet.getTerm()), '/');
  444. if (!normal.isEmpty())
  445. {
  446. int32_t nn;
  447. bx::fromString(&nn, bx::StringView(normal.getPtr() + 1, triplet.getTerm()));
  448. index.m_normal = (nn < 0) ? nn + numNormals : nn - 1;
  449. }
  450. texcoord.set(texcoord.getPtr() + 1, normal.getPtr());
  451. // Reference(s):
  452. // - Wavefront .obj file / Vertex normal indices without texture coordinate indices
  453. // https://en.wikipedia.org/wiki/Wavefront_.obj_file#Vertex_Normal_Indices_Without_Texture_Coordinate_Indices
  454. if (!texcoord.isEmpty())
  455. {
  456. int32_t tex;
  457. bx::fromString(&tex, texcoord);
  458. index.m_texcoord = (tex < 0) ? tex + numTexcoords : tex - 1;
  459. }
  460. }
  461. int32_t pos;
  462. bx::fromString(&pos, vertex);
  463. index.m_position = (pos < 0) ? pos + numPositions : pos - 1;
  464. }
  465. switch (edge)
  466. {
  467. case 0: case 1: case 2:
  468. triangle.m_index[edge] = index;
  469. if (2 == edge)
  470. {
  471. _mesh->m_triangles.push_back(triangle);
  472. }
  473. break;
  474. default:
  475. triangle.m_index[1] = triangle.m_index[2];
  476. triangle.m_index[2] = index;
  477. _mesh->m_triangles.push_back(triangle);
  478. break;
  479. }
  480. }
  481. }
  482. else if (0 == bx::strCmp(argv[0], "g") )
  483. {
  484. group.m_name = argv[1];
  485. }
  486. else if (*argv[0] == 'v')
  487. {
  488. group.m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - group.m_startTriangle;
  489. if (0 < group.m_numTriangles)
  490. {
  491. _mesh->m_groups.push_back(group);
  492. group.m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  493. group.m_numTriangles = 0;
  494. }
  495. if (0 == bx::strCmp(argv[0], "vn") )
  496. {
  497. bx::Vec3 normal;
  498. bx::fromString(&normal.x, argv[1]);
  499. bx::fromString(&normal.y, argv[2]);
  500. bx::fromString(&normal.z, argv[3]);
  501. _mesh->m_normals.push_back(normal);
  502. }
  503. else if (0 == bx::strCmp(argv[0], "vp") )
  504. {
  505. static bool once = true;
  506. if (once)
  507. {
  508. once = false;
  509. bx::printf("warning: 'parameter space vertices' are unsupported.\n");
  510. }
  511. }
  512. else if (0 == bx::strCmp(argv[0], "vt") )
  513. {
  514. bx::Vec3 texcoord;
  515. texcoord.y = 0.0f;
  516. texcoord.z = 0.0f;
  517. bx::fromString(&texcoord.x, argv[1]);
  518. switch (argc)
  519. {
  520. case 4:
  521. bx::fromString(&texcoord.z, argv[3]);
  522. BX_FALLTHROUGH;
  523. case 3:
  524. bx::fromString(&texcoord.y, argv[2]);
  525. break;
  526. default:
  527. break;
  528. }
  529. _mesh->m_texcoords.push_back(texcoord);
  530. }
  531. else
  532. {
  533. float px, py, pz, pw;
  534. bx::fromString(&px, argv[1]);
  535. bx::fromString(&py, argv[2]);
  536. bx::fromString(&pz, argv[3]);
  537. if (argc == 5 || argc == 8)
  538. {
  539. bx::fromString(&pw, argv[4]);
  540. }
  541. else
  542. {
  543. pw = 1.0f;
  544. }
  545. float invW = 1.0f/pw;
  546. px *= invW;
  547. py *= invW;
  548. pz *= invW;
  549. bx::Vec3 pos;
  550. pos.x = px;
  551. pos.y = py;
  552. pos.z = pz;
  553. _mesh->m_positions.push_back(pos);
  554. }
  555. }
  556. else if (0 == bx::strCmp(argv[0], "usemtl") )
  557. {
  558. stl::string material(argv[1]);
  559. if (0 != bx::strCmp(material.c_str(), group.m_material.c_str() ) )
  560. {
  561. group.m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - group.m_startTriangle;
  562. if (0 < group.m_numTriangles)
  563. {
  564. _mesh->m_groups.push_back(group);
  565. group.m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  566. group.m_numTriangles = 0;
  567. }
  568. }
  569. group.m_material = material;
  570. }
  571. // unsupported tags
  572. // else if (0 == bx::strCmp(argv[0], "mtllib") )
  573. // {
  574. // }
  575. // else if (0 == bx::strCmp(argv[0], "o") )
  576. // {
  577. // }
  578. // else if (0 == bx::strCmp(argv[0], "s") )
  579. // {
  580. // }
  581. }
  582. ++num;
  583. }
  584. group.m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - group.m_startTriangle;
  585. if (0 < group.m_numTriangles)
  586. {
  587. _mesh->m_groups.push_back(group);
  588. group.m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  589. group.m_numTriangles = 0;
  590. }
  591. bx::printf("obj parser # %d\n"
  592. , num );
  593. }
  594. void gltfReadFloat(const float* _accessorData, cgltf_size _accessorNumComponents, cgltf_size _index, cgltf_float* _out, cgltf_size _outElementSize)
  595. {
  596. const float* input = &_accessorData[_accessorNumComponents * _index];
  597. for (cgltf_size ii = 0; ii < _outElementSize; ++ii)
  598. {
  599. _out[ii] = (ii < _accessorNumComponents) ? input[ii] : 0.0f;
  600. }
  601. }
  602. void processGltfNode(cgltf_node* _node, Mesh* _mesh, Group* _group, bool _hasBc)
  603. {
  604. cgltf_mesh* mesh = _node->mesh;
  605. if (NULL != mesh)
  606. {
  607. float nodeToWorld[16];
  608. cgltf_node_transform_world(_node, nodeToWorld);
  609. float nodeToWorldNormal[16];
  610. bx::mtxCofactor(nodeToWorldNormal, nodeToWorld);
  611. for (cgltf_size primitiveIndex = 0; primitiveIndex < mesh->primitives_count; ++primitiveIndex)
  612. {
  613. cgltf_primitive* primitive = &mesh->primitives[primitiveIndex];
  614. cgltf_size numVertex = primitive->attributes[0].data->count;
  615. int32_t basePositionIndex = (int32_t)_mesh->m_positions.size();
  616. int32_t baseNormalIndex = (int32_t)_mesh->m_normals.size();
  617. int32_t baseTexcoordIndex = (int32_t)_mesh->m_texcoords.size();
  618. bool hasNormal = false;
  619. bool hasTexcoord = false;
  620. for (cgltf_size attributeIndex = 0; attributeIndex < primitive->attributes_count; ++attributeIndex)
  621. {
  622. cgltf_attribute* attribute = &primitive->attributes[attributeIndex];
  623. cgltf_accessor* accessor = attribute->data;
  624. cgltf_size accessorCount = accessor->count;
  625. BX_CHECK(numVertex == accessorCount, "Invalid attribute count");
  626. cgltf_size floatCount = cgltf_accessor_unpack_floats(accessor, NULL, 0);
  627. float* accessorData = (float*)malloc(floatCount * sizeof(float));
  628. cgltf_accessor_unpack_floats(accessor, accessorData, floatCount);
  629. cgltf_size numComponents = cgltf_num_components(accessor->type);
  630. if (attribute->type == cgltf_attribute_type_position && attribute->index == 0)
  631. {
  632. _mesh->m_positions.reserve(_mesh->m_positions.size() + accessorCount);
  633. bx::Vec3 pos;
  634. for(cgltf_size v=0;v<accessorCount;++v)
  635. {
  636. gltfReadFloat(accessorData, numComponents, v, &pos.x, 3);
  637. pos = mul(pos, nodeToWorld);
  638. _mesh->m_positions.push_back(pos);
  639. }
  640. }
  641. else if (attribute->type == cgltf_attribute_type_normal && attribute->index == 0)
  642. {
  643. _mesh->m_normals.reserve(_mesh->m_normals.size() + accessorCount);
  644. hasNormal = true;
  645. bx::Vec3 normal;
  646. for(cgltf_size v=0;v<accessorCount;++v)
  647. {
  648. gltfReadFloat(accessorData, numComponents, v, &normal.x, 3);
  649. normal = mul(normal, nodeToWorldNormal);
  650. _mesh->m_normals.push_back(normal);
  651. }
  652. }
  653. else if (attribute->type == cgltf_attribute_type_texcoord && attribute->index == 0)
  654. {
  655. _mesh->m_texcoords.reserve(_mesh->m_texcoords.size() + accessorCount);
  656. hasTexcoord = true;
  657. bx::Vec3 texcoord;
  658. for(cgltf_size v=0;v<accessorCount;++v)
  659. {
  660. gltfReadFloat(accessorData, numComponents, v, &texcoord.x, 3);
  661. _mesh->m_texcoords.push_back(texcoord);
  662. }
  663. }
  664. free(accessorData);
  665. }
  666. if ( primitive->indices != NULL )
  667. {
  668. cgltf_accessor* accessor = primitive->indices;
  669. for(cgltf_size v=0;v<accessor->count; v+=3)
  670. {
  671. TriIndices triangle;
  672. for(int i=0;i<3;++i)
  673. {
  674. Index3 index;
  675. int32_t vertexIndex = int32_t(cgltf_accessor_read_index(accessor, v+i));
  676. index.m_position = basePositionIndex + vertexIndex;
  677. index.m_normal = hasNormal ? baseNormalIndex + vertexIndex : -1;
  678. index.m_texcoord = hasTexcoord ? baseTexcoordIndex + vertexIndex : -1;
  679. index.m_vbc = _hasBc ? i : 0;
  680. triangle.m_index[i] = index;
  681. }
  682. _mesh->m_triangles.push_back(triangle);
  683. }
  684. }
  685. else
  686. {
  687. for(cgltf_size v=0;v<numVertex; v+=3)
  688. {
  689. TriIndices triangle;
  690. for(int i=0;i<3;++i)
  691. {
  692. Index3 index;
  693. int32_t vertexIndex = int32_t(v * 3 + i);
  694. index.m_position = basePositionIndex + vertexIndex;
  695. index.m_normal = hasNormal ? baseNormalIndex + vertexIndex : -1;
  696. index.m_texcoord = hasTexcoord ? baseTexcoordIndex + vertexIndex : -1;
  697. index.m_vbc = _hasBc ? i : 0;
  698. triangle.m_index[i] = index;
  699. }
  700. _mesh->m_triangles.push_back(triangle);
  701. }
  702. }
  703. _group->m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - _group->m_startTriangle;
  704. if (0 < _group->m_numTriangles)
  705. {
  706. _mesh->m_groups.push_back(*_group);
  707. _group->m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  708. _group->m_numTriangles = 0;
  709. }
  710. }
  711. }
  712. for (cgltf_size childIndex = 0; childIndex < _node->children_count; ++childIndex)
  713. processGltfNode(_node->children[childIndex], _mesh, _group, _hasBc);
  714. }
  715. void parseGltf(char* _data, uint32_t _size, Mesh* _mesh, bool _hasBc, const bx::StringView& _path)
  716. {
  717. // Reference(s):
  718. // - Gltf 2.0 specification
  719. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0
  720. _mesh->m_coordinateSystem.m_handness = bx::Handness::Right;
  721. _mesh->m_coordinateSystem.m_forward = Axis::PositiveZ;
  722. _mesh->m_coordinateSystem.m_up = Axis::PositiveY;
  723. Group group;
  724. group.m_startTriangle = 0;
  725. group.m_numTriangles = 0;
  726. cgltf_options options = { };
  727. cgltf_data* data = NULL;
  728. cgltf_result result = cgltf_parse(&options, _data, _size, &data);
  729. if (result == cgltf_result_success)
  730. {
  731. char* path = (char*)malloc(_path.getLength()+1);
  732. bx::memCopy(path, _path.getPtr(), _path.getLength());
  733. path[_path.getLength()] = 0;
  734. result = cgltf_load_buffers(&options, data, path);
  735. free(path);
  736. if (result == cgltf_result_success)
  737. {
  738. for (cgltf_size sceneIndex = 0; sceneIndex < data->scenes_count; ++sceneIndex)
  739. {
  740. cgltf_scene* scene = &data->scenes[sceneIndex];
  741. for (cgltf_size nodeIndex = 0; nodeIndex < scene->nodes_count; ++nodeIndex)
  742. {
  743. cgltf_node* node = scene->nodes[nodeIndex];
  744. processGltfNode(node, _mesh, &group, _hasBc);
  745. }
  746. }
  747. }
  748. cgltf_free(data);
  749. }
  750. }
  751. void help(const char* _error = NULL)
  752. {
  753. if (NULL != _error)
  754. {
  755. bx::printf("Error:\n%s\n\n", _error);
  756. }
  757. bx::printf(
  758. "geometryc, bgfx geometry compiler tool, version %d.%d.%d.\n"
  759. "Copyright 2011-2020 Branimir Karadzic. All rights reserved.\n"
  760. "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n\n"
  761. , BGFX_GEOMETRYC_VERSION_MAJOR
  762. , BGFX_GEOMETRYC_VERSION_MINOR
  763. , BGFX_API_VERSION
  764. );
  765. bx::printf(
  766. "Usage: geometryc -f <in> -o <out>\n"
  767. "\n"
  768. "Supported input file types:\n"
  769. " *.obj Wavefront\n"
  770. " *.gltf,*.glb glTF 2.0\n"
  771. "\n"
  772. "Options:\n"
  773. " -h, --help Help.\n"
  774. " -v, --version Version information only.\n"
  775. " -f <file path> Input file path.\n"
  776. " -o <file path> Output file path.\n"
  777. " -s, --scale <num> Scale factor.\n"
  778. " --ccw Front face is counter-clockwise winding order.\n"
  779. " --flipv Flip texture coordinate V.\n"
  780. " --obb <num> Number of steps for calculating oriented bounding box.\n"
  781. " Default value is 17. Less steps less precise OBB is.\n"
  782. " More steps slower calculation.\n"
  783. " --packnormal <num> Normal packing.\n"
  784. " 0 - unpacked 12 bytes (default).\n"
  785. " 1 - packed 4 bytes.\n"
  786. " --packuv <num> Texture coordinate packing.\n"
  787. " 0 - unpacked 8 bytes (default).\n"
  788. " 1 - packed 4 bytes.\n"
  789. " --tangent Calculate tangent vectors (packing mode is the same as normal).\n"
  790. " --barycentric Adds barycentric vertex attribute (packed in bgfx::Attrib::Color1).\n"
  791. " -c, --compress Compress indices.\n"
  792. " --[l/r]h-up+[y/z] Coordinate system. Default is '--lh-up+y' Left-Handed +Y is up.\n"
  793. "\n"
  794. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  795. );
  796. }
  797. int main(int _argc, const char* _argv[])
  798. {
  799. bx::CommandLine cmdLine(_argc, _argv);
  800. if (cmdLine.hasArg('v', "version"))
  801. {
  802. bx::printf(
  803. "geometryc, bgfx geometry compiler tool, version %d.%d.%d.\n"
  804. , BGFX_GEOMETRYC_VERSION_MAJOR
  805. , BGFX_GEOMETRYC_VERSION_MINOR
  806. , BGFX_API_VERSION
  807. );
  808. return bx::kExitSuccess;
  809. }
  810. if (cmdLine.hasArg('h', "help"))
  811. {
  812. help();
  813. return bx::kExitFailure;
  814. }
  815. const char* filePath = cmdLine.findOption('f');
  816. if (NULL == filePath)
  817. {
  818. help("Input file name must be specified.");
  819. return bx::kExitFailure;
  820. }
  821. const char* outFilePath = cmdLine.findOption('o');
  822. if (NULL == outFilePath)
  823. {
  824. help("Output file name must be specified.");
  825. return bx::kExitFailure;
  826. }
  827. float scale = 1.0f;
  828. const char* scaleArg = cmdLine.findOption('s', "scale");
  829. if (NULL != scaleArg)
  830. {
  831. if (!bx::fromString(&scale, scaleArg))
  832. {
  833. scale = 1.0f;
  834. }
  835. }
  836. bool compress = cmdLine.hasArg('c', "compress");
  837. cmdLine.hasArg(s_obbSteps, '\0', "obb");
  838. s_obbSteps = bx::uint32_min(bx::uint32_max(s_obbSteps, 1), 90);
  839. uint32_t packNormal = 0;
  840. cmdLine.hasArg(packNormal, '\0', "packnormal");
  841. uint32_t packUv = 0;
  842. cmdLine.hasArg(packUv, '\0', "packuv");
  843. bool ccw = cmdLine.hasArg("ccw");
  844. bool flipV = cmdLine.hasArg("flipv");
  845. bool hasTangent = cmdLine.hasArg("tangent");
  846. bool hasBc = cmdLine.hasArg("barycentric");
  847. CoordinateSystem outputCoordinateSystem;
  848. outputCoordinateSystem.m_handness = bx::Handness::Left;
  849. outputCoordinateSystem.m_forward = Axis::PositiveZ;
  850. outputCoordinateSystem.m_up = Axis::PositiveY;
  851. for (uint32_t ii = 0; ii < BX_COUNTOF(s_coordinateSystemMappings); ++ii)
  852. {
  853. if (cmdLine.hasArg(s_coordinateSystemMappings[ii].m_param))
  854. {
  855. outputCoordinateSystem = s_coordinateSystemMappings[ii].m_coordinateSystem;
  856. }
  857. }
  858. bx::FileReader fr;
  859. if (!bx::open(&fr, filePath) )
  860. {
  861. bx::printf("Unable to open input file '%s'.", filePath);
  862. return bx::kExitFailure;
  863. }
  864. int64_t parseElapsed = -bx::getHPCounter();
  865. int64_t triReorderElapsed = 0;
  866. uint32_t size = (uint32_t)bx::getSize(&fr);
  867. char* data = new char[size+1];
  868. size = bx::read(&fr, data, size);
  869. data[size] = '\0';
  870. bx::close(&fr);
  871. Mesh mesh;
  872. bx::StringView ext = bx::FilePath(filePath).getExt();
  873. if (0 == bx::strCmpI(ext, ".obj"))
  874. {
  875. parseObj(data, size, &mesh, hasBc);
  876. }
  877. else if (0 == bx::strCmpI(ext, ".gltf") || 0 == bx::strCmpI(ext, ".glb"))
  878. {
  879. parseGltf(data, size, &mesh, hasBc, bx::FilePath(filePath).getPath());
  880. }
  881. else
  882. {
  883. bx::printf("Unsupported input file format '%s'.", filePath);
  884. exit(bx::kExitFailure);
  885. }
  886. delete [] data;
  887. int64_t now = bx::getHPCounter();
  888. parseElapsed += now;
  889. int64_t convertElapsed = -now;
  890. std::sort(mesh.m_groups.begin(), mesh.m_groups.end(), GroupSortByMaterial() );
  891. bool changeWinding = ccw;
  892. if (scale != 1.0f)
  893. {
  894. for (Vec3Array::iterator it = mesh.m_positions.begin(), itEnd = mesh.m_positions.end(); it != itEnd; ++it)
  895. {
  896. it->x *= scale;
  897. it->y *= scale;
  898. it->z *= scale;
  899. }
  900. }
  901. {
  902. float meshTransform[16];
  903. mtxCoordinateTransform(meshTransform, mesh.m_coordinateSystem);
  904. float meshInvTranform[16];
  905. bx::mtxTranspose(meshInvTranform, meshTransform);
  906. float outTransform[16];
  907. mtxCoordinateTransform(outTransform, outputCoordinateSystem);
  908. float transform[16];
  909. bx::mtxMul(transform, meshInvTranform, outTransform);
  910. if ( mtxDeterminant(transform) < 0.0f )
  911. {
  912. changeWinding = !changeWinding;
  913. }
  914. float identity[16];
  915. bx::mtxIdentity(identity);
  916. if ( 0 != bx::memCmp(identity, transform, sizeof(transform) ) )
  917. {
  918. for (Vec3Array::iterator it = mesh.m_positions.begin(), itEnd = mesh.m_positions.end(); it != itEnd; ++it)
  919. {
  920. *it = bx::mul(*it, transform);
  921. }
  922. for (Vec3Array::iterator it = mesh.m_normals.begin(), itEnd = mesh.m_normals.end(); it != itEnd; ++it)
  923. {
  924. *it = bx::mul(*it, transform);
  925. }
  926. }
  927. }
  928. bool hasColor = false;
  929. bool hasNormal = false;
  930. bool hasTexcoord = false;
  931. {
  932. for (TriangleArray::iterator jt = mesh.m_triangles.begin(), jtEnd = mesh.m_triangles.end(); jt != jtEnd && !hasTexcoord; ++jt)
  933. {
  934. for (uint32_t i = 0; i < 3; ++i)
  935. {
  936. hasTexcoord |= -1 != jt->m_index[i].m_texcoord;
  937. }
  938. }
  939. for (TriangleArray::iterator jt = mesh.m_triangles.begin(), jtEnd = mesh.m_triangles.end(); jt != jtEnd && !hasNormal; ++jt)
  940. {
  941. for (uint32_t i = 0; i < 3; ++i)
  942. {
  943. hasNormal |= -1 != jt->m_index[i].m_normal;
  944. }
  945. }
  946. if (changeWinding)
  947. {
  948. for (TriangleArray::iterator jt = mesh.m_triangles.begin(), jtEnd = mesh.m_triangles.end(); jt != jtEnd; ++jt)
  949. {
  950. bx::swap(jt->m_index[1], jt->m_index[2]);
  951. }
  952. }
  953. }
  954. bgfx::VertexLayout layout;
  955. layout.begin();
  956. layout.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  957. if (hasColor)
  958. {
  959. layout.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  960. }
  961. if (hasBc)
  962. {
  963. layout.add(bgfx::Attrib::Color1, 4, bgfx::AttribType::Uint8, true);
  964. }
  965. if (hasTexcoord)
  966. {
  967. switch (packUv)
  968. {
  969. default:
  970. case 0:
  971. layout.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  972. break;
  973. case 1:
  974. layout.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
  975. break;
  976. }
  977. }
  978. if (hasNormal)
  979. {
  980. hasTangent &= hasTexcoord;
  981. switch (packNormal)
  982. {
  983. default:
  984. case 0:
  985. layout.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
  986. if (hasTangent)
  987. {
  988. layout.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float);
  989. }
  990. break;
  991. case 1:
  992. layout.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
  993. if (hasTangent)
  994. {
  995. layout.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true);
  996. }
  997. break;
  998. }
  999. }
  1000. layout.end();
  1001. uint32_t stride = layout.getStride();
  1002. uint8_t* vertexData = new uint8_t[mesh.m_triangles.size() * 3 * stride];
  1003. uint16_t* indexData = new uint16_t[mesh.m_triangles.size() * 3];
  1004. int32_t numVertices = 0;
  1005. int32_t numIndices = 0;
  1006. int32_t writtenPrimitives = 0;
  1007. int32_t writtenVertices = 0;
  1008. int32_t writtenIndices = 0;
  1009. uint8_t* vertices = vertexData;
  1010. uint16_t* indices = indexData;
  1011. const uint32_t tableSize = 65536 * 2;
  1012. const uint32_t hashmod = tableSize - 1;
  1013. uint32_t* table = new uint32_t[tableSize];
  1014. bx::memSet(table, 0xff, tableSize * sizeof(uint32_t));
  1015. stl::string material = mesh.m_groups.empty() ? "" : mesh.m_groups.begin()->m_material;
  1016. PrimitiveArray primitives;
  1017. bx::FileWriter writer;
  1018. if (!bx::open(&writer, outFilePath) )
  1019. {
  1020. bx::printf("Unable to open output file '%s'.", outFilePath);
  1021. exit(bx::kExitFailure);
  1022. }
  1023. Primitive prim;
  1024. prim.m_startVertex = 0;
  1025. prim.m_startIndex = 0;
  1026. uint32_t positionOffset = layout.getOffset(bgfx::Attrib::Position);
  1027. uint32_t color0Offset = layout.getOffset(bgfx::Attrib::Color0);
  1028. Group sentinelGroup;
  1029. sentinelGroup.m_startTriangle = 0;
  1030. sentinelGroup.m_numTriangles = UINT32_MAX;
  1031. mesh.m_groups.push_back(sentinelGroup);
  1032. uint32_t ii = 0;
  1033. for (GroupArray::const_iterator groupIt = mesh.m_groups.begin(); groupIt != mesh.m_groups.end(); ++groupIt, ++ii)
  1034. {
  1035. bool sentinel = groupIt->m_startTriangle == 0 && groupIt->m_numTriangles == UINT32_MAX;
  1036. for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
  1037. {
  1038. if (0 != bx::strCmp(material.c_str(), groupIt->m_material.c_str() )
  1039. || sentinel
  1040. || 65533 <= numVertices)
  1041. {
  1042. prim.m_numVertices = numVertices - prim.m_startVertex;
  1043. prim.m_numIndices = numIndices - prim.m_startIndex;
  1044. if (0 < prim.m_numVertices)
  1045. {
  1046. primitives.push_back(prim);
  1047. }
  1048. if (hasTangent)
  1049. {
  1050. calcTangents(vertexData, uint16_t(numVertices), layout, indexData, numIndices);
  1051. }
  1052. triReorderElapsed -= bx::getHPCounter();
  1053. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  1054. {
  1055. const Primitive& prim1 = *primIt;
  1056. optimizeVertexCache(indexData + prim1.m_startIndex, prim1.m_numIndices, numVertices);
  1057. }
  1058. numVertices = optimizeVertexFetch(indexData, numIndices, vertexData, numVertices, uint16_t(stride));
  1059. triReorderElapsed += bx::getHPCounter();
  1060. if ( numVertices > 0 && numIndices > 0 )
  1061. {
  1062. write(&writer
  1063. , vertexData
  1064. , numVertices
  1065. , layout
  1066. , indexData
  1067. , numIndices
  1068. , compress
  1069. , material
  1070. , primitives
  1071. );
  1072. }
  1073. primitives.clear();
  1074. bx::memSet(table, 0xff, tableSize * sizeof(uint32_t));
  1075. ++writtenPrimitives;
  1076. writtenVertices += numVertices;
  1077. writtenIndices += numIndices;
  1078. vertices = vertexData;
  1079. indices = indexData;
  1080. numVertices = 0;
  1081. numIndices = 0;
  1082. prim.m_startVertex = 0;
  1083. prim.m_startIndex = 0;
  1084. material = groupIt->m_material;
  1085. if (sentinel)
  1086. break;
  1087. }
  1088. TriIndices& triangle = mesh.m_triangles[tri];
  1089. for (uint32_t edge = 0; edge < 3; ++edge)
  1090. {
  1091. Index3& index = triangle.m_index[edge];
  1092. float* position = (float*)(vertices + positionOffset);
  1093. bx::memCopy(position, &mesh.m_positions[index.m_position], 3*sizeof(float) );
  1094. if (hasColor)
  1095. {
  1096. uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
  1097. *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
  1098. }
  1099. if (hasBc)
  1100. {
  1101. const float bc[4] =
  1102. {
  1103. (index.m_vbc == 0) ? 1.0f : 0.0f,
  1104. (index.m_vbc == 1) ? 1.0f : 0.0f,
  1105. (index.m_vbc == 2) ? 1.0f : 0.0f,
  1106. 0.0f
  1107. };
  1108. bgfx::vertexPack(bc, true, bgfx::Attrib::Color1, layout, vertices);
  1109. }
  1110. if (hasTexcoord)
  1111. {
  1112. float uv[2];
  1113. bx::memCopy(uv, &mesh.m_texcoords[index.m_texcoord == -1 ? 0 : index.m_texcoord], 2*sizeof(float) );
  1114. if (flipV)
  1115. {
  1116. uv[1] = -uv[1];
  1117. }
  1118. bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, layout, vertices);
  1119. }
  1120. if (hasNormal)
  1121. {
  1122. float normal[4];
  1123. bx::store(normal, bx::normalize(bx::load<bx::Vec3>(&mesh.m_normals[index.m_normal == -1 ? 0 : index.m_normal]) ) );
  1124. normal[3] = 0.0f;
  1125. bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, layout, vertices);
  1126. }
  1127. uint32_t hash = bx::hash<bx::HashMurmur2A>(vertices, stride);
  1128. size_t bucket = hash & hashmod;
  1129. uint32_t vertexIndex = UINT32_MAX;
  1130. for (size_t probe = 0; probe <= hashmod; ++probe)
  1131. {
  1132. uint32_t& item = table[bucket];
  1133. if (item == ~0u)
  1134. {
  1135. vertices += stride;
  1136. item = numVertices++;
  1137. vertexIndex = item;
  1138. break;
  1139. }
  1140. if (0 == bx::memCmp(vertexData + item * stride, vertices, stride))
  1141. {
  1142. vertexIndex = item;
  1143. break;
  1144. }
  1145. bucket = (bucket + probe + 1) & hashmod;
  1146. }
  1147. if ( vertexIndex == UINT32_MAX )
  1148. {
  1149. bx::printf("hash table insert failed");
  1150. exit(bx::kExitFailure);
  1151. }
  1152. *indices++ = (uint16_t)vertexIndex;
  1153. ++numIndices;
  1154. }
  1155. }
  1156. prim.m_numVertices = numVertices - prim.m_startVertex;
  1157. if (0 < prim.m_numVertices)
  1158. {
  1159. prim.m_numIndices = numIndices - prim.m_startIndex;
  1160. prim.m_name = groupIt->m_name;
  1161. primitives.push_back(prim);
  1162. prim.m_startVertex = numVertices;
  1163. prim.m_startIndex = numIndices;
  1164. }
  1165. BX_TRACE("%3d: s %5d, n %5d, %s\n"
  1166. , ii
  1167. , groupIt->m_startTriangle
  1168. , groupIt->m_numTriangles
  1169. , groupIt->m_material.c_str()
  1170. );
  1171. }
  1172. BX_CHECK(0 == primitives.size(), "Not all primitives are written");
  1173. bx::printf("size: %d\n", uint32_t(bx::seek(&writer) ) );
  1174. bx::close(&writer);
  1175. delete [] table;
  1176. delete [] indexData;
  1177. delete [] vertexData;
  1178. now = bx::getHPCounter();
  1179. convertElapsed += now;
  1180. bx::printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\ng %d, p %d, v %d, i %d\n"
  1181. , double(parseElapsed)/bx::getHPFrequency()
  1182. , double(triReorderElapsed)/bx::getHPFrequency()
  1183. , double(convertElapsed)/bx::getHPFrequency()
  1184. , uint32_t(mesh.m_groups.size()-1)
  1185. , writtenPrimitives
  1186. , writtenVertices
  1187. , writtenIndices
  1188. );
  1189. return bx::kExitSuccess;
  1190. }