bgfx_utils.cpp 14 KB

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