webgl_particles_shapes.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <!DOCTYPE HTML>
  2. <html lang="en">
  3. <head>
  4. <title>three.js canvas/webgl - geometry - text</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
  7. <style type="text/css">
  8. body {
  9. font-family: Monospace;
  10. background-color: #f0f0f0;
  11. margin: 0px;
  12. overflow: hidden;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <script type="text/javascript" src="../build/Three.js"></script>
  18. <script type="text/javascript" src="js/RequestAnimationFrame.js"></script>
  19. <script type="text/javascript" src="js/Stats.js"></script>
  20. <script type="text/javascript" src="js/Tween.js"></script>
  21. <script type="text/javascript" src="js/Sparks.js"></script>
  22. <script type="text/javascript" src="js/ShaderExtras.js"></script>
  23. <script type="text/javascript" src="js/postprocessing/EffectComposer.js"></script>
  24. <script type="text/javascript" src="js/postprocessing/RenderPass.js"></script>
  25. <script type="text/javascript" src="js/postprocessing/ShaderPass.js"></script>
  26. <script type="text/javascript" src="js/postprocessing/MaskPass.js"></script>
  27. <script type="text/javascript" src="js/postprocessing/BloomPass.js"></script>
  28. <!-- load the font file from canvas-text -->
  29. <script type="text/javascript" src="fonts/helvetiker_regular.typeface.js"></script>
  30. <script type="x-shader/x-vertex" id="vertexshader">
  31. attribute float size;
  32. attribute vec4 ca;
  33. varying vec4 vColor;
  34. void main() {
  35. vColor = ca;
  36. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  37. gl_PointSize = size * ( 150.0 / length( mvPosition.xyz ) );
  38. gl_Position = projectionMatrix * mvPosition;
  39. }
  40. </script>
  41. <script type="x-shader/x-fragment" id="fragmentshader">
  42. uniform vec3 color;
  43. uniform sampler2D texture;
  44. varying vec4 vColor;
  45. uniform float radius;
  46. uniform vec2 delta;
  47. varying vec2 texCoord;
  48. void main() {
  49. vec4 outColor = texture2D( texture, gl_PointCoord );
  50. if ( outColor.a < 0.5 ) discard;
  51. gl_FragColor = outColor * vec4( color * vColor.xyz, 1.0 );
  52. //float depth = gl_FragCoord.z / gl_FragCoord.w;
  53. ///const vec3 fogColor = vec3( 0.0 );
  54. //float fogFactor = smoothstep( 200.0, 600.0, depth );
  55. //gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );
  56. }
  57. </script>
  58. <script type="text/javascript">
  59. var container, stats;
  60. var camera, scene, renderer;
  61. var text, plane;
  62. var targetRotation = 0;
  63. var targetRotationOnMouseDown = 0;
  64. var mouseX = 0;
  65. var mouseXOnMouseDown = 0;
  66. var windowHalfX = window.innerWidth / 2;
  67. var windowHalfY = window.innerHeight / 2;
  68. var heartShape, particleCloud, sparksEmitter, emitterPos;
  69. var _rotation = 0;
  70. var timeOnShapePath = 0;
  71. init();
  72. animate();
  73. function init() {
  74. container = document.createElement( 'div' );
  75. document.body.appendChild( container );
  76. var info = document.createElement( 'div' );
  77. info.style.position = 'absolute';
  78. info.style.top = '10px';
  79. info.style.width = '100%';
  80. info.style.textAlign = 'center';
  81. info.innerHTML = 'Three.js with WebGL Love. Simple Particle Systems with Shapes by <a href="http://www.lab4games.net/zz85/blog">zz85</a><br/>Move your mouse. Click to pause/resume.';
  82. container.appendChild( info );
  83. camera = new THREE.Camera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
  84. camera.position.y = 150;
  85. camera.position.z = 700;
  86. camera.target.position.y = 150;
  87. scene = new THREE.Scene();
  88. // Get text from hash
  89. var theText = "THREE.JS";
  90. var hash = document.location.hash.substr( 1 );
  91. if ( hash.length !== 0 ) {
  92. theText = hash;
  93. }
  94. var text3d = new THREE.TextGeometry( theText, {
  95. size: 80,
  96. height: 20,
  97. curveSegments: 2,
  98. font: "helvetiker"
  99. });
  100. text3d.computeBoundingBox();
  101. var centerOffset = -0.5 * ( text3d.boundingBox.x[ 1 ] - text3d.boundingBox.x[ 0 ] );
  102. var textMaterial = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: false } );
  103. text = new THREE.Mesh( text3d, textMaterial );
  104. // Potentially, we can extract the vertices or faces of the text to generate particles too.
  105. // Geo > Vertices > Position
  106. text.doubleSided = false;
  107. text.position.x = centerOffset;
  108. text.position.y = 100;
  109. text.position.z = 0;
  110. text.rotation.x = 0;
  111. text.rotation.y = Math.PI * 2;
  112. text.overdraw = true;
  113. parent = new THREE.Object3D();
  114. parent.addChild( text );
  115. scene.addObject( parent );
  116. ///// Create particle objects for Three.js
  117. var particleslength = 50000;
  118. var particles = new THREE.Geometry();
  119. function newpos(x, y, z) {
  120. return new THREE.Vertex(
  121. new THREE.Vector3(x, y, z)
  122. );
  123. }
  124. var Pool = {
  125. __pools: [],
  126. // Get a new Vector
  127. get: function() {
  128. if (this.__pools.length>0) {
  129. return this.__pools.pop();
  130. }
  131. console.log("pool ran out!")
  132. return null;
  133. },
  134. // Release a vector back into the pool
  135. add: function(v) {
  136. this.__pools.push(v);
  137. },
  138. };
  139. for ( i = 0; i < particleslength; i++ ) {
  140. particles.vertices.push(newpos(Math.random() *200 - 100, Math.random() *100+150, Math.random() *50));
  141. Pool.add(i);
  142. }
  143. // Create pools of vectors
  144. attributes = {
  145. size: { type: 'f', value: [] },
  146. ca: { type: 'c', value: [] } //ca //customColor
  147. };
  148. var sprite = generateSprite() ;
  149. textu = new THREE.Texture ( sprite );
  150. textu.needsUpdate = true;
  151. uniforms = {
  152. amplitude: { type: "f", value: 1.0 },
  153. color: { type: "c", value: new THREE.Color( 0xffffff ) },
  154. texture: { type: "t", value: 0, texture:textu} //
  155. //
  156. };
  157. // PARAMS.
  158. // Steadycounter
  159. // Life
  160. // Opacity
  161. // Hue Speed
  162. // Movement Speed
  163. function generateSprite() {
  164. var canvas = document.createElement( 'canvas' );
  165. canvas.width = 128;
  166. canvas.height = 128;
  167. var context = canvas.getContext( '2d' );
  168. // Just a square, doesnt work too bad with blur pp.
  169. // context.fillStyle = "white";
  170. // context.strokeStyle = "white";
  171. // context.fillRect(0, 0, 63, 63) ;
  172. // Heart Shapes are not too pretty here
  173. // var x = 4, y = 0;
  174. // context.save();
  175. // context.scale(8, 8); // Scale so canvas render can redraw within bounds
  176. // context.beginPath();
  177. // context.bezierCurveTo( x + 2.5, y + 2.5, x + 2.0, y, x, y );
  178. // context.bezierCurveTo( x - 3.0, y, x - 3.0, y + 3.5,x - 3.0,y + 3.5 );
  179. // context.bezierCurveTo( x - 3.0, y + 5.5, x - 1.0, y + 7.7, x + 2.5, y + 9.5 );
  180. // context.bezierCurveTo( x + 6.0, y + 7.7, x + 8.0, y + 5.5, x + 8.0, y + 3.5 );
  181. // context.bezierCurveTo( x + 8.0, y + 3.5, x + 8.0, y, x + 5.0, y );
  182. // context.bezierCurveTo( x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5 );
  183. // context.closePath();
  184. context.beginPath();
  185. context.arc(64, 64, 60, 0, Math.PI*2, false);
  186. context.closePath();
  187. context.lineWidth = 0.5; //0.05
  188. context.stroke();
  189. context.restore();
  190. var gradient = context.createRadialGradient( canvas.width /2, canvas.height /2, 0, canvas.width /2, canvas.height /2, canvas.width /2 );
  191. gradient.addColorStop( 0, 'rgba(255,255,255,1)' );
  192. gradient.addColorStop( 0.2, 'rgba(255,255,255,1)' );
  193. //gradient.addColorStop( 0.6, 'rgba(200,200,200,1)' );
  194. gradient.addColorStop( 0.4, 'rgba(128,128,128,1)' );
  195. gradient.addColorStop( 1, 'rgba(0,0,0,1)' );
  196. context.fillStyle = gradient;
  197. context.fill();
  198. //var idata =context.getImageData(0, 0, canvas.width, canvas.height);
  199. //document.body.appendChild(canvas);
  200. return canvas;
  201. }
  202. var shaderMaterial = new THREE.MeshShaderMaterial( {
  203. uniforms: uniforms,
  204. attributes: attributes,
  205. vertexShader: document.getElementById( 'vertexshader' ).textContent,
  206. fragmentShader: document.getElementById( 'fragmentshader' ).textContent
  207. ,
  208. blending: THREE.AdditiveBlending,
  209. depthTest: false,
  210. transparent: true
  211. });
  212. particleCloud = new THREE.ParticleSystem( particles, shaderMaterial );
  213. particleCloud.dynamic = true;
  214. //particleCloud.sortParticles = true;
  215. var vertices = particleCloud.geometry.vertices;
  216. var values_size = attributes.size.value;
  217. var values_color = attributes.ca.value;
  218. for( var v = 0; v < vertices.length; v++ ) {
  219. values_size[ v ] = 50;
  220. values_color[ v ] = new THREE.Color( 0xaaff00 );
  221. values_color[ v ].setHSV( 0, 0, 0 );
  222. particles.vertices[v].position.set(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
  223. }
  224. parent.addChild( particleCloud );
  225. //scene.addObject( 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.0006;
  254. if (hue>1) hue-=1;
  255. // TODO Create a PointOnShape Action/Zone in the particle engine
  256. timeOnShapePath += 0.002;
  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. particles.vertices[target].position = p.position;
  262. values_color[target].setHSV(hue, 0.8, 0.15);
  263. };
  264. };
  265. var onParticleDead = function(particle) {
  266. var target = particle.target;
  267. if (target) {
  268. // Hide the particle
  269. values_color[target].setHSV(0, 0, 0);
  270. particles.vertices[target].position.set(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
  271. // Mark particle system as available by returning to pool
  272. Pool.add(particle.target);
  273. }
  274. };
  275. var engineLoopUpdate = function() {
  276. };
  277. sparksEmitter = new SPARKS.Emitter(new SPARKS.SteadyCounter(600));
  278. emitterpos = new THREE.Vector3(0,0,0);
  279. sparksEmitter.addInitializer(new SPARKS.Position( new SPARKS.PointZone( emitterpos ) ) );
  280. sparksEmitter.addInitializer(new SPARKS.Lifetime(1,4));
  281. sparksEmitter.addInitializer(new SPARKS.Target(null, setTargetParticle));
  282. sparksEmitter.addInitializer(new SPARKS.Velocity(new SPARKS.PointZone(new THREE.Vector3(0,-50,10))));
  283. // TOTRY Set velocity to move away from centroid
  284. sparksEmitter.addAction(new SPARKS.Age());
  285. sparksEmitter.addAction(new SPARKS.Accelerate(0,0,50));
  286. sparksEmitter.addAction(new SPARKS.Move());
  287. sparksEmitter.addAction(new SPARKS.RandomDrift(50,50,2000));
  288. sparksEmitter.addCallback("created", onParticleCreated);
  289. sparksEmitter.addCallback("dead", onParticleDead);
  290. sparksEmitter.start();
  291. //sparksEmitter.addCallback("loopUpdated", engineLoopUpdate);
  292. //sparksEmitter.addCallback("updated", function(p) {
  293. // var target = particle.target;
  294. // if (target) {
  295. // // update energy properties
  296. // //values_size[target] = Math.random()*100;
  297. // }
  298. //});
  299. //
  300. // End Particles
  301. renderer = new THREE.WebGLRenderer();
  302. renderer.setSize( window.innerWidth, window.innerHeight );
  303. container.appendChild( renderer.domElement );
  304. stats = new Stats();
  305. stats.domElement.style.position = 'absolute';
  306. stats.domElement.style.top = '0px';
  307. container.appendChild( stats.domElement );
  308. // POST PROCESSING
  309. var shaderFocus = THREE.ShaderExtras[ "focus" ];
  310. var effectFocus = new THREE.ShaderPass( shaderFocus );
  311. var shaderBlur = THREE.ShaderExtras[ "triangleBlur" ];
  312. var effectBlur = new THREE.ShaderPass( shaderBlur, 'texture' );; //
  313. var blurAmount = 0.0020;
  314. effectBlur.uniforms['delta'].value = new THREE.Vector2(blurAmount,blurAmount);
  315. effectFocus.uniforms['sampleDistance'].value = 0.99; //0.94
  316. effectFocus.uniforms['waveFactor'].value = 0.002; //0.00125
  317. var renderScene = new THREE.RenderPass( scene, camera );
  318. composer = new THREE.EffectComposer( renderer );
  319. composer.addPass( renderScene );
  320. composer.addPass( effectBlur ); // effectBlur effectFocus
  321. effectBlur.renderToScreen = true;
  322. effectFocus.renderToScreen = true;
  323. document.addEventListener( 'mousedown', onDocumentMouseDown, false );
  324. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  325. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  326. }
  327. //
  328. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  329. function onDocumentMouseDown( event ) {
  330. event.preventDefault();
  331. mouseXOnMouseDown = event.clientX - windowHalfX;
  332. targetRotationOnMouseDown = targetRotation;
  333. if (sparksEmitter.isRunning()) {
  334. sparksEmitter.stop();
  335. } else {
  336. sparksEmitter.start();
  337. }
  338. }
  339. function onDocumentMouseMove( event ) {
  340. mouseX = event.clientX - windowHalfX;
  341. targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02;
  342. }
  343. function onDocumentTouchStart( event ) {
  344. if ( event.touches.length == 1 ) {
  345. event.preventDefault();
  346. mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
  347. targetRotationOnMouseDown = targetRotation;
  348. }
  349. }
  350. function onDocumentTouchMove( event ) {
  351. if ( event.touches.length == 1 ) {
  352. event.preventDefault();
  353. mouseX = event.touches[ 0 ].pageX - windowHalfX;
  354. targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
  355. }
  356. }
  357. //
  358. function animate() {
  359. requestAnimationFrame( animate );
  360. render();
  361. stats.update();
  362. }
  363. function render() {
  364. particleCloud.geometry.__dirtyVertices = true;
  365. particleCloud.geometry.__dirtyColors = true;
  366. attributes.size.needsUpdate = true;
  367. attributes.ca.needsUpdate = true;
  368. // Pretty cool effect if you enable this
  369. //particleCloud.rotation.y += 0.05;
  370. parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05;
  371. //renderer.render( scene, camera );
  372. composer.render( );
  373. }
  374. </script>
  375. </body>
  376. </html>