Debian Codegraph @

Source/Core/VideoCommon/BPFunctions.cpp

raw symbols SCIP
1 // Copyright 2009 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/BPFunctions.h"
5
6 #include <algorithm>
7 #include <cmath>
8 #include <string_view>
9
10 #include "Common/Assert.h"
11 #include "Common/CommonTypes.h"
12 #include "Common/Logging/Log.h"
13 #include "Common/SmallVector.h"
14 #include "Core/System.h"
15
16 #include "VideoCommon/AbstractGfx.h"
17 #include "VideoCommon/BPMemory.h"
18 #include "VideoCommon/EFBInterface.h"
19 #include "VideoCommon/FramebufferManager.h"
20 #include "VideoCommon/VertexManagerBase.h"
21 #include "VideoCommon/VertexShaderManager.h"
22 #include "VideoCommon/VideoCommon.h"
23 #include "VideoCommon/VideoConfig.h"
24 #include "VideoCommon/XFMemory.h"
25
26 namespace BPFunctions
27 {
28 // ----------------------------------------------
29 // State translation lookup tables
30 // Reference: Yet Another GameCube Documentation
31 // ----------------------------------------------
32
33 void FlushPipeline()
34 {
35 g_vertex_manager->Flush();
36 }
37
38 void SetGenerationMode()
39 {
40 g_vertex_manager->SetRasterizationStateChanged();
41 }
42
43 int ScissorRect::GetArea() const
44 {
45 return rect.GetWidth() * rect.GetHeight();
46 }
47
48 int ScissorResult::GetViewportArea(const ScissorRect& rect) const
49 {
50 int x0 = std::clamp<int>(rect.rect.left + rect.x_off, viewport_left, viewport_right);
51 int x1 = std::clamp<int>(rect.rect.right + rect.x_off, viewport_left, viewport_right);
52
53 int y0 = std::clamp<int>(rect.rect.top + rect.y_off, viewport_top, viewport_bottom);
54 int y1 = std::clamp<int>(rect.rect.bottom + rect.y_off, viewport_top, viewport_bottom);
55
56 return (x1 - x0) * (y1 - y0);
57 }
58
59 // Compare so that a sorted collection of rectangles has the best one last, so that if they're drawn
60 // in order, the best one is the one that is drawn last (and thus over the rest).
61 // The exact iteration order on hardware hasn't been tested, but silly things can happen where a
62 // polygon can intersect with itself; this only applies outside of the viewport region (in areas
63 // that would normally be affected by clipping). No game is known to care about this.
64 bool ScissorResult::IsWorse(const ScissorRect& lhs, const ScissorRect& rhs) const
65 {
66 // First, penalize any rect that is not in the viewport
67 int lhs_area = GetViewportArea(lhs);
68 int rhs_area = GetViewportArea(rhs);
69
70 if (lhs_area != rhs_area)
71 return lhs_area < rhs_area;
72
73 // Now compare on total areas, without regard for the viewport
74 return lhs.GetArea() < rhs.GetArea();
75 }
76
77 namespace
78 {
79 using RangeList = Common::SmallVector<ScissorRange, 9>;
80
81 static RangeList ComputeScissorRanges(int start, int end, int offset, int efb_dim)
82 {
83 RangeList ranges;
84
85 for (int extra_off = -4096; extra_off <= 4096; extra_off += 1024)
86 {
87 int new_off = offset + extra_off;
88 int new_start = std::clamp(start - new_off, 0, efb_dim);
89 int new_end = std::clamp(end - new_off + 1, 0, efb_dim);
90 if (new_start < new_end)
91 {
92 ranges.emplace_back(new_off, new_start, new_end);
93 }
94 }
95
96 return ranges;
97 }
98 } // namespace
99
100 ScissorResult::ScissorResult(ScissorPos scissor_top_left, ScissorPos scissor_bottom_right,
101 ScissorOffset scissor_offset, const Viewport& viewport)
102 : ScissorResult(scissor_top_left, scissor_bottom_right, scissor_offset,
103 std::minmax(viewport.xOrig - viewport.wd, viewport.xOrig + viewport.wd),
104 std::minmax(viewport.yOrig - viewport.ht, viewport.yOrig + viewport.ht))
105 {
106 }
107 ScissorResult::ScissorResult(ScissorPos scissor_top_left, ScissorPos scissor_bottom_right,
108 ScissorOffset scissor_offset, std::pair<float, float> viewport_x,
109 std::pair<float, float> viewport_y)
110 : scissor_tl{.hex = scissor_top_left.hex}, scissor_br{.hex = scissor_bottom_right.hex},
111 scissor_off{.hex = scissor_offset.hex}, viewport_left(viewport_x.first),
112 viewport_right(viewport_x.second), viewport_top(viewport_y.first),
113 viewport_bottom(viewport_y.second)
114 {
115 // Range is [left, right] and [top, bottom] (closed intervals)
116 const int left = scissor_tl.x;
117 const int right = scissor_br.x;
118 const int top = scissor_tl.y;
119 const int bottom = scissor_br.y;
120 // When left > right or top > bottom, nothing renders (even with wrapping from the offsets)
121 if (left > right || top > bottom)
122 return;
123
124 // Note that both the offsets and the coordinates have 342 added to them internally by GX
125 // functions (for the offsets, this is before they are divided by 2/right shifted). This code
126 // could undo both sets of offsets, but it doesn't need to since they cancel out when subtracting
127 // (and those offsets actually matter for the left > right and top > bottom checks).
128 const int x_off = scissor_off.x << 1;
129 const int y_off = scissor_off.y << 1;
130
131 RangeList x_ranges = ComputeScissorRanges(left, right, x_off, EFB_WIDTH);
132 RangeList y_ranges = ComputeScissorRanges(top, bottom, y_off, EFB_HEIGHT);
133
134 rectangles.reserve(x_ranges.size() * y_ranges.size());
135
136 // Now we need to form actual rectangles from the x and y ranges,
137 // which is a simple Cartesian product of x_ranges_clamped and y_ranges_clamped.
138 // Each rectangle is also a Cartesian product of x_range and y_range, with
139 // the rectangles being half-open (of the form [x0, x1) X [y0, y1)).
140 for (const auto& x_range : x_ranges)
141 {
142 DEBUG_ASSERT(x_range.start < x_range.end);
143 DEBUG_ASSERT(static_cast<u32>(x_range.end) <= EFB_WIDTH);
144 for (const auto& y_range : y_ranges)
145 {
146 DEBUG_ASSERT(y_range.start < y_range.end);
147 DEBUG_ASSERT(static_cast<u32>(y_range.end) <= EFB_HEIGHT);
148 rectangles.emplace_back(x_range, y_range);
149 }
150 }
151
152 auto cmp = [&](const ScissorRect& lhs, const ScissorRect& rhs) { return IsWorse(lhs, rhs); };
153 std::ranges::sort(rectangles, cmp);
154 }
155
156 ScissorRect ScissorResult::Best() const
157 {
158 // For now, simply choose the best rectangle (see ScissorResult::IsWorse).
159 // This does mean we calculate all rectangles and only choose one, which is not optimal, but this
160 // is called infrequently. Eventually, all backends will support multiple scissor rects.
161 if (!rectangles.empty())
162 {
163 return rectangles.back();
164 }
165 else
166 {
167 // But if we have no rectangles, use a bogus one that's out of bounds.
168 // Ideally, all backends will support multiple scissor rects, in which case this won't be
169 // needed.
170 return ScissorRect(ScissorRange{0, 1000, 1001}, ScissorRange{0, 1000, 1001});
171 }
172 }
173
174 ScissorResult ComputeScissorRects(ScissorPos scissor_top_left, ScissorPos scissor_bottom_right,
175 ScissorOffset scissor_offset, const Viewport& viewport)
176 {
177 return ScissorResult{scissor_top_left, scissor_bottom_right, scissor_offset, viewport};
178 }
179
180 void SetScissorAndViewport(FramebufferManager* frame_buffer_manager, ScissorPos scissor_top_left,
181 ScissorPos scissor_bottom_right, ScissorOffset scissor_offset,
182 Viewport viewport)
183 {
184 const auto result = BPFunctions::ComputeScissorRects(scissor_top_left, scissor_bottom_right,
185 scissor_offset, viewport);
186 auto native_rc = result.Best();
187
188 auto target_rc = frame_buffer_manager->ConvertEFBRectangle(native_rc.rect);
189 auto converted_rc = g_gfx->ConvertFramebufferRectangle(target_rc, g_gfx->GetCurrentFramebuffer());
190 g_gfx->SetScissorRect(converted_rc);
191
192 float raw_x = (viewport.xOrig - native_rc.x_off) - viewport.wd;
193 float raw_y = (viewport.yOrig - native_rc.y_off) + viewport.ht;
194 float raw_width = 2.0f * viewport.wd;
195 float raw_height = -2.0f * viewport.ht;
196 if (g_ActiveConfig.UseVertexRounding())
197 {
198 // Round the viewport to match full 1x IR pixels as well.
199 // This eliminates a line in the archery mode in Wii Sports Resort at 3x IR and higher.
200 raw_x = std::round(raw_x);
201 raw_y = std::round(raw_y);
202 raw_width = std::round(raw_width);
203 raw_height = std::round(raw_height);
204 }
205
206 float x = frame_buffer_manager->EFBToScaledXf(raw_x);
207 float y = frame_buffer_manager->EFBToScaledYf(raw_y);
208 float width = frame_buffer_manager->EFBToScaledXf(raw_width);
209 float height = frame_buffer_manager->EFBToScaledYf(raw_height);
210 float min_depth = (viewport.farZ - viewport.zRange) / 16777216.0f;
211 float max_depth = viewport.farZ / 16777216.0f;
212 if (width < 0.f)
213 {
214 x += width;
215 width *= -1;
216 }
217 if (height < 0.f)
218 {
219 y += height;
220 height *= -1;
221 }
222
223 if (!g_backend_info.bSupportsDepthClamp)
224 {
225 // There's no way to support oversized depth ranges in this situation. Let's just clamp the
226 // range to the maximum value supported by the console GPU and hope for the best.
227 min_depth = std::clamp(min_depth, 0.0f, MAX_EFB_DEPTH);
228 max_depth = std::clamp(max_depth, 0.0f, MAX_EFB_DEPTH);
229 }
230
231 if (VertexShaderManager::UseVertexDepthRange())
232 {
233 // We need to ensure depth values are clamped the maximum value supported by the console GPU.
234 // Taking into account whether the depth range is inverted or not.
235 if (viewport.zRange < 0.0f && g_backend_info.bSupportsReversedDepthRange)
236 {
237 min_depth = MAX_EFB_DEPTH;
238 max_depth = 0.0f;
239 }
240 else
241 {
242 min_depth = 0.0f;
243 max_depth = MAX_EFB_DEPTH;
244 }
245 }
246
247 float near_depth, far_depth;
248 if (g_backend_info.bSupportsReversedDepthRange)
249 {
250 // Set the reversed depth range.
251 near_depth = max_depth;
252 far_depth = min_depth;
253 }
254 else
255 {
256 // We use an inverted depth range here to apply the Reverse Z trick.
257 // This trick makes sure we match the precision provided by the 1:0
258 // clipping depth range on the hardware.
259 near_depth = 1.0f - max_depth;
260 far_depth = 1.0f - min_depth;
261 }
262
263 // Lower-left flip.
264 if (g_backend_info.bUsesLowerLeftOrigin)
265 y = static_cast<float>(g_gfx->GetCurrentFramebuffer()->GetHeight()) - y - height;
266
267 g_gfx->SetViewport(x, y, width, height, near_depth, far_depth);
268
269 g_gfx->StoreViewportAndScissor(AbstractGfx::ViewportAndScissor{.scissor_rect = converted_rc,
270 .viewport_x = x,
271 .viewport_y = y,
272 .viewport_width = width,
273 .viewport_height = height,
274 .viewport_near_depth = near_depth,
275 .viewport_far_depth = far_depth});
276 }
277
278 void SetDepthMode()
279 {
280 g_vertex_manager->SetDepthStateChanged();
281 }
282
283 void SetBlendMode()
284 {
285 g_vertex_manager->SetBlendingStateChanged();
286 }
287
288 /* Explanation of the magic behind ClearScreen:
289 There's numerous possible formats for the pixel data in the EFB.
290 However, in the HW accelerated backends we're always using RGBA8
291 for the EFB format, which causes some problems:
292 - We're using an alpha channel although the game doesn't
293 - If the actual EFB format is RGBA6_Z24 or R5G6B5_Z16, we are using more bits per channel than the
294 native HW
295
296 To properly emulate the above points, we're doing the following:
297 (1)
298 - disable alpha channel writing of any kind of rendering if the actual EFB format doesn't use an
299 alpha channel
300 - NOTE: Always make sure that the EFB has been cleared to an alpha value of 0xFF in this case!
301 - Same for color channels, these need to be cleared to 0x00 though.
302 (2)
303 - convert the RGBA8 color to RGBA6/RGB8/RGB565 and convert it to RGBA8 again
304 - convert the Z24 depth value to Z16 and back to Z24
305 */
306 bool ClearScreen(FramebufferManager* frame_buffer_manager, const MathUtil::Rectangle<int>& rc,
307 bool color_enable, bool alpha_enable, bool z_enable, PixelFormat pixel_format,
308 u32 clear_color_ar, u32 clear_color_gb, u32 clear_z_value)
309 {
310 // (1): Disable unused color channels
311 if (pixel_format == PixelFormat::RGB8_Z24 || pixel_format == PixelFormat::RGB565_Z16 ||
312 pixel_format == PixelFormat::Z24)
313 {
314 alpha_enable = false;
315 }
316
317 if (color_enable || alpha_enable || z_enable)
318 {
319 u32 color = (clear_color_ar << 16) | clear_color_gb;
320 u32 z = clear_z_value;
321
322 // (2) drop additional accuracy
323 if (pixel_format == PixelFormat::RGBA6_Z24)
324 {
325 color = RGBA8ToRGBA6ToRGBA8(color);
326 }
327 else if (pixel_format == PixelFormat::RGB565_Z16)
328 {
329 color = RGBA8ToRGB565ToRGBA8(color);
330 z = Z24ToZ16ToZ24(z);
331 }
332 frame_buffer_manager->ClearEFB(rc, color_enable, alpha_enable, z_enable, color, z,
333 pixel_format);
334 return true;
335 }
336
337 return false;
338 }
339
340 void OnPixelFormatChange(FramebufferManager* frame_buffer_manager, PixelFormat pixel_format,
341 DepthFormat z_format)
342 {
343 // TODO : Check for Z compression format change
344 // When using 16bit Z, the game may enable a special compression format which we might need to
345 // handle. Only a few games like RS2 and RS3 even use z compression but it looks like they
346 // always use ZFAR when using 16bit Z (on top of linear 24bit Z)
347
348 // Besides, we currently don't even emulate 16bit depth and force it to 24bit.
349
350 /*
351 * When changing the EFB format, the pixel data won't get converted to the new format but stays
352 * the same.
353 * Since we are always using an RGBA8 buffer though, this causes issues in some games.
354 * Thus, we reinterpret the old EFB data with the new format here.
355 */
356 if (!g_ActiveConfig.bEFBEmulateFormatChanges)
357 return;
358
359 const auto old_format = frame_buffer_manager->GetPrevPixelFormat();
360 const auto new_format = pixel_format;
361 frame_buffer_manager->StorePixelFormat(new_format);
362
363 DEBUG_LOG_FMT(VIDEO, "pixelfmt: pixel={}, zc={}", new_format, z_format);
364
365 // no need to reinterpret pixel data in these cases
366 if (new_format == old_format || old_format == PixelFormat::INVALID_FMT)
367 return;
368
369 // Check for pixel format changes
370 switch (old_format)
371 {
372 case PixelFormat::RGB8_Z24:
373 case PixelFormat::Z24:
374 {
375 // Z24 and RGB8_Z24 are treated equal, so just return in this case
376 if (new_format == PixelFormat::RGB8_Z24 || new_format == PixelFormat::Z24)
377 return;
378
379 if (new_format == PixelFormat::RGBA6_Z24)
380 {
381 g_efb_interface->ReinterpretPixelData(EFBReinterpretType::RGB8ToRGBA6);
382 return;
383 }
384 else if (new_format == PixelFormat::RGB565_Z16)
385 {
386 g_efb_interface->ReinterpretPixelData(EFBReinterpretType::RGB8ToRGB565);
387 return;
388 }
389 }
390 break;
391
392 case PixelFormat::RGBA6_Z24:
393 {
394 if (new_format == PixelFormat::RGB8_Z24 || new_format == PixelFormat::Z24)
395 {
396 g_efb_interface->ReinterpretPixelData(EFBReinterpretType::RGBA6ToRGB8);
397 return;
398 }
399 else if (new_format == PixelFormat::RGB565_Z16)
400 {
401 g_efb_interface->ReinterpretPixelData(EFBReinterpretType::RGBA6ToRGB565);
402 return;
403 }
404 }
405 break;
406
407 case PixelFormat::RGB565_Z16:
408 {
409 if (new_format == PixelFormat::RGB8_Z24 || new_format == PixelFormat::Z24)
410 {
411 g_efb_interface->ReinterpretPixelData(EFBReinterpretType::RGB565ToRGB8);
412 return;
413 }
414 else if (new_format == PixelFormat::RGBA6_Z24)
415 {
416 g_efb_interface->ReinterpretPixelData(EFBReinterpretType::RGB565ToRGBA6);
417 return;
418 }
419 }
420 break;
421
422 default:
423 break;
424 }
425
426 ERROR_LOG_FMT(VIDEO, "Unhandled EFB format change: {} to {}", old_format, new_format);
427 }
428
429 void SetInterlacingMode(const BPCmd& bp)
430 {
431 // TODO
432 switch (bp.address)
433 {
434 case BPMEM_FIELDMODE:
435 {
436 // SDK always sets bpmem.lineptwidth.lineaspect via BPMEM_LINEPTWIDTH
437 // just before this cmd
438 DEBUG_LOG_FMT(VIDEO, "BPMEM_FIELDMODE texLOD:{} lineaspect:{}", bpmem.fieldmode.texLOD,
439 bpmem.lineptwidth.adjust_for_aspect_ratio);
440 }
441 break;
442 case BPMEM_FIELDMASK:
443 {
444 // Determines if fields will be written to EFB (always computed)
445 DEBUG_LOG_FMT(VIDEO, "BPMEM_FIELDMASK even:{} odd:{}", bpmem.fieldmask.even,
446 bpmem.fieldmask.odd);
447 }
448 break;
449 default:
450 ERROR_LOG_FMT(VIDEO, "SetInterlacingMode default");
451 break;
452 }
453 }
454 } // namespace BPFunctions