2
0

nbody.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /*
  2. * Copyright 2014 Stanlo Slasinski. 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 <bgfx/bgfx.h>
  10. struct u_paramsDataStruct
  11. {
  12. float timeStep;
  13. int32_t dispatchSize;
  14. float gravity;
  15. float damping;
  16. float particleIntensity;
  17. float particleSize;
  18. int32_t baseSeed;
  19. float particlePower;
  20. float initialSpeed;
  21. int32_t initialShape;
  22. float maxAccel;
  23. };
  24. void InitializeParams(int32_t _mode, u_paramsDataStruct* _params)
  25. {
  26. switch(_mode)
  27. {
  28. case 0:
  29. _params->timeStep = 0.0067f;
  30. _params->dispatchSize = 32;
  31. _params->gravity = 0.069f;
  32. _params->damping = 0.0f;
  33. _params->particleIntensity = 0.35f;
  34. _params->particleSize = 0.925f;
  35. _params->baseSeed = 0;
  36. _params->particlePower = 5.0f;
  37. _params->initialSpeed = 122.6f;
  38. _params->initialShape = 0;
  39. _params->maxAccel = 30.0;
  40. break;
  41. case 1:
  42. _params->timeStep = 0.0157f;
  43. _params->dispatchSize = 32;
  44. _params->gravity = 0.109f;
  45. _params->damping = 0.25f;
  46. _params->particleIntensity = 0.64f;
  47. _params->particleSize = 0.279f;
  48. _params->baseSeed = 57;
  49. _params->particlePower = 3.5f;
  50. _params->initialSpeed = 3.2f;
  51. _params->initialShape = 1;
  52. _params->maxAccel = 100.0;
  53. break;
  54. case 2:
  55. _params->timeStep = 0.02f;
  56. _params->dispatchSize = 32;
  57. _params->gravity = 0.24f;
  58. _params->damping = 0.12f;
  59. _params->particleIntensity = 1.0f;
  60. _params->particleSize = 1.0f;
  61. _params->baseSeed = 23;
  62. _params->particlePower = 4.0f;
  63. _params->initialSpeed = 31.1f;
  64. _params->initialShape = 2;
  65. _params->maxAccel = 39.29f;
  66. break;
  67. case 3:
  68. _params->timeStep = 0.0118f;
  69. _params->dispatchSize = 32;
  70. _params->gravity = 0.141f;
  71. _params->damping = 1.0f;
  72. _params->particleIntensity = 0.64f;
  73. _params->particleSize = 0.28f;
  74. _params->baseSeed = 60;
  75. _params->particlePower = 1.97f;
  76. _params->initialSpeed = 69.7f;
  77. _params->initialShape = 3;
  78. _params->maxAccel = 3.21f;
  79. break;
  80. }
  81. }
  82. static const float s_quadVertices[] =
  83. {
  84. 1.0f, 1.0f,
  85. -1.0f, 1.0f,
  86. -1.0f, -1.0f,
  87. 1.0f, -1.0f,
  88. };
  89. static const uint16_t s_quadIndices[] = { 0, 1, 2, 2, 3, 0, };
  90. int _main_(int _argc, char** _argv)
  91. {
  92. Args args(_argc, _argv);
  93. uint32_t width = 1280;
  94. uint32_t height = 720;
  95. uint32_t debug = BGFX_DEBUG_TEXT;
  96. uint32_t reset = BGFX_RESET_VSYNC;
  97. bgfx::init(args.m_type, args.m_pciId);
  98. bgfx::reset(width, height, reset);
  99. // Enable debug text.
  100. bgfx::setDebug(debug);
  101. // Set view 0 clear state.
  102. bgfx::setViewClear(0
  103. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  104. , 0x303030ff
  105. , 1.0f
  106. , 0
  107. );
  108. const bgfx::Caps* caps = bgfx::getCaps();
  109. const bool computeSupported = !!(caps->supported & BGFX_CAPS_COMPUTE);
  110. const bool indirectSupported = !!(caps->supported & BGFX_CAPS_DRAW_INDIRECT);
  111. if (computeSupported)
  112. {
  113. // Imgui.
  114. imguiCreate();
  115. bgfx::VertexDecl quadVertexDecl;
  116. quadVertexDecl.begin()
  117. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  118. .end();
  119. // Create static vertex buffer.
  120. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(
  121. // Static data can be passed with bgfx::makeRef
  122. bgfx::makeRef(s_quadVertices, sizeof(s_quadVertices) )
  123. , quadVertexDecl
  124. );
  125. // Create static index buffer.
  126. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(
  127. // Static data can be passed with bgfx::makeRef
  128. bgfx::makeRef(s_quadIndices, sizeof(s_quadIndices) )
  129. );
  130. // Create particle program from shaders.
  131. bgfx::ProgramHandle particleProgram = loadProgram("vs_particle", "fs_particle");
  132. // Setup compute buffers
  133. bgfx::VertexDecl computeVertexDecl;
  134. computeVertexDecl.begin()
  135. .add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float)
  136. .end();
  137. const uint32_t threadGroupUpdateSize = 512;
  138. const uint32_t maxParticleCount = 32 * 1024;
  139. bgfx::DynamicVertexBufferHandle currPositionBuffer0 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  140. bgfx::DynamicVertexBufferHandle currPositionBuffer1 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  141. bgfx::DynamicVertexBufferHandle prevPositionBuffer0 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  142. bgfx::DynamicVertexBufferHandle prevPositionBuffer1 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  143. bgfx::UniformHandle u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, 3);
  144. bgfx::ProgramHandle initInstancesProgram = bgfx::createProgram(loadShader("cs_init_instances"), true);
  145. bgfx::ProgramHandle updateInstancesProgram = bgfx::createProgram(loadShader("cs_update_instances"), true);
  146. bgfx::ProgramHandle indirectProgram = BGFX_INVALID_HANDLE;
  147. bgfx::IndirectBufferHandle indirectBuffer = BGFX_INVALID_HANDLE;
  148. if (indirectSupported)
  149. {
  150. indirectProgram = bgfx::createProgram(loadShader("cs_indirect"), true);
  151. indirectBuffer = bgfx::createIndirectBuffer(2);
  152. }
  153. u_paramsDataStruct u_paramsData;
  154. InitializeParams(0, &u_paramsData);
  155. bgfx::setUniform(u_params, &u_paramsData, 3);
  156. bgfx::setBuffer(0, prevPositionBuffer0, bgfx::Access::Write);
  157. bgfx::setBuffer(1, currPositionBuffer0, bgfx::Access::Write);
  158. bgfx::dispatch(0, initInstancesProgram, maxParticleCount / threadGroupUpdateSize, 1, 1);
  159. float view[16];
  160. float initialPos[3] = { 0.0f, 0.0f, -45.0f };
  161. cameraCreate();
  162. cameraSetPosition(initialPos);
  163. cameraSetVerticalAngle(0.0f);
  164. cameraGetViewMtx(view);
  165. int32_t scrollArea = 0;
  166. bool useIndirect = false;
  167. entry::MouseState mouseState;
  168. while (!entry::processEvents(width, height, debug, reset, &mouseState) )
  169. {
  170. int64_t now = bx::getHPCounter();
  171. static int64_t last = now;
  172. const int64_t frameTime = now - last;
  173. last = now;
  174. const double freq = double(bx::getHPFrequency() );
  175. const float deltaTime = float(frameTime/freq);
  176. if (deltaTime > 1000.0)
  177. {
  178. abort();
  179. }
  180. // Set view 0 default viewport.
  181. bgfx::setViewRect(0, 0, 0, width, height);
  182. // Use debug font to print information about this example.
  183. bgfx::dbgTextClear();
  184. bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/24-nbody");
  185. bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: N-body simulation with compute shaders using buffers.");
  186. imguiBeginFrame(mouseState.m_mx
  187. , mouseState.m_my
  188. , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  189. | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  190. | (mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  191. , mouseState.m_mz
  192. , width
  193. , height
  194. );
  195. imguiBeginScrollArea("Settings", width - width / 4 - 10, 10, width / 4, 500, &scrollArea);
  196. imguiSlider("Random seed", u_paramsData.baseSeed, 0, 100);
  197. int32_t shape = imguiChoose(u_paramsData.initialShape, "Point", "Sphere", "Box", "Donut");
  198. imguiSlider("Initial speed", u_paramsData.initialSpeed, 0.0f, 300.0f, 0.1f);
  199. bool defaults = imguiButton("Reset");
  200. imguiSeparatorLine();
  201. imguiSlider("Particle count (x512)", u_paramsData.dispatchSize, 1, 64);
  202. imguiSlider("Gravity", u_paramsData.gravity, 0.0f, 0.3f, 0.001f);
  203. imguiSlider("Damping", u_paramsData.damping, 0.0f, 1.0f, 0.01f);
  204. imguiSlider("Max acceleration", u_paramsData.maxAccel, 0.0f, 100.0f, 0.01f);
  205. imguiSlider("Time step", u_paramsData.timeStep, 0.0f, 0.02f, 0.0001f);
  206. imguiSeparatorLine();
  207. imguiSlider("Particle intensity", u_paramsData.particleIntensity, 0.0f, 1.0f, 0.001f);
  208. imguiSlider("Particle size", u_paramsData.particleSize, 0.0f, 1.0f, 0.001f);
  209. imguiSlider("Particle power", u_paramsData.particlePower, 0.001f, 16.0f, 0.01f);
  210. imguiSeparatorLine();
  211. if (imguiCheck("Use draw/dispatch indirect", useIndirect, indirectSupported) )
  212. {
  213. useIndirect = !useIndirect;
  214. }
  215. imguiEndScrollArea();
  216. imguiEndFrame();
  217. // Modify parameters and reset if shape is changed
  218. if (shape != u_paramsData.initialShape)
  219. {
  220. defaults = true;
  221. InitializeParams(shape, &u_paramsData);
  222. }
  223. if (defaults)
  224. {
  225. bgfx::setBuffer(0, prevPositionBuffer0, bgfx::Access::Write);
  226. bgfx::setBuffer(1, currPositionBuffer0, bgfx::Access::Write);
  227. bgfx::setUniform(u_params, &u_paramsData, 3);
  228. bgfx::dispatch(0, initInstancesProgram, maxParticleCount / threadGroupUpdateSize, 1, 1);
  229. }
  230. if (useIndirect)
  231. {
  232. bgfx::setUniform(u_params, &u_paramsData, 3);
  233. bgfx::setBuffer(0, indirectBuffer, bgfx::Access::Write);
  234. bgfx::dispatch(0, indirectProgram);
  235. }
  236. bgfx::setBuffer(0, prevPositionBuffer0, bgfx::Access::Read);
  237. bgfx::setBuffer(1, currPositionBuffer0, bgfx::Access::Read);
  238. bgfx::setBuffer(2, prevPositionBuffer1, bgfx::Access::Write);
  239. bgfx::setBuffer(3, currPositionBuffer1, bgfx::Access::Write);
  240. bgfx::setUniform(u_params, &u_paramsData, 3);
  241. if (useIndirect)
  242. {
  243. bgfx::dispatch(0, updateInstancesProgram, indirectBuffer, 1);
  244. }
  245. else
  246. {
  247. bgfx::dispatch(0, updateInstancesProgram, u_paramsData.dispatchSize, 1, 1);
  248. }
  249. bx::xchg(currPositionBuffer0, currPositionBuffer1);
  250. bx::xchg(prevPositionBuffer0, prevPositionBuffer1);
  251. // Update camera.
  252. cameraUpdate(deltaTime, mouseState);
  253. cameraGetViewMtx(view);
  254. // Set view and projection matrix for view 0.
  255. const bgfx::HMD* hmd = bgfx::getHMD();
  256. if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) )
  257. {
  258. float viewHead[16];
  259. float eye[3] = {};
  260. bx::mtxQuatTranslationHMD(viewHead, hmd->eye[0].rotation, eye);
  261. float tmp[16];
  262. bx::mtxMul(tmp, view, viewHead);
  263. bgfx::setViewTransform(0, tmp, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection);
  264. // Set view 0 default viewport.
  265. //
  266. // Use HMD's width/height since HMD's internal frame buffer size
  267. // might be much larger than window size.
  268. bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
  269. }
  270. else
  271. {
  272. float proj[16];
  273. bx::mtxProj(proj, 90.0f, float(width)/float(height), 0.1f, 10000.0f);
  274. bgfx::setViewTransform(0, view, proj);
  275. // Set view 0 default viewport.
  276. bgfx::setViewRect(0, 0, 0, width, height);
  277. }
  278. // Set vertex and index buffer.
  279. bgfx::setVertexBuffer(vbh);
  280. bgfx::setIndexBuffer(ibh);
  281. bgfx::setInstanceDataBuffer(currPositionBuffer0, 0, u_paramsData.dispatchSize * threadGroupUpdateSize);
  282. // Set render states.
  283. bgfx::setState(0
  284. | BGFX_STATE_RGB_WRITE
  285. | BGFX_STATE_BLEND_ADD
  286. | BGFX_STATE_DEPTH_TEST_ALWAYS
  287. );
  288. // Submit primitive for rendering to view 0.
  289. if (useIndirect)
  290. {
  291. bgfx::submit(0, particleProgram, indirectBuffer, 0);
  292. }
  293. else
  294. {
  295. bgfx::submit(0, particleProgram);
  296. }
  297. // Advance to next frame. Rendering thread will be kicked to
  298. // process submitted rendering primitives.
  299. bgfx::frame();
  300. }
  301. // Cleanup.
  302. cameraDestroy();
  303. imguiDestroy();
  304. if (indirectSupported)
  305. {
  306. bgfx::destroyProgram(indirectProgram);
  307. bgfx::destroyIndirectBuffer(indirectBuffer);
  308. }
  309. bgfx::destroyUniform(u_params);
  310. bgfx::destroyDynamicVertexBuffer(currPositionBuffer0);
  311. bgfx::destroyDynamicVertexBuffer(currPositionBuffer1);
  312. bgfx::destroyDynamicVertexBuffer(prevPositionBuffer0);
  313. bgfx::destroyDynamicVertexBuffer(prevPositionBuffer1);
  314. bgfx::destroyProgram(updateInstancesProgram);
  315. bgfx::destroyProgram(initInstancesProgram);
  316. bgfx::destroyIndexBuffer(ibh);
  317. bgfx::destroyVertexBuffer(vbh);
  318. bgfx::destroyProgram(particleProgram);
  319. }
  320. else
  321. {
  322. int64_t timeOffset = bx::getHPCounter();
  323. entry::MouseState mouseState;
  324. while (!entry::processEvents(width, height, debug, reset, &mouseState) )
  325. {
  326. int64_t now = bx::getHPCounter();
  327. float time = (float)( (now - timeOffset)/double(bx::getHPFrequency() ) );
  328. bgfx::setViewRect(0, 0, 0, width, height);
  329. bgfx::dbgTextClear();
  330. bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/24-nbody");
  331. bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: N-body simulation with compute shaders using buffers.");
  332. bool blink = uint32_t(time*3.0f)&1;
  333. bgfx::dbgTextPrintf(0, 5, blink ? 0x1f : 0x01, " Compute is not supported by GPU. ");
  334. bgfx::touch(0);
  335. bgfx::frame();
  336. }
  337. }
  338. // Shutdown bgfx.
  339. bgfx::shutdown();
  340. return 0;
  341. }