babylon.standardRenderingPipeline.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. module BABYLON {
  2. export class StandardRenderingPipeline extends PostProcessRenderPipeline implements IDisposable, IAnimatable {
  3. /**
  4. * Public members
  5. */
  6. // Post-processes
  7. public originalPostProcess: Nullable<PostProcess>;
  8. public downSampleX4PostProcess: Nullable<PostProcess> = null;
  9. public brightPassPostProcess: Nullable<PostProcess> = null;
  10. public blurHPostProcesses: PostProcess[] = [];
  11. public blurVPostProcesses: PostProcess[] = [];
  12. public textureAdderPostProcess: Nullable<PostProcess> = null;
  13. public volumetricLightPostProcess: Nullable<PostProcess> = null;
  14. public volumetricLightSmoothXPostProcess: Nullable<BlurPostProcess> = null;
  15. public volumetricLightSmoothYPostProcess: Nullable<BlurPostProcess> = null;
  16. public volumetricLightMergePostProces: Nullable<PostProcess> = null;
  17. public volumetricLightFinalPostProcess: Nullable<PostProcess> = null;
  18. public luminancePostProcess: Nullable<PostProcess> = null;
  19. public luminanceDownSamplePostProcesses: PostProcess[] = [];
  20. public hdrPostProcess: Nullable<PostProcess> = null;
  21. public textureAdderFinalPostProcess: Nullable<PostProcess> = null;
  22. public lensFlareFinalPostProcess: Nullable<PostProcess> = null;
  23. public hdrFinalPostProcess: Nullable<PostProcess> = null;
  24. public lensFlarePostProcess: Nullable<PostProcess> = null;
  25. public lensFlareComposePostProcess: Nullable<PostProcess> = null;
  26. public motionBlurPostProcess: Nullable<PostProcess> = null;
  27. public depthOfFieldPostProcess: Nullable<PostProcess> = null;
  28. // Values
  29. @serialize()
  30. public brightThreshold: number = 1.0;
  31. @serialize()
  32. public blurWidth: number = 512.0;
  33. @serialize()
  34. public horizontalBlur: boolean = false;
  35. @serialize()
  36. public exposure: number = 1.0;
  37. @serializeAsTexture("lensTexture")
  38. public lensTexture: Nullable<Texture> = null;
  39. @serialize()
  40. public volumetricLightCoefficient: number = 0.2;
  41. @serialize()
  42. public volumetricLightPower: number = 4.0;
  43. @serialize()
  44. public volumetricLightBlurScale: number = 64.0;
  45. public sourceLight: Nullable<SpotLight |  DirectionalLight> = null;
  46. @serialize()
  47. public hdrMinimumLuminance: number = 1.0;
  48. @serialize()
  49. public hdrDecreaseRate: number = 0.5;
  50. @serialize()
  51. public hdrIncreaseRate: number = 0.5;
  52. @serializeAsTexture("lensColorTexture")
  53. public lensColorTexture: Nullable<Texture> = null;
  54. @serialize()
  55. public lensFlareStrength: number = 20.0;
  56. @serialize()
  57. public lensFlareGhostDispersal: number = 1.4;
  58. @serialize()
  59. public lensFlareHaloWidth: number = 0.7;
  60. @serialize()
  61. public lensFlareDistortionStrength: number = 16.0;
  62. @serializeAsTexture("lensStarTexture")
  63. public lensStarTexture: Nullable<Texture> = null;
  64. @serializeAsTexture("lensFlareDirtTexture")
  65. public lensFlareDirtTexture: Nullable<Texture> = null;
  66. @serialize()
  67. public depthOfFieldDistance: number = 10.0;
  68. @serialize()
  69. public depthOfFieldBlurWidth: number = 64.0;
  70. @serialize()
  71. public motionStrength: number = 1.0;
  72. // IAnimatable
  73. public animations: Animation[] = [];
  74. /**
  75. * Private members
  76. */
  77. private _scene: Scene;
  78. private _currentDepthOfFieldSource: Nullable<PostProcess> = null;
  79. private _basePostProcess: Nullable<PostProcess>;
  80. private _hdrCurrentLuminance: number = 1.0;
  81. private _floatTextureType: number;
  82. @serialize()
  83. private _ratio: number;
  84. // Getters and setters
  85. private _bloomEnabled: boolean = true;
  86. private _depthOfFieldEnabled: boolean = false;
  87. private _vlsEnabled: boolean = false;
  88. private _lensFlareEnabled: boolean = false;
  89. private _hdrEnabled: boolean = false;
  90. private _motionBlurEnabled: boolean = false;
  91. private _motionBlurSamples: number = 64.0;
  92. private _volumetricLightStepsCount: number = 50.0;
  93. @serialize()
  94. public get BloomEnabled(): boolean {
  95. return this._bloomEnabled;
  96. }
  97. public set BloomEnabled(enabled: boolean) {
  98. if (this._bloomEnabled === enabled) {
  99. return;
  100. }
  101. this._bloomEnabled = enabled;
  102. this._buildPipeline();
  103. }
  104. @serialize()
  105. public get DepthOfFieldEnabled(): boolean {
  106. return this._depthOfFieldEnabled;
  107. }
  108. public set DepthOfFieldEnabled(enabled: boolean) {
  109. if (this._depthOfFieldEnabled === enabled) {
  110. return;
  111. }
  112. this._depthOfFieldEnabled = enabled;
  113. this._buildPipeline();
  114. }
  115. @serialize()
  116. public get LensFlareEnabled(): boolean {
  117. return this._lensFlareEnabled;
  118. }
  119. public set LensFlareEnabled(enabled: boolean) {
  120. if (this._lensFlareEnabled === enabled) {
  121. return;
  122. }
  123. this._lensFlareEnabled = enabled;
  124. this._buildPipeline();
  125. }
  126. @serialize()
  127. public get HDREnabled(): boolean {
  128. return this._hdrEnabled;
  129. }
  130. public set HDREnabled(enabled: boolean) {
  131. if (this._hdrEnabled === enabled) {
  132. return;
  133. }
  134. this._hdrEnabled = enabled;
  135. this._buildPipeline();
  136. }
  137. @serialize()
  138. public get VLSEnabled(): boolean {
  139. return this._vlsEnabled;
  140. }
  141. public set VLSEnabled(enabled) {
  142. if (this._vlsEnabled === enabled) {
  143. return;
  144. }
  145. if (enabled) {
  146. var geometry = this._scene.enableGeometryBufferRenderer();
  147. if (!geometry) {
  148. Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  149. return;
  150. }
  151. }
  152. this._vlsEnabled = enabled;
  153. this._buildPipeline();
  154. }
  155. @serialize()
  156. public get MotionBlurEnabled(): boolean {
  157. return this._motionBlurEnabled;
  158. }
  159. public set MotionBlurEnabled(enabled: boolean) {
  160. if (this._motionBlurEnabled === enabled) {
  161. return;
  162. }
  163. this._motionBlurEnabled = enabled;
  164. this._buildPipeline();
  165. }
  166. @serialize()
  167. public get volumetricLightStepsCount(): number {
  168. return this._volumetricLightStepsCount;
  169. }
  170. public set volumetricLightStepsCount(count: number)  {
  171. if (this.volumetricLightPostProcess) {
  172. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  173. }
  174. this._volumetricLightStepsCount = count;
  175. }
  176. @serialize()
  177. public get motionBlurSamples(): number {
  178. return this._motionBlurSamples;
  179. }
  180. public set motionBlurSamples(samples: number) {
  181. if (this.motionBlurPostProcess) {
  182. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  183. }
  184. this._motionBlurSamples = samples;
  185. }
  186. /**
  187. * @constructor
  188. * @param {string} name - The rendering pipeline name
  189. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  190. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  191. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  192. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  193. */
  194. constructor(name: string, scene: Scene, ratio: number, originalPostProcess: Nullable<PostProcess> = null, cameras?: Camera[]) {
  195. super(scene.getEngine(), name);
  196. this._cameras = cameras ||  [];
  197. // Initialize
  198. this._scene = scene;
  199. this._basePostProcess = originalPostProcess;
  200. this._ratio = ratio;
  201. // Misc
  202. this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? Engine.TEXTURETYPE_FLOAT : Engine.TEXTURETYPE_HALF_FLOAT;
  203. // Finish
  204. scene.postProcessRenderPipelineManager.addPipeline(this);
  205. this._buildPipeline();
  206. }
  207. private _buildPipeline(): void {
  208. var ratio = this._ratio;
  209. var scene = this._scene;
  210. this._disposePostProcesses();
  211. this._reset();
  212. // Create pass post-process
  213. if (!this._basePostProcess) {
  214. this.originalPostProcess = new PostProcess("HDRPass", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  215. this.originalPostProcess.onApply = (effect: Effect) => {
  216. this._currentDepthOfFieldSource = this.originalPostProcess;
  217. };
  218. }
  219. else {
  220. this.originalPostProcess = this._basePostProcess;
  221. }
  222. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", () => { return this.originalPostProcess; }, true));
  223. this._currentDepthOfFieldSource = this.originalPostProcess;
  224. if (this._vlsEnabled) {
  225. // Create volumetric light
  226. this._createVolumetricLightPostProcess(scene, ratio);
  227. // Create volumetric light final post-process
  228. this.volumetricLightFinalPostProcess = new PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", Engine.TEXTURETYPE_UNSIGNED_INT);
  229. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", () => { return this.volumetricLightFinalPostProcess; }, true));
  230. }
  231. if (this._bloomEnabled) {
  232. // Create down sample X4 post-process
  233. this._createDownSampleX4PostProcess(scene, ratio / 2);
  234. // Create bright pass post-process
  235. this._createBrightPassPostProcess(scene, ratio / 2);
  236. // Create gaussian blur post-processes (down sampling blurs)
  237. this._createBlurPostProcesses(scene, ratio / 4, 1);
  238. // Create texture adder post-process
  239. this._createTextureAdderPostProcess(scene, ratio);
  240. // Create depth-of-field source post-process
  241. this.textureAdderFinalPostProcess = new PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", Engine.TEXTURETYPE_UNSIGNED_INT);
  242. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", () => { return this.textureAdderFinalPostProcess; }, true));
  243. }
  244. if (this._lensFlareEnabled) {
  245. // Create lens flare post-process
  246. this._createLensFlarePostProcess(scene, ratio);
  247. // Create depth-of-field source post-process post lens-flare and disable it now
  248. this.lensFlareFinalPostProcess = new PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", Engine.TEXTURETYPE_UNSIGNED_INT);
  249. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", () => { return this.lensFlareFinalPostProcess; }, true));
  250. }
  251. if (this._hdrEnabled) {
  252. // Create luminance
  253. this._createLuminancePostProcesses(scene, this._floatTextureType);
  254. // Create HDR
  255. this._createHdrPostProcess(scene, ratio);
  256. // Create depth-of-field source post-process post hdr and disable it now
  257. this.hdrFinalPostProcess = new PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", Engine.TEXTURETYPE_UNSIGNED_INT);
  258. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", () => { return this.hdrFinalPostProcess; }, true));
  259. }
  260. if (this._depthOfFieldEnabled) {
  261. // Create gaussian blur used by depth-of-field
  262. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  263. // Create depth-of-field post-process
  264. this._createDepthOfFieldPostProcess(scene, ratio);
  265. }
  266. if (this._motionBlurEnabled) {
  267. // Create motion blur post-process
  268. this._createMotionBlurPostProcess(scene, ratio);
  269. }
  270. if (this._cameras !== null) {
  271. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  272. }
  273. }
  274. // Down Sample X4 Post-Processs
  275. private _createDownSampleX4PostProcess(scene: Scene, ratio: number): void {
  276. var downSampleX4Offsets = new Array<number>(32);
  277. this.downSampleX4PostProcess = new PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", Engine.TEXTURETYPE_UNSIGNED_INT);
  278. this.downSampleX4PostProcess.onApply = (effect: Effect) => {
  279. var id = 0;
  280. let width = (<PostProcess>this.downSampleX4PostProcess).width;
  281. let height = (<PostProcess>this.downSampleX4PostProcess).height;
  282. for (var i = -2; i < 2; i++) {
  283. for (var j = -2; j < 2; j++) {
  284. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  285. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  286. id += 2;
  287. }
  288. }
  289. effect.setArray2("dsOffsets", downSampleX4Offsets);
  290. };
  291. // Add to pipeline
  292. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", () => { return this.downSampleX4PostProcess; }, true));
  293. }
  294. // Brightpass Post-Process
  295. private _createBrightPassPostProcess(scene: Scene, ratio: number): void {
  296. var brightOffsets = new Array<number>(8);
  297. this.brightPassPostProcess = new PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", Engine.TEXTURETYPE_UNSIGNED_INT);
  298. this.brightPassPostProcess.onApply = (effect: Effect) => {
  299. var sU = (1.0 / (<PostProcess>this.brightPassPostProcess).width);
  300. var sV = (1.0 / (<PostProcess>this.brightPassPostProcess).height);
  301. brightOffsets[0] = -0.5 * sU;
  302. brightOffsets[1] = 0.5 * sV;
  303. brightOffsets[2] = 0.5 * sU;
  304. brightOffsets[3] = 0.5 * sV;
  305. brightOffsets[4] = -0.5 * sU;
  306. brightOffsets[5] = -0.5 * sV;
  307. brightOffsets[6] = 0.5 * sU;
  308. brightOffsets[7] = -0.5 * sV;
  309. effect.setArray2("dsOffsets", brightOffsets);
  310. effect.setFloat("brightThreshold", this.brightThreshold);
  311. }
  312. // Add to pipeline
  313. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", () => { return this.brightPassPostProcess; }, true));
  314. }
  315. // Create blur H&V post-processes
  316. private _createBlurPostProcesses(scene: Scene, ratio: number, indice: number, blurWidthKey: string = "blurWidth"): void {
  317. var engine = scene.getEngine();
  318. var blurX = new BlurPostProcess("HDRBlurH" + "_" + indice, new Vector2(1, 0), (<any>this)[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, Engine.TEXTURETYPE_UNSIGNED_INT);
  319. var blurY = new BlurPostProcess("HDRBlurV" + "_" + indice, new Vector2(0, 1), (<any>this)[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, Engine.TEXTURETYPE_UNSIGNED_INT);
  320. blurX.onActivateObservable.add(() => {
  321. let dw = blurX.width / engine.getRenderWidth();
  322. blurX.kernel = (<any>this)[blurWidthKey] * dw;
  323. });
  324. blurY.onActivateObservable.add(() => {
  325. let dw = blurY.height / engine.getRenderHeight();
  326. blurY.kernel = this.horizontalBlur ? 64 * dw : (<any>this)[blurWidthKey] * dw;
  327. });
  328. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, () => { return blurX; }, true));
  329. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, () => { return blurY; }, true));
  330. this.blurHPostProcesses.push(blurX);
  331. this.blurVPostProcesses.push(blurY);
  332. }
  333. // Create texture adder post-process
  334. private _createTextureAdderPostProcess(scene: Scene, ratio: number): void {
  335. this.textureAdderPostProcess = new PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", Engine.TEXTURETYPE_UNSIGNED_INT);
  336. this.textureAdderPostProcess.onApply = (effect: Effect) => {
  337. effect.setTextureFromPostProcess("otherSampler", this._vlsEnabled ? this._currentDepthOfFieldSource : this.originalPostProcess);
  338. effect.setTexture("lensSampler", this.lensTexture);
  339. effect.setFloat("exposure", this.exposure);
  340. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  341. };
  342. // Add to pipeline
  343. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", () => { return this.textureAdderPostProcess; }, true));
  344. }
  345. private _createVolumetricLightPostProcess(scene: Scene, ratio: number): void {
  346. var geometryRenderer = <GeometryBufferRenderer>scene.enableGeometryBufferRenderer();
  347. geometryRenderer.enablePosition = true;
  348. var geometry = geometryRenderer.getGBuffer();
  349. // Base post-process
  350. this.volumetricLightPostProcess = new PostProcess("HDRVLS", "standard",
  351. ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"],
  352. ["shadowMapSampler", "positionSampler"],
  353. ratio / 8,
  354. null,
  355. Texture.BILINEAR_SAMPLINGMODE,
  356. scene.getEngine(),
  357. false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  358. var depthValues = Vector2.Zero();
  359. this.volumetricLightPostProcess.onApply = (effect: Effect) => {
  360. if (this.sourceLight && this.sourceLight.getShadowGenerator() && this._scene.activeCamera) {
  361. var generator = <ShadowGenerator>this.sourceLight.getShadowGenerator();
  362. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  363. effect.setTexture("positionSampler", geometry.textures[2]);
  364. effect.setColor3("sunColor", this.sourceLight.diffuse);
  365. effect.setVector3("sunDirection", this.sourceLight.getShadowDirection());
  366. effect.setVector3("cameraPosition", this._scene.activeCamera.globalPosition);
  367. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  368. effect.setFloat("scatteringCoefficient", this.volumetricLightCoefficient);
  369. effect.setFloat("scatteringPower", this.volumetricLightPower);
  370. depthValues.x = generator.getLight().getDepthMinZ(this._scene.activeCamera);
  371. depthValues.y = generator.getLight().getDepthMaxZ(this._scene.activeCamera);
  372. effect.setVector2("depthValues", depthValues);
  373. }
  374. };
  375. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLS", () => { return this.volumetricLightPostProcess; }, true));
  376. // Smooth
  377. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  378. // Merge
  379. this.volumetricLightMergePostProces = new PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  380. this.volumetricLightMergePostProces.onApply = (effect: Effect) => {
  381. effect.setTextureFromPostProcess("originalSampler", this.originalPostProcess);
  382. this._currentDepthOfFieldSource = this.volumetricLightFinalPostProcess;
  383. };
  384. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", () => { return this.volumetricLightMergePostProces; }, true));
  385. }
  386. // Create luminance
  387. private _createLuminancePostProcesses(scene: Scene, textureType: number): void {
  388. // Create luminance
  389. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  390. this.luminancePostProcess = new PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  391. var offsets: number[] = [];
  392. this.luminancePostProcess.onApply = (effect: Effect) => {
  393. var sU = (1.0 / (<PostProcess>this.luminancePostProcess).width);
  394. var sV = (1.0 / (<PostProcess>this.luminancePostProcess).height);
  395. offsets[0] = -0.5 * sU;
  396. offsets[1] = 0.5 * sV;
  397. offsets[2] = 0.5 * sU;
  398. offsets[3] = 0.5 * sV;
  399. offsets[4] = -0.5 * sU;
  400. offsets[5] = -0.5 * sV;
  401. offsets[6] = 0.5 * sU;
  402. offsets[7] = -0.5 * sV;
  403. effect.setArray2("lumOffsets", offsets);
  404. };
  405. // Add to pipeline
  406. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", () => { return this.luminancePostProcess; }, true));
  407. // Create down sample luminance
  408. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  409. var size = Math.pow(3, i);
  410. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  411. if (i === 0) {
  412. defines += "#define FINAL_DOWN_SAMPLER";
  413. }
  414. var postProcess = new PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  415. this.luminanceDownSamplePostProcesses.push(postProcess);
  416. }
  417. // Create callbacks and add effects
  418. var lastLuminance: Nullable<PostProcess> = this.luminancePostProcess;
  419. this.luminanceDownSamplePostProcesses.forEach((pp, index) => {
  420. var downSampleOffsets = new Array<number>(18);
  421. pp.onApply = (effect: Effect) => {
  422. if (!lastLuminance) {
  423. return;
  424. }
  425. var id = 0;
  426. for (var x = -1; x < 2; x++) {
  427. for (var y = -1; y < 2; y++) {
  428. downSampleOffsets[id] = x / lastLuminance.width;
  429. downSampleOffsets[id + 1] = y / lastLuminance.height;
  430. id += 2;
  431. }
  432. }
  433. effect.setArray2("dsOffsets", downSampleOffsets);
  434. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  435. if (index === this.luminanceDownSamplePostProcesses.length - 1) {
  436. lastLuminance = this.luminancePostProcess;
  437. } else {
  438. lastLuminance = pp;
  439. }
  440. };
  441. if (index === this.luminanceDownSamplePostProcesses.length - 1) {
  442. pp.onAfterRender = (effect: Effect) => {
  443. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  444. var bit_shift = new Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  445. this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  446. };
  447. }
  448. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, () => { return pp; }, true));
  449. });
  450. }
  451. // Create HDR post-process
  452. private _createHdrPostProcess(scene: Scene, ratio: number): void {
  453. this.hdrPostProcess = new PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", Engine.TEXTURETYPE_UNSIGNED_INT);
  454. var outputLiminance = 1;
  455. var time = 0;
  456. var lastTime = 0;
  457. this.hdrPostProcess.onApply = (effect: Effect) => {
  458. effect.setTextureFromPostProcess("textureAdderSampler", this._currentDepthOfFieldSource);
  459. time += scene.getEngine().getDeltaTime();
  460. if (outputLiminance < 0) {
  461. outputLiminance = this._hdrCurrentLuminance;
  462. } else {
  463. var dt = (lastTime - time) / 1000.0;
  464. if (this._hdrCurrentLuminance < outputLiminance + this.hdrDecreaseRate * dt) {
  465. outputLiminance += this.hdrDecreaseRate * dt;
  466. }
  467. else if (this._hdrCurrentLuminance > outputLiminance - this.hdrIncreaseRate * dt) {
  468. outputLiminance -= this.hdrIncreaseRate * dt;
  469. }
  470. else {
  471. outputLiminance = this._hdrCurrentLuminance;
  472. }
  473. }
  474. outputLiminance = Scalar.Clamp(outputLiminance, this.hdrMinimumLuminance, 1e20);
  475. effect.setFloat("averageLuminance", outputLiminance);
  476. lastTime = time;
  477. this._currentDepthOfFieldSource = this.hdrFinalPostProcess;
  478. };
  479. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDR", () => { return this.hdrPostProcess; }, true));
  480. }
  481. // Create lens flare post-process
  482. private _createLensFlarePostProcess(scene: Scene, ratio: number): void {
  483. this.lensFlarePostProcess = new PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", Engine.TEXTURETYPE_UNSIGNED_INT);
  484. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", () => { return this.lensFlarePostProcess; }, true));
  485. this._createBlurPostProcesses(scene, ratio / 4, 2);
  486. this.lensFlareComposePostProcess = new PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", Engine.TEXTURETYPE_UNSIGNED_INT);
  487. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", () => { return this.lensFlareComposePostProcess; }, true));
  488. var resolution = new Vector2(0, 0);
  489. // Lens flare
  490. this.lensFlarePostProcess.onApply = (effect: Effect) => {
  491. effect.setTextureFromPostProcess("textureSampler", this._bloomEnabled ? this.blurHPostProcesses[0] : this.originalPostProcess);
  492. effect.setTexture("lensColorSampler", this.lensColorTexture);
  493. effect.setFloat("strength", this.lensFlareStrength);
  494. effect.setFloat("ghostDispersal", this.lensFlareGhostDispersal);
  495. effect.setFloat("haloWidth", this.lensFlareHaloWidth);
  496. // Shift
  497. resolution.x = (<PostProcess>this.lensFlarePostProcess).width;
  498. resolution.y = (<PostProcess>this.lensFlarePostProcess).height;
  499. effect.setVector2("resolution", resolution);
  500. effect.setFloat("distortionStrength", this.lensFlareDistortionStrength);
  501. };
  502. // Compose
  503. var scaleBias1 = Matrix.FromValues(
  504. 2.0, 0.0, -1.0, 0.0,
  505. 0.0, 2.0, -1.0, 0.0,
  506. 0.0, 0.0, 1.0, 0.0,
  507. 0.0, 0.0, 0.0, 1.0
  508. );
  509. var scaleBias2 = Matrix.FromValues(
  510. 0.5, 0.0, 0.5, 0.0,
  511. 0.0, 0.5, 0.5, 0.0,
  512. 0.0, 0.0, 1.0, 0.0,
  513. 0.0, 0.0, 0.0, 1.0
  514. );
  515. this.lensFlareComposePostProcess.onApply = (effect: Effect) => {
  516. if (!this._scene.activeCamera) {
  517. return;
  518. }
  519. effect.setTextureFromPostProcess("otherSampler", this._currentDepthOfFieldSource);
  520. effect.setTexture("lensDirtSampler", this.lensFlareDirtTexture);
  521. effect.setTexture("lensStarSampler", this.lensStarTexture);
  522. // Lens start rotation matrix
  523. var camerax = (<Vector4>this._scene.activeCamera.getViewMatrix().getRow(0));
  524. var cameraz = (<Vector4>this._scene.activeCamera.getViewMatrix().getRow(2));
  525. var camRot = Vector3.Dot(camerax.toVector3(), new Vector3(1.0, 0.0, 0.0)) + Vector3.Dot(cameraz.toVector3(), new Vector3(0.0, 0.0, 1.0));
  526. camRot *= 4.0;
  527. var starRotation = Matrix.FromValues(
  528. Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0,
  529. Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0,
  530. 0.0, 0.0, 1.0, 0.0,
  531. 0.0, 0.0, 0.0, 1.0
  532. );
  533. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  534. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  535. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  536. };
  537. }
  538. // Create depth-of-field post-process
  539. private _createDepthOfFieldPostProcess(scene: Scene, ratio: number): void {
  540. this.depthOfFieldPostProcess = new PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", Engine.TEXTURETYPE_UNSIGNED_INT);
  541. this.depthOfFieldPostProcess.onApply = (effect: Effect) => {
  542. effect.setTextureFromPostProcess("otherSampler", this._currentDepthOfFieldSource);
  543. effect.setTexture("depthSampler", this._getDepthTexture());
  544. effect.setFloat("distance", this.depthOfFieldDistance);
  545. };
  546. // Add to pipeline
  547. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", () => { return this.depthOfFieldPostProcess; }, true));
  548. }
  549. // Create motion blur post-process
  550. private _createMotionBlurPostProcess(scene: Scene, ratio: number): void {
  551. this.motionBlurPostProcess = new PostProcess("HDRMotionBlur", "standard",
  552. ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"],
  553. ["depthSampler"],
  554. ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), Engine.TEXTURETYPE_UNSIGNED_INT);
  555. var motionScale: number = 0;
  556. var prevViewProjection = Matrix.Identity();
  557. var invViewProjection = Matrix.Identity();
  558. var viewProjection = Matrix.Identity();
  559. var screenSize = Vector2.Zero();
  560. this.motionBlurPostProcess.onApply = (effect: Effect) => {
  561. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  562. viewProjection.invertToRef(invViewProjection);
  563. effect.setMatrix("inverseViewProjection", invViewProjection);
  564. effect.setMatrix("prevViewProjection", prevViewProjection);
  565. prevViewProjection = viewProjection;
  566. screenSize.x = (<PostProcess>this.motionBlurPostProcess).width;
  567. screenSize.y = (<PostProcess>this.motionBlurPostProcess).height;
  568. effect.setVector2("screenSize", screenSize);
  569. motionScale = scene.getEngine().getFps() / 60.0;
  570. effect.setFloat("motionScale", motionScale);
  571. effect.setFloat("motionStrength", this.motionStrength);
  572. effect.setTexture("depthSampler", this._getDepthTexture());
  573. };
  574. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", () => { return this.motionBlurPostProcess; }, true));
  575. }
  576. private _getDepthTexture(): Texture {
  577. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  578. let renderer = <GeometryBufferRenderer>this._scene.enableGeometryBufferRenderer();
  579. return renderer.getGBuffer().textures[0];
  580. }
  581. return this._scene.enableDepthRenderer().getDepthMap();
  582. }
  583. private _disposePostProcesses(): void {
  584. for (var i = 0; i < this._cameras.length; i++) {
  585. var camera = this._cameras[i];
  586. if (this.originalPostProcess) { this.originalPostProcess.dispose(camera); }
  587. if (this.downSampleX4PostProcess) { this.downSampleX4PostProcess.dispose(camera); }
  588. if (this.brightPassPostProcess) { this.brightPassPostProcess.dispose(camera); }
  589. if (this.textureAdderPostProcess) { this.textureAdderPostProcess.dispose(camera); }
  590. if (this.textureAdderFinalPostProcess) { this.textureAdderFinalPostProcess.dispose(camera); }
  591. if (this.volumetricLightPostProcess) { this.volumetricLightPostProcess.dispose(camera); }
  592. if (this.volumetricLightSmoothXPostProcess) { this.volumetricLightSmoothXPostProcess.dispose(camera); }
  593. if (this.volumetricLightSmoothYPostProcess) { this.volumetricLightSmoothYPostProcess.dispose(camera); }
  594. if (this.volumetricLightMergePostProces) { this.volumetricLightMergePostProces.dispose(camera); }
  595. if (this.volumetricLightFinalPostProcess) { this.volumetricLightFinalPostProcess.dispose(camera); }
  596. if (this.lensFlarePostProcess) { this.lensFlarePostProcess.dispose(camera); }
  597. if (this.lensFlareComposePostProcess) { this.lensFlareComposePostProcess.dispose(camera); }
  598. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  599. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  600. }
  601. if (this.luminancePostProcess) { this.luminancePostProcess.dispose(camera); }
  602. if (this.hdrPostProcess) { this.hdrPostProcess.dispose(camera); }
  603. if (this.hdrFinalPostProcess) { this.hdrFinalPostProcess.dispose(camera); }
  604. if (this.depthOfFieldPostProcess) { this.depthOfFieldPostProcess.dispose(camera); }
  605. if (this.motionBlurPostProcess) { this.motionBlurPostProcess.dispose(camera); }
  606. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  607. this.blurHPostProcesses[j].dispose(camera);
  608. }
  609. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  610. this.blurVPostProcesses[j].dispose(camera);
  611. }
  612. }
  613. this.originalPostProcess = null;
  614. this.downSampleX4PostProcess = null;
  615. this.brightPassPostProcess = null;
  616. this.textureAdderPostProcess = null;
  617. this.textureAdderFinalPostProcess = null;
  618. this.volumetricLightPostProcess = null;
  619. this.volumetricLightSmoothXPostProcess = null;
  620. this.volumetricLightSmoothYPostProcess = null;
  621. this.volumetricLightMergePostProces = null;
  622. this.volumetricLightFinalPostProcess = null;
  623. this.lensFlarePostProcess = null;
  624. this.lensFlareComposePostProcess = null;
  625. this.luminancePostProcess = null;
  626. this.hdrPostProcess = null;
  627. this.hdrFinalPostProcess = null;
  628. this.depthOfFieldPostProcess = null;
  629. this.motionBlurPostProcess = null;
  630. this.luminanceDownSamplePostProcesses = [];
  631. this.blurHPostProcesses = [];
  632. this.blurVPostProcesses = [];
  633. }
  634. // Dispose
  635. public dispose(): void {
  636. this._disposePostProcesses();
  637. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  638. super.dispose();
  639. }
  640. // Serialize rendering pipeline
  641. public serialize(): any {
  642. var serializationObject = SerializationHelper.Serialize(this);
  643. serializationObject.customType = "StandardRenderingPipeline";
  644. return serializationObject;
  645. }
  646. /**
  647. * Static members
  648. */
  649. // Parse serialized pipeline
  650. public static Parse(source: any, scene: Scene, rootUrl: string): StandardRenderingPipeline {
  651. return SerializationHelper.Parse(() => new StandardRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);
  652. }
  653. // Luminance steps
  654. public static LuminanceSteps: number = 6;
  655. }
  656. }