bgfx_utils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <string.h> // strlen
  6. #include <tinystl/allocator.h>
  7. #include <tinystl/vector.h>
  8. #include <tinystl/string.h>
  9. namespace stl = tinystl;
  10. #include <bgfx.h>
  11. #include <bx/readerwriter.h>
  12. #include <bx/fpumath.h>
  13. #include "entry/entry.h"
  14. #include <ib-compress/indexbufferdecompression.h>
  15. #include "bgfx_utils.h"
  16. void* load(bx::FileReaderI* _reader, const char* _filePath, uint32_t* _size)
  17. {
  18. if (0 == bx::open(_reader, _filePath) )
  19. {
  20. uint32_t size = (uint32_t)bx::getSize(_reader);
  21. void* data = malloc(size);
  22. bx::read(_reader, data, size);
  23. bx::close(_reader);
  24. if (NULL != _size)
  25. {
  26. *_size = size;
  27. }
  28. return data;
  29. }
  30. if (NULL != _size)
  31. {
  32. *_size = 0;
  33. }
  34. return NULL;
  35. }
  36. void* load(const char* _filePath, uint32_t* _size)
  37. {
  38. return load(entry::getFileReader(), _filePath, _size);
  39. }
  40. static const bgfx::Memory* loadMem(bx::FileReaderI* _reader, const char* _filePath)
  41. {
  42. if (0 == bx::open(_reader, _filePath) )
  43. {
  44. uint32_t size = (uint32_t)bx::getSize(_reader);
  45. const bgfx::Memory* mem = bgfx::alloc(size+1);
  46. bx::read(_reader, mem->data, size);
  47. bx::close(_reader);
  48. mem->data[mem->size-1] = '\0';
  49. return mem;
  50. }
  51. return NULL;
  52. }
  53. static bgfx::ShaderHandle loadShader(bx::FileReaderI* _reader, const char* _name)
  54. {
  55. char filePath[512];
  56. const char* shaderPath = "shaders/dx9/";
  57. switch (bgfx::getRendererType() )
  58. {
  59. case bgfx::RendererType::Direct3D11:
  60. shaderPath = "shaders/dx11/";
  61. break;
  62. case bgfx::RendererType::OpenGL:
  63. shaderPath = "shaders/glsl/";
  64. break;
  65. case bgfx::RendererType::OpenGLES:
  66. shaderPath = "shaders/gles/";
  67. break;
  68. default:
  69. break;
  70. }
  71. strcpy(filePath, shaderPath);
  72. strcat(filePath, _name);
  73. strcat(filePath, ".bin");
  74. return bgfx::createShader(loadMem(_reader, filePath) );
  75. }
  76. bgfx::ShaderHandle loadShader(const char* _name)
  77. {
  78. return loadShader(entry::getFileReader(), _name);
  79. }
  80. bgfx::ProgramHandle loadProgram(bx::FileReaderI* _reader, const char* _vsName, const char* _fsName)
  81. {
  82. bgfx::ShaderHandle vsh = loadShader(_reader, _vsName);
  83. bgfx::ShaderHandle fsh = loadShader(_reader, _fsName);
  84. return bgfx::createProgram(vsh, fsh, true /* destroy shaders when program is destroyed */);
  85. }
  86. bgfx::ProgramHandle loadProgram(const char* _vsName, const char* _fsName)
  87. {
  88. return loadProgram(entry::getFileReader(), _vsName, _fsName);
  89. }
  90. bgfx::TextureHandle loadTexture(bx::FileReaderI* _reader, const char* _name, uint32_t _flags, uint8_t _skip, bgfx::TextureInfo* _info)
  91. {
  92. char filePath[512];
  93. strcpy(filePath, "textures/");
  94. strcat(filePath, _name);
  95. const bgfx::Memory* mem = loadMem(_reader, filePath);
  96. return bgfx::createTexture(mem, _flags, _skip, _info);
  97. }
  98. bgfx::TextureHandle loadTexture(const char* _name, uint32_t _flags, uint8_t _skip, bgfx::TextureInfo* _info)
  99. {
  100. return loadTexture(entry::getFileReader(), _name, _flags, _skip, _info);
  101. }
  102. void calcTangents(void* _vertices, uint16_t _numVertices, bgfx::VertexDecl _decl, const uint16_t* _indices, uint32_t _numIndices)
  103. {
  104. struct PosTexcoord
  105. {
  106. float m_x;
  107. float m_y;
  108. float m_z;
  109. float m_pad0;
  110. float m_u;
  111. float m_v;
  112. float m_pad1;
  113. float m_pad2;
  114. };
  115. float* tangents = new float[6*_numVertices];
  116. memset(tangents, 0, 6*_numVertices*sizeof(float) );
  117. PosTexcoord v0;
  118. PosTexcoord v1;
  119. PosTexcoord v2;
  120. for (uint32_t ii = 0, num = _numIndices/3; ii < num; ++ii)
  121. {
  122. const uint16_t* indices = &_indices[ii*3];
  123. uint32_t i0 = indices[0];
  124. uint32_t i1 = indices[1];
  125. uint32_t i2 = indices[2];
  126. bgfx::vertexUnpack(&v0.m_x, bgfx::Attrib::Position, _decl, _vertices, i0);
  127. bgfx::vertexUnpack(&v0.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i0);
  128. bgfx::vertexUnpack(&v1.m_x, bgfx::Attrib::Position, _decl, _vertices, i1);
  129. bgfx::vertexUnpack(&v1.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i1);
  130. bgfx::vertexUnpack(&v2.m_x, bgfx::Attrib::Position, _decl, _vertices, i2);
  131. bgfx::vertexUnpack(&v2.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i2);
  132. const float bax = v1.m_x - v0.m_x;
  133. const float bay = v1.m_y - v0.m_y;
  134. const float baz = v1.m_z - v0.m_z;
  135. const float bau = v1.m_u - v0.m_u;
  136. const float bav = v1.m_v - v0.m_v;
  137. const float cax = v2.m_x - v0.m_x;
  138. const float cay = v2.m_y - v0.m_y;
  139. const float caz = v2.m_z - v0.m_z;
  140. const float cau = v2.m_u - v0.m_u;
  141. const float cav = v2.m_v - v0.m_v;
  142. const float det = (bau * cav - bav * cau);
  143. const float invDet = 1.0f / det;
  144. const float tx = (bax * cav - cax * bav) * invDet;
  145. const float ty = (bay * cav - cay * bav) * invDet;
  146. const float tz = (baz * cav - caz * bav) * invDet;
  147. const float bx = (cax * bau - bax * cau) * invDet;
  148. const float by = (cay * bau - bay * cau) * invDet;
  149. const float bz = (caz * bau - baz * cau) * invDet;
  150. for (uint32_t jj = 0; jj < 3; ++jj)
  151. {
  152. float* tanu = &tangents[indices[jj]*6];
  153. float* tanv = &tanu[3];
  154. tanu[0] += tx;
  155. tanu[1] += ty;
  156. tanu[2] += tz;
  157. tanv[0] += bx;
  158. tanv[1] += by;
  159. tanv[2] += bz;
  160. }
  161. }
  162. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  163. {
  164. const float* tanu = &tangents[ii*6];
  165. const float* tanv = &tangents[ii*6 + 3];
  166. float normal[4];
  167. bgfx::vertexUnpack(normal, bgfx::Attrib::Normal, _decl, _vertices, ii);
  168. float ndt = bx::vec3Dot(normal, tanu);
  169. float nxt[3];
  170. bx::vec3Cross(nxt, normal, tanu);
  171. float tmp[3];
  172. tmp[0] = tanu[0] - normal[0] * ndt;
  173. tmp[1] = tanu[1] - normal[1] * ndt;
  174. tmp[2] = tanu[2] - normal[2] * ndt;
  175. float tangent[4];
  176. bx::vec3Norm(tangent, tmp);
  177. tangent[3] = bx::vec3Dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  178. bgfx::vertexPack(tangent, true, bgfx::Attrib::Tangent, _decl, _vertices, ii);
  179. }
  180. delete [] tangents;
  181. }
  182. struct Aabb
  183. {
  184. float m_min[3];
  185. float m_max[3];
  186. };
  187. struct Obb
  188. {
  189. float m_mtx[16];
  190. };
  191. struct Sphere
  192. {
  193. float m_center[3];
  194. float m_radius;
  195. };
  196. struct Primitive
  197. {
  198. uint32_t m_startIndex;
  199. uint32_t m_numIndices;
  200. uint32_t m_startVertex;
  201. uint32_t m_numVertices;
  202. Sphere m_sphere;
  203. Aabb m_aabb;
  204. Obb m_obb;
  205. };
  206. typedef stl::vector<Primitive> PrimitiveArray;
  207. struct Group
  208. {
  209. Group()
  210. {
  211. reset();
  212. }
  213. void reset()
  214. {
  215. m_vbh.idx = bgfx::invalidHandle;
  216. m_ibh.idx = bgfx::invalidHandle;
  217. m_prims.clear();
  218. }
  219. bgfx::VertexBufferHandle m_vbh;
  220. bgfx::IndexBufferHandle m_ibh;
  221. Sphere m_sphere;
  222. Aabb m_aabb;
  223. Obb m_obb;
  224. PrimitiveArray m_prims;
  225. };
  226. namespace bgfx
  227. {
  228. int32_t read(bx::ReaderI* _reader, bgfx::VertexDecl& _decl);
  229. }
  230. struct Mesh
  231. {
  232. void load(bx::ReaderSeekerI* _reader)
  233. {
  234. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x1)
  235. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  236. #define BGFX_CHUNK_MAGIC_IBC BX_MAKEFOURCC('I', 'B', 'C', 0x0)
  237. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  238. using namespace bx;
  239. using namespace bgfx;
  240. Group group;
  241. bx::ReallocatorI* allocator = entry::getAllocator();
  242. uint32_t chunk;
  243. while (4 == bx::read(_reader, chunk) )
  244. {
  245. switch (chunk)
  246. {
  247. case BGFX_CHUNK_MAGIC_VB:
  248. {
  249. read(_reader, group.m_sphere);
  250. read(_reader, group.m_aabb);
  251. read(_reader, group.m_obb);
  252. read(_reader, m_decl);
  253. uint16_t stride = m_decl.getStride();
  254. uint16_t numVertices;
  255. read(_reader, numVertices);
  256. const bgfx::Memory* mem = bgfx::alloc(numVertices*stride);
  257. read(_reader, mem->data, mem->size);
  258. group.m_vbh = bgfx::createVertexBuffer(mem, m_decl);
  259. }
  260. break;
  261. case BGFX_CHUNK_MAGIC_IB:
  262. {
  263. uint32_t numIndices;
  264. read(_reader, numIndices);
  265. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  266. read(_reader, mem->data, mem->size);
  267. group.m_ibh = bgfx::createIndexBuffer(mem);
  268. }
  269. break;
  270. case BGFX_CHUNK_MAGIC_IBC:
  271. {
  272. uint32_t numIndices;
  273. bx::read(_reader, numIndices);
  274. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  275. uint32_t compressedSize;
  276. bx::read(_reader, compressedSize);
  277. void* compressedIndices = BX_ALLOC(allocator, compressedSize);
  278. bx::read(_reader, compressedIndices, compressedSize);
  279. ReadBitstream rbs( (const uint8_t*)compressedIndices, compressedSize);
  280. DecompressIndexBuffer( (uint16_t*)mem->data, numIndices / 3, rbs);
  281. BX_FREE(allocator, compressedIndices);
  282. group.m_ibh = bgfx::createIndexBuffer(mem);
  283. }
  284. break;
  285. case BGFX_CHUNK_MAGIC_PRI:
  286. {
  287. uint16_t len;
  288. read(_reader, len);
  289. stl::string material;
  290. material.resize(len);
  291. read(_reader, const_cast<char*>(material.c_str() ), len);
  292. uint16_t num;
  293. read(_reader, num);
  294. for (uint32_t ii = 0; ii < num; ++ii)
  295. {
  296. read(_reader, len);
  297. stl::string name;
  298. name.resize(len);
  299. read(_reader, const_cast<char*>(name.c_str() ), len);
  300. Primitive prim;
  301. read(_reader, prim.m_startIndex);
  302. read(_reader, prim.m_numIndices);
  303. read(_reader, prim.m_startVertex);
  304. read(_reader, prim.m_numVertices);
  305. read(_reader, prim.m_sphere);
  306. read(_reader, prim.m_aabb);
  307. read(_reader, prim.m_obb);
  308. group.m_prims.push_back(prim);
  309. }
  310. m_groups.push_back(group);
  311. group.reset();
  312. }
  313. break;
  314. default:
  315. DBG("%08x at %d", chunk, bx::skip(_reader, 0) );
  316. break;
  317. }
  318. }
  319. }
  320. void unload()
  321. {
  322. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  323. {
  324. const Group& group = *it;
  325. bgfx::destroyVertexBuffer(group.m_vbh);
  326. if (bgfx::isValid(group.m_ibh) )
  327. {
  328. bgfx::destroyIndexBuffer(group.m_ibh);
  329. }
  330. }
  331. m_groups.clear();
  332. }
  333. void submit(uint8_t _id, bgfx::ProgramHandle _program, const float* _mtx, uint64_t _state) const
  334. {
  335. if (BGFX_STATE_MASK == _state)
  336. {
  337. _state = 0
  338. | BGFX_STATE_RGB_WRITE
  339. | BGFX_STATE_ALPHA_WRITE
  340. | BGFX_STATE_DEPTH_WRITE
  341. | BGFX_STATE_DEPTH_TEST_LESS
  342. | BGFX_STATE_CULL_CCW
  343. | BGFX_STATE_MSAA
  344. ;
  345. }
  346. uint32_t cached = bgfx::setTransform(_mtx);
  347. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  348. {
  349. const Group& group = *it;
  350. bgfx::setTransform(cached);
  351. bgfx::setProgram(_program);
  352. bgfx::setIndexBuffer(group.m_ibh);
  353. bgfx::setVertexBuffer(group.m_vbh);
  354. bgfx::setState(_state);
  355. bgfx::submit(_id);
  356. }
  357. }
  358. void submit(const MeshState*const* _state, uint8_t _numPasses, const float* _mtx, uint16_t _numMatrices) const
  359. {
  360. uint32_t cached = bgfx::setTransform(_mtx, _numMatrices);
  361. for (uint32_t pass = 0; pass < _numPasses; ++pass)
  362. {
  363. const MeshState& state = *_state[pass];
  364. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  365. {
  366. const Group& group = *it;
  367. bgfx::setTransform(cached, _numMatrices);
  368. for (uint8_t tex = 0; tex < state.m_numTextures; ++tex)
  369. {
  370. const MeshState::Texture& texture = state.m_textures[tex];
  371. bgfx::setTexture(texture.m_stage
  372. , texture.m_sampler
  373. , texture.m_texture
  374. , texture.m_flags
  375. );
  376. }
  377. bgfx::setProgram(state.m_program);
  378. bgfx::setIndexBuffer(group.m_ibh);
  379. bgfx::setVertexBuffer(group.m_vbh);
  380. bgfx::setState(state.m_state);
  381. bgfx::submit(state.m_viewId);
  382. }
  383. }
  384. }
  385. bgfx::VertexDecl m_decl;
  386. typedef stl::vector<Group> GroupArray;
  387. GroupArray m_groups;
  388. };
  389. Mesh* meshLoad(bx::ReaderSeekerI* _reader)
  390. {
  391. Mesh* mesh = new Mesh;
  392. mesh->load(_reader);
  393. return mesh;
  394. }
  395. Mesh* meshLoad(const char* _filePath)
  396. {
  397. bx::FileReaderI* reader = entry::getFileReader();
  398. bx::open(reader, _filePath);
  399. Mesh* mesh = meshLoad(reader);
  400. bx::close(reader);
  401. return mesh;
  402. }
  403. void meshUnload(Mesh* _mesh)
  404. {
  405. _mesh->unload();
  406. delete _mesh;
  407. }
  408. MeshState* meshStateCreate()
  409. {
  410. MeshState* state = (MeshState*)BX_ALLOC(entry::getAllocator(), sizeof(MeshState) );
  411. return state;
  412. }
  413. void meshStateDestroy(MeshState* _meshState)
  414. {
  415. BX_FREE(entry::getAllocator(), _meshState);
  416. }
  417. void meshSubmit(const Mesh* _mesh, uint8_t _id, bgfx::ProgramHandle _program, const float* _mtx, uint64_t _state)
  418. {
  419. _mesh->submit(_id, _program, _mtx, _state);
  420. }
  421. void meshSubmit(const Mesh* _mesh, const MeshState*const* _state, uint8_t _numPasses, const float* _mtx, uint16_t _numMatrices)
  422. {
  423. _mesh->submit(_state, _numPasses, _mtx, _numMatrices);
  424. }