bgfx_utils.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. if (NULL != img)
  145. {
  146. handle = bgfx::createTexture2D(uint16_t(width), uint16_t(height), 1
  147. , bgfx::TextureFormat::RGBA8
  148. , _flags
  149. , bgfx::copy(img, width*height*4)
  150. );
  151. free(img);
  152. if (NULL != _info)
  153. {
  154. bgfx::calcTextureSize(*_info
  155. , uint16_t(width)
  156. , uint16_t(height)
  157. , 0
  158. , false
  159. , 1
  160. , bgfx::TextureFormat::RGBA8
  161. );
  162. }
  163. }
  164. }
  165. else
  166. {
  167. DBG("Failed to load %s.", filePath);
  168. }
  169. return handle;
  170. }
  171. bgfx::TextureHandle loadTexture(const char* _name, uint32_t _flags, uint8_t _skip, bgfx::TextureInfo* _info)
  172. {
  173. return loadTexture(entry::getFileReader(), _name, _flags, _skip, _info);
  174. }
  175. void calcTangents(void* _vertices, uint16_t _numVertices, bgfx::VertexDecl _decl, 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. 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, _decl, _vertices, i0);
  200. bgfx::vertexUnpack(&v0.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i0);
  201. bgfx::vertexUnpack(&v1.m_x, bgfx::Attrib::Position, _decl, _vertices, i1);
  202. bgfx::vertexUnpack(&v1.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i1);
  203. bgfx::vertexUnpack(&v2.m_x, bgfx::Attrib::Position, _decl, _vertices, i2);
  204. bgfx::vertexUnpack(&v2.m_u, bgfx::Attrib::TexCoord0, _decl, _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 float* tanu = &tangents[ii*6];
  238. const float* tanv = &tangents[ii*6 + 3];
  239. float normal[4];
  240. bgfx::vertexUnpack(normal, bgfx::Attrib::Normal, _decl, _vertices, ii);
  241. float ndt = bx::vec3Dot(normal, tanu);
  242. float nxt[3];
  243. bx::vec3Cross(nxt, normal, tanu);
  244. float tmp[3];
  245. tmp[0] = tanu[0] - normal[0] * ndt;
  246. tmp[1] = tanu[1] - normal[1] * ndt;
  247. tmp[2] = tanu[2] - normal[2] * ndt;
  248. float tangent[4];
  249. bx::vec3Norm(tangent, tmp);
  250. tangent[3] = bx::vec3Dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  251. bgfx::vertexPack(tangent, true, bgfx::Attrib::Tangent, _decl, _vertices, ii);
  252. }
  253. delete [] tangents;
  254. }
  255. struct Aabb
  256. {
  257. float m_min[3];
  258. float m_max[3];
  259. };
  260. struct Obb
  261. {
  262. float m_mtx[16];
  263. };
  264. struct Sphere
  265. {
  266. float m_center[3];
  267. float m_radius;
  268. };
  269. struct Primitive
  270. {
  271. uint32_t m_startIndex;
  272. uint32_t m_numIndices;
  273. uint32_t m_startVertex;
  274. uint32_t m_numVertices;
  275. Sphere m_sphere;
  276. Aabb m_aabb;
  277. Obb m_obb;
  278. };
  279. typedef stl::vector<Primitive> PrimitiveArray;
  280. struct Group
  281. {
  282. Group()
  283. {
  284. reset();
  285. }
  286. void reset()
  287. {
  288. m_vbh.idx = bgfx::invalidHandle;
  289. m_ibh.idx = bgfx::invalidHandle;
  290. m_prims.clear();
  291. }
  292. bgfx::VertexBufferHandle m_vbh;
  293. bgfx::IndexBufferHandle m_ibh;
  294. Sphere m_sphere;
  295. Aabb m_aabb;
  296. Obb m_obb;
  297. PrimitiveArray m_prims;
  298. };
  299. namespace bgfx
  300. {
  301. int32_t read(bx::ReaderI* _reader, bgfx::VertexDecl& _decl);
  302. }
  303. struct Mesh
  304. {
  305. void load(bx::ReaderSeekerI* _reader)
  306. {
  307. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x1)
  308. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  309. #define BGFX_CHUNK_MAGIC_IBC BX_MAKEFOURCC('I', 'B', 'C', 0x0)
  310. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  311. using namespace bx;
  312. using namespace bgfx;
  313. Group group;
  314. bx::ReallocatorI* allocator = entry::getAllocator();
  315. uint32_t chunk;
  316. while (4 == bx::read(_reader, chunk) )
  317. {
  318. switch (chunk)
  319. {
  320. case BGFX_CHUNK_MAGIC_VB:
  321. {
  322. read(_reader, group.m_sphere);
  323. read(_reader, group.m_aabb);
  324. read(_reader, group.m_obb);
  325. read(_reader, m_decl);
  326. uint16_t stride = m_decl.getStride();
  327. uint16_t numVertices;
  328. read(_reader, numVertices);
  329. const bgfx::Memory* mem = bgfx::alloc(numVertices*stride);
  330. read(_reader, mem->data, mem->size);
  331. group.m_vbh = bgfx::createVertexBuffer(mem, m_decl);
  332. }
  333. break;
  334. case BGFX_CHUNK_MAGIC_IB:
  335. {
  336. uint32_t numIndices;
  337. read(_reader, numIndices);
  338. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  339. read(_reader, mem->data, mem->size);
  340. group.m_ibh = bgfx::createIndexBuffer(mem);
  341. }
  342. break;
  343. case BGFX_CHUNK_MAGIC_IBC:
  344. {
  345. uint32_t numIndices;
  346. bx::read(_reader, numIndices);
  347. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  348. uint32_t compressedSize;
  349. bx::read(_reader, compressedSize);
  350. void* compressedIndices = BX_ALLOC(allocator, compressedSize);
  351. bx::read(_reader, compressedIndices, compressedSize);
  352. ReadBitstream rbs( (const uint8_t*)compressedIndices, compressedSize);
  353. DecompressIndexBuffer( (uint16_t*)mem->data, numIndices / 3, rbs);
  354. BX_FREE(allocator, compressedIndices);
  355. group.m_ibh = bgfx::createIndexBuffer(mem);
  356. }
  357. break;
  358. case BGFX_CHUNK_MAGIC_PRI:
  359. {
  360. uint16_t len;
  361. read(_reader, len);
  362. stl::string material;
  363. material.resize(len);
  364. read(_reader, const_cast<char*>(material.c_str() ), len);
  365. uint16_t num;
  366. read(_reader, num);
  367. for (uint32_t ii = 0; ii < num; ++ii)
  368. {
  369. read(_reader, len);
  370. stl::string name;
  371. name.resize(len);
  372. read(_reader, const_cast<char*>(name.c_str() ), len);
  373. Primitive prim;
  374. read(_reader, prim.m_startIndex);
  375. read(_reader, prim.m_numIndices);
  376. read(_reader, prim.m_startVertex);
  377. read(_reader, prim.m_numVertices);
  378. read(_reader, prim.m_sphere);
  379. read(_reader, prim.m_aabb);
  380. read(_reader, prim.m_obb);
  381. group.m_prims.push_back(prim);
  382. }
  383. m_groups.push_back(group);
  384. group.reset();
  385. }
  386. break;
  387. default:
  388. DBG("%08x at %d", chunk, bx::skip(_reader, 0) );
  389. break;
  390. }
  391. }
  392. }
  393. void unload()
  394. {
  395. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  396. {
  397. const Group& group = *it;
  398. bgfx::destroyVertexBuffer(group.m_vbh);
  399. if (bgfx::isValid(group.m_ibh) )
  400. {
  401. bgfx::destroyIndexBuffer(group.m_ibh);
  402. }
  403. }
  404. m_groups.clear();
  405. }
  406. void submit(uint8_t _id, bgfx::ProgramHandle _program, const float* _mtx, uint64_t _state) const
  407. {
  408. if (BGFX_STATE_MASK == _state)
  409. {
  410. _state = 0
  411. | BGFX_STATE_RGB_WRITE
  412. | BGFX_STATE_ALPHA_WRITE
  413. | BGFX_STATE_DEPTH_WRITE
  414. | BGFX_STATE_DEPTH_TEST_LESS
  415. | BGFX_STATE_CULL_CCW
  416. | BGFX_STATE_MSAA
  417. ;
  418. }
  419. uint32_t cached = bgfx::setTransform(_mtx);
  420. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  421. {
  422. const Group& group = *it;
  423. bgfx::setTransform(cached);
  424. bgfx::setProgram(_program);
  425. bgfx::setIndexBuffer(group.m_ibh);
  426. bgfx::setVertexBuffer(group.m_vbh);
  427. bgfx::setState(_state);
  428. bgfx::submit(_id);
  429. }
  430. }
  431. void submit(const MeshState*const* _state, uint8_t _numPasses, const float* _mtx, uint16_t _numMatrices) const
  432. {
  433. uint32_t cached = bgfx::setTransform(_mtx, _numMatrices);
  434. for (uint32_t pass = 0; pass < _numPasses; ++pass)
  435. {
  436. const MeshState& state = *_state[pass];
  437. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  438. {
  439. const Group& group = *it;
  440. bgfx::setTransform(cached, _numMatrices);
  441. for (uint8_t tex = 0; tex < state.m_numTextures; ++tex)
  442. {
  443. const MeshState::Texture& texture = state.m_textures[tex];
  444. bgfx::setTexture(texture.m_stage
  445. , texture.m_sampler
  446. , texture.m_texture
  447. , texture.m_flags
  448. );
  449. }
  450. bgfx::setProgram(state.m_program);
  451. bgfx::setIndexBuffer(group.m_ibh);
  452. bgfx::setVertexBuffer(group.m_vbh);
  453. bgfx::setState(state.m_state);
  454. bgfx::submit(state.m_viewId);
  455. }
  456. }
  457. }
  458. bgfx::VertexDecl m_decl;
  459. typedef stl::vector<Group> GroupArray;
  460. GroupArray m_groups;
  461. };
  462. Mesh* meshLoad(bx::ReaderSeekerI* _reader)
  463. {
  464. Mesh* mesh = new Mesh;
  465. mesh->load(_reader);
  466. return mesh;
  467. }
  468. Mesh* meshLoad(const char* _filePath)
  469. {
  470. bx::FileReaderI* reader = entry::getFileReader();
  471. bx::open(reader, _filePath);
  472. Mesh* mesh = meshLoad(reader);
  473. bx::close(reader);
  474. return mesh;
  475. }
  476. void meshUnload(Mesh* _mesh)
  477. {
  478. _mesh->unload();
  479. delete _mesh;
  480. }
  481. MeshState* meshStateCreate()
  482. {
  483. MeshState* state = (MeshState*)BX_ALLOC(entry::getAllocator(), sizeof(MeshState) );
  484. return state;
  485. }
  486. void meshStateDestroy(MeshState* _meshState)
  487. {
  488. BX_FREE(entry::getAllocator(), _meshState);
  489. }
  490. void meshSubmit(const Mesh* _mesh, uint8_t _id, bgfx::ProgramHandle _program, const float* _mtx, uint64_t _state)
  491. {
  492. _mesh->submit(_id, _program, _mtx, _state);
  493. }
  494. void meshSubmit(const Mesh* _mesh, const MeshState*const* _state, uint8_t _numPasses, const float* _mtx, uint16_t _numMatrices)
  495. {
  496. _mesh->submit(_state, _numPasses, _mtx, _numMatrices);
  497. }