lod.cpp 13 KB

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