bgfx_utils.cpp 14 KB

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