postProcess.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. import { Nullable } from "../types";
  2. import { SmartArray } from "../Misc/smartArray";
  3. import { Observable, Observer } from "../Misc/observable";
  4. import { Vector2 } from "../Maths/math.vector";
  5. import { Camera } from "../Cameras/camera";
  6. import { Effect } from "../Materials/effect";
  7. import { Constants } from "../Engines/constants";
  8. import "../Shaders/postprocess.vertex";
  9. import { IInspectable } from '../Misc/iInspectable';
  10. import { Engine } from '../Engines/engine';
  11. import { Color4 } from '../Maths/math.color';
  12. import "../Engines/Extensions/engine.renderTarget";
  13. declare type Scene = import("../scene").Scene;
  14. declare type InternalTexture = import("../Materials/Textures/internalTexture").InternalTexture;
  15. declare type WebVRFreeCamera = import("../Cameras/VR/webVRCamera").WebVRFreeCamera;
  16. declare type Animation = import("../Animations/animation").Animation;
  17. /**
  18. * Size options for a post process
  19. */
  20. export type PostProcessOptions = { width: number, height: number };
  21. /**
  22. * PostProcess can be used to apply a shader to a texture after it has been rendered
  23. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  24. */
  25. export class PostProcess {
  26. /**
  27. * Gets or sets the unique id of the post process
  28. */
  29. public uniqueId: number;
  30. /**
  31. * Width of the texture to apply the post process on
  32. */
  33. public width = -1;
  34. /**
  35. * Height of the texture to apply the post process on
  36. */
  37. public height = -1;
  38. /**
  39. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  40. * @hidden
  41. */
  42. public _outputTexture: Nullable<InternalTexture> = null;
  43. /**
  44. * Sampling mode used by the shader
  45. * See https://doc.babylonjs.com/classes/3.1/texture
  46. */
  47. public renderTargetSamplingMode: number;
  48. /**
  49. * Clear color to use when screen clearing
  50. */
  51. public clearColor: Color4;
  52. /**
  53. * If the buffer needs to be cleared before applying the post process. (default: true)
  54. * Should be set to false if shader will overwrite all previous pixels.
  55. */
  56. public autoClear = true;
  57. /**
  58. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59. */
  60. public alphaMode = Constants.ALPHA_DISABLE;
  61. /**
  62. * Sets the setAlphaBlendConstants of the babylon engine
  63. */
  64. public alphaConstants: Color4;
  65. /**
  66. * Animations to be used for the post processing
  67. */
  68. public animations = new Array<Animation>();
  69. /**
  70. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  72. */
  73. public enablePixelPerfectMode = false;
  74. /**
  75. * Force the postprocess to be applied without taking in account viewport
  76. */
  77. public forceFullscreenViewport = true;
  78. /**
  79. * List of inspectable custom properties (used by the Inspector)
  80. * @see https://doc.babylonjs.com/how_to/debug_layer#extensibility
  81. */
  82. public inspectableCustomProperties: IInspectable[];
  83. /**
  84. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  85. *
  86. * | Value | Type | Description |
  87. * | ----- | ----------------------------------- | ----------- |
  88. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  89. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  90. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  91. *
  92. */
  93. public scaleMode = Constants.SCALEMODE_FLOOR;
  94. /**
  95. * Force textures to be a power of two (default: false)
  96. */
  97. public alwaysForcePOT = false;
  98. private _samples = 1;
  99. /**
  100. * Number of sample textures (default: 1)
  101. */
  102. public get samples() {
  103. return this._samples;
  104. }
  105. public set samples(n: number) {
  106. this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples);
  107. this._textures.forEach((texture) => {
  108. if (texture.samples !== this._samples) {
  109. this._engine.updateRenderTargetTextureSampleCount(texture, this._samples);
  110. }
  111. });
  112. }
  113. /**
  114. * Modify the scale of the post process to be the same as the viewport (default: false)
  115. */
  116. public adaptScaleToCurrentViewport = false;
  117. private _camera: Camera;
  118. private _scene: Scene;
  119. private _engine: Engine;
  120. private _options: number | PostProcessOptions;
  121. private _reusable = false;
  122. private _textureType: number;
  123. /**
  124. * Smart array of input and output textures for the post process.
  125. * @hidden
  126. */
  127. public _textures = new SmartArray<InternalTexture>(2);
  128. /**
  129. * The index in _textures that corresponds to the output texture.
  130. * @hidden
  131. */
  132. public _currentRenderTextureInd = 0;
  133. private _effect: Effect;
  134. private _samplers: string[];
  135. private _fragmentUrl: string;
  136. private _vertexUrl: string;
  137. private _parameters: string[];
  138. private _scaleRatio = new Vector2(1, 1);
  139. protected _indexParameters: any;
  140. private _shareOutputWithPostProcess: Nullable<PostProcess>;
  141. private _texelSize = Vector2.Zero();
  142. private _forcedOutputTexture: InternalTexture;
  143. /**
  144. * Returns the fragment url or shader name used in the post process.
  145. * @returns the fragment url or name in the shader store.
  146. */
  147. public getEffectName(): string {
  148. return this._fragmentUrl;
  149. }
  150. // Events
  151. /**
  152. * An event triggered when the postprocess is activated.
  153. */
  154. public onActivateObservable = new Observable<Camera>();
  155. private _onActivateObserver: Nullable<Observer<Camera>>;
  156. /**
  157. * A function that is added to the onActivateObservable
  158. */
  159. public set onActivate(callback: Nullable<(camera: Camera) => void>) {
  160. if (this._onActivateObserver) {
  161. this.onActivateObservable.remove(this._onActivateObserver);
  162. }
  163. if (callback) {
  164. this._onActivateObserver = this.onActivateObservable.add(callback);
  165. }
  166. }
  167. /**
  168. * An event triggered when the postprocess changes its size.
  169. */
  170. public onSizeChangedObservable = new Observable<PostProcess>();
  171. private _onSizeChangedObserver: Nullable<Observer<PostProcess>>;
  172. /**
  173. * A function that is added to the onSizeChangedObservable
  174. */
  175. public set onSizeChanged(callback: (postProcess: PostProcess) => void) {
  176. if (this._onSizeChangedObserver) {
  177. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  178. }
  179. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  180. }
  181. /**
  182. * An event triggered when the postprocess applies its effect.
  183. */
  184. public onApplyObservable = new Observable<Effect>();
  185. private _onApplyObserver: Nullable<Observer<Effect>>;
  186. /**
  187. * A function that is added to the onApplyObservable
  188. */
  189. public set onApply(callback: (effect: Effect) => void) {
  190. if (this._onApplyObserver) {
  191. this.onApplyObservable.remove(this._onApplyObserver);
  192. }
  193. this._onApplyObserver = this.onApplyObservable.add(callback);
  194. }
  195. /**
  196. * An event triggered before rendering the postprocess
  197. */
  198. public onBeforeRenderObservable = new Observable<Effect>();
  199. private _onBeforeRenderObserver: Nullable<Observer<Effect>>;
  200. /**
  201. * A function that is added to the onBeforeRenderObservable
  202. */
  203. public set onBeforeRender(callback: (effect: Effect) => void) {
  204. if (this._onBeforeRenderObserver) {
  205. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  206. }
  207. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  208. }
  209. /**
  210. * An event triggered after rendering the postprocess
  211. */
  212. public onAfterRenderObservable = new Observable<Effect>();
  213. private _onAfterRenderObserver: Nullable<Observer<Effect>>;
  214. /**
  215. * A function that is added to the onAfterRenderObservable
  216. */
  217. public set onAfterRender(callback: (efect: Effect) => void) {
  218. if (this._onAfterRenderObserver) {
  219. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  220. }
  221. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  222. }
  223. /**
  224. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  225. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  226. */
  227. public get inputTexture(): InternalTexture {
  228. return this._textures.data[this._currentRenderTextureInd];
  229. }
  230. public set inputTexture(value: InternalTexture) {
  231. this._forcedOutputTexture = value;
  232. }
  233. /**
  234. * Gets the camera which post process is applied to.
  235. * @returns The camera the post process is applied to.
  236. */
  237. public getCamera(): Camera {
  238. return this._camera;
  239. }
  240. /**
  241. * Gets the texel size of the postprocess.
  242. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  243. */
  244. public get texelSize(): Vector2 {
  245. if (this._shareOutputWithPostProcess) {
  246. return this._shareOutputWithPostProcess.texelSize;
  247. }
  248. if (this._forcedOutputTexture) {
  249. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  250. }
  251. return this._texelSize;
  252. }
  253. /**
  254. * Creates a new instance PostProcess
  255. * @param name The name of the PostProcess.
  256. * @param fragmentUrl The url of the fragment shader to be used.
  257. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  258. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  259. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  260. * @param camera The camera to apply the render pass to.
  261. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  262. * @param engine The engine which the post process will be applied. (default: current engine)
  263. * @param reusable If the post process can be reused on the same frame. (default: false)
  264. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  265. * @param textureType Type of textures used when performing the post process. (default: 0)
  266. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  267. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  268. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  269. */
  270. constructor(
  271. /** Name of the PostProcess. */
  272. public name: string,
  273. fragmentUrl: string, parameters: Nullable<string[]>, samplers: Nullable<string[]>, options: number | PostProcessOptions, camera: Nullable<Camera>,
  274. samplingMode: number = Constants.TEXTURE_NEAREST_SAMPLINGMODE, engine?: Engine, reusable?: boolean, defines: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT, vertexUrl: string = "postprocess", indexParameters?: any, blockCompilation = false) {
  275. if (camera != null) {
  276. this._camera = camera;
  277. this._scene = camera.getScene();
  278. camera.attachPostProcess(this);
  279. this._engine = this._scene.getEngine();
  280. this._scene.postProcesses.push(this);
  281. this.uniqueId = this._scene.getUniqueId();
  282. }
  283. else if (engine) {
  284. this._engine = engine;
  285. this._engine.postProcesses.push(this);
  286. }
  287. this._options = options;
  288. this.renderTargetSamplingMode = samplingMode ? samplingMode : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  289. this._reusable = reusable || false;
  290. this._textureType = textureType;
  291. this._samplers = samplers || [];
  292. this._samplers.push("textureSampler");
  293. this._fragmentUrl = fragmentUrl;
  294. this._vertexUrl = vertexUrl;
  295. this._parameters = parameters || [];
  296. this._parameters.push("scale");
  297. this._indexParameters = indexParameters;
  298. if (!blockCompilation) {
  299. this.updateEffect(defines);
  300. }
  301. }
  302. /**
  303. * Gets a string idenfifying the name of the class
  304. * @returns "PostProcess" string
  305. */
  306. public getClassName(): string {
  307. return "PostProcess";
  308. }
  309. /**
  310. * Gets the engine which this post process belongs to.
  311. * @returns The engine the post process was enabled with.
  312. */
  313. public getEngine(): Engine {
  314. return this._engine;
  315. }
  316. /**
  317. * The effect that is created when initializing the post process.
  318. * @returns The created effect corresponding the the postprocess.
  319. */
  320. public getEffect(): Effect {
  321. return this._effect;
  322. }
  323. /**
  324. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  325. * @param postProcess The post process to share the output with.
  326. * @returns This post process.
  327. */
  328. public shareOutputWith(postProcess: PostProcess): PostProcess {
  329. this._disposeTextures();
  330. this._shareOutputWithPostProcess = postProcess;
  331. return this;
  332. }
  333. /**
  334. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  335. * This should be called if the post process that shares output with this post process is disabled/disposed.
  336. */
  337. public useOwnOutput() {
  338. if (this._textures.length == 0) {
  339. this._textures = new SmartArray<InternalTexture>(2);
  340. }
  341. this._shareOutputWithPostProcess = null;
  342. }
  343. /**
  344. * Updates the effect with the current post process compile time values and recompiles the shader.
  345. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  346. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  347. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  348. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  349. * @param onCompiled Called when the shader has been compiled.
  350. * @param onError Called if there is an error when compiling a shader.
  351. */
  352. public updateEffect(defines: Nullable<string> = null, uniforms: Nullable<string[]> = null, samplers: Nullable<string[]> = null, indexParameters?: any,
  353. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void) {
  354. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl },
  355. ["position"],
  356. uniforms || this._parameters,
  357. samplers || this._samplers,
  358. defines !== null ? defines : "",
  359. undefined,
  360. onCompiled,
  361. onError,
  362. indexParameters || this._indexParameters
  363. );
  364. }
  365. /**
  366. * The post process is reusable if it can be used multiple times within one frame.
  367. * @returns If the post process is reusable
  368. */
  369. public isReusable(): boolean {
  370. return this._reusable;
  371. }
  372. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  373. public markTextureDirty(): void {
  374. this.width = -1;
  375. }
  376. /**
  377. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  378. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  379. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  380. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  381. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  382. * @returns The target texture that was bound to be written to.
  383. */
  384. public activate(camera: Nullable<Camera>, sourceTexture: Nullable<InternalTexture> = null, forceDepthStencil?: boolean): InternalTexture {
  385. camera = camera || this._camera;
  386. var scene = camera.getScene();
  387. var engine = scene.getEngine();
  388. var maxSize = engine.getCaps().maxTextureSize;
  389. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * <number>this._options) | 0;
  390. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * <number>this._options) | 0;
  391. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  392. var webVRCamera = (<WebVRFreeCamera>camera.parent);
  393. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  394. requiredWidth /= 2;
  395. }
  396. var desiredWidth = ((<PostProcessOptions>this._options).width || requiredWidth);
  397. var desiredHeight = (<PostProcessOptions>this._options).height || requiredHeight;
  398. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  399. if (this.adaptScaleToCurrentViewport) {
  400. let currentViewport = engine.currentViewport;
  401. if (currentViewport) {
  402. desiredWidth *= currentViewport.width;
  403. desiredHeight *= currentViewport.height;
  404. }
  405. }
  406. if (this.renderTargetSamplingMode === Constants.TEXTURE_TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  407. if (!(<PostProcessOptions>this._options).width) {
  408. desiredWidth = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  409. }
  410. if (!(<PostProcessOptions>this._options).height) {
  411. desiredHeight = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  412. }
  413. }
  414. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  415. if (this._textures.length > 0) {
  416. for (var i = 0; i < this._textures.length; i++) {
  417. this._engine._releaseTexture(this._textures.data[i]);
  418. }
  419. this._textures.reset();
  420. }
  421. this.width = desiredWidth;
  422. this.height = desiredHeight;
  423. const needMipMaps = this.renderTargetSamplingMode === Constants.TEXTURE_TRILINEAR_SAMPLINGMODE ||
  424. this.renderTargetSamplingMode === Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR ||
  425. this.renderTargetSamplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR ||
  426. this.renderTargetSamplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR ||
  427. this.renderTargetSamplingMode === Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  428. let textureSize = { width: this.width, height: this.height };
  429. let textureOptions = {
  430. generateMipMaps: needMipMaps,
  431. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  432. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  433. samplingMode: this.renderTargetSamplingMode,
  434. type: this._textureType
  435. };
  436. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  437. if (this._reusable) {
  438. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  439. }
  440. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  441. this.onSizeChangedObservable.notifyObservers(this);
  442. }
  443. this._textures.forEach((texture) => {
  444. if (texture.samples !== this.samples) {
  445. this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);
  446. }
  447. });
  448. }
  449. var target: InternalTexture;
  450. if (this._shareOutputWithPostProcess) {
  451. target = this._shareOutputWithPostProcess.inputTexture;
  452. } else if (this._forcedOutputTexture) {
  453. target = this._forcedOutputTexture;
  454. this.width = this._forcedOutputTexture.width;
  455. this.height = this._forcedOutputTexture.height;
  456. } else {
  457. target = this.inputTexture;
  458. }
  459. // Bind the input of this post process to be used as the output of the previous post process.
  460. if (this.enablePixelPerfectMode) {
  461. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  462. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  463. }
  464. else {
  465. this._scaleRatio.copyFromFloats(1, 1);
  466. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  467. }
  468. this.onActivateObservable.notifyObservers(camera);
  469. // Clear
  470. if (this.autoClear && this.alphaMode === Constants.ALPHA_DISABLE) {
  471. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  472. }
  473. if (this._reusable) {
  474. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  475. }
  476. return target;
  477. }
  478. /**
  479. * If the post process is supported.
  480. */
  481. public get isSupported(): boolean {
  482. return this._effect.isSupported;
  483. }
  484. /**
  485. * The aspect ratio of the output texture.
  486. */
  487. public get aspectRatio(): number {
  488. if (this._shareOutputWithPostProcess) {
  489. return this._shareOutputWithPostProcess.aspectRatio;
  490. }
  491. if (this._forcedOutputTexture) {
  492. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  493. }
  494. return this.width / this.height;
  495. }
  496. /**
  497. * Get a value indicating if the post-process is ready to be used
  498. * @returns true if the post-process is ready (shader is compiled)
  499. */
  500. public isReady(): boolean {
  501. return this._effect && this._effect.isReady();
  502. }
  503. /**
  504. * Binds all textures and uniforms to the shader, this will be run on every pass.
  505. * @returns the effect corresponding to this post process. Null if not compiled or not ready.
  506. */
  507. public apply(): Nullable<Effect> {
  508. // Check
  509. if (!this._effect || !this._effect.isReady()) {
  510. return null;
  511. }
  512. // States
  513. this._engine.enableEffect(this._effect);
  514. this._engine.setState(false);
  515. this._engine.setDepthBuffer(false);
  516. this._engine.setDepthWrite(false);
  517. // Alpha
  518. this._engine.setAlphaMode(this.alphaMode);
  519. if (this.alphaConstants) {
  520. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  521. }
  522. // Bind the output texture of the preivous post process as the input to this post process.
  523. var source: InternalTexture;
  524. if (this._shareOutputWithPostProcess) {
  525. source = this._shareOutputWithPostProcess.inputTexture;
  526. } else if (this._forcedOutputTexture) {
  527. source = this._forcedOutputTexture;
  528. } else {
  529. source = this.inputTexture;
  530. }
  531. this._effect._bindTexture("textureSampler", source);
  532. // Parameters
  533. this._effect.setVector2("scale", this._scaleRatio);
  534. this.onApplyObservable.notifyObservers(this._effect);
  535. return this._effect;
  536. }
  537. private _disposeTextures() {
  538. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  539. return;
  540. }
  541. if (this._textures.length > 0) {
  542. for (var i = 0; i < this._textures.length; i++) {
  543. this._engine._releaseTexture(this._textures.data[i]);
  544. }
  545. }
  546. this._textures.dispose();
  547. }
  548. /**
  549. * Disposes the post process.
  550. * @param camera The camera to dispose the post process on.
  551. */
  552. public dispose(camera?: Camera): void {
  553. camera = camera || this._camera;
  554. this._disposeTextures();
  555. if (this._scene) {
  556. let index = this._scene.postProcesses.indexOf(this);
  557. if (index !== -1) {
  558. this._scene.postProcesses.splice(index, 1);
  559. }
  560. } else {
  561. let index = this._engine.postProcesses.indexOf(this);
  562. if (index !== -1) {
  563. this._engine.postProcesses.splice(index, 1);
  564. }
  565. }
  566. if (!camera) {
  567. return;
  568. }
  569. camera.detachPostProcess(this);
  570. var index = camera._postProcesses.indexOf(this);
  571. if (index === 0 && camera._postProcesses.length > 0) {
  572. var firstPostProcess = this._camera._getFirstPostProcess();
  573. if (firstPostProcess) {
  574. firstPostProcess.markTextureDirty();
  575. }
  576. }
  577. this.onActivateObservable.clear();
  578. this.onAfterRenderObservable.clear();
  579. this.onApplyObservable.clear();
  580. this.onBeforeRenderObservable.clear();
  581. this.onSizeChangedObservable.clear();
  582. }
  583. }