Debian Codegraph @

Source/Core/VideoCommon/PostProcessing.cpp

raw symbols SCIP
1 // Copyright 2014 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/PostProcessing.h"
5
6 #include <sstream>
7 #include <string>
8 #include <string_view>
9
10 #include <fmt/format.h>
11
12 #include "Common/Assert.h"
13 #include "Common/CommonPaths.h"
14 #include "Common/CommonTypes.h"
15 #include "Common/FileSearch.h"
16 #include "Common/FileUtil.h"
17 #include "Common/IniFile.h"
18 #include "Common/Logging/Log.h"
19 #include "Common/MsgHandler.h"
20 #include "Common/StringUtil.h"
21
22 #include "VideoCommon/AbstractFramebuffer.h"
23 #include "VideoCommon/AbstractGfx.h"
24 #include "VideoCommon/AbstractPipeline.h"
25 #include "VideoCommon/AbstractShader.h"
26 #include "VideoCommon/AbstractTexture.h"
27 #include "VideoCommon/Present.h"
28 #include "VideoCommon/ShaderCache.h"
29 #include "VideoCommon/ShaderCompileUtils.h"
30 #include "VideoCommon/VertexManagerBase.h"
31 #include "VideoCommon/VideoCommon.h"
32 #include "VideoCommon/VideoConfig.h"
33
34 namespace VideoCommon
35 {
36 static const char s_empty_pixel_shader[] = "void main() { SetOutput(Sample()); }\n";
37 static const char s_default_pixel_shader_name[] = "default_pre_post_process";
38 // Keep the highest quality possible to avoid losing quality on subtle gamma conversions.
39 // RGBA16F should have enough quality even if we store colors in gamma space on it.
40 static const AbstractTextureFormat s_intermediary_buffer_format = AbstractTextureFormat::RGBA16F;
41
42 static bool LoadShaderFromFile(const std::string& shader, const std::string& sub_dir,
43 std::string& out_code)
44 {
45 std::string path = File::GetUserPath(D_SHADERS_IDX) + sub_dir + shader + ".glsl";
46
47 if (!File::Exists(path))
48 {
49 // Fallback to shared user dir
50 path = File::GetSysDirectory() + SHADERS_DIR DIR_SEP + sub_dir + shader + ".glsl";
51 }
52
53 if (!File::ReadFileToString(path, out_code))
54 {
55 out_code = "";
56 ERROR_LOG_FMT(VIDEO, "Post-processing shader not found: {}", path);
57 return false;
58 }
59
60 return true;
61 }
62
63 PostProcessingConfiguration::PostProcessingConfiguration() = default;
64
65 PostProcessingConfiguration::~PostProcessingConfiguration() = default;
66
67 void PostProcessingConfiguration::LoadShader(const std::string& shader)
68 {
69 // Load the shader from the configuration if there isn't one sent to us.
70 m_current_shader = shader;
71 if (shader.empty())
72 {
73 LoadDefaultShader();
74 return;
75 }
76
77 std::string sub_dir = "";
78
79 if (g_Config.stereo_mode == StereoMode::Anaglyph)
80 {
81 sub_dir = ANAGLYPH_DIR DIR_SEP;
82 }
83 else if (g_Config.stereo_mode == StereoMode::Passive)
84 {
85 sub_dir = PASSIVE_DIR DIR_SEP;
86 }
87
88 std::string code;
89 if (!LoadShaderFromFile(shader, sub_dir, code))
90 {
91 LoadDefaultShader();
92 return;
93 }
94
95 LoadOptions(code);
96 // Note that this will build the shaders with the custom options values users
97 // might have set in the settings
98 LoadOptionsConfiguration();
99 m_current_shader_code = code;
100 m_shader_includer =
101 std::make_unique<ShaderIncluder>(File::GetUserPath(D_SHADERS_IDX) + sub_dir,
102 File::GetSysDirectory() + SHADERS_DIR DIR_SEP + sub_dir);
103 }
104
105 void PostProcessingConfiguration::LoadDefaultShader()
106 {
107 m_options.clear();
108 m_any_options_dirty = false;
109 m_current_shader = "";
110 m_current_shader_code = s_empty_pixel_shader;
111 }
112
113 void PostProcessingConfiguration::LoadOptions(const std::string& code)
114 {
115 const std::string config_start_delimiter = "[configuration]";
116 const std::string config_end_delimiter = "[/configuration]";
117 size_t configuration_start = code.find(config_start_delimiter);
118 size_t configuration_end = code.find(config_end_delimiter);
119
120 m_options.clear();
121 m_any_options_dirty = true;
122
123 if (configuration_start == std::string::npos || configuration_end == std::string::npos)
124 {
125 // Issue loading configuration or there isn't one.
126 return;
127 }
128
129 std::string configuration_string =
130 code.substr(configuration_start + config_start_delimiter.size(),
131 configuration_end - configuration_start - config_start_delimiter.size());
132
133 std::istringstream in(configuration_string);
134
135 struct GLSLStringOption
136 {
137 std::string m_type;
138 std::vector<std::pair<std::string, std::string>> m_options;
139 };
140
141 std::vector<GLSLStringOption> option_strings;
142 GLSLStringOption* current_strings = nullptr;
143 std::string line_str;
144 while (std::getline(in, line_str))
145 {
146 std::string_view line = line_str;
147
148 #ifndef _WIN32
149 // Check for CRLF eol and convert it to LF
150 if (!line.empty() && line.at(line.size() - 1) == '\r')
151 line.remove_suffix(1);
152 #endif
153
154 if (!line.empty())
155 {
156 if (line[0] == '[')
157 {
158 size_t endpos = line.find("]");
159
160 if (endpos != std::string::npos)
161 {
162 // New section!
163 std::string_view sub = line.substr(1, endpos - 1);
164 option_strings.push_back({std::string(sub)});
165 current_strings = &option_strings.back();
166 }
167 }
168 else
169 {
170 if (current_strings)
171 {
172 std::string key, value;
173 Common::IniFile::ParseLine(line, &key, &value);
174
175 if (!(key.empty() && value.empty()))
176 current_strings->m_options.emplace_back(key, value);
177 }
178 }
179 }
180 }
181
182 for (const auto& it : option_strings)
183 {
184 ConfigurationOption option;
185 option.m_dirty = true;
186
187 if (it.m_type == "OptionBool")
188 option.m_type = ConfigurationOption::OptionType::Bool;
189 else if (it.m_type == "OptionRangeFloat")
190 option.m_type = ConfigurationOption::OptionType::Float;
191 else if (it.m_type == "OptionRangeInteger")
192 option.m_type = ConfigurationOption::OptionType::Integer;
193
194 for (const auto& string_option : it.m_options)
195 {
196 if (string_option.first == "GUIName")
197 {
198 option.m_gui_name = string_option.second;
199 }
200 else if (string_option.first == "OptionName")
201 {
202 option.m_option_name = string_option.second;
203 }
204 else if (string_option.first == "DependentOption")
205 {
206 option.m_dependent_option = string_option.second;
207 }
208 else if (string_option.first == "MinValue" || string_option.first == "MaxValue" ||
209 string_option.first == "DefaultValue" || string_option.first == "StepAmount")
210 {
211 std::vector<s32>* output_integer = nullptr;
212 std::vector<float>* output_float = nullptr;
213
214 if (string_option.first == "MinValue")
215 {
216 output_integer = &option.m_integer_min_values;
217 output_float = &option.m_float_min_values;
218 }
219 else if (string_option.first == "MaxValue")
220 {
221 output_integer = &option.m_integer_max_values;
222 output_float = &option.m_float_max_values;
223 }
224 else if (string_option.first == "DefaultValue")
225 {
226 output_integer = &option.m_integer_values;
227 output_float = &option.m_float_values;
228 }
229 else if (string_option.first == "StepAmount")
230 {
231 output_integer = &option.m_integer_step_values;
232 output_float = &option.m_float_step_values;
233 }
234
235 if (option.m_type == ConfigurationOption::OptionType::Bool)
236 {
237 TryParse(string_option.second, &option.m_bool_value);
238 }
239 else if (option.m_type == ConfigurationOption::OptionType::Integer)
240 {
241 TryParseVector(string_option.second, output_integer);
242 if (output_integer->size() > 4)
243 output_integer->erase(output_integer->begin() + 4, output_integer->end());
244 }
245 else if (option.m_type == ConfigurationOption::OptionType::Float)
246 {
247 TryParseVector(string_option.second, output_float);
248 if (output_float->size() > 4)
249 output_float->erase(output_float->begin() + 4, output_float->end());
250 }
251 }
252 }
253 m_options[option.m_option_name] = option;
254 }
255 }
256
257 void PostProcessingConfiguration::LoadOptionsConfiguration()
258 {
259 Common::IniFile ini;
260 ini.Load(File::GetUserPath(F_DOLPHINCONFIG_IDX));
261 std::string section = m_current_shader + "-options";
262
263 // We already expect all the options to be marked as "dirty" when we reach here
264 for (auto& it : m_options)
265 {
266 switch (it.second.m_type)
267 {
268 case ConfigurationOption::OptionType::Bool:
269 ini.GetOrCreateSection(section)->Get(it.second.m_option_name, &it.second.m_bool_value,
270 it.second.m_bool_value);
271 break;
272 case ConfigurationOption::OptionType::Integer:
273 {
274 std::string value;
275 ini.GetOrCreateSection(section)->Get(it.second.m_option_name, &value);
276 if (!value.empty())
277 {
278 auto integer_values = it.second.m_integer_values;
279 if (TryParseVector(value, &integer_values))
280 {
281 it.second.m_integer_values = integer_values;
282 }
283 }
284 }
285 break;
286 case ConfigurationOption::OptionType::Float:
287 {
288 std::string value;
289 ini.GetOrCreateSection(section)->Get(it.second.m_option_name, &value);
290 if (!value.empty())
291 {
292 auto float_values = it.second.m_float_values;
293 if (TryParseVector(value, &float_values))
294 {
295 it.second.m_float_values = float_values;
296 }
297 }
298 }
299 break;
300 }
301 }
302 }
303
304 void PostProcessingConfiguration::SaveOptionsConfiguration()
305 {
306 Common::IniFile ini;
307 ini.Load(File::GetUserPath(F_DOLPHINCONFIG_IDX));
308 std::string section = m_current_shader + "-options";
309
310 for (auto& it : m_options)
311 {
312 switch (it.second.m_type)
313 {
314 case ConfigurationOption::OptionType::Bool:
315 {
316 ini.GetOrCreateSection(section)->Set(it.second.m_option_name, it.second.m_bool_value);
317 }
318 break;
319 case ConfigurationOption::OptionType::Integer:
320 {
321 std::string value;
322 for (size_t i = 0; i < it.second.m_integer_values.size(); ++i)
323 {
324 value += fmt::format("{}{}", it.second.m_integer_values[i],
325 i == (it.second.m_integer_values.size() - 1) ? "" : ", ");
326 }
327 ini.GetOrCreateSection(section)->Set(it.second.m_option_name, value);
328 }
329 break;
330 case ConfigurationOption::OptionType::Float:
331 {
332 std::ostringstream value;
333 value.imbue(std::locale("C"));
334
335 for (size_t i = 0; i < it.second.m_float_values.size(); ++i)
336 {
337 value << it.second.m_float_values[i];
338 if (i != (it.second.m_float_values.size() - 1))
339 value << ", ";
340 }
341 ini.GetOrCreateSection(section)->Set(it.second.m_option_name, value.str());
342 }
343 break;
344 }
345 }
346 ini.Save(File::GetUserPath(F_DOLPHINCONFIG_IDX));
347 }
348
349 void PostProcessingConfiguration::SetOptionf(const std::string& option, int index, float value)
350 {
351 auto it = m_options.find(option);
352
353 it->second.m_float_values[index] = value;
354 it->second.m_dirty = true;
355 m_any_options_dirty = true;
356 }
357
358 void PostProcessingConfiguration::SetOptioni(const std::string& option, int index, s32 value)
359 {
360 auto it = m_options.find(option);
361
362 it->second.m_integer_values[index] = value;
363 it->second.m_dirty = true;
364 m_any_options_dirty = true;
365 }
366
367 void PostProcessingConfiguration::SetOptionb(const std::string& option, bool value)
368 {
369 auto it = m_options.find(option);
370
371 it->second.m_bool_value = value;
372 it->second.m_dirty = true;
373 m_any_options_dirty = true;
374 }
375
376 PostProcessing::PostProcessing()
377 {
378 m_timer.Start();
379 }
380
381 PostProcessing::~PostProcessing()
382 {
383 m_timer.Stop();
384 }
385
386 static std::vector<std::string> GetShaders(const std::string& sub_dir = "")
387 {
388 std::vector<std::string> paths =
389 Common::DoFileSearch({{File::GetUserPath(D_SHADERS_IDX) + sub_dir,
390 File::GetSysDirectory() + SHADERS_DIR DIR_SEP + sub_dir}},
391 ".glsl");
392 std::vector<std::string> result;
393 for (std::string path : paths)
394 {
395 std::string name;
396 SplitPath(path, nullptr, &name, nullptr);
397 if (name == s_default_pixel_shader_name)
398 continue;
399 result.push_back(name);
400 }
401 return result;
402 }
403
404 std::vector<std::string> PostProcessing::GetShaderList()
405 {
406 return GetShaders();
407 }
408
409 std::vector<std::string> PostProcessing::GetAnaglyphShaderList()
410 {
411 return GetShaders(ANAGLYPH_DIR DIR_SEP);
412 }
413
414 std::vector<std::string> PostProcessing::GetPassiveShaderList()
415 {
416 return GetShaders(PASSIVE_DIR DIR_SEP);
417 }
418
419 bool PostProcessing::Initialize(AbstractTextureFormat format)
420 {
421 m_framebuffer_format = format;
422 // CompilePixelShader() must be run first if configuration options are used.
423 // Otherwise the UBO has a different member list between vertex and pixel
424 // shaders, which is a link error on some backends.
425 if (!CompilePixelShader() || !CompileVertexShader() || !CompilePipeline())
426 return false;
427
428 return true;
429 }
430
431 void PostProcessing::RecompileShader()
432 {
433 // Note: for simplicity we already recompile all the shaders
434 // and pipelines even if there might not be need to.
435
436 m_default_pipeline.reset();
437 m_pipeline.reset();
438 m_default_pixel_shader.reset();
439 m_pixel_shader.reset();
440 m_default_vertex_shader.reset();
441 m_vertex_shader.reset();
442 if (!CompilePixelShader())
443 return;
444 if (!CompileVertexShader())
445 return;
446
447 CompilePipeline();
448 }
449
450 void PostProcessing::RecompilePipeline()
451 {
452 m_default_pipeline.reset();
453 m_pipeline.reset();
454 CompilePipeline();
455 }
456
457 bool PostProcessing::IsColorCorrectionActive() const
458 {
459 // We can skip the color correction pass if none of these settings are on
460 // (it might have still helped with gamma correct sampling, but it's not worth running it).
461 return g_ActiveConfig.color_correction.bCorrectColorSpace ||
462 g_ActiveConfig.color_correction.bCorrectGamma ||
463 m_framebuffer_format == AbstractTextureFormat::RGBA16F;
464 }
465
466 bool PostProcessing::NeedsIntermediaryBuffer() const
467 {
468 // If we have no user selected post process shader,
469 // there's no point in having an intermediary buffer doing nothing.
470 return !m_config.GetShader().empty();
471 }
472
473 void PostProcessing::BlitFromTexture(const MathUtil::Rectangle<int>& dst,
474 const MathUtil::Rectangle<int>& src,
475 const AbstractTexture* src_tex, int src_layer)
476 {
477 if (g_gfx->GetCurrentFramebuffer()->GetColorFormat() != m_framebuffer_format)
478 {
479 m_framebuffer_format = g_gfx->GetCurrentFramebuffer()->GetColorFormat();
480 RecompilePipeline();
481 }
482
483 // By default all source layers will be copied into the respective target layers
484 const bool copy_all_layers = src_layer < 0;
485 src_layer = std::max(src_layer, 0);
486
487 MathUtil::Rectangle<int> src_rect = src;
488 g_gfx->SetSamplerState(0, RenderState::GetLinearSamplerState());
489 g_gfx->SetSamplerState(1, RenderState::GetPointSamplerState());
490 g_gfx->SetTexture(0, src_tex);
491 g_gfx->SetTexture(1, src_tex);
492
493 const bool needs_color_correction = IsColorCorrectionActive();
494 // Rely on the default (bi)linear sampler with the default mode
495 // (it might not be gamma corrected).
496 const bool needs_resampling =
497 g_ActiveConfig.output_resampling_mode > OutputResamplingMode::Default;
498 const bool needs_intermediary_buffer = NeedsIntermediaryBuffer();
499 const bool needs_default_pipeline = needs_color_correction || needs_resampling;
500 const AbstractPipeline* final_pipeline = m_pipeline.get();
501 std::vector<u8>* uniform_staging_buffer = &m_default_uniform_staging_buffer;
502 bool default_uniform_staging_buffer = true;
503 const MathUtil::Rectangle<int> present_rect = g_presenter->GetTargetRectangle();
504
505 // Intermediary pass.
506 // We draw to a high quality intermediary texture for a couple reasons:
507 // -Consistently do high quality gamma corrected resampling (upscaling/downscaling)
508 // -Keep quality for gamma and gamut conversions, and HDR output
509 // (low bit depths lose too much quality with gamma conversions)
510 // -Keep the post process phase in linear space, to better operate with colors
511 if (m_default_pipeline && needs_default_pipeline && needs_intermediary_buffer)
512 {
513 AbstractFramebuffer* const previous_framebuffer = g_gfx->GetCurrentFramebuffer();
514
515 // We keep the min number of layers as the render target,
516 // as in case of OpenGL, the source FBX will have two layers,
517 // but we will render onto two separate frame buffers (one by one),
518 // so it would be a waste to allocate two layers (see "bUsesExplictQuadBuffering").
519 const u32 target_layers = copy_all_layers ? src_tex->GetLayers() : 1;
520
521 const u32 target_width =
522 needs_resampling ? present_rect.GetWidth() : static_cast<u32>(src_rect.GetWidth());
523 const u32 target_height =
524 needs_resampling ? present_rect.GetHeight() : static_cast<u32>(src_rect.GetHeight());
525
526 if (!m_intermediary_frame_buffer || !m_intermediary_color_texture ||
527 m_intermediary_color_texture->GetWidth() != target_width ||
528 m_intermediary_color_texture->GetHeight() != target_height ||
529 m_intermediary_color_texture->GetLayers() != target_layers)
530 {
531 const TextureConfig intermediary_color_texture_config(
532 target_width, target_height, 1, target_layers, src_tex->GetSamples(),
533 s_intermediary_buffer_format, AbstractTextureFlag_RenderTarget,
534 AbstractTextureType::Texture_2DArray);
535 m_intermediary_color_texture = g_gfx->CreateTexture(intermediary_color_texture_config,
536 "Intermediary post process texture");
537
538 m_intermediary_frame_buffer =
539 g_gfx->CreateFramebuffer(m_intermediary_color_texture.get(), nullptr);
540 }
541
542 g_gfx->SetFramebuffer(m_intermediary_frame_buffer.get());
543
544 FillUniformBuffer(src_rect, src_tex, src_layer, g_gfx->GetCurrentFramebuffer()->GetRect(),
545 present_rect, uniform_staging_buffer->data(), !default_uniform_staging_buffer,
546 true);
547 g_vertex_manager->UploadUtilityUniforms(uniform_staging_buffer->data(),
548 static_cast<u32>(uniform_staging_buffer->size()));
549
550 g_gfx->SetViewportAndScissor(g_gfx->ConvertFramebufferRectangle(
551 m_intermediary_color_texture->GetRect(), m_intermediary_frame_buffer.get()));
552 g_gfx->SetPipeline(m_default_pipeline.get());
553 g_gfx->Draw(0, 3);
554
555 g_gfx->SetFramebuffer(previous_framebuffer);
556 src_rect = m_intermediary_color_texture->GetRect();
557 src_tex = m_intermediary_color_texture.get();
558 g_gfx->SetTexture(0, src_tex);
559 g_gfx->SetTexture(1, src_tex);
560 // The "m_intermediary_color_texture" has already copied
561 // from the specified source layer onto its first one.
562 // If we query for a layer that the source texture doesn't have,
563 // it will fall back on the first one anyway.
564 src_layer = 0;
565 uniform_staging_buffer = &m_uniform_staging_buffer;
566 default_uniform_staging_buffer = false;
567 }
568 else
569 {
570 // If we have no custom user shader selected, and color correction
571 // is active, directly run the fixed pipeline shader instead of
572 // doing two passes, with the second one doing nothing useful.
573 if (m_default_pipeline && needs_default_pipeline)
574 {
575 final_pipeline = m_default_pipeline.get();
576 }
577 else
578 {
579 uniform_staging_buffer = &m_uniform_staging_buffer;
580 default_uniform_staging_buffer = false;
581 }
582
583 m_intermediary_frame_buffer.reset();
584 m_intermediary_color_texture.reset();
585 }
586
587 // TODO: ideally we'd do the user selected post process pass in the intermediary buffer in linear
588 // space (instead of gamma space), so the shaders could act more accurately (and sample in linear
589 // space), though that would break the look of some of current post processes we have, and thus is
590 // better avoided for now.
591
592 // Final pass, either a user selected shader or the default (fixed) shader.
593 if (final_pipeline)
594 {
595 FillUniformBuffer(src_rect, src_tex, src_layer, g_gfx->GetCurrentFramebuffer()->GetRect(),
596 present_rect, uniform_staging_buffer->data(), !default_uniform_staging_buffer,
597 false);
598 g_vertex_manager->UploadUtilityUniforms(uniform_staging_buffer->data(),
599 static_cast<u32>(uniform_staging_buffer->size()));
600
601 g_gfx->SetViewportAndScissor(
602 g_gfx->ConvertFramebufferRectangle(dst, g_gfx->GetCurrentFramebuffer()));
603 g_gfx->SetPipeline(final_pipeline);
604 g_gfx->Draw(0, 3);
605 }
606 }
607
608 std::string PostProcessing::GetUniformBufferHeader(bool user_post_process) const
609 {
610 std::ostringstream ss;
611 u32 unused_counter = 1;
612 ss << "UBO_BINDING(std140, 1) uniform PSBlock {\n";
613
614 // Builtin uniforms:
615
616 ss << " float4 resolution;\n"; // Source resolution
617 ss << " float4 target_resolution;\n";
618 ss << " float4 window_resolution;\n";
619 // How many horizontal and vertical stereo views do we have? (set to 1 when we use layers instead)
620 ss << " int2 stereo_views;\n";
621 ss << " float4 src_rect;\n";
622 // The first (but not necessarily only) source layer we target
623 ss << " int src_layer;\n";
624 ss << " uint time;\n";
625 ss << " int graphics_api;\n";
626 // If true, it's an intermediary buffer (including the first), if false, it's the final one
627 ss << " int intermediary_buffer;\n";
628
629 ss << " int resampling_method;\n";
630 ss << " int correct_color_space;\n";
631 ss << " int game_color_space;\n";
632 ss << " int correct_gamma;\n";
633 ss << " float game_gamma;\n";
634 ss << " int sdr_display_gamma_sRGB;\n";
635 ss << " float sdr_display_custom_gamma;\n";
636 ss << " int linear_space_output;\n";
637 ss << " int hdr_output;\n";
638 ss << " float hdr_paper_white_nits;\n";
639 ss << " float hdr_sdr_white_nits;\n";
640
641 if (user_post_process)
642 {
643 ss << "\n";
644 // Custom options/uniforms
645 for (const auto& it : m_config.GetOptions())
646 {
647 if (it.second.m_type == PostProcessingConfiguration::ConfigurationOption::OptionType::Bool)
648 {
649 ss << fmt::format(" int {};\n", it.first);
650 for (u32 i = 0; i < 3; i++)
651 ss << " int ubo_align_" << unused_counter++ << "_;\n";
652 }
653 else if (it.second.m_type ==
654 PostProcessingConfiguration::ConfigurationOption::OptionType::Integer)
655 {
656 u32 count = static_cast<u32>(it.second.m_integer_values.size());
657 if (count == 1)
658 ss << fmt::format(" int {};\n", it.first);
659 else
660 ss << fmt::format(" int{} {};\n", count, it.first);
661
662 for (u32 i = count; i < 4; i++)
663 ss << " int ubo_align_" << unused_counter++ << "_;\n";
664 }
665 else if (it.second.m_type ==
666 PostProcessingConfiguration::ConfigurationOption::OptionType::Float)
667 {
668 u32 count = static_cast<u32>(it.second.m_float_values.size());
669 if (count == 1)
670 ss << fmt::format(" float {};\n", it.first);
671 else
672 ss << fmt::format(" float{} {};\n", count, it.first);
673
674 for (u32 i = count; i < 4; i++)
675 ss << " float ubo_align_" << unused_counter++ << "_;\n";
676 }
677 }
678 }
679
680 ss << "};\n\n";
681 return ss.str();
682 }
683
684 std::string PostProcessing::GetHeader(bool user_post_process) const
685 {
686 std::ostringstream ss;
687 ss << GetUniformBufferHeader(user_post_process);
688 ss << "SAMPLER_BINDING(0) uniform sampler2DArray samp0;\n";
689 ss << "SAMPLER_BINDING(1) uniform sampler2DArray samp1;\n";
690
691 if (g_backend_info.bSupportsGeometryShaders)
692 {
693 ss << "VARYING_LOCATION(0) in VertexData {\n";
694 ss << " float3 v_tex0;\n";
695 ss << "};\n";
696 }
697 else
698 {
699 ss << "VARYING_LOCATION(0) in float3 v_tex0;\n";
700 }
701
702 ss << "FRAGMENT_OUTPUT_LOCATION(0) out float4 ocol0;\n";
703
704 ss << R"(
705 float4 Sample() { return texture(samp0, v_tex0); }
706 float4 SampleLocation(float2 location) { return texture(samp0, float3(location, float(v_tex0.z))); }
707 float4 SampleLayer(int layer) { return texture(samp0, float3(v_tex0.xy, float(layer))); }
708 #define SampleOffset(offset) textureOffset(samp0, v_tex0, offset)
709
710 float2 GetTargetResolution()
711 {
712 return target_resolution.xy;
713 }
714
715 float2 GetInvTargetResolution()
716 {
717 return target_resolution.zw;
718 }
719
720 float2 GetWindowResolution()
721 {
722 return window_resolution.xy;
723 }
724
725 float2 GetInvWindowResolution()
726 {
727 return window_resolution.zw;
728 }
729
730 float2 GetResolution()
731 {
732 return resolution.xy;
733 }
734
735 float2 GetInvResolution()
736 {
737 return resolution.zw;
738 }
739
740 float2 GetCoordinates()
741 {
742 return v_tex0.xy;
743 }
744
745 float GetLayer()
746 {
747 return v_tex0.z;
748 }
749
750 uint GetTime()
751 {
752 return time;
753 }
754
755 void SetOutput(float4 color)
756 {
757 ocol0 = color;
758 }
759
760 #define GetOption(x) (x)
761 #define OptionEnabled(x) ((x) != 0)
762 #define OptionDisabled(x) ((x) == 0)
763
764 )";
765 return ss.str();
766 }
767
768 std::string PostProcessing::GetFooter() const
769 {
770 return {};
771 }
772
773 static std::string GetVertexShaderBody()
774 {
775 std::ostringstream ss;
776 if (g_backend_info.bSupportsGeometryShaders)
777 {
778 ss << "VARYING_LOCATION(0) out VertexData {\n";
779 ss << " float3 v_tex0;\n";
780 ss << "};\n";
781 }
782 else
783 {
784 ss << "VARYING_LOCATION(0) out float3 v_tex0;\n";
785 }
786
787 ss << "#define id gl_VertexID\n";
788 ss << "#define opos gl_Position\n";
789 ss << "void main() {\n";
790 ss << " v_tex0 = float3(float((id << 1) & 2), float(id & 2), 0.0f);\n";
791 ss << " opos = float4(v_tex0.xy * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);\n";
792 ss << " v_tex0 = float3(src_rect.xy + (src_rect.zw * v_tex0.xy), float(src_layer));\n";
793
794 // Vulkan Y needs to be inverted on every pass
795 if (g_backend_info.api_type == APIType::Vulkan)
796 {
797 ss << " opos.y = -opos.y;\n";
798 }
799 // OpenGL Y needs to be inverted in all passes except the last one
800 else if (g_backend_info.api_type == APIType::OpenGL)
801 {
802 ss << " if (intermediary_buffer != 0)\n";
803 ss << " opos.y = -opos.y;\n";
804 }
805
806 ss << "}\n";
807 return ss.str();
808 }
809
810 bool PostProcessing::CompileVertexShader()
811 {
812 std::ostringstream ss_default;
813 ss_default << GetUniformBufferHeader(false);
814 ss_default << GetVertexShaderBody();
815 m_default_vertex_shader = g_gfx->CreateShaderFromSource(
816 ShaderStage::Vertex, ss_default.str(), nullptr, "Default post-processing vertex shader");
817
818 std::ostringstream ss;
819 ss << GetUniformBufferHeader(true);
820 ss << GetVertexShaderBody();
821 m_vertex_shader = g_gfx->CreateShaderFromSource(ShaderStage::Vertex, ss.str(), nullptr,
822 "Post-processing vertex shader");
823
824 if (!m_default_vertex_shader || !m_vertex_shader)
825 {
826 PanicAlertFmt("Failed to compile post-processing vertex shader");
827 m_default_vertex_shader.reset();
828 m_vertex_shader.reset();
829 return false;
830 }
831
832 return true;
833 }
834
835 struct BuiltinUniforms
836 {
837 // bools need to be represented as "s32"
838
839 std::array<float, 4> source_resolution;
840 std::array<float, 4> target_resolution;
841 std::array<float, 4> window_resolution;
842 std::array<float, 4> stereo_views;
843 std::array<float, 4> src_rect;
844 s32 src_layer;
845 u32 time;
846 s32 graphics_api;
847 s32 intermediary_buffer;
848 s32 resampling_method;
849 s32 correct_color_space;
850 s32 game_color_space;
851 s32 correct_gamma;
852 float game_gamma;
853 s32 sdr_display_gamma_sRGB;
854 float sdr_display_custom_gamma;
855 s32 linear_space_output;
856 s32 hdr_output;
857 float hdr_paper_white_nits;
858 float hdr_sdr_white_nits;
859 };
860
861 size_t PostProcessing::CalculateUniformsSize(bool user_post_process) const
862 {
863 // Allocate a vec4 for each uniform to simplify allocation.
864 return sizeof(BuiltinUniforms) +
865 (user_post_process ? m_config.GetOptions().size() : 0) * sizeof(float) * 4;
866 }
867
868 void PostProcessing::FillUniformBuffer(const MathUtil::Rectangle<int>& src,
869 const AbstractTexture* src_tex, int src_layer,
870 const MathUtil::Rectangle<int>& dst,
871 const MathUtil::Rectangle<int>& wnd, u8* buffer,
872 bool user_post_process, bool intermediary_buffer)
873 {
874 const float rcp_src_width = 1.0f / src_tex->GetWidth();
875 const float rcp_src_height = 1.0f / src_tex->GetHeight();
876
877 BuiltinUniforms builtin_uniforms;
878 builtin_uniforms.source_resolution = {static_cast<float>(src_tex->GetWidth()),
879 static_cast<float>(src_tex->GetHeight()), rcp_src_width,
880 rcp_src_height};
881 builtin_uniforms.target_resolution = {
882 static_cast<float>(dst.GetWidth()), static_cast<float>(dst.GetHeight()),
883 1.0f / static_cast<float>(dst.GetWidth()), 1.0f / static_cast<float>(dst.GetHeight())};
884 builtin_uniforms.window_resolution = {
885 static_cast<float>(wnd.GetWidth()), static_cast<float>(wnd.GetHeight()),
886 1.0f / static_cast<float>(wnd.GetWidth()), 1.0f / static_cast<float>(wnd.GetHeight())};
887 builtin_uniforms.src_rect = {static_cast<float>(src.left) * rcp_src_width,
888 static_cast<float>(src.top) * rcp_src_height,
889 static_cast<float>(src.GetWidth()) * rcp_src_width,
890 static_cast<float>(src.GetHeight()) * rcp_src_height};
891 builtin_uniforms.src_layer = static_cast<s32>(src_layer);
892 builtin_uniforms.time = static_cast<u32>(m_timer.ElapsedMs());
893 builtin_uniforms.graphics_api = static_cast<s32>(g_backend_info.api_type);
894 builtin_uniforms.intermediary_buffer = static_cast<s32>(intermediary_buffer);
895
896 builtin_uniforms.resampling_method = static_cast<s32>(g_ActiveConfig.output_resampling_mode);
897 // Color correction related uniforms.
898 // These are mainly used by the "m_default_pixel_shader",
899 // but should also be accessible to all other shaders.
900 builtin_uniforms.correct_color_space = g_ActiveConfig.color_correction.bCorrectColorSpace;
901 builtin_uniforms.game_color_space =
902 static_cast<int>(g_ActiveConfig.color_correction.game_color_space);
903 builtin_uniforms.correct_gamma = g_ActiveConfig.color_correction.bCorrectGamma;
904 builtin_uniforms.game_gamma = g_ActiveConfig.color_correction.fGameGamma;
905 builtin_uniforms.sdr_display_gamma_sRGB = g_ActiveConfig.color_correction.bSDRDisplayGammaSRGB;
906 builtin_uniforms.sdr_display_custom_gamma =
907 g_ActiveConfig.color_correction.fSDRDisplayCustomGamma;
908 // scRGB (RGBA16F) expects linear values as opposed to sRGB gamma
909 builtin_uniforms.linear_space_output = m_framebuffer_format == AbstractTextureFormat::RGBA16F;
910 // Implies output values can be beyond the 0-1 range
911 builtin_uniforms.hdr_output = m_framebuffer_format == AbstractTextureFormat::RGBA16F;
912 builtin_uniforms.hdr_paper_white_nits = g_ActiveConfig.color_correction.fHDRPaperWhiteNits;
913 // A value of 1 1 1 usually matches 80 nits in HDR
914 builtin_uniforms.hdr_sdr_white_nits = 80.f;
915
916 std::memcpy(buffer, &builtin_uniforms, sizeof(builtin_uniforms));
917 buffer += sizeof(builtin_uniforms);
918
919 // Don't include the custom pp shader options if they are not necessary,
920 // having mismatching uniforms between different shaders can cause issues on some backends
921 if (!user_post_process)
922 return;
923
924 for (auto& it : m_config.GetOptions())
925 {
926 union
927 {
928 u32 as_bool[4];
929 s32 as_int[4];
930 float as_float[4];
931 } value = {};
932
933 switch (it.second.m_type)
934 {
935 case PostProcessingConfiguration::ConfigurationOption::OptionType::Bool:
936 value.as_bool[0] = it.second.m_bool_value ? 1 : 0;
937 break;
938
939 case PostProcessingConfiguration::ConfigurationOption::OptionType::Integer:
940 ASSERT(it.second.m_integer_values.size() <= 4);
941 std::copy_n(it.second.m_integer_values.begin(), it.second.m_integer_values.size(),
942 value.as_int);
943 break;
944
945 case PostProcessingConfiguration::ConfigurationOption::OptionType::Float:
946 ASSERT(it.second.m_float_values.size() <= 4);
947 std::copy_n(it.second.m_float_values.begin(), it.second.m_float_values.size(),
948 value.as_float);
949 break;
950 }
951
952 it.second.m_dirty = false;
953
954 std::memcpy(buffer, &value, sizeof(value));
955 buffer += sizeof(value);
956 }
957
958 m_config.SetDirty(false);
959 }
960
961 bool PostProcessing::CompilePixelShader()
962 {
963 m_default_pixel_shader.reset();
964 m_pixel_shader.reset();
965
966 // Generate GLSL and compile the new shaders:
967
968 std::string default_pixel_shader_code;
969 if (LoadShaderFromFile(s_default_pixel_shader_name, "", default_pixel_shader_code))
970 {
971 m_default_pixel_shader = g_gfx->CreateShaderFromSource(
972 ShaderStage::Pixel, GetHeader(false) + default_pixel_shader_code + GetFooter(), nullptr,
973 "Default post-processing pixel shader");
974 // We continue even if all of this failed, it doesn't matter
975 m_default_uniform_staging_buffer.resize(CalculateUniformsSize(false));
976 }
977 else
978 {
979 m_default_uniform_staging_buffer.resize(0);
980 }
981
982 m_config.LoadShader(g_ActiveConfig.sPostProcessingShader);
983 m_pixel_shader = g_gfx->CreateShaderFromSource(
984 ShaderStage::Pixel, GetHeader(true) + m_config.GetShaderCode() + GetFooter(),
985 m_config.GetShaderIncluder(),
986 fmt::format("User post-processing pixel shader: {}", m_config.GetShader()));
987 if (!m_pixel_shader)
988 {
989 PanicAlertFmt("Failed to compile user post-processing shader {}", m_config.GetShader());
990
991 // Use default shader.
992 m_config.LoadDefaultShader();
993 m_pixel_shader = g_gfx->CreateShaderFromSource(
994 ShaderStage::Pixel, GetHeader(true) + m_config.GetShaderCode() + GetFooter(), nullptr,
995 "Default user post-processing pixel shader");
996 if (!m_pixel_shader)
997 {
998 m_uniform_staging_buffer.resize(0);
999 return false;
1000 }
1001 }
1002
1003 m_uniform_staging_buffer.resize(CalculateUniformsSize(true));
1004 return true;
1005 }
1006
1007 static bool UseGeometryShaderForPostProcess(bool is_intermediary_buffer)
1008 {
1009 // We only return true on stereo modes that need to copy
1010 // both source texture layers into the target texture layers.
1011 // Any other case is handled manually with multiple copies, thus
1012 // it doesn't need a geom shader.
1013 switch (g_ActiveConfig.stereo_mode)
1014 {
1015 case StereoMode::QuadBuffer:
1016 return !g_backend_info.bUsesExplictQuadBuffering;
1017 case StereoMode::Anaglyph:
1018 case StereoMode::Passive:
1019 return is_intermediary_buffer;
1020 case StereoMode::SideBySide:
1021 case StereoMode::TopAndBottom:
1022 case StereoMode::Off:
1023 default:
1024 return false;
1025 }
1026 }
1027
1028 bool PostProcessing::CompilePipeline()
1029 {
1030 // Not needed. Some backends don't like making pipelines with no targets,
1031 // and in any case, we don't need to render anything if that happened.
1032 if (m_framebuffer_format == AbstractTextureFormat::Undefined)
1033 return true;
1034
1035 // If this is true, the "m_default_pipeline" won't be the only one that runs
1036 const bool needs_intermediary_buffer = NeedsIntermediaryBuffer();
1037
1038 AbstractPipelineConfig config = {};
1039 config.vertex_shader = m_default_vertex_shader.get();
1040 // This geometry shader will take care of reading both layer 0 and 1 on the source texture,
1041 // and writing to both layer 0 and 1 on the render target.
1042 config.geometry_shader = UseGeometryShaderForPostProcess(needs_intermediary_buffer) ?
1043 g_shader_cache->GetTexcoordGeometryShader() :
1044 nullptr;
1045 config.pixel_shader = m_default_pixel_shader.get();
1046 config.rasterization_state = RenderState::GetNoCullRasterizationState(PrimitiveType::Triangles);
1047 config.depth_state = RenderState::GetNoDepthTestingDepthState();
1048 config.blending_state = RenderState::GetNoBlendingBlendState();
1049 config.framebuffer_state = RenderState::GetColorFramebufferState(
1050 needs_intermediary_buffer ? s_intermediary_buffer_format : m_framebuffer_format);
1051 config.usage = AbstractPipelineUsage::Utility;
1052 // We continue even if it failed, it will be skipped later on
1053 if (config.pixel_shader)
1054 m_default_pipeline = g_gfx->CreatePipeline(config);
1055
1056 config.vertex_shader = m_vertex_shader.get();
1057 config.geometry_shader = UseGeometryShaderForPostProcess(false) ?
1058 g_shader_cache->GetTexcoordGeometryShader() :
1059 nullptr;
1060 config.pixel_shader = m_pixel_shader.get();
1061 config.framebuffer_state = RenderState::GetColorFramebufferState(m_framebuffer_format);
1062 m_pipeline = g_gfx->CreatePipeline(config);
1063 if (!m_pipeline)
1064 return false;
1065
1066 return true;
1067 }
1068 } // namespace VideoCommon