Debian Codegraph @

Data/Sys/Shaders/default_pre_post_process.glsl

raw
1 /***** COLOR CORRECTION *****/
2
3 // Color Space references:
4 // https://www.unravel.com.au/understanding-color-spaces
5
6 // SMPTE 170M - BT.601 (NTSC-M) -> BT.709
7 mat3 from_NTSCM = transpose(mat3(
8 0.939497225737661, 0.0502268452914346, 0.0102759289709032,
9 0.0177558637510127, 0.965824605885027, 0.0164195303639603,
10 -0.00162163209967010, -0.00437400622653655, 1.00599563832621));
11
12 // ARIB TR-B9 (9300K+27MPCD with chromatic adaptation) (NTSC-J) -> BT.709
13 mat3 from_NTSCJ = transpose(mat3(
14 0.768497526, -0.210804164, 0.000297427177,
15 0.0397904068, 1.04825413, 0.00555809540,
16 0.00147510506, 0.0328789241, 1.36515128));
17
18 // EBU - BT.470BG/BT.601 (PAL) -> BT.709
19 mat3 from_PAL = transpose(mat3(
20 1.04408168421813, -0.0440816842181253, 0.000000000000000,
21 0.000000000000000, 1.00000000000000, 0.000000000000000,
22 0.000000000000000, 0.0118044782106489, 0.988195521789351));
23
24 float3 LinearTosRGBGamma(float3 color)
25 {
26 const float a = 0.055;
27
28 for (int i = 0; i < 3; ++i)
29 {
30 float x = color[i];
31 if (x <= 0.0031308)
32 x = x * 12.92;
33 else
34 x = (1.0 + a) * pow(x, 1.0 / 2.4) - a;
35 color[i] = x;
36 }
37
38 return color;
39 }
40
41 float3 Rec709_Luminance = float3(0.2126, 0.7152, 0.0722);
42
43 float Luminance(float3 color, bool native_color_space)
44 {
45 if (native_color_space && OptionEnabled(correct_color_space))
46 {
47 if (game_color_space == 0)
48 color *= from_NTSCM;
49 else if (game_color_space == 1)
50 color *= from_NTSCJ;
51 else if (game_color_space == 2)
52 color *= from_PAL;
53 }
54 return dot(color, Rec709_Luminance);
55 }
56
57 /***** COLOR SAMPLING *****/
58
59 // Non filtered gamma corrected sample (nearest neighbor)
60 float4 QuickSample(float3 uvw, float gamma)
61 {
62 #if 0 // Test sampling range
63 const float threshold = 0.00000001;
64 float2 xy = uvw.xy * GetResolution();
65 // Sampling outside the valid range, draw in yellow
66 if (xy.x < (0.0 - threshold) || xy.x > (GetResolution().x + threshold) || xy.y < (0.0 - threshold) || xy.y > (GetResolution().y + threshold))
67 return float4(1.0, 1.0, 0.0, 1);
68 // Sampling at the edges, draw in purple
69 if (xy.x < 1.0 || xy.x > (GetResolution().x - 1.0) || xy.y < 1.0 || xy.y > (GetResolution().y - 1.0))
70 return float4(0.5, 0, 0.5, 1);
71 #endif
72
73 float4 color = texture(samp1, uvw);
74 color.rgb = pow(color.rgb, float3(gamma));
75 return color;
76 }
77 float4 QuickSample(float2 uv, float w, float gamma)
78 {
79 return QuickSample(float3(uv, w), gamma);
80 }
81 float4 QuickSampleByPixel(float2 xy, float w, float gamma)
82 {
83 float3 uvw = float3(xy * GetInvResolution(), w);
84 return QuickSample(uvw, gamma);
85 }
86
87 /***** Bilinear Interpolation *****/
88
89 float4 BilinearSample(float3 uvw, float gamma)
90 {
91 // This emulates the (bi)linear filtering done directly from GPUs HW.
92 // Note that GPUs might natively filter red green and blue differently, but we don't do it.
93 // They might also use different filtering between upscaling and downscaling.
94 float2 source_size = GetResolution();
95 float2 pixel = (uvw.xy * source_size) - 0.5; // Try to find the matching pixel top left corner
96
97 // Find the integer and floating point parts
98 float2 int_pixel = floor(pixel);
99 float2 frac_pixel = fract(pixel);
100
101 // Take 4 samples around the original uvw
102 float4 c11 = QuickSampleByPixel(int_pixel + float2(0.5, 0.5), uvw.z, gamma);
103 float4 c21 = QuickSampleByPixel(int_pixel + float2(1.5, 0.5), uvw.z, gamma);
104 float4 c12 = QuickSampleByPixel(int_pixel + float2(0.5, 1.5), uvw.z, gamma);
105 float4 c22 = QuickSampleByPixel(int_pixel + float2(1.5, 1.5), uvw.z, gamma);
106
107 // Blend the 4 samples by their weight
108 float4 avg_c = lerp(lerp(c11, c21, frac_pixel.x), lerp(c12, c22, frac_pixel.x), frac_pixel.y);
109
110 // Calculate the average of the gamma space luminance, as that can be used to
111 // properly determine the perceptual brightness the color should have.
112 float l11 = pow(Luminance(c11.rgb, true), 1.0 / gamma);
113 float l21 = pow(Luminance(c21.rgb, true), 1.0 / gamma);
114 float l12 = pow(Luminance(c12.rgb, true), 1.0 / gamma);
115 float l22 = pow(Luminance(c22.rgb, true), 1.0 / gamma);
116 float target_avg_c_lum = lerp(lerp(l11, l21, frac_pixel.x), lerp(l12, l22, frac_pixel.x), frac_pixel.y);
117
118 float avg_c_lum = Luminance(avg_c.rgb, true);
119 if (avg_c_lum != 0.0)
120 {
121 avg_c.rgb *= pow(target_avg_c_lum, gamma) / avg_c_lum;
122 }
123
124 return avg_c;
125 }
126
127 /***** Bicubic Interpolation *****/
128
129 // Formula derived from:
130 // https://en.wikipedia.org/wiki/Mitchell%E2%80%93Netravali_filters#Definition
131 // Values from:
132 // https://guideencodemoe-mkdocs.readthedocs.io/encoding/resampling/#mitchell-netravali-bicubic
133 // Other references:
134 // https://www.codeproject.com/Articles/236394/Bi-Cubic-and-Bi-Linear-Interpolation-with-GLSL
135 // https://github.com/ValveSoftware/gamescope/pull/740
136 // https://stackoverflow.com/questions/13501081/efficient-bicubic-filtering-code-in-glsl
137 #define CUBIC_COEFF_GEN(B, C) \
138 (mat4(/* t^0 */ ((B) / 6.0), (-(B) / 3.0 + 1.0), ((B) / 6.0), (0.0), \
139 /* t^1 */ (-(B) / 2.0 - (C)), (0.0), ((B) / 2.0 + (C)), (0.0), \
140 /* t^2 */ ((B) / 2.0 + 2.0 * (C)), (2.0 * (B) + (C)-3.0), \
141 (-5.0 * (B) / 2.0 - 2.0 * (C) + 3.0), (-(C)), \
142 /* t^3 */ (-(B) / 6.0 - (C)), (-3.0 * (B) / 2.0 - (C) + 2.0), \
143 (3.0 * (B) / 2.0 + (C)-2.0), ((B) / 6.0 + (C))))
144
145 float4 CubicCoeffs(float t, mat4 coeffs)
146 {
147 return coeffs * float4(1.0, t, t * t, t * t * t);
148 }
149
150 float4 CubicMix(float4 c0, float4 c1, float4 c2, float4 c3, float4 coeffs)
151 {
152 return c0 * coeffs[0] + c1 * coeffs[1] + c2 * coeffs[2] + c3 * coeffs[3];
153 }
154
155 // By Sam Belliveau. Public Domain license.
156 // Simple 16 tap, gamma correct, implementation of bicubic filtering.
157 float4 BicubicSample(float3 uvw, float gamma, mat4 coeffs)
158 {
159 float2 pixel = (uvw.xy * GetResolution()) - 0.5;
160 float2 int_pixel = floor(pixel);
161 float2 frac_pixel = fract(pixel);
162
163 float4 c00 = QuickSampleByPixel(int_pixel + float2(-0.5, -0.5), uvw.z, gamma);
164 float4 c10 = QuickSampleByPixel(int_pixel + float2(+0.5, -0.5), uvw.z, gamma);
165 float4 c20 = QuickSampleByPixel(int_pixel + float2(+1.5, -0.5), uvw.z, gamma);
166 float4 c30 = QuickSampleByPixel(int_pixel + float2(+2.5, -0.5), uvw.z, gamma);
167
168 float4 c01 = QuickSampleByPixel(int_pixel + float2(-0.5, +0.5), uvw.z, gamma);
169 float4 c11 = QuickSampleByPixel(int_pixel + float2(+0.5, +0.5), uvw.z, gamma);
170 float4 c21 = QuickSampleByPixel(int_pixel + float2(+1.5, +0.5), uvw.z, gamma);
171 float4 c31 = QuickSampleByPixel(int_pixel + float2(+2.5, +0.5), uvw.z, gamma);
172
173 float4 c02 = QuickSampleByPixel(int_pixel + float2(-0.5, +1.5), uvw.z, gamma);
174 float4 c12 = QuickSampleByPixel(int_pixel + float2(+0.5, +1.5), uvw.z, gamma);
175 float4 c22 = QuickSampleByPixel(int_pixel + float2(+1.5, +1.5), uvw.z, gamma);
176 float4 c32 = QuickSampleByPixel(int_pixel + float2(+2.5, +1.5), uvw.z, gamma);
177
178 float4 c03 = QuickSampleByPixel(int_pixel + float2(-0.5, +2.5), uvw.z, gamma);
179 float4 c13 = QuickSampleByPixel(int_pixel + float2(+0.5, +2.5), uvw.z, gamma);
180 float4 c23 = QuickSampleByPixel(int_pixel + float2(+1.5, +2.5), uvw.z, gamma);
181 float4 c33 = QuickSampleByPixel(int_pixel + float2(+2.5, +2.5), uvw.z, gamma);
182
183 float4 cx = CubicCoeffs(frac_pixel.x, coeffs);
184 float4 cy = CubicCoeffs(frac_pixel.y, coeffs);
185
186 float4 x0 = CubicMix(c00, c10, c20, c30, cx);
187 float4 x1 = CubicMix(c01, c11, c21, c31, cx);
188 float4 x2 = CubicMix(c02, c12, c22, c32, cx);
189 float4 x3 = CubicMix(c03, c13, c23, c33, cx);
190
191 return CubicMix(x0, x1, x2, x3, cy);
192 }
193
194 /***** Sharp Bilinear Filtering *****/
195
196 // Based on https://github.com/libretro/slang-shaders/blob/master/interpolation/shaders/sharp-bilinear.slang
197 // by Themaister, Public Domain license
198 // Does a bilinear stretch, with a preapplied Nx nearest-neighbor scale,
199 // giving a sharper image than plain bilinear.
200 float4 SharpBilinearSample(float3 uvw, float gamma)
201 {
202 float2 source_size = GetResolution();
203 float2 inverted_source_size = GetInvResolution();
204 float2 target_size = GetWindowResolution();
205 float2 texel = uvw.xy * source_size;
206 float2 texel_floored = floor(texel);
207 float2 s = fract(texel);
208 float scale = max(floor(max(target_size.x * inverted_source_size.x, target_size.y * inverted_source_size.y)), 1.0);
209 float region_range = 0.5 - (0.5 / scale);
210
211 // Figure out where in the texel to sample to get correct pre-scaled bilinear.
212
213 float2 center_dist = s - 0.5;
214 float2 f = ((center_dist - clamp(center_dist, -region_range, region_range)) * scale) + 0.5;
215
216 float2 mod_texel = texel_floored + f;
217
218 uvw.xy = mod_texel * inverted_source_size;
219 return BilinearSample(uvw, gamma);
220 }
221
222 /***** Area Sampling *****/
223
224 // By Sam Belliveau and Filippo Tarpini. Public Domain license.
225 // Effectively a more accurate sharp bilinear filter when upscaling,
226 // that also works as a mathematically perfect downscale filter.
227 // https://entropymine.com/imageworsener/pixelmixing/
228 // https://github.com/obsproject/obs-studio/pull/1715
229 // https://legacy.imagemagick.org/Usage/filter/
230 float4 AreaSampling(float3 uvw, float gamma)
231 {
232 // Determine the sizes of the source and target images.
233 float2 source_size = GetResolution();
234 float2 target_size = GetWindowResolution();
235 float2 inverted_target_size = GetInvWindowResolution();
236
237 // Compute the top-left and bottom-right corners of the target pixel box.
238 float2 t_beg = floor(uvw.xy * target_size);
239 float2 t_end = t_beg + float2(1.0, 1.0);
240
241 // Convert the target pixel box to source pixel box.
242 float2 beg = t_beg * inverted_target_size * source_size;
243 float2 end = t_end * inverted_target_size * source_size;
244
245 // Compute the top-left and bottom-right corners of the pixel box.
246 float2 f_beg = floor(beg);
247 float2 f_end = floor(end);
248
249 // Compute how much of the start and end pixels are covered horizontally & vertically.
250 float area_w = 1.0 - fract(beg.x);
251 float area_n = 1.0 - fract(beg.y);
252 float area_e = fract(end.x);
253 float area_s = fract(end.y);
254
255 // Compute the areas of the corner pixels in the pixel box.
256 float area_nw = area_n * area_w;
257 float area_ne = area_n * area_e;
258 float area_sw = area_s * area_w;
259 float area_se = area_s * area_e;
260
261 // Initialize the color accumulator.
262 float4 avg_color = float4(0.0, 0.0, 0.0, 0.0);
263 float avg_luminance = 0.0;
264 float4 temp_color;
265
266 float luminance_gamma = gamma; // For now, default to the user selected gamma (alternatively we could fix it to anything between 2.2 and 3.0)
267 float luminance_inv_gamma = 1.0 / luminance_gamma;
268
269 // Prevents rounding errors due to the coordinates flooring above
270 const float2 offset = float2(0.5, 0.5);
271
272 // Accumulate corner pixels.
273 temp_color = QuickSampleByPixel(float2(f_beg.x, f_beg.y) + offset, uvw.z, gamma);
274 avg_color += area_nw * temp_color;
275 avg_luminance += area_nw * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
276 temp_color = QuickSampleByPixel(float2(f_end.x, f_beg.y) + offset, uvw.z, gamma);
277 avg_color += area_ne * temp_color;
278 avg_luminance += area_ne * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
279 temp_color = QuickSampleByPixel(float2(f_beg.x, f_end.y) + offset, uvw.z, gamma);
280 avg_color += area_sw * temp_color;
281 avg_luminance += area_sw * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
282 temp_color = QuickSampleByPixel(float2(f_end.x, f_end.y) + offset, uvw.z, gamma);
283 avg_color += area_se * temp_color;
284 avg_luminance += area_se * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
285
286 // Determine the size of the pixel box.
287 int x_range = int(f_end.x - f_beg.x - 0.5);
288 int y_range = int(f_end.y - f_beg.y - 0.5);
289
290 // Workaround to compile the shader with DX11/12.
291 // If this isn't done, it will complain that the loop could have too many iterations.
292 // This number should be enough to guarantee downscaling from very high to very small resolutions.
293 // Note that this number might be referenced in the UI.
294 const int max_iterations = 16;
295
296 // Fix up the average calculations in case we reached the upper limit
297 x_range = min(x_range, max_iterations);
298 y_range = min(y_range, max_iterations);
299
300 // Accumulate top and bottom edge pixels.
301 for (int ix = 0; ix < max_iterations; ++ix)
302 {
303 if (ix < x_range)
304 {
305 float x = f_beg.x + 1.0 + float(ix);
306 temp_color = QuickSampleByPixel(float2(x, f_beg.y) + offset, uvw.z, gamma);
307 avg_color += area_n * temp_color;
308 avg_luminance += area_n * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
309 temp_color = QuickSampleByPixel(float2(x, f_end.y) + offset, uvw.z, gamma);
310 avg_color += area_s * temp_color;
311 avg_luminance += area_s * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
312 }
313 }
314
315 // Accumulate left and right edge pixels and all the pixels in between.
316 for (int iy = 0; iy < max_iterations; ++iy)
317 {
318 if (iy < y_range)
319 {
320 float y = f_beg.y + 1.0 + float(iy);
321
322 temp_color = QuickSampleByPixel(float2(f_beg.x, y) + offset, uvw.z, gamma);
323 avg_color += area_w * temp_color;
324 avg_luminance += area_w * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
325 temp_color = QuickSampleByPixel(float2(f_end.x, y) + offset, uvw.z, gamma);
326 avg_color += area_e * temp_color;
327 avg_luminance += area_e * pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
328
329 for (int ix = 0; ix < max_iterations; ++ix)
330 {
331 if (ix < x_range)
332 {
333 float x = f_beg.x + 1.0 + float(ix);
334 temp_color = QuickSampleByPixel(float2(x, y) + offset, uvw.z, gamma);
335 avg_color += temp_color;
336 avg_luminance += pow(Luminance(temp_color.rgb, true), luminance_inv_gamma);
337 }
338 }
339 }
340 }
341
342 // Compute the area of the pixel box that was sampled.
343 float area_corners = area_nw + area_ne + area_sw + area_se;
344 float area_edges = float(x_range) * (area_n + area_s) + float(y_range) * (area_w + area_e);
345 float area_center = float(x_range) * float(y_range);
346
347 float4 nrm_color = avg_color / (area_corners + area_edges + area_center);
348 float target_nrm_color_luminance = avg_luminance / (area_corners + area_edges + area_center);
349
350 // Restore the averaged "gamma" space luminance, for better gamma correction.
351 // This retains the best feature of gamma correct sampling (no hue shifts),
352 // while also maintaining the perceptual "brightness" level of blending two colors with an alpha
353 // (in linear space a 0.5 alpha won't produce a color that has a perceptual brightness in the middle point of the two source colors).
354 float nrm_color_luminance = Luminance(nrm_color.rgb, true);
355 if (nrm_color_luminance != 0.0)
356 {
357 nrm_color.rgb *= pow(target_nrm_color_luminance, luminance_gamma) / nrm_color_luminance;
358 }
359
360 // Return the normalized average color.
361 return nrm_color;
362 }
363
364 /***** Main Functions *****/
365
366 // Returns an accurate (gamma corrected) sample of a gamma space space texture.
367 // Outputs in linear space for simplicity.
368 float4 LinearGammaCorrectedSample(float gamma)
369 {
370 float3 uvw = v_tex0;
371 float4 color = float4(0, 0, 0, 1);
372
373 if (resampling_method <= 1) // Bilinear
374 {
375 color = BilinearSample(uvw, gamma);
376 }
377 else if (resampling_method == 2) // Bicubic: B-Spline
378 {
379 color = BicubicSample(uvw, gamma, CUBIC_COEFF_GEN(1.0, 0.0));
380 }
381 else if (resampling_method == 3) // Bicubic: Mitchell-Netravali
382 {
383 color = BicubicSample(uvw, gamma, CUBIC_COEFF_GEN(1.0 / 3.0, 1.0 / 3.0));
384 }
385 else if (resampling_method == 4) // Bicubic: Catmull-Rom
386 {
387 color = BicubicSample(uvw, gamma, CUBIC_COEFF_GEN(0.0, 0.5));
388 }
389 else if (resampling_method == 5) // Sharp Bilinear
390 {
391 color = SharpBilinearSample(uvw, gamma);
392 }
393 else if (resampling_method == 6) // Area Sampling
394 {
395 color = AreaSampling(uvw, gamma);
396 }
397 else if (resampling_method == 7) // Nearest Neighbor
398 {
399 color = QuickSample(uvw, gamma);
400 }
401 else if (resampling_method == 8) // Bicubic: Hermite
402 {
403 color = BicubicSample(uvw, gamma, CUBIC_COEFF_GEN(0.0, 0.0));
404 }
405
406 return color;
407 }
408
409 void main()
410 {
411 // This tries to fall back on GPU HW sampling if it can (it won't be gamma corrected).
412 bool raw_resampling = resampling_method <= 0;
413 bool needs_rescaling = GetResolution() != GetWindowResolution();
414
415 bool needs_resampling = needs_rescaling && (OptionEnabled(hdr_output) || OptionEnabled(correct_gamma) || !raw_resampling);
416
417 float4 color;
418
419 if (needs_resampling)
420 {
421 // Doing linear sampling in "gamma space" on linear texture formats isn't correct.
422 // If the source and target resolutions don't match, the GPU will return a color
423 // that is the average of 4 gamma space colors, but gamma space colors can't be blended together,
424 // gamma needs to be de-applied first. This makes a big difference if colors change
425 // drastically between two pixels.
426
427 color = LinearGammaCorrectedSample(game_gamma);
428 }
429 else
430 {
431 // Default GPU HW sampling. Bilinear is identical to Nearest Neighbor if the input and output resolutions match.
432 if (needs_rescaling)
433 color = texture(samp0, v_tex0);
434 else
435 color = texture(samp1, v_tex0);
436
437 // Convert to linear before doing any other of follow up operations.
438 color.rgb = pow(color.rgb, float3(game_gamma));
439 }
440
441 if (OptionEnabled(correct_color_space))
442 {
443 if (game_color_space == 0)
444 color.rgb = color.rgb * from_NTSCM;
445 else if (game_color_space == 1)
446 color.rgb = color.rgb * from_NTSCJ;
447 else if (game_color_space == 2)
448 color.rgb = color.rgb * from_PAL;
449 }
450
451 if (OptionEnabled(hdr_output))
452 {
453 float hdr_paper_white = hdr_paper_white_nits / hdr_sdr_white_nits;
454 color.rgb *= hdr_paper_white;
455 }
456
457 if (OptionEnabled(linear_space_output))
458 {
459 // Nothing to do here
460 }
461 // Correct the SDR gamma for sRGB (PC/Monitor) or ~2.2 (Common TV gamma)
462 else if (OptionEnabled(correct_gamma))
463 {
464 if (OptionEnabled(sdr_display_gamma_sRGB))
465 color.rgb = LinearTosRGBGamma(color.rgb);
466 else
467 color.rgb = pow(color.rgb, float3(1.0 / sdr_display_custom_gamma));
468 }
469 // Restore the original gamma without changes
470 else
471 {
472 color.rgb = pow(color.rgb, float3(1.0 / game_gamma));
473 }
474
475 SetOutput(color);
476 }