babylon.gpuParticleSystem.ts 45 KB

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