babylon.hdrRenderingPipeline.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. module BABYLON {
  2. export class HDRRenderingPipeline extends PostProcessRenderPipeline implements IDisposable {
  3. /**
  4. * Public members
  5. */
  6. // Gaussian Blur
  7. /**
  8. * Gaussian blur coefficient
  9. * @type {number}
  10. */
  11. public gaussCoeff: number = 0.3;
  12. /**
  13. * Gaussian blur mean
  14. * @type {number}
  15. */
  16. public gaussMean: number = 1.0;
  17. /**
  18. * Gaussian blur standard deviation
  19. * @type {number}
  20. */
  21. public gaussStandDev: number = 0.8;
  22. /**
  23. * Gaussian blur multiplier. Multiplies the blur effect
  24. * @type {number}
  25. */
  26. public gaussMultiplier: number = 4.0;
  27. // HDR
  28. /**
  29. * Exposure, controls the overall intensity of the pipeline
  30. * @type {number}
  31. */
  32. public exposure: number = 1.0;
  33. /**
  34. * Minimum luminance that the post-process can output. Luminance is >= 0
  35. * @type {number}
  36. */
  37. public minimumLuminance: number = 1.0;
  38. /**
  39. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40. * @type {number}
  41. */
  42. public maximumLuminance: number = 1e20;
  43. /**
  44. * Increase rate for luminance: eye adaptation speed to dark
  45. * @type {number}
  46. */
  47. public luminanceIncreaserate: number = 0.5;
  48. /**
  49. * Decrease rate for luminance: eye adaptation speed to bright
  50. * @type {number}
  51. */
  52. public luminanceDecreaseRate: number = 0.5;
  53. // Bright pass
  54. /**
  55. * Minimum luminance needed to compute HDR
  56. * @type {number}
  57. */
  58. public brightThreshold: number = 0.8;
  59. /**
  60. * Private members
  61. */
  62. // Gaussian blur
  63. private _guassianBlurHPostProcess: PostProcess;
  64. private _guassianBlurVPostProcess: PostProcess;
  65. // Bright pass
  66. private _brightPassPostProcess: PostProcess;
  67. // Texture adder
  68. private _textureAdderPostProcess: PostProcess;
  69. // Down Sampling
  70. private _downSampleX4PostProcess: PostProcess;
  71. // Original Post-process
  72. private _originalPostProcess: PostProcess;
  73. // HDR
  74. private _hdrPostProcess: PostProcess;
  75. private _hdrCurrentLuminance: number;
  76. private _hdrOutputLuminance: number;
  77. // Luminance generator
  78. public static LUM_STEPS: number = 6;
  79. private _downSamplePostProcesses: Array<PostProcess>;
  80. // Global
  81. private _scene: Scene;
  82. private _needUpdate: boolean = true;
  83. /**
  84. * @constructor
  85. * @param {string} name - The rendering pipeline name
  86. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  87. * @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)
  88. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  89. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  90. */
  91. constructor(name: string, scene: Scene, ratio: number, originalPostProcess: PostProcess = null, cameras?: Camera[]) {
  92. super(scene.getEngine(), name);
  93. this._scene = scene;
  94. // Bright pass
  95. this._createBrightPassPostProcess(scene, ratio);
  96. // Down sample X4
  97. this._createDownSampleX4PostProcess(scene, ratio);
  98. // Create gaussian blur post-processes
  99. this._createGaussianBlurPostProcess(scene, ratio);
  100. // Texture adder
  101. this._createTextureAdderPostProcess(scene, ratio);
  102. // Luminance generator
  103. this._createLuminanceGeneratorPostProcess(scene);
  104. // HDR
  105. this._createHDRPostProcess(scene, ratio);
  106. // Pass postprocess
  107. if (originalPostProcess === null) {
  108. this._originalPostProcess = new PassPostProcess("hdr", ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  109. } else {
  110. this._originalPostProcess = originalPostProcess;
  111. }
  112. // Configure pipeline
  113. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess",() => { return this._originalPostProcess; }, true));
  114. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass",() => { return this._brightPassPostProcess; }, true));
  115. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4",() => { return this._downSampleX4PostProcess; }, true));
  116. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH",() => { return this._guassianBlurHPostProcess; }, true));
  117. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV",() => { return this._guassianBlurVPostProcess; }, true));
  118. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder",() => { return this._textureAdderPostProcess; }, true));
  119. var addDownSamplerPostProcess = (id: number) => {
  120. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id,() => { return this._downSamplePostProcesses[id]; }, true));
  121. };
  122. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  123. addDownSamplerPostProcess(i);
  124. }
  125. this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDR",() => { return this._hdrPostProcess; }, true));
  126. // Finish
  127. scene.postProcessRenderPipelineManager.addPipeline(this);
  128. if (cameras !== null) {
  129. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  130. }
  131. this.update();
  132. }
  133. /**
  134. * Tells the pipeline to update its post-processes
  135. */
  136. public update(): void {
  137. this._needUpdate = true;
  138. }
  139. /**
  140. * Returns the current calculated luminance
  141. */
  142. public getCurrentLuminance(): number {
  143. return this._hdrCurrentLuminance;
  144. }
  145. /**
  146. * Returns the currently drawn luminance
  147. */
  148. public getOutputLuminance(): number {
  149. return this._hdrOutputLuminance;
  150. }
  151. /**
  152. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  153. */
  154. public dispose(): void {
  155. this._originalPostProcess = undefined;
  156. this._brightPassPostProcess = undefined;
  157. this._downSampleX4PostProcess = undefined;
  158. this._guassianBlurHPostProcess = undefined;
  159. this._guassianBlurVPostProcess = undefined;
  160. this._textureAdderPostProcess = undefined;
  161. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  162. this._downSamplePostProcesses[i] = undefined;
  163. }
  164. this._hdrPostProcess = undefined;
  165. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  166. }
  167. /**
  168. * Creates the HDR post-process and computes the luminance adaptation
  169. */
  170. private _createHDRPostProcess(scene: Scene, ratio: number): void {
  171. var hdrLastLuminance = 0.0;
  172. this._hdrOutputLuminance = -1.0;
  173. this._hdrCurrentLuminance = 1.0;
  174. this._hdrPostProcess = new PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  175. this._hdrPostProcess.onApply = (effect: Effect) => {
  176. if (this._hdrOutputLuminance < 0.0) {
  177. this._hdrOutputLuminance = this._hdrCurrentLuminance;
  178. }
  179. else {
  180. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  181. if (this._hdrCurrentLuminance < this._hdrOutputLuminance + this.luminanceDecreaseRate * dt) {
  182. this._hdrOutputLuminance += this.luminanceDecreaseRate * dt;
  183. }
  184. else if (this._hdrCurrentLuminance > this._hdrOutputLuminance - this.luminanceIncreaserate * dt) {
  185. this._hdrOutputLuminance -= this.luminanceIncreaserate * dt;
  186. }
  187. else {
  188. this._hdrOutputLuminance = this._hdrCurrentLuminance;
  189. }
  190. }
  191. this._hdrOutputLuminance = Tools.Clamp(this._hdrOutputLuminance, this.minimumLuminance, this.maximumLuminance);
  192. hdrLastLuminance += scene.getEngine().getDeltaTime();
  193. effect.setTextureFromPostProcess("textureSampler", this._textureAdderPostProcess);
  194. effect.setTextureFromPostProcess("otherSampler", this._originalPostProcess);
  195. effect.setFloat("exposure", this.exposure);
  196. effect.setFloat("avgLuminance", this._hdrOutputLuminance);
  197. this._needUpdate = false;
  198. };
  199. }
  200. /**
  201. * Texture Adder post-process
  202. */
  203. private _createTextureAdderPostProcess(scene: Scene, ratio: number): void {
  204. this._textureAdderPostProcess = new PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  205. this._textureAdderPostProcess.onApply = (effect: Effect) => {
  206. effect.setTextureFromPostProcess("otherSampler", this._originalPostProcess);
  207. };
  208. }
  209. /**
  210. * Down sample X4 post-process
  211. */
  212. private _createDownSampleX4PostProcess(scene: Scene, ratio: number): void {
  213. var downSampleX4Offsets = new Array<number>(32);
  214. this._downSampleX4PostProcess = new PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  215. this._downSampleX4PostProcess.onApply = (effect: Effect) => {
  216. if (this._needUpdate) {
  217. var id = 0;
  218. for (var i = -2; i < 2; i++) {
  219. for (var j = -2; j < 2; j++) {
  220. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / this._downSampleX4PostProcess.width);
  221. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / this._downSampleX4PostProcess.height);
  222. id += 2;
  223. }
  224. }
  225. }
  226. effect.setArray2("dsOffsets", downSampleX4Offsets);
  227. };
  228. }
  229. /**
  230. * Bright pass post-process
  231. */
  232. private _createBrightPassPostProcess(scene: Scene, ratio: number): void {
  233. var brightOffsets = new Array<number>(8);
  234. var brightPassCallback = (effect: Effect) => {
  235. if (this._needUpdate) {
  236. var sU = (1.0 / this._brightPassPostProcess.width);
  237. var sV = (1.0 / this._brightPassPostProcess.height);
  238. brightOffsets[0] = -0.5 * sU;
  239. brightOffsets[1] = 0.5 * sV;
  240. brightOffsets[2] = 0.5 * sU;
  241. brightOffsets[3] = 0.5 * sV;
  242. brightOffsets[4] = -0.5 * sU;
  243. brightOffsets[5] = -0.5 * sV;
  244. brightOffsets[6] = 0.5 * sU;
  245. brightOffsets[7] = -0.5 * sV;
  246. }
  247. effect.setArray2("dsOffsets", brightOffsets);
  248. effect.setFloat("brightThreshold", this.brightThreshold);
  249. };
  250. this._brightPassPostProcess = new PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  251. this._brightPassPostProcess.onApply = brightPassCallback;
  252. }
  253. /**
  254. * Luminance generator. Creates the luminance post-process and down sample post-processes
  255. */
  256. private _createLuminanceGeneratorPostProcess(scene: Scene): void {
  257. var lumSteps: number = HDRRenderingPipeline.LUM_STEPS;
  258. var luminanceOffsets = new Array<number>(8);
  259. var downSampleOffsets = new Array<number>(18);
  260. var halfDestPixelSize: number;
  261. this._downSamplePostProcesses = new Array<PostProcess>(lumSteps);
  262. // Utils for luminance
  263. var luminanceUpdateSourceOffsets = (width: number, height: number) => {
  264. var sU = (1.0 / width);
  265. var sV = (1.0 / height);
  266. luminanceOffsets[0] = -0.5 * sU;
  267. luminanceOffsets[1] = 0.5 * sV;
  268. luminanceOffsets[2] = 0.5 * sU;
  269. luminanceOffsets[3] = 0.5 * sV;
  270. luminanceOffsets[4] = -0.5 * sU;
  271. luminanceOffsets[5] = -0.5 * sV;
  272. luminanceOffsets[6] = 0.5 * sU;
  273. luminanceOffsets[7] = -0.5 * sV;
  274. };
  275. var luminanceUpdateDestOffsets = (width: number, height: number) => {
  276. var id = 0;
  277. for (var x = -1; x < 2; x++) {
  278. for (var y = -1; y < 2; y++) {
  279. downSampleOffsets[id] = (x) / width;
  280. downSampleOffsets[id + 1] = (y) / height;
  281. id += 2;
  282. }
  283. }
  284. };
  285. // Luminance callback
  286. var luminanceCallback = (effect: Effect) => {
  287. if (this._needUpdate) {
  288. luminanceUpdateSourceOffsets(this._textureAdderPostProcess.width, this._textureAdderPostProcess.height);
  289. }
  290. effect.setTextureFromPostProcess("textureSampler", this._textureAdderPostProcess);
  291. effect.setArray2("lumOffsets", luminanceOffsets);
  292. }
  293. // Down sample callbacks
  294. var downSampleCallback = (indice: number) => {
  295. var i = indice;
  296. return (effect: Effect) => {
  297. luminanceUpdateSourceOffsets(this._downSamplePostProcesses[i].width, this._downSamplePostProcesses[i].height);
  298. luminanceUpdateDestOffsets(this._downSamplePostProcesses[i].width, this._downSamplePostProcesses[i].height);
  299. halfDestPixelSize = 0.5 / this._downSamplePostProcesses[i].width;
  300. effect.setTextureFromPostProcess("textureSampler", this._downSamplePostProcesses[i + 1]);
  301. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  302. effect.setArray2("dsOffsets", downSampleOffsets);
  303. }
  304. };
  305. var downSampleAfterRenderCallback = (effect: Effect) => {
  306. // Unpack result
  307. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  308. 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);
  309. this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  310. };
  311. // Create luminance post-process
  312. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  313. this._downSamplePostProcesses[lumSteps - 1] = new PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", Engine.TEXTURETYPE_FLOAT);
  314. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  315. // Create down sample post-processes
  316. for (var i = lumSteps - 2; i >= 0; i--) {
  317. var length = Math.pow(3, i);
  318. ratio = { width: length, height: length };
  319. var defines = "#define DOWN_SAMPLE\n";
  320. if (i === 0) {
  321. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  322. }
  323. this._downSamplePostProcesses[i] = new PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, Engine.TEXTURETYPE_FLOAT);
  324. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  325. if (i === 0) {
  326. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  327. }
  328. }
  329. }
  330. /**
  331. * Gaussian blur post-processes. Horizontal and Vertical
  332. */
  333. private _createGaussianBlurPostProcess(scene: Scene, ratio: number): void {
  334. var blurOffsetsW = new Array<number>(9);
  335. var blurOffsetsH = new Array<number>(9);
  336. var blurWeights = new Array<number>(9);
  337. var uniforms: string[] = ["blurOffsets", "blurWeights", "multiplier"];
  338. // Utils for gaussian blur
  339. var calculateBlurOffsets = (height: boolean) => {
  340. var lastOutputDimensions: any = {
  341. width: scene.getEngine().getRenderWidth(),
  342. height: scene.getEngine().getRenderHeight()
  343. };
  344. for (var i = 0; i < 9; i++) {
  345. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  346. if (height) {
  347. blurOffsetsH[i] = value;
  348. } else {
  349. blurOffsetsW[i] = value;
  350. }
  351. }
  352. };
  353. var calculateWeights = () => {
  354. var x: number = 0.0;
  355. for (var i = 0; i < 9; i++) {
  356. x = (i - 4.0) / 4.0;
  357. blurWeights[i] = this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * this.gaussStandDev)) * Math.exp((-((x - this.gaussMean) * (x - this.gaussMean))) / (2.0 * this.gaussStandDev * this.gaussStandDev));
  358. }
  359. }
  360. // Callback
  361. var gaussianBlurCallback = (height: boolean) => {
  362. return (effect: Effect) => {
  363. if (this._needUpdate) {
  364. calculateWeights();
  365. calculateBlurOffsets(height);
  366. }
  367. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  368. effect.setArray("blurWeights", blurWeights);
  369. effect.setFloat("multiplier", this.gaussMultiplier);
  370. };
  371. };
  372. // Create horizontal gaussian blur post-processes
  373. this._guassianBlurHPostProcess = new PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  374. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  375. // Create vertical gaussian blur post-process
  376. this._guassianBlurVPostProcess = new PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  377. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  378. }
  379. }
  380. }