gpuParticleSystem.ts 67 KB

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