bgfx_utils.cpp 13 KB

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