postProcess.ts 29 KB

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