lod.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /*
  2. * Copyright 2013 Milos Tosic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "common.h"
  6. #include <bgfx.h>
  7. #include <bx/timer.h>
  8. #include <bx/readerwriter.h>
  9. #include "fpumath.h"
  10. #include "imgui/imgui.h"
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <string>
  14. #include <vector>
  15. static const char* s_shaderPath = NULL;
  16. static bool s_flipV = false;
  17. struct KnightPos
  18. {
  19. int32_t m_x;
  20. int32_t m_y;
  21. };
  22. KnightPos knightTour[8*4] =
  23. {
  24. {0,0}, {1,2}, {3,3}, {4,1}, {5,3}, {7,2}, {6,0}, {5,2},
  25. {7,3}, {6,1}, {4,0}, {3,2}, {2,0}, {0,1}, {1,3}, {2,1},
  26. {0,2}, {1,0}, {2,2}, {0,3}, {1,1}, {3,0}, {4,2}, {5,0},
  27. {7,1}, {6,3}, {5,1}, {7,0}, {6,2}, {4,3}, {3,1}, {2,3}
  28. };
  29. static void shaderFilePath(char* _out, const char* _name)
  30. {
  31. strcpy(_out, s_shaderPath);
  32. strcat(_out, _name);
  33. strcat(_out, ".bin");
  34. }
  35. long int fsize(FILE* _file)
  36. {
  37. long int pos = ftell(_file);
  38. fseek(_file, 0L, SEEK_END);
  39. long int size = ftell(_file);
  40. fseek(_file, pos, SEEK_SET);
  41. return size;
  42. }
  43. static const bgfx::Memory* load(const char* _filePath)
  44. {
  45. FILE* file = fopen(_filePath, "rb");
  46. if (NULL != file)
  47. {
  48. uint32_t size = (uint32_t)fsize(file);
  49. const bgfx::Memory* mem = bgfx::alloc(size+1);
  50. size_t ignore = fread(mem->data, 1, size, file);
  51. BX_UNUSED(ignore);
  52. fclose(file);
  53. mem->data[mem->size-1] = '\0';
  54. return mem;
  55. }
  56. return NULL;
  57. }
  58. static const bgfx::Memory* loadTexture(const char* _name)
  59. {
  60. char filePath[512];
  61. strcpy(filePath, "textures/");
  62. strcat(filePath, _name);
  63. return load(filePath);
  64. }
  65. static const bgfx::Memory* loadShader(const char* _name)
  66. {
  67. char filePath[512];
  68. shaderFilePath(filePath, _name);
  69. return load(filePath);
  70. }
  71. static bgfx::ProgramHandle loadProgram(const char* _vsName, const char* _fsName)
  72. {
  73. const bgfx::Memory* mem;
  74. // Load vertex shader.
  75. mem = loadShader(_vsName);
  76. bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem);
  77. // Load fragment shader.
  78. mem = loadShader(_fsName);
  79. bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem);
  80. // Create program from shaders.
  81. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh);
  82. // We can destroy vertex and fragment shader here since
  83. // their reference is kept inside bgfx after calling createProgram.
  84. // Vertex and fragment shader will be destroyed once program is
  85. // destroyed.
  86. bgfx::destroyVertexShader(vsh);
  87. bgfx::destroyFragmentShader(fsh);
  88. return program;
  89. }
  90. struct Aabb
  91. {
  92. float m_min[3];
  93. float m_max[3];
  94. };
  95. struct Obb
  96. {
  97. float m_mtx[16];
  98. };
  99. struct Sphere
  100. {
  101. float m_center[3];
  102. float m_radius;
  103. };
  104. struct Primitive
  105. {
  106. uint32_t m_startIndex;
  107. uint32_t m_numIndices;
  108. uint32_t m_startVertex;
  109. uint32_t m_numVertices;
  110. Sphere m_sphere;
  111. Aabb m_aabb;
  112. Obb m_obb;
  113. };
  114. typedef std::vector<Primitive> PrimitiveArray;
  115. struct Group
  116. {
  117. Group()
  118. {
  119. reset();
  120. }
  121. void reset()
  122. {
  123. m_vbh.idx = bgfx::invalidHandle;
  124. m_ibh.idx = bgfx::invalidHandle;
  125. m_prims.clear();
  126. }
  127. bgfx::VertexBufferHandle m_vbh;
  128. bgfx::IndexBufferHandle m_ibh;
  129. Sphere m_sphere;
  130. Aabb m_aabb;
  131. Obb m_obb;
  132. PrimitiveArray m_prims;
  133. };
  134. struct Mesh
  135. {
  136. void load(const char* _filePath)
  137. {
  138. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x0)
  139. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  140. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  141. bx::CrtFileReader reader;
  142. reader.open(_filePath);
  143. Group group;
  144. uint32_t chunk;
  145. while (4 == bx::read(&reader, chunk) )
  146. {
  147. switch (chunk)
  148. {
  149. case BGFX_CHUNK_MAGIC_VB:
  150. {
  151. bx::read(&reader, group.m_sphere);
  152. bx::read(&reader, group.m_aabb);
  153. bx::read(&reader, group.m_obb);
  154. bx::read(&reader, m_decl);
  155. uint16_t stride = m_decl.getStride();
  156. uint16_t numVertices;
  157. bx::read(&reader, numVertices);
  158. const bgfx::Memory* mem = bgfx::alloc(numVertices*stride);
  159. bx::read(&reader, mem->data, mem->size);
  160. group.m_vbh = bgfx::createVertexBuffer(mem, m_decl);
  161. }
  162. break;
  163. case BGFX_CHUNK_MAGIC_IB:
  164. {
  165. uint32_t numIndices;
  166. bx::read(&reader, numIndices);
  167. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  168. bx::read(&reader, mem->data, mem->size);
  169. group.m_ibh = bgfx::createIndexBuffer(mem);
  170. }
  171. break;
  172. case BGFX_CHUNK_MAGIC_PRI:
  173. {
  174. uint16_t len;
  175. bx::read(&reader, len);
  176. std::string material;
  177. material.resize(len);
  178. bx::read(&reader, const_cast<char*>(material.c_str() ), len);
  179. uint16_t num;
  180. bx::read(&reader, num);
  181. for (uint32_t ii = 0; ii < num; ++ii)
  182. {
  183. bx::read(&reader, len);
  184. std::string name;
  185. name.resize(len);
  186. bx::read(&reader, const_cast<char*>(name.c_str() ), len);
  187. Primitive prim;
  188. bx::read(&reader, prim.m_startIndex);
  189. bx::read(&reader, prim.m_numIndices);
  190. bx::read(&reader, prim.m_startVertex);
  191. bx::read(&reader, prim.m_numVertices);
  192. bx::read(&reader, prim.m_sphere);
  193. bx::read(&reader, prim.m_aabb);
  194. bx::read(&reader, prim.m_obb);
  195. group.m_prims.push_back(prim);
  196. }
  197. m_groups.push_back(group);
  198. group.reset();
  199. }
  200. break;
  201. default:
  202. DBG("%08x at %d", chunk, reader.seek() );
  203. break;
  204. }
  205. }
  206. reader.close();
  207. }
  208. void unload()
  209. {
  210. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  211. {
  212. const Group& group = *it;
  213. bgfx::destroyVertexBuffer(group.m_vbh);
  214. if (bgfx::isValid(group.m_ibh) )
  215. {
  216. bgfx::destroyIndexBuffer(group.m_ibh);
  217. }
  218. }
  219. m_groups.clear();
  220. }
  221. void submit(bgfx::ProgramHandle _program, float* _mtx, bool _blend)
  222. {
  223. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  224. {
  225. const Group& group = *it;
  226. // Set model matrix for rendering.
  227. bgfx::setTransform(_mtx);
  228. bgfx::setProgram(_program);
  229. bgfx::setIndexBuffer(group.m_ibh);
  230. bgfx::setVertexBuffer(group.m_vbh);
  231. // Set render states.
  232. bgfx::setState(0
  233. |BGFX_STATE_RGB_WRITE
  234. |BGFX_STATE_ALPHA_WRITE
  235. |(_blend?0:BGFX_STATE_DEPTH_WRITE)
  236. |BGFX_STATE_DEPTH_TEST_LESS
  237. |BGFX_STATE_CULL_CCW
  238. |BGFX_STATE_MSAA
  239. |(_blend?BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA):0)
  240. );
  241. // Submit primitive for rendering to view 0.
  242. bgfx::submit(0);
  243. }
  244. }
  245. bgfx::VertexDecl m_decl;
  246. typedef std::vector<Group> GroupArray;
  247. GroupArray m_groups;
  248. };
  249. int _main_(int /*_argc*/, char** /*_argv*/)
  250. {
  251. uint32_t width = 1280;
  252. uint32_t height = 720;
  253. uint32_t debug = BGFX_DEBUG_TEXT;
  254. uint32_t reset = BGFX_RESET_VSYNC;
  255. bgfx::init();
  256. bgfx::reset(width, height, reset);
  257. // Enable debug text.
  258. bgfx::setDebug(debug);
  259. // Set view 0 clear state.
  260. bgfx::setViewClear(0
  261. , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
  262. , 0x303030ff
  263. , 1.0f
  264. , 0
  265. );
  266. // Setup root path for binary shaders. Shader binaries are different
  267. // for each renderer.
  268. switch (bgfx::getRendererType() )
  269. {
  270. default:
  271. case bgfx::RendererType::Direct3D9:
  272. s_shaderPath = "shaders/dx9/";
  273. break;
  274. case bgfx::RendererType::Direct3D11:
  275. s_shaderPath = "shaders/dx11/";
  276. break;
  277. case bgfx::RendererType::OpenGL:
  278. s_shaderPath = "shaders/glsl/";
  279. s_flipV = true;
  280. break;
  281. case bgfx::RendererType::OpenGLES2:
  282. case bgfx::RendererType::OpenGLES3:
  283. s_shaderPath = "shaders/gles/";
  284. s_flipV = true;
  285. break;
  286. }
  287. bgfx::UniformHandle u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv);
  288. bgfx::UniformHandle u_stipple = bgfx::createUniform("u_stipple", bgfx::UniformType::Uniform3fv);
  289. bgfx::UniformHandle u_texStipple = bgfx::createUniform("u_texStipple", bgfx::UniformType::Uniform1iv);
  290. bgfx::ProgramHandle program = loadProgram("vs_tree", "fs_tree");
  291. const bgfx::Memory* mem;
  292. mem = loadTexture("leafs1.dds");
  293. bgfx::TextureHandle textureLeafs = bgfx::createTexture(mem);
  294. mem = loadTexture("bark1.dds");
  295. bgfx::TextureHandle textureBark = bgfx::createTexture(mem);
  296. bgfx::TextureHandle textureStipple;
  297. const bgfx::Memory* stipple = bgfx::alloc(8*4);
  298. memset(stipple->data, 0, stipple->size);
  299. for (uint32_t ii = 0; ii < 32; ++ii)
  300. {
  301. stipple->data[knightTour[ii].m_y * 8 + knightTour[ii].m_x] = ii*4;
  302. }
  303. textureStipple = bgfx::createTexture2D(8, 4, 1, bgfx::TextureFormat::L8, BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIN_POINT, stipple);
  304. Mesh mesh_top[3];
  305. mesh_top[0].load("meshes/tree1b_lod0_1.bin");
  306. mesh_top[1].load("meshes/tree1b_lod1_1.bin");
  307. mesh_top[2].load("meshes/tree1b_lod2_1.bin");
  308. Mesh mesh_trunk[3];
  309. mesh_trunk[0].load("meshes/tree1b_lod0_2.bin");
  310. mesh_trunk[1].load("meshes/tree1b_lod1_2.bin");
  311. mesh_trunk[2].load("meshes/tree1b_lod2_2.bin");
  312. FILE* file = fopen("font/droidsans.ttf", "rb");
  313. uint32_t size = (uint32_t)fsize(file);
  314. void* data = malloc(size);
  315. size_t ignore = fread(data, 1, size, file);
  316. BX_UNUSED(ignore);
  317. fclose(file);
  318. imguiCreate(data, size);
  319. free(data);
  320. int32_t scrollArea = 0;
  321. bool transitions = true;
  322. int transitionFrame = 0;
  323. int currLOD = 0;
  324. int targetLOD = 0;
  325. float at[3] = { 0.0f, 1.0f, 0.0f };
  326. float eye[3] = { 0.0f, 1.0f, -2.0f };
  327. entry::MouseState mouseState;
  328. while (!entry::processEvents(width, height, debug, reset, &mouseState) )
  329. {
  330. imguiBeginFrame(mouseState.m_mx
  331. , mouseState.m_my
  332. , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  333. | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  334. , 0
  335. , width
  336. , height
  337. );
  338. imguiBeginScrollArea("Toggle transitions", width - width / 5 - 10, 10, width / 5, height / 6, &scrollArea);
  339. imguiSeparatorLine();
  340. if (imguiButton(transitions ? "ON" : "OFF") )
  341. {
  342. transitions = !transitions;
  343. }
  344. static float distance = 2.0f;
  345. imguiSlider("Distance", &distance, 2.0f, 6.0f, .01f);
  346. imguiEndScrollArea();
  347. imguiEndFrame();
  348. // Set view 0 default viewport.
  349. bgfx::setViewRect(0, 0, 0, width, height);
  350. // This dummy draw call is here to make sure that view 0 is cleared
  351. // if no other draw calls are submitted to view 0.
  352. bgfx::submit(0);
  353. int64_t now = bx::getHPCounter();
  354. static int64_t last = now;
  355. const int64_t frameTime = now - last;
  356. last = now;
  357. const double freq = double(bx::getHPFrequency() );
  358. const double toMs = 1000.0/freq;
  359. // Use debug font to print information about this example.
  360. bgfx::dbgTextClear();
  361. bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/12-lod");
  362. bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Mesh LOD transitions.");
  363. bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
  364. bgfx::dbgTextPrintf(0, 4, transitions ? 0x2f : 0x1f, transitions ? "Transitions on" : "Transitions off");
  365. eye[2] = -distance;
  366. float view[16];
  367. float proj[16];
  368. mtxLookAt(view, eye, at);
  369. mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);
  370. // Set view and projection matrix for view 0.
  371. bgfx::setViewTransform(0, view, proj);
  372. float mtx[16];
  373. mtxIdentity(mtx);
  374. float stipple[3];
  375. float stippleInv[3];
  376. const int currentLODframe = transitions ? 32-transitionFrame : 32;
  377. const int mainLOD = transitions ? currLOD : targetLOD;
  378. stipple[0] = 0.0f;
  379. stipple[1] = -1.0f;
  380. stipple[2] = (float(currentLODframe)*4.0f/255.0f) - (1.0f/255.0f);
  381. stippleInv[0] = (float(31)*4.0f/255.0f);
  382. stippleInv[1] = 1.0f;
  383. stippleInv[2] = (float(transitionFrame)*4.0f/255.0f) - (1.0f/255.0f);
  384. bgfx::setTexture(0, u_texColor, textureBark);
  385. bgfx::setTexture(1, u_texStipple, textureStipple);
  386. bgfx::setUniform(u_stipple, stipple);
  387. mesh_trunk[mainLOD].submit(program, mtx, false);
  388. bgfx::setTexture(0, u_texColor, textureLeafs);
  389. bgfx::setTexture(1, u_texStipple, textureStipple);
  390. bgfx::setUniform(u_stipple, stipple);
  391. mesh_top[mainLOD].submit(program, mtx, true);
  392. if (transitions
  393. && (transitionFrame != 0) )
  394. {
  395. bgfx::setTexture(0, u_texColor, textureBark);
  396. bgfx::setTexture(1, u_texStipple, textureStipple);
  397. bgfx::setUniform(u_stipple, stippleInv);
  398. mesh_trunk[targetLOD].submit(program, mtx, false);
  399. bgfx::setTexture(0, u_texColor, textureLeafs);
  400. bgfx::setTexture(1, u_texStipple, textureStipple);
  401. bgfx::setUniform(u_stipple, stippleInv);
  402. mesh_top[targetLOD].submit(program, mtx, true);
  403. }
  404. int lod = 0;
  405. if (eye[2] < -2.5f)
  406. {
  407. lod = 1;
  408. }
  409. if (eye[2] < -5.0f)
  410. {
  411. lod = 2;
  412. }
  413. if (targetLOD!=lod)
  414. {
  415. if (targetLOD==currLOD)
  416. {
  417. targetLOD = lod;
  418. }
  419. }
  420. if (currLOD != targetLOD)
  421. {
  422. transitionFrame++;
  423. }
  424. if (transitionFrame>32)
  425. {
  426. currLOD = targetLOD;
  427. transitionFrame = 0;
  428. }
  429. // Advance to next frame. Rendering thread will be kicked to
  430. // process submitted rendering primitives.
  431. bgfx::frame();
  432. }
  433. imguiDestroy();
  434. for (uint32_t ii = 0; ii < 3; ++ii)
  435. {
  436. mesh_top[ii].unload();
  437. mesh_trunk[ii].unload();
  438. }
  439. // Cleanup.
  440. bgfx::destroyProgram(program);
  441. bgfx::destroyUniform(u_texColor);
  442. bgfx::destroyUniform(u_stipple);
  443. bgfx::destroyUniform(u_texStipple);
  444. bgfx::destroyTexture(textureStipple);
  445. bgfx::destroyTexture(textureLeafs);
  446. bgfx::destroyTexture(textureBark);
  447. // Shutdown bgfx.
  448. bgfx::shutdown();
  449. return 0;
  450. }