2
0

svt.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  70. init.platformData.ndt = entry::getNativeDisplayHandle();
  71. init.platformData.type = entry::getNativeWindowHandleType();
  72. init.resolution.width = m_width;
  73. init.resolution.height = m_height;
  74. init.resolution.reset = m_reset;
  75. bgfx::init(init);
  76. // Enable m_debug text.
  77. bgfx::setDebug(m_debug);
  78. // Set views clear state (first pass to 0, second pass to some background color)
  79. for (uint16_t i = 0; i < 2; ++i)
  80. {
  81. bgfx::setViewClear(i
  82. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  83. , i == 0 ? 0 : 0x101050ff
  84. , 1.0f
  85. , 0
  86. );
  87. }
  88. // Create vertex stream declaration.
  89. PosTexcoordVertex::init();
  90. // Create static vertex buffer.
  91. m_vbh = bgfx::createVertexBuffer(
  92. bgfx::makeRef(s_vplaneVertices, sizeof(s_vplaneVertices))
  93. , PosTexcoordVertex::ms_layout
  94. );
  95. m_ibh = bgfx::createIndexBuffer(
  96. bgfx::makeRef(s_planeIndices, sizeof(s_planeIndices))
  97. );
  98. // Create program from shaders.
  99. m_vt_unlit = loadProgram("vs_vt_generic", "fs_vt_unlit");
  100. m_vt_mip = loadProgram("vs_vt_generic", "fs_vt_mip");
  101. // Imgui.
  102. imguiCreate();
  103. // Get renderer capabilities info.
  104. m_caps = bgfx::getCaps();
  105. m_scrollArea = 0;
  106. // Create and setup camera
  107. cameraCreate();
  108. cameraSetPosition({ 0.0f, 5.0f, 0.0f });
  109. cameraSetVerticalAngle(0.0f);
  110. // Set VirtualTexture system allocator
  111. vt::VirtualTexture::setAllocator(&m_vtAllocator);
  112. // Create Virtual texture info
  113. m_vti = new vt::VirtualTextureInfo();
  114. m_vti->m_virtualTextureSize = 8192; // The actual size will be read from the tile data file
  115. m_vti->m_tileSize = 128;
  116. m_vti->m_borderSize = 1;
  117. // Generate tile data file (if not yet created)
  118. {
  119. vt::TileGenerator tileGenerator(m_vti);
  120. tileGenerator.generate("textures/8k_mars.jpg");
  121. }
  122. // Load tile data file
  123. auto tileDataFile = new vt::TileDataFile("temp/8k_mars.vt", m_vti);
  124. tileDataFile->readInfo();
  125. // Create virtual texture and feedback buffer
  126. m_vt = new vt::VirtualTexture(tileDataFile, m_vti, 2048, 1);
  127. m_feedbackBuffer = new vt::FeedbackBuffer(m_vti, 64, 64);
  128. m_frameTime.reset();
  129. }
  130. virtual int shutdown() override
  131. {
  132. // Cleanup.
  133. bgfx::frame();
  134. cameraDestroy();
  135. imguiDestroy();
  136. bgfx::destroy(m_ibh);
  137. bgfx::destroy(m_vbh);
  138. bgfx::destroy(m_vt_unlit);
  139. bgfx::destroy(m_vt_mip);
  140. delete m_vti;
  141. delete m_vt;
  142. delete m_feedbackBuffer;
  143. // Shutdown bgfx.
  144. bgfx::shutdown();
  145. return 0;
  146. }
  147. bool update() override
  148. {
  149. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  150. {
  151. m_frameTime.frame();
  152. const float time = bx::toSeconds<float>(m_frameTime.getDurationTime() );
  153. const float deltaTime = bx::toSeconds<float>(m_frameTime.getDeltaTime() );
  154. imguiBeginFrame(
  155. m_mouseState.m_mx
  156. , m_mouseState.m_my
  157. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  158. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  159. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  160. , m_mouseState.m_mz
  161. , uint16_t(m_width)
  162. , uint16_t(m_height)
  163. );
  164. showExampleDialog(this);
  165. if ((BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK) != (bgfx::getCaps()->supported & (BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK)))
  166. {
  167. // When texture read-back or blit is not supported by GPU blink!
  168. bool blink = uint32_t(time*3.0f) & 1;
  169. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Texture read-back and/or blit not supported by GPU. ");
  170. // Set view 0 default viewport.
  171. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));
  172. // This dummy draw call is here to make sure that view 0 is cleared
  173. // if no other draw calls are submitted to view 0.
  174. bgfx::touch(0);
  175. }
  176. else
  177. {
  178. ImGui::SetNextWindowPos(
  179. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  180. , ImGuiCond_FirstUseEver
  181. );
  182. ImGui::SetNextWindowSize(
  183. ImVec2(m_width / 5.0f, m_height - 10.0f)
  184. , ImGuiCond_FirstUseEver
  185. );
  186. ImGui::Begin("Settings"
  187. , NULL
  188. , 0
  189. );
  190. //ImGui::SliderFloat("intensity", &m_intensity, 0.0f, 3.0f);
  191. auto showBorders = m_vt->isShowBoardersEnabled();
  192. if (ImGui::Checkbox("Show borders", &showBorders))
  193. {
  194. m_vt->enableShowBoarders(showBorders);
  195. }
  196. auto colorMipLevels = m_vt->isColorMipLevelsEnabled();
  197. if (ImGui::Checkbox("Color mip levels", &colorMipLevels))
  198. {
  199. m_vt->enableColorMipLevels(colorMipLevels);
  200. }
  201. auto uploadsperframe = m_vt->getUploadsPerFrame();
  202. if (ImGui::InputInt("Updates per frame", &uploadsperframe, 1, 2))
  203. {
  204. uploadsperframe = bx::clamp(uploadsperframe, 1, 100);
  205. m_vt->setUploadsPerFrame(uploadsperframe);
  206. }
  207. ImGui::ImageButton(m_vt->getAtlastTexture(), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  208. ImGui::ImageButton(bgfx::getTexture(m_feedbackBuffer->getFrameBuffer()), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  209. ImGui::End();
  210. // Update camera.
  211. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  212. float view[16];
  213. cameraGetViewMtx(view);
  214. float proj[16];
  215. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 1000.0f, m_caps->homogeneousDepth);
  216. // Setup views
  217. for (uint16_t i = 0; i < 2; ++i)
  218. {
  219. uint16_t viewWidth = 0;
  220. uint16_t viewHeight = 0;
  221. // Setup pass, first pass is into mip-map feedback buffer, second pass is on screen
  222. if (i == 0)
  223. {
  224. bgfx::setViewFrameBuffer(i, m_feedbackBuffer->getFrameBuffer());
  225. viewWidth = uint16_t(m_feedbackBuffer->getWidth());
  226. viewHeight = uint16_t(m_feedbackBuffer->getHeight());
  227. }
  228. else
  229. {
  230. bgfx::FrameBufferHandle invalid = BGFX_INVALID_HANDLE;
  231. bgfx::setViewFrameBuffer(i, invalid);
  232. viewWidth = uint16_t(m_width);
  233. viewHeight = uint16_t(m_height);
  234. }
  235. bgfx::setViewRect(i, 0, 0, viewWidth, viewHeight);
  236. bgfx::setViewTransform(i, view, proj);
  237. float mtx[16];
  238. bx::mtxIdentity(mtx);
  239. // Set identity transform for draw call.
  240. bgfx::setTransform(mtx);
  241. // Set vertex and index buffer.
  242. bgfx::setVertexBuffer(0, m_vbh);
  243. bgfx::setIndexBuffer(m_ibh);
  244. // Set render states.
  245. bgfx::setState(0
  246. | BGFX_STATE_WRITE_RGB
  247. | BGFX_STATE_WRITE_A
  248. | BGFX_STATE_WRITE_Z
  249. | BGFX_STATE_DEPTH_TEST_LESS
  250. );
  251. // Set virtual texture uniforms
  252. m_vt->setUniforms();
  253. // Submit primitive for rendering to first pass (to feedback buffer, where mip levels and tile x/y will be rendered
  254. if (i == 0)
  255. {
  256. bgfx::submit(i, m_vt_mip);
  257. // Download previous frame feedback info
  258. m_feedbackBuffer->download();
  259. // Update and upload new requests
  260. m_vt->update(m_feedbackBuffer->getRequests(), 4);
  261. // Clear feedback
  262. m_feedbackBuffer->clear();
  263. // Copy new frame feedback buffer
  264. m_feedbackBuffer->copy(3);
  265. }
  266. else
  267. {
  268. // Submit primitive for rendering to second pass (to back buffer, where virtual texture page table and atlas will be used)
  269. bgfx::submit(i, m_vt_unlit);
  270. }
  271. }
  272. }
  273. imguiEndFrame();
  274. // Advance to next frame. Rendering thread will be kicked to
  275. // process submitted rendering primitives.
  276. bgfx::frame();
  277. return true;
  278. }
  279. return false;
  280. }
  281. bgfx::VertexBufferHandle m_vbh;
  282. bgfx::IndexBufferHandle m_ibh;
  283. bgfx::ProgramHandle m_vt_unlit;
  284. bgfx::ProgramHandle m_vt_mip;
  285. uint32_t m_width;
  286. uint32_t m_height;
  287. uint32_t m_debug;
  288. uint32_t m_reset;
  289. int32_t m_scrollArea;
  290. entry::MouseState m_mouseState;
  291. const bgfx::Caps* m_caps;
  292. bx::DefaultAllocator m_vtAllocator;
  293. vt::VirtualTextureInfo* m_vti;
  294. vt::VirtualTexture* m_vt;
  295. vt::FeedbackBuffer* m_feedbackBuffer;
  296. FrameTime m_frameTime;
  297. };
  298. } // namespace
  299. ENTRY_IMPLEMENT_MAIN(
  300. ExampleSVT
  301. , "40-svt"
  302. , "Sparse Virtual Textures."
  303. , "https://bkaradzic.github.io/bgfx/examples.html#svt"
  304. );