Debian Codegraph @

Source/Core/VideoCommon/Present.cpp

raw symbols SCIP
1 // Copyright 2023 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/Present.h"
5
6 #include "Common/ChunkFile.h"
7 #include "Core/Config/GraphicsSettings.h"
8 #include "Core/Config/MainSettings.h"
9 #include "Core/CoreTiming.h"
10 #include "Core/HW/VideoInterface.h"
11 #include "Core/Host.h"
12 #include "Core/System.h"
13
14 #include "InputCommon/ControllerInterface/ControllerInterface.h"
15
16 #include "Present.h"
17 #include "VideoCommon/AbstractGfx.h"
18 #include "VideoCommon/FrameDumper.h"
19 #include "VideoCommon/FramebufferManager.h"
20 #include "VideoCommon/OnScreenUI.h"
21 #include "VideoCommon/PostProcessing.h"
22 #include "VideoCommon/VertexManagerBase.h"
23 #include "VideoCommon/VideoConfig.h"
24 #include "VideoCommon/VideoEvents.h"
25 #include "VideoCommon/Widescreen.h"
26
27 std::unique_ptr<VideoCommon::Presenter> g_presenter;
28
29 namespace VideoCommon
30 {
31 // Stretches the native/internal analog resolution aspect ratio from ~4:3 to ~16:9
32 static float SourceAspectRatioToWidescreen(float source_aspect)
33 {
34 return source_aspect * ((16.0f / 9.0f) / (4.0f / 3.0f));
35 }
36
37 static std::tuple<int, int> FindClosestIntegerResolution(float width, float height,
38 float aspect_ratio)
39 {
40 // We can't round both the x and y resolution as that might generate an aspect ratio
41 // further away from the target one, we also can't either ceil or floor both sides,
42 // so we find the combination or flooring and ceiling that is closest to the target ar.
43 const int ceiled_width = static_cast<int>(std::ceil(width));
44 const int ceiled_height = static_cast<int>(std::ceil(height));
45 const int floored_width = static_cast<int>(std::floor(width));
46 const int floored_height = static_cast<int>(std::floor(height));
47
48 int int_width = floored_width;
49 int int_height = floored_height;
50
51 float min_aspect_ratio_distance = std::numeric_limits<float>::max();
52 for (const int new_width : std::array<int, 2>{ceiled_width, floored_width})
53 {
54 for (const int new_height : std::array<int, 2>{ceiled_height, floored_height})
55 {
56 const float new_aspect_ratio = static_cast<float>(new_width) / new_height;
57 const float aspect_ratio_distance = std::abs((new_aspect_ratio / aspect_ratio) - 1.f);
58 if (aspect_ratio_distance < min_aspect_ratio_distance)
59 {
60 min_aspect_ratio_distance = aspect_ratio_distance;
61 int_width = new_width;
62 int_height = new_height;
63 }
64 }
65 }
66
67 return std::make_tuple(int_width, int_height);
68 }
69
70 static void TryToSnapToXFBSize(int& width, int& height, int xfb_width, int xfb_height)
71 {
72 // Screen is blanking (e.g. game booting up), nothing to do here
73 if (xfb_width == 0 || xfb_height == 0)
74 return;
75
76 // If there's only 1 pixel of either horizontal or vertical resolution difference,
77 // make the output size match a multiple of the XFB native resolution,
78 // to achieve the highest quality (least scaling).
79 // The reason why the threshold is 1 pixel (per internal resolution multiplier) is because of
80 // minor inaccuracies of the VI aspect ratio (and because some resolutions are rounded
81 // while other are floored).
82 const unsigned int efb_scale = g_framebuffer_manager->GetEFBScale();
83 const unsigned int pixel_difference_width = std::abs(width - xfb_width);
84 const unsigned int pixel_difference_height = std::abs(height - xfb_height);
85 // We ignore this if there's an offset on both hor and ver size,
86 // as then we'd be changing the aspect ratio too much and would need to
87 // re-calculate a lot of stuff (like black bars).
88 if ((pixel_difference_width <= efb_scale && pixel_difference_height == 0) ||
89 (pixel_difference_height <= efb_scale && pixel_difference_width == 0))
90 {
91 width = xfb_width;
92 height = xfb_height;
93 }
94 }
95
96 Presenter::Presenter()
97 {
98 auto& video_events = GetVideoEvents();
99
100 m_config_changed =
101 video_events.config_changed_event.Register([this](u32 bits) { ConfigChanged(bits); });
102
103 m_end_field_hook = video_events.vi_end_field_event.Register(
104 [this] { m_immediate_swap_happened_this_field.store(false, std::memory_order_relaxed); });
105 }
106
107 Presenter::~Presenter()
108 {
109 // Disable ControllerInterface's aspect ratio adjustments so mapping dialog behaves normally.
110 g_controller_interface.SetAspectRatioAdjustment(1);
111 }
112
113 bool Presenter::Initialize()
114 {
115 UpdateDrawRectangle();
116
117 m_immediate_swap_happened_this_field.store(false, std::memory_order_relaxed);
118
119 if (!g_gfx->IsHeadless())
120 {
121 SetBackbuffer(g_gfx->GetSurfaceInfo());
122
123 m_post_processor = std::make_unique<VideoCommon::PostProcessing>();
124 if (!m_post_processor->Initialize(m_backbuffer_format))
125 return false;
126
127 m_onscreen_ui = std::make_unique<OnScreenUI>();
128 if (!m_onscreen_ui->Initialize(m_backbuffer_width, m_backbuffer_height, m_backbuffer_scale))
129 return false;
130
131 // Draw a blank frame (and complete OnScreenUI initialization)
132 g_gfx->BindBackbuffer({{0.0f, 0.0f, 0.0f, 1.0f}});
133 g_gfx->PresentBackbuffer();
134 }
135
136 return true;
137 }
138
139 bool Presenter::FetchXFB(u32 xfb_addr, u32 fb_width, u32 fb_stride, u32 fb_height, u64 ticks)
140 {
141 ReleaseXFBContentLock();
142 u64 old_xfb_id = m_last_xfb_id;
143
144 if (fb_width == 0 || fb_height == 0)
145 {
146 // Game is blanking the screen
147 m_xfb_entry.reset();
148 m_xfb_rect = MathUtil::Rectangle<int>();
149 m_last_xfb_id = std::numeric_limits<u64>::max();
150 }
151 else
152 {
153 m_xfb_entry =
154 g_texture_cache->GetXFBTexture(xfb_addr, fb_width, fb_height, fb_stride, &m_xfb_rect);
155 m_last_xfb_id = m_xfb_entry->id;
156
157 m_xfb_entry->AcquireContentLock();
158 }
159 m_last_xfb_addr = xfb_addr;
160 m_last_xfb_ticks = ticks;
161 m_last_xfb_width = fb_width;
162 m_last_xfb_stride = fb_stride;
163 m_last_xfb_height = fb_height;
164
165 return old_xfb_id == m_last_xfb_id;
166 }
167
168 void Presenter::ViSwap(u32 xfb_addr, u32 fb_width, u32 fb_stride, u32 fb_height, u64 ticks,
169 TimePoint presentation_time)
170 {
171 bool is_duplicate = FetchXFB(xfb_addr, fb_width, fb_stride, fb_height, ticks);
172
173 PresentInfo present_info{
174 .present_count = m_present_count++,
175 .emulated_timestamp = ticks,
176 .intended_present_time = presentation_time,
177 };
178
179 if (is_duplicate)
180 {
181 present_info.frame_count = m_frame_count - 1; // Previous frame
182 present_info.reason = PresentInfo::PresentReason::VideoInterfaceDuplicate;
183 }
184 else
185 {
186 present_info.frame_count = m_frame_count++;
187 present_info.reason = PresentInfo::PresentReason::VideoInterface;
188 }
189
190 if (m_xfb_entry)
191 {
192 // With no references, this XFB copy wasn't stitched together
193 // so just use its name directly
194 if (m_xfb_entry->references.empty())
195 {
196 if (!m_xfb_entry->texture_info_name.empty())
197 present_info.xfb_copy_hashes.push_back(m_xfb_entry->texture_info_name);
198 }
199 else
200 {
201 for (const auto& reference : m_xfb_entry->references)
202 {
203 if (!reference->texture_info_name.empty())
204 present_info.xfb_copy_hashes.push_back(reference->texture_info_name);
205 }
206 }
207 }
208
209 auto& video_events = GetVideoEvents();
210
211 video_events.before_present_event.Trigger(present_info);
212
213 if (!is_duplicate || !g_ActiveConfig.bSkipPresentingDuplicateXFBs)
214 {
215 Present(&present_info);
216 ProcessFrameDumping(ticks);
217
218 video_events.after_present_event.Trigger(present_info);
219 }
220 }
221
222 void Presenter::ImmediateSwap(u32 xfb_addr, u32 fb_width, u32 fb_stride, u32 fb_height)
223 {
224 if (m_immediate_swap_happened_this_field.exchange(true, std::memory_order_relaxed) &&
225 Config::Get(Config::GFX_HACK_CAP_IMMEDIATE_XFB))
226 {
227 return;
228 }
229
230 const u64 ticks = m_next_swap_estimated_ticks;
231
232 FetchXFB(xfb_addr, fb_width, fb_stride, fb_height, ticks);
233
234 PresentInfo present_info{
235 .frame_count = m_frame_count++,
236 .present_count = m_present_count++,
237 .reason = PresentInfo::PresentReason::Immediate,
238 .emulated_timestamp = ticks,
239 .intended_present_time = m_next_swap_estimated_time,
240 };
241
242 auto& video_events = GetVideoEvents();
243
244 video_events.before_present_event.Trigger(present_info);
245
246 Present(&present_info);
247 ProcessFrameDumping(ticks);
248
249 video_events.after_present_event.Trigger(present_info);
250 }
251
252 void Presenter::SetNextSwapEstimatedTime(u64 ticks, TimePoint host_time)
253 {
254 m_next_swap_estimated_ticks = ticks;
255 m_next_swap_estimated_time = host_time;
256 }
257
258 void Presenter::ProcessFrameDumping(u64 ticks) const
259 {
260 if (g_frame_dumper->IsFrameDumping() && m_xfb_entry)
261 {
262 MathUtil::Rectangle<int> target_rect;
263 switch (Config::Get(Config::GFX_FRAME_DUMPS_RESOLUTION_TYPE))
264 {
265 default:
266 case FrameDumpResolutionType::WindowResolution:
267 {
268 if (!g_gfx->IsHeadless())
269 {
270 target_rect = GetTargetRectangle();
271 break;
272 }
273 [[fallthrough]];
274 }
275 case FrameDumpResolutionType::XFBAspectRatioCorrectedResolution:
276 {
277 target_rect = m_xfb_rect;
278 const bool allow_stretch = false;
279 auto [float_width, float_height] =
280 ScaleToDisplayAspectRatio(m_xfb_rect.GetWidth(), m_xfb_rect.GetHeight(), allow_stretch);
281 const float draw_aspect_ratio = CalculateDrawAspectRatio(allow_stretch);
282 auto [int_width, int_height] =
283 FindClosestIntegerResolution(float_width, float_height, draw_aspect_ratio);
284 target_rect = MathUtil::Rectangle<int>(0, 0, int_width, int_height);
285 break;
286 }
287 case FrameDumpResolutionType::XFBRawResolution:
288 {
289 target_rect = m_xfb_rect;
290 break;
291 }
292 }
293
294 int width = target_rect.GetWidth();
295 int height = target_rect.GetHeight();
296
297 const int resolution_lcm = g_frame_dumper->GetRequiredResolutionLeastCommonMultiple();
298
299 // Ensure divisibility by the dumper LCM and a min of 1 to make it compatible with all the
300 // video encoders. Note that this is theoretically only necessary when recording videos and not
301 // screenshots.
302 // We always scale positively to make sure the least amount of information is lost.
303 //
304 // TODO: this should be added as black padding on the edges by the frame dumper.
305 if ((width % resolution_lcm) != 0 || width == 0)
306 width += resolution_lcm - (width % resolution_lcm);
307 if ((height % resolution_lcm) != 0 || height == 0)
308 height += resolution_lcm - (height % resolution_lcm);
309
310 // Remove any black borders, there would be no point in including them in the recording
311 target_rect.left = 0;
312 target_rect.top = 0;
313 target_rect.right = width;
314 target_rect.bottom = height;
315
316 // TODO: any scaling done by this won't be gamma corrected,
317 // we should either apply post processing as well, or port its gamma correction code
318 g_frame_dumper->DumpCurrentFrame(m_xfb_entry->texture.get(), m_xfb_rect, target_rect, ticks,
319 m_frame_count);
320 }
321 }
322
323 void Presenter::SetBackbuffer(int backbuffer_width, int backbuffer_height)
324 {
325 const bool is_first = m_backbuffer_width == 0 && m_backbuffer_height == 0;
326 const bool size_changed =
327 (m_backbuffer_width != backbuffer_width || m_backbuffer_height != backbuffer_height);
328 m_backbuffer_width = backbuffer_width;
329 m_backbuffer_height = backbuffer_height;
330 UpdateDrawRectangle();
331
332 OnBackbufferSet(size_changed, is_first);
333 }
334
335 void Presenter::SetBackbuffer(SurfaceInfo info)
336 {
337 const bool is_first = m_backbuffer_width == 0 && m_backbuffer_height == 0;
338 const bool size_changed =
339 (m_backbuffer_width != (int)info.width || m_backbuffer_height != (int)info.height);
340 m_backbuffer_width = info.width;
341 m_backbuffer_height = info.height;
342 m_backbuffer_scale = info.scale;
343 m_backbuffer_format = info.format;
344 if (m_onscreen_ui)
345 m_onscreen_ui->SetScale(info.scale);
346
347 OnBackbufferSet(size_changed, is_first);
348 }
349
350 void Presenter::OnBackbufferSet(bool size_changed, bool is_first_set)
351 {
352 UpdateDrawRectangle();
353
354 // Automatically update the resolution scale if the window size changed,
355 // or if the game XFB resolution changed.
356 if (size_changed && !is_first_set && g_ActiveConfig.iEFBScale == EFB_SCALE_AUTO_INTEGRAL &&
357 m_auto_resolution_scale != AutoIntegralScale())
358 {
359 g_framebuffer_manager->RecreateEFBFramebuffer(g_ActiveConfig.iEFBScale);
360 }
361 if (size_changed || is_first_set)
362 {
363 m_auto_resolution_scale = AutoIntegralScale();
364 }
365 }
366
367 void Presenter::ConfigChanged(u32 changed_bits)
368 {
369 // Check for post-processing shader changes. Done up here as it doesn't affect anything outside
370 // the post-processor. Note that options are applied every frame, so no need to check those.
371 if (changed_bits & ConfigChangeBits::CONFIG_CHANGE_BIT_POST_PROCESSING_SHADER && m_post_processor)
372 {
373 // The existing shader must not be in use when it's destroyed
374 g_gfx->WaitForGPUIdle();
375
376 m_post_processor->RecompileShader();
377 }
378
379 // Stereo mode change requires recompiling our post processing pipeline and imgui pipelines for
380 // rendering the UI.
381 if (changed_bits & ConfigChangeBits::CONFIG_CHANGE_BIT_STEREO_MODE)
382 {
383 if (m_onscreen_ui)
384 m_onscreen_ui->RecompileImGuiPipeline();
385 if (m_post_processor)
386 m_post_processor->RecompilePipeline();
387 }
388 }
389
390 std::tuple<MathUtil::Rectangle<int>, MathUtil::Rectangle<int>>
391 Presenter::ConvertStereoRectangle(const MathUtil::Rectangle<int>& rc) const
392 {
393 // Resize target to half its original size
394 auto draw_rc = rc;
395 if (g_ActiveConfig.stereo_mode == StereoMode::TopAndBottom)
396 {
397 // The height may be negative due to flipped rectangles
398 int height = rc.bottom - rc.top;
399 draw_rc.top += height / 4;
400 draw_rc.bottom -= height / 4;
401 }
402 else
403 {
404 int width = rc.right - rc.left;
405 draw_rc.left += width / 4;
406 draw_rc.right -= width / 4;
407 }
408
409 // Create two target rectangle offset to the sides of the backbuffer
410 auto left_rc = draw_rc;
411 auto right_rc = draw_rc;
412 if (g_ActiveConfig.stereo_mode == StereoMode::TopAndBottom)
413 {
414 left_rc.top -= m_backbuffer_height / 4;
415 left_rc.bottom -= m_backbuffer_height / 4;
416 right_rc.top += m_backbuffer_height / 4;
417 right_rc.bottom += m_backbuffer_height / 4;
418 }
419 else
420 {
421 left_rc.left -= m_backbuffer_width / 4;
422 left_rc.right -= m_backbuffer_width / 4;
423 right_rc.left += m_backbuffer_width / 4;
424 right_rc.right += m_backbuffer_width / 4;
425 }
426
427 return std::make_tuple(left_rc, right_rc);
428 }
429
430 MathUtil::Rectangle<int> Presenter::GetCustomCrop(const MathUtil::Rectangle<int>& rect) const
431 {
432 if (!g_ActiveConfig.bCropCustom)
433 return MathUtil::Rectangle<int>(0, 0, 0, 0);
434
435 const int uncropped_source_width = rect.GetWidth();
436 const int uncropped_source_height = rect.GetHeight();
437 const int efb_scale = g_framebuffer_manager->GetEFBScale();
438
439 // Determine amount of pixels to crop from the source rect.
440 const int source_crop_left =
441 std::min(g_ActiveConfig.iCropCustomLeft * efb_scale, uncropped_source_width);
442 const int source_crop_right = std::min(g_ActiveConfig.iCropCustomRight * efb_scale,
443 uncropped_source_width - source_crop_left);
444 const int source_crop_top =
445 std::min(g_ActiveConfig.iCropCustomTop * efb_scale, uncropped_source_height);
446 const int source_crop_bottom = std::min(g_ActiveConfig.iCropCustomBottom * efb_scale,
447 uncropped_source_height - source_crop_top);
448
449 return MathUtil::Rectangle<int>(source_crop_left, source_crop_top, source_crop_right,
450 source_crop_bottom);
451 }
452
453 MathUtil::Rectangle<int> Presenter::AdjustForCustomCrop(const MathUtil::Rectangle<int>& rect) const
454 {
455 const MathUtil::Rectangle<int> crop = GetCustomCrop(rect);
456 const MathUtil::Rectangle<int> cropped(rect.left + crop.left, rect.top + crop.top,
457 rect.right - crop.right, rect.bottom - crop.bottom);
458 return cropped;
459 }
460
461 float Presenter::AdjustAspectRatioForCustomCrop(float input_aspect_ratio) const
462 {
463 if (!g_ActiveConfig.bCropCustom)
464 return input_aspect_ratio;
465
466 const MathUtil::Rectangle<int> rect = m_xfb_rect;
467 if (rect.GetWidth() <= 0 || rect.GetHeight() <= 0)
468 return input_aspect_ratio;
469
470 const MathUtil::Rectangle<int> cropped = AdjustForCustomCrop(rect);
471 const float relative_width_difference =
472 static_cast<float>(cropped.GetWidth()) / static_cast<float>(rect.GetWidth());
473 const float relative_height_difference =
474 static_cast<float>(cropped.GetHeight()) / static_cast<float>(rect.GetHeight());
475 return input_aspect_ratio * (relative_width_difference / relative_height_difference);
476 }
477
478 float Presenter::CalculateDrawAspectRatio(bool allow_stretch) const
479 {
480 auto aspect_mode = g_ActiveConfig.aspect_mode;
481 float resulting_aspect_ratio;
482
483 if (!allow_stretch && aspect_mode == AspectMode::Stretch)
484 aspect_mode = AspectMode::Auto;
485
486 // If stretch is enabled, we prefer the aspect ratio of the window.
487 if (aspect_mode == AspectMode::Stretch)
488 {
489 resulting_aspect_ratio =
490 (static_cast<float>(m_backbuffer_width) / static_cast<float>(m_backbuffer_height));
491 }
492 else
493 {
494 // The actual aspect ratio of the XFB texture is irrelevant, the VI one is the one that matters
495 const auto& vi = Core::System::GetInstance().GetVideoInterface();
496 const float vi_aspect_ratio = vi.GetAspectRatio();
497 const float source_aspect_ratio = AdjustAspectRatioForCustomCrop(vi_aspect_ratio);
498
499 // This will scale up the source ~4:3 resolution to its equivalent ~16:9 resolution
500 if (aspect_mode == AspectMode::ForceWide ||
501 (aspect_mode == AspectMode::Auto && g_widescreen->IsGameWidescreen()))
502 {
503 resulting_aspect_ratio = SourceAspectRatioToWidescreen(source_aspect_ratio);
504 }
505 else if (aspect_mode == AspectMode::Custom)
506 {
507 resulting_aspect_ratio =
508 source_aspect_ratio * (g_ActiveConfig.GetCustomAspectRatio() / (4.0f / 3.0f));
509 }
510 // For the "custom stretch" mode, we force the exact target aspect ratio, without
511 // acknowledging the difference between the source aspect ratio and 4:3.
512 else if (aspect_mode == AspectMode::CustomStretch)
513 {
514 resulting_aspect_ratio = g_ActiveConfig.GetCustomAspectRatio();
515 }
516 else if (aspect_mode == AspectMode::Raw)
517 {
518 resulting_aspect_ratio =
519 m_xfb_entry ? (static_cast<float>(m_last_xfb_width) / m_last_xfb_height) : 1.f;
520 }
521 else
522 {
523 resulting_aspect_ratio = source_aspect_ratio;
524 }
525 }
526
527 if (g_ActiveConfig.stereo_per_eye_resolution_full)
528 {
529 if (g_ActiveConfig.stereo_mode == StereoMode::SideBySide)
530 {
531 // Render twice as wide if using side-by-side 3D, since the 3D will halve the horizontal
532 // resolution
533 resulting_aspect_ratio *= 2.0;
534 }
535 else if (g_ActiveConfig.stereo_mode == StereoMode::TopAndBottom)
536 {
537 // Render twice as tall if using top-and-bottom 3D, since the 3D will halve the vertical
538 // resolution
539 resulting_aspect_ratio /= 2.0;
540 }
541 }
542
543 return resulting_aspect_ratio;
544 }
545
546 void Presenter::AdjustRectanglesToFitBounds(MathUtil::Rectangle<int>* target_rect,
547 MathUtil::Rectangle<int>* source_rect, int fb_width,
548 int fb_height)
549 {
550 const int orig_target_width = target_rect->GetWidth();
551 const int orig_target_height = target_rect->GetHeight();
552 const int orig_source_width = source_rect->GetWidth();
553 const int orig_source_height = source_rect->GetHeight();
554 if (target_rect->left < 0)
555 {
556 const int offset = -target_rect->left;
557 target_rect->left = 0;
558 source_rect->left += offset * orig_source_width / orig_target_width;
559 }
560 if (target_rect->right > fb_width)
561 {
562 const int offset = target_rect->right - fb_width;
563 target_rect->right -= offset;
564 source_rect->right -= offset * orig_source_width / orig_target_width;
565 }
566 if (target_rect->top < 0)
567 {
568 const int offset = -target_rect->top;
569 target_rect->top = 0;
570 source_rect->top += offset * orig_source_height / orig_target_height;
571 }
572 if (target_rect->bottom > fb_height)
573 {
574 const int offset = target_rect->bottom - fb_height;
575 target_rect->bottom -= offset;
576 source_rect->bottom -= offset * orig_source_height / orig_target_height;
577 }
578 }
579
580 void Presenter::ReleaseXFBContentLock()
581 {
582 if (m_xfb_entry)
583 m_xfb_entry->ReleaseContentLock();
584 }
585
586 void Presenter::ChangeSurface(void* new_surface_handle)
587 {
588 std::lock_guard<std::mutex> lock(m_swap_mutex);
589 m_new_surface_handle = new_surface_handle;
590 m_surface_changed.Set();
591 }
592
593 void Presenter::ResizeSurface()
594 {
595 std::lock_guard<std::mutex> lock(m_swap_mutex);
596 m_surface_resized.Set();
597 }
598
599 void* Presenter::GetNewSurfaceHandle()
600 {
601 void* handle = m_new_surface_handle;
602 m_new_surface_handle = nullptr;
603 return handle;
604 }
605
606 u32 Presenter::AutoIntegralScale() const
607 {
608 // Take the source/native resolution (XFB) and stretch it on the target (window) aspect ratio.
609 // If the target resolution is larger (on either x or y), we scale the source
610 // by a integer multiplier until it won't have to be scaled up anymore.
611 // NOTE: this might conflict with "Config::MAIN_RENDER_WINDOW_AUTOSIZE",
612 // as they mutually influence each other.
613 u32 source_width = m_last_xfb_width;
614 u32 source_height = m_last_xfb_height;
615 const u32 target_width = m_target_rectangle.GetWidth();
616 const u32 target_height = m_target_rectangle.GetHeight();
617 const float source_aspect_ratio = (float)source_width / source_height;
618 const float target_aspect_ratio = (float)target_width / target_height;
619 if (source_aspect_ratio >= target_aspect_ratio)
620 source_width = std::round(source_height * target_aspect_ratio);
621 else
622 source_height = std::round(source_width / target_aspect_ratio);
623 const u32 width_scale =
624 source_width > 0 ? ((target_width + (source_width - 1)) / source_width) : 1;
625 const u32 height_scale =
626 source_height > 0 ? ((target_height + (source_height - 1)) / source_height) : 1;
627 // Limit to the max to avoid creating textures larger than their max supported resolution.
628 return std::min(std::max(width_scale, height_scale),
629 static_cast<u32>(Config::Get(Config::GFX_MAX_EFB_SCALE)));
630 }
631
632 void Presenter::SetSuggestedWindowSize(int width, int height)
633 {
634 // While trying to guess the best window resolution, we can't allow it to use the
635 // "AspectMode::Stretch" setting because that would self influence the output result,
636 // given it would be based on the previous frame resolution
637 const bool allow_stretch = false;
638 const auto [out_width, out_height] = CalculateOutputDimensions(width, height, allow_stretch);
639
640 // Track the last values of width/height to avoid sending a window resize event every frame.
641 if (out_width == m_last_window_request_width && out_height == m_last_window_request_height)
642 return;
643
644 m_last_window_request_width = out_width;
645 m_last_window_request_height = out_height;
646 // Pass in the suggested window size. This might not always be acknowledged.
647 Host_RequestRenderWindowSize(out_width, out_height);
648 }
649
650 // Crop to exact forced aspect ratios if enabled and not AspectMode::Stretch.
651 std::tuple<float, float> Presenter::ApplyStandardAspectCrop(float width, float height,
652 bool allow_stretch) const
653 {
654 auto aspect_mode = g_ActiveConfig.aspect_mode;
655
656 if (!allow_stretch && aspect_mode == AspectMode::Stretch)
657 aspect_mode = AspectMode::Auto;
658
659 if (!g_ActiveConfig.bCropToAspectRatio || aspect_mode == AspectMode::Stretch ||
660 aspect_mode == AspectMode::Raw)
661 {
662 return {width, height};
663 }
664
665 // Force aspect ratios by cropping the image.
666 const float current_aspect = width / height;
667 float expected_aspect;
668 switch (aspect_mode)
669 {
670 default:
671 case AspectMode::Auto:
672 expected_aspect = g_widescreen->IsGameWidescreen() ? (16.0f / 9.0f) : (4.0f / 3.0f);
673 break;
674 case AspectMode::ForceWide:
675 expected_aspect = 16.0f / 9.0f;
676 break;
677 case AspectMode::ForceStandard:
678 expected_aspect = 4.0f / 3.0f;
679 break;
680 // For the custom (relative) case, we want to crop from the native aspect ratio
681 // to the specific target one, as they likely have a small difference
682 case AspectMode::Custom:
683 // There should be no cropping needed in the custom stretch case,
684 // as output should always exactly match the target aspect ratio
685 case AspectMode::CustomStretch:
686 expected_aspect = g_ActiveConfig.GetCustomAspectRatio();
687 break;
688 }
689
690 if (current_aspect > expected_aspect)
691 {
692 // keep height, crop width
693 width = height * expected_aspect;
694 }
695 else
696 {
697 // keep width, crop height
698 height = width / expected_aspect;
699 }
700
701 return {width, height};
702 }
703
704 void Presenter::UpdateDrawRectangle()
705 {
706 const float draw_aspect_ratio = CalculateDrawAspectRatio();
707
708 // Update aspect ratio hack values
709 // Won't take effect until next frame
710 // Don't know if there is a better place for this code so there isn't a 1 frame delay
711 if (g_ActiveConfig.bWidescreenHack)
712 {
713 const auto& vi = Core::System::GetInstance().GetVideoInterface();
714 float source_aspect_ratio = vi.GetAspectRatio();
715 // If the game is meant to be in widescreen (or forced to),
716 // scale the source aspect ratio to it.
717 if (g_widescreen->IsGameWidescreen())
718 source_aspect_ratio = SourceAspectRatioToWidescreen(source_aspect_ratio);
719
720 const float adjust = source_aspect_ratio / draw_aspect_ratio;
721 if (adjust > 1)
722 {
723 // Vert+
724 g_Config.fAspectRatioHackW = 1;
725 g_Config.fAspectRatioHackH = 1 / adjust;
726 }
727 else
728 {
729 // Hor+
730 g_Config.fAspectRatioHackW = adjust;
731 g_Config.fAspectRatioHackH = 1;
732 }
733 }
734 else
735 {
736 // Hack is disabled.
737 g_Config.fAspectRatioHackW = 1;
738 g_Config.fAspectRatioHackH = 1;
739 }
740
741 // The rendering window size
742 const float win_width = static_cast<float>(m_backbuffer_width);
743 const float win_height = static_cast<float>(m_backbuffer_height);
744 const float win_aspect_ratio = win_width / win_height;
745
746 // FIXME: this breaks at very low widget sizes
747 // Make ControllerInterface aware of the render window region actually being used
748 // to adjust mouse cursor inputs.
749 // This also doesn't handle the image cropping settings.
750 g_controller_interface.SetAspectRatioAdjustment(draw_aspect_ratio / win_aspect_ratio);
751
752 float draw_width = draw_aspect_ratio;
753 float draw_height = 1;
754
755 // Crop the picture to a standard aspect ratio. (if enabled)
756 auto [crop_width, crop_height] = ApplyStandardAspectCrop(draw_width, draw_height);
757 const float crop_aspect_ratio = crop_width / crop_height;
758
759 // scale the picture to fit the rendering window
760 if (win_aspect_ratio >= crop_aspect_ratio)
761 {
762 // the window is flatter than the picture
763 draw_width *= win_height / crop_height;
764 crop_width *= win_height / crop_height;
765 draw_height *= win_height / crop_height;
766 crop_height = win_height;
767 }
768 else
769 {
770 // the window is skinnier than the picture
771 draw_width *= win_width / crop_width;
772 draw_height *= win_width / crop_width;
773 crop_height *= win_width / crop_width;
774 crop_width = win_width;
775 }
776
777 int int_draw_width;
778 int int_draw_height;
779
780 if (g_ActiveConfig.aspect_mode != AspectMode::Raw || !m_xfb_entry)
781 {
782 // Find the best integer resolution: the closest aspect ratio with the least black bars.
783 // This should have no influence if "AspectMode::Stretch" is active.
784 const float updated_draw_aspect_ratio = draw_width / draw_height;
785 const auto int_draw_res =
786 FindClosestIntegerResolution(draw_width, draw_height, updated_draw_aspect_ratio);
787 int_draw_width = std::get<0>(int_draw_res);
788 int_draw_height = std::get<1>(int_draw_res);
789 if (!g_ActiveConfig.bCropToAspectRatio)
790 {
791 if (g_ActiveConfig.aspect_mode != AspectMode::Stretch)
792 {
793 const MathUtil::Rectangle<int> rect = AdjustForCustomCrop(m_xfb_rect);
794 TryToSnapToXFBSize(int_draw_width, int_draw_height, rect.GetWidth(), rect.GetHeight());
795 }
796 // We can't draw something bigger than the window, it will crop
797 int_draw_width = std::min(int_draw_width, static_cast<int>(win_width));
798 int_draw_height = std::min(int_draw_height, static_cast<int>(win_height));
799 }
800 }
801 else
802 {
803 const MathUtil::Rectangle<int> rect = AdjustForCustomCrop(m_xfb_rect);
804 int_draw_width = rect.GetWidth();
805 int_draw_height = rect.GetHeight();
806 }
807
808 m_target_rectangle.left = static_cast<int>(std::round(win_width / 2.0 - int_draw_width / 2.0));
809 m_target_rectangle.top = static_cast<int>(std::round(win_height / 2.0 - int_draw_height / 2.0));
810 m_target_rectangle.right = m_target_rectangle.left + int_draw_width;
811 m_target_rectangle.bottom = m_target_rectangle.top + int_draw_height;
812 }
813
814 std::tuple<float, float> Presenter::ScaleToDisplayAspectRatio(const int width, const int height,
815 bool allow_stretch) const
816 {
817 // Scale either the width or height depending the content aspect ratio.
818 // This way we preserve as much resolution as possible when scaling.
819 float scaled_width = static_cast<float>(width);
820 float scaled_height = static_cast<float>(height);
821 const float draw_aspect = CalculateDrawAspectRatio(allow_stretch);
822 if (scaled_width / scaled_height >= draw_aspect)
823 scaled_height = scaled_width / draw_aspect;
824 else
825 scaled_width = scaled_height * draw_aspect;
826 return std::make_tuple(scaled_width, scaled_height);
827 }
828
829 std::tuple<int, int> Presenter::CalculateOutputDimensions(int width, int height,
830 bool allow_stretch) const
831 {
832 // Protect against zero width and height, a minimum of 1 will do
833 width = std::max(width, 1);
834 height = std::max(height, 1);
835
836 auto [scaled_width, scaled_height] = ScaleToDisplayAspectRatio(width, height, allow_stretch);
837
838 // Apply crop if enabled.
839 std::tie(scaled_width, scaled_height) =
840 ApplyStandardAspectCrop(scaled_width, scaled_height, allow_stretch);
841
842 auto aspect_mode = g_ActiveConfig.aspect_mode;
843
844 if (!allow_stretch && aspect_mode == AspectMode::Stretch)
845 aspect_mode = AspectMode::Auto;
846
847 if (!g_ActiveConfig.bCropToAspectRatio && aspect_mode != AspectMode::Stretch)
848 {
849 // Find the closest integer resolution for the aspect ratio,
850 // this avoids a small black line from being drawn on one of the four edges
851 const float draw_aspect_ratio = CalculateDrawAspectRatio(allow_stretch);
852 auto [int_width, int_height] =
853 FindClosestIntegerResolution(scaled_width, scaled_height, draw_aspect_ratio);
854 if (aspect_mode != AspectMode::Raw)
855 {
856 TryToSnapToXFBSize(int_width, int_height, m_xfb_rect.GetWidth(), m_xfb_rect.GetHeight());
857 }
858 width = int_width;
859 height = int_height;
860 }
861 else
862 {
863 width = static_cast<int>(std::ceil(scaled_width));
864 height = static_cast<int>(std::ceil(scaled_height));
865 }
866
867 return std::make_tuple(width, height);
868 }
869
870 void Presenter::RenderXFBToScreen(const MathUtil::Rectangle<int>& target_rc,
871 const AbstractTexture* source_texture,
872 const MathUtil::Rectangle<int>& source_rc)
873 {
874 if (g_ActiveConfig.stereo_mode == StereoMode::QuadBuffer &&
875 g_backend_info.bUsesExplictQuadBuffering)
876 {
877 // Quad-buffered stereo is annoying on GL.
878 g_gfx->SelectLeftBuffer();
879 m_post_processor->BlitFromTexture(target_rc, source_rc, source_texture, 0);
880
881 g_gfx->SelectRightBuffer();
882 m_post_processor->BlitFromTexture(target_rc, source_rc, source_texture, 1);
883
884 g_gfx->SelectMainBuffer();
885 }
886 else if (g_ActiveConfig.stereo_mode == StereoMode::SideBySide ||
887 g_ActiveConfig.stereo_mode == StereoMode::TopAndBottom)
888 {
889 const auto [left_rc, right_rc] = ConvertStereoRectangle(target_rc);
890
891 m_post_processor->BlitFromTexture(left_rc, source_rc, source_texture, 0);
892 m_post_processor->BlitFromTexture(right_rc, source_rc, source_texture, 1);
893 }
894 // Every other case will be treated the same (stereo or not).
895 // If there's multiple source layers, they should all be copied.
896 else
897 {
898 m_post_processor->BlitFromTexture(target_rc, source_rc, source_texture);
899 }
900 }
901
902 void Presenter::Present(PresentInfo* present_info)
903 {
904 m_present_count++;
905
906 if (g_gfx->IsHeadless() || (!m_onscreen_ui && !m_xfb_entry))
907 return;
908
909 if (!g_gfx->SupportsUtilityDrawing())
910 {
911 // Video Software doesn't support drawing a UI or doing post-processing
912 // So just show the XFB
913 if (m_xfb_entry)
914 {
915 const MathUtil::Rectangle<int> rect = AdjustForCustomCrop(m_xfb_rect);
916 g_gfx->ShowImage(m_xfb_entry->texture.get(), rect);
917
918 // Update the window size based on the frame that was just rendered.
919 // Due to depending on guest state, we need to call this every frame.
920 SetSuggestedWindowSize(rect.GetWidth(), rect.GetHeight());
921 }
922 return;
923 }
924
925 // Since we use the common pipelines here and draw vertices if a batch is currently being
926 // built by the vertex loader, we end up trampling over its pointer, as we share the buffer
927 // with the loader, and it has not been unmapped yet. Force a pipeline flush to avoid this.
928 g_vertex_manager->Flush();
929
930 UpdateDrawRectangle();
931
932 g_gfx->BeginUtilityDrawing();
933 const bool backbuffer_bound = g_gfx->BindBackbuffer({{0.0f, 0.0f, 0.0f, 1.0f}});
934
935 // Render the XFB to the screen.
936 if (backbuffer_bound && m_xfb_entry)
937 {
938 // Adjust the source rectangle instead of using an oversized viewport to render the XFB.
939 MathUtil::Rectangle<int> render_target_rc = GetTargetRectangle();
940 MathUtil::Rectangle<int> render_source_rc = AdjustForCustomCrop(m_xfb_rect);
941 AdjustRectanglesToFitBounds(&render_target_rc, &render_source_rc, m_backbuffer_width,
942 m_backbuffer_height);
943 RenderXFBToScreen(render_target_rc, m_xfb_entry->texture.get(), render_source_rc);
944 }
945
946 if (m_onscreen_ui)
947 {
948 m_onscreen_ui->Finalize();
949 if (backbuffer_bound)
950 m_onscreen_ui->DrawImGui();
951 }
952
953 // Present to the window system.
954 {
955 std::lock_guard<std::mutex> guard(m_swap_mutex);
956
957 if (present_info != nullptr)
958 {
959 const auto present_time = GetUpdatedPresentationTime(present_info->intended_present_time);
960
961 Core::System::GetInstance().GetCoreTiming().SleepUntil(present_time);
962
963 // Perhaps in the future a more accurate time can be acquired from the various backends.
964 present_info->actual_present_time = Clock::now();
965 present_info->present_time_accuracy = PresentInfo::PresentTimeAccuracy::PresentInProgress;
966 }
967
968 g_gfx->PresentBackbuffer();
969 }
970
971 if (m_xfb_entry)
972 {
973 // Update the window size based on the frame that was just rendered.
974 // Due to depending on guest state, we need to call this every frame.
975 const MathUtil::Rectangle<int> rect = AdjustForCustomCrop(m_xfb_rect);
976 SetSuggestedWindowSize(rect.GetWidth(), rect.GetHeight());
977 }
978
979 if (m_onscreen_ui)
980 m_onscreen_ui->BeginImGuiFrame(m_backbuffer_width, m_backbuffer_height);
981
982 g_gfx->EndUtilityDrawing();
983 }
984
985 TimePoint Presenter::GetUpdatedPresentationTime(TimePoint intended_presentation_time)
986 {
987 const auto now = Clock::now();
988 const auto arrival_offset = std::min(now - intended_presentation_time, DT{});
989
990 if (!Config::Get(Config::MAIN_SMOOTH_EARLY_PRESENTATION))
991 {
992 m_presentation_time_offset = arrival_offset;
993
994 // When SmoothEarlyPresentation is off and ImmediateXFB or RushFramePresentation are on,
995 // present as soon as possible as the goal is to achieve low input latency.
996 if (g_ActiveConfig.bImmediateXFB || Config::Get(Config::MAIN_RUSH_FRAME_PRESENTATION))
997 return now;
998
999 return intended_presentation_time;
1000 }
1001
1002 // Adjust slowly backward in time but quickly forward in time.
1003 // This keeps the pacing moderately smooth even if games produce regular sporadic bumps.
1004 // This was tuned to handle the terrible pacing in Brawl with "Immediate XFB".
1005 // Super Mario Galaxy 1 + 2 still perform poorly here in SingleCore mode.
1006 const auto adjustment_divisor = (arrival_offset < m_presentation_time_offset) ? 100 : 2;
1007
1008 m_presentation_time_offset += (arrival_offset - m_presentation_time_offset) / adjustment_divisor;
1009
1010 return intended_presentation_time + m_presentation_time_offset;
1011 }
1012
1013 void Presenter::SetKeyMap(const DolphinKeyMap& key_map)
1014 {
1015 if (m_onscreen_ui)
1016 m_onscreen_ui->SetKeyMap(key_map);
1017 }
1018
1019 void Presenter::SetKey(u32 key, bool is_down, const char* chars)
1020 {
1021 if (m_onscreen_ui)
1022 m_onscreen_ui->SetKey(key, is_down, chars);
1023 }
1024
1025 void Presenter::SetMousePos(float x, float y)
1026 {
1027 if (m_onscreen_ui)
1028 m_onscreen_ui->SetMousePos(x, y);
1029 }
1030
1031 void Presenter::SetMousePress(u32 button_mask)
1032 {
1033 if (m_onscreen_ui)
1034 m_onscreen_ui->SetMousePress(button_mask);
1035 }
1036
1037 void Presenter::DoState(PointerWrap& p)
1038 {
1039 p.Do(m_frame_count);
1040 p.Do(m_last_xfb_ticks);
1041 p.Do(m_last_xfb_addr);
1042 p.Do(m_last_xfb_width);
1043 p.Do(m_last_xfb_stride);
1044 p.Do(m_last_xfb_height);
1045
1046 // If we're loading and there is a last XFB, re-display it.
1047 if (p.IsReadMode() && m_last_xfb_stride != 0)
1048 {
1049 // This technically counts as the end of the frame
1050 GetVideoEvents().after_frame_event.Trigger(Core::System::GetInstance());
1051
1052 m_next_swap_estimated_ticks = m_last_xfb_ticks;
1053 m_next_swap_estimated_time = Clock::now();
1054
1055 m_immediate_swap_happened_this_field.store(false, std::memory_order_relaxed);
1056
1057 ImmediateSwap(m_last_xfb_addr, m_last_xfb_width, m_last_xfb_stride, m_last_xfb_height);
1058 }
1059 }
1060
1061 } // namespace VideoCommon