terrain.cpp 14 KB

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