terrain.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /*
  2. * Copyright 2015 Andrew Mac. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include <bx/allocator.h>
  6. #include <bx/debug.h>
  7. #include <bx/math.h>
  8. #include "common.h"
  9. #include "bgfx_utils.h"
  10. #include "imgui/imgui.h"
  11. #include "camera.h"
  12. namespace
  13. {
  14. static const uint16_t s_terrainSize = 256;
  15. struct PosTexCoord0Vertex
  16. {
  17. float m_x;
  18. float m_y;
  19. float m_z;
  20. float m_u;
  21. float m_v;
  22. static void init()
  23. {
  24. ms_layout
  25. .begin()
  26. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  27. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  28. .end();
  29. }
  30. static bgfx::VertexLayout ms_layout;
  31. };
  32. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  33. struct TerrainData
  34. {
  35. int32_t m_mode;
  36. bool m_dirty;
  37. float m_transform[16];
  38. uint8_t* m_heightMap;
  39. PosTexCoord0Vertex* m_vertices;
  40. uint32_t m_vertexCount;
  41. uint16_t* m_indices;
  42. uint32_t m_indexCount;
  43. };
  44. struct BrushData
  45. {
  46. bool m_raise;
  47. int32_t m_size;
  48. float m_power;
  49. };
  50. class ExampleTerrain : public entry::AppI
  51. {
  52. public:
  53. ExampleTerrain(const char* _name, const char* _description, const char* _url)
  54. : entry::AppI(_name, _description, _url)
  55. {
  56. }
  57. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  58. {
  59. Args args(_argc, _argv);
  60. m_width = _width;
  61. m_height = _height;
  62. m_debug = BGFX_DEBUG_NONE;
  63. m_reset = BGFX_RESET_VSYNC;
  64. bgfx::Init init;
  65. init.type = args.m_type;
  66. init.vendorId = args.m_pciId;
  67. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  68. init.platformData.ndt = entry::getNativeDisplayHandle();
  69. init.platformData.type = entry::getNativeWindowHandleType(entry::kDefaultWindowHandle);
  70. init.resolution.width = m_width;
  71. init.resolution.height = m_height;
  72. init.resolution.reset = m_reset;
  73. bgfx::init(init);
  74. // Enable m_debug text.
  75. bgfx::setDebug(m_debug);
  76. // Set view 0 clear state.
  77. bgfx::setViewClear(0
  78. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  79. , 0x303030ff
  80. , 1.0f
  81. , 0
  82. );
  83. // Create vertex stream declaration.
  84. PosTexCoord0Vertex::init();
  85. // Create program from shaders.
  86. m_terrainProgram = loadProgram("vs_terrain", "fs_terrain");
  87. m_terrainHeightTextureProgram = loadProgram("vs_terrain_height_texture", "fs_terrain");
  88. // Imgui.
  89. imguiCreate();
  90. m_timeOffset = bx::getHPCounter();
  91. m_vbh.idx = bgfx::kInvalidHandle;
  92. m_ibh.idx = bgfx::kInvalidHandle;
  93. m_dvbh.idx = bgfx::kInvalidHandle;
  94. m_dibh.idx = bgfx::kInvalidHandle;
  95. m_heightTexture.idx = bgfx::kInvalidHandle;
  96. s_heightTexture = bgfx::createUniform("s_heightTexture", bgfx::UniformType::Sampler);
  97. m_oldWidth = 0;
  98. m_oldHeight = 0;
  99. m_oldReset = m_reset;
  100. m_brush.m_power = 0.5f;
  101. m_brush.m_size = 10;
  102. m_brush.m_raise = true;
  103. uint32_t num = s_terrainSize * s_terrainSize;
  104. m_terrain.m_mode = 0;
  105. m_terrain.m_dirty = true;
  106. m_terrain.m_vertices = (PosTexCoord0Vertex*)bx::alloc(entry::getAllocator(), num * sizeof(PosTexCoord0Vertex) );
  107. m_terrain.m_indices = (uint16_t*)bx::alloc(entry::getAllocator(), num * sizeof(uint16_t) * 6);
  108. m_terrain.m_heightMap = (uint8_t*)bx::alloc(entry::getAllocator(), num);
  109. bx::mtxSRT(m_terrain.m_transform, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
  110. bx::memSet(m_terrain.m_heightMap, 0, sizeof(uint8_t) * s_terrainSize * s_terrainSize);
  111. cameraCreate();
  112. cameraSetPosition({ s_terrainSize/2.0f, 100.0f, 0.0f });
  113. cameraSetVerticalAngle(-bx::kPiQuarter);
  114. }
  115. virtual int shutdown() override
  116. {
  117. // Cleanup.
  118. cameraDestroy();
  119. imguiDestroy();
  120. if (bgfx::isValid(m_ibh) )
  121. {
  122. bgfx::destroy(m_ibh);
  123. }
  124. if (bgfx::isValid(m_vbh) )
  125. {
  126. bgfx::destroy(m_vbh);
  127. }
  128. if (bgfx::isValid(m_dibh) )
  129. {
  130. bgfx::destroy(m_dibh);
  131. }
  132. if (bgfx::isValid(m_dvbh) )
  133. {
  134. bgfx::destroy(m_dvbh);
  135. }
  136. bgfx::destroy(s_heightTexture);
  137. if (bgfx::isValid(m_heightTexture) )
  138. {
  139. bgfx::destroy(m_heightTexture);
  140. }
  141. bgfx::destroy(m_terrainProgram);
  142. bgfx::destroy(m_terrainHeightTextureProgram);
  143. /// When data is passed to bgfx via makeRef we need to make
  144. /// sure library is done with it before freeing memory blocks.
  145. bgfx::frame();
  146. bx::AllocatorI* allocator = entry::getAllocator();
  147. bx::free(allocator, m_terrain.m_vertices);
  148. bx::free(allocator, m_terrain.m_indices);
  149. bx::free(allocator, m_terrain.m_heightMap);
  150. // Shutdown bgfx.
  151. bgfx::shutdown();
  152. return 0;
  153. }
  154. void updateTerrainMesh()
  155. {
  156. m_terrain.m_vertexCount = 0;
  157. for (uint32_t y = 0; y < s_terrainSize; y++)
  158. {
  159. for (uint32_t x = 0; x < s_terrainSize; x++)
  160. {
  161. PosTexCoord0Vertex* vert = &m_terrain.m_vertices[m_terrain.m_vertexCount];
  162. vert->m_x = (float)x;
  163. vert->m_y = m_terrain.m_heightMap[(y * s_terrainSize) + x];
  164. vert->m_z = (float)y;
  165. vert->m_u = (x + 0.5f) / s_terrainSize;
  166. vert->m_v = (y + 0.5f) / s_terrainSize;
  167. m_terrain.m_vertexCount++;
  168. }
  169. }
  170. m_terrain.m_indexCount = 0;
  171. for (uint16_t y = 0; y < (s_terrainSize - 1); y++)
  172. {
  173. uint16_t y_offset = (y * s_terrainSize);
  174. for (uint16_t x = 0; x < (s_terrainSize - 1); x++)
  175. {
  176. m_terrain.m_indices[m_terrain.m_indexCount + 0] = y_offset + x + 1;
  177. m_terrain.m_indices[m_terrain.m_indexCount + 1] = y_offset + x + s_terrainSize;
  178. m_terrain.m_indices[m_terrain.m_indexCount + 2] = y_offset + x;
  179. m_terrain.m_indices[m_terrain.m_indexCount + 3] = y_offset + x + s_terrainSize + 1;
  180. m_terrain.m_indices[m_terrain.m_indexCount + 4] = y_offset + x + s_terrainSize;
  181. m_terrain.m_indices[m_terrain.m_indexCount + 5] = y_offset + x + 1;
  182. m_terrain.m_indexCount += 6;
  183. }
  184. }
  185. }
  186. void updateTerrain()
  187. {
  188. const bgfx::Memory* mem;
  189. switch (m_terrain.m_mode)
  190. {
  191. default: // Vertex Buffer : Destroy and recreate a regular vertex buffer to update terrain.
  192. updateTerrainMesh();
  193. if (bgfx::isValid(m_vbh) )
  194. {
  195. bgfx::destroy(m_vbh);
  196. }
  197. mem = bgfx::makeRef(&m_terrain.m_vertices[0], sizeof(PosTexCoord0Vertex) * m_terrain.m_vertexCount);
  198. m_vbh = bgfx::createVertexBuffer(mem, PosTexCoord0Vertex::ms_layout);
  199. if (bgfx::isValid(m_ibh) )
  200. {
  201. bgfx::destroy(m_ibh);
  202. }
  203. mem = bgfx::makeRef(&m_terrain.m_indices[0], sizeof(uint16_t) * m_terrain.m_indexCount);
  204. m_ibh = bgfx::createIndexBuffer(mem);
  205. break;
  206. case 1: // Dynamic Vertex Buffer : Utilize dynamic vertex buffer to update terrain.
  207. updateTerrainMesh();
  208. if (!bgfx::isValid(m_dvbh) )
  209. {
  210. m_dvbh = bgfx::createDynamicVertexBuffer(m_terrain.m_vertexCount, PosTexCoord0Vertex::ms_layout);
  211. }
  212. mem = bgfx::makeRef(&m_terrain.m_vertices[0], sizeof(PosTexCoord0Vertex) * m_terrain.m_vertexCount);
  213. bgfx::update(m_dvbh, 0, mem);
  214. if (!bgfx::isValid(m_dibh) )
  215. {
  216. m_dibh = bgfx::createDynamicIndexBuffer(m_terrain.m_indexCount);
  217. }
  218. mem = bgfx::makeRef(&m_terrain.m_indices[0], sizeof(uint16_t) * m_terrain.m_indexCount);
  219. bgfx::update(m_dibh, 0, mem);
  220. break;
  221. case 2: // Height Texture: Update a height texture that is sampled in the terrain vertex shader.
  222. if (!bgfx::isValid(m_vbh) || !bgfx::isValid(m_ibh) )
  223. {
  224. updateTerrainMesh();
  225. mem = bgfx::makeRef(&m_terrain.m_vertices[0], sizeof(PosTexCoord0Vertex) * m_terrain.m_vertexCount);
  226. m_vbh = bgfx::createVertexBuffer(mem, PosTexCoord0Vertex::ms_layout);
  227. mem = bgfx::makeRef(&m_terrain.m_indices[0], sizeof(uint16_t) * m_terrain.m_indexCount);
  228. m_ibh = bgfx::createIndexBuffer(mem);
  229. }
  230. if (!bgfx::isValid(m_heightTexture) )
  231. {
  232. m_heightTexture = bgfx::createTexture2D(s_terrainSize, s_terrainSize, false, 1, bgfx::TextureFormat::R8);
  233. }
  234. mem = bgfx::makeRef(&m_terrain.m_heightMap[0], sizeof(uint8_t) * s_terrainSize * s_terrainSize);
  235. bgfx::updateTexture2D(m_heightTexture, 0, 0, 0, 0, s_terrainSize, s_terrainSize, mem);
  236. break;
  237. }
  238. }
  239. void paintTerrainHeight(uint32_t _x, uint32_t _y)
  240. {
  241. for (int32_t area_y = -m_brush.m_size; area_y < m_brush.m_size; ++area_y)
  242. {
  243. for (int32_t area_x = -m_brush.m_size; area_x < m_brush.m_size; ++area_x)
  244. {
  245. int32_t brush_x = _x + area_x;
  246. if (brush_x < 0
  247. || brush_x >= (int32_t)s_terrainSize)
  248. {
  249. continue;
  250. }
  251. int32_t brush_y = _y + area_y;
  252. if (brush_y < 0
  253. || brush_y >= (int32_t)s_terrainSize)
  254. {
  255. continue;
  256. }
  257. uint32_t heightMapPos = (brush_y * s_terrainSize) + brush_x;
  258. float height = (float)m_terrain.m_heightMap[heightMapPos];
  259. // Brush attenuation
  260. float a2 = (float)(area_x * area_x);
  261. float b2 = (float)(area_y * area_y);
  262. float brushAttn = m_brush.m_size - bx::sqrt(a2 + b2);
  263. // Raise/Lower and scale by brush power.
  264. height += 0.0f < bx::clamp(brushAttn*m_brush.m_power, 0.0f, m_brush.m_power) && m_brush.m_raise
  265. ? 1.0f
  266. : -1.0f
  267. ;
  268. m_terrain.m_heightMap[heightMapPos] = (uint8_t)bx::clamp(height, 0.0f, 255.0f);
  269. m_terrain.m_dirty = true;
  270. }
  271. }
  272. }
  273. void mousePickTerrain()
  274. {
  275. float ray_clip[4];
  276. ray_clip[0] = ( (2.0f * m_mouseState.m_mx) / m_width - 1.0f) * -1.0f;
  277. ray_clip[1] = ( (1.0f - (2.0f * m_mouseState.m_my) / m_height) ) * -1.0f;
  278. ray_clip[2] = -1.0f;
  279. ray_clip[3] = 1.0f;
  280. float invProjMtx[16];
  281. bx::mtxInverse(invProjMtx, m_projMtx);
  282. float ray_eye[4];
  283. bx::vec4MulMtx(ray_eye, ray_clip, invProjMtx);
  284. ray_eye[2] = -1.0f;
  285. ray_eye[3] = 0.0f;
  286. float invViewMtx[16];
  287. bx::mtxInverse(invViewMtx, m_viewMtx);
  288. float ray_world[4];
  289. bx::vec4MulMtx(ray_world, ray_eye, invViewMtx);
  290. const bx::Vec3 rayDir = bx::mul(bx::normalize(bx::load<bx::Vec3>(ray_world) ), -1.0f);
  291. bx::Vec3 pos = cameraGetPosition();
  292. for (int i = 0; i < 1000; ++i)
  293. {
  294. pos = bx::add(pos, rayDir);
  295. if (pos.x < 0
  296. || pos.x >= s_terrainSize
  297. || pos.z < 0
  298. || pos.z >= s_terrainSize)
  299. {
  300. continue;
  301. }
  302. uint32_t heightMapPos = ( (uint32_t)pos.z * s_terrainSize) + (uint32_t)pos.x;
  303. if (pos.y < m_terrain.m_heightMap[heightMapPos])
  304. {
  305. paintTerrainHeight( (uint32_t)pos.x, (uint32_t)pos.z);
  306. return;
  307. }
  308. }
  309. }
  310. bool update() override
  311. {
  312. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  313. {
  314. int64_t now = bx::getHPCounter();
  315. static int64_t last = now;
  316. const int64_t frameTime = now - last;
  317. last = now;
  318. const double freq = double(bx::getHPFrequency() );
  319. const float deltaTime = float(frameTime/freq);
  320. imguiBeginFrame(m_mouseState.m_mx
  321. , m_mouseState.m_my
  322. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  323. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  324. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  325. , m_mouseState.m_mz
  326. , uint16_t(m_width)
  327. , uint16_t(m_height)
  328. );
  329. showExampleDialog(this);
  330. ImGui::SetNextWindowPos(
  331. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  332. , ImGuiCond_FirstUseEver
  333. );
  334. ImGui::SetNextWindowSize(
  335. ImVec2(m_width / 5.0f, m_height / 3.0f)
  336. , ImGuiCond_FirstUseEver
  337. );
  338. ImGui::Begin("Settings"
  339. , NULL
  340. , 0
  341. );
  342. ImGui::Separator();
  343. m_terrain.m_dirty |= ImGui::RadioButton("Vertex Buffer", &m_terrain.m_mode, 0);
  344. m_terrain.m_dirty |= ImGui::RadioButton("Dynamic Vertex Buffer", &m_terrain.m_mode, 1);
  345. m_terrain.m_dirty |= ImGui::RadioButton("Height Texture", &m_terrain.m_mode, 2);
  346. ImGui::Separator();
  347. ImGui::Checkbox("Raise Terrain", &m_brush.m_raise);
  348. ImGui::SliderInt("Brush Size", &m_brush.m_size, 1, 50);
  349. ImGui::SliderFloat("Brush Power", &m_brush.m_power, 0.0f, 1.0f);
  350. ImGui::End();
  351. imguiEndFrame();
  352. // Update camera.
  353. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  354. if (!ImGui::MouseOverArea() )
  355. {
  356. if (!!m_mouseState.m_buttons[entry::MouseButton::Left])
  357. {
  358. mousePickTerrain();
  359. }
  360. }
  361. // Update terrain.
  362. if (m_terrain.m_dirty)
  363. {
  364. updateTerrain();
  365. m_terrain.m_dirty = false;
  366. }
  367. // Set view 0 default viewport.
  368. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  369. cameraGetViewMtx(m_viewMtx);
  370. bx::mtxProj(m_projMtx, 60.0f, float(m_width) / float(m_height), 0.1f, 2000.0f, bgfx::getCaps()->homogeneousDepth);
  371. bgfx::setViewTransform(0, m_viewMtx, m_projMtx);
  372. bgfx::setTransform(m_terrain.m_transform);
  373. switch (m_terrain.m_mode)
  374. {
  375. default:
  376. bgfx::setVertexBuffer(0, m_vbh);
  377. bgfx::setIndexBuffer(m_ibh);
  378. bgfx::submit(0, m_terrainProgram);
  379. break;
  380. case 1:
  381. bgfx::setVertexBuffer(0, m_dvbh);
  382. bgfx::setIndexBuffer(m_dibh);
  383. bgfx::submit(0, m_terrainProgram);
  384. break;
  385. case 2:
  386. bgfx::setVertexBuffer(0, m_vbh);
  387. bgfx::setIndexBuffer(m_ibh);
  388. bgfx::setTexture(0, s_heightTexture, m_heightTexture);
  389. bgfx::submit(0, m_terrainHeightTextureProgram);
  390. break;
  391. }
  392. // Advance to next frame. Rendering thread will be kicked to
  393. // process submitted rendering primitives.
  394. bgfx::frame();
  395. return true;
  396. }
  397. return false;
  398. }
  399. bgfx::VertexBufferHandle m_vbh;
  400. bgfx::IndexBufferHandle m_ibh;
  401. bgfx::DynamicVertexBufferHandle m_dvbh;
  402. bgfx::DynamicIndexBufferHandle m_dibh;
  403. bgfx::ProgramHandle m_terrainProgram;
  404. bgfx::ProgramHandle m_terrainHeightTextureProgram;
  405. bgfx::UniformHandle s_heightTexture;
  406. bgfx::TextureHandle m_heightTexture;
  407. float m_viewMtx[16];
  408. float m_projMtx[16];
  409. uint32_t m_width;
  410. uint32_t m_height;
  411. uint32_t m_debug;
  412. uint32_t m_reset;
  413. uint32_t m_oldWidth;
  414. uint32_t m_oldHeight;
  415. uint32_t m_oldReset;
  416. TerrainData m_terrain;
  417. BrushData m_brush;
  418. entry::MouseState m_mouseState;
  419. int64_t m_timeOffset;
  420. };
  421. } // namespace
  422. ENTRY_IMPLEMENT_MAIN(
  423. ExampleTerrain
  424. , "27-terrain"
  425. , "Terrain painting example."
  426. , "https://bkaradzic.github.io/bgfx/examples.html#terrain"
  427. );