babylon.gpuParticleSystem.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. module BABYLON {
  2. /**
  3. * This represents a GPU particle system in Babylon
  4. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  5. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  6. */
  7. export class GPUParticleSystem implements IDisposable, IParticleSystem, IAnimatable {
  8. /**
  9. * The id of the Particle system.
  10. */
  11. public id: string;
  12. /**
  13. * The friendly name of the Particle system.
  14. */
  15. public name: string;
  16. /**
  17. * The emitter represents the Mesh or position we are attaching the particle system to.
  18. */
  19. public emitter: Nullable<AbstractMesh | Vector3> = null;
  20. /**
  21. * The rendering group used by the Particle system to chose when to render.
  22. */
  23. public renderingGroupId = 0;
  24. /**
  25. * The layer mask we are rendering the particles through.
  26. */
  27. public layerMask: number = 0x0FFFFFFF;
  28. private _capacity: number;
  29. private _activeCount: number;
  30. private _currentActiveCount: number;
  31. private _renderEffect: Effect;
  32. private _updateEffect: Effect;
  33. private _buffer0: Buffer;
  34. private _buffer1: Buffer;
  35. private _spriteBuffer: Buffer;
  36. private _updateVAO: Array<WebGLVertexArrayObject>;
  37. private _renderVAO: Array<WebGLVertexArrayObject>;
  38. private _targetIndex = 0;
  39. private _sourceBuffer: Buffer;
  40. private _targetBuffer: Buffer;
  41. private _scene: Scene;
  42. private _engine: Engine;
  43. private _currentRenderId = -1;
  44. private _started = false;
  45. private _stopped = false;
  46. private _timeDelta = 0;
  47. private _randomTexture: RawTexture;
  48. private readonly _attributesStrideSize = 14;
  49. private _updateEffectOptions: EffectCreationOptions;
  50. private _randomTextureSize: number;
  51. private _actualFrame = 0;
  52. /**
  53. * List of animations used by the particle system.
  54. */
  55. public animations: Animation[] = [];
  56. /**
  57. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  58. */
  59. public static get IsSupported(): boolean {
  60. if (!Engine.LastCreatedEngine) {
  61. return false;
  62. }
  63. return Engine.LastCreatedEngine.webGLVersion > 1;
  64. }
  65. /**
  66. * An event triggered when the system is disposed.
  67. */
  68. public onDisposeObservable = new Observable<GPUParticleSystem>();
  69. /**
  70. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  71. */
  72. public updateSpeed = 0.01;
  73. /**
  74. * The amount of time the particle system is running (depends of the overall update speed).
  75. */
  76. public targetStopDuration = 0;
  77. /**
  78. * The texture used to render each particle. (this can be a spritesheet)
  79. */
  80. public particleTexture: Nullable<Texture>;
  81. /**
  82. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  83. */
  84. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  85. /**
  86. * Minimum life time of emitting particles.
  87. */
  88. public minLifeTime = 1;
  89. /**
  90. * Maximum life time of emitting particles.
  91. */
  92. public maxLifeTime = 1;
  93. /**
  94. * Minimum Size of emitting particles.
  95. */
  96. public minSize = 1;
  97. /**
  98. * Maximum Size of emitting particles.
  99. */
  100. public maxSize = 1;
  101. /**
  102. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  103. */
  104. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  105. /**
  106. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  107. */
  108. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  109. /**
  110. * Color the particle will have at the end of its lifetime.
  111. */
  112. public colorDead = new Color4(0, 0, 0, 0);
  113. /**
  114. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  115. */
  116. public emitRate = 100;
  117. /**
  118. * You can use gravity if you want to give an orientation to your particles.
  119. */
  120. public gravity = Vector3.Zero();
  121. /**
  122. * Minimum power of emitting particles.
  123. */
  124. public minEmitPower = 1;
  125. /**
  126. * Maximum power of emitting particles.
  127. */
  128. public maxEmitPower = 1;
  129. /**
  130. * The particle emitter type defines the emitter used by the particle system.
  131. * It can be for example box, sphere, or cone...
  132. */
  133. public particleEmitterType: Nullable<IParticleEmitterType>;
  134. /**
  135. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  136. * This only works when particleEmitterTyps is a BoxParticleEmitter
  137. */
  138. public get direction1(): Vector3 {
  139. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  140. return (<BoxParticleEmitter>this.particleEmitterType).direction1;
  141. }
  142. return Vector3.Zero();
  143. }
  144. public set direction1(value: Vector3) {
  145. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  146. (<BoxParticleEmitter>this.particleEmitterType).direction1 = value;
  147. }
  148. }
  149. /**
  150. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  151. * This only works when particleEmitterTyps is a BoxParticleEmitter
  152. */
  153. public get direction2(): Vector3 {
  154. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  155. return (<BoxParticleEmitter>this.particleEmitterType).direction2;
  156. }
  157. return Vector3.Zero();
  158. }
  159. public set direction2(value: Vector3) {
  160. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  161. (<BoxParticleEmitter>this.particleEmitterType).direction2 = value;
  162. }
  163. }
  164. /**
  165. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  166. * This only works when particleEmitterTyps is a BoxParticleEmitter
  167. */
  168. public get minEmitBox(): Vector3 {
  169. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  170. return (<BoxParticleEmitter>this.particleEmitterType).minEmitBox;
  171. }
  172. return Vector3.Zero();
  173. }
  174. public set minEmitBox(value: Vector3) {
  175. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  176. (<BoxParticleEmitter>this.particleEmitterType).minEmitBox = value;
  177. }
  178. }
  179. /**
  180. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  181. * This only works when particleEmitterTyps is a BoxParticleEmitter
  182. */
  183. public get maxEmitBox(): Vector3 {
  184. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  185. return (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox;
  186. }
  187. return Vector3.Zero();
  188. }
  189. public set maxEmitBox(value: Vector3) {
  190. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  191. (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox = value;
  192. }
  193. }
  194. /**
  195. * Gets the maximum number of particles active at the same time.
  196. * @returns The max number of active particles.
  197. */
  198. public getCapacity(): number {
  199. return this._capacity;
  200. }
  201. /**
  202. * Gets or set the number of active particles
  203. */
  204. public get activeParticleCount(): number {
  205. return this._activeCount;
  206. }
  207. public set activeParticleCount(value: number) {
  208. this._activeCount = Math.min(value, this._capacity);
  209. }
  210. /**
  211. * Gets Wether the system has been started.
  212. * @returns True if it has been started, otherwise false.
  213. */
  214. public isStarted(): boolean {
  215. return this._started;
  216. }
  217. /**
  218. * Starts the particle system and begins to emit.
  219. */
  220. public start(): void {
  221. this._started = true;
  222. this._stopped = false;
  223. }
  224. /**
  225. * Stops the particle system.
  226. */
  227. public stop(): void {
  228. this._stopped = true;
  229. }
  230. /**
  231. * Remove all active particles
  232. */
  233. public reset(): void {
  234. this._releaseBuffers();
  235. this._releaseVAOs();
  236. this._currentActiveCount = 0;
  237. this._targetIndex = 0;
  238. }
  239. /**
  240. * Returns the string "GPUParticleSystem"
  241. * @returns a string containing the class name
  242. */
  243. public getClassName(): string {
  244. return "GPUParticleSystem";
  245. }
  246. /**
  247. * Instantiates a GPU particle system.
  248. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  249. * @param name The name of the particle system
  250. * @param capacity The max number of particles alive at the same time
  251. * @param scene The scene the particle system belongs to
  252. */
  253. constructor(name: string, options: Partial<{
  254. capacity: number,
  255. randomTextureSize: number
  256. }>, scene: Scene) {
  257. this.id = name;
  258. this.name = name;
  259. this._scene = scene || Engine.LastCreatedScene;
  260. this._engine = this._scene.getEngine();
  261. let fullOptions = {
  262. capacity: 50000,
  263. randomTextureSize: this._engine.getCaps().maxTextureSize,
  264. ...options
  265. };
  266. this._capacity = fullOptions.capacity;
  267. this._activeCount = fullOptions.capacity;
  268. this._currentActiveCount = 0;
  269. this._scene.particleSystems.push(this);
  270. this._updateEffectOptions = {
  271. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  272. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  273. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  274. uniformBuffersNames: [],
  275. samplers:["randomSampler"],
  276. defines: "",
  277. fallbacks: null,
  278. onCompiled: null,
  279. onError: null,
  280. indexParameters: null,
  281. maxSimultaneousLights: 0,
  282. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  283. };
  284. // Random data
  285. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  286. var d = [];
  287. for (var i = 0; i < maxTextureSize; ++i) {
  288. d.push(Math.random());
  289. d.push(Math.random());
  290. d.push(Math.random());
  291. d.push(Math.random());
  292. }
  293. this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT)
  294. this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;
  295. this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;
  296. this._randomTextureSize = maxTextureSize;
  297. this.particleEmitterType = new BoxParticleEmitter();
  298. }
  299. private _createUpdateVAO(source: Buffer): WebGLVertexArrayObject {
  300. let updateVertexBuffers: {[key: string]: VertexBuffer} = {};
  301. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  302. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  303. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  304. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  305. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  306. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  307. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  308. let vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  309. this._engine.bindArrayBuffer(null);
  310. return vao;
  311. }
  312. private _createRenderVAO(source: Buffer, spriteSource: Buffer): WebGLVertexArrayObject {
  313. let renderVertexBuffers: {[key: string]: VertexBuffer} = {};
  314. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  315. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  316. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  317. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  318. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  319. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  320. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  321. let vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  322. this._engine.bindArrayBuffer(null);
  323. return vao;
  324. }
  325. private _initialize(force = false): void {
  326. if (this._buffer0 && !force) {
  327. return;
  328. }
  329. let engine = this._scene.getEngine();
  330. var data = new Array<float>();
  331. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  332. // position
  333. data.push(0.0);
  334. data.push(0.0);
  335. data.push(0.0);
  336. // Age and life
  337. data.push(0.0); // create the particle as a dead one to create a new one at start
  338. data.push(0.0);
  339. // Seed
  340. data.push(Math.random());
  341. // Size
  342. data.push(0.0);
  343. // color
  344. data.push(0.0);
  345. data.push(0.0);
  346. data.push(0.0);
  347. data.push(0.0);
  348. // direction
  349. data.push(0.0);
  350. data.push(0.0);
  351. data.push(0.0);
  352. }
  353. // Sprite data
  354. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  355. -0.5, 0.5, 0, 1,
  356. -0.5, -0.5, 0, 0,
  357. 0.5, -0.5, 1, 0]);
  358. // Buffers
  359. this._buffer0 = new Buffer(engine, data, false, this._attributesStrideSize);
  360. this._buffer1 = new Buffer(engine, data, false, this._attributesStrideSize);
  361. this._spriteBuffer = new Buffer(engine, spriteData, false, 4);
  362. // Update VAO
  363. this._updateVAO = [];
  364. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  365. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  366. // Render VAO
  367. this._renderVAO = [];
  368. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  369. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  370. // Links
  371. this._sourceBuffer = this._buffer0;
  372. this._targetBuffer = this._buffer1;
  373. }
  374. /** @ignore */
  375. public _recreateUpdateEffect() {
  376. let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  377. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  378. return;
  379. }
  380. this._updateEffectOptions.defines = defines;
  381. this._updateEffect = new Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  382. }
  383. /** @ignore */
  384. public _recreateRenderEffect() {
  385. let defines = "";
  386. if (this._scene.clipPlane) {
  387. defines = "\n#define CLIPPLANE";
  388. }
  389. if (this._renderEffect && this._renderEffect.defines === defines) {
  390. return;
  391. }
  392. this._renderEffect = new Effect("gpuRenderParticles",
  393. ["position", "age", "life", "size", "color", "offset", "uv"],
  394. ["view", "projection", "colorDead", "invView", "vClipPlane"],
  395. ["textureSampler"], this._scene.getEngine(), defines);
  396. }
  397. /**
  398. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  399. */
  400. public animate(): void {
  401. if (!this._stopped) {
  402. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  403. this._actualFrame += this._timeDelta;
  404. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  405. this.stop();
  406. } else {
  407. this._timeDelta = 0;
  408. }
  409. }
  410. /**
  411. * Renders the particle system in its current state.
  412. * @returns the current number of particles
  413. */
  414. public render(): number {
  415. if (!this._started) {
  416. return 0;
  417. }
  418. this._recreateUpdateEffect();
  419. this._recreateRenderEffect();
  420. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() ) {
  421. return 0;
  422. }
  423. if (this._currentRenderId === this._scene.getRenderId()) {
  424. return 0;
  425. }
  426. this._currentRenderId = this._scene.getRenderId();
  427. // Get everything ready to render
  428. this. _initialize();
  429. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  430. // Enable update effect
  431. this._engine.enableEffect(this._updateEffect);
  432. this._engine.setState(false);
  433. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  434. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  435. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  436. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  437. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  438. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  439. this._updateEffect.setDirectColor4("color1", this.color1);
  440. this._updateEffect.setDirectColor4("color2", this.color2);
  441. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  442. this._updateEffect.setVector3("gravity", this.gravity);
  443. if (this.particleEmitterType) {
  444. this.particleEmitterType.applyToShader(this._updateEffect);
  445. }
  446. let emitterWM: Matrix;
  447. if ((<AbstractMesh>this.emitter).position) {
  448. var emitterMesh = (<AbstractMesh>this.emitter);
  449. emitterWM = emitterMesh.getWorldMatrix();
  450. } else {
  451. var emitterPosition = (<Vector3>this.emitter);
  452. emitterWM = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  453. }
  454. this._updateEffect.setMatrix("emitterWM", emitterWM);
  455. // Bind source VAO
  456. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  457. // Update
  458. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  459. this._engine.setRasterizerState(false);
  460. this._engine.beginTransformFeedback();
  461. this._engine.drawArraysType(Material.PointListDrawMode, 0, this._currentActiveCount);
  462. this._engine.endTransformFeedback();
  463. this._engine.setRasterizerState(true);
  464. this._engine.bindTransformFeedbackBuffer(null);
  465. // Enable render effect
  466. this._engine.enableEffect(this._renderEffect);
  467. let viewMatrix = this._scene.getViewMatrix();
  468. this._renderEffect.setMatrix("view", viewMatrix);
  469. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  470. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  471. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  472. if (this._scene.clipPlane) {
  473. var clipPlane = this._scene.clipPlane;
  474. var invView = viewMatrix.clone();
  475. invView.invert();
  476. this._renderEffect.setMatrix("invView", invView);
  477. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  478. }
  479. // Draw order
  480. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  481. this._engine.setAlphaMode(Engine.ALPHA_ONEONE);
  482. } else {
  483. this._engine.setAlphaMode(Engine.ALPHA_COMBINE);
  484. }
  485. // Bind source VAO
  486. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  487. // Render
  488. this._engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  489. this._engine.setAlphaMode(Engine.ALPHA_DISABLE);
  490. // Switch VAOs
  491. this._targetIndex++;
  492. if (this._targetIndex === 2) {
  493. this._targetIndex = 0;
  494. }
  495. // Switch buffers
  496. let tmpBuffer = this._sourceBuffer;
  497. this._sourceBuffer = this._targetBuffer;
  498. this._targetBuffer = tmpBuffer;
  499. return this._currentActiveCount;
  500. }
  501. /**
  502. * Rebuilds the particle system
  503. */
  504. public rebuild(): void {
  505. this._initialize(true);
  506. }
  507. private _releaseBuffers() {
  508. if (this._buffer0) {
  509. this._buffer0.dispose();
  510. (<any>this._buffer0) = null;
  511. }
  512. if (this._buffer1) {
  513. this._buffer1.dispose();
  514. (<any>this._buffer1) = null;
  515. }
  516. if (this._spriteBuffer) {
  517. this._spriteBuffer.dispose();
  518. (<any>this._spriteBuffer) = null;
  519. }
  520. }
  521. private _releaseVAOs() {
  522. for (var index = 0; index < this._updateVAO.length; index++) {
  523. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  524. }
  525. this._updateVAO = [];
  526. for (var index = 0; index < this._renderVAO.length; index++) {
  527. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  528. }
  529. this._renderVAO = [];
  530. }
  531. /**
  532. * Disposes the particle system and free the associated resources.
  533. */
  534. public dispose(): void {
  535. var index = this._scene.particleSystems.indexOf(this);
  536. if (index > -1) {
  537. this._scene.particleSystems.splice(index, 1);
  538. }
  539. this._releaseBuffers();
  540. this._releaseVAOs();
  541. if (this._randomTexture) {
  542. this._randomTexture.dispose();
  543. (<any>this._randomTexture) = null;
  544. }
  545. // Callback
  546. this.onDisposeObservable.notifyObservers(this);
  547. this.onDisposeObservable.clear();
  548. }
  549. /**
  550. * Clones the particle system.
  551. * @param name The name of the cloned object
  552. * @param newEmitter The new emitter to use
  553. * @returns the cloned particle system
  554. */
  555. public clone(name: string, newEmitter: any): Nullable<GPUParticleSystem> {
  556. var result = new GPUParticleSystem(name, {capacity: this._capacity, randomTextureSize: this._randomTextureSize}, this._scene);
  557. Tools.DeepCopy(this, result);
  558. if (newEmitter === undefined) {
  559. newEmitter = this.emitter;
  560. }
  561. result.emitter = newEmitter;
  562. if (this.particleTexture) {
  563. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  564. }
  565. return result;
  566. }
  567. /**
  568. * Serializes the particle system to a JSON object.
  569. * @returns the JSON object
  570. */
  571. public serialize(): any {
  572. var serializationObject: any = {};
  573. serializationObject.name = this.name;
  574. serializationObject.id = this.id;
  575. // Emitter
  576. if ((<AbstractMesh>this.emitter).position) {
  577. var emitterMesh = (<AbstractMesh>this.emitter);
  578. serializationObject.emitterId = emitterMesh.id;
  579. } else {
  580. var emitterPosition = (<Vector3>this.emitter);
  581. serializationObject.emitter = emitterPosition.asArray();
  582. }
  583. serializationObject.capacity = this.getCapacity();
  584. if (this.particleTexture) {
  585. serializationObject.textureName = this.particleTexture.name;
  586. }
  587. // Animations
  588. Animation.AppendSerializedAnimations(this, serializationObject);
  589. // Particle system
  590. serializationObject.activeParticleCount = this.activeParticleCount;
  591. serializationObject.randomTextureSize = this._randomTextureSize;
  592. serializationObject.minSize = this.minSize;
  593. serializationObject.maxSize = this.maxSize;
  594. serializationObject.minEmitPower = this.minEmitPower;
  595. serializationObject.maxEmitPower = this.maxEmitPower;
  596. serializationObject.minLifeTime = this.minLifeTime;
  597. serializationObject.maxLifeTime = this.maxLifeTime;
  598. serializationObject.emitRate = this.emitRate;
  599. serializationObject.gravity = this.gravity.asArray();
  600. serializationObject.color1 = this.color1.asArray();
  601. serializationObject.color2 = this.color2.asArray();
  602. serializationObject.colorDead = this.colorDead.asArray();
  603. serializationObject.updateSpeed = this.updateSpeed;
  604. serializationObject.targetStopDuration = this.targetStopDuration;
  605. serializationObject.blendMode = this.blendMode;
  606. // Emitter
  607. if (this.particleEmitterType) {
  608. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  609. }
  610. return serializationObject;
  611. }
  612. /**
  613. * Parses a JSON object to create a GPU particle system.
  614. * @param parsedParticleSystem The JSON object to parse
  615. * @param scene The scene to create the particle system in
  616. * @param rootUrl The root url to use to load external dependencies like texture
  617. * @returns the parsed GPU particle system
  618. */
  619. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem {
  620. var name = parsedParticleSystem.name;
  621. var particleSystem = new GPUParticleSystem(name, {capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize}, scene);
  622. if (parsedParticleSystem.id) {
  623. particleSystem.id = parsedParticleSystem.id;
  624. }
  625. // Texture
  626. if (parsedParticleSystem.textureName) {
  627. particleSystem.particleTexture = new Texture(rootUrl + parsedParticleSystem.textureName, scene);
  628. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  629. }
  630. // Emitter
  631. if (parsedParticleSystem.emitterId) {
  632. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  633. } else {
  634. particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
  635. }
  636. // Animations
  637. if (parsedParticleSystem.animations) {
  638. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  639. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  640. particleSystem.animations.push(Animation.Parse(parsedAnimation));
  641. }
  642. }
  643. // Particle system
  644. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  645. particleSystem.minSize = parsedParticleSystem.minSize;
  646. particleSystem.maxSize = parsedParticleSystem.maxSize;
  647. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  648. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  649. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  650. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  651. particleSystem.emitRate = parsedParticleSystem.emitRate;
  652. particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
  653. particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
  654. particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
  655. particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
  656. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  657. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  658. particleSystem.blendMode = parsedParticleSystem.blendMode;
  659. // Emitter
  660. if (parsedParticleSystem.particleEmitterType) {
  661. let emitterType: IParticleEmitterType;
  662. switch (parsedParticleSystem.particleEmitterType.type) {
  663. case "SphereEmitter":
  664. emitterType = new SphereParticleEmitter();
  665. break;
  666. case "SphereDirectedParticleEmitter":
  667. emitterType = new SphereDirectedParticleEmitter();
  668. break;
  669. case "ConeEmitter":
  670. emitterType = new ConeParticleEmitter();
  671. break;
  672. case "BoxEmitter":
  673. default:
  674. emitterType = new BoxParticleEmitter();
  675. break;
  676. }
  677. emitterType.parse(parsedParticleSystem.particleEmitterType);
  678. particleSystem.particleEmitterType = emitterType;
  679. }
  680. return particleSystem;
  681. }
  682. }
  683. }