babylon.postProcess.ts 25 KB

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