gpuParticleSystem.ts 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  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 { IParticleSystem } from "./IParticleSystem";
  10. import { BaseParticleSystem } from "./baseParticleSystem";
  11. import { ParticleSystem } from "./particleSystem";
  12. import { BoxParticleEmitter } from "../Particles/EmitterTypes/boxParticleEmitter";
  13. import { IDisposable } from "../scene";
  14. import { Effect, IEffectCreationOptions } from "../Materials/effect";
  15. import { MaterialHelper } from "../Materials/materialHelper";
  16. import { ImageProcessingConfiguration } from "../Materials/imageProcessingConfiguration";
  17. import { RawTexture } from "../Materials/Textures/rawTexture";
  18. import { Constants } from "../Engines/constants";
  19. import { EngineStore } from "../Engines/engineStore";
  20. import { IAnimatable } from '../Animations/animatable.interface';
  21. import { CustomParticleEmitter } from './EmitterTypes/customParticleEmitter';
  22. import { ThinEngine } from '../Engines/thinEngine';
  23. declare type Scene = import("../scene").Scene;
  24. declare type Engine = import("../Engines/engine").Engine;
  25. declare type AbstractMesh = import("../Meshes/abstractMesh").AbstractMesh;
  26. import "../Shaders/gpuUpdateParticles.fragment";
  27. import "../Shaders/gpuUpdateParticles.vertex";
  28. import "../Shaders/gpuRenderParticles.fragment";
  29. import "../Shaders/gpuRenderParticles.vertex";
  30. /**
  31. * This represents a GPU particle system in Babylon
  32. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  33. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  34. */
  35. export class GPUParticleSystem extends BaseParticleSystem implements IDisposable, IParticleSystem, IAnimatable {
  36. /**
  37. * The layer mask we are rendering the particles through.
  38. */
  39. public layerMask: number = 0x0FFFFFFF;
  40. private _capacity: number;
  41. private _activeCount: number;
  42. private _currentActiveCount: number;
  43. private _accumulatedCount = 0;
  44. private _renderEffect: Effect;
  45. private _updateEffect: Effect;
  46. private _buffer0: Buffer;
  47. private _buffer1: Buffer;
  48. private _spriteBuffer: Buffer;
  49. private _updateVAO: Array<WebGLVertexArrayObject>;
  50. private _renderVAO: Array<WebGLVertexArrayObject>;
  51. private _targetIndex = 0;
  52. private _sourceBuffer: Buffer;
  53. private _targetBuffer: Buffer;
  54. private _currentRenderId = -1;
  55. private _started = false;
  56. private _stopped = false;
  57. private _timeDelta = 0;
  58. private _randomTexture: RawTexture;
  59. private _randomTexture2: RawTexture;
  60. private _attributesStrideSize: number;
  61. private _updateEffectOptions: IEffectCreationOptions;
  62. private _randomTextureSize: number;
  63. private _actualFrame = 0;
  64. private _customEffect: { [blendMode: number] : Nullable<Effect> };
  65. private readonly _rawTextureWidth = 256;
  66. /**
  67. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  68. */
  69. public static get IsSupported(): boolean {
  70. if (!EngineStore.LastCreatedEngine) {
  71. return false;
  72. }
  73. return EngineStore.LastCreatedEngine.webGLVersion > 1;
  74. }
  75. /**
  76. * An event triggered when the system is disposed.
  77. */
  78. public onDisposeObservable = new Observable<IParticleSystem>();
  79. /**
  80. * Gets the maximum number of particles active at the same time.
  81. * @returns The max number of active particles.
  82. */
  83. public getCapacity(): number {
  84. return this._capacity;
  85. }
  86. /**
  87. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  88. * to override the particles.
  89. */
  90. public forceDepthWrite = false;
  91. /**
  92. * Gets or set the number of active particles
  93. */
  94. public get activeParticleCount(): number {
  95. return this._activeCount;
  96. }
  97. public set activeParticleCount(value: number) {
  98. this._activeCount = Math.min(value, this._capacity);
  99. }
  100. private _preWarmDone = false;
  101. /**
  102. * Specifies if the particles are updated in emitter local space or world space.
  103. */
  104. public isLocal = false;
  105. /** Gets or sets a matrix to use to compute projection */
  106. public defaultProjectionMatrix: Matrix;
  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 && !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 && this._scene) {
  169. this._scene.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 https://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 sceneOrEngine The scene the particle system belongs to or the engine to use if no scene
  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. }>, sceneOrEngine: Scene | ThinEngine, isAnimationSheetEnabled: boolean = false, customEffect: Nullable<Effect> = null) {
  594. super(name);
  595. if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") {
  596. this._scene = (sceneOrEngine as Scene) || EngineStore.LastCreatedScene;
  597. this._engine = this._scene.getEngine();
  598. this.uniqueId = this._scene.getUniqueId();
  599. this._scene.particleSystems.push(this);
  600. } else {
  601. this._engine = (sceneOrEngine as ThinEngine);
  602. this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100);
  603. }
  604. this._customEffect = { 0: customEffect };
  605. // Setup the default processing configuration to the scene.
  606. this._attachImageProcessingConfiguration(null);
  607. if (!options.randomTextureSize) {
  608. delete options.randomTextureSize;
  609. }
  610. let fullOptions = {
  611. capacity: 50000,
  612. randomTextureSize: this._engine.getCaps().maxTextureSize,
  613. ...options
  614. };
  615. var optionsAsNumber = <number>options;
  616. if (isFinite(optionsAsNumber)) {
  617. fullOptions.capacity = optionsAsNumber;
  618. }
  619. this._capacity = fullOptions.capacity;
  620. this._activeCount = fullOptions.capacity;
  621. this._currentActiveCount = 0;
  622. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  623. this._updateEffectOptions = {
  624. attributes: ["position", "initialPosition", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  625. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  626. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  627. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  628. uniformBuffersNames: [],
  629. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  630. defines: "",
  631. fallbacks: null,
  632. onCompiled: null,
  633. onError: null,
  634. indexParameters: null,
  635. maxSimultaneousLights: 0,
  636. transformFeedbackVaryings: []
  637. };
  638. this.particleEmitterType = new BoxParticleEmitter();
  639. // Random data
  640. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  641. var d = [];
  642. for (var i = 0; i < maxTextureSize; ++i) {
  643. d.push(Math.random());
  644. d.push(Math.random());
  645. d.push(Math.random());
  646. d.push(Math.random());
  647. }
  648. this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, Constants.TEXTUREFORMAT_RGBA, sceneOrEngine, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE, Constants.TEXTURETYPE_FLOAT);
  649. this._randomTexture.wrapU = Constants.TEXTURE_WRAP_ADDRESSMODE;
  650. this._randomTexture.wrapV = Constants.TEXTURE_WRAP_ADDRESSMODE;
  651. d = [];
  652. for (var i = 0; i < maxTextureSize; ++i) {
  653. d.push(Math.random());
  654. d.push(Math.random());
  655. d.push(Math.random());
  656. d.push(Math.random());
  657. }
  658. this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, Constants.TEXTUREFORMAT_RGBA, sceneOrEngine, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE, Constants.TEXTURETYPE_FLOAT);
  659. this._randomTexture2.wrapU = Constants.TEXTURE_WRAP_ADDRESSMODE;
  660. this._randomTexture2.wrapV = Constants.TEXTURE_WRAP_ADDRESSMODE;
  661. this._randomTextureSize = maxTextureSize;
  662. }
  663. protected _reset() {
  664. this._releaseBuffers();
  665. }
  666. private _createUpdateVAO(source: Buffer): WebGLVertexArrayObject {
  667. let updateVertexBuffers: { [key: string]: VertexBuffer } = {};
  668. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  669. let offset = 3;
  670. if (this.particleEmitterType instanceof CustomParticleEmitter) {
  671. updateVertexBuffers["initialPosition"] = source.createVertexBuffer("initialPosition", offset, 3);
  672. offset += 3;
  673. }
  674. updateVertexBuffers["age"] = source.createVertexBuffer("age", offset, 1);
  675. offset += 1;
  676. updateVertexBuffers["life"] = source.createVertexBuffer("life", offset, 1);
  677. offset += 1;
  678. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", offset, 4);
  679. offset += 4;
  680. updateVertexBuffers["size"] = source.createVertexBuffer("size", offset, 3);
  681. offset += 3;
  682. if (!this._colorGradientsTexture) {
  683. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  684. offset += 4;
  685. }
  686. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  687. offset += 3;
  688. if (!this._isBillboardBased) {
  689. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  690. offset += 3;
  691. }
  692. if (this._angularSpeedGradientsTexture) {
  693. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  694. offset += 1;
  695. } else {
  696. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  697. offset += 2;
  698. }
  699. if (this._isAnimationSheetEnabled) {
  700. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  701. offset += 1;
  702. if (this.spriteRandomStartCell) {
  703. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  704. offset += 1;
  705. }
  706. }
  707. if (this.noiseTexture) {
  708. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  709. offset += 3;
  710. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  711. offset += 3;
  712. }
  713. let vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  714. this._engine.bindArrayBuffer(null);
  715. return vao;
  716. }
  717. private _createRenderVAO(source: Buffer, spriteSource: Buffer): WebGLVertexArrayObject {
  718. let renderVertexBuffers: { [key: string]: VertexBuffer } = {};
  719. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  720. let offset = 3;
  721. if (this.particleEmitterType instanceof CustomParticleEmitter) {
  722. offset += 3;
  723. }
  724. renderVertexBuffers["age"] = source.createVertexBuffer("age", offset, 1, this._attributesStrideSize, true);
  725. offset += 1;
  726. renderVertexBuffers["life"] = source.createVertexBuffer("life", offset, 1, this._attributesStrideSize, true);
  727. offset += 5;
  728. renderVertexBuffers["size"] = source.createVertexBuffer("size", offset, 3, this._attributesStrideSize, true);
  729. offset += 3;
  730. if (!this._colorGradientsTexture) {
  731. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  732. offset += 4;
  733. }
  734. if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  735. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  736. }
  737. offset += 3; // Direction
  738. if (!this._isBillboardBased) {
  739. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  740. offset += 3;
  741. }
  742. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  743. if (this._angularSpeedGradientsTexture) {
  744. offset++;
  745. } else {
  746. offset += 2;
  747. }
  748. if (this._isAnimationSheetEnabled) {
  749. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  750. offset += 1;
  751. if (this.spriteRandomStartCell) {
  752. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  753. offset += 1;
  754. }
  755. }
  756. if (this.noiseTexture) {
  757. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  758. offset += 3;
  759. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  760. offset += 3;
  761. }
  762. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  763. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  764. let vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._getEffect());
  765. this._engine.bindArrayBuffer(null);
  766. return vao;
  767. }
  768. private _initialize(force = false): void {
  769. if (this._buffer0 && !force) {
  770. return;
  771. }
  772. let engine = this._engine;
  773. var data = new Array<float>();
  774. this._attributesStrideSize = 21;
  775. this._targetIndex = 0;
  776. if (this.particleEmitterType instanceof CustomParticleEmitter) {
  777. this._attributesStrideSize += 3;
  778. }
  779. if (!this.isBillboardBased) {
  780. this._attributesStrideSize += 3;
  781. }
  782. if (this._colorGradientsTexture) {
  783. this._attributesStrideSize -= 4;
  784. }
  785. if (this._angularSpeedGradientsTexture) {
  786. this._attributesStrideSize -= 1;
  787. }
  788. if (this._isAnimationSheetEnabled) {
  789. this._attributesStrideSize += 1;
  790. if (this.spriteRandomStartCell) {
  791. this._attributesStrideSize += 1;
  792. }
  793. }
  794. if (this.noiseTexture) {
  795. this._attributesStrideSize += 6;
  796. }
  797. const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter;
  798. const tmpVector = TmpVectors.Vector3[0];
  799. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  800. // position
  801. data.push(0.0);
  802. data.push(0.0);
  803. data.push(0.0);
  804. if (usingCustomEmitter) {
  805. (this.particleEmitterType as CustomParticleEmitter).particlePositionGenerator(particleIndex, null, tmpVector);
  806. data.push(tmpVector.x);
  807. data.push(tmpVector.y);
  808. data.push(tmpVector.z);
  809. }
  810. // Age and life
  811. data.push(0.0); // create the particle as a dead one to create a new one at start
  812. data.push(0.0);
  813. // Seed
  814. data.push(Math.random());
  815. data.push(Math.random());
  816. data.push(Math.random());
  817. data.push(Math.random());
  818. // Size
  819. data.push(0.0);
  820. data.push(0.0);
  821. data.push(0.0);
  822. if (!this._colorGradientsTexture) {
  823. // color
  824. data.push(0.0);
  825. data.push(0.0);
  826. data.push(0.0);
  827. data.push(0.0);
  828. }
  829. // direction
  830. if (usingCustomEmitter) {
  831. (this.particleEmitterType as CustomParticleEmitter).particleDestinationGenerator(particleIndex, null, tmpVector);
  832. data.push(tmpVector.x);
  833. data.push(tmpVector.y);
  834. data.push(tmpVector.z);
  835. } else {
  836. data.push(0.0);
  837. data.push(0.0);
  838. data.push(0.0);
  839. }
  840. if (!this.isBillboardBased) {
  841. // initialDirection
  842. data.push(0.0);
  843. data.push(0.0);
  844. data.push(0.0);
  845. }
  846. // angle
  847. data.push(0.0);
  848. if (!this._angularSpeedGradientsTexture) {
  849. data.push(0.0);
  850. }
  851. if (this._isAnimationSheetEnabled) {
  852. data.push(0.0);
  853. if (this.spriteRandomStartCell) {
  854. data.push(0.0);
  855. }
  856. }
  857. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  858. data.push(Math.random());
  859. data.push(Math.random());
  860. data.push(Math.random());
  861. data.push(Math.random());
  862. data.push(Math.random());
  863. data.push(Math.random());
  864. }
  865. }
  866. // Sprite data
  867. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  868. -0.5, 0.5, 0, 1,
  869. -0.5, -0.5, 0, 0,
  870. 0.5, -0.5, 1, 0]);
  871. // Buffers
  872. this._buffer0 = new Buffer(engine, data, false, this._attributesStrideSize);
  873. this._buffer1 = new Buffer(engine, data, false, this._attributesStrideSize);
  874. this._spriteBuffer = new Buffer(engine, spriteData, false, 4);
  875. // Update VAO
  876. this._updateVAO = [];
  877. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  878. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  879. // Render VAO
  880. this._renderVAO = [];
  881. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  882. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  883. // Links
  884. this._sourceBuffer = this._buffer0;
  885. this._targetBuffer = this._buffer1;
  886. }
  887. /** @hidden */
  888. public _recreateUpdateEffect() {
  889. let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  890. if (this._isBillboardBased) {
  891. defines += "\n#define BILLBOARD";
  892. }
  893. if (this._colorGradientsTexture) {
  894. defines += "\n#define COLORGRADIENTS";
  895. }
  896. if (this._sizeGradientsTexture) {
  897. defines += "\n#define SIZEGRADIENTS";
  898. }
  899. if (this._angularSpeedGradientsTexture) {
  900. defines += "\n#define ANGULARSPEEDGRADIENTS";
  901. }
  902. if (this._velocityGradientsTexture) {
  903. defines += "\n#define VELOCITYGRADIENTS";
  904. }
  905. if (this._limitVelocityGradientsTexture) {
  906. defines += "\n#define LIMITVELOCITYGRADIENTS";
  907. }
  908. if (this._dragGradientsTexture) {
  909. defines += "\n#define DRAGGRADIENTS";
  910. }
  911. if (this.isAnimationSheetEnabled) {
  912. defines += "\n#define ANIMATESHEET";
  913. if (this.spriteRandomStartCell) {
  914. defines += "\n#define ANIMATESHEETRANDOMSTART";
  915. }
  916. }
  917. if (this.noiseTexture) {
  918. defines += "\n#define NOISE";
  919. }
  920. if (this.isLocal) {
  921. defines += "\n#define LOCAL";
  922. }
  923. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  924. return;
  925. }
  926. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition"];
  927. if (this.particleEmitterType instanceof CustomParticleEmitter) {
  928. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition");
  929. }
  930. this._updateEffectOptions.transformFeedbackVaryings.push("outAge");
  931. this._updateEffectOptions.transformFeedbackVaryings.push("outLife");
  932. this._updateEffectOptions.transformFeedbackVaryings.push("outSeed");
  933. this._updateEffectOptions.transformFeedbackVaryings.push("outSize");
  934. if (!this._colorGradientsTexture) {
  935. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  936. }
  937. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  938. if (!this._isBillboardBased) {
  939. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  940. }
  941. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  942. if (this.isAnimationSheetEnabled) {
  943. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  944. if (this.spriteRandomStartCell) {
  945. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  946. }
  947. }
  948. if (this.noiseTexture) {
  949. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  950. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  951. }
  952. this._updateEffectOptions.defines = defines;
  953. this._updateEffect = new Effect("gpuUpdateParticles", this._updateEffectOptions, this._engine);
  954. }
  955. private _getEffect(): Effect {
  956. return this.getCustomEffect() ?? this._renderEffect;
  957. }
  958. /**
  959. * Fill the defines array according to the current settings of the particle system
  960. * @param defines Array to be updated
  961. * @param blendMode blend mode to take into account when updating the array
  962. */
  963. public fillDefines(defines: Array<string>, blendMode: number = 0) {
  964. if (this._scene) {
  965. if (this._scene.clipPlane) {
  966. defines.push("#define CLIPPLANE");
  967. }
  968. if (this._scene.clipPlane2) {
  969. defines.push("#define CLIPPLANE2");
  970. }
  971. if (this._scene.clipPlane3) {
  972. defines.push("#define CLIPPLANE3");
  973. }
  974. if (this._scene.clipPlane4) {
  975. defines.push("#define CLIPPLANE4");
  976. }
  977. if (this._scene.clipPlane5) {
  978. defines.push("#define CLIPPLANE5");
  979. }
  980. if (this._scene.clipPlane6) {
  981. defines.push("#define CLIPPLANE6");
  982. }
  983. }
  984. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  985. defines.push("#define BLENDMULTIPLYMODE");
  986. }
  987. if (this.isLocal) {
  988. defines.push("#define LOCAL");
  989. }
  990. if (this._isBillboardBased) {
  991. defines.push("#define BILLBOARD");
  992. switch (this.billboardMode) {
  993. case ParticleSystem.BILLBOARDMODE_Y:
  994. defines.push("#define BILLBOARDY");
  995. break;
  996. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  997. defines.push("#define BILLBOARDSTRETCHED");
  998. break;
  999. case ParticleSystem.BILLBOARDMODE_ALL:
  1000. defines.push("#define BILLBOARDMODE_ALL");
  1001. break;
  1002. default:
  1003. break;
  1004. }
  1005. }
  1006. if (this._colorGradientsTexture) {
  1007. defines.push("#define COLORGRADIENTS");
  1008. }
  1009. if (this.isAnimationSheetEnabled) {
  1010. defines.push("#define ANIMATESHEET");
  1011. }
  1012. if (this._imageProcessingConfiguration) {
  1013. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  1014. defines.push("" + this._imageProcessingConfigurationDefines.toString());
  1015. }
  1016. }
  1017. /**
  1018. * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system
  1019. * @param uniforms Uniforms array to fill
  1020. * @param attributes Attributes array to fill
  1021. * @param samplers Samplers array to fill
  1022. */
  1023. public fillUniformsAttributesAndSamplerNames(uniforms: Array<string>, attributes: Array<string>, samplers: Array<string>) {
  1024. attributes.push("position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex");
  1025. uniforms.push("emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "sheetInfos", "translationPivot", "eyePosition");
  1026. samplers.push("diffuseSampler", "colorGradientSampler");
  1027. if (this._imageProcessingConfiguration) {
  1028. ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  1029. ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  1030. }
  1031. }
  1032. /** @hidden */
  1033. public _recreateRenderEffect(): Effect {
  1034. const customEffect = this.getCustomEffect();
  1035. if (customEffect) {
  1036. return customEffect;
  1037. }
  1038. let defines: Array<string> = [];
  1039. this.fillDefines(defines);
  1040. var join = defines.join("\n");
  1041. if (this._renderEffect && this._renderEffect.defines === join) {
  1042. return this._renderEffect;
  1043. }
  1044. var attributes: Array<string> = [];
  1045. var uniforms: Array<string> = [];
  1046. var samplers: Array<string> = [];
  1047. this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers);
  1048. this._renderEffect = new Effect("gpuRenderParticles",
  1049. attributes,
  1050. uniforms,
  1051. samplers, this._engine, join);
  1052. return this._renderEffect;
  1053. }
  1054. /**
  1055. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  1056. * @param preWarm defines if we are in the pre-warmimg phase
  1057. */
  1058. public animate(preWarm = false): void {
  1059. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1);
  1060. this._actualFrame += this._timeDelta;
  1061. if (!this._stopped) {
  1062. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  1063. this.stop();
  1064. }
  1065. }
  1066. }
  1067. private _createFactorGradientTexture(factorGradients: Nullable<IValueGradient[]>, textureName: string) {
  1068. let texture: RawTexture = (<any>this)[textureName];
  1069. if (!factorGradients || !factorGradients.length || texture) {
  1070. return;
  1071. }
  1072. let data = new Float32Array(this._rawTextureWidth);
  1073. for (var x = 0; x < this._rawTextureWidth; x++) {
  1074. var ratio = x / this._rawTextureWidth;
  1075. GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {
  1076. data[x] = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  1077. });
  1078. }
  1079. (<any>this)[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  1080. }
  1081. private _createSizeGradientTexture() {
  1082. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  1083. }
  1084. private _createAngularSpeedGradientTexture() {
  1085. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  1086. }
  1087. private _createVelocityGradientTexture() {
  1088. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  1089. }
  1090. private _createLimitVelocityGradientTexture() {
  1091. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  1092. }
  1093. private _createDragGradientTexture() {
  1094. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  1095. }
  1096. private _createColorGradientTexture() {
  1097. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  1098. return;
  1099. }
  1100. let data = new Uint8Array(this._rawTextureWidth * 4);
  1101. let tmpColor = TmpColors.Color4[0];
  1102. for (var x = 0; x < this._rawTextureWidth; x++) {
  1103. var ratio = x / this._rawTextureWidth;
  1104. GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  1105. Color4.LerpToRef((<ColorGradient>currentGradient).color1, (<ColorGradient>nextGradient).color1, scale, tmpColor);
  1106. data[x * 4] = tmpColor.r * 255;
  1107. data[x * 4 + 1] = tmpColor.g * 255;
  1108. data[x * 4 + 2] = tmpColor.b * 255;
  1109. data[x * 4 + 3] = tmpColor.a * 255;
  1110. });
  1111. }
  1112. this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  1113. }
  1114. /**
  1115. * Renders the particle system in its current state
  1116. * @param preWarm defines if the system should only update the particles but not render them
  1117. * @returns the current number of particles
  1118. */
  1119. public render(preWarm = false): number {
  1120. if (!this._started) {
  1121. return 0;
  1122. }
  1123. this._createColorGradientTexture();
  1124. this._createSizeGradientTexture();
  1125. this._createAngularSpeedGradientTexture();
  1126. this._createVelocityGradientTexture();
  1127. this._createLimitVelocityGradientTexture();
  1128. this._createDragGradientTexture();
  1129. this._recreateUpdateEffect();
  1130. this._recreateRenderEffect();
  1131. if (!this.isReady()) {
  1132. return 0;
  1133. }
  1134. if (!preWarm && this._scene) {
  1135. if (!this._preWarmDone && this.preWarmCycles) {
  1136. for (var index = 0; index < this.preWarmCycles; index++) {
  1137. this.animate(true);
  1138. this.render(true);
  1139. }
  1140. this._preWarmDone = true;
  1141. }
  1142. if (this._currentRenderId === this._scene.getFrameId()) {
  1143. return 0;
  1144. }
  1145. this._currentRenderId = this._scene.getFrameId();
  1146. }
  1147. // Get everything ready to render
  1148. this._initialize();
  1149. this._accumulatedCount += this.emitRate * this._timeDelta;
  1150. if (this._accumulatedCount > 1) {
  1151. var intPart = this._accumulatedCount | 0;
  1152. this._accumulatedCount -= intPart;
  1153. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  1154. }
  1155. if (!this._currentActiveCount) {
  1156. return 0;
  1157. }
  1158. // Enable update effect
  1159. this._engine.enableEffect(this._updateEffect);
  1160. var engine = this._engine as Engine;
  1161. if (!engine.setState) {
  1162. throw new Error("GPU particles cannot work with a full Engine. ThinEngine is not supported");
  1163. }
  1164. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  1165. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  1166. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  1167. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  1168. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  1169. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  1170. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  1171. if (!this._colorGradientsTexture) {
  1172. this._updateEffect.setDirectColor4("color1", this.color1);
  1173. this._updateEffect.setDirectColor4("color2", this.color2);
  1174. }
  1175. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  1176. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  1177. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  1178. this._updateEffect.setVector3("gravity", this.gravity);
  1179. if (this._sizeGradientsTexture) {
  1180. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  1181. }
  1182. if (this._angularSpeedGradientsTexture) {
  1183. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  1184. }
  1185. if (this._velocityGradientsTexture) {
  1186. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  1187. }
  1188. if (this._limitVelocityGradientsTexture) {
  1189. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  1190. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  1191. }
  1192. if (this._dragGradientsTexture) {
  1193. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  1194. }
  1195. if (this.particleEmitterType) {
  1196. this.particleEmitterType.applyToShader(this._updateEffect);
  1197. }
  1198. if (this._isAnimationSheetEnabled) {
  1199. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  1200. }
  1201. if (this.noiseTexture) {
  1202. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  1203. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  1204. }
  1205. let emitterWM: Matrix;
  1206. if ((<AbstractMesh>this.emitter).position) {
  1207. var emitterMesh = (<AbstractMesh>this.emitter);
  1208. emitterWM = emitterMesh.getWorldMatrix();
  1209. } else {
  1210. var emitterPosition = (<Vector3>this.emitter);
  1211. emitterWM = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  1212. }
  1213. if (!this.isLocal) {
  1214. this._updateEffect.setMatrix("emitterWM", emitterWM);
  1215. }
  1216. // Bind source VAO
  1217. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  1218. // Update
  1219. engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  1220. engine.setRasterizerState(false);
  1221. engine.beginTransformFeedback(true);
  1222. engine.drawArraysType(Constants.MATERIAL_PointListDrawMode, 0, this._currentActiveCount);
  1223. engine.endTransformFeedback();
  1224. engine.setRasterizerState(true);
  1225. engine.bindTransformFeedbackBuffer(null);
  1226. if (!preWarm) {
  1227. // Enable render effect
  1228. const effect = this._getEffect();
  1229. this._engine.enableEffect(effect);
  1230. let viewMatrix = this._scene?.getViewMatrix() || Matrix.IdentityReadOnly;
  1231. effect.setMatrix("view", viewMatrix);
  1232. effect.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene!.getProjectionMatrix());
  1233. effect.setTexture("diffuseSampler", this.particleTexture);
  1234. effect.setVector2("translationPivot", this.translationPivot);
  1235. effect.setVector3("worldOffset", this.worldOffset);
  1236. if (this.isLocal) {
  1237. effect.setMatrix("emitterWM", emitterWM);
  1238. }
  1239. if (this._colorGradientsTexture) {
  1240. effect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  1241. } else {
  1242. effect.setDirectColor4("colorDead", this.colorDead);
  1243. }
  1244. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1245. let baseSize = this.particleTexture.getBaseSize();
  1246. effect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  1247. }
  1248. if (this._isBillboardBased && this._scene) {
  1249. var camera = this._scene.activeCamera!;
  1250. effect.setVector3("eyePosition", camera.globalPosition);
  1251. }
  1252. const defines = effect.defines;
  1253. if (this._scene) {
  1254. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4 || this._scene.clipPlane5 || this._scene.clipPlane6) {
  1255. MaterialHelper.BindClipPlane(effect, this._scene);
  1256. }
  1257. }
  1258. if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) {
  1259. var invView = viewMatrix.clone();
  1260. invView.invert();
  1261. effect.setMatrix("invView", invView);
  1262. }
  1263. // image processing
  1264. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  1265. this._imageProcessingConfiguration.bind(effect);
  1266. }
  1267. // Draw order
  1268. switch (this.blendMode) {
  1269. case ParticleSystem.BLENDMODE_ADD:
  1270. this._engine.setAlphaMode(Constants.ALPHA_ADD);
  1271. break;
  1272. case ParticleSystem.BLENDMODE_ONEONE:
  1273. this._engine.setAlphaMode(Constants.ALPHA_ONEONE);
  1274. break;
  1275. case ParticleSystem.BLENDMODE_STANDARD:
  1276. this._engine.setAlphaMode(Constants.ALPHA_COMBINE);
  1277. break;
  1278. case ParticleSystem.BLENDMODE_MULTIPLY:
  1279. this._engine.setAlphaMode(Constants.ALPHA_MULTIPLY);
  1280. break;
  1281. }
  1282. if (this.forceDepthWrite) {
  1283. engine.setDepthWrite(true);
  1284. }
  1285. // Bind source VAO
  1286. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  1287. if (this._onBeforeDrawParticlesObservable) {
  1288. this._onBeforeDrawParticlesObservable.notifyObservers(effect);
  1289. }
  1290. // Render
  1291. this._engine.drawArraysType(Constants.MATERIAL_TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  1292. this._engine.setAlphaMode(Constants.ALPHA_DISABLE);
  1293. }
  1294. // Switch VAOs
  1295. this._targetIndex++;
  1296. if (this._targetIndex === 2) {
  1297. this._targetIndex = 0;
  1298. }
  1299. // Switch buffers
  1300. let tmpBuffer = this._sourceBuffer;
  1301. this._sourceBuffer = this._targetBuffer;
  1302. this._targetBuffer = tmpBuffer;
  1303. return this._currentActiveCount;
  1304. }
  1305. /**
  1306. * Rebuilds the particle system
  1307. */
  1308. public rebuild(): void {
  1309. this._initialize(true);
  1310. }
  1311. private _releaseBuffers() {
  1312. if (this._buffer0) {
  1313. this._buffer0.dispose();
  1314. (<any>this._buffer0) = null;
  1315. }
  1316. if (this._buffer1) {
  1317. this._buffer1.dispose();
  1318. (<any>this._buffer1) = null;
  1319. }
  1320. if (this._spriteBuffer) {
  1321. this._spriteBuffer.dispose();
  1322. (<any>this._spriteBuffer) = null;
  1323. }
  1324. }
  1325. private _releaseVAOs() {
  1326. if (!this._updateVAO) {
  1327. return;
  1328. }
  1329. for (var index = 0; index < this._updateVAO.length; index++) {
  1330. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  1331. }
  1332. this._updateVAO = [];
  1333. for (var index = 0; index < this._renderVAO.length; index++) {
  1334. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  1335. }
  1336. this._renderVAO = [];
  1337. }
  1338. /**
  1339. * Disposes the particle system and free the associated resources
  1340. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1341. */
  1342. public dispose(disposeTexture = true): void {
  1343. if (this._scene) {
  1344. var index = this._scene.particleSystems.indexOf(this);
  1345. if (index > -1) {
  1346. this._scene.particleSystems.splice(index, 1);
  1347. }
  1348. }
  1349. this._releaseBuffers();
  1350. this._releaseVAOs();
  1351. if (this._colorGradientsTexture) {
  1352. this._colorGradientsTexture.dispose();
  1353. (<any>this._colorGradientsTexture) = null;
  1354. }
  1355. if (this._sizeGradientsTexture) {
  1356. this._sizeGradientsTexture.dispose();
  1357. (<any>this._sizeGradientsTexture) = null;
  1358. }
  1359. if (this._angularSpeedGradientsTexture) {
  1360. this._angularSpeedGradientsTexture.dispose();
  1361. (<any>this._angularSpeedGradientsTexture) = null;
  1362. }
  1363. if (this._velocityGradientsTexture) {
  1364. this._velocityGradientsTexture.dispose();
  1365. (<any>this._velocityGradientsTexture) = null;
  1366. }
  1367. if (this._limitVelocityGradientsTexture) {
  1368. this._limitVelocityGradientsTexture.dispose();
  1369. (<any>this._limitVelocityGradientsTexture) = null;
  1370. }
  1371. if (this._dragGradientsTexture) {
  1372. this._dragGradientsTexture.dispose();
  1373. (<any>this._dragGradientsTexture) = null;
  1374. }
  1375. if (this._randomTexture) {
  1376. this._randomTexture.dispose();
  1377. (<any>this._randomTexture) = null;
  1378. }
  1379. if (this._randomTexture2) {
  1380. this._randomTexture2.dispose();
  1381. (<any>this._randomTexture2) = null;
  1382. }
  1383. if (disposeTexture && this.particleTexture) {
  1384. this.particleTexture.dispose();
  1385. this.particleTexture = null;
  1386. }
  1387. if (disposeTexture && this.noiseTexture) {
  1388. this.noiseTexture.dispose();
  1389. this.noiseTexture = null;
  1390. }
  1391. // Callback
  1392. this.onDisposeObservable.notifyObservers(this);
  1393. this.onDisposeObservable.clear();
  1394. }
  1395. /**
  1396. * Clones the particle system.
  1397. * @param name The name of the cloned object
  1398. * @param newEmitter The new emitter to use
  1399. * @returns the cloned particle system
  1400. */
  1401. public clone(name: string, newEmitter: any): GPUParticleSystem {
  1402. let serialization = this.serialize();
  1403. var result = GPUParticleSystem.Parse(serialization, this._scene || this._engine, "");
  1404. var custom = { ...this._customEffect };
  1405. result.name = name;
  1406. result._customEffect = custom;
  1407. if (newEmitter === undefined) {
  1408. newEmitter = this.emitter;
  1409. }
  1410. result.emitter = newEmitter;
  1411. result.noiseTexture = this.noiseTexture;
  1412. return result;
  1413. }
  1414. /**
  1415. * Serializes the particle system to a JSON object
  1416. * @param serializeTexture defines if the texture must be serialized as well
  1417. * @returns the JSON object
  1418. */
  1419. public serialize(serializeTexture = false): any {
  1420. var serializationObject: any = {};
  1421. ParticleSystem._Serialize(serializationObject, this, serializeTexture);
  1422. serializationObject.activeParticleCount = this.activeParticleCount;
  1423. serializationObject.randomTextureSize = this._randomTextureSize;
  1424. return serializationObject;
  1425. }
  1426. /**
  1427. * Parses a JSON object to create a GPU particle system.
  1428. * @param parsedParticleSystem The JSON object to parse
  1429. * @param sceneOrEngine The scene or the engine to create the particle system in
  1430. * @param rootUrl The root url to use to load external dependencies like texture
  1431. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  1432. * @returns the parsed GPU particle system
  1433. */
  1434. public static Parse(parsedParticleSystem: any, sceneOrEngine: Scene | ThinEngine, rootUrl: string, doNotStart = false): GPUParticleSystem {
  1435. var name = parsedParticleSystem.name;
  1436. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine);
  1437. if (parsedParticleSystem.activeParticleCount) {
  1438. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  1439. }
  1440. ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);
  1441. // Auto start
  1442. if (parsedParticleSystem.preventAutoStart) {
  1443. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  1444. }
  1445. if (!doNotStart && !particleSystem.preventAutoStart) {
  1446. particleSystem.start();
  1447. }
  1448. return particleSystem;
  1449. }
  1450. }