webgl_particles_shapes.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - particles - shapes</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. font-family: Monospace;
  10. color: #aaa;
  11. background-color: #000;
  12. margin: 0px;
  13. overflow: hidden;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <script src="../build/Three.js"></script>
  19. <script src="js/RequestAnimationFrame.js"></script>
  20. <script src="js/Stats.js"></script>
  21. <script src="js/Tween.js"></script>
  22. <script src="js/Sparks.js"></script>
  23. <script src="js/ShaderExtras.js"></script>
  24. <script src="js/postprocessing/EffectComposer.js"></script>
  25. <script src="js/postprocessing/RenderPass.js"></script>
  26. <script src="js/postprocessing/ShaderPass.js"></script>
  27. <script src="js/postprocessing/MaskPass.js"></script>
  28. <script src="js/postprocessing/BloomPass.js"></script>
  29. <script src="js/postprocessing/FilmPass.js"></script>
  30. <!-- load the font file from canvas-text -->
  31. <script src="fonts/helvetiker_regular.typeface.js"></script>
  32. <script type="x-shader/x-vertex" id="vertexshader">
  33. attribute float size;
  34. attribute vec3 pcolor;
  35. varying vec3 vColor;
  36. void main() {
  37. vColor = pcolor;
  38. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  39. gl_PointSize = size * ( 200.0 / length( mvPosition.xyz ) );
  40. gl_Position = projectionMatrix * mvPosition;
  41. }
  42. </script>
  43. <script type="x-shader/x-fragment" id="fragmentshader">
  44. uniform sampler2D texture;
  45. varying vec3 vColor;
  46. void main() {
  47. vec4 outColor = texture2D( texture, gl_PointCoord );
  48. gl_FragColor = outColor * vec4( vColor, 1.0 );
  49. }
  50. </script>
  51. <script>
  52. var container, stats;
  53. var camera, scene, renderer;
  54. var text, plane;
  55. var speed = 50;
  56. var pointLight;
  57. var targetRotation = 0;
  58. var targetRotationOnMouseDown = 0;
  59. var mouseX = 0;
  60. var mouseXOnMouseDown = 0;
  61. var windowHalfX = window.innerWidth / 2;
  62. var windowHalfY = window.innerHeight / 2;
  63. var delta = 1, clock = new THREE.Clock();
  64. var heartShape, particleCloud, sparksEmitter, emitterPos;
  65. var _rotation = 0;
  66. var timeOnShapePath = 0;
  67. init();
  68. animate();
  69. function init() {
  70. container = document.createElement( 'div' );
  71. document.body.appendChild( container );
  72. var info = document.createElement( 'div' );
  73. info.style.position = 'absolute';
  74. info.style.top = '10px';
  75. info.style.width = '100%';
  76. info.style.textAlign = 'center';
  77. info.innerHTML = 'Three.js - simple particle systems with shapes by <a href="http://www.lab4games.net/zz85/blog">zz85</a><br/>Move your mouse. Click to pause/resume.';
  78. container.appendChild( info );
  79. // CAMERA
  80. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 2000 );
  81. camera.position.set( 0, 150, 400 );
  82. // SCENE
  83. scene = new THREE.Scene();
  84. var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  85. directionalLight.position.set( 0, -1, 1 );
  86. directionalLight.position.normalize();
  87. scene.add( directionalLight );
  88. pointLight = new THREE.PointLight( 0xffffff, 2, 300 );
  89. pointLight.position.set( 0, 0, 0 );
  90. scene.add( pointLight );
  91. // TEXT
  92. var theText = "THREE.JS";
  93. // Get text from hash
  94. var hash = document.location.hash.substr( 1 );
  95. if ( hash.length !== 0 ) {
  96. theText = hash;
  97. }
  98. var textMaterialFront = new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, opacity: 0.95 } );
  99. var textMaterialSide = new THREE.MeshLambertMaterial( { color: 0xffffff } );
  100. var text3d = new THREE.TextGeometry( theText, {
  101. size: 70,
  102. height: 25,
  103. curveSegments: 4,
  104. font: "helvetiker",
  105. bevelEnabled: true,
  106. bevelThickness: 2,
  107. bevelSize: 2,
  108. material: 0,
  109. extrudeMaterial: 1
  110. });
  111. text3d.materials = [ textMaterialFront, textMaterialSide ];
  112. text3d.computeVertexNormals();
  113. text3d.computeBoundingBox();
  114. var centerOffset = -0.5 * ( text3d.boundingBox.max.x - text3d.boundingBox.min.x );
  115. text = new THREE.Mesh( text3d, new THREE.MeshFaceMaterial() );
  116. // Potentially, we can extract the vertices or faces of the text to generate particles too.
  117. // Geo > Vertices > Position
  118. text.position.x = centerOffset;
  119. text.position.y = 130;
  120. text.position.z = -50;
  121. text.rotation.x = 0;
  122. text.rotation.y = Math.PI * 2;
  123. parent = new THREE.Object3D();
  124. parent.add( text );
  125. scene.add( parent );
  126. ///// Create particle objects for Three.js
  127. var particlesLength = 70000;
  128. var particles = new THREE.Geometry();
  129. function newpos( x, y, z ) {
  130. return new THREE.Vertex( new THREE.Vector3( x, y, z ) );
  131. }
  132. var Pool = {
  133. __pools: [],
  134. // Get a new Vector
  135. get: function() {
  136. if ( this.__pools.length > 0 ) {
  137. return this.__pools.pop();
  138. }
  139. console.log( "pool ran out!" )
  140. return null;
  141. },
  142. // Release a vector back into the pool
  143. add: function( v ) {
  144. this.__pools.push( v );
  145. }
  146. };
  147. for ( i = 0; i < particlesLength; i ++ ) {
  148. particles.vertices.push( newpos( Math.random() * 200 - 100, Math.random() * 100 + 150, Math.random() * 50 ) );
  149. Pool.add( i );
  150. }
  151. // Create pools of vectors
  152. attributes = {
  153. size: { type: 'f', value: [] },
  154. pcolor: { type: 'c', value: [] }
  155. };
  156. var sprite = generateSprite() ;
  157. texture = new THREE.Texture( sprite );
  158. texture.needsUpdate = true;
  159. uniforms = {
  160. texture: { type: "t", value: 0, texture: texture }
  161. };
  162. // PARAMETERS
  163. // Steadycounter
  164. // Life
  165. // Opacity
  166. // Hue Speed
  167. // Movement Speed
  168. function generateSprite() {
  169. var canvas = document.createElement( 'canvas' );
  170. canvas.width = 128;
  171. canvas.height = 128;
  172. var context = canvas.getContext( '2d' );
  173. // Just a square, doesnt work too bad with blur pp.
  174. // context.fillStyle = "white";
  175. // context.strokeStyle = "white";
  176. // context.fillRect(0, 0, 63, 63) ;
  177. // Heart Shapes are not too pretty here
  178. // var x = 4, y = 0;
  179. // context.save();
  180. // context.scale(8, 8); // Scale so canvas render can redraw within bounds
  181. // context.beginPath();
  182. // context.bezierCurveTo( x + 2.5, y + 2.5, x + 2.0, y, x, y );
  183. // context.bezierCurveTo( x - 3.0, y, x - 3.0, y + 3.5,x - 3.0,y + 3.5 );
  184. // context.bezierCurveTo( x - 3.0, y + 5.5, x - 1.0, y + 7.7, x + 2.5, y + 9.5 );
  185. // context.bezierCurveTo( x + 6.0, y + 7.7, x + 8.0, y + 5.5, x + 8.0, y + 3.5 );
  186. // context.bezierCurveTo( x + 8.0, y + 3.5, x + 8.0, y, x + 5.0, y );
  187. // context.bezierCurveTo( x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5 );
  188. // context.closePath();
  189. context.beginPath();
  190. context.arc( 64, 64, 60, 0, Math.PI * 2, false) ;
  191. context.closePath();
  192. context.lineWidth = 0.5; //0.05
  193. context.stroke();
  194. context.restore();
  195. var gradient = context.createRadialGradient( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 );
  196. gradient.addColorStop( 0, 'rgba(255,255,255,1)' );
  197. gradient.addColorStop( 0.2, 'rgba(255,255,255,1)' );
  198. gradient.addColorStop( 0.4, 'rgba(200,200,200,1)' );
  199. gradient.addColorStop( 1, 'rgba(0,0,0,1)' );
  200. context.fillStyle = gradient;
  201. context.fill();
  202. return canvas;
  203. }
  204. var shaderMaterial = new THREE.ShaderMaterial( {
  205. uniforms: uniforms,
  206. attributes: attributes,
  207. vertexShader: document.getElementById( 'vertexshader' ).textContent,
  208. fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
  209. blending: THREE.AdditiveBlending,
  210. depthWrite: false,
  211. transparent: true
  212. });
  213. particleCloud = new THREE.ParticleSystem( particles, shaderMaterial );
  214. particleCloud.dynamic = true;
  215. //particleCloud.sortParticles = true;
  216. var vertices = particleCloud.geometry.vertices;
  217. var values_size = attributes.size.value;
  218. var values_color = attributes.pcolor.value;
  219. for( var v = 0; v < vertices.length; v ++ ) {
  220. values_size[ v ] = 50;
  221. values_color[ v ] = new THREE.Color( 0xffffff );
  222. values_color[ v ].setHSV( 0, 0, 0 );
  223. particles.vertices[ v ].position.set( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY );
  224. }
  225. parent.add( particleCloud );
  226. particleCloud.y = 800;
  227. // Create Particle Systems
  228. // EMITTER STUFF
  229. // Heart
  230. var x = 0, y = 0;
  231. heartShape = new THREE.Shape();
  232. heartShape.moveTo( x + 25, y + 25 );
  233. heartShape.bezierCurveTo( x + 25, y + 25, x + 20, y, x, y );
  234. heartShape.bezierCurveTo( x - 30, y, x - 30, y + 35,x - 30,y + 35 );
  235. heartShape.bezierCurveTo( x - 30, y + 55, x - 10, y + 77, x + 25, y + 95 );
  236. heartShape.bezierCurveTo( x + 60, y + 77, x + 80, y + 55, x + 80, y + 35 );
  237. heartShape.bezierCurveTo( x + 80, y + 35, x + 80, y, x + 50, y );
  238. heartShape.bezierCurveTo( x + 35, y, x + 25, y + 25, x + 25, y + 25 );
  239. var hue = 0;
  240. var setTargetParticle = function() {
  241. var target = Pool.get();
  242. values_size[ target ] = Math.random() * 200 + 100;
  243. return target;
  244. };
  245. var onParticleCreated = function( p ) {
  246. var position = p.position;
  247. p.target.position = position;
  248. var target = p.target;
  249. if ( target ) {
  250. //console.log(target,particles.vertices[target]);
  251. //values_size[target]
  252. //values_color[target]
  253. hue += 0.0003 * delta;
  254. if ( hue > 1 ) hue -= 1;
  255. // TODO Create a PointOnShape Action/Zone in the particle engine
  256. timeOnShapePath += 0.00035 * delta;
  257. if ( timeOnShapePath > 1 ) timeOnShapePath -= 1;
  258. var pointOnShape = heartShape.getPointAt( timeOnShapePath );
  259. emitterpos.x = pointOnShape.x * 5 - 100;
  260. emitterpos.y = -pointOnShape.y * 5 + 400;
  261. //pointLight.position.copy( emitterpos );
  262. pointLight.position.x = emitterpos.x;
  263. pointLight.position.y = emitterpos.y;
  264. pointLight.position.z = 100;
  265. particles.vertices[ target ].position = p.position;
  266. values_color[ target ].setHSV( hue, 0.8, 0.15 );
  267. pointLight.color.setHSV( hue, 0.8, 0.95 );
  268. };
  269. };
  270. var onParticleDead = function( particle ) {
  271. var target = particle.target;
  272. if ( target ) {
  273. // Hide the particle
  274. values_color[ target ].setHSV( 0, 0, 0 );
  275. particles.vertices[ target ].position.set( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY );
  276. // Mark particle system as available by returning to pool
  277. Pool.add( particle.target );
  278. }
  279. };
  280. var engineLoopUpdate = function() {
  281. };
  282. sparksEmitter = new SPARKS.Emitter( new SPARKS.SteadyCounter( 500 ) );
  283. emitterpos = new THREE.Vector3( 0, 0, 0 );
  284. sparksEmitter.addInitializer( new SPARKS.Position( new SPARKS.PointZone( emitterpos ) ) );
  285. sparksEmitter.addInitializer( new SPARKS.Lifetime( 1, 15 ));
  286. sparksEmitter.addInitializer( new SPARKS.Target( null, setTargetParticle ) );
  287. sparksEmitter.addInitializer( new SPARKS.Velocity( new SPARKS.PointZone( new THREE.Vector3( 0, -5, 1 ) ) ) );
  288. // TOTRY Set velocity to move away from centroid
  289. sparksEmitter.addAction( new SPARKS.Age() );
  290. sparksEmitter.addAction( new SPARKS.Accelerate( 0, 0, -50 ) );
  291. sparksEmitter.addAction( new SPARKS.Move() );
  292. sparksEmitter.addAction( new SPARKS.RandomDrift( 90, 100, 2000 ) );
  293. sparksEmitter.addCallback( "created", onParticleCreated );
  294. sparksEmitter.addCallback( "dead", onParticleDead );
  295. sparksEmitter.start();
  296. //sparksEmitter.addCallback("loopUpdated", engineLoopUpdate);
  297. //sparksEmitter.addCallback("updated", function(p) {
  298. // var target = particle.target;
  299. // if (target) {
  300. // // update energy properties
  301. // //values_size[target] = Math.random()*100;
  302. // }
  303. //});
  304. //
  305. // End Particles
  306. renderer = new THREE.WebGLRenderer();
  307. renderer.setSize( window.innerWidth, window.innerHeight );
  308. renderer.setClearColorHex( 0x000000, 1 );
  309. container.appendChild( renderer.domElement );
  310. stats = new Stats();
  311. stats.domElement.style.position = 'absolute';
  312. stats.domElement.style.top = '0px';
  313. container.appendChild( stats.domElement );
  314. // POST PROCESSING
  315. var effectFocus = new THREE.ShaderPass( THREE.ShaderExtras[ "focus" ] );
  316. var effectScreen = new THREE.ShaderPass( THREE.ShaderExtras[ "screen" ] );
  317. effectFilm = new THREE.FilmPass( 0.5, 0.25, 2048, false );
  318. var shaderBlur = THREE.ShaderExtras[ "triangleBlur" ];
  319. var effectBlurX = new THREE.ShaderPass( shaderBlur, 'texture' );
  320. var effectBlurY = new THREE.ShaderPass( shaderBlur, 'texture' );
  321. var radius = 15;
  322. var blurAmountX = radius / window.innerWidth;
  323. var blurAmountY = radius / window.innerHeight;
  324. var hblur = new THREE.ShaderPass( THREE.ShaderExtras[ "horizontalBlur" ] );
  325. var vblur = new THREE.ShaderPass( THREE.ShaderExtras[ "verticalBlur" ] );
  326. hblur.uniforms[ 'h' ].value = 1 / window.innerWidth;
  327. vblur.uniforms[ 'v' ].value = 1 / window.innerHeight;
  328. effectBlurX.uniforms[ 'delta' ].value = new THREE.Vector2( blurAmountX, 0 );
  329. effectBlurY.uniforms[ 'delta' ].value = new THREE.Vector2( 0, blurAmountY );
  330. effectFocus.uniforms[ 'sampleDistance' ].value = 0.99; //0.94
  331. effectFocus.uniforms[ 'waveFactor' ].value = 0.003; //0.00125
  332. var renderScene = new THREE.RenderPass( scene, camera );
  333. composer = new THREE.EffectComposer( renderer );
  334. composer.addPass( renderScene );
  335. composer.addPass( hblur );
  336. composer.addPass( vblur );
  337. //composer.addPass( effectBlurX );
  338. //composer.addPass( effectBlurY );
  339. //composer.addPass( effectScreen );
  340. //composer.addPass( effectFocus );
  341. //composer.addPass( effectFilm );
  342. vblur.renderToScreen = true;
  343. effectBlurY.renderToScreen = true;
  344. effectFocus.renderToScreen = true;
  345. effectScreen.renderToScreen = true;
  346. effectFilm.renderToScreen = true;
  347. document.addEventListener( 'mousedown', onDocumentMouseDown, false );
  348. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  349. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  350. }
  351. //
  352. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  353. function onDocumentMouseDown( event ) {
  354. event.preventDefault();
  355. mouseXOnMouseDown = event.clientX - windowHalfX;
  356. targetRotationOnMouseDown = targetRotation;
  357. if ( sparksEmitter.isRunning() ) {
  358. sparksEmitter.stop();
  359. } else {
  360. sparksEmitter.start();
  361. }
  362. }
  363. function onDocumentMouseMove( event ) {
  364. mouseX = event.clientX - windowHalfX;
  365. targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02;
  366. }
  367. function onDocumentTouchStart( event ) {
  368. if ( event.touches.length == 1 ) {
  369. event.preventDefault();
  370. mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
  371. targetRotationOnMouseDown = targetRotation;
  372. }
  373. }
  374. function onDocumentTouchMove( event ) {
  375. if ( event.touches.length == 1 ) {
  376. event.preventDefault();
  377. mouseX = event.touches[ 0 ].pageX - windowHalfX;
  378. targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
  379. }
  380. }
  381. //
  382. function animate() {
  383. requestAnimationFrame( animate );
  384. render();
  385. stats.update();
  386. }
  387. function render() {
  388. delta = speed * clock.getDelta();
  389. particleCloud.geometry.__dirtyVertices = true;
  390. attributes.size.needsUpdate = true;
  391. attributes.pcolor.needsUpdate = true;
  392. // Pretty cool effect if you enable this
  393. //particleCloud.rotation.y += 0.05;
  394. parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05;
  395. renderer.clear();
  396. //renderer.render( scene, camera );
  397. composer.render( 0.1 );
  398. }
  399. </script>
  400. </body>
  401. </html>