babylon.gpuParticleSystem.ts 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  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 extends BaseParticleSystem implements IDisposable, IParticleSystem, IAnimatable {
  8. /**
  9. * The layer mask we are rendering the particles through.
  10. */
  11. public layerMask: number = 0x0FFFFFFF;
  12. private _capacity: number;
  13. private _activeCount: number;
  14. private _currentActiveCount: number;
  15. private _accumulatedCount = 0;
  16. private _renderEffect: Effect;
  17. private _updateEffect: Effect;
  18. private _buffer0: Buffer;
  19. private _buffer1: Buffer;
  20. private _spriteBuffer: Buffer;
  21. private _updateVAO: Array<WebGLVertexArrayObject>;
  22. private _renderVAO: Array<WebGLVertexArrayObject>;
  23. private _targetIndex = 0;
  24. private _sourceBuffer: Buffer;
  25. private _targetBuffer: Buffer;
  26. private _engine: Engine;
  27. private _currentRenderId = -1;
  28. private _started = false;
  29. private _stopped = false;
  30. private _timeDelta = 0;
  31. private _randomTexture: RawTexture;
  32. private _randomTexture2: RawTexture;
  33. private _attributesStrideSize = 21;
  34. private _updateEffectOptions: EffectCreationOptions;
  35. private _randomTextureSize: number;
  36. private _actualFrame = 0;
  37. private readonly _rawTextureWidth = 256;
  38. /**
  39. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  40. */
  41. public static get IsSupported(): boolean {
  42. if (!Engine.LastCreatedEngine) {
  43. return false;
  44. }
  45. return Engine.LastCreatedEngine.webGLVersion > 1;
  46. }
  47. /**
  48. * An event triggered when the system is disposed.
  49. */
  50. public onDisposeObservable = new Observable<GPUParticleSystem>();
  51. /**
  52. * Gets the maximum number of particles active at the same time.
  53. * @returns The max number of active particles.
  54. */
  55. public getCapacity(): number {
  56. return this._capacity;
  57. }
  58. /**
  59. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60. * to override the particles.
  61. */
  62. public forceDepthWrite = false;
  63. /**
  64. * Gets or set the number of active particles
  65. */
  66. public get activeParticleCount(): number {
  67. return this._activeCount;
  68. }
  69. public set activeParticleCount(value: number) {
  70. this._activeCount = Math.min(value, this._capacity);
  71. }
  72. private _preWarmDone = false;
  73. /**
  74. * Is this system ready to be used/rendered
  75. * @return true if the system is ready
  76. */
  77. public isReady(): boolean {
  78. if (!this._updateEffect) {
  79. this._recreateUpdateEffect();
  80. this._recreateRenderEffect();
  81. return false;
  82. }
  83. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  84. return false;
  85. }
  86. return true;
  87. }
  88. /**
  89. * Gets if the system has been started. (Note: this will still be true after stop is called)
  90. * @returns True if it has been started, otherwise false.
  91. */
  92. public isStarted(): boolean {
  93. return this._started;
  94. }
  95. /**
  96. * Starts the particle system and begins to emit
  97. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  98. */
  99. public start(delay = 0): void {
  100. if (delay) {
  101. setTimeout(()=> {
  102. this.start(0);
  103. }, delay);
  104. return;
  105. }
  106. this._started = true;
  107. this._stopped = false;
  108. this._preWarmDone = false;
  109. }
  110. /**
  111. * Stops the particle system.
  112. */
  113. public stop(): void {
  114. this._stopped = true;
  115. }
  116. /**
  117. * Remove all active particles
  118. */
  119. public reset(): void {
  120. this._releaseBuffers();
  121. this._releaseVAOs();
  122. this._currentActiveCount = 0;
  123. this._targetIndex = 0;
  124. }
  125. /**
  126. * Returns the string "GPUParticleSystem"
  127. * @returns a string containing the class name
  128. */
  129. public getClassName(): string {
  130. return "GPUParticleSystem";
  131. }
  132. private _colorGradientsTexture: RawTexture;
  133. private _removeGradient(gradient: number, gradients: Nullable<IValueGradient[]>, texture: RawTexture): GPUParticleSystem {
  134. if (!gradients) {
  135. return this;
  136. }
  137. let index = 0;
  138. for (var valueGradient of gradients) {
  139. if (valueGradient.gradient === gradient) {
  140. gradients.splice(index, 1);
  141. break;
  142. }
  143. index++;
  144. }
  145. if (texture) {
  146. texture.dispose();
  147. }
  148. this._releaseBuffers();
  149. return this;
  150. }
  151. /**
  152. * Adds a new color gradient
  153. * @param gradient defines the gradient to use (between 0 and 1)
  154. * @param color defines the color to affect to the specified gradient
  155. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  156. * @returns the current particle system
  157. */
  158. public addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem {
  159. if (!this._colorGradients) {
  160. this._colorGradients = [];
  161. }
  162. let colorGradient = new ColorGradient();
  163. colorGradient.gradient = gradient;
  164. colorGradient.color1 = color1;
  165. this._colorGradients.push(colorGradient);
  166. this._colorGradients.sort((a, b) => {
  167. if (a.gradient < b.gradient) {
  168. return -1;
  169. } else if (a.gradient > b.gradient) {
  170. return 1;
  171. }
  172. return 0;
  173. });
  174. if (this._colorGradientsTexture) {
  175. this._colorGradientsTexture.dispose();
  176. (<any>this._colorGradientsTexture) = null;
  177. }
  178. this._releaseBuffers();
  179. return this;
  180. }
  181. /**
  182. * Remove a specific color gradient
  183. * @param gradient defines the gradient to remove
  184. * @returns the current particle system
  185. */
  186. public removeColorGradient(gradient: number): GPUParticleSystem {
  187. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  188. (<any>this._colorGradientsTexture) = null;
  189. return this;
  190. }
  191. private _angularSpeedGradientsTexture: RawTexture;
  192. private _sizeGradientsTexture: RawTexture;
  193. private _velocityGradientsTexture: RawTexture;
  194. private _limitVelocityGradientsTexture: RawTexture;
  195. private _dragGradientsTexture: RawTexture;
  196. private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number) {
  197. let valueGradient = new FactorGradient();
  198. valueGradient.gradient = gradient;
  199. valueGradient.factor1 = factor;
  200. factorGradients.push(valueGradient);
  201. factorGradients.sort((a, b) => {
  202. if (a.gradient < b.gradient) {
  203. return -1;
  204. } else if (a.gradient > b.gradient) {
  205. return 1;
  206. }
  207. return 0;
  208. });
  209. this._releaseBuffers();
  210. }
  211. /**
  212. * Adds a new size gradient
  213. * @param gradient defines the gradient to use (between 0 and 1)
  214. * @param factor defines the size factor to affect to the specified gradient
  215. * @returns the current particle system
  216. */
  217. public addSizeGradient(gradient: number, factor: number): GPUParticleSystem {
  218. if (!this._sizeGradients) {
  219. this._sizeGradients = [];
  220. }
  221. this._addFactorGradient(this._sizeGradients, gradient, factor);
  222. if (this._sizeGradientsTexture) {
  223. this._sizeGradientsTexture.dispose();
  224. (<any>this._sizeGradientsTexture) = null;
  225. }
  226. this._releaseBuffers();
  227. return this;
  228. }
  229. /**
  230. * Remove a specific size gradient
  231. * @param gradient defines the gradient to remove
  232. * @returns the current particle system
  233. */
  234. public removeSizeGradient(gradient: number): GPUParticleSystem {
  235. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  236. (<any>this._sizeGradientsTexture) = null;
  237. return this;
  238. }
  239. /**
  240. * Adds a new angular speed gradient
  241. * @param gradient defines the gradient to use (between 0 and 1)
  242. * @param factor defines the angular speed to affect to the specified gradient
  243. * @returns the current particle system
  244. */
  245. public addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem {
  246. if (!this._angularSpeedGradients) {
  247. this._angularSpeedGradients = [];
  248. }
  249. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  250. if (this._angularSpeedGradientsTexture) {
  251. this._angularSpeedGradientsTexture.dispose();
  252. (<any>this._angularSpeedGradientsTexture) = null;
  253. }
  254. this._releaseBuffers();
  255. return this;
  256. }
  257. /**
  258. * Remove a specific angular speed gradient
  259. * @param gradient defines the gradient to remove
  260. * @returns the current particle system
  261. */
  262. public removeAngularSpeedGradient(gradient: number): GPUParticleSystem {
  263. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  264. (<any>this._angularSpeedGradientsTexture) = null;
  265. return this;
  266. }
  267. /**
  268. * Adds a new velocity gradient
  269. * @param gradient defines the gradient to use (between 0 and 1)
  270. * @param factor defines the velocity to affect to the specified gradient
  271. * @returns the current particle system
  272. */
  273. public addVelocityGradient(gradient: number, factor: number): GPUParticleSystem {
  274. if (!this._velocityGradients) {
  275. this._velocityGradients = [];
  276. }
  277. this._addFactorGradient(this._velocityGradients, gradient, factor);
  278. if (this._velocityGradientsTexture) {
  279. this._velocityGradientsTexture.dispose();
  280. (<any>this._velocityGradientsTexture) = null;
  281. }
  282. this._releaseBuffers();
  283. return this;
  284. }
  285. /**
  286. * Remove a specific velocity gradient
  287. * @param gradient defines the gradient to remove
  288. * @returns the current particle system
  289. */
  290. public removeVelocityGradient(gradient: number): GPUParticleSystem {
  291. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  292. (<any>this._velocityGradientsTexture) = null;
  293. return this;
  294. }
  295. /**
  296. * Adds a new limit velocity gradient
  297. * @param gradient defines the gradient to use (between 0 and 1)
  298. * @param factor defines the limit velocity value to affect to the specified gradient
  299. * @returns the current particle system
  300. */
  301. public addLimitVelocityGradient(gradient: number, factor: number): GPUParticleSystem {
  302. if (!this._limitVelocityGradients) {
  303. this._limitVelocityGradients = [];
  304. }
  305. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  306. if (this._limitVelocityGradientsTexture) {
  307. this._limitVelocityGradientsTexture.dispose();
  308. (<any>this._limitVelocityGradientsTexture) = null;
  309. }
  310. this._releaseBuffers();
  311. return this;
  312. }
  313. /**
  314. * Remove a specific limit velocity gradient
  315. * @param gradient defines the gradient to remove
  316. * @returns the current particle system
  317. */
  318. public removeLimitVelocityGradient(gradient: number): GPUParticleSystem {
  319. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  320. (<any>this._limitVelocityGradientsTexture) = null;
  321. return this;
  322. }
  323. /**
  324. * Adds a new drag gradient
  325. * @param gradient defines the gradient to use (between 0 and 1)
  326. * @param factor defines the drag value to affect to the specified gradient
  327. * @returns the current particle system
  328. */
  329. public addDragGradient(gradient: number, factor: number): GPUParticleSystem {
  330. if (!this._dragGradients) {
  331. this._dragGradients = [];
  332. }
  333. this._addFactorGradient(this._dragGradients, gradient, factor);
  334. if (this._dragGradientsTexture) {
  335. this._dragGradientsTexture.dispose();
  336. (<any>this._dragGradientsTexture) = null;
  337. }
  338. this._releaseBuffers();
  339. return this;
  340. }
  341. /**
  342. * Remove a specific drag gradient
  343. * @param gradient defines the gradient to remove
  344. * @returns the current particle system
  345. */
  346. public removeDragGradient(gradient: number): GPUParticleSystem {
  347. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  348. (<any>this._dragGradientsTexture) = null;
  349. return this;
  350. }
  351. /**
  352. * Not supported by GPUParticleSystem
  353. * @param gradient defines the gradient to use (between 0 and 1)
  354. * @param factor defines the emit rate value to affect to the specified gradient
  355. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  356. * @returns the current particle system
  357. */
  358. public addEmitRateGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  359. // Do nothing as emit rate is not supported by GPUParticleSystem
  360. return this;
  361. }
  362. /**
  363. * Not supported by GPUParticleSystem
  364. * @param gradient defines the gradient to remove
  365. * @returns the current particle system
  366. */
  367. public removeEmitRateGradient(gradient: number): IParticleSystem {
  368. // Do nothing as emit rate is not supported by GPUParticleSystem
  369. return this;
  370. }
  371. /**
  372. * Not supported by GPUParticleSystem
  373. * @param gradient defines the gradient to use (between 0 and 1)
  374. * @param factor defines the start size value to affect to the specified gradient
  375. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  376. * @returns the current particle system
  377. */
  378. public addStartSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
  379. // Do nothing as start size is not supported by GPUParticleSystem
  380. return this;
  381. }
  382. /**
  383. * Not supported by GPUParticleSystem
  384. * @param gradient defines the gradient to remove
  385. * @returns the current particle system
  386. */
  387. public removeStartSizeGradient(gradient: number): IParticleSystem {
  388. // Do nothing as start size is not supported by GPUParticleSystem
  389. return this;
  390. }
  391. /**
  392. * Instantiates a GPU particle system.
  393. * 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.
  394. * @param name The name of the particle system
  395. * @param options The options used to create the system
  396. * @param scene The scene the particle system belongs to
  397. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  398. */
  399. constructor(name: string, options: Partial<{
  400. capacity: number,
  401. randomTextureSize: number
  402. }>, scene: Scene, isAnimationSheetEnabled: boolean = false) {
  403. super(name);
  404. this._scene = scene || Engine.LastCreatedScene;
  405. // Setup the default processing configuration to the scene.
  406. this._attachImageProcessingConfiguration(null);
  407. this._engine = this._scene.getEngine();
  408. if (!options.randomTextureSize) {
  409. delete options.randomTextureSize;
  410. }
  411. let fullOptions = {
  412. capacity: 50000,
  413. randomTextureSize: this._engine.getCaps().maxTextureSize,
  414. ...options
  415. };
  416. var optionsAsNumber = <number>options;
  417. if (isFinite(optionsAsNumber)) {
  418. fullOptions.capacity = optionsAsNumber;
  419. }
  420. this._capacity = fullOptions.capacity;
  421. this._activeCount = fullOptions.capacity;
  422. this._currentActiveCount = 0;
  423. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  424. this._scene.particleSystems.push(this);
  425. this._updateEffectOptions = {
  426. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  427. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange","gravity", "emitPower",
  428. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  429. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  430. uniformBuffersNames: [],
  431. samplers:["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  432. defines: "",
  433. fallbacks: null,
  434. onCompiled: null,
  435. onError: null,
  436. indexParameters: null,
  437. maxSimultaneousLights: 0,
  438. transformFeedbackVaryings: []
  439. };
  440. this.particleEmitterType = new BoxParticleEmitter();
  441. // Random data
  442. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  443. var d = [];
  444. for (var i = 0; i < maxTextureSize; ++i) {
  445. d.push(Math.random());
  446. d.push(Math.random());
  447. d.push(Math.random());
  448. d.push(Math.random());
  449. }
  450. this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);
  451. this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;
  452. this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;
  453. d = [];
  454. for (var i = 0; i < maxTextureSize; ++i) {
  455. d.push(Math.random());
  456. d.push(Math.random());
  457. d.push(Math.random());
  458. d.push(Math.random());
  459. }
  460. this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);
  461. this._randomTexture2.wrapU = Texture.WRAP_ADDRESSMODE;
  462. this._randomTexture2.wrapV = Texture.WRAP_ADDRESSMODE;
  463. this._randomTextureSize = maxTextureSize;
  464. }
  465. protected _reset() {
  466. this._releaseBuffers();
  467. }
  468. private _createUpdateVAO(source: Buffer): WebGLVertexArrayObject {
  469. let updateVertexBuffers: {[key: string]: VertexBuffer} = {};
  470. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  471. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  472. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  473. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  474. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  475. let offset = 12;
  476. if (!this._colorGradientsTexture) {
  477. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  478. offset += 4;
  479. }
  480. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  481. offset += 3
  482. if (!this._isBillboardBased) {
  483. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  484. offset += 3;
  485. }
  486. if (this._angularSpeedGradientsTexture) {
  487. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  488. offset += 1;
  489. } else {
  490. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  491. offset += 2;
  492. }
  493. if (this._isAnimationSheetEnabled) {
  494. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  495. offset += 1;
  496. if (this.spriteRandomStartCell) {
  497. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  498. offset += 1;
  499. }
  500. }
  501. let vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  502. this._engine.bindArrayBuffer(null);
  503. return vao;
  504. }
  505. private _createRenderVAO(source: Buffer, spriteSource: Buffer): WebGLVertexArrayObject {
  506. let renderVertexBuffers: {[key: string]: VertexBuffer} = {};
  507. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  508. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  509. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  510. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  511. let offset = 12;
  512. if (!this._colorGradientsTexture) {
  513. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  514. offset += 4;
  515. }
  516. offset += 3; // Direction
  517. if (!this._isBillboardBased) {
  518. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  519. offset += 3;
  520. }
  521. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  522. if (this._angularSpeedGradientsTexture) {
  523. offset++;
  524. } else {
  525. offset += 2;
  526. }
  527. if (this._isAnimationSheetEnabled) {
  528. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  529. offset += 1;
  530. if (this.spriteRandomStartCell) {
  531. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  532. offset += 1;
  533. }
  534. }
  535. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  536. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  537. let vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  538. this._engine.bindArrayBuffer(null);
  539. return vao;
  540. }
  541. private _initialize(force = false): void {
  542. if (this._buffer0 && !force) {
  543. return;
  544. }
  545. let engine = this._scene.getEngine();
  546. var data = new Array<float>();
  547. if (!this.isBillboardBased) {
  548. this._attributesStrideSize += 3;
  549. }
  550. if (this._colorGradientsTexture) {
  551. this._attributesStrideSize -= 4;
  552. }
  553. if (this._angularSpeedGradientsTexture) {
  554. this._attributesStrideSize -= 1;
  555. }
  556. if (this._isAnimationSheetEnabled) {
  557. this._attributesStrideSize += 1;
  558. if (this.spriteRandomStartCell) {
  559. this._attributesStrideSize += 1;
  560. }
  561. }
  562. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  563. // position
  564. data.push(0.0);
  565. data.push(0.0);
  566. data.push(0.0);
  567. // Age and life
  568. data.push(0.0); // create the particle as a dead one to create a new one at start
  569. data.push(0.0);
  570. // Seed
  571. data.push(Math.random());
  572. data.push(Math.random());
  573. data.push(Math.random());
  574. data.push(Math.random());
  575. // Size
  576. data.push(0.0);
  577. data.push(0.0);
  578. data.push(0.0);
  579. if (!this._colorGradientsTexture) {
  580. // color
  581. data.push(0.0);
  582. data.push(0.0);
  583. data.push(0.0);
  584. data.push(0.0);
  585. }
  586. // direction
  587. data.push(0.0);
  588. data.push(0.0);
  589. data.push(0.0);
  590. if (!this.isBillboardBased) {
  591. // initialDirection
  592. data.push(0.0);
  593. data.push(0.0);
  594. data.push(0.0);
  595. }
  596. // angle
  597. data.push(0.0);
  598. if (!this._angularSpeedGradientsTexture) {
  599. data.push(0.0);
  600. }
  601. if (this._isAnimationSheetEnabled) {
  602. data.push(0.0);
  603. if (this.spriteRandomStartCell) {
  604. data.push(0.0);
  605. }
  606. }
  607. }
  608. // Sprite data
  609. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  610. -0.5, 0.5, 0, 1,
  611. -0.5, -0.5, 0, 0,
  612. 0.5, -0.5, 1, 0]);
  613. // Buffers
  614. this._buffer0 = new Buffer(engine, data, false, this._attributesStrideSize);
  615. this._buffer1 = new Buffer(engine, data, false, this._attributesStrideSize);
  616. this._spriteBuffer = new Buffer(engine, spriteData, false, 4);
  617. // Update VAO
  618. this._updateVAO = [];
  619. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  620. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  621. // Render VAO
  622. this._renderVAO = [];
  623. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  624. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  625. // Links
  626. this._sourceBuffer = this._buffer0;
  627. this._targetBuffer = this._buffer1;
  628. }
  629. /** @hidden */
  630. public _recreateUpdateEffect() {
  631. let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  632. if (this._isBillboardBased) {
  633. defines += "\n#define BILLBOARD";
  634. }
  635. if (this._colorGradientsTexture) {
  636. defines += "\n#define COLORGRADIENTS";
  637. }
  638. if (this._sizeGradientsTexture) {
  639. defines += "\n#define SIZEGRADIENTS";
  640. }
  641. if (this._angularSpeedGradientsTexture) {
  642. defines += "\n#define ANGULARSPEEDGRADIENTS";
  643. }
  644. if (this._velocityGradientsTexture) {
  645. defines += "\n#define VELOCITYGRADIENTS";
  646. }
  647. if (this._limitVelocityGradientsTexture) {
  648. defines += "\n#define LIMITVELOCITYGRADIENTS";
  649. }
  650. if (this._dragGradientsTexture) {
  651. defines += "\n#define DRAGGRADIENTS";
  652. }
  653. if (this.isAnimationSheetEnabled) {
  654. defines += "\n#define ANIMATESHEET";
  655. if (this.spriteRandomStartCell) {
  656. defines += "\n#define ANIMATESHEETRANDOMSTART";
  657. }
  658. }
  659. if (this.noiseTexture) {
  660. defines += "\n#define NOISE";
  661. }
  662. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  663. return;
  664. }
  665. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  666. if (!this._colorGradientsTexture) {
  667. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  668. }
  669. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  670. if (!this._isBillboardBased) {
  671. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  672. }
  673. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  674. if (this.isAnimationSheetEnabled) {
  675. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  676. if (this.spriteRandomStartCell) {
  677. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  678. }
  679. }
  680. this._updateEffectOptions.defines = defines;
  681. this._updateEffect = new Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  682. }
  683. /** @hidden */
  684. public _recreateRenderEffect() {
  685. let defines = "";
  686. if (this._scene.clipPlane) {
  687. defines = "\n#define CLIPPLANE";
  688. }
  689. if (this._scene.clipPlane2) {
  690. defines = "\n#define CLIPPLANE2";
  691. }
  692. if (this._scene.clipPlane3) {
  693. defines = "\n#define CLIPPLANE3";
  694. }
  695. if (this._scene.clipPlane4) {
  696. defines = "\n#define CLIPPLANE4";
  697. }
  698. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  699. defines = "\n#define BLENDMULTIPLYMODE";
  700. }
  701. if (this._isBillboardBased) {
  702. defines += "\n#define BILLBOARD";
  703. switch (this.billboardMode) {
  704. case AbstractMesh.BILLBOARDMODE_Y:
  705. defines += "\n#define BILLBOARDY";
  706. break;
  707. case AbstractMesh.BILLBOARDMODE_ALL:
  708. default:
  709. break;
  710. }
  711. }
  712. if (this._colorGradientsTexture) {
  713. defines += "\n#define COLORGRADIENTS";
  714. }
  715. if (this.isAnimationSheetEnabled) {
  716. defines += "\n#define ANIMATESHEET";
  717. }
  718. if (this._imageProcessingConfiguration) {
  719. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  720. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  721. }
  722. if (this._renderEffect && this._renderEffect.defines === defines) {
  723. return;
  724. }
  725. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  726. var samplers = ["textureSampler", "colorGradientSampler"];
  727. if (ImageProcessingConfiguration) {
  728. ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  729. ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  730. }
  731. this._renderEffect = new Effect("gpuRenderParticles",
  732. ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"],
  733. uniforms,
  734. samplers, this._scene.getEngine(), defines);
  735. }
  736. /**
  737. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  738. * @param preWarm defines if we are in the pre-warmimg phase
  739. */
  740. public animate(preWarm = false): void {
  741. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  742. this._actualFrame += this._timeDelta;
  743. if (!this._stopped) {
  744. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  745. this.stop();
  746. }
  747. }
  748. }
  749. private _createFactorGradientTexture(factorGradients: Nullable<IValueGradient[]>, textureName: string) {
  750. let texture:RawTexture = (<any>this)[textureName];
  751. if (!factorGradients || !factorGradients.length || texture) {
  752. return;
  753. }
  754. let data = new Float32Array(this._rawTextureWidth);
  755. for (var x = 0; x < this._rawTextureWidth; x++) {
  756. var ratio = x / this._rawTextureWidth;
  757. Tools.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {
  758. data[x] = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  759. });
  760. }
  761. (<any>this)[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  762. }
  763. private _createSizeGradientTexture() {
  764. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  765. }
  766. private _createAngularSpeedGradientTexture() {
  767. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  768. }
  769. private _createVelocityGradientTexture() {
  770. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  771. }
  772. private _createLimitVelocityGradientTexture() {
  773. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  774. }
  775. private _createDragGradientTexture() {
  776. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  777. }
  778. private _createColorGradientTexture() {
  779. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  780. return;
  781. }
  782. let data = new Uint8Array(this._rawTextureWidth * 4);
  783. let tmpColor = Tmp.Color4[0];
  784. for (var x = 0; x < this._rawTextureWidth; x++) {
  785. var ratio = x / this._rawTextureWidth;
  786. Tools.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  787. Color4.LerpToRef((<ColorGradient>currentGradient).color1, (<ColorGradient>nextGradient).color1, scale, tmpColor);
  788. data[x * 4] = tmpColor.r * 255;
  789. data[x * 4 + 1] = tmpColor.g * 255;
  790. data[x * 4 + 2] = tmpColor.b * 255;
  791. data[x * 4 + 3] = tmpColor.a * 255;
  792. });
  793. }
  794. this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  795. }
  796. /**
  797. * Renders the particle system in its current state
  798. * @param preWarm defines if the system should only update the particles but not render them
  799. * @returns the current number of particles
  800. */
  801. public render(preWarm = false): number {
  802. if (!this._started) {
  803. return 0;
  804. }
  805. this._createColorGradientTexture();
  806. this._createSizeGradientTexture();
  807. this._createAngularSpeedGradientTexture();
  808. this._createVelocityGradientTexture();
  809. this._createLimitVelocityGradientTexture();
  810. this._createDragGradientTexture();
  811. this._recreateUpdateEffect();
  812. this._recreateRenderEffect();
  813. if (!this.isReady()) {
  814. return 0;
  815. }
  816. if (!preWarm) {
  817. if (!this._preWarmDone && this.preWarmCycles) {
  818. for (var index = 0; index < this.preWarmCycles; index++) {
  819. this.animate(true);
  820. this.render(true);
  821. }
  822. this._preWarmDone = true;
  823. }
  824. if (this._currentRenderId === this._scene.getRenderId()) {
  825. return 0;
  826. }
  827. this._currentRenderId = this._scene.getRenderId();
  828. }
  829. // Get everything ready to render
  830. this._initialize();
  831. this._accumulatedCount += this.emitRate * this._timeDelta;
  832. if (this._accumulatedCount > 1) {
  833. var intPart = this._accumulatedCount | 0;
  834. this._accumulatedCount -= intPart;
  835. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  836. }
  837. if (!this._currentActiveCount) {
  838. return 0;
  839. }
  840. // Enable update effect
  841. this._engine.enableEffect(this._updateEffect);
  842. this._engine.setState(false);
  843. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  844. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  845. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  846. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  847. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  848. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  849. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  850. if (!this._colorGradientsTexture) {
  851. this._updateEffect.setDirectColor4("color1", this.color1);
  852. this._updateEffect.setDirectColor4("color2", this.color2);
  853. }
  854. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  855. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  856. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  857. this._updateEffect.setVector3("gravity", this.gravity);
  858. if (this._sizeGradientsTexture) {
  859. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  860. }
  861. if (this._angularSpeedGradientsTexture) {
  862. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  863. }
  864. if (this._velocityGradientsTexture) {
  865. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  866. }
  867. if (this._limitVelocityGradientsTexture) {
  868. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  869. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  870. }
  871. if (this._dragGradientsTexture) {
  872. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  873. }
  874. if (this.particleEmitterType) {
  875. this.particleEmitterType.applyToShader(this._updateEffect);
  876. }
  877. if (this._isAnimationSheetEnabled) {
  878. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  879. }
  880. if (this.noiseTexture) {
  881. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  882. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  883. }
  884. let emitterWM: Matrix;
  885. if ((<AbstractMesh>this.emitter).position) {
  886. var emitterMesh = (<AbstractMesh>this.emitter);
  887. emitterWM = emitterMesh.getWorldMatrix();
  888. } else {
  889. var emitterPosition = (<Vector3>this.emitter);
  890. emitterWM = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  891. }
  892. this._updateEffect.setMatrix("emitterWM", emitterWM);
  893. // Bind source VAO
  894. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  895. // Update
  896. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  897. this._engine.setRasterizerState(false);
  898. this._engine.beginTransformFeedback(true);
  899. this._engine.drawArraysType(Material.PointListDrawMode, 0, this._currentActiveCount);
  900. this._engine.endTransformFeedback();
  901. this._engine.setRasterizerState(true);
  902. this._engine.bindTransformFeedbackBuffer(null);
  903. if (!preWarm) {
  904. // Enable render effect
  905. this._engine.enableEffect(this._renderEffect);
  906. let viewMatrix = this._scene.getViewMatrix();
  907. this._renderEffect.setMatrix("view", viewMatrix);
  908. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  909. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  910. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  911. if (this._colorGradientsTexture) {
  912. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  913. } else {
  914. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  915. }
  916. if (this._isAnimationSheetEnabled && this.particleTexture) {
  917. let baseSize = this.particleTexture.getBaseSize();
  918. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  919. }
  920. if (this._isBillboardBased) {
  921. var camera = this._scene.activeCamera!;
  922. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  923. }
  924. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  925. var invView = viewMatrix.clone();
  926. invView.invert();
  927. this._renderEffect.setMatrix("invView", invView);
  928. MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  929. }
  930. // image processing
  931. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  932. this._imageProcessingConfiguration.bind(this._renderEffect);
  933. }
  934. // Draw order
  935. switch(this.blendMode)
  936. {
  937. case ParticleSystem.BLENDMODE_ADD:
  938. this._engine.setAlphaMode(Engine.ALPHA_ADD);
  939. break;
  940. case ParticleSystem.BLENDMODE_ONEONE:
  941. this._engine.setAlphaMode(Engine.ALPHA_ONEONE);
  942. break;
  943. case ParticleSystem.BLENDMODE_STANDARD:
  944. this._engine.setAlphaMode(Engine.ALPHA_COMBINE);
  945. break;
  946. case ParticleSystem.BLENDMODE_MULTIPLY:
  947. this._engine.setAlphaMode(Engine.ALPHA_MULTIPLY);
  948. break;
  949. }
  950. if (this.forceDepthWrite) {
  951. this._engine.setDepthWrite(true);
  952. }
  953. // Bind source VAO
  954. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  955. // Render
  956. this._engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  957. this._engine.setAlphaMode(Engine.ALPHA_DISABLE);
  958. }
  959. // Switch VAOs
  960. this._targetIndex++;
  961. if (this._targetIndex === 2) {
  962. this._targetIndex = 0;
  963. }
  964. // Switch buffers
  965. let tmpBuffer = this._sourceBuffer;
  966. this._sourceBuffer = this._targetBuffer;
  967. this._targetBuffer = tmpBuffer;
  968. return this._currentActiveCount;
  969. }
  970. /**
  971. * Rebuilds the particle system
  972. */
  973. public rebuild(): void {
  974. this._initialize(true);
  975. }
  976. private _releaseBuffers() {
  977. if (this._buffer0) {
  978. this._buffer0.dispose();
  979. (<any>this._buffer0) = null;
  980. }
  981. if (this._buffer1) {
  982. this._buffer1.dispose();
  983. (<any>this._buffer1) = null;
  984. }
  985. if (this._spriteBuffer) {
  986. this._spriteBuffer.dispose();
  987. (<any>this._spriteBuffer) = null;
  988. }
  989. }
  990. private _releaseVAOs() {
  991. if (!this._updateVAO) {
  992. return;
  993. }
  994. for (var index = 0; index < this._updateVAO.length; index++) {
  995. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  996. }
  997. this._updateVAO = [];
  998. for (var index = 0; index < this._renderVAO.length; index++) {
  999. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  1000. }
  1001. this._renderVAO = [];
  1002. }
  1003. /**
  1004. * Disposes the particle system and free the associated resources
  1005. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1006. */
  1007. public dispose(disposeTexture = true): void {
  1008. var index = this._scene.particleSystems.indexOf(this);
  1009. if (index > -1) {
  1010. this._scene.particleSystems.splice(index, 1);
  1011. }
  1012. this._releaseBuffers();
  1013. this._releaseVAOs();
  1014. if (this._colorGradientsTexture) {
  1015. this._colorGradientsTexture.dispose();
  1016. (<any>this._colorGradientsTexture) = null;
  1017. }
  1018. if (this._sizeGradientsTexture) {
  1019. this._sizeGradientsTexture.dispose();
  1020. (<any>this._sizeGradientsTexture) = null;
  1021. }
  1022. if (this._angularSpeedGradientsTexture) {
  1023. this._angularSpeedGradientsTexture.dispose();
  1024. (<any>this._angularSpeedGradientsTexture) = null;
  1025. }
  1026. if (this._velocityGradientsTexture) {
  1027. this._velocityGradientsTexture.dispose();
  1028. (<any>this._velocityGradientsTexture) = null;
  1029. }
  1030. if (this._limitVelocityGradientsTexture) {
  1031. this._limitVelocityGradientsTexture.dispose();
  1032. (<any>this._limitVelocityGradientsTexture) = null;
  1033. }
  1034. if (this._dragGradientsTexture) {
  1035. this._dragGradientsTexture.dispose();
  1036. (<any>this._dragGradientsTexture) = null;
  1037. }
  1038. if (this._randomTexture) {
  1039. this._randomTexture.dispose();
  1040. (<any>this._randomTexture) = null;
  1041. }
  1042. if (this._randomTexture2) {
  1043. this._randomTexture2.dispose();
  1044. (<any>this._randomTexture2) = null;
  1045. }
  1046. if (disposeTexture && this.particleTexture) {
  1047. this.particleTexture.dispose();
  1048. this.particleTexture = null;
  1049. }
  1050. if (disposeTexture && this.noiseTexture) {
  1051. this.noiseTexture.dispose();
  1052. this.noiseTexture = null;
  1053. }
  1054. // Callback
  1055. this.onDisposeObservable.notifyObservers(this);
  1056. this.onDisposeObservable.clear();
  1057. }
  1058. /**
  1059. * Clones the particle system.
  1060. * @param name The name of the cloned object
  1061. * @param newEmitter The new emitter to use
  1062. * @returns the cloned particle system
  1063. */
  1064. public clone(name: string, newEmitter: any): GPUParticleSystem {
  1065. var result = new GPUParticleSystem(name, {capacity: this._capacity, randomTextureSize: this._randomTextureSize}, this._scene);
  1066. Tools.DeepCopy(this, result);
  1067. if (newEmitter === undefined) {
  1068. newEmitter = this.emitter;
  1069. }
  1070. result.emitter = newEmitter;
  1071. if (this.particleTexture) {
  1072. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1073. }
  1074. return result;
  1075. }
  1076. /**
  1077. * Serializes the particle system to a JSON object.
  1078. * @returns the JSON object
  1079. */
  1080. public serialize(): any {
  1081. var serializationObject: any = {};
  1082. ParticleSystem._Serialize(serializationObject, this);
  1083. serializationObject.activeParticleCount = this.activeParticleCount;
  1084. return serializationObject;
  1085. }
  1086. /**
  1087. * Parses a JSON object to create a GPU particle system.
  1088. * @param parsedParticleSystem The JSON object to parse
  1089. * @param scene The scene to create the particle system in
  1090. * @param rootUrl The root url to use to load external dependencies like texture
  1091. * @returns the parsed GPU particle system
  1092. */
  1093. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem {
  1094. var name = parsedParticleSystem.name;
  1095. var particleSystem = new GPUParticleSystem(name, {capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize}, scene);
  1096. if (parsedParticleSystem.activeParticleCount) {
  1097. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  1098. }
  1099. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  1100. return particleSystem;
  1101. }
  1102. }
  1103. }