terrain.cpp 13 KB

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