Sparks.js 18 KB

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