Sparks.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. // run its built in timer / stepping
  32. start: function() {
  33. this._lastTime = Date.now();
  34. this._timer = setTimeout(this.step, this._timerStep, this);
  35. this._isRunning = true;
  36. },
  37. stop: function() {
  38. this._isRunning = false;
  39. clearTimeout(this._timer);
  40. },
  41. isRunning: function() {
  42. return this._isRunning & true;
  43. },
  44. // Step gets called upon by the engine
  45. // but attempts to call update() on a regular basics
  46. // This method is also described in http://gameclosure.com/2011/04/11/deterministic-delta-tee-in-js-games/
  47. step: function(emitter) {
  48. var time = Date.now();
  49. var elapsed = time - emitter._lastTime;
  50. while(elapsed >= emitter._TIMESTEP) {
  51. emitter.update(emitter._TIMESTEP / 1000);
  52. elapsed -= emitter._TIMESTEP;
  53. }
  54. emitter._lastTime = time - elapsed;
  55. if (emitter._isRunning)
  56. setTimeout(emitter.step, emitter._timerStep, emitter);
  57. },
  58. // Update particle engine in seconds, not milliseconds
  59. update: function(time) {
  60. var len = this._counter.updateEmitter( this, time );
  61. // Create particles
  62. for( i = 0; i < len; i++ ) {
  63. this.createParticle();
  64. }
  65. // Update activities
  66. len = this._activities.length;
  67. for ( i = 0; i < len; i++ )
  68. {
  69. this_.activities[i].update( this, time );
  70. }
  71. len = this._actions.length;
  72. var action;
  73. var len2 = this._particles.length;
  74. for( j = 0; j < len; j++ )
  75. {
  76. action = this._actions[j];
  77. for ( i = 0; i < len2; ++i )
  78. {
  79. particle = this._particles[i];
  80. action.update( this, particle, time );
  81. }
  82. }
  83. // remove dead particles
  84. for ( i = len2; i--; )
  85. {
  86. particle = this._particles[i];
  87. if ( particle.isDead )
  88. {
  89. //particle =
  90. this._particles.splice( i, 1 );
  91. this.dispatchEvent("dead", particle);
  92. SPARKS.VectorPool.release(particle.position); //
  93. SPARKS.VectorPool.release(particle.velocity);
  94. } else {
  95. this.dispatchEvent("updated", particle);
  96. }
  97. }
  98. },
  99. createParticle: function() {
  100. var particle = new SPARKS.Particle();
  101. // In future, use a Particle Factory
  102. var len = this._initializers.length, i;
  103. for ( i = 0; i < len; i++ ) {
  104. this._initializers[i].initialize( this, particle );
  105. }
  106. this._particles.push( particle );
  107. this.dispatchEvent("created", particle); // ParticleCreated
  108. return particle;
  109. },
  110. addInitializer: function (initializer) {
  111. this._initializers.push(initializer);
  112. },
  113. addAction: function (action) {
  114. this._actions.push(action);
  115. },
  116. addCallback: function(name, callback) {
  117. this.callbacks[name] = callback;
  118. },
  119. dispatchEvent: function(name, args) {
  120. var callback = this.callbacks[name];
  121. if (callback) {
  122. callback(args);
  123. }
  124. }
  125. };
  126. // Number of particles per seconds
  127. SPARKS.SteadyCounter = function(rate) {
  128. this.rate = rate;
  129. };
  130. SPARKS.SteadyCounter.prototype.updateEmitter = function(emitter, time) {
  131. return Math.floor(time * this.rate);
  132. };
  133. /********************************
  134. * Particle Class
  135. *
  136. * Represents a single particle
  137. *********************************/
  138. SPARKS.Particle = function() {
  139. /**
  140. * The lifetime of the particle, in seconds.
  141. */
  142. this.lifetime = 0;
  143. /**
  144. * The age of the particle, in seconds.
  145. */
  146. this.age = 0;
  147. /**
  148. * The energy of the particle.
  149. */
  150. this.energy = 1;
  151. /**
  152. * Whether the particle is dead and should be removed from the stage.
  153. */
  154. this.isDead = false;
  155. this.target = null; // tag
  156. /**
  157. * For 3D
  158. */
  159. this.position = SPARKS.VectorPool.get().set(0,0,0); //new THREE.Vector3( 0, 0, 0 );
  160. this.velocity = SPARKS.VectorPool.get().set(0,0,0); //new THREE.Vector3( 0, 0, 0 );
  161. // rotation vec3
  162. // angVelocity vec3
  163. // faceAxis vec3
  164. };
  165. /********************************
  166. * Action Classes
  167. *
  168. * An abstract class which have
  169. * update function
  170. *********************************/
  171. SPARKS.Action = function() {
  172. this._priority = 0;
  173. };
  174. SPARKS.Age = function(easing) {
  175. this._easing = (easing == null) ? TWEEN.Easing.Linear.EaseNone : easing;
  176. };
  177. SPARKS.Age.prototype.update = function (emitter, particle, time) {
  178. particle.age += time;
  179. if( particle.age >= particle.lifetime )
  180. {
  181. particle.energy = 0;
  182. particle.isDead = true;
  183. }
  184. else
  185. {
  186. var t = this._easing(particle.age / particle.lifetime);
  187. particle.energy = -1 * t + 1;
  188. }
  189. };
  190. /*
  191. // Mark particle as dead when particle's < 0
  192. SPARKS.Death = function(easing) {
  193. this._easing = (easing == null) ? TWEEN.Linear.EaseNone : easing;
  194. };
  195. SPARKS.Death.prototype.update = function (emitter, particle, time) {
  196. if (particle.life <= 0) {
  197. particle.isDead = true;
  198. }
  199. };
  200. */
  201. SPARKS.Move = function() {
  202. };
  203. SPARKS.Move.prototype.update = function(emitter, particle, time) {
  204. var p = particle.position;
  205. var v = particle.velocity;
  206. p.x += v.x * time;
  207. p.y += v.y * time;
  208. p.z += v.z * time;
  209. };
  210. SPARKS.Accelerate = function(x,y,z) {
  211. if (x instanceof THREE.Vector3) {
  212. this.acceleration = x;
  213. return;
  214. }
  215. this.acceleration = new THREE.Vector3(x,y,z);
  216. };
  217. SPARKS.Accelerate.prototype.update = function(emitter, particle, time) {
  218. var acc = this.acceleration;
  219. var v = particle.velocity;
  220. v.x += acc.x * time;
  221. v.y += acc.y * time;
  222. v.z += acc.z * time;
  223. };
  224. /* Set the max ammount of x,y,z drift movements in a second */
  225. SPARKS.RandomDrift = function(x,y,z) {
  226. if (x instanceof THREE.Vector3) {
  227. this.drift = x;
  228. return;
  229. }
  230. this.drift = new THREE.Vector3(x,y,z);
  231. }
  232. SPARKS.RandomDrift.prototype.update = function(emitter, particle, time) {
  233. var drift = this.drift;
  234. var v = particle.velocity;
  235. v.x += ( Math.random() - 0.5 ) * drift.x * time;
  236. v.y += ( Math.random() - 0.5 ) * drift.y * time;
  237. v.z += ( Math.random() - 0.5 ) * drift.z * time;
  238. };
  239. /********************************
  240. * Zone Classes
  241. *
  242. * An abstract classes which have
  243. * getLocation() function
  244. *********************************/
  245. SPARKS.Zone = function() {
  246. };
  247. // TODO, contains() for Zone
  248. SPARKS.PointZone = function(pos) {
  249. this.pos = pos;
  250. };
  251. SPARKS.PointZone.prototype.getLocation = function() {
  252. return this.pos;
  253. };
  254. SPARKS.PointZone = function(pos) {
  255. this.pos = pos;
  256. };
  257. SPARKS.PointZone.prototype.getLocation = function() {
  258. return this.pos;
  259. };
  260. SPARKS.LineZone = function(start, end) {
  261. this.start = start;
  262. this.end = end;
  263. this._length = end.clone().subSelf( start );
  264. };
  265. SPARKS.LineZone.prototype.getLocation = function() {
  266. var len = this._length.clone();
  267. len.multiplyScalar( Math.random() );
  268. return len.addSelf( this.start );
  269. };
  270. // Basically a RectangleZone
  271. SPARKS.ParallelogramZone = function(corner, side1, side2) {
  272. this.corner = corner;
  273. this.side1 = side1;
  274. this.side2 = side2;
  275. };
  276. SPARKS.ParallelogramZone.prototype.getLocation = function() {
  277. var d1 = this.side1.clone().multiplyScalar( Math.random() );
  278. var d2 = this.side2.clone().multiplyScalar( Math.random() );
  279. d1.addSelf(d2);
  280. return d1.addSelf( this.corner );
  281. };
  282. /**
  283. * The constructor creates a DiscZone 3D zone.
  284. *
  285. * @param centre The point at the center of the disc.
  286. * @param normal A vector normal to the disc.
  287. * @param outerRadius The outer radius of the disc.
  288. * @param innerRadius The inner radius of the disc. This defines the hole
  289. * in the center of the disc. If set to zero, there is no hole.
  290. */
  291. /*
  292. // BUGGY!!
  293. SPARKS.DiscZone = function(center, radiusNormal, outerRadius, innerRadius) {
  294. this.center = center;
  295. this.radiusNormal = radiusNormal;
  296. this.outerRadius = (outerRadius==undefined) ? 0 : outerRadius;
  297. this.innerRadius = (innerRadius==undefined) ? 0 : innerRadius;
  298. };
  299. SPARKS.DiscZone.prototype.getLocation = function() {
  300. var rand = Math.random();
  301. var _innerRadius = this.innerRadius;
  302. var _outerRadius = this.outerRadius;
  303. var center = this.center;
  304. var _normal = this.radiusNormal;
  305. _distToOrigin = _normal.dot( center );
  306. var radius = _innerRadius + (1 - rand * rand ) * ( _outerRadius - _innerRadius );
  307. var angle = Math.random() * SPARKS.Utils.TWOPI;
  308. var _distToOrigin = _normal.dot( center );
  309. var axes = SPARKS.Utils.getPerpendiculars( _normal.clone() );
  310. var _planeAxis1 = axes[0];
  311. var _planeAxis2 = axes[1];
  312. var p = _planeAxis1.clone();
  313. p.multiplyScalar( radius * Math.cos( angle ) );
  314. var p2 = _planeAxis2.clone();
  315. p2.multiplyScalar( radius * Math.sin( angle ) );
  316. p.addSelf( p2 );
  317. return _center.add( p );
  318. };
  319. */
  320. SPARKS.SphereCapZone = function(x, y, z, minr, maxr, angle) {
  321. this.x = x;
  322. this.y = y;
  323. this.z = z;
  324. this.minr = minr;
  325. this.maxr = maxr;
  326. this.angle = angle;
  327. };
  328. SPARKS.SphereCapZone.prototype.getLocation = function() {
  329. var theta = Math.PI *2 * SPARKS.Utils.random();
  330. var r = SPARKS.Utils.random();
  331. //new THREE.Vector3
  332. var v = SPARKS.VectorPool.get().set(r * Math.cos(theta), -1 / Math.tan(this.angle * SPARKS.Utils.DEGREE_TO_RADIAN), r * Math.sin(theta));
  333. //v.length = StardustMath.interpolate(0, _minRadius, 1, _maxRadius, Math.random());
  334. var i = this.minr - ((this.minr-this.maxr) * Math.random() );
  335. v.multiplyScalar(i);
  336. v.__markedForReleased = true;
  337. return v;
  338. };
  339. /********************************
  340. * Initializer Classes
  341. *
  342. * Classes which initializes
  343. * particles. Implements initialize( emitter:Emitter, particle:Particle )
  344. *********************************/
  345. // Specifies random life between max and min
  346. SPARKS.Lifetime = function(min, max) {
  347. this._min = min;
  348. this._max = max ? max : min;
  349. };
  350. SPARKS.Lifetime.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) {
  351. particle.lifetime = this._min + SPARKS.Utils.random() * ( this._max - this._min );
  352. };
  353. SPARKS.Position = function(zone) {
  354. this.zone = zone;
  355. };
  356. SPARKS.Position.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) {
  357. var pos = this.zone.getLocation();
  358. particle.position.set(pos.x, pos.y, pos.z);
  359. };
  360. SPARKS.Velocity = function(zone) {
  361. this.zone = zone;
  362. };
  363. SPARKS.Velocity.prototype.initialize = function( emitter/*Emitter*/, particle/*Particle*/ ) {
  364. var pos = this.zone.getLocation();
  365. particle.velocity.set(pos.x, pos.y, pos.z);
  366. if (pos.__markedForReleased) {
  367. //console.log("release");
  368. SPARKS.VectorPool.release(pos);
  369. pos.__markedForReleased = false;
  370. }
  371. };
  372. SPARKS.Target = function(target, callback) {
  373. this.target = target;
  374. this.callback = callback;
  375. };
  376. SPARKS.Target.prototype.initialize = function( emitter, particle) {
  377. if (this.callback) {
  378. particle.target = this.callback();
  379. } else {
  380. particle.target = this.target;
  381. }
  382. };
  383. /********************************
  384. * VectorPool
  385. *
  386. * Reuse much of Vectors if possible
  387. *********************************/
  388. SPARKS.VectorPool = {
  389. __pools: [],
  390. // Get a new Vector
  391. get: function() {
  392. if (this.__pools.length>0) {
  393. return this.__pools.pop();
  394. }
  395. return this._addToPool();
  396. },
  397. // Release a vector back into the pool
  398. release: function(v) {
  399. this.__pools.push(v);
  400. },
  401. // Create a bunch of vectors and add to the pool
  402. _addToPool: function() {
  403. //console.log("creating some pools");
  404. for (var i=0, size = 100; i < size; i++) {
  405. this.__pools.push(new THREE.Vector3());
  406. }
  407. return new THREE.Vector3();
  408. }
  409. };
  410. /********************************
  411. * Util Classes
  412. *
  413. * Classes which initializes
  414. * particles. Implements initialize( emitter:Emitter, particle:Particle )
  415. *********************************/
  416. SPARKS.Utils = {
  417. random: function() {
  418. return Math.random();
  419. },
  420. DEGREE_TO_RADIAN: Math.PI / 180,
  421. TWOPI: Math.PI * 2,
  422. getPerpendiculars: function(normal) {
  423. var p1 = this.getPerpendicular( normal );
  424. var p2 = normal.cross( p1 );
  425. p2.normalize();
  426. return [ p1, p2 ];
  427. },
  428. getPerpendicular: function( v )
  429. {
  430. if( v.x == 0 )
  431. {
  432. return new THREE.Vector3D( 1, 0, 0 );
  433. }
  434. else
  435. {
  436. var temp = new THREE.Vector3( v.y, -v.x, 0 );
  437. return temp.normalize();
  438. }
  439. }
  440. };