babylon.particleSystem.js 21 KB

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