bgfx_utils.cpp 12 KB

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