webgl_gpgpu_protoplanet.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - gpgpu - protoplanet</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <style>
  8. body {
  9. background-color: #000000;
  10. margin: 0px;
  11. overflow: hidden;
  12. font-family:Monospace;
  13. font-size:13px;
  14. text-align:center;
  15. text-align:center;
  16. cursor: pointer;
  17. }
  18. a {
  19. color:#0078ff;
  20. }
  21. #info {
  22. color: #ffffff;
  23. position: absolute;
  24. top: 10px;
  25. width: 100%;
  26. }
  27. #warning {
  28. color: #ff0000;
  29. }
  30. </style>
  31. </head>
  32. <body>
  33. <div id="info">
  34. <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - <span id="protoplanets"></span> webgl gpgpu debris<br/>
  35. Select <span id="options"></span> debris<br/>
  36. <span id="warning"></span>
  37. </div>
  38. <script src="../build/three.js"></script>
  39. <script src="js/Detector.js"></script>
  40. <script src="js/libs/stats.min.js"></script>
  41. <script src="js/libs/dat.gui.min.js"></script>
  42. <script src="js/controls/OrbitControls.js"></script>
  43. <script src="js/GPUComputationRenderer.js"></script>
  44. <!-- Fragment shader for protoplanet's position -->
  45. <script id="computeShaderPosition" type="x-shader/x-fragment">
  46. #define delta ( 1.0 / 60.0 )
  47. void main() {
  48. vec2 uv = gl_FragCoord.xy / resolution.xy;
  49. vec4 tmpPos = texture2D( texturePosition, uv );
  50. vec3 pos = tmpPos.xyz;
  51. vec4 tmpVel = texture2D( textureVelocity, uv );
  52. vec3 vel = tmpVel.xyz;
  53. float mass = tmpVel.w;
  54. if ( mass == 0.0 ) {
  55. vel = vec3( 0.0 );
  56. }
  57. // Dynamics
  58. pos += vel * delta;
  59. gl_FragColor = vec4( pos, 1.0 );
  60. }
  61. </script>
  62. <!-- Fragment shader for protoplanet's velocity -->
  63. <script id="computeShaderVelocity" type="x-shader/x-fragment">
  64. // For PI declaration:
  65. #include <common>
  66. #define delta ( 1.0 / 60.0 )
  67. uniform float gravityConstant;
  68. uniform float density;
  69. const float width = resolution.x;
  70. const float height = resolution.y;
  71. float radiusFromMass( float mass ) {
  72. // Calculate radius of a sphere from mass and density
  73. return pow( ( 3.0 / ( 4.0 * PI ) ) * mass / density, 1.0 / 3.0 );
  74. }
  75. void main() {
  76. vec2 uv = gl_FragCoord.xy / resolution.xy;
  77. float idParticle = uv.y * resolution.x + uv.x;
  78. vec4 tmpPos = texture2D( texturePosition, uv );
  79. vec3 pos = tmpPos.xyz;
  80. vec4 tmpVel = texture2D( textureVelocity, uv );
  81. vec3 vel = tmpVel.xyz;
  82. float mass = tmpVel.w;
  83. if ( mass > 0.0 ) {
  84. float radius = radiusFromMass( mass );
  85. vec3 acceleration = vec3( 0.0 );
  86. // Gravity interaction
  87. for ( float y = 0.0; y < height; y++ ) {
  88. for ( float x = 0.0; x < width; x++ ) {
  89. vec2 secondParticleCoords = vec2( x + 0.5, y + 0.5 ) / resolution.xy;
  90. vec3 pos2 = texture2D( texturePosition, secondParticleCoords ).xyz;
  91. vec4 velTemp2 = texture2D( textureVelocity, secondParticleCoords );
  92. vec3 vel2 = velTemp2.xyz;
  93. float mass2 = velTemp2.w;
  94. float idParticle2 = secondParticleCoords.y * resolution.x + secondParticleCoords.x;
  95. if ( idParticle == idParticle2 ) {
  96. continue;
  97. }
  98. if ( mass2 == 0.0 ) {
  99. continue;
  100. }
  101. vec3 dPos = pos2 - pos;
  102. float distance = length( dPos );
  103. float radius2 = radiusFromMass( mass2 );
  104. if ( distance == 0.0 ) {
  105. continue;
  106. }
  107. // Checks collision
  108. if ( distance < radius + radius2 ) {
  109. if ( idParticle < idParticle2 ) {
  110. // This particle is aggregated by the other
  111. vel = ( vel * mass + vel2 * mass2 ) / ( mass + mass2 );
  112. mass += mass2;
  113. radius = radiusFromMass( mass );
  114. }
  115. else {
  116. // This particle dies
  117. mass = 0.0;
  118. radius = 0.0;
  119. vel = vec3( 0.0 );
  120. break;
  121. }
  122. }
  123. float distanceSq = distance * distance;
  124. float gravityField = gravityConstant * mass2 / distanceSq;
  125. gravityField = min( gravityField, 1000.0 );
  126. acceleration += gravityField * normalize( dPos );
  127. }
  128. if ( mass == 0.0 ) {
  129. break;
  130. }
  131. }
  132. // Dynamics
  133. vel += delta * acceleration;
  134. }
  135. gl_FragColor = vec4( vel, mass );
  136. }
  137. </script>
  138. <!-- Particles vertex shader -->
  139. <script type="x-shader/x-vertex" id="particleVertexShader">
  140. // For PI declaration:
  141. #include <common>
  142. uniform sampler2D texturePosition;
  143. uniform sampler2D textureVelocity;
  144. uniform float cameraConstant;
  145. uniform float density;
  146. varying vec4 vColor;
  147. float radiusFromMass( float mass ) {
  148. // Calculate radius of a sphere from mass and density
  149. return pow( ( 3.0 / ( 4.0 * PI ) ) * mass / density, 1.0 / 3.0 );
  150. }
  151. void main() {
  152. vec4 posTemp = texture2D( texturePosition, uv );
  153. vec3 pos = posTemp.xyz;
  154. vec4 velTemp = texture2D( textureVelocity, uv );
  155. vec3 vel = velTemp.xyz;
  156. float mass = velTemp.w;
  157. vColor = vec4( 1.0, mass / 250.0, 0.0, 1.0 );
  158. vec4 mvPosition = modelViewMatrix * vec4( pos, 1.0 );
  159. // Calculate radius of a sphere from mass and density
  160. //float radius = pow( ( 3.0 / ( 4.0 * PI ) ) * mass / density, 1.0 / 3.0 );
  161. float radius = radiusFromMass( mass );
  162. // Apparent size in pixels
  163. if ( mass == 0.0 ) {
  164. gl_PointSize = 0.0;
  165. }
  166. else {
  167. gl_PointSize = radius * cameraConstant / ( - mvPosition.z );
  168. }
  169. gl_Position = projectionMatrix * mvPosition;
  170. }
  171. </script>
  172. <!-- Particles fragment shader -->
  173. <script type="x-shader/x-fragment" id="particleFragmentShader">
  174. varying vec4 vColor;
  175. void main() {
  176. float f = length( gl_PointCoord - vec2( 0.5, 0.5 ) );
  177. if ( f > 0.5 ) {
  178. discard;
  179. }
  180. gl_FragColor = vColor;
  181. }
  182. </script>
  183. <script>
  184. if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
  185. var isIE = /Trident/i.test( navigator.userAgent );
  186. var isEdge = /Edge/i.test( navigator.userAgent );
  187. var hash = document.location.hash.substr( 1 );
  188. if ( hash ) hash = parseInt( hash, 0 );
  189. // Texture width for simulation (each texel is a debris particle)
  190. var WIDTH = hash || ( ( isIE || isEdge ) ? 4 : 64 );
  191. var container, stats;
  192. var camera, scene, renderer, geometry, controls;
  193. var PARTICLES = WIDTH * WIDTH;
  194. document.getElementById( 'protoplanets' ).innerText = PARTICLES;
  195. function change( n ) {
  196. location.hash = n;
  197. location.reload();
  198. return false;
  199. }
  200. var options = '';
  201. for ( var i = 1; i < 8; i++ ) {
  202. var j = Math.pow( 2, i );
  203. options += '<a href="#" onclick="return change(' + j + ')">' + ( j * j ) + '</a> ';
  204. }
  205. document.getElementById( 'options' ).innerHTML = options;
  206. if ( isEdge || isIE ) {
  207. document.getElementById( 'warning' ).innerText = 'particle counts greater than 16 may not render with ' + ( isEdge ? 'Edge' : 'IE11' );
  208. }
  209. var gpuCompute;
  210. var velocityVariable;
  211. var positionVariable;
  212. var positionUniforms;
  213. var velocityUniforms;
  214. var particleUniforms;
  215. var effectController;
  216. init();
  217. animate();
  218. function init() {
  219. container = document.createElement( 'div' );
  220. document.body.appendChild( container );
  221. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 5, 15000 );
  222. camera.position.y = 120;
  223. camera.position.z = 400;
  224. scene = new THREE.Scene();
  225. renderer = new THREE.WebGLRenderer();
  226. renderer.setPixelRatio( window.devicePixelRatio );
  227. renderer.setSize( window.innerWidth, window.innerHeight );
  228. container.appendChild( renderer.domElement );
  229. controls = new THREE.OrbitControls( camera, renderer.domElement );
  230. effectController = {
  231. // Can be changed dynamically
  232. gravityConstant: 100.0,
  233. density: 0.45,
  234. // Must restart simulation
  235. radius: 300,
  236. height: 8,
  237. exponent: 0.4,
  238. maxMass: 15.0,
  239. velocity: 70,
  240. velocityExponent: 0.2,
  241. randVelocity: 0.001
  242. };
  243. initComputeRenderer();
  244. stats = new Stats();
  245. container.appendChild( stats.dom );
  246. window.addEventListener( 'resize', onWindowResize, false );
  247. initGUI();
  248. initProtoplanets();
  249. dynamicValuesChanger();
  250. }
  251. function initComputeRenderer() {
  252. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  253. var dtPosition = gpuCompute.createTexture();
  254. var dtVelocity = gpuCompute.createTexture();
  255. fillTextures( dtPosition, dtVelocity );
  256. velocityVariable = gpuCompute.addVariable( "textureVelocity", document.getElementById( 'computeShaderVelocity' ).textContent, dtVelocity );
  257. positionVariable = gpuCompute.addVariable( "texturePosition", document.getElementById( 'computeShaderPosition' ).textContent, dtPosition );
  258. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  259. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  260. positionUniforms = positionVariable.material.uniforms;
  261. velocityUniforms = velocityVariable.material.uniforms;
  262. velocityUniforms.gravityConstant = { value: 0.0 };
  263. velocityUniforms.density = { value: 0.0 };
  264. var error = gpuCompute.init();
  265. if ( error !== null ) {
  266. console.error( error );
  267. }
  268. }
  269. function restartSimulation() {
  270. var dtPosition = gpuCompute.createTexture();
  271. var dtVelocity = gpuCompute.createTexture();
  272. fillTextures( dtPosition, dtVelocity );
  273. gpuCompute.renderTexture( dtPosition, positionVariable.renderTargets[ 0 ] );
  274. gpuCompute.renderTexture( dtPosition, positionVariable.renderTargets[ 1 ] );
  275. gpuCompute.renderTexture( dtVelocity, velocityVariable.renderTargets[ 0 ] );
  276. gpuCompute.renderTexture( dtVelocity, velocityVariable.renderTargets[ 1 ] );
  277. }
  278. function initProtoplanets() {
  279. geometry = new THREE.BufferGeometry();
  280. var positions = new Float32Array( PARTICLES * 3 );
  281. var p = 0;
  282. for ( var i = 0; i < PARTICLES; i++ ) {
  283. positions[ p++ ] = ( Math.random() * 2 - 1 ) * effectController.radius;
  284. positions[ p++ ] = 0; //( Math.random() * 2 - 1 ) * effectController.radius;
  285. positions[ p++ ] = ( Math.random() * 2 - 1 ) * effectController.radius;
  286. }
  287. var uvs = new Float32Array( PARTICLES * 2 );
  288. p = 0;
  289. for ( var j = 0; j < WIDTH; j++ ) {
  290. for ( var i = 0; i < WIDTH; i++ ) {
  291. uvs[ p++ ] = i / ( WIDTH - 1 );
  292. uvs[ p++ ] = j / ( WIDTH - 1 );
  293. }
  294. }
  295. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  296. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  297. particleUniforms = {
  298. texturePosition: { value: null },
  299. textureVelocity: { value: null },
  300. cameraConstant: { value: getCameraConstant( camera ) },
  301. density: { value: 0.0 }
  302. };
  303. // ShaderMaterial
  304. var material = new THREE.ShaderMaterial( {
  305. uniforms: particleUniforms,
  306. vertexShader: document.getElementById( 'particleVertexShader' ).textContent,
  307. fragmentShader: document.getElementById( 'particleFragmentShader' ).textContent
  308. } );
  309. material.extensions.drawBuffers = true;
  310. var particles = new THREE.Points( geometry, material );
  311. particles.matrixAutoUpdate = false;
  312. particles.updateMatrix();
  313. scene.add( particles );
  314. }
  315. function fillTextures( texturePosition, textureVelocity ) {
  316. var posArray = texturePosition.image.data;
  317. var velArray = textureVelocity.image.data;
  318. var radius = effectController.radius;
  319. var height = effectController.height;
  320. var exponent = effectController.exponent;
  321. var maxMass = effectController.maxMass * 1024 / PARTICLES;
  322. var maxVel = effectController.velocity;
  323. var velExponent = effectController.velocityExponent;
  324. var randVel = effectController.randVelocity;
  325. for ( var k = 0, kl = posArray.length; k < kl; k += 4 ) {
  326. // Position
  327. var x, y, z, rr;
  328. do {
  329. x = ( Math.random() * 2 - 1 );
  330. z = ( Math.random() * 2 - 1 );
  331. rr = x * x + z * z;
  332. } while ( rr > 1 );
  333. rr = Math.sqrt( rr );
  334. var rExp = radius * Math.pow( rr, exponent );
  335. // Velocity
  336. var vel = maxVel * Math.pow( rr, velExponent );
  337. var vx = vel * z + ( Math.random() * 2 - 1 ) * randVel;
  338. var vy = ( Math.random() * 2 - 1 ) * randVel * 0.05;
  339. var vz = - vel * x + ( Math.random() * 2 - 1 ) * randVel;
  340. x *= rExp;
  341. z *= rExp;
  342. y = ( Math.random() * 2 - 1 ) * height;
  343. var mass = Math.random() * maxMass + 1;
  344. // Fill in texture values
  345. posArray[ k + 0 ] = x;
  346. posArray[ k + 1 ] = y;
  347. posArray[ k + 2 ] = z;
  348. posArray[ k + 3 ] = 1;
  349. velArray[ k + 0 ] = vx;
  350. velArray[ k + 1 ] = vy;
  351. velArray[ k + 2 ] = vz;
  352. velArray[ k + 3 ] = mass;
  353. }
  354. }
  355. function onWindowResize() {
  356. camera.aspect = window.innerWidth / window.innerHeight;
  357. camera.updateProjectionMatrix();
  358. renderer.setSize( window.innerWidth, window.innerHeight );
  359. particleUniforms.cameraConstant.value = getCameraConstant( camera );
  360. }
  361. function dynamicValuesChanger() {
  362. velocityUniforms.gravityConstant.value = effectController.gravityConstant;
  363. velocityUniforms.density.value = effectController.density;
  364. particleUniforms.density.value = effectController.density;
  365. }
  366. function initGUI() {
  367. var gui = new dat.GUI();
  368. var folder1 = gui.addFolder( 'Dynamic parameters' );
  369. folder1.add( effectController, "gravityConstant", 0.0, 1000.0, 0.05 ).onChange( dynamicValuesChanger );
  370. folder1.add( effectController, "density", 0.0, 10.0, 0.001 ).onChange( dynamicValuesChanger );
  371. var folder2 = gui.addFolder( 'Static parameters - press restartSimulation' );
  372. folder2.add( effectController, "radius", 10.0, 1000.0, 1.0 );
  373. folder2.add( effectController, "height", 0.0, 50.0, 0.01 );
  374. folder2.add( effectController, "exponent", 0.0, 2.0, 0.001 );
  375. folder2.add( effectController, "maxMass", 1.0, 50.0, 0.1 );
  376. folder2.add( effectController, "velocity", 0.0, 150.0, 0.1 );
  377. folder2.add( effectController, "velocityExponent", 0.0, 1.0, 0.01 );
  378. folder2.add( effectController, "randVelocity", 0.0, 50.0, 0.1 );
  379. var buttonRestart = {
  380. restartSimulation: function() { restartSimulation(); }
  381. };
  382. folder2.add( buttonRestart, 'restartSimulation' );
  383. folder1.open();
  384. folder2.open();
  385. }
  386. function getCameraConstant( camera ) {
  387. return window.innerHeight / ( Math.tan( THREE.Math.DEG2RAD * 0.5 * camera.fov ) / camera.zoom );
  388. }
  389. function animate() {
  390. requestAnimationFrame( animate );
  391. render();
  392. stats.update();
  393. }
  394. function render() {
  395. gpuCompute.compute();
  396. particleUniforms.texturePosition.value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  397. particleUniforms.textureVelocity.value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  398. renderer.render( scene, camera );
  399. }
  400. </script>
  401. </body>
  402. </html>