gpuParticleSystem.ts 61 KB

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