bgfx_utils.cpp 14 KB

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