babylon.postProcess.ts 25 KB

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