babylon.particleSystem.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var randomNumber = function (min, max) {
  4. if (min === max) {
  5. return (min);
  6. }
  7. var random = Math.random();
  8. return ((random * (max - min)) + min);
  9. };
  10. var ParticleSystem = (function () {
  11. function ParticleSystem(name, capacity, scene, customEffect) {
  12. var _this = this;
  13. this.name = name;
  14. // Members
  15. this.animations = [];
  16. this.renderingGroupId = 0;
  17. this.emitter = null;
  18. this.emitRate = 10;
  19. this.manualEmitCount = -1;
  20. this.updateSpeed = 0.01;
  21. this.targetStopDuration = 0;
  22. this.disposeOnStop = false;
  23. this.minEmitPower = 1;
  24. this.maxEmitPower = 1;
  25. this.minLifeTime = 1;
  26. this.maxLifeTime = 1;
  27. this.minSize = 1;
  28. this.maxSize = 1;
  29. this.minAngularSpeed = 0;
  30. this.maxAngularSpeed = 0;
  31. this.layerMask = 0x0FFFFFFF;
  32. /**
  33. * An event triggered when the system is disposed.
  34. * @type {BABYLON.Observable}
  35. */
  36. this.onDisposeObservable = new BABYLON.Observable();
  37. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  38. this.forceDepthWrite = false;
  39. this.gravity = BABYLON.Vector3.Zero();
  40. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  41. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  42. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48. this.particles = new Array();
  49. this._stockParticles = new Array();
  50. this._newPartsExcess = 0;
  51. this._vertexBuffers = {};
  52. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  53. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54. this._scaledDirection = BABYLON.Vector3.Zero();
  55. this._scaledGravity = BABYLON.Vector3.Zero();
  56. this._currentRenderId = -1;
  57. this._started = false;
  58. this._stopped = false;
  59. this._actualFrame = 0;
  60. this.id = name;
  61. this._capacity = capacity;
  62. this._scene = scene;
  63. this._customEffect = customEffect;
  64. scene.particleSystems.push(this);
  65. var indices = [];
  66. var index = 0;
  67. for (var count = 0; count < capacity; count++) {
  68. indices.push(index);
  69. indices.push(index + 1);
  70. indices.push(index + 2);
  71. indices.push(index);
  72. indices.push(index + 2);
  73. indices.push(index + 3);
  74. index += 4;
  75. }
  76. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  77. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  78. this._vertexData = new Float32Array(capacity * 11 * 4);
  79. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  80. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  81. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  82. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  83. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  84. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  85. this._vertexBuffers["options"] = options;
  86. // Default behaviors
  87. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  88. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  89. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  90. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  91. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  92. };
  93. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  94. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  95. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  96. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  97. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  98. };
  99. this.updateFunction = function (particles) {
  100. for (var index = 0; index < particles.length; index++) {
  101. var particle = particles[index];
  102. particle.age += _this._scaledUpdateSpeed;
  103. if (particle.age >= particle.lifeTime) {
  104. _this.recycleParticle(particle);
  105. index--;
  106. continue;
  107. }
  108. else {
  109. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  110. particle.color.addInPlace(_this._scaledColorStep);
  111. if (particle.color.a < 0)
  112. particle.color.a = 0;
  113. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  114. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  115. particle.position.addInPlace(_this._scaledDirection);
  116. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  117. particle.direction.addInPlace(_this._scaledGravity);
  118. }
  119. }
  120. };
  121. }
  122. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  123. set: function (callback) {
  124. if (this._onDisposeObserver) {
  125. this.onDisposeObservable.remove(this._onDisposeObserver);
  126. }
  127. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  128. },
  129. enumerable: true,
  130. configurable: true
  131. });
  132. ParticleSystem.prototype.recycleParticle = function (particle) {
  133. var lastParticle = this.particles.pop();
  134. if (lastParticle !== particle) {
  135. lastParticle.copyTo(particle);
  136. this._stockParticles.push(lastParticle);
  137. }
  138. };
  139. ParticleSystem.prototype.getCapacity = function () {
  140. return this._capacity;
  141. };
  142. ParticleSystem.prototype.isAlive = function () {
  143. return this._alive;
  144. };
  145. ParticleSystem.prototype.isStarted = function () {
  146. return this._started;
  147. };
  148. ParticleSystem.prototype.start = function () {
  149. this._started = true;
  150. this._stopped = false;
  151. this._actualFrame = 0;
  152. };
  153. ParticleSystem.prototype.stop = function () {
  154. this._stopped = true;
  155. };
  156. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  157. var offset = index * 11;
  158. this._vertexData[offset] = particle.position.x;
  159. this._vertexData[offset + 1] = particle.position.y;
  160. this._vertexData[offset + 2] = particle.position.z;
  161. this._vertexData[offset + 3] = particle.color.r;
  162. this._vertexData[offset + 4] = particle.color.g;
  163. this._vertexData[offset + 5] = particle.color.b;
  164. this._vertexData[offset + 6] = particle.color.a;
  165. this._vertexData[offset + 7] = particle.angle;
  166. this._vertexData[offset + 8] = particle.size;
  167. this._vertexData[offset + 9] = offsetX;
  168. this._vertexData[offset + 10] = offsetY;
  169. };
  170. ParticleSystem.prototype._update = function (newParticles) {
  171. // Update current
  172. this._alive = this.particles.length > 0;
  173. this.updateFunction(this.particles);
  174. // Add new ones
  175. var worldMatrix;
  176. if (this.emitter.position) {
  177. worldMatrix = this.emitter.getWorldMatrix();
  178. }
  179. else {
  180. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  181. }
  182. var particle;
  183. for (var index = 0; index < newParticles; index++) {
  184. if (this.particles.length === this._capacity) {
  185. break;
  186. }
  187. if (this._stockParticles.length !== 0) {
  188. particle = this._stockParticles.pop();
  189. particle.age = 0;
  190. }
  191. else {
  192. particle = new BABYLON.Particle();
  193. }
  194. this.particles.push(particle);
  195. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  196. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  197. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  198. particle.size = randomNumber(this.minSize, this.maxSize);
  199. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  200. this.startPositionFunction(worldMatrix, particle.position, particle);
  201. var step = randomNumber(0, 1.0);
  202. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  203. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  204. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  205. }
  206. };
  207. ParticleSystem.prototype._getEffect = function () {
  208. if (this._customEffect) {
  209. return this._customEffect;
  210. }
  211. ;
  212. var defines = [];
  213. if (this._scene.clipPlane) {
  214. defines.push("#define CLIPPLANE");
  215. }
  216. // Effect
  217. var join = defines.join("\n");
  218. if (this._cachedDefines !== join) {
  219. this._cachedDefines = join;
  220. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  221. }
  222. return this._effect;
  223. };
  224. ParticleSystem.prototype.animate = function () {
  225. if (!this._started)
  226. return;
  227. var effect = this._getEffect();
  228. // Check
  229. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  230. return;
  231. if (this._currentRenderId === this._scene.getRenderId()) {
  232. return;
  233. }
  234. this._currentRenderId = this._scene.getRenderId();
  235. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  236. // determine the number of particles we need to create
  237. var newParticles;
  238. if (this.manualEmitCount > -1) {
  239. newParticles = this.manualEmitCount;
  240. this._newPartsExcess = 0;
  241. this.manualEmitCount = 0;
  242. }
  243. else {
  244. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  245. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  246. }
  247. if (this._newPartsExcess > 1.0) {
  248. newParticles += this._newPartsExcess >> 0;
  249. this._newPartsExcess -= this._newPartsExcess >> 0;
  250. }
  251. this._alive = false;
  252. if (!this._stopped) {
  253. this._actualFrame += this._scaledUpdateSpeed;
  254. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  255. this.stop();
  256. }
  257. else {
  258. newParticles = 0;
  259. }
  260. this._update(newParticles);
  261. // Stopped?
  262. if (this._stopped) {
  263. if (!this._alive) {
  264. this._started = false;
  265. if (this.disposeOnStop) {
  266. this._scene._toBeDisposed.push(this);
  267. }
  268. }
  269. }
  270. // Update VBO
  271. var offset = 0;
  272. for (var index = 0; index < this.particles.length; index++) {
  273. var particle = this.particles[index];
  274. this._appendParticleVertex(offset++, particle, 0, 0);
  275. this._appendParticleVertex(offset++, particle, 1, 0);
  276. this._appendParticleVertex(offset++, particle, 1, 1);
  277. this._appendParticleVertex(offset++, particle, 0, 1);
  278. }
  279. this._vertexBuffer.update(this._vertexData);
  280. };
  281. ParticleSystem.prototype.render = function () {
  282. var effect = this._getEffect();
  283. // Check
  284. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  285. return 0;
  286. var engine = this._scene.getEngine();
  287. // Render
  288. engine.enableEffect(effect);
  289. engine.setState(false);
  290. var viewMatrix = this._scene.getViewMatrix();
  291. effect.setTexture("diffuseSampler", this.particleTexture);
  292. effect.setMatrix("view", viewMatrix);
  293. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  294. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  295. if (this._scene.clipPlane) {
  296. var clipPlane = this._scene.clipPlane;
  297. var invView = viewMatrix.clone();
  298. invView.invert();
  299. effect.setMatrix("invView", invView);
  300. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  301. }
  302. // VBOs
  303. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  304. // Draw order
  305. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  306. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  307. }
  308. else {
  309. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  310. }
  311. if (this.forceDepthWrite) {
  312. engine.setDepthWrite(true);
  313. }
  314. engine.draw(true, 0, this.particles.length * 6);
  315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  316. return this.particles.length;
  317. };
  318. ParticleSystem.prototype.dispose = function () {
  319. if (this._vertexBuffer) {
  320. this._vertexBuffer.dispose();
  321. this._vertexBuffer = null;
  322. }
  323. if (this._indexBuffer) {
  324. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  325. this._indexBuffer = null;
  326. }
  327. if (this.particleTexture) {
  328. this.particleTexture.dispose();
  329. this.particleTexture = null;
  330. }
  331. // Remove from scene
  332. var index = this._scene.particleSystems.indexOf(this);
  333. this._scene.particleSystems.splice(index, 1);
  334. // Callback
  335. this.onDisposeObservable.notifyObservers(this);
  336. this.onDisposeObservable.clear();
  337. };
  338. // Clone
  339. ParticleSystem.prototype.clone = function (name, newEmitter) {
  340. var result = new ParticleSystem(name, this._capacity, this._scene);
  341. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  342. if (newEmitter === undefined) {
  343. newEmitter = this.emitter;
  344. }
  345. result.emitter = newEmitter;
  346. if (this.particleTexture) {
  347. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  348. }
  349. result.start();
  350. return result;
  351. };
  352. ParticleSystem.prototype.serialize = function () {
  353. var serializationObject = {};
  354. serializationObject.name = this.name;
  355. serializationObject.id = this.id;
  356. // Emitter
  357. if (this.emitter.position) {
  358. serializationObject.emitterId = this.emitter.id;
  359. }
  360. else {
  361. serializationObject.emitter = this.emitter.asArray();
  362. }
  363. serializationObject.capacity = this.getCapacity();
  364. if (this.particleTexture) {
  365. serializationObject.textureName = this.particleTexture.name;
  366. }
  367. // Animations
  368. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  369. // Particle system
  370. serializationObject.minAngularSpeed = this.minAngularSpeed;
  371. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  372. serializationObject.minSize = this.minSize;
  373. serializationObject.maxSize = this.maxSize;
  374. serializationObject.minEmitPower = this.minEmitPower;
  375. serializationObject.maxEmitPower = this.maxEmitPower;
  376. serializationObject.minLifeTime = this.minLifeTime;
  377. serializationObject.maxLifeTime = this.maxLifeTime;
  378. serializationObject.emitRate = this.emitRate;
  379. serializationObject.minEmitBox = this.minEmitBox.asArray();
  380. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  381. serializationObject.gravity = this.gravity.asArray();
  382. serializationObject.direction1 = this.direction1.asArray();
  383. serializationObject.direction2 = this.direction2.asArray();
  384. serializationObject.color1 = this.color1.asArray();
  385. serializationObject.color2 = this.color2.asArray();
  386. serializationObject.colorDead = this.colorDead.asArray();
  387. serializationObject.updateSpeed = this.updateSpeed;
  388. serializationObject.targetStopDuration = this.targetStopDuration;
  389. serializationObject.textureMask = this.textureMask.asArray();
  390. serializationObject.blendMode = this.blendMode;
  391. return serializationObject;
  392. };
  393. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  394. var name = parsedParticleSystem.name;
  395. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  396. if (parsedParticleSystem.id) {
  397. particleSystem.id = parsedParticleSystem.id;
  398. }
  399. // Texture
  400. if (parsedParticleSystem.textureName) {
  401. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  402. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  403. }
  404. // Emitter
  405. if (parsedParticleSystem.emitterId) {
  406. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  407. }
  408. else {
  409. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  410. }
  411. // Animations
  412. if (parsedParticleSystem.animations) {
  413. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  414. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  415. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  416. }
  417. }
  418. if (parsedParticleSystem.autoAnimate) {
  419. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  420. }
  421. // Particle system
  422. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  423. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  424. particleSystem.minSize = parsedParticleSystem.minSize;
  425. particleSystem.maxSize = parsedParticleSystem.maxSize;
  426. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  427. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  428. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  429. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  430. particleSystem.emitRate = parsedParticleSystem.emitRate;
  431. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  432. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  433. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  434. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  435. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  436. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  437. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  438. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  439. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  440. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  441. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  442. particleSystem.blendMode = parsedParticleSystem.blendMode;
  443. if (!parsedParticleSystem.preventAutoStart) {
  444. particleSystem.start();
  445. }
  446. return particleSystem;
  447. };
  448. // Statics
  449. ParticleSystem.BLENDMODE_ONEONE = 0;
  450. ParticleSystem.BLENDMODE_STANDARD = 1;
  451. return ParticleSystem;
  452. }());
  453. BABYLON.ParticleSystem = ParticleSystem;
  454. })(BABYLON || (BABYLON = {}));