svt.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. * Copyright 2018 Ales Mlakar. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. /*
  6. * Reference(s):
  7. * - Sparse Virtual Textures by Sean Barrett
  8. * http://web.archive.org/web/20190103162611/http://silverspaceship.com/src/svt/
  9. * - Based on Virtual Texture Demo by Brad Blanchard
  10. * http://web.archive.org/web/20190103162638/http://linedef.com/virtual-texture-demo.html
  11. * - Mars texture
  12. * http://web.archive.org/web/20190103162730/http://www.celestiamotherlode.net/catalog/mars.php
  13. */
  14. #include "common.h"
  15. #include "bgfx_utils.h"
  16. #include "imgui/imgui.h"
  17. #include "camera.h"
  18. #include "vt.h"
  19. namespace
  20. {
  21. struct PosTexcoordVertex
  22. {
  23. float m_x;
  24. float m_y;
  25. float m_z;
  26. float m_u;
  27. float m_v;
  28. static void init()
  29. {
  30. ms_layout
  31. .begin()
  32. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  33. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  34. .end();
  35. };
  36. static bgfx::VertexLayout ms_layout;
  37. };
  38. bgfx::VertexLayout PosTexcoordVertex::ms_layout;
  39. static const float s_planeScale = 50.0f;
  40. static PosTexcoordVertex s_vplaneVertices[] =
  41. {
  42. { -s_planeScale, 0.0f, s_planeScale, 1.0f, 1.0f },
  43. { s_planeScale, 0.0f, s_planeScale, 1.0f, 0.0f },
  44. { -s_planeScale, 0.0f, -s_planeScale, 0.0f, 1.0f },
  45. { s_planeScale, 0.0f, -s_planeScale, 0.0f, 0.0f },
  46. };
  47. static const uint16_t s_planeIndices[] =
  48. {
  49. 0, 1, 2,
  50. 1, 3, 2,
  51. };
  52. class ExampleSVT : public entry::AppI
  53. {
  54. public:
  55. ExampleSVT(const char* _name, const char* _description, const char* _url)
  56. : entry::AppI(_name, _description, _url)
  57. {
  58. }
  59. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  60. {
  61. Args args(_argc, _argv);
  62. m_width = _width;
  63. m_height = _height;
  64. m_debug = BGFX_DEBUG_TEXT;
  65. m_reset = BGFX_RESET_VSYNC;
  66. bgfx::Init init;
  67. init.type = args.m_type;
  68. init.vendorId = args.m_pciId;
  69. init.resolution.width = m_width;
  70. init.resolution.height = m_height;
  71. init.resolution.reset = m_reset;
  72. bgfx::init(init);
  73. // Enable m_debug text.
  74. bgfx::setDebug(m_debug);
  75. // Set views clear state (first pass to 0, second pass to some background color)
  76. for (uint16_t i = 0; i < 2; ++i)
  77. {
  78. bgfx::setViewClear(i
  79. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  80. , i == 0 ? 0 : 0x101050ff
  81. , 1.0f
  82. , 0
  83. );
  84. }
  85. // Create vertex stream declaration.
  86. PosTexcoordVertex::init();
  87. // Create static vertex buffer.
  88. m_vbh = bgfx::createVertexBuffer(
  89. bgfx::makeRef(s_vplaneVertices, sizeof(s_vplaneVertices))
  90. , PosTexcoordVertex::ms_layout
  91. );
  92. m_ibh = bgfx::createIndexBuffer(
  93. bgfx::makeRef(s_planeIndices, sizeof(s_planeIndices))
  94. );
  95. // Create program from shaders.
  96. m_vt_unlit = loadProgram("vs_vt_generic", "fs_vt_unlit");
  97. m_vt_mip = loadProgram("vs_vt_generic", "fs_vt_mip");
  98. // Imgui.
  99. imguiCreate();
  100. m_timeOffset = bx::getHPCounter();
  101. // Get renderer capabilities info.
  102. m_caps = bgfx::getCaps();
  103. m_scrollArea = 0;
  104. // Create and setup camera
  105. cameraCreate();
  106. cameraSetPosition({ 0.0f, 5.0f, 0.0f });
  107. cameraSetVerticalAngle(0.0f);
  108. // Set VirtualTexture system allocator
  109. vt::VirtualTexture::setAllocator(&m_vtAllocator);
  110. // Create Virtual texture info
  111. m_vti = new vt::VirtualTextureInfo();
  112. m_vti->m_virtualTextureSize = 8192; // The actual size will be read from the tile data file
  113. m_vti->m_tileSize = 128;
  114. m_vti->m_borderSize = 1;
  115. // Generate tile data file (if not yet created)
  116. {
  117. vt::TileGenerator tileGenerator(m_vti);
  118. tileGenerator.generate("textures/8k_mars.jpg");
  119. }
  120. // Load tile data file
  121. auto tileDataFile = new vt::TileDataFile("temp/8k_mars.vt", m_vti);
  122. tileDataFile->readInfo();
  123. // Create virtual texture and feedback buffer
  124. m_vt = new vt::VirtualTexture(tileDataFile, m_vti, 2048, 1);
  125. m_feedbackBuffer = new vt::FeedbackBuffer(m_vti, 64, 64);
  126. }
  127. virtual int shutdown() override
  128. {
  129. // Cleanup.
  130. bgfx::frame();
  131. cameraDestroy();
  132. imguiDestroy();
  133. bgfx::destroy(m_ibh);
  134. bgfx::destroy(m_vbh);
  135. bgfx::destroy(m_vt_unlit);
  136. bgfx::destroy(m_vt_mip);
  137. delete m_vti;
  138. delete m_vt;
  139. delete m_feedbackBuffer;
  140. // Shutdown bgfx.
  141. bgfx::shutdown();
  142. return 0;
  143. }
  144. bool update() override
  145. {
  146. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  147. {
  148. imguiBeginFrame(
  149. m_mouseState.m_mx
  150. , m_mouseState.m_my
  151. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  152. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  153. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  154. , m_mouseState.m_mz
  155. , uint16_t(m_width)
  156. , uint16_t(m_height)
  157. );
  158. showExampleDialog(this);
  159. int64_t now = bx::getHPCounter();
  160. static int64_t last = now;
  161. const int64_t frameTime = now - last;
  162. last = now;
  163. const double freq = double(bx::getHPFrequency());
  164. const float deltaTime = float(frameTime / freq);
  165. float time = (float)((now - m_timeOffset) / freq);
  166. if ((BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK) != (bgfx::getCaps()->supported & (BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK)))
  167. {
  168. // When texture read-back or blit is not supported by GPU blink!
  169. bool blink = uint32_t(time*3.0f) & 1;
  170. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Texture read-back and/or blit not supported by GPU. ");
  171. // Set view 0 default viewport.
  172. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));
  173. // This dummy draw call is here to make sure that view 0 is cleared
  174. // if no other draw calls are submitted to view 0.
  175. bgfx::touch(0);
  176. }
  177. else
  178. {
  179. ImGui::SetNextWindowPos(
  180. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  181. , ImGuiCond_FirstUseEver
  182. );
  183. ImGui::SetNextWindowSize(
  184. ImVec2(m_width / 5.0f, m_height - 10.0f)
  185. , ImGuiCond_FirstUseEver
  186. );
  187. ImGui::Begin("Settings"
  188. , NULL
  189. , 0
  190. );
  191. //ImGui::SliderFloat("intensity", &m_intensity, 0.0f, 3.0f);
  192. auto showBorders = m_vt->isShowBoardersEnabled();
  193. if (ImGui::Checkbox("Show borders", &showBorders))
  194. {
  195. m_vt->enableShowBoarders(showBorders);
  196. }
  197. auto colorMipLevels = m_vt->isColorMipLevelsEnabled();
  198. if (ImGui::Checkbox("Color mip levels", &colorMipLevels))
  199. {
  200. m_vt->enableColorMipLevels(colorMipLevels);
  201. }
  202. auto uploadsperframe = m_vt->getUploadsPerFrame();
  203. if (ImGui::InputInt("Updates per frame", &uploadsperframe, 1, 2))
  204. {
  205. uploadsperframe = bx::clamp(uploadsperframe, 1, 100);
  206. m_vt->setUploadsPerFrame(uploadsperframe);
  207. }
  208. ImGui::ImageButton(m_vt->getAtlastTexture(), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  209. ImGui::ImageButton(bgfx::getTexture(m_feedbackBuffer->getFrameBuffer()), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  210. ImGui::End();
  211. // Update camera.
  212. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  213. float view[16];
  214. cameraGetViewMtx(view);
  215. float proj[16];
  216. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 1000.0f, m_caps->homogeneousDepth);
  217. // Setup views
  218. for (uint16_t i = 0; i < 2; ++i)
  219. {
  220. uint16_t viewWidth = 0;
  221. uint16_t viewHeight = 0;
  222. // Setup pass, first pass is into mip-map feedback buffer, second pass is on screen
  223. if (i == 0)
  224. {
  225. bgfx::setViewFrameBuffer(i, m_feedbackBuffer->getFrameBuffer());
  226. viewWidth = uint16_t(m_feedbackBuffer->getWidth());
  227. viewHeight = uint16_t(m_feedbackBuffer->getHeight());
  228. }
  229. else
  230. {
  231. bgfx::FrameBufferHandle invalid = BGFX_INVALID_HANDLE;
  232. bgfx::setViewFrameBuffer(i, invalid);
  233. viewWidth = uint16_t(m_width);
  234. viewHeight = uint16_t(m_height);
  235. }
  236. bgfx::setViewRect(i, 0, 0, viewWidth, viewHeight);
  237. bgfx::setViewTransform(i, view, proj);
  238. float mtx[16];
  239. bx::mtxIdentity(mtx);
  240. // Set identity transform for draw call.
  241. bgfx::setTransform(mtx);
  242. // Set vertex and index buffer.
  243. bgfx::setVertexBuffer(0, m_vbh);
  244. bgfx::setIndexBuffer(m_ibh);
  245. // Set render states.
  246. bgfx::setState(0
  247. | BGFX_STATE_WRITE_RGB
  248. | BGFX_STATE_WRITE_A
  249. | BGFX_STATE_WRITE_Z
  250. | BGFX_STATE_DEPTH_TEST_LESS
  251. );
  252. // Set virtual texture uniforms
  253. m_vt->setUniforms();
  254. // Submit primitive for rendering to first pass (to feedback buffer, where mip levels and tile x/y will be rendered
  255. if (i == 0)
  256. {
  257. bgfx::submit(i, m_vt_mip);
  258. // Download previous frame feedback info
  259. m_feedbackBuffer->download();
  260. // Update and upload new requests
  261. m_vt->update(m_feedbackBuffer->getRequests(), 4);
  262. // Clear feedback
  263. m_feedbackBuffer->clear();
  264. // Copy new frame feedback buffer
  265. m_feedbackBuffer->copy(3);
  266. }
  267. else
  268. {
  269. // Submit primitive for rendering to second pass (to back buffer, where virtual texture page table and atlas will be used)
  270. bgfx::submit(i, m_vt_unlit);
  271. }
  272. }
  273. }
  274. imguiEndFrame();
  275. // Advance to next frame. Rendering thread will be kicked to
  276. // process submitted rendering primitives.
  277. bgfx::frame();
  278. return true;
  279. }
  280. return false;
  281. }
  282. bgfx::VertexBufferHandle m_vbh;
  283. bgfx::IndexBufferHandle m_ibh;
  284. bgfx::ProgramHandle m_vt_unlit;
  285. bgfx::ProgramHandle m_vt_mip;
  286. uint32_t m_width;
  287. uint32_t m_height;
  288. uint32_t m_debug;
  289. uint32_t m_reset;
  290. int32_t m_scrollArea;
  291. entry::MouseState m_mouseState;
  292. const bgfx::Caps* m_caps;
  293. int64_t m_timeOffset;
  294. bx::DefaultAllocator m_vtAllocator;
  295. vt::VirtualTextureInfo* m_vti;
  296. vt::VirtualTexture* m_vt;
  297. vt::FeedbackBuffer* m_feedbackBuffer;
  298. };
  299. } // namespace
  300. ENTRY_IMPLEMENT_MAIN(
  301. ExampleSVT
  302. , "40-svt"
  303. , "Sparse Virtual Textures."
  304. , "https://bkaradzic.github.io/bgfx/examples.html#svt"
  305. );