gpuParticleSystem.js 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. import { FactorGradient, ColorGradient, GradientHelper } from "../Misc/gradients.js";
  2. import { Observable } from "../Misc/observable.js";
  3. import { Vector3, Matrix, TmpVectors } from "../Maths/math.vector.js";
  4. import { Color4, TmpColors } from "../Maths/math.color.js";
  5. import { Scalar } from "../Maths/math.scalar.js";
  6. import { VertexBuffer, Buffer } from "../Buffers/buffer.js";
  7. import { BaseParticleSystem } from "./baseParticleSystem.js";
  8. import { ParticleSystem } from "./particleSystem.js";
  9. import { BoxParticleEmitter } from "../Particles/EmitterTypes/boxParticleEmitter.js";
  10. import { ImageProcessingConfiguration } from "../Materials/imageProcessingConfiguration.js";
  11. import { RawTexture } from "../Materials/Textures/rawTexture.js";
  12. import { EngineStore } from "../Engines/engineStore.js";
  13. import { CustomParticleEmitter } from "./EmitterTypes/customParticleEmitter.js";
  14. import { AbstractEngine } from "../Engines/abstractEngine.js";
  15. import { DrawWrapper } from "../Materials/drawWrapper.js";
  16. import { GetClass } from "../Misc/typeStore.js";
  17. import { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from "../Materials/clipPlaneMaterialHelper.js";
  18. import { Scene } from "../scene.js";
  19. import "../Engines/Extensions/engine.transformFeedback.js";
  20. import "../Shaders/gpuRenderParticles.fragment.js";
  21. import "../Shaders/gpuRenderParticles.vertex.js";
  22. import { BindFogParameters, BindLogDepth } from "../Materials/materialHelper.functions.js";
  23. import { CreateConeEmitter, CreateCylinderEmitter, CreateDirectedCylinderEmitter, CreateDirectedSphereEmitter, CreateHemisphericEmitter, CreatePointEmitter, CreateSphereEmitter, } from "./particleSystem.functions.js";
  24. /**
  25. * This represents a GPU particle system in Babylon
  26. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  27. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  28. */
  29. export class GPUParticleSystem extends BaseParticleSystem {
  30. /**
  31. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  32. */
  33. static get IsSupported() {
  34. if (!EngineStore.LastCreatedEngine) {
  35. return false;
  36. }
  37. const caps = EngineStore.LastCreatedEngine.getCaps();
  38. return caps.supportTransformFeedbacks || caps.supportComputeShaders;
  39. }
  40. _createIndexBuffer() {
  41. this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3]), undefined, "GPUParticleSystemLinesIndexBuffer");
  42. }
  43. /**
  44. * Gets the maximum number of particles active at the same time.
  45. * @returns The max number of active particles.
  46. */
  47. getCapacity() {
  48. return this._capacity;
  49. }
  50. /**
  51. * Gets or set the number of active particles
  52. * The value cannot be greater than "capacity" (if it is, it will be limited to "capacity").
  53. */
  54. get maxActiveParticleCount() {
  55. return this._maxActiveParticleCount;
  56. }
  57. set maxActiveParticleCount(value) {
  58. this._maxActiveParticleCount = Math.min(value, this._capacity);
  59. }
  60. /**
  61. * Gets or set the number of active particles
  62. * @deprecated Please use maxActiveParticleCount instead.
  63. */
  64. get activeParticleCount() {
  65. return this.maxActiveParticleCount;
  66. }
  67. set activeParticleCount(value) {
  68. this.maxActiveParticleCount = value;
  69. }
  70. /**
  71. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  72. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  73. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  74. * @returns the emitter
  75. */
  76. createPointEmitter(direction1, direction2) {
  77. const particleEmitter = CreatePointEmitter(direction1, direction2);
  78. this.particleEmitterType = particleEmitter;
  79. return particleEmitter;
  80. }
  81. /**
  82. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  83. * @param radius The radius of the hemisphere to emit from
  84. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  85. * @returns the emitter
  86. */
  87. createHemisphericEmitter(radius = 1, radiusRange = 1) {
  88. const particleEmitter = CreateHemisphericEmitter(radius, radiusRange);
  89. this.particleEmitterType = particleEmitter;
  90. return particleEmitter;
  91. }
  92. /**
  93. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  94. * @param radius The radius of the sphere to emit from
  95. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  96. * @returns the emitter
  97. */
  98. createSphereEmitter(radius = 1, radiusRange = 1) {
  99. const particleEmitter = CreateSphereEmitter(radius, radiusRange);
  100. this.particleEmitterType = particleEmitter;
  101. return particleEmitter;
  102. }
  103. /**
  104. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  105. * @param radius The radius of the sphere to emit from
  106. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  107. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  108. * @returns the emitter
  109. */
  110. createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) {
  111. const particleEmitter = CreateDirectedSphereEmitter(radius, direction1, direction2);
  112. this.particleEmitterType = particleEmitter;
  113. return particleEmitter;
  114. }
  115. /**
  116. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  117. * @param radius The radius of the emission cylinder
  118. * @param height The height of the emission cylinder
  119. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  120. * @param directionRandomizer How much to randomize the particle direction [0-1]
  121. * @returns the emitter
  122. */
  123. createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {
  124. const particleEmitter = CreateCylinderEmitter(radius, height, radiusRange, directionRandomizer);
  125. this.particleEmitterType = particleEmitter;
  126. return particleEmitter;
  127. }
  128. /**
  129. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  130. * @param radius The radius of the cylinder to emit from
  131. * @param height The height of the emission cylinder
  132. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  133. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  134. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  135. * @returns the emitter
  136. */
  137. createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) {
  138. const particleEmitter = CreateDirectedCylinderEmitter(radius, height, radiusRange, direction1, direction2);
  139. this.particleEmitterType = particleEmitter;
  140. return particleEmitter;
  141. }
  142. /**
  143. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  144. * @param radius The radius of the cone to emit from
  145. * @param angle The base angle of the cone
  146. * @returns the emitter
  147. */
  148. createConeEmitter(radius = 1, angle = Math.PI / 4) {
  149. const particleEmitter = CreateConeEmitter(radius, angle);
  150. this.particleEmitterType = particleEmitter;
  151. return particleEmitter;
  152. }
  153. /**
  154. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  155. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  156. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  157. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  158. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  159. * @returns the emitter
  160. */
  161. createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) {
  162. const particleEmitter = new BoxParticleEmitter();
  163. this.particleEmitterType = particleEmitter;
  164. this.direction1 = direction1;
  165. this.direction2 = direction2;
  166. this.minEmitBox = minEmitBox;
  167. this.maxEmitBox = maxEmitBox;
  168. return particleEmitter;
  169. }
  170. /**
  171. * Is this system ready to be used/rendered
  172. * @returns true if the system is ready
  173. */
  174. isReady() {
  175. if (!this.emitter ||
  176. (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) ||
  177. !this.particleTexture ||
  178. !this.particleTexture.isReady() ||
  179. this._rebuildingAfterContextLost) {
  180. return false;
  181. }
  182. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  183. if (!this._getWrapper(this.blendMode).effect.isReady()) {
  184. return false;
  185. }
  186. }
  187. else {
  188. if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {
  189. return false;
  190. }
  191. if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) {
  192. return false;
  193. }
  194. }
  195. if (!this._platform.isUpdateBufferCreated()) {
  196. this._recreateUpdateEffect();
  197. return false;
  198. }
  199. return this._platform.isUpdateBufferReady();
  200. }
  201. /**
  202. * Gets if the system has been started. (Note: this will still be true after stop is called)
  203. * @returns True if it has been started, otherwise false.
  204. */
  205. isStarted() {
  206. return this._started;
  207. }
  208. /**
  209. * Gets if the system has been stopped. (Note: rendering is still happening but the system is frozen)
  210. * @returns True if it has been stopped, otherwise false.
  211. */
  212. isStopped() {
  213. return this._stopped;
  214. }
  215. /**
  216. * Gets a boolean indicating that the system is stopping
  217. * @returns true if the system is currently stopping
  218. */
  219. isStopping() {
  220. return false; // Stop is immediate on GPU
  221. }
  222. /**
  223. * Gets the number of particles active at the same time.
  224. * @returns The number of active particles.
  225. */
  226. getActiveCount() {
  227. return this._currentActiveCount;
  228. }
  229. /**
  230. * Starts the particle system and begins to emit
  231. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  232. */
  233. start(delay = this.startDelay) {
  234. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  235. // eslint-disable-next-line no-throw-literal
  236. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  237. }
  238. if (delay) {
  239. setTimeout(() => {
  240. this.start(0);
  241. }, delay);
  242. return;
  243. }
  244. this._started = true;
  245. this._stopped = false;
  246. this._preWarmDone = false;
  247. // Animations
  248. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {
  249. this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  250. }
  251. }
  252. /**
  253. * Stops the particle system.
  254. */
  255. stop() {
  256. if (this._stopped) {
  257. return;
  258. }
  259. this._stopped = true;
  260. }
  261. /**
  262. * Remove all active particles
  263. */
  264. reset() {
  265. this._releaseBuffers();
  266. this._platform.releaseVertexBuffers();
  267. this._currentActiveCount = 0;
  268. this._targetIndex = 0;
  269. }
  270. /**
  271. * Returns the string "GPUParticleSystem"
  272. * @returns a string containing the class name
  273. */
  274. getClassName() {
  275. return "GPUParticleSystem";
  276. }
  277. /**
  278. * Gets the custom effect used to render the particles
  279. * @param blendMode Blend mode for which the effect should be retrieved
  280. * @returns The effect
  281. */
  282. getCustomEffect(blendMode = 0) {
  283. return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect;
  284. }
  285. _getCustomDrawWrapper(blendMode = 0) {
  286. return this._customWrappers[blendMode] ?? this._customWrappers[0];
  287. }
  288. /**
  289. * Sets the custom effect used to render the particles
  290. * @param effect The effect to set
  291. * @param blendMode Blend mode for which the effect should be set
  292. */
  293. setCustomEffect(effect, blendMode = 0) {
  294. this._customWrappers[blendMode] = new DrawWrapper(this._engine);
  295. this._customWrappers[blendMode].effect = effect;
  296. }
  297. /**
  298. * Observable that will be called just before the particles are drawn
  299. */
  300. get onBeforeDrawParticlesObservable() {
  301. if (!this._onBeforeDrawParticlesObservable) {
  302. this._onBeforeDrawParticlesObservable = new Observable();
  303. }
  304. return this._onBeforeDrawParticlesObservable;
  305. }
  306. /**
  307. * Gets the name of the particle vertex shader
  308. */
  309. get vertexShaderName() {
  310. return "gpuRenderParticles";
  311. }
  312. /**
  313. * Gets the vertex buffers used by the particle system
  314. * Should be called after render() has been called for the current frame so that the buffers returned are the ones that have been updated
  315. * in the current frame (there's a ping-pong between two sets of buffers - for a given frame, one set is used as the source and the other as the destination)
  316. */
  317. get vertexBuffers() {
  318. // We return the other buffers than those corresponding to this._targetIndex because it is assumed vertexBuffers will be called in the current frame
  319. // after render() has been called, meaning that the buffers have already been swapped and this._targetIndex points to the buffers that will be updated
  320. // in the next frame (and which are the sources in this frame) and (this._targetIndex ^ 1) points to the buffers that have been updated this frame
  321. // (and that will be the source buffers in the next frame)
  322. return this._renderVertexBuffers[this._targetIndex ^ 1];
  323. }
  324. /**
  325. * Gets the index buffer used by the particle system (null for GPU particle systems)
  326. */
  327. get indexBuffer() {
  328. return null;
  329. }
  330. _removeGradientAndTexture(gradient, gradients, texture) {
  331. super._removeGradientAndTexture(gradient, gradients, texture);
  332. this._releaseBuffers();
  333. return this;
  334. }
  335. /**
  336. * Adds a new color gradient
  337. * @param gradient defines the gradient to use (between 0 and 1)
  338. * @param color1 defines the color to affect to the specified gradient
  339. * @returns the current particle system
  340. */
  341. addColorGradient(gradient, color1) {
  342. if (!this._colorGradients) {
  343. this._colorGradients = [];
  344. }
  345. const colorGradient = new ColorGradient(gradient, color1);
  346. this._colorGradients.push(colorGradient);
  347. this._refreshColorGradient(true);
  348. this._releaseBuffers();
  349. return this;
  350. }
  351. _refreshColorGradient(reorder = false) {
  352. if (this._colorGradients) {
  353. if (reorder) {
  354. this._colorGradients.sort((a, b) => {
  355. if (a.gradient < b.gradient) {
  356. return -1;
  357. }
  358. else if (a.gradient > b.gradient) {
  359. return 1;
  360. }
  361. return 0;
  362. });
  363. }
  364. if (this._colorGradientsTexture) {
  365. this._colorGradientsTexture.dispose();
  366. this._colorGradientsTexture = null;
  367. }
  368. }
  369. }
  370. /** Force the system to rebuild all gradients that need to be resync */
  371. forceRefreshGradients() {
  372. this._refreshColorGradient();
  373. this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture");
  374. this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  375. this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture");
  376. this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  377. this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture");
  378. this.reset();
  379. }
  380. /**
  381. * Remove a specific color gradient
  382. * @param gradient defines the gradient to remove
  383. * @returns the current particle system
  384. */
  385. removeColorGradient(gradient) {
  386. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  387. this._colorGradientsTexture = null;
  388. return this;
  389. }
  390. /**
  391. * Resets the draw wrappers cache
  392. */
  393. resetDrawCache() {
  394. for (const blendMode in this._drawWrappers) {
  395. const drawWrapper = this._drawWrappers[blendMode];
  396. drawWrapper.drawContext?.reset();
  397. }
  398. }
  399. _addFactorGradient(factorGradients, gradient, factor) {
  400. const valueGradient = new FactorGradient(gradient, factor);
  401. factorGradients.push(valueGradient);
  402. this._releaseBuffers();
  403. }
  404. /**
  405. * Adds a new size gradient
  406. * @param gradient defines the gradient to use (between 0 and 1)
  407. * @param factor defines the size factor to affect to the specified gradient
  408. * @returns the current particle system
  409. */
  410. addSizeGradient(gradient, factor) {
  411. if (!this._sizeGradients) {
  412. this._sizeGradients = [];
  413. }
  414. this._addFactorGradient(this._sizeGradients, gradient, factor);
  415. this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", true);
  416. this._releaseBuffers();
  417. return this;
  418. }
  419. /**
  420. * Remove a specific size gradient
  421. * @param gradient defines the gradient to remove
  422. * @returns the current particle system
  423. */
  424. removeSizeGradient(gradient) {
  425. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  426. this._sizeGradientsTexture = null;
  427. return this;
  428. }
  429. _refreshFactorGradient(factorGradients, textureName, reorder = false) {
  430. if (!factorGradients) {
  431. return;
  432. }
  433. if (reorder) {
  434. factorGradients.sort((a, b) => {
  435. if (a.gradient < b.gradient) {
  436. return -1;
  437. }
  438. else if (a.gradient > b.gradient) {
  439. return 1;
  440. }
  441. return 0;
  442. });
  443. }
  444. const that = this;
  445. if (that[textureName]) {
  446. that[textureName].dispose();
  447. that[textureName] = null;
  448. }
  449. }
  450. /**
  451. * Adds a new angular speed gradient
  452. * @param gradient defines the gradient to use (between 0 and 1)
  453. * @param factor defines the angular speed to affect to the specified gradient
  454. * @returns the current particle system
  455. */
  456. addAngularSpeedGradient(gradient, factor) {
  457. if (!this._angularSpeedGradients) {
  458. this._angularSpeedGradients = [];
  459. }
  460. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  461. this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", true);
  462. this._releaseBuffers();
  463. return this;
  464. }
  465. /**
  466. * Remove a specific angular speed gradient
  467. * @param gradient defines the gradient to remove
  468. * @returns the current particle system
  469. */
  470. removeAngularSpeedGradient(gradient) {
  471. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  472. this._angularSpeedGradientsTexture = null;
  473. return this;
  474. }
  475. /**
  476. * Adds a new velocity gradient
  477. * @param gradient defines the gradient to use (between 0 and 1)
  478. * @param factor defines the velocity to affect to the specified gradient
  479. * @returns the current particle system
  480. */
  481. addVelocityGradient(gradient, factor) {
  482. if (!this._velocityGradients) {
  483. this._velocityGradients = [];
  484. }
  485. this._addFactorGradient(this._velocityGradients, gradient, factor);
  486. this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", true);
  487. this._releaseBuffers();
  488. return this;
  489. }
  490. /**
  491. * Remove a specific velocity gradient
  492. * @param gradient defines the gradient to remove
  493. * @returns the current particle system
  494. */
  495. removeVelocityGradient(gradient) {
  496. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  497. this._velocityGradientsTexture = null;
  498. return this;
  499. }
  500. /**
  501. * Adds a new limit velocity gradient
  502. * @param gradient defines the gradient to use (between 0 and 1)
  503. * @param factor defines the limit velocity value to affect to the specified gradient
  504. * @returns the current particle system
  505. */
  506. addLimitVelocityGradient(gradient, factor) {
  507. if (!this._limitVelocityGradients) {
  508. this._limitVelocityGradients = [];
  509. }
  510. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  511. this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", true);
  512. this._releaseBuffers();
  513. return this;
  514. }
  515. /**
  516. * Remove a specific limit velocity gradient
  517. * @param gradient defines the gradient to remove
  518. * @returns the current particle system
  519. */
  520. removeLimitVelocityGradient(gradient) {
  521. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  522. this._limitVelocityGradientsTexture = null;
  523. return this;
  524. }
  525. /**
  526. * Adds a new drag gradient
  527. * @param gradient defines the gradient to use (between 0 and 1)
  528. * @param factor defines the drag value to affect to the specified gradient
  529. * @returns the current particle system
  530. */
  531. addDragGradient(gradient, factor) {
  532. if (!this._dragGradients) {
  533. this._dragGradients = [];
  534. }
  535. this._addFactorGradient(this._dragGradients, gradient, factor);
  536. this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", true);
  537. this._releaseBuffers();
  538. return this;
  539. }
  540. /**
  541. * Remove a specific drag gradient
  542. * @param gradient defines the gradient to remove
  543. * @returns the current particle system
  544. */
  545. removeDragGradient(gradient) {
  546. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  547. this._dragGradientsTexture = null;
  548. return this;
  549. }
  550. /**
  551. * Not supported by GPUParticleSystem
  552. * @returns the current particle system
  553. */
  554. addEmitRateGradient() {
  555. // Do nothing as emit rate is not supported by GPUParticleSystem
  556. return this;
  557. }
  558. /**
  559. * Not supported by GPUParticleSystem
  560. * @returns the current particle system
  561. */
  562. removeEmitRateGradient() {
  563. // Do nothing as emit rate is not supported by GPUParticleSystem
  564. return this;
  565. }
  566. /**
  567. * Not supported by GPUParticleSystem
  568. * @returns the current particle system
  569. */
  570. addStartSizeGradient() {
  571. // Do nothing as start size is not supported by GPUParticleSystem
  572. return this;
  573. }
  574. /**
  575. * Not supported by GPUParticleSystem
  576. * @returns the current particle system
  577. */
  578. removeStartSizeGradient() {
  579. // Do nothing as start size is not supported by GPUParticleSystem
  580. return this;
  581. }
  582. /**
  583. * Not supported by GPUParticleSystem
  584. * @returns the current particle system
  585. */
  586. addColorRemapGradient() {
  587. // Do nothing as start size is not supported by GPUParticleSystem
  588. return this;
  589. }
  590. /**
  591. * Not supported by GPUParticleSystem
  592. * @returns the current particle system
  593. */
  594. removeColorRemapGradient() {
  595. // Do nothing as start size is not supported by GPUParticleSystem
  596. return this;
  597. }
  598. /**
  599. * Not supported by GPUParticleSystem
  600. * @returns the current particle system
  601. */
  602. addAlphaRemapGradient() {
  603. // Do nothing as start size is not supported by GPUParticleSystem
  604. return this;
  605. }
  606. /**
  607. * Not supported by GPUParticleSystem
  608. * @returns the current particle system
  609. */
  610. removeAlphaRemapGradient() {
  611. // Do nothing as start size is not supported by GPUParticleSystem
  612. return this;
  613. }
  614. /**
  615. * Not supported by GPUParticleSystem
  616. * @returns the current particle system
  617. */
  618. addRampGradient() {
  619. //Not supported by GPUParticleSystem
  620. return this;
  621. }
  622. /**
  623. * Not supported by GPUParticleSystem
  624. * @returns the current particle system
  625. */
  626. removeRampGradient() {
  627. //Not supported by GPUParticleSystem
  628. return this;
  629. }
  630. /**
  631. * Not supported by GPUParticleSystem
  632. * @returns the list of ramp gradients
  633. */
  634. getRampGradients() {
  635. return null;
  636. }
  637. /**
  638. * Not supported by GPUParticleSystem
  639. * Gets or sets a boolean indicating that ramp gradients must be used
  640. * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients
  641. */
  642. get useRampGradients() {
  643. //Not supported by GPUParticleSystem
  644. return false;
  645. }
  646. set useRampGradients(value) {
  647. //Not supported by GPUParticleSystem
  648. }
  649. /**
  650. * Not supported by GPUParticleSystem
  651. * @returns the current particle system
  652. */
  653. addLifeTimeGradient() {
  654. //Not supported by GPUParticleSystem
  655. return this;
  656. }
  657. /**
  658. * Not supported by GPUParticleSystem
  659. * @returns the current particle system
  660. */
  661. removeLifeTimeGradient() {
  662. //Not supported by GPUParticleSystem
  663. return this;
  664. }
  665. /**
  666. * Instantiates a GPU particle system.
  667. * 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.
  668. * @param name The name of the particle system
  669. * @param options The options used to create the system
  670. * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene
  671. * @param customEffect a custom effect used to change the way particles are rendered by default
  672. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  673. */
  674. constructor(name, options, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false) {
  675. super(name);
  676. /**
  677. * The layer mask we are rendering the particles through.
  678. */
  679. this.layerMask = 0x0fffffff;
  680. this._accumulatedCount = 0;
  681. this._renderVertexBuffers = [];
  682. this._targetIndex = 0;
  683. this._currentRenderId = -1;
  684. this._currentRenderingCameraUniqueId = -1;
  685. this._started = false;
  686. this._stopped = false;
  687. this._timeDelta = 0;
  688. /** Indicates that the update of particles is done in the animate function (and not in render). Default: false */
  689. this.updateInAnimate = false;
  690. this._actualFrame = 0;
  691. this._rawTextureWidth = 256;
  692. this._rebuildingAfterContextLost = false;
  693. /**
  694. * An event triggered when the system is disposed.
  695. */
  696. this.onDisposeObservable = new Observable();
  697. /**
  698. * An event triggered when the system is stopped
  699. */
  700. this.onStoppedObservable = new Observable();
  701. /**
  702. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  703. * to override the particles.
  704. */
  705. this.forceDepthWrite = false;
  706. this._preWarmDone = false;
  707. /**
  708. * Specifies if the particles are updated in emitter local space or world space.
  709. */
  710. this.isLocal = false;
  711. /** Indicates that the particle system is GPU based */
  712. this.isGPU = true;
  713. /** @internal */
  714. this._onBeforeDrawParticlesObservable = null;
  715. if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") {
  716. this._scene = sceneOrEngine || EngineStore.LastCreatedScene;
  717. this._engine = this._scene.getEngine();
  718. this.uniqueId = this._scene.getUniqueId();
  719. this._scene.particleSystems.push(this);
  720. }
  721. else {
  722. this._engine = sceneOrEngine;
  723. this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);
  724. }
  725. if (this._engine.getCaps().supportComputeShaders) {
  726. if (!GetClass("BABYLON.ComputeShaderParticleSystem")) {
  727. throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");
  728. }
  729. this._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem"))(this, this._engine);
  730. }
  731. else {
  732. if (!GetClass("BABYLON.WebGL2ParticleSystem")) {
  733. throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");
  734. }
  735. this._platform = new (GetClass("BABYLON.WebGL2ParticleSystem"))(this, this._engine);
  736. }
  737. this._customWrappers = { 0: new DrawWrapper(this._engine) };
  738. this._customWrappers[0].effect = customEffect;
  739. this._drawWrappers = { 0: new DrawWrapper(this._engine) };
  740. if (this._drawWrappers[0].drawContext) {
  741. this._drawWrappers[0].drawContext.useInstancing = true;
  742. }
  743. this._createIndexBuffer();
  744. // Setup the default processing configuration to the scene.
  745. this._attachImageProcessingConfiguration(null);
  746. options = options ?? {};
  747. if (!options.randomTextureSize) {
  748. delete options.randomTextureSize;
  749. }
  750. const fullOptions = {
  751. capacity: 50000,
  752. randomTextureSize: this._engine.getCaps().maxTextureSize,
  753. ...options,
  754. };
  755. const optionsAsNumber = options;
  756. if (isFinite(optionsAsNumber)) {
  757. fullOptions.capacity = optionsAsNumber;
  758. }
  759. this._capacity = fullOptions.capacity;
  760. this._maxActiveParticleCount = fullOptions.capacity;
  761. this._currentActiveCount = 0;
  762. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  763. this.particleEmitterType = new BoxParticleEmitter();
  764. // Random data
  765. const maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  766. let d = [];
  767. for (let i = 0; i < maxTextureSize; ++i) {
  768. d.push(Math.random());
  769. d.push(Math.random());
  770. d.push(Math.random());
  771. d.push(Math.random());
  772. }
  773. this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);
  774. this._randomTexture.name = "GPUParticleSystem_random1";
  775. this._randomTexture.wrapU = 1;
  776. this._randomTexture.wrapV = 1;
  777. d = [];
  778. for (let i = 0; i < maxTextureSize; ++i) {
  779. d.push(Math.random());
  780. d.push(Math.random());
  781. d.push(Math.random());
  782. d.push(Math.random());
  783. }
  784. this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);
  785. this._randomTexture2.name = "GPUParticleSystem_random2";
  786. this._randomTexture2.wrapU = 1;
  787. this._randomTexture2.wrapV = 1;
  788. this._randomTextureSize = maxTextureSize;
  789. }
  790. _reset() {
  791. this._releaseBuffers();
  792. }
  793. _createVertexBuffers(updateBuffer, renderBuffer, spriteSource) {
  794. const renderVertexBuffers = {};
  795. renderVertexBuffers["position"] = renderBuffer.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  796. let offset = 3;
  797. renderVertexBuffers["age"] = renderBuffer.createVertexBuffer("age", offset, 1, this._attributesStrideSize, true);
  798. offset += 1;
  799. renderVertexBuffers["size"] = renderBuffer.createVertexBuffer("size", offset, 3, this._attributesStrideSize, true);
  800. offset += 3;
  801. renderVertexBuffers["life"] = renderBuffer.createVertexBuffer("life", offset, 1, this._attributesStrideSize, true);
  802. offset += 1;
  803. offset += 4; // seed
  804. if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  805. renderVertexBuffers["direction"] = renderBuffer.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  806. }
  807. offset += 3; // direction
  808. if (this._platform.alignDataInBuffer) {
  809. offset += 1;
  810. }
  811. if (this.particleEmitterType instanceof CustomParticleEmitter) {
  812. offset += 3;
  813. if (this._platform.alignDataInBuffer) {
  814. offset += 1;
  815. }
  816. }
  817. if (!this._colorGradientsTexture) {
  818. renderVertexBuffers["color"] = renderBuffer.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  819. offset += 4;
  820. }
  821. if (!this._isBillboardBased) {
  822. renderVertexBuffers["initialDirection"] = renderBuffer.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  823. offset += 3;
  824. if (this._platform.alignDataInBuffer) {
  825. offset += 1;
  826. }
  827. }
  828. if (this.noiseTexture) {
  829. renderVertexBuffers["noiseCoordinates1"] = renderBuffer.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  830. offset += 3;
  831. if (this._platform.alignDataInBuffer) {
  832. offset += 1;
  833. }
  834. renderVertexBuffers["noiseCoordinates2"] = renderBuffer.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  835. offset += 3;
  836. if (this._platform.alignDataInBuffer) {
  837. offset += 1;
  838. }
  839. }
  840. renderVertexBuffers["angle"] = renderBuffer.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  841. if (this._angularSpeedGradientsTexture) {
  842. offset++;
  843. }
  844. else {
  845. offset += 2;
  846. }
  847. if (this._isAnimationSheetEnabled) {
  848. renderVertexBuffers["cellIndex"] = renderBuffer.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  849. offset += 1;
  850. if (this.spriteRandomStartCell) {
  851. renderVertexBuffers["cellStartOffset"] = renderBuffer.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  852. offset += 1;
  853. }
  854. }
  855. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  856. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  857. this._renderVertexBuffers.push(renderVertexBuffers);
  858. this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers);
  859. this.resetDrawCache();
  860. }
  861. _initialize(force = false) {
  862. if (this._buffer0 && !force) {
  863. return;
  864. }
  865. const engine = this._engine;
  866. const data = [];
  867. this._attributesStrideSize = 21;
  868. this._targetIndex = 0;
  869. if (this._platform.alignDataInBuffer) {
  870. this._attributesStrideSize += 1;
  871. }
  872. if (this.particleEmitterType instanceof CustomParticleEmitter) {
  873. this._attributesStrideSize += 3;
  874. if (this._platform.alignDataInBuffer) {
  875. this._attributesStrideSize += 1;
  876. }
  877. }
  878. if (!this.isBillboardBased) {
  879. this._attributesStrideSize += 3;
  880. if (this._platform.alignDataInBuffer) {
  881. this._attributesStrideSize += 1;
  882. }
  883. }
  884. if (this._colorGradientsTexture) {
  885. this._attributesStrideSize -= 4;
  886. }
  887. if (this._angularSpeedGradientsTexture) {
  888. this._attributesStrideSize -= 1;
  889. }
  890. if (this._isAnimationSheetEnabled) {
  891. this._attributesStrideSize += 1;
  892. if (this.spriteRandomStartCell) {
  893. this._attributesStrideSize += 1;
  894. }
  895. }
  896. if (this.noiseTexture) {
  897. this._attributesStrideSize += 6;
  898. if (this._platform.alignDataInBuffer) {
  899. this._attributesStrideSize += 2;
  900. }
  901. }
  902. if (this._platform.alignDataInBuffer) {
  903. this._attributesStrideSize += 3 - ((this._attributesStrideSize + 3) & 3); // round to multiple of 4
  904. }
  905. const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter;
  906. const tmpVector = TmpVectors.Vector3[0];
  907. let offset = 0;
  908. for (let particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  909. // position
  910. data.push(0.0);
  911. data.push(0.0);
  912. data.push(0.0);
  913. // Age
  914. data.push(0.0); // create the particle as a dead one to create a new one at start
  915. // Size
  916. data.push(0.0);
  917. data.push(0.0);
  918. data.push(0.0);
  919. // life
  920. data.push(0.0);
  921. // Seed
  922. data.push(Math.random());
  923. data.push(Math.random());
  924. data.push(Math.random());
  925. data.push(Math.random());
  926. // direction
  927. if (usingCustomEmitter) {
  928. this.particleEmitterType.particleDestinationGenerator(particleIndex, null, tmpVector);
  929. data.push(tmpVector.x);
  930. data.push(tmpVector.y);
  931. data.push(tmpVector.z);
  932. }
  933. else {
  934. data.push(0.0);
  935. data.push(0.0);
  936. data.push(0.0);
  937. }
  938. if (this._platform.alignDataInBuffer) {
  939. data.push(0.0); // dummy0
  940. }
  941. offset += 16; // position, age, size, life, seed, direction, dummy0
  942. if (usingCustomEmitter) {
  943. this.particleEmitterType.particlePositionGenerator(particleIndex, null, tmpVector);
  944. data.push(tmpVector.x);
  945. data.push(tmpVector.y);
  946. data.push(tmpVector.z);
  947. if (this._platform.alignDataInBuffer) {
  948. data.push(0.0); // dummy1
  949. }
  950. offset += 4;
  951. }
  952. if (!this._colorGradientsTexture) {
  953. // color
  954. data.push(0.0);
  955. data.push(0.0);
  956. data.push(0.0);
  957. data.push(0.0);
  958. offset += 4;
  959. }
  960. if (!this.isBillboardBased) {
  961. // initialDirection
  962. data.push(0.0);
  963. data.push(0.0);
  964. data.push(0.0);
  965. if (this._platform.alignDataInBuffer) {
  966. data.push(0.0); // dummy2
  967. }
  968. offset += 4;
  969. }
  970. if (this.noiseTexture) {
  971. // Random coordinates for reading into noise texture
  972. data.push(Math.random());
  973. data.push(Math.random());
  974. data.push(Math.random());
  975. if (this._platform.alignDataInBuffer) {
  976. data.push(0.0); // dummy3
  977. }
  978. data.push(Math.random());
  979. data.push(Math.random());
  980. data.push(Math.random());
  981. if (this._platform.alignDataInBuffer) {
  982. data.push(0.0); // dummy4
  983. }
  984. offset += 8;
  985. }
  986. // angle
  987. data.push(0.0);
  988. offset += 1;
  989. if (!this._angularSpeedGradientsTexture) {
  990. data.push(0.0);
  991. offset += 1;
  992. }
  993. if (this._isAnimationSheetEnabled) {
  994. data.push(0.0);
  995. offset += 1;
  996. if (this.spriteRandomStartCell) {
  997. data.push(0.0);
  998. offset += 1;
  999. }
  1000. }
  1001. if (this._platform.alignDataInBuffer) {
  1002. let numDummies = 3 - ((offset + 3) & 3);
  1003. offset += numDummies;
  1004. while (numDummies-- > 0) {
  1005. data.push(0.0);
  1006. }
  1007. }
  1008. }
  1009. // Sprite data
  1010. const spriteData = new Float32Array([0.5, 0.5, 1, 1, -0.5, 0.5, 0, 1, 0.5, -0.5, 1, 0, -0.5, -0.5, 0, 0]);
  1011. const bufferData1 = this._platform.createParticleBuffer(data);
  1012. const bufferData2 = this._platform.createParticleBuffer(data);
  1013. // Buffers
  1014. this._buffer0 = new Buffer(engine, bufferData1, false, this._attributesStrideSize);
  1015. this._buffer1 = new Buffer(engine, bufferData2, false, this._attributesStrideSize);
  1016. this._spriteBuffer = new Buffer(engine, spriteData, false, 4);
  1017. // Update & Render vertex buffers
  1018. this._renderVertexBuffers = [];
  1019. this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer);
  1020. this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer);
  1021. // Links
  1022. this._sourceBuffer = this._buffer0;
  1023. this._targetBuffer = this._buffer1;
  1024. }
  1025. /** @internal */
  1026. _recreateUpdateEffect() {
  1027. this._createColorGradientTexture();
  1028. this._createSizeGradientTexture();
  1029. this._createAngularSpeedGradientTexture();
  1030. this._createVelocityGradientTexture();
  1031. this._createLimitVelocityGradientTexture();
  1032. this._createDragGradientTexture();
  1033. let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  1034. if (this._isBillboardBased) {
  1035. defines += "\n#define BILLBOARD";
  1036. }
  1037. if (this._colorGradientsTexture) {
  1038. defines += "\n#define COLORGRADIENTS";
  1039. }
  1040. if (this._sizeGradientsTexture) {
  1041. defines += "\n#define SIZEGRADIENTS";
  1042. }
  1043. if (this._angularSpeedGradientsTexture) {
  1044. defines += "\n#define ANGULARSPEEDGRADIENTS";
  1045. }
  1046. if (this._velocityGradientsTexture) {
  1047. defines += "\n#define VELOCITYGRADIENTS";
  1048. }
  1049. if (this._limitVelocityGradientsTexture) {
  1050. defines += "\n#define LIMITVELOCITYGRADIENTS";
  1051. }
  1052. if (this._dragGradientsTexture) {
  1053. defines += "\n#define DRAGGRADIENTS";
  1054. }
  1055. if (this.isAnimationSheetEnabled) {
  1056. defines += "\n#define ANIMATESHEET";
  1057. if (this.spriteRandomStartCell) {
  1058. defines += "\n#define ANIMATESHEETRANDOMSTART";
  1059. }
  1060. }
  1061. if (this.noiseTexture) {
  1062. defines += "\n#define NOISE";
  1063. }
  1064. if (this.isLocal) {
  1065. defines += "\n#define LOCAL";
  1066. }
  1067. if (this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === defines) {
  1068. return this._platform.isUpdateBufferReady();
  1069. }
  1070. this._cachedUpdateDefines = defines;
  1071. this._updateBuffer = this._platform.createUpdateBuffer(defines);
  1072. return this._platform.isUpdateBufferReady();
  1073. }
  1074. /**
  1075. * @internal
  1076. */
  1077. _getWrapper(blendMode) {
  1078. const customWrapper = this._getCustomDrawWrapper(blendMode);
  1079. if (customWrapper?.effect) {
  1080. return customWrapper;
  1081. }
  1082. const defines = [];
  1083. this.fillDefines(defines, blendMode);
  1084. // Effect
  1085. let drawWrapper = this._drawWrappers[blendMode];
  1086. if (!drawWrapper) {
  1087. drawWrapper = new DrawWrapper(this._engine);
  1088. if (drawWrapper.drawContext) {
  1089. drawWrapper.drawContext.useInstancing = true;
  1090. }
  1091. this._drawWrappers[blendMode] = drawWrapper;
  1092. }
  1093. const join = defines.join("\n");
  1094. if (drawWrapper.defines !== join) {
  1095. const attributes = [];
  1096. const uniforms = [];
  1097. const samplers = [];
  1098. this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers);
  1099. drawWrapper.setEffect(this._engine.createEffect("gpuRenderParticles", attributes, uniforms, samplers, join), join);
  1100. }
  1101. return drawWrapper;
  1102. }
  1103. /**
  1104. * @internal
  1105. */
  1106. static _GetAttributeNamesOrOptions(hasColorGradients = false, isAnimationSheetEnabled = false, isBillboardBased = false, isBillboardStretched = false) {
  1107. const attributeNamesOrOptions = [VertexBuffer.PositionKind, "age", "life", "size", "angle"];
  1108. if (!hasColorGradients) {
  1109. attributeNamesOrOptions.push(VertexBuffer.ColorKind);
  1110. }
  1111. if (isAnimationSheetEnabled) {
  1112. attributeNamesOrOptions.push("cellIndex");
  1113. }
  1114. if (!isBillboardBased) {
  1115. attributeNamesOrOptions.push("initialDirection");
  1116. }
  1117. if (isBillboardStretched) {
  1118. attributeNamesOrOptions.push("direction");
  1119. }
  1120. attributeNamesOrOptions.push("offset", VertexBuffer.UVKind);
  1121. return attributeNamesOrOptions;
  1122. }
  1123. /**
  1124. * @internal
  1125. */
  1126. static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) {
  1127. const effectCreationOption = ["emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "translationPivot", "eyePosition"];
  1128. addClipPlaneUniforms(effectCreationOption);
  1129. if (isAnimationSheetEnabled) {
  1130. effectCreationOption.push("sheetInfos");
  1131. }
  1132. if (useLogarithmicDepth) {
  1133. effectCreationOption.push("logarithmicDepthConstant");
  1134. }
  1135. if (applyFog) {
  1136. effectCreationOption.push("vFogInfos");
  1137. effectCreationOption.push("vFogColor");
  1138. }
  1139. return effectCreationOption;
  1140. }
  1141. /**
  1142. * Fill the defines array according to the current settings of the particle system
  1143. * @param defines Array to be updated
  1144. * @param blendMode blend mode to take into account when updating the array
  1145. */
  1146. fillDefines(defines, blendMode = 0) {
  1147. if (this._scene) {
  1148. prepareStringDefinesForClipPlanes(this, this._scene, defines);
  1149. if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE) {
  1150. defines.push("#define FOG");
  1151. }
  1152. }
  1153. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  1154. defines.push("#define BLENDMULTIPLYMODE");
  1155. }
  1156. if (this.isLocal) {
  1157. defines.push("#define LOCAL");
  1158. }
  1159. if (this.useLogarithmicDepth) {
  1160. defines.push("#define LOGARITHMICDEPTH");
  1161. }
  1162. if (this._isBillboardBased) {
  1163. defines.push("#define BILLBOARD");
  1164. switch (this.billboardMode) {
  1165. case ParticleSystem.BILLBOARDMODE_Y:
  1166. defines.push("#define BILLBOARDY");
  1167. break;
  1168. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  1169. defines.push("#define BILLBOARDSTRETCHED");
  1170. break;
  1171. case ParticleSystem.BILLBOARDMODE_ALL:
  1172. defines.push("#define BILLBOARDMODE_ALL");
  1173. break;
  1174. default:
  1175. break;
  1176. }
  1177. }
  1178. if (this._colorGradientsTexture) {
  1179. defines.push("#define COLORGRADIENTS");
  1180. }
  1181. if (this.isAnimationSheetEnabled) {
  1182. defines.push("#define ANIMATESHEET");
  1183. }
  1184. if (this._imageProcessingConfiguration) {
  1185. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  1186. defines.push("" + this._imageProcessingConfigurationDefines.toString());
  1187. }
  1188. }
  1189. /**
  1190. * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system
  1191. * @param uniforms Uniforms array to fill
  1192. * @param attributes Attributes array to fill
  1193. * @param samplers Samplers array to fill
  1194. */
  1195. fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {
  1196. attributes.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED));
  1197. uniforms.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog));
  1198. samplers.push("diffuseSampler", "colorGradientSampler");
  1199. if (this._imageProcessingConfiguration) {
  1200. ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  1201. ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  1202. }
  1203. }
  1204. /**
  1205. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  1206. * @param preWarm defines if we are in the pre-warmimg phase
  1207. */
  1208. animate(preWarm = false) {
  1209. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1);
  1210. this._actualFrame += this._timeDelta;
  1211. if (!this._stopped) {
  1212. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  1213. this.stop();
  1214. }
  1215. }
  1216. if (this.updateInAnimate) {
  1217. this._update();
  1218. }
  1219. }
  1220. _createFactorGradientTexture(factorGradients, textureName) {
  1221. const texture = this[textureName];
  1222. if (!factorGradients || !factorGradients.length || texture) {
  1223. return;
  1224. }
  1225. const data = new Float32Array(this._rawTextureWidth);
  1226. for (let x = 0; x < this._rawTextureWidth; x++) {
  1227. const ratio = x / this._rawTextureWidth;
  1228. GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {
  1229. data[x] = Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  1230. });
  1231. }
  1232. this[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, 1);
  1233. this[textureName].name = textureName.substring(1);
  1234. }
  1235. _createSizeGradientTexture() {
  1236. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  1237. }
  1238. _createAngularSpeedGradientTexture() {
  1239. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  1240. }
  1241. _createVelocityGradientTexture() {
  1242. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  1243. }
  1244. _createLimitVelocityGradientTexture() {
  1245. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  1246. }
  1247. _createDragGradientTexture() {
  1248. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  1249. }
  1250. _createColorGradientTexture() {
  1251. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  1252. return;
  1253. }
  1254. const data = new Uint8Array(this._rawTextureWidth * 4);
  1255. const tmpColor = TmpColors.Color4[0];
  1256. for (let x = 0; x < this._rawTextureWidth; x++) {
  1257. const ratio = x / this._rawTextureWidth;
  1258. GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  1259. Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  1260. data[x * 4] = tmpColor.r * 255;
  1261. data[x * 4 + 1] = tmpColor.g * 255;
  1262. data[x * 4 + 2] = tmpColor.b * 255;
  1263. data[x * 4 + 3] = tmpColor.a * 255;
  1264. });
  1265. }
  1266. this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);
  1267. this._colorGradientsTexture.name = "colorGradients";
  1268. }
  1269. _render(blendMode, emitterWM) {
  1270. // Enable render effect
  1271. const drawWrapper = this._getWrapper(blendMode);
  1272. const effect = drawWrapper.effect;
  1273. this._engine.enableEffect(drawWrapper);
  1274. const viewMatrix = this._scene?.getViewMatrix() || Matrix.IdentityReadOnly;
  1275. effect.setMatrix("view", viewMatrix);
  1276. effect.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix());
  1277. effect.setTexture("diffuseSampler", this.particleTexture);
  1278. effect.setVector2("translationPivot", this.translationPivot);
  1279. effect.setVector3("worldOffset", this.worldOffset);
  1280. if (this.isLocal) {
  1281. effect.setMatrix("emitterWM", emitterWM);
  1282. }
  1283. if (this._colorGradientsTexture) {
  1284. effect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  1285. }
  1286. else {
  1287. effect.setDirectColor4("colorDead", this.colorDead);
  1288. }
  1289. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1290. const baseSize = this.particleTexture.getBaseSize();
  1291. effect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  1292. }
  1293. if (this._isBillboardBased && this._scene) {
  1294. const camera = this._scene.activeCamera;
  1295. effect.setVector3("eyePosition", camera.globalPosition);
  1296. }
  1297. const defines = effect.defines;
  1298. if (this._scene) {
  1299. bindClipPlane(effect, this, this._scene);
  1300. if (this.applyFog) {
  1301. BindFogParameters(this._scene, undefined, effect);
  1302. }
  1303. }
  1304. if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) {
  1305. const invView = viewMatrix.clone();
  1306. invView.invert();
  1307. effect.setMatrix("invView", invView);
  1308. }
  1309. // Log. depth
  1310. if (this.useLogarithmicDepth && this._scene) {
  1311. BindLogDepth(defines, effect, this._scene);
  1312. }
  1313. // image processing
  1314. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  1315. this._imageProcessingConfiguration.bind(effect);
  1316. }
  1317. // Draw order
  1318. switch (blendMode) {
  1319. case ParticleSystem.BLENDMODE_ADD:
  1320. this._engine.setAlphaMode(1);
  1321. break;
  1322. case ParticleSystem.BLENDMODE_ONEONE:
  1323. this._engine.setAlphaMode(6);
  1324. break;
  1325. case ParticleSystem.BLENDMODE_STANDARD:
  1326. this._engine.setAlphaMode(2);
  1327. break;
  1328. case ParticleSystem.BLENDMODE_MULTIPLY:
  1329. this._engine.setAlphaMode(4);
  1330. break;
  1331. }
  1332. // Bind source VAO
  1333. this._platform.bindDrawBuffers(this._targetIndex, effect, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null);
  1334. if (this._onBeforeDrawParticlesObservable) {
  1335. this._onBeforeDrawParticlesObservable.notifyObservers(effect);
  1336. }
  1337. // Render
  1338. if (this._scene?.forceWireframe) {
  1339. this._engine.drawElementsType(6, 0, 10, this._currentActiveCount);
  1340. }
  1341. else {
  1342. this._engine.drawArraysType(7, 0, 4, this._currentActiveCount);
  1343. }
  1344. this._engine.setAlphaMode(0);
  1345. if (this._scene?.forceWireframe) {
  1346. this._engine.unbindInstanceAttributes();
  1347. }
  1348. return this._currentActiveCount;
  1349. }
  1350. /** @internal */
  1351. _update(emitterWM) {
  1352. if (!this.emitter || !this._targetBuffer) {
  1353. return;
  1354. }
  1355. if (!this._recreateUpdateEffect() || this._rebuildingAfterContextLost) {
  1356. return;
  1357. }
  1358. if (!emitterWM) {
  1359. if (this.emitter.position) {
  1360. const emitterMesh = this.emitter;
  1361. emitterWM = emitterMesh.getWorldMatrix();
  1362. }
  1363. else {
  1364. const emitterPosition = this.emitter;
  1365. emitterWM = TmpVectors.Matrix[0];
  1366. Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);
  1367. }
  1368. }
  1369. this._platform.preUpdateParticleBuffer();
  1370. this._updateBuffer.setFloat("currentCount", this._currentActiveCount);
  1371. this._updateBuffer.setFloat("timeDelta", this._timeDelta);
  1372. this._updateBuffer.setFloat("stopFactor", this._stopped ? 0 : 1);
  1373. this._updateBuffer.setInt("randomTextureSize", this._randomTextureSize);
  1374. this._updateBuffer.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  1375. this._updateBuffer.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  1376. if (!this._colorGradientsTexture) {
  1377. this._updateBuffer.setDirectColor4("color1", this.color1);
  1378. this._updateBuffer.setDirectColor4("color2", this.color2);
  1379. }
  1380. this._updateBuffer.setFloat2("sizeRange", this.minSize, this.maxSize);
  1381. this._updateBuffer.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  1382. this._updateBuffer.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  1383. this._updateBuffer.setVector3("gravity", this.gravity);
  1384. if (this._limitVelocityGradientsTexture) {
  1385. this._updateBuffer.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  1386. }
  1387. if (this.particleEmitterType) {
  1388. this.particleEmitterType.applyToShader(this._updateBuffer);
  1389. }
  1390. if (this._isAnimationSheetEnabled) {
  1391. this._updateBuffer.setFloat4("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0);
  1392. }
  1393. if (this.noiseTexture) {
  1394. this._updateBuffer.setVector3("noiseStrength", this.noiseStrength);
  1395. }
  1396. if (!this.isLocal) {
  1397. this._updateBuffer.setMatrix("emitterWM", emitterWM);
  1398. }
  1399. this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount);
  1400. // Switch VAOs
  1401. this._targetIndex++;
  1402. if (this._targetIndex === 2) {
  1403. this._targetIndex = 0;
  1404. }
  1405. // Switch buffers
  1406. const tmpBuffer = this._sourceBuffer;
  1407. this._sourceBuffer = this._targetBuffer;
  1408. this._targetBuffer = tmpBuffer;
  1409. }
  1410. /**
  1411. * Renders the particle system in its current state
  1412. * @param preWarm defines if the system should only update the particles but not render them
  1413. * @param forceUpdateOnly if true, force to only update the particles and never display them (meaning, even if preWarm=false, when forceUpdateOnly=true the particles won't be displayed)
  1414. * @returns the current number of particles
  1415. */
  1416. render(preWarm = false, forceUpdateOnly = false) {
  1417. if (!this._started) {
  1418. return 0;
  1419. }
  1420. if (!this.isReady()) {
  1421. return 0;
  1422. }
  1423. if (!preWarm && this._scene) {
  1424. if (!this._preWarmDone && this.preWarmCycles) {
  1425. for (let index = 0; index < this.preWarmCycles; index++) {
  1426. this.animate(true);
  1427. this.render(true, true);
  1428. }
  1429. this._preWarmDone = true;
  1430. }
  1431. if (this._currentRenderId === this._scene.getRenderId() &&
  1432. (!this._scene.activeCamera || (this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId))) {
  1433. return 0;
  1434. }
  1435. this._currentRenderId = this._scene.getRenderId();
  1436. if (this._scene.activeCamera) {
  1437. this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId;
  1438. }
  1439. }
  1440. // Get everything ready to render
  1441. this._initialize();
  1442. this._accumulatedCount += this.emitRate * this._timeDelta;
  1443. if (this._accumulatedCount > 1) {
  1444. const intPart = this._accumulatedCount | 0;
  1445. this._accumulatedCount -= intPart;
  1446. this._currentActiveCount += intPart;
  1447. }
  1448. this._currentActiveCount = Math.min(this._maxActiveParticleCount, this._currentActiveCount);
  1449. if (!this._currentActiveCount) {
  1450. return 0;
  1451. }
  1452. // Enable update effect
  1453. let emitterWM;
  1454. if (this.emitter.position) {
  1455. const emitterMesh = this.emitter;
  1456. emitterWM = emitterMesh.getWorldMatrix();
  1457. }
  1458. else {
  1459. const emitterPosition = this.emitter;
  1460. emitterWM = TmpVectors.Matrix[0];
  1461. Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);
  1462. }
  1463. const engine = this._engine;
  1464. if (!this.updateInAnimate) {
  1465. this._update(emitterWM);
  1466. }
  1467. let outparticles = 0;
  1468. if (!preWarm && !forceUpdateOnly) {
  1469. engine.setState(false);
  1470. if (this.forceDepthWrite) {
  1471. engine.setDepthWrite(true);
  1472. }
  1473. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  1474. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY, emitterWM) + this._render(ParticleSystem.BLENDMODE_ADD, emitterWM);
  1475. }
  1476. else {
  1477. outparticles = this._render(this.blendMode, emitterWM);
  1478. }
  1479. this._engine.setAlphaMode(0);
  1480. }
  1481. return outparticles;
  1482. }
  1483. /**
  1484. * Rebuilds the particle system
  1485. */
  1486. rebuild() {
  1487. const checkUpdateEffect = () => {
  1488. if (!this._recreateUpdateEffect() || !this._platform.isUpdateBufferReady()) {
  1489. setTimeout(checkUpdateEffect, 10);
  1490. }
  1491. else {
  1492. this._initialize(true);
  1493. this._rebuildingAfterContextLost = false;
  1494. }
  1495. };
  1496. this._createIndexBuffer();
  1497. this._cachedUpdateDefines = "";
  1498. this._platform.contextLost();
  1499. this._rebuildingAfterContextLost = true;
  1500. checkUpdateEffect();
  1501. }
  1502. _releaseBuffers() {
  1503. if (this._buffer0) {
  1504. this._buffer0.dispose();
  1505. this._buffer0 = null;
  1506. }
  1507. if (this._buffer1) {
  1508. this._buffer1.dispose();
  1509. this._buffer1 = null;
  1510. }
  1511. if (this._spriteBuffer) {
  1512. this._spriteBuffer.dispose();
  1513. this._spriteBuffer = null;
  1514. }
  1515. this._platform.releaseBuffers();
  1516. }
  1517. /**
  1518. * Disposes the particle system and free the associated resources
  1519. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1520. */
  1521. dispose(disposeTexture = true) {
  1522. for (const blendMode in this._drawWrappers) {
  1523. const drawWrapper = this._drawWrappers[blendMode];
  1524. drawWrapper.dispose();
  1525. }
  1526. this._drawWrappers = {};
  1527. if (this._scene) {
  1528. const index = this._scene.particleSystems.indexOf(this);
  1529. if (index > -1) {
  1530. this._scene.particleSystems.splice(index, 1);
  1531. }
  1532. }
  1533. this._releaseBuffers();
  1534. this._platform.releaseVertexBuffers();
  1535. for (let i = 0; i < this._renderVertexBuffers.length; ++i) {
  1536. const rvb = this._renderVertexBuffers[i];
  1537. for (const key in rvb) {
  1538. rvb[key].dispose();
  1539. }
  1540. }
  1541. this._renderVertexBuffers = [];
  1542. if (this._colorGradientsTexture) {
  1543. this._colorGradientsTexture.dispose();
  1544. this._colorGradientsTexture = null;
  1545. }
  1546. if (this._sizeGradientsTexture) {
  1547. this._sizeGradientsTexture.dispose();
  1548. this._sizeGradientsTexture = null;
  1549. }
  1550. if (this._angularSpeedGradientsTexture) {
  1551. this._angularSpeedGradientsTexture.dispose();
  1552. this._angularSpeedGradientsTexture = null;
  1553. }
  1554. if (this._velocityGradientsTexture) {
  1555. this._velocityGradientsTexture.dispose();
  1556. this._velocityGradientsTexture = null;
  1557. }
  1558. if (this._limitVelocityGradientsTexture) {
  1559. this._limitVelocityGradientsTexture.dispose();
  1560. this._limitVelocityGradientsTexture = null;
  1561. }
  1562. if (this._dragGradientsTexture) {
  1563. this._dragGradientsTexture.dispose();
  1564. this._dragGradientsTexture = null;
  1565. }
  1566. if (this._randomTexture) {
  1567. this._randomTexture.dispose();
  1568. this._randomTexture = null;
  1569. }
  1570. if (this._randomTexture2) {
  1571. this._randomTexture2.dispose();
  1572. this._randomTexture2 = null;
  1573. }
  1574. if (disposeTexture && this.particleTexture) {
  1575. this.particleTexture.dispose();
  1576. this.particleTexture = null;
  1577. }
  1578. if (disposeTexture && this.noiseTexture) {
  1579. this.noiseTexture.dispose();
  1580. this.noiseTexture = null;
  1581. }
  1582. // Callback
  1583. this.onStoppedObservable.clear();
  1584. this.onDisposeObservable.notifyObservers(this);
  1585. this.onDisposeObservable.clear();
  1586. }
  1587. /**
  1588. * Clones the particle system.
  1589. * @param name The name of the cloned object
  1590. * @param newEmitter The new emitter to use
  1591. * @param cloneTexture Also clone the textures if true
  1592. * @returns the cloned particle system
  1593. */
  1594. clone(name, newEmitter, cloneTexture = false) {
  1595. const custom = { ...this._customWrappers };
  1596. let program = null;
  1597. const engine = this._engine;
  1598. if (engine.createEffectForParticles) {
  1599. if (this.customShader != null) {
  1600. program = this.customShader;
  1601. const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : "";
  1602. custom[0] = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, this);
  1603. }
  1604. }
  1605. const serialization = this.serialize(cloneTexture);
  1606. const result = GPUParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl);
  1607. result.name = name;
  1608. result.customShader = program;
  1609. result._customWrappers = custom;
  1610. if (newEmitter === undefined) {
  1611. newEmitter = this.emitter;
  1612. }
  1613. if (this.noiseTexture) {
  1614. result.noiseTexture = this.noiseTexture.clone();
  1615. }
  1616. result.emitter = newEmitter;
  1617. return result;
  1618. }
  1619. /**
  1620. * Serializes the particle system to a JSON object
  1621. * @param serializeTexture defines if the texture must be serialized as well
  1622. * @returns the JSON object
  1623. */
  1624. serialize(serializeTexture = false) {
  1625. const serializationObject = {};
  1626. ParticleSystem._Serialize(serializationObject, this, serializeTexture);
  1627. serializationObject.activeParticleCount = this.activeParticleCount;
  1628. serializationObject.randomTextureSize = this._randomTextureSize;
  1629. serializationObject.customShader = this.customShader;
  1630. return serializationObject;
  1631. }
  1632. /**
  1633. * Parses a JSON object to create a GPU particle system.
  1634. * @param parsedParticleSystem The JSON object to parse
  1635. * @param sceneOrEngine The scene or the engine to create the particle system in
  1636. * @param rootUrl The root url to use to load external dependencies like texture
  1637. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  1638. * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)
  1639. * @returns the parsed GPU particle system
  1640. */
  1641. static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) {
  1642. const name = parsedParticleSystem.name;
  1643. let engine;
  1644. let scene;
  1645. if (sceneOrEngine instanceof AbstractEngine) {
  1646. engine = sceneOrEngine;
  1647. }
  1648. else {
  1649. scene = sceneOrEngine;
  1650. engine = scene.getEngine();
  1651. }
  1652. const particleSystem = new GPUParticleSystem(name, { capacity: capacity || parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine, null, parsedParticleSystem.isAnimationSheetEnabled);
  1653. particleSystem._rootUrl = rootUrl;
  1654. if (parsedParticleSystem.customShader && engine.createEffectForParticles) {
  1655. const program = parsedParticleSystem.customShader;
  1656. const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : "";
  1657. const custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, particleSystem);
  1658. particleSystem.setCustomEffect(custom, 0);
  1659. particleSystem.customShader = program;
  1660. }
  1661. if (parsedParticleSystem.id) {
  1662. particleSystem.id = parsedParticleSystem.id;
  1663. }
  1664. if (parsedParticleSystem.activeParticleCount) {
  1665. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  1666. }
  1667. ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);
  1668. // Auto start
  1669. if (parsedParticleSystem.preventAutoStart) {
  1670. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  1671. }
  1672. if (!doNotStart && !particleSystem.preventAutoStart) {
  1673. particleSystem.start();
  1674. }
  1675. return particleSystem;
  1676. }
  1677. }
  1678. //# sourceMappingURL=gpuParticleSystem.js.map