postProcess.ts 30 KB

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