Sparks.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /*
  2. * @author zz85 (http://github.com/zz85 http://www.lab4games.net/zz85/blog)
  3. *
  4. * a simple to use javascript 3d particles system inspired by FliNT and Stardust
  5. * created with TWEEN.js and THREE.js
  6. *
  7. * for feature requests or bugs, please visit https://github.com/zz85/sparks.js
  8. *
  9. * licensed under the MIT license
  10. */
  11. var SPARKS = {};
  12. /********************************
  13. * Emitter Class
  14. *
  15. * Creates and Manages Particles
  16. *********************************/
  17. SPARKS.Emitter = function (counter) {
  18. this._counter = counter ? counter : new SPARKS.SteadyCounter(10); // provides number of particles to produce
  19. this._particles = [];
  20. this._initializers = []; // use for creation of particles
  21. this._actions = []; // uses action to update particles
  22. this._activities = []; // not supported yet
  23. this._handlers = [];
  24. this.callbacks = {};
  25. };
  26. SPARKS.Emitter.prototype = {
  27. _TIMESTEP: 15,
  28. _timer: null,
  29. _lastTime: null,
  30. _timerStep: 10,
  31. _velocityVerlet: true,
  32. // run its built in timer / stepping
  33. start: function() {
  34. this._lastTime = Date.now();
  35. this._timer = setTimeout(this.step, this._timerStep, this);
  36. this._isRunning = true;
  37. },
  38. stop: function() {
  39. this._isRunning = false;
  40. clearTimeout(this._timer);
  41. },
  42. isRunning: function() {
  43. return this._isRunning & true;
  44. },
  45. // Step gets called upon by the engine
  46. // but attempts to call update() on a regular basics
  47. // This method is also described in http://gameclosure.com/2011/04/11/deterministic-delta-tee-in-js-games/
  48. step: function(emitter) {
  49. var time = Date.now();
  50. var elapsed = time - emitter._lastTime;
  51. if (!this._velocityVerlet) {
  52. // if elapsed is way higher than time step, (usually after switching tabs, or excution cached in ff)
  53. // we will drop cycles. perhaps set to a limit of 10 or something?
  54. var maxBlock = emitter._TIMESTEP * 20;
  55. if (elapsed >= maxBlock) {
  56. //console.log('warning: sparks.js is fast fowarding engine, skipping steps', elapsed / emitter._TIMESTEP);
  57. //emitter.update( (elapsed - maxBlock) / 1000);
  58. elapsed = maxBlock;
  59. }
  60. while(elapsed >= emitter._TIMESTEP) {
  61. emitter.update(emitter._TIMESTEP / 1000);
  62. elapsed -= emitter._TIMESTEP;
  63. }
  64. emitter._lastTime = time - elapsed;
  65. } else {
  66. emitter.update(elapsed/1000);
  67. emitter._lastTime = time;
  68. }
  69. if (emitter._isRunning)
  70. setTimeout(emitter.step, emitter._timerStep, emitter);
  71. },
  72. // Update particle engine in seconds, not milliseconds
  73. update: function(time) {
  74. var i, j;
  75. var len = this._counter.updateEmitter( this, time );
  76. // Create particles
  77. for( i = 0; i < len; i++ ) {
  78. this.createParticle();
  79. }
  80. // Update activities
  81. len = this._activities.length;
  82. for ( i = 0; i < len; i++ )
  83. {
  84. this._activities[i].update( this, time );
  85. }
  86. len = this._actions.length;
  87. var particle;
  88. var action;
  89. var len2 = this._particles.length;
  90. for( j = 0; j < len; j++ )
  91. {
  92. action = this._actions[j];
  93. for ( i = 0; i < len2; ++i )
  94. {
  95. particle = this._particles[i];
  96. action.update( this, particle, time );
  97. }
  98. }
  99. // remove dead particles
  100. for ( i = len2; i--; )
  101. {
  102. particle = this._particles[i];
  103. if ( particle.isDead )
  104. {
  105. //particle =
  106. this._particles.splice( i, 1 );
  107. this.dispatchEvent("dead", particle);
  108. SPARKS.VectorPool.release(particle.position); //
  109. SPARKS.VectorPool.release(particle.velocity);
  110. } else {
  111. this.dispatchEvent("updated", particle);
  112. }
  113. }
  114. this.dispatchEvent("loopUpdated");
  115. },
  116. createParticle: function() {
  117. var particle = new SPARKS.Particle();
  118. // In future, use a Particle Factory
  119. var len = this._initializers.length, i;
  120. for ( i = 0; i < len; i++ ) {
  121. this._initializers[i].initialize( this, particle );
  122. }
  123. this._particles.push( particle );
  124. this.dispatchEvent("created", particle); // ParticleCreated
  125. return particle;
  126. },
  127. addInitializer: function (initializer) {
  128. this._initializers.push(initializer);
  129. },
  130. addAction: function (action) {
  131. this._actions.push(action);
  132. },
  133. removeInitializer: function (initializer) {
  134. var index = this._initializers.indexOf(initializer);
  135. if (index > -1) {
  136. this._initializers.splice( index, 1 );
  137. }
  138. },
  139. removeAction: function (action) {
  140. var index = this._actions.indexOf(action);
  141. if (index > -1) {
  142. this._actions.splice( index, 1 );
  143. }
  144. //console.log('removeAction', index, this._actions);
  145. },
  146. addCallback: function(name, callback) {
  147. this.callbacks[name] = callback;
  148. },
  149. dispatchEvent: function(name, args) {
  150. var callback = this.callbacks[name];
  151. if (callback) {
  152. callback(args);
  153. }
  154. }
  155. };
  156. /*
  157. * Constant Names for
  158. * Events called by emitter.dispatchEvent()
  159. *
  160. */
  161. SPARKS.EVENT_PARTICLE_CREATED = "created"
  162. SPARKS.EVENT_PARTICLE_UPDATED = "updated"
  163. SPARKS.EVENT_PARTICLE_DEAD = "dead";
  164. SPARKS.EVENT_LOOP_UPDATED = "loopUpdated";
  165. /*
  166. * Steady Counter attempts to produces a particle rate steadily
  167. *
  168. */
  169. // Number of particles per seconds
  170. SPARKS.SteadyCounter = function(rate) {
  171. this.rate = rate;
  172. // we use a shortfall counter to make up for slow emitters
  173. this.leftover = 0;
  174. };
  175. SPARKS.SteadyCounter.prototype.updateEmitter = function(emitter, time) {
  176. var targetRelease = time * this.rate + this.leftover;
  177. var actualRelease = Math.floor(targetRelease);
  178. this.leftover = targetRelease - actualRelease;
  179. return actualRelease;
  180. };
  181. /*
  182. * Shot Counter produces specified particles
  183. * on a single impluse or burst
  184. */
  185. SPARKS.ShotCounter = function(particles) {
  186. this.particles = particles;
  187. this.used = false;
  188. };
  189. SPARKS.ShotCounter.prototype.updateEmitter = function(emitter, time) {
  190. if (this.used) {
  191. return 0;
  192. } else {
  193. this.used = true;
  194. }
  195. return this.particles;
  196. };
  197. /********************************
  198. * Particle Class
  199. *
  200. * Represents a single particle
  201. *********************************/
  202. SPARKS.Particle = function() {
  203. /**
  204. * The lifetime of the particle, in seconds.
  205. */
  206. this.lifetime = 0;
  207. /**
  208. * The age of the particle, in seconds.
  209. */
  210. this.age = 0;
  211. /**
  212. * The energy of the particle.
  213. */
  214. this.energy = 1;
  215. /**
  216. * Whether the particle is dead and should be removed from the stage.
  217. */
  218. this.isDead = false;
  219. this.target = null; // tag
  220. /**
  221. * For 3D
  222. */
  223. this.position = SPARKS.VectorPool.get().set(0,0,0); //new THREE.Vector3( 0, 0, 0 );
  224. this.velocity = SPARKS.VectorPool.get().set(0,0,0); //new THREE.Vector3( 0, 0, 0 );
  225. this._oldvelocity = SPARKS.VectorPool.get().set(0,0,0);
  226. // rotation vec3
  227. // angVelocity vec3
  228. // faceAxis vec3
  229. };
  230. /********************************
  231. * Action Classes
  232. *
  233. * An abstract class which have
  234. * update function
  235. *********************************/
  236. SPARKS.Action = function() {
  237. this._priority = 0;
  238. };
  239. SPARKS.Age = function(easing) {
  240. this._easing = (easing == null) ? TWEEN.Easing.Linear.None : easing;
  241. };
  242. SPARKS.Age.prototype.update = function (emitter, particle, time) {
  243. particle.age += time;
  244. if( particle.age >= particle.lifetime )
  245. {
  246. particle.energy = 0;
  247. particle.isDead = true;
  248. }
  249. else
  250. {
  251. var t = this._easing(particle.age / particle.lifetime);
  252. particle.energy = -1 * t + 1;
  253. }
  254. };
  255. /*
  256. // Mark particle as dead when particle's < 0
  257. SPARKS.Death = function(easing) {
  258. this._easing = (easing == null) ? TWEEN.Linear.None : easing;
  259. };
  260. SPARKS.Death.prototype.update = function (emitter, particle, time) {
  261. if (particle.life <= 0) {
  262. particle.isDead = true;
  263. }
  264. };
  265. */
  266. SPARKS.Move = function() {
  267. };
  268. SPARKS.Move.prototype.update = function(emitter, particle, time) {
  269. // attempt verlet velocity updating.
  270. var p = particle.position;
  271. var v = particle.velocity;
  272. var old = particle._oldvelocity;
  273. if (this._velocityVerlet) {
  274. p.x += (v.x + old.x) * 0.5 * time;
  275. p.y += (v.y + old.y) * 0.5 * time;
  276. p.z += (v.z + old.z) * 0.5 * time;
  277. } else {
  278. p.x += v.x * time;
  279. p.y += v.y * time;
  280. p.z += v.z * time;
  281. }
  282. // OldVel = Vel;
  283. // Vel = Vel + Accel * dt;
  284. // Pos = Pos + (vel + Vel + Accel * dt) * 0.5 * dt;
  285. };
  286. /* Marks particles found in specified zone dead */
  287. SPARKS.DeathZone = function(zone) {
  288. this.zone = zone;
  289. };
  290. SPARKS.DeathZone.prototype.update = function(emitter, particle, time) {
  291. if (this.zone.contains(particle.position)) {
  292. particle.isDead = true;
  293. }
  294. };
  295. /*
  296. * SPARKS.ActionZone applies an action when particle is found in zone
  297. */
  298. SPARKS.ActionZone = function(action, zone) {
  299. this.action = action;
  300. this.zone = zone;
  301. };
  302. SPARKS.ActionZone.prototype.update = function(emitter, particle, time) {
  303. if (this.zone.contains(particle.position)) {
  304. this.action.update( emitter, particle, time );
  305. }
  306. };
  307. /*
  308. * Accelerate action affects velocity in specified 3d direction
  309. */
  310. SPARKS.Accelerate = function(x,y,z) {
  311. if (x instanceof THREE.Vector3) {
  312. this.acceleration = x;
  313. return;
  314. }
  315. this.acceleration = new THREE.Vector3(x,y,z);
  316. };
  317. SPARKS.Accelerate.prototype.update = function(emitter, particle, time) {
  318. var acc = this.acceleration;
  319. var v = particle.velocity;
  320. particle._oldvelocity.set(v.x, v.y, v.z);
  321. v.x += acc.x * time;
  322. v.y += acc.y * time;
  323. v.z += acc.z * time;
  324. };
  325. /*
  326. * Accelerate Factor accelerate based on a factor of particle's velocity.
  327. */
  328. SPARKS.AccelerateFactor = function(factor) {
  329. this.factor = factor;
  330. };
  331. SPARKS.AccelerateFactor.prototype.update = function(emitter, particle, time) {
  332. var factor = this.factor;
  333. var v = particle.velocity;
  334. var len = v.length();
  335. var adjFactor;
  336. if (len>0) {
  337. adjFactor = factor * time / len;
  338. adjFactor += 1;
  339. v.multiplyScalar(adjFactor);
  340. // v.x *= adjFactor;
  341. // v.y *= adjFactor;
  342. // v.z *= adjFactor;
  343. }
  344. };
  345. /*
  346. AccelerateNormal
  347. * AccelerateVelocity affects velocity based on its velocity direction
  348. */
  349. SPARKS.AccelerateVelocity = function(factor) {
  350. this.factor = factor;
  351. };
  352. SPARKS.AccelerateVelocity.prototype.update = function(emitter, particle, time) {
  353. var factor = this.factor;
  354. var v = particle.velocity;
  355. v.z += - v.x * factor;
  356. v.y += v.z * factor;
  357. v.x += v.y * factor;
  358. };
  359. /* Set the max ammount of x,y,z drift movements in a second */
  360. SPARKS.RandomDrift = function(x,y,z) {
  361. if (x instanceof THREE.Vector3) {
  362. this.drift = x;
  363. return;
  364. }
  365. this.drift = new THREE.Vector3(x,y,z);
  366. }
  367. SPARKS.RandomDrift.prototype.update = function(emitter, particle, time) {
  368. var drift = this.drift;
  369. var v = particle.velocity;
  370. v.x += ( Math.random() - 0.5 ) * drift.x * time;
  371. v.y += ( Math.random() - 0.5 ) * drift.y * time;
  372. v.z += ( Math.random() - 0.5 ) * drift.z * time;
  373. };
  374. /********************************
  375. * Zone Classes
  376. *
  377. * An abstract classes which have
  378. * getLocation() function
  379. *********************************/
  380. SPARKS.Zone = function() {
  381. };
  382. // TODO, contains() for Zone
  383. SPARKS.PointZone = function(pos) {
  384. this.pos = pos;
  385. };
  386. SPARKS.PointZone.prototype.getLocation = function() {
  387. return this.pos;
  388. };
  389. SPARKS.PointZone = function(pos) {
  390. this.pos = pos;
  391. };
  392. SPARKS.PointZone.prototype.getLocation = function() {
  393. return this.pos;
  394. };
  395. SPARKS.LineZone = function(start, end) {
  396. this.start = start;
  397. this.end = end;
  398. this._length = end.clone().sub( start );
  399. };
  400. SPARKS.LineZone.prototype.getLocation = function() {
  401. var len = this._length.clone();
  402. len.multiplyScalar( Math.random() );
  403. return len.add( this.start );
  404. };
  405. // Basically a RectangleZone
  406. SPARKS.ParallelogramZone = function(corner, side1, side2) {
  407. this.corner = corner;
  408. this.side1 = side1;
  409. this.side2 = side2;
  410. };
  411. SPARKS.ParallelogramZone.prototype.getLocation = function() {
  412. var d1 = this.side1.clone().multiplyScalar( Math.random() );
  413. var d2 = this.side2.clone().multiplyScalar( Math.random() );
  414. d1.add(d2);
  415. return d1.add( this.corner );
  416. };
  417. SPARKS.CubeZone = function(position, x, y, z) {
  418. this.position = position;
  419. this.x = x;
  420. this.y = y;
  421. this.z = z;
  422. };
  423. SPARKS.CubeZone.prototype.getLocation = function() {
  424. //TODO use pool?
  425. var location = this.position.clone();
  426. location.x += Math.random() * this.x;
  427. location.y += Math.random() * this.y;
  428. location.z += Math.random() * this.z;
  429. return location;
  430. };
  431. SPARKS.CubeZone.prototype.contains = function(position) {
  432. var startX = this.position.x;
  433. var startY = this.position.y;
  434. var startZ = this.position.z;
  435. var x = this.x; // width
  436. var y = this.y; // depth
  437. var z = this.z; // height
  438. if (x<0) {
  439. startX += x;
  440. x = Math.abs(x);
  441. }
  442. if (y<0) {
  443. startY += y;
  444. y = Math.abs(y);
  445. }
  446. if (z<0) {
  447. startZ += z;
  448. z = Math.abs(z);
  449. }
  450. var diffX = position.x - startX;
  451. var diffY = position.y - startY;
  452. var diffZ = position.z - startZ;
  453. if ( (diffX > 0) && (diffX < x) &&
  454. (diffY > 0) && (diffY < y) &&
  455. (diffZ > 0) && (diffZ < z) ) {
  456. return true;
  457. }
  458. return false;
  459. };
  460. /**
  461. * The constructor creates a DiscZone 3D zone.
  462. *
  463. * @param centre The point at the center of the disc.
  464. * @param normal A vector normal to the disc.
  465. * @param outerRadius The outer radius of the disc.
  466. * @param innerRadius The inner radius of the disc. This defines the hole
  467. * in the center of the disc. If set to zero, there is no hole.
  468. */
  469. /*
  470. // BUGGY!!
  471. SPARKS.DiscZone = function(center, radiusNormal, outerRadius, innerRadius) {
  472. this.center = center;
  473. this.radiusNormal = radiusNormal;
  474. this.outerRadius = (outerRadius==undefined) ? 0 : outerRadius;
  475. this.innerRadius = (innerRadius==undefined) ? 0 : innerRadius;
  476. };
  477. SPARKS.DiscZone.prototype.getLocation = function() {
  478. var rand = Math.random();
  479. var _innerRadius = this.innerRadius;
  480. var _outerRadius = this.outerRadius;
  481. var center = this.center;
  482. var _normal = this.radiusNormal;
  483. _distToOrigin = _normal.dot( center );
  484. var radius = _innerRadius + (1 - rand * rand ) * ( _outerRadius - _innerRadius );
  485. var angle = Math.random() * SPARKS.Utils.TWOPI;
  486. var _distToOrigin = _normal.dot( center );
  487. var axes = SPARKS.Utils.getPerpendiculars( _normal.clone() );
  488. var _planeAxis1 = axes[0];
  489. var _planeAxis2 = axes[1];
  490. var p = _planeAxis1.clone();
  491. p.multiplyScalar( radius * Math.cos( angle ) );
  492. var p2 = _planeAxis2.clone();
  493. p2.multiplyScalar( radius * Math.sin( angle ) );
  494. p.add( p2 );
  495. return _center.add( p );
  496. };
  497. */
  498. SPARKS.SphereCapZone = function(x, y, z, minr, maxr, angle) {
  499. this.x = x;
  500. this.y = y;
  501. this.z = z;
  502. this.minr = minr;
  503. this.maxr = maxr;
  504. this.angle = angle;
  505. };
  506. SPARKS.SphereCapZone.prototype.getLocation = function() {
  507. var theta = Math.PI *2 * SPARKS.Utils.random();
  508. var r = SPARKS.Utils.random();
  509. //new THREE.Vector3
  510. var v = SPARKS.VectorPool.get().set(r * Math.cos(theta), -1 / Math.tan(this.angle * SPARKS.Utils.DEGREE_TO_RADIAN), r * Math.sin(theta));
  511. //v.length = StardustMath.interpolate(0, _minRadius, 1, _maxRadius, Math.random());
  512. var i = this.minr - ((this.minr-this.maxr) * Math.random() );
  513. v.multiplyScalar(i);
  514. v.__markedForReleased = true;
  515. return v;
  516. };
  517. /********************************
  518. * Initializer Classes
  519. *
  520. * Classes which initializes
  521. * particles. Implements initialize( emitter:Emitter, particle:Particle )
  522. *********************************/
  523. // Specifies random life between max and min
  524. SPARKS.Lifetime = function(min, max) {
  525. this._min = min;
  526. this._max = max ? max : min;
  527. };
  528. SPARKS.Lifetime.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) {
  529. particle.lifetime = this._min + SPARKS.Utils.random() * ( this._max - this._min );
  530. };
  531. SPARKS.Position = function(zone) {
  532. this.zone = zone;
  533. };
  534. SPARKS.Position.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) {
  535. var pos = this.zone.getLocation();
  536. particle.position.set(pos.x, pos.y, pos.z);
  537. };
  538. SPARKS.Velocity = function(zone) {
  539. this.zone = zone;
  540. };
  541. SPARKS.Velocity.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) {
  542. var pos = this.zone.getLocation();
  543. particle.velocity.set(pos.x, pos.y, pos.z);
  544. if (pos.__markedForReleased) {
  545. //console.log("release");
  546. SPARKS.VectorPool.release(pos);
  547. pos.__markedForReleased = false;
  548. }
  549. };
  550. SPARKS.Target = function(target, callback) {
  551. this.target = target;
  552. this.callback = callback;
  553. };
  554. SPARKS.Target.prototype.initialize = function( emitter, particle ) {
  555. if (this.callback) {
  556. particle.target = this.callback();
  557. } else {
  558. particle.target = this.target;
  559. }
  560. };
  561. /********************************
  562. * VectorPool
  563. *
  564. * Reuse much of Vectors if possible
  565. *********************************/
  566. SPARKS.VectorPool = {
  567. __pools: [],
  568. // Get a new Vector
  569. get: function() {
  570. if (this.__pools.length>0) {
  571. return this.__pools.pop();
  572. }
  573. return this._addToPool();
  574. },
  575. // Release a vector back into the pool
  576. release: function(v) {
  577. this.__pools.push(v);
  578. },
  579. // Create a bunch of vectors and add to the pool
  580. _addToPool: function() {
  581. //console.log("creating some pools");
  582. for (var i=0, size = 100; i < size; i++) {
  583. this.__pools.push(new THREE.Vector3());
  584. }
  585. return new THREE.Vector3();
  586. }
  587. };
  588. /********************************
  589. * Util Classes
  590. *
  591. * Classes which initializes
  592. * particles. Implements initialize( emitter:Emitter, particle:Particle )
  593. *********************************/
  594. SPARKS.Utils = {
  595. random: function() {
  596. return Math.random();
  597. },
  598. DEGREE_TO_RADIAN: Math.PI / 180,
  599. TWOPI: Math.PI * 2,
  600. getPerpendiculars: function(normal) {
  601. var p1 = this.getPerpendicular( normal );
  602. var p2 = normal.cross( p1 );
  603. p2.normalize();
  604. return [ p1, p2 ];
  605. },
  606. getPerpendicular: function( v )
  607. {
  608. if( v.x == 0 )
  609. {
  610. return new THREE.Vector3D( 1, 0, 0 );
  611. }
  612. else
  613. {
  614. var temp = new THREE.Vector3( v.y, -v.x, 0 );
  615. return temp.normalize();
  616. }
  617. }
  618. };