webgl_gpgpu_protoplanet.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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/WebGL.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 ( WEBGL.isWebGLAvailable() === false ) {
  185. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  186. }
  187. var isIE = /Trident/i.test( navigator.userAgent );
  188. var isEdge = /Edge/i.test( navigator.userAgent );
  189. var hash = document.location.hash.substr( 1 );
  190. if ( hash ) hash = parseInt( hash, 0 );
  191. // Texture width for simulation (each texel is a debris particle)
  192. var WIDTH = hash || ( ( isIE || isEdge ) ? 4 : 64 );
  193. var container, stats;
  194. var camera, scene, renderer, geometry, controls;
  195. var PARTICLES = WIDTH * WIDTH;
  196. document.getElementById( 'protoplanets' ).innerText = PARTICLES;
  197. function change( n ) {
  198. location.hash = n;
  199. location.reload();
  200. return false;
  201. }
  202. var options = '';
  203. for ( var i = 1; i < 8; i++ ) {
  204. var j = Math.pow( 2, i );
  205. options += '<a href="#" onclick="return change(' + j + ')">' + ( j * j ) + '</a> ';
  206. }
  207. document.getElementById( 'options' ).innerHTML = options;
  208. if ( isEdge || isIE ) {
  209. document.getElementById( 'warning' ).innerText = 'particle counts greater than 16 may not render with ' + ( isEdge ? 'Edge' : 'IE11' );
  210. }
  211. var gpuCompute;
  212. var velocityVariable;
  213. var positionVariable;
  214. var positionUniforms;
  215. var velocityUniforms;
  216. var particleUniforms;
  217. var effectController;
  218. init();
  219. animate();
  220. function init() {
  221. container = document.createElement( 'div' );
  222. document.body.appendChild( container );
  223. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 5, 15000 );
  224. camera.position.y = 120;
  225. camera.position.z = 400;
  226. scene = new THREE.Scene();
  227. renderer = new THREE.WebGLRenderer();
  228. renderer.setPixelRatio( window.devicePixelRatio );
  229. renderer.setSize( window.innerWidth, window.innerHeight );
  230. container.appendChild( renderer.domElement );
  231. controls = new THREE.OrbitControls( camera, renderer.domElement );
  232. effectController = {
  233. // Can be changed dynamically
  234. gravityConstant: 100.0,
  235. density: 0.45,
  236. // Must restart simulation
  237. radius: 300,
  238. height: 8,
  239. exponent: 0.4,
  240. maxMass: 15.0,
  241. velocity: 70,
  242. velocityExponent: 0.2,
  243. randVelocity: 0.001
  244. };
  245. initComputeRenderer();
  246. stats = new Stats();
  247. container.appendChild( stats.dom );
  248. window.addEventListener( 'resize', onWindowResize, false );
  249. initGUI();
  250. initProtoplanets();
  251. dynamicValuesChanger();
  252. }
  253. function initComputeRenderer() {
  254. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  255. var dtPosition = gpuCompute.createTexture();
  256. var dtVelocity = gpuCompute.createTexture();
  257. fillTextures( dtPosition, dtVelocity );
  258. velocityVariable = gpuCompute.addVariable( "textureVelocity", document.getElementById( 'computeShaderVelocity' ).textContent, dtVelocity );
  259. positionVariable = gpuCompute.addVariable( "texturePosition", document.getElementById( 'computeShaderPosition' ).textContent, dtPosition );
  260. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  261. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  262. positionUniforms = positionVariable.material.uniforms;
  263. velocityUniforms = velocityVariable.material.uniforms;
  264. velocityUniforms.gravityConstant = { value: 0.0 };
  265. velocityUniforms.density = { value: 0.0 };
  266. var error = gpuCompute.init();
  267. if ( error !== null ) {
  268. console.error( error );
  269. }
  270. }
  271. function restartSimulation() {
  272. var dtPosition = gpuCompute.createTexture();
  273. var dtVelocity = gpuCompute.createTexture();
  274. fillTextures( dtPosition, dtVelocity );
  275. gpuCompute.renderTexture( dtPosition, positionVariable.renderTargets[ 0 ] );
  276. gpuCompute.renderTexture( dtPosition, positionVariable.renderTargets[ 1 ] );
  277. gpuCompute.renderTexture( dtVelocity, velocityVariable.renderTargets[ 0 ] );
  278. gpuCompute.renderTexture( dtVelocity, velocityVariable.renderTargets[ 1 ] );
  279. }
  280. function initProtoplanets() {
  281. geometry = new THREE.BufferGeometry();
  282. var positions = new Float32Array( PARTICLES * 3 );
  283. var p = 0;
  284. for ( var i = 0; i < PARTICLES; i++ ) {
  285. positions[ p++ ] = ( Math.random() * 2 - 1 ) * effectController.radius;
  286. positions[ p++ ] = 0; //( Math.random() * 2 - 1 ) * effectController.radius;
  287. positions[ p++ ] = ( Math.random() * 2 - 1 ) * effectController.radius;
  288. }
  289. var uvs = new Float32Array( PARTICLES * 2 );
  290. p = 0;
  291. for ( var j = 0; j < WIDTH; j++ ) {
  292. for ( var i = 0; i < WIDTH; i++ ) {
  293. uvs[ p++ ] = i / ( WIDTH - 1 );
  294. uvs[ p++ ] = j / ( WIDTH - 1 );
  295. }
  296. }
  297. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  298. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  299. particleUniforms = {
  300. texturePosition: { value: null },
  301. textureVelocity: { value: null },
  302. cameraConstant: { value: getCameraConstant( camera ) },
  303. density: { value: 0.0 }
  304. };
  305. // ShaderMaterial
  306. var material = new THREE.ShaderMaterial( {
  307. uniforms: particleUniforms,
  308. vertexShader: document.getElementById( 'particleVertexShader' ).textContent,
  309. fragmentShader: document.getElementById( 'particleFragmentShader' ).textContent
  310. } );
  311. material.extensions.drawBuffers = true;
  312. var particles = new THREE.Points( geometry, material );
  313. particles.matrixAutoUpdate = false;
  314. particles.updateMatrix();
  315. scene.add( particles );
  316. }
  317. function fillTextures( texturePosition, textureVelocity ) {
  318. var posArray = texturePosition.image.data;
  319. var velArray = textureVelocity.image.data;
  320. var radius = effectController.radius;
  321. var height = effectController.height;
  322. var exponent = effectController.exponent;
  323. var maxMass = effectController.maxMass * 1024 / PARTICLES;
  324. var maxVel = effectController.velocity;
  325. var velExponent = effectController.velocityExponent;
  326. var randVel = effectController.randVelocity;
  327. for ( var k = 0, kl = posArray.length; k < kl; k += 4 ) {
  328. // Position
  329. var x, y, z, rr;
  330. do {
  331. x = ( Math.random() * 2 - 1 );
  332. z = ( Math.random() * 2 - 1 );
  333. rr = x * x + z * z;
  334. } while ( rr > 1 );
  335. rr = Math.sqrt( rr );
  336. var rExp = radius * Math.pow( rr, exponent );
  337. // Velocity
  338. var vel = maxVel * Math.pow( rr, velExponent );
  339. var vx = vel * z + ( Math.random() * 2 - 1 ) * randVel;
  340. var vy = ( Math.random() * 2 - 1 ) * randVel * 0.05;
  341. var vz = - vel * x + ( Math.random() * 2 - 1 ) * randVel;
  342. x *= rExp;
  343. z *= rExp;
  344. y = ( Math.random() * 2 - 1 ) * height;
  345. var mass = Math.random() * maxMass + 1;
  346. // Fill in texture values
  347. posArray[ k + 0 ] = x;
  348. posArray[ k + 1 ] = y;
  349. posArray[ k + 2 ] = z;
  350. posArray[ k + 3 ] = 1;
  351. velArray[ k + 0 ] = vx;
  352. velArray[ k + 1 ] = vy;
  353. velArray[ k + 2 ] = vz;
  354. velArray[ k + 3 ] = mass;
  355. }
  356. }
  357. function onWindowResize() {
  358. camera.aspect = window.innerWidth / window.innerHeight;
  359. camera.updateProjectionMatrix();
  360. renderer.setSize( window.innerWidth, window.innerHeight );
  361. particleUniforms.cameraConstant.value = getCameraConstant( camera );
  362. }
  363. function dynamicValuesChanger() {
  364. velocityUniforms.gravityConstant.value = effectController.gravityConstant;
  365. velocityUniforms.density.value = effectController.density;
  366. particleUniforms.density.value = effectController.density;
  367. }
  368. function initGUI() {
  369. var gui = new dat.GUI();
  370. var folder1 = gui.addFolder( 'Dynamic parameters' );
  371. folder1.add( effectController, "gravityConstant", 0.0, 1000.0, 0.05 ).onChange( dynamicValuesChanger );
  372. folder1.add( effectController, "density", 0.0, 10.0, 0.001 ).onChange( dynamicValuesChanger );
  373. var folder2 = gui.addFolder( 'Static parameters - press restartSimulation' );
  374. folder2.add( effectController, "radius", 10.0, 1000.0, 1.0 );
  375. folder2.add( effectController, "height", 0.0, 50.0, 0.01 );
  376. folder2.add( effectController, "exponent", 0.0, 2.0, 0.001 );
  377. folder2.add( effectController, "maxMass", 1.0, 50.0, 0.1 );
  378. folder2.add( effectController, "velocity", 0.0, 150.0, 0.1 );
  379. folder2.add( effectController, "velocityExponent", 0.0, 1.0, 0.01 );
  380. folder2.add( effectController, "randVelocity", 0.0, 50.0, 0.1 );
  381. var buttonRestart = {
  382. restartSimulation: function() { restartSimulation(); }
  383. };
  384. folder2.add( buttonRestart, 'restartSimulation' );
  385. folder1.open();
  386. folder2.open();
  387. }
  388. function getCameraConstant( camera ) {
  389. return window.innerHeight / ( Math.tan( THREE.Math.DEG2RAD * 0.5 * camera.fov ) / camera.zoom );
  390. }
  391. function animate() {
  392. requestAnimationFrame( animate );
  393. render();
  394. stats.update();
  395. }
  396. function render() {
  397. gpuCompute.compute();
  398. particleUniforms.texturePosition.value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  399. particleUniforms.textureVelocity.value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  400. renderer.render( scene, camera );
  401. }
  402. </script>
  403. </body>
  404. </html>