| 1 | // Copyright 2010 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "VideoCommon/VertexManagerBase.h" |
| 5 | |
| 6 | #include <array> |
| 7 | #include <cmath> |
| 8 | #include <memory> |
| 9 | |
| 10 | #include "Common/ChunkFile.h" |
| 11 | #include "Common/CommonTypes.h" |
| 12 | #include "Common/Contains.h" |
| 13 | #include "Common/EnumMap.h" |
| 14 | #include "Common/Logging/Log.h" |
| 15 | #include "Common/MathUtil.h" |
| 16 | #include "Common/SmallVector.h" |
| 17 | |
| 18 | #include "Core/DolphinAnalytics.h" |
| 19 | #include "Core/HW/SystemTimers.h" |
| 20 | #include "Core/System.h" |
| 21 | |
| 22 | #include "VideoCommon/AbstractGfx.h" |
| 23 | #include "VideoCommon/BPMemory.h" |
| 24 | #include "VideoCommon/BoundingBox.h" |
| 25 | #include "VideoCommon/DataReader.h" |
| 26 | #include "VideoCommon/FramebufferManager.h" |
| 27 | #include "VideoCommon/GeometryShaderManager.h" |
| 28 | #include "VideoCommon/GraphicsModSystem/Runtime/CustomShaderCache.h" |
| 29 | #include "VideoCommon/GraphicsModSystem/Runtime/GraphicsModActionData.h" |
| 30 | #include "VideoCommon/GraphicsModSystem/Runtime/GraphicsModManager.h" |
| 31 | #include "VideoCommon/IndexGenerator.h" |
| 32 | #include "VideoCommon/NativeVertexFormat.h" |
| 33 | #include "VideoCommon/OpcodeDecoding.h" |
| 34 | #include "VideoCommon/PerfQueryBase.h" |
| 35 | #include "VideoCommon/PixelShaderGen.h" |
| 36 | #include "VideoCommon/PixelShaderManager.h" |
| 37 | #include "VideoCommon/Statistics.h" |
| 38 | #include "VideoCommon/TextureCacheBase.h" |
| 39 | #include "VideoCommon/VertexLoaderManager.h" |
| 40 | #include "VideoCommon/VertexShaderManager.h" |
| 41 | #include "VideoCommon/VideoBackendBase.h" |
| 42 | #include "VideoCommon/VideoCommon.h" |
| 43 | #include "VideoCommon/VideoConfig.h" |
| 44 | #include "VideoCommon/XFMemory.h" |
| 45 | #include "VideoCommon/XFStateManager.h" |
| 46 | |
| 47 | std::unique_ptr<VertexManagerBase> g_vertex_manager; |
| 48 | |
| 49 | using OpcodeDecoder::Primitive; |
| 50 | |
| 51 | // GX primitive -> RenderState primitive, no primitive restart |
| 52 | constexpr Common::EnumMap<PrimitiveType, Primitive::GX_DRAW_POINTS> primitive_from_gx{ |
| 53 | PrimitiveType::Triangles, // GX_DRAW_QUADS |
| 54 | PrimitiveType::Triangles, // GX_DRAW_QUADS_2 |
| 55 | PrimitiveType::Triangles, // GX_DRAW_TRIANGLES |
| 56 | PrimitiveType::Triangles, // GX_DRAW_TRIANGLE_STRIP |
| 57 | PrimitiveType::Triangles, // GX_DRAW_TRIANGLE_FAN |
| 58 | PrimitiveType::Lines, // GX_DRAW_LINES |
| 59 | PrimitiveType::Lines, // GX_DRAW_LINE_STRIP |
| 60 | PrimitiveType::Points, // GX_DRAW_POINTS |
| 61 | }; |
| 62 | |
| 63 | // GX primitive -> RenderState primitive, using primitive restart |
| 64 | constexpr Common::EnumMap<PrimitiveType, Primitive::GX_DRAW_POINTS> primitive_from_gx_pr{ |
| 65 | PrimitiveType::TriangleStrip, // GX_DRAW_QUADS |
| 66 | PrimitiveType::TriangleStrip, // GX_DRAW_QUADS_2 |
| 67 | PrimitiveType::TriangleStrip, // GX_DRAW_TRIANGLES |
| 68 | PrimitiveType::TriangleStrip, // GX_DRAW_TRIANGLE_STRIP |
| 69 | PrimitiveType::TriangleStrip, // GX_DRAW_TRIANGLE_FAN |
| 70 | PrimitiveType::Lines, // GX_DRAW_LINES |
| 71 | PrimitiveType::Lines, // GX_DRAW_LINE_STRIP |
| 72 | PrimitiveType::Points, // GX_DRAW_POINTS |
| 73 | }; |
| 74 | |
| 75 | // Due to the BT.601 standard which the GameCube is based on being a compromise |
| 76 | // between PAL and NTSC, neither standard gets square pixels. They are each off |
| 77 | // by ~9% in opposite directions. |
| 78 | // Just in case any game decides to take this into account, we do both these |
| 79 | // tests with a large amount of slop. |
| 80 | |
| 81 | static float CalculateProjectionViewportRatio(const Projection::Raw& projection, |
| 82 | const Viewport& viewport) |
| 83 | { |
| 84 | const float projection_ar = projection[2] / projection[0]; |
| 85 | const float viewport_ar = viewport.wd / viewport.ht; |
| 86 | |
| 87 | return std::abs(projection_ar / viewport_ar); |
| 88 | } |
| 89 | |
| 90 | static bool IsAnamorphicProjection(const Projection::Raw& projection, const Viewport& viewport, |
| 91 | const VideoConfig& config) |
| 92 | { |
| 93 | // If ratio between our projection and viewport aspect ratios is similar to 16:9 / 4:3 |
| 94 | // we have an anamorphic projection. This value can be overridden by a GameINI. |
| 95 | // Game cheats that change the aspect ratio to natively unsupported ones |
| 96 | // won't be automatically recognized here. |
| 97 | |
| 98 | return std::abs(CalculateProjectionViewportRatio(projection, viewport) - |
| 99 | config.widescreen_heuristic_widescreen_ratio) < |
| 100 | config.widescreen_heuristic_aspect_ratio_slop; |
| 101 | } |
| 102 | |
| 103 | static bool IsNormalProjection(const Projection::Raw& projection, const Viewport& viewport, |
| 104 | const VideoConfig& config) |
| 105 | { |
| 106 | return std::abs(CalculateProjectionViewportRatio(projection, viewport) - |
| 107 | config.widescreen_heuristic_standard_ratio) < |
| 108 | config.widescreen_heuristic_aspect_ratio_slop; |
| 109 | } |
| 110 | |
| 111 | VertexManagerBase::VertexManagerBase() |
| 112 | : m_cpu_vertex_buffer(MAXVBUFFERSIZE), m_cpu_index_buffer(MAXIBUFFERSIZE) |
| 113 | { |
| 114 | } |
| 115 | |
| 116 | VertexManagerBase::~VertexManagerBase() = default; |
| 117 | |
| 118 | bool VertexManagerBase::Initialize() |
| 119 | { |
| 120 | auto& video_events = GetVideoEvents(); |
| 121 | |
| 122 | m_frame_end_event = |
| 123 | video_events.after_frame_event.Register([this](Core::System&) { OnEndFrame(); }); |
| 124 | m_after_present_event = video_events.after_present_event.Register( |
| 125 | [this](const PresentInfo& pi) { m_ticks_elapsed = pi.emulated_timestamp; }); |
| 126 | m_index_generator.Init(); |
| 127 | m_custom_shader_cache = std::make_unique<CustomShaderCache>(); |
| 128 | m_cpu_cull.Init(); |
| 129 | return true; |
| 130 | } |
| 131 | |
| 132 | u32 VertexManagerBase::GetRemainingSize() const |
| 133 | { |
| 134 | return static_cast<u32>(m_end_buffer_pointer - m_cur_buffer_pointer); |
| 135 | } |
| 136 | |
| 137 | void VertexManagerBase::AddIndices(OpcodeDecoder::Primitive primitive, u32 num_vertices) |
| 138 | { |
| 139 | m_index_generator.AddIndices(primitive, num_vertices); |
| 140 | } |
| 141 | |
| 142 | bool VertexManagerBase::AreAllVerticesCulled(VertexLoaderBase* loader, |
| 143 | OpcodeDecoder::Primitive primitive, const u8* src, |
| 144 | u32 count) |
| 145 | { |
| 146 | return m_cpu_cull.AreAllVerticesCulled(loader, primitive, src, count); |
| 147 | } |
| 148 | |
| 149 | DataReader VertexManagerBase::PrepareForAdditionalData(OpcodeDecoder::Primitive primitive, |
| 150 | u32 count, u32 stride, bool cullall) |
| 151 | { |
| 152 | // Flush all EFB pokes. Since the buffer is shared, we can't draw pokes+primitives concurrently. |
| 153 | g_framebuffer_manager->FlushEFBPokes(); |
| 154 | |
| 155 | // The SSE vertex loader can write up to 4 bytes past the end |
| 156 | u32 const needed_vertex_bytes = count * stride + 4; |
| 157 | |
| 158 | // We can't merge different kinds of primitives, so we have to flush here |
| 159 | PrimitiveType new_primitive_type = g_backend_info.bSupportsPrimitiveRestart ? |
| 160 | primitive_from_gx_pr[primitive] : |
| 161 | primitive_from_gx[primitive]; |
| 162 | if (m_current_primitive_type != new_primitive_type) [[unlikely]] |
| 163 | { |
| 164 | Flush(); |
| 165 | |
| 166 | // Have to update the rasterization state for point/line cull modes. |
| 167 | m_current_primitive_type = new_primitive_type; |
| 168 | SetRasterizationStateChanged(); |
| 169 | } |
| 170 | |
| 171 | u32 remaining_indices = GetRemainingIndices(primitive); |
| 172 | u32 remaining_index_generator_indices = m_index_generator.GetRemainingIndices(primitive); |
| 173 | |
| 174 | // Check for size in buffer, if the buffer gets full, call Flush() |
| 175 | if (!m_is_flushed && (count > remaining_index_generator_indices || count > remaining_indices || |
| 176 | needed_vertex_bytes > GetRemainingSize())) [[unlikely]] |
| 177 | { |
| 178 | Flush(); |
| 179 | } |
| 180 | |
| 181 | m_cull_all = cullall; |
| 182 | |
| 183 | // need to alloc new buffer |
| 184 | if (m_is_flushed) [[unlikely]] |
| 185 | { |
| 186 | if (cullall) |
| 187 | { |
| 188 | // This buffer isn't getting sent to the GPU. Just allocate it on the cpu. |
| 189 | m_cur_buffer_pointer = m_base_buffer_pointer = m_cpu_vertex_buffer.data(); |
| 190 | m_end_buffer_pointer = m_base_buffer_pointer + m_cpu_vertex_buffer.size(); |
| 191 | m_index_generator.Start(m_cpu_index_buffer.data()); |
| 192 | } |
| 193 | else |
| 194 | { |
| 195 | ResetBuffer(stride); |
| 196 | } |
| 197 | |
| 198 | remaining_index_generator_indices = m_index_generator.GetRemainingIndices(primitive); |
| 199 | remaining_indices = GetRemainingIndices(primitive); |
| 200 | m_is_flushed = false; |
| 201 | } |
| 202 | |
| 203 | // Now that we've reset the buffer, there should be enough space. It's possible that we still |
| 204 | // won't have enough space in a few rare cases, such as vertex shader line/point expansion with a |
| 205 | // ton of lines in one draw command, in which case we will either need to add support for |
| 206 | // splitting a single draw command into multiple draws or using bigger indices. |
| 207 | ASSERT_MSG(VIDEO, count <= remaining_index_generator_indices, |
| 208 | "VertexManager: Too few remaining index values ({} > {}). " |
| 209 | "32-bit indices or primitive breaking needed.", |
| 210 | count, remaining_index_generator_indices); |
| 211 | ASSERT_MSG(VIDEO, count <= remaining_indices, |
| 212 | "VertexManager: Buffer not large enough for all indices! ({} > {}) " |
| 213 | "Increase MAXIBUFFERSIZE or we need primitive breaking after all.", |
| 214 | count, remaining_indices); |
| 215 | ASSERT_MSG(VIDEO, needed_vertex_bytes <= GetRemainingSize(), |
| 216 | "VertexManager: Buffer not large enough for all vertices! ({} > {}) " |
| 217 | "Increase MAXVBUFFERSIZE or we need primitive breaking after all.", |
| 218 | needed_vertex_bytes, GetRemainingSize()); |
| 219 | |
| 220 | return DataReader(m_cur_buffer_pointer, m_end_buffer_pointer); |
| 221 | } |
| 222 | |
| 223 | DataReader VertexManagerBase::DisableCullAll(u32 stride) |
| 224 | { |
| 225 | if (m_cull_all) |
| 226 | { |
| 227 | m_cull_all = false; |
| 228 | ResetBuffer(stride); |
| 229 | } |
| 230 | return DataReader(m_cur_buffer_pointer, m_end_buffer_pointer); |
| 231 | } |
| 232 | |
| 233 | void VertexManagerBase::FlushData(u32 count, u32 stride) |
| 234 | { |
| 235 | m_cur_buffer_pointer += count * stride; |
| 236 | } |
| 237 | |
| 238 | u32 VertexManagerBase::GetRemainingIndices(OpcodeDecoder::Primitive primitive) const |
| 239 | { |
| 240 | const u32 index_len = MAXIBUFFERSIZE - m_index_generator.GetIndexLen(); |
| 241 | |
| 242 | if (primitive >= Primitive::GX_DRAW_LINES) |
| 243 | { |
| 244 | if (g_Config.UseVSForLinePointExpand()) |
| 245 | { |
| 246 | if (g_backend_info.bSupportsPrimitiveRestart) |
| 247 | { |
| 248 | switch (primitive) |
| 249 | { |
| 250 | case Primitive::GX_DRAW_LINES: |
| 251 | return index_len / 5 * 2; |
| 252 | case Primitive::GX_DRAW_LINE_STRIP: |
| 253 | return index_len / 5 + 1; |
| 254 | case Primitive::GX_DRAW_POINTS: |
| 255 | return index_len / 5; |
| 256 | default: |
| 257 | return 0; |
| 258 | } |
| 259 | } |
| 260 | else |
| 261 | { |
| 262 | switch (primitive) |
| 263 | { |
| 264 | case Primitive::GX_DRAW_LINES: |
| 265 | return index_len / 6 * 2; |
| 266 | case Primitive::GX_DRAW_LINE_STRIP: |
| 267 | return index_len / 6 + 1; |
| 268 | case Primitive::GX_DRAW_POINTS: |
| 269 | return index_len / 6; |
| 270 | default: |
| 271 | return 0; |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | else |
| 276 | { |
| 277 | switch (primitive) |
| 278 | { |
| 279 | case Primitive::GX_DRAW_LINES: |
| 280 | return index_len; |
| 281 | case Primitive::GX_DRAW_LINE_STRIP: |
| 282 | return index_len / 2 + 1; |
| 283 | case Primitive::GX_DRAW_POINTS: |
| 284 | return index_len; |
| 285 | default: |
| 286 | return 0; |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | else if (g_backend_info.bSupportsPrimitiveRestart) |
| 291 | { |
| 292 | switch (primitive) |
| 293 | { |
| 294 | case Primitive::GX_DRAW_QUADS: |
| 295 | case Primitive::GX_DRAW_QUADS_2: |
| 296 | return index_len / 5 * 4; |
| 297 | case Primitive::GX_DRAW_TRIANGLES: |
| 298 | return index_len / 4 * 3; |
| 299 | case Primitive::GX_DRAW_TRIANGLE_STRIP: |
| 300 | return index_len / 1 - 1; |
| 301 | case Primitive::GX_DRAW_TRIANGLE_FAN: |
| 302 | return index_len / 6 * 4 + 1; |
| 303 | default: |
| 304 | return 0; |
| 305 | } |
| 306 | } |
| 307 | else |
| 308 | { |
| 309 | switch (primitive) |
| 310 | { |
| 311 | case Primitive::GX_DRAW_QUADS: |
| 312 | case Primitive::GX_DRAW_QUADS_2: |
| 313 | return index_len / 6 * 4; |
| 314 | case Primitive::GX_DRAW_TRIANGLES: |
| 315 | return index_len; |
| 316 | case Primitive::GX_DRAW_TRIANGLE_STRIP: |
| 317 | return index_len / 3 + 2; |
| 318 | case Primitive::GX_DRAW_TRIANGLE_FAN: |
| 319 | return index_len / 3 + 2; |
| 320 | default: |
| 321 | return 0; |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | auto VertexManagerBase::ResetFlushAspectRatioCount() -> FlushStatistics |
| 327 | { |
| 328 | const auto result = m_flush_statistics; |
| 329 | m_flush_statistics = {}; |
| 330 | return result; |
| 331 | } |
| 332 | |
| 333 | void VertexManagerBase::ResetBuffer(u32 vertex_stride) |
| 334 | { |
| 335 | m_base_buffer_pointer = m_cpu_vertex_buffer.data(); |
| 336 | m_cur_buffer_pointer = m_cpu_vertex_buffer.data(); |
| 337 | m_end_buffer_pointer = m_base_buffer_pointer + m_cpu_vertex_buffer.size(); |
| 338 | m_index_generator.Start(m_cpu_index_buffer.data()); |
| 339 | } |
| 340 | |
| 341 | void VertexManagerBase::CommitBuffer(u32 num_vertices, u32 vertex_stride, u32 num_indices, |
| 342 | u32* out_base_vertex, u32* out_base_index) |
| 343 | { |
| 344 | *out_base_vertex = 0; |
| 345 | *out_base_index = 0; |
| 346 | } |
| 347 | |
| 348 | void VertexManagerBase::DrawCurrentBatch(u32 base_index, u32 num_indices, u32 base_vertex) |
| 349 | { |
| 350 | // If bounding box is enabled, we need to flush any changes first, then invalidate what we have. |
| 351 | if (g_bounding_box->IsEnabled() && g_ActiveConfig.bBBoxEnable && g_backend_info.bSupportsBBox) |
| 352 | { |
| 353 | g_bounding_box->Flush(); |
| 354 | } |
| 355 | |
| 356 | g_gfx->DrawIndexed(base_index, num_indices, base_vertex); |
| 357 | } |
| 358 | |
| 359 | void VertexManagerBase::UploadUniforms() |
| 360 | { |
| 361 | } |
| 362 | |
| 363 | void VertexManagerBase::InvalidateConstants() |
| 364 | { |
| 365 | auto& system = Core::System::GetInstance(); |
| 366 | auto& vertex_shader_manager = system.GetVertexShaderManager(); |
| 367 | auto& geometry_shader_manager = system.GetGeometryShaderManager(); |
| 368 | auto& pixel_shader_manager = system.GetPixelShaderManager(); |
| 369 | vertex_shader_manager.dirty = true; |
| 370 | geometry_shader_manager.dirty = true; |
| 371 | pixel_shader_manager.dirty = true; |
| 372 | } |
| 373 | |
| 374 | void VertexManagerBase::UploadUtilityUniforms(const void* uniforms, u32 uniforms_size) |
| 375 | { |
| 376 | } |
| 377 | |
| 378 | void VertexManagerBase::UploadUtilityVertices(const void* vertices, u32 vertex_stride, |
| 379 | u32 num_vertices, const u16* indices, u32 num_indices, |
| 380 | u32* out_base_vertex, u32* out_base_index) |
| 381 | { |
| 382 | // The GX vertex list should be flushed before any utility draws occur. |
| 383 | ASSERT(m_is_flushed); |
| 384 | |
| 385 | // Copy into the buffers usually used for GX drawing. |
| 386 | ResetBuffer(std::max(vertex_stride, 1u)); |
| 387 | if (vertices) |
| 388 | { |
| 389 | const u32 copy_size = vertex_stride * num_vertices; |
| 390 | ASSERT((m_cur_buffer_pointer + copy_size) <= m_end_buffer_pointer); |
| 391 | std::memcpy(m_cur_buffer_pointer, vertices, copy_size); |
| 392 | m_cur_buffer_pointer += copy_size; |
| 393 | } |
| 394 | if (indices) |
| 395 | m_index_generator.AddExternalIndices(indices, num_indices, num_vertices); |
| 396 | |
| 397 | CommitBuffer(num_vertices, vertex_stride, num_indices, out_base_vertex, out_base_index); |
| 398 | } |
| 399 | |
| 400 | u32 VertexManagerBase::GetTexelBufferElementSize(TexelBufferFormat buffer_format) |
| 401 | { |
| 402 | // R8 - 1, R16 - 2, RGBA8 - 4, R32G32 - 8 |
| 403 | return 1u << static_cast<u32>(buffer_format); |
| 404 | } |
| 405 | |
| 406 | bool VertexManagerBase::UploadTexelBuffer(const void* data, u32 data_size, TexelBufferFormat format, |
| 407 | u32* out_offset) |
| 408 | { |
| 409 | return false; |
| 410 | } |
| 411 | |
| 412 | bool VertexManagerBase::UploadTexelBuffer(const void* data, u32 data_size, TexelBufferFormat format, |
| 413 | u32* out_offset, const void* palette_data, |
| 414 | u32 palette_size, TexelBufferFormat palette_format, |
| 415 | u32* palette_offset) |
| 416 | { |
| 417 | return false; |
| 418 | } |
| 419 | |
| 420 | BitSet32 VertexManagerBase::UsedTextures() const |
| 421 | { |
| 422 | BitSet32 usedtextures; |
| 423 | for (u32 i = 0; i < bpmem.genMode.numtevstages + 1u; ++i) |
| 424 | if (bpmem.tevorders[i / 2].getEnable(i & 1)) |
| 425 | usedtextures[bpmem.tevorders[i / 2].getTexMap(i & 1)] = true; |
| 426 | |
| 427 | if (bpmem.genMode.numindstages > 0) |
| 428 | for (unsigned int i = 0; i < bpmem.genMode.numtevstages + 1u; ++i) |
| 429 | if (bpmem.tevind[i].IsActive() && bpmem.tevind[i].bt < bpmem.genMode.numindstages) |
| 430 | usedtextures[bpmem.tevindref.getTexMap(bpmem.tevind[i].bt)] = true; |
| 431 | |
| 432 | return usedtextures; |
| 433 | } |
| 434 | |
| 435 | void VertexManagerBase::Flush() |
| 436 | { |
| 437 | if (m_is_flushed) |
| 438 | return; |
| 439 | |
| 440 | m_is_flushed = true; |
| 441 | |
| 442 | if (m_draw_counter == 0) |
| 443 | { |
| 444 | // This is more or less the start of the Frame |
| 445 | GetVideoEvents().before_frame_event.Trigger(); |
| 446 | } |
| 447 | |
| 448 | if (xfmem.numTexGen.numTexGens != bpmem.genMode.numtexgens || |
| 449 | xfmem.numChan.numColorChans != bpmem.genMode.numcolchans) |
| 450 | { |
| 451 | ERROR_LOG_FMT( |
| 452 | VIDEO, |
| 453 | "Mismatched configuration between XF and BP stages - {}/{} texgens, {}/{} colors. " |
| 454 | "Skipping draw. Please report on the issue tracker.", |
| 455 | xfmem.numTexGen.numTexGens, bpmem.genMode.numtexgens.Value(), xfmem.numChan.numColorChans, |
| 456 | bpmem.genMode.numcolchans.Value()); |
| 457 | |
| 458 | // Analytics reporting so we can discover which games have this problem, that way when we |
| 459 | // eventually simulate the behavior we have test cases for it. |
| 460 | if (xfmem.numTexGen.numTexGens != bpmem.genMode.numtexgens) |
| 461 | { |
| 462 | DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::MismatchedGPUTexGensBetweenXFAndBP); |
| 463 | } |
| 464 | if (xfmem.numChan.numColorChans != bpmem.genMode.numcolchans) |
| 465 | { |
| 466 | DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::MismatchedGPUColorsBetweenXFAndBP); |
| 467 | } |
| 468 | |
| 469 | return; |
| 470 | } |
| 471 | |
| 472 | #if defined(_DEBUG) || defined(DEBUGFAST) |
| 473 | PRIM_LOG("frame{}:\n texgen={}, numchan={}, dualtex={}, ztex={}, cole={}, alpe={}, ze={}", |
| 474 | g_ActiveConfig.iSaveTargetId, xfmem.numTexGen.numTexGens, xfmem.numChan.numColorChans, |
| 475 | xfmem.dualTexTrans.enabled, bpmem.ztex2.op.Value(), bpmem.blendmode.color_update.Value(), |
| 476 | bpmem.blendmode.alpha_update.Value(), bpmem.zmode.update_enable.Value()); |
| 477 | |
| 478 | for (u32 i = 0; i < xfmem.numChan.numColorChans; ++i) |
| 479 | { |
| 480 | LitChannel* ch = &xfmem.color[i]; |
| 481 | PRIM_LOG("colchan{}: matsrc={}, light={:#x}, ambsrc={}, diffunc={}, attfunc={}", i, |
| 482 | ch->matsource.Value(), ch->GetFullLightMask(), ch->ambsource.Value(), |
| 483 | ch->diffusefunc.Value(), ch->attnfunc.Value()); |
| 484 | ch = &xfmem.alpha[i]; |
| 485 | PRIM_LOG("alpchan{}: matsrc={}, light={:#x}, ambsrc={}, diffunc={}, attfunc={}", i, |
| 486 | ch->matsource.Value(), ch->GetFullLightMask(), ch->ambsource.Value(), |
| 487 | ch->diffusefunc.Value(), ch->attnfunc.Value()); |
| 488 | } |
| 489 | |
| 490 | for (u32 i = 0; i < xfmem.numTexGen.numTexGens; ++i) |
| 491 | { |
| 492 | TexMtxInfo tinfo = xfmem.texMtxInfo[i]; |
| 493 | if (tinfo.texgentype != TexGenType::EmbossMap) |
| 494 | tinfo.hex &= 0x7ff; |
| 495 | if (tinfo.texgentype != TexGenType::Regular) |
| 496 | tinfo.projection = TexSize::ST; |
| 497 | |
| 498 | PRIM_LOG("txgen{}: proj={}, input={}, gentype={}, srcrow={}, embsrc={}, emblght={}, " |
| 499 | "postmtx={}, postnorm={}", |
| 500 | i, tinfo.projection.Value(), tinfo.inputform.Value(), tinfo.texgentype.Value(), |
| 501 | tinfo.sourcerow.Value(), tinfo.embosssourceshift.Value(), |
| 502 | tinfo.embosslightshift.Value(), xfmem.postMtxInfo[i].index.Value(), |
| 503 | xfmem.postMtxInfo[i].normalize.Value()); |
| 504 | } |
| 505 | |
| 506 | PRIM_LOG("pixel: tev={}, ind={}, texgen={}, dstalpha={}, alphatest={:#x}", |
| 507 | bpmem.genMode.numtevstages.Value() + 1, bpmem.genMode.numindstages.Value(), |
| 508 | bpmem.genMode.numtexgens.Value(), bpmem.dstalpha.enable.Value(), |
| 509 | (bpmem.alpha_test.hex >> 16) & 0xff); |
| 510 | #endif |
| 511 | |
| 512 | // Track some stats used elsewhere by the anamorphic widescreen heuristic. |
| 513 | auto& system = Core::System::GetInstance(); |
| 514 | if (!system.IsWii()) |
| 515 | { |
| 516 | const bool is_perspective = xfmem.projection.type == ProjectionType::Perspective; |
| 517 | |
| 518 | auto& counts = |
| 519 | is_perspective ? m_flush_statistics.perspective : m_flush_statistics.orthographic; |
| 520 | |
| 521 | const auto& projection = xfmem.projection.rawProjection; |
| 522 | // TODO: Potentially the viewport size could be used as weight for the flush count average. |
| 523 | // This way a small minimap would have less effect than a fullscreen projection. |
| 524 | const auto& viewport = xfmem.viewport; |
| 525 | |
| 526 | // FYI: This average is based on flushes. |
| 527 | // It doesn't look at vertex counts like the heuristic does. |
| 528 | counts.average_ratio.Push(CalculateProjectionViewportRatio(projection, viewport)); |
| 529 | |
| 530 | if (IsAnamorphicProjection(projection, viewport, g_ActiveConfig)) |
| 531 | { |
| 532 | ++counts.anamorphic_flush_count; |
| 533 | counts.anamorphic_vertex_count += m_index_generator.GetIndexLen(); |
| 534 | } |
| 535 | else if (IsNormalProjection(projection, viewport, g_ActiveConfig)) |
| 536 | { |
| 537 | ++counts.normal_flush_count; |
| 538 | counts.normal_vertex_count += m_index_generator.GetIndexLen(); |
| 539 | } |
| 540 | else |
| 541 | { |
| 542 | ++counts.other_flush_count; |
| 543 | counts.other_vertex_count += m_index_generator.GetIndexLen(); |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | auto& pixel_shader_manager = system.GetPixelShaderManager(); |
| 548 | auto& geometry_shader_manager = system.GetGeometryShaderManager(); |
| 549 | auto& vertex_shader_manager = system.GetVertexShaderManager(); |
| 550 | auto& xf_state_manager = system.GetXFStateManager(); |
| 551 | |
| 552 | if (g_ActiveConfig.bGraphicMods) |
| 553 | { |
| 554 | const double seconds_elapsed = |
| 555 | static_cast<double>(m_ticks_elapsed) / system.GetSystemTimers().GetTicksPerSecond(); |
| 556 | pixel_shader_manager.constants.time_ms = seconds_elapsed * 1000; |
| 557 | } |
| 558 | |
| 559 | CalculateNormals(VertexLoaderManager::GetCurrentVertexFormat()); |
| 560 | // Calculate ZSlope for zfreeze |
| 561 | const auto used_textures = UsedTextures(); |
| 562 | std::vector<std::string> texture_names; |
| 563 | Common::SmallVector<u32, 8> texture_units; |
| 564 | std::array<SamplerState, 8> samplers; |
| 565 | if (!m_cull_all) |
| 566 | { |
| 567 | if (!g_ActiveConfig.bGraphicMods) |
| 568 | { |
| 569 | for (const u32 i : used_textures) |
| 570 | { |
| 571 | const auto cache_entry = g_texture_cache->Load(i); |
| 572 | if (!cache_entry) |
| 573 | continue; |
| 574 | const float custom_tex_scale = cache_entry->GetWidth() / float(cache_entry->native_width); |
| 575 | samplers[i] = TextureCacheBase::GetSamplerState( |
| 576 | i, custom_tex_scale, cache_entry->is_custom_tex, cache_entry->has_arbitrary_mips); |
| 577 | } |
| 578 | } |
| 579 | else |
| 580 | { |
| 581 | for (const u32 i : used_textures) |
| 582 | { |
| 583 | const auto cache_entry = g_texture_cache->Load(i); |
| 584 | if (cache_entry) |
| 585 | { |
| 586 | if (!Common::Contains(texture_names, cache_entry->texture_info_name)) |
| 587 | { |
| 588 | texture_names.push_back(cache_entry->texture_info_name); |
| 589 | texture_units.push_back(i); |
| 590 | } |
| 591 | |
| 592 | const float custom_tex_scale = cache_entry->GetWidth() / float(cache_entry->native_width); |
| 593 | samplers[i] = TextureCacheBase::GetSamplerState( |
| 594 | i, custom_tex_scale, cache_entry->is_custom_tex, cache_entry->has_arbitrary_mips); |
| 595 | } |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | vertex_shader_manager.SetConstants(texture_names, xf_state_manager); |
| 600 | if (!bpmem.genMode.zfreeze) |
| 601 | { |
| 602 | // Must be done after VertexShaderManager::SetConstants() |
| 603 | CalculateZSlope(VertexLoaderManager::GetCurrentVertexFormat()); |
| 604 | } |
| 605 | else if (m_zslope.dirty && !m_cull_all) // or apply any dirty ZSlopes |
| 606 | { |
| 607 | pixel_shader_manager.SetZSlope(m_zslope.dfdx, m_zslope.dfdy, m_zslope.f0); |
| 608 | m_zslope.dirty = false; |
| 609 | } |
| 610 | |
| 611 | if (!m_cull_all) |
| 612 | { |
| 613 | CustomPixelShaderContents custom_pixel_shader_contents; |
| 614 | std::optional<CustomPixelShader> custom_pixel_shader; |
| 615 | std::vector<std::string> custom_pixel_texture_names; |
| 616 | std::span<u8> custom_pixel_shader_uniforms; |
| 617 | bool skip = false; |
| 618 | for (size_t i = 0; i < texture_names.size(); i++) |
| 619 | { |
| 620 | GraphicsModActionData::DrawStarted draw_started{texture_units, &skip, &custom_pixel_shader, |
| 621 | &custom_pixel_shader_uniforms}; |
| 622 | for (const auto& action : g_graphics_mod_manager->GetDrawStartedActions(texture_names[i])) |
| 623 | { |
| 624 | action->OnDrawStarted(&draw_started); |
| 625 | if (custom_pixel_shader) |
| 626 | { |
| 627 | custom_pixel_shader_contents.shaders.push_back(*custom_pixel_shader); |
| 628 | custom_pixel_texture_names.push_back(texture_names[i]); |
| 629 | } |
| 630 | custom_pixel_shader = std::nullopt; |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | // Now the vertices can be flushed to the GPU. Everything following the CommitBuffer() call |
| 635 | // must be careful to not upload any utility vertices, as the binding will be lost otherwise. |
| 636 | const u32 num_indices = m_index_generator.GetIndexLen(); |
| 637 | if (num_indices == 0) |
| 638 | return; |
| 639 | |
| 640 | // Texture loading can cause palettes to be applied (-> uniforms -> draws). |
| 641 | // Palette application does not use vertices, only a full-screen quad, so this is okay. |
| 642 | // Same with GPU texture decoding, which uses compute shaders. |
| 643 | g_texture_cache->BindTextures(used_textures, samplers); |
| 644 | |
| 645 | if (!skip) |
| 646 | { |
| 647 | UpdatePipelineConfig(); |
| 648 | UpdatePipelineObject(); |
| 649 | if (m_current_pipeline_object) |
| 650 | { |
| 651 | const AbstractPipeline* pipeline_object = m_current_pipeline_object; |
| 652 | if (!custom_pixel_shader_contents.shaders.empty()) |
| 653 | { |
| 654 | if (const auto custom_pipeline = |
| 655 | GetCustomPipeline(custom_pixel_shader_contents, m_current_pipeline_config, |
| 656 | m_current_uber_pipeline_config, m_current_pipeline_object)) |
| 657 | { |
| 658 | pipeline_object = custom_pipeline; |
| 659 | } |
| 660 | } |
| 661 | RenderDrawCall(pixel_shader_manager, geometry_shader_manager, custom_pixel_shader_contents, |
| 662 | custom_pixel_shader_uniforms, m_current_primitive_type, pipeline_object); |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | // Even if we skip the draw, emulated state should still be impacted |
| 667 | OnDraw(); |
| 668 | |
| 669 | // The EFB cache is now potentially stale. |
| 670 | g_framebuffer_manager->FlagPeekCacheAsOutOfDate(); |
| 671 | } |
| 672 | |
| 673 | if (xfmem.numTexGen.numTexGens != bpmem.genMode.numtexgens) |
| 674 | { |
| 675 | ERROR_LOG_FMT(VIDEO, |
| 676 | "xf.numtexgens ({}) does not match bp.numtexgens ({}). Error in command stream.", |
| 677 | xfmem.numTexGen.numTexGens, bpmem.genMode.numtexgens.Value()); |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | void VertexManagerBase::DoState(PointerWrap& p) |
| 682 | { |
| 683 | if (p.IsReadMode()) |
| 684 | { |
| 685 | // Flush old vertex data before loading state. |
| 686 | Flush(); |
| 687 | } |
| 688 | |
| 689 | p.Do(m_zslope); |
| 690 | p.Do(VertexLoaderManager::normal_cache); |
| 691 | p.Do(VertexLoaderManager::tangent_cache); |
| 692 | p.Do(VertexLoaderManager::binormal_cache); |
| 693 | } |
| 694 | |
| 695 | void VertexManagerBase::CalculateZSlope(NativeVertexFormat* format) |
| 696 | { |
| 697 | float out[12]; |
| 698 | float viewOffset[2] = {xfmem.viewport.xOrig - bpmem.scissorOffset.x * 2, |
| 699 | xfmem.viewport.yOrig - bpmem.scissorOffset.y * 2}; |
| 700 | |
| 701 | if (m_current_primitive_type != PrimitiveType::Triangles && |
| 702 | m_current_primitive_type != PrimitiveType::TriangleStrip) |
| 703 | { |
| 704 | return; |
| 705 | } |
| 706 | |
| 707 | // Global matrix ID. |
| 708 | u32 mtxIdx = g_main_cp_state.matrix_index_a.PosNormalMtxIdx; |
| 709 | const PortableVertexDeclaration vert_decl = format->GetVertexDeclaration(); |
| 710 | |
| 711 | // Make sure the buffer contains at least 3 vertices. |
| 712 | if ((m_cur_buffer_pointer - m_base_buffer_pointer) < (vert_decl.stride * 3)) |
| 713 | return; |
| 714 | |
| 715 | // Lookup vertices of the last rendered triangle and software-transform them |
| 716 | // This allows us to determine the depth slope, which will be used if z-freeze |
| 717 | // is enabled in the following flush. |
| 718 | auto& system = Core::System::GetInstance(); |
| 719 | auto& vertex_shader_manager = system.GetVertexShaderManager(); |
| 720 | for (unsigned int i = 0; i < 3; ++i) |
| 721 | { |
| 722 | // If this vertex format has per-vertex position matrix IDs, look it up. |
| 723 | if (vert_decl.posmtx.enable) |
| 724 | mtxIdx = VertexLoaderManager::position_matrix_index_cache[2 - i]; |
| 725 | |
| 726 | if (vert_decl.position.components == 2) |
| 727 | VertexLoaderManager::position_cache[2 - i][2] = 0; |
| 728 | |
| 729 | vertex_shader_manager.TransformToClipSpace(&VertexLoaderManager::position_cache[2 - i][0], |
| 730 | &out[i * 4], mtxIdx); |
| 731 | |
| 732 | // Transform to Screenspace |
| 733 | float inv_w = 1.0f / out[3 + i * 4]; |
| 734 | |
| 735 | out[0 + i * 4] = out[0 + i * 4] * inv_w * xfmem.viewport.wd + viewOffset[0]; |
| 736 | out[1 + i * 4] = out[1 + i * 4] * inv_w * xfmem.viewport.ht + viewOffset[1]; |
| 737 | out[2 + i * 4] = out[2 + i * 4] * inv_w * xfmem.viewport.zRange + xfmem.viewport.farZ; |
| 738 | } |
| 739 | |
| 740 | float dx31 = out[8] - out[0]; |
| 741 | float dx12 = out[0] - out[4]; |
| 742 | float dy12 = out[1] - out[5]; |
| 743 | float dy31 = out[9] - out[1]; |
| 744 | |
| 745 | float DF31 = out[10] - out[2]; |
| 746 | float DF21 = out[6] - out[2]; |
| 747 | float a = DF31 * -dy12 - DF21 * dy31; |
| 748 | float b = dx31 * DF21 + dx12 * DF31; |
| 749 | float c = -dx12 * dy31 - dx31 * -dy12; |
| 750 | |
| 751 | // Sometimes we process de-generate triangles. Stop any divide by zeros |
| 752 | if (c == 0) |
| 753 | return; |
| 754 | |
| 755 | m_zslope.dfdx = -a / c; |
| 756 | m_zslope.dfdy = -b / c; |
| 757 | m_zslope.f0 = out[2] - (out[0] * m_zslope.dfdx + out[1] * m_zslope.dfdy); |
| 758 | m_zslope.dirty = true; |
| 759 | } |
| 760 | |
| 761 | void VertexManagerBase::CalculateNormals(NativeVertexFormat* format) |
| 762 | { |
| 763 | const PortableVertexDeclaration vert_decl = format->GetVertexDeclaration(); |
| 764 | |
| 765 | // Only update the binormal/tangent vertex shader constants if the vertex format lacks binormals |
| 766 | // (VertexLoaderManager::binormal_cache gets updated by the vertex loader when binormals are |
| 767 | // present, though) |
| 768 | if (vert_decl.normals[1].enable) |
| 769 | return; |
| 770 | |
| 771 | VertexLoaderManager::tangent_cache[3] = 0; |
| 772 | VertexLoaderManager::binormal_cache[3] = 0; |
| 773 | |
| 774 | auto& system = Core::System::GetInstance(); |
| 775 | auto& vertex_shader_manager = system.GetVertexShaderManager(); |
| 776 | if (vertex_shader_manager.constants.cached_tangent != VertexLoaderManager::tangent_cache) |
| 777 | { |
| 778 | vertex_shader_manager.constants.cached_tangent = VertexLoaderManager::tangent_cache; |
| 779 | vertex_shader_manager.dirty = true; |
| 780 | } |
| 781 | if (vertex_shader_manager.constants.cached_binormal != VertexLoaderManager::binormal_cache) |
| 782 | { |
| 783 | vertex_shader_manager.constants.cached_binormal = VertexLoaderManager::binormal_cache; |
| 784 | vertex_shader_manager.dirty = true; |
| 785 | } |
| 786 | |
| 787 | if (vert_decl.normals[0].enable) |
| 788 | return; |
| 789 | |
| 790 | VertexLoaderManager::normal_cache[3] = 0; |
| 791 | if (vertex_shader_manager.constants.cached_normal != VertexLoaderManager::normal_cache) |
| 792 | { |
| 793 | vertex_shader_manager.constants.cached_normal = VertexLoaderManager::normal_cache; |
| 794 | vertex_shader_manager.dirty = true; |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | void VertexManagerBase::UpdatePipelineConfig() |
| 799 | { |
| 800 | NativeVertexFormat* vertex_format = VertexLoaderManager::GetCurrentVertexFormat(); |
| 801 | if (vertex_format != m_current_pipeline_config.vertex_format) |
| 802 | { |
| 803 | m_current_pipeline_config.vertex_format = vertex_format; |
| 804 | m_current_uber_pipeline_config.vertex_format = |
| 805 | VertexLoaderManager::GetUberVertexFormat(vertex_format->GetVertexDeclaration()); |
| 806 | m_pipeline_config_changed = true; |
| 807 | } |
| 808 | |
| 809 | VertexShaderUid vs_uid = GetVertexShaderUid(); |
| 810 | if (vs_uid != m_current_pipeline_config.vs_uid) |
| 811 | { |
| 812 | m_current_pipeline_config.vs_uid = vs_uid; |
| 813 | m_current_uber_pipeline_config.vs_uid = UberShader::GetVertexShaderUid(); |
| 814 | m_pipeline_config_changed = true; |
| 815 | } |
| 816 | |
| 817 | PixelShaderUid ps_uid = GetPixelShaderUid(); |
| 818 | if (ps_uid != m_current_pipeline_config.ps_uid) |
| 819 | { |
| 820 | m_current_pipeline_config.ps_uid = ps_uid; |
| 821 | m_current_uber_pipeline_config.ps_uid = UberShader::GetPixelShaderUid(); |
| 822 | m_pipeline_config_changed = true; |
| 823 | } |
| 824 | |
| 825 | GeometryShaderUid gs_uid = GetGeometryShaderUid(GetCurrentPrimitiveType()); |
| 826 | if (gs_uid != m_current_pipeline_config.gs_uid) |
| 827 | { |
| 828 | m_current_pipeline_config.gs_uid = gs_uid; |
| 829 | m_current_uber_pipeline_config.gs_uid = gs_uid; |
| 830 | m_pipeline_config_changed = true; |
| 831 | } |
| 832 | |
| 833 | if (m_rasterization_state_changed) |
| 834 | { |
| 835 | m_rasterization_state_changed = false; |
| 836 | |
| 837 | RasterizationState new_rs = {}; |
| 838 | new_rs.Generate(bpmem, m_current_primitive_type); |
| 839 | if (new_rs != m_current_pipeline_config.rasterization_state) |
| 840 | { |
| 841 | m_current_pipeline_config.rasterization_state = new_rs; |
| 842 | m_current_uber_pipeline_config.rasterization_state = new_rs; |
| 843 | m_pipeline_config_changed = true; |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | if (m_depth_state_changed) |
| 848 | { |
| 849 | m_depth_state_changed = false; |
| 850 | |
| 851 | DepthState new_ds = {}; |
| 852 | new_ds.Generate(bpmem); |
| 853 | if (new_ds != m_current_pipeline_config.depth_state) |
| 854 | { |
| 855 | m_current_pipeline_config.depth_state = new_ds; |
| 856 | m_current_uber_pipeline_config.depth_state = new_ds; |
| 857 | m_pipeline_config_changed = true; |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | if (m_blending_state_changed) |
| 862 | { |
| 863 | m_blending_state_changed = false; |
| 864 | |
| 865 | BlendingState new_bs = {}; |
| 866 | new_bs.Generate(bpmem); |
| 867 | if (new_bs != m_current_pipeline_config.blending_state) |
| 868 | { |
| 869 | m_current_pipeline_config.blending_state = new_bs; |
| 870 | m_current_uber_pipeline_config.blending_state = new_bs; |
| 871 | m_pipeline_config_changed = true; |
| 872 | } |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | void VertexManagerBase::UpdatePipelineObject() |
| 877 | { |
| 878 | if (!m_pipeline_config_changed) |
| 879 | return; |
| 880 | |
| 881 | m_current_pipeline_object = nullptr; |
| 882 | m_pipeline_config_changed = false; |
| 883 | |
| 884 | switch (g_ActiveConfig.iShaderCompilationMode) |
| 885 | { |
| 886 | case ShaderCompilationMode::Synchronous: |
| 887 | { |
| 888 | // Ubershaders disabled? Block and compile the specialized shader. |
| 889 | m_current_pipeline_object = g_shader_cache->GetPipelineForUid(m_current_pipeline_config); |
| 890 | } |
| 891 | break; |
| 892 | |
| 893 | case ShaderCompilationMode::SynchronousUberShaders: |
| 894 | { |
| 895 | // Exclusive ubershader mode, always use ubershaders. |
| 896 | m_current_pipeline_object = |
| 897 | g_shader_cache->GetUberPipelineForUid(m_current_uber_pipeline_config); |
| 898 | } |
| 899 | break; |
| 900 | |
| 901 | case ShaderCompilationMode::AsynchronousUberShaders: |
| 902 | case ShaderCompilationMode::AsynchronousSkipRendering: |
| 903 | { |
| 904 | // Can we background compile shaders? If so, get the pipeline asynchronously. |
| 905 | auto res = g_shader_cache->GetPipelineForUidAsync(m_current_pipeline_config); |
| 906 | if (res) |
| 907 | { |
| 908 | // Specialized shaders are ready, prefer these. |
| 909 | m_current_pipeline_object = *res; |
| 910 | return; |
| 911 | } |
| 912 | |
| 913 | if (g_ActiveConfig.iShaderCompilationMode == ShaderCompilationMode::AsynchronousUberShaders) |
| 914 | { |
| 915 | // Specialized shaders not ready, use the ubershaders. |
| 916 | m_current_pipeline_object = |
| 917 | g_shader_cache->GetUberPipelineForUid(m_current_uber_pipeline_config); |
| 918 | } |
| 919 | else |
| 920 | { |
| 921 | // Ensure we try again next draw. Otherwise, if no registers change between frames, the |
| 922 | // object will never be drawn, even when the shader is ready. |
| 923 | m_pipeline_config_changed = true; |
| 924 | } |
| 925 | } |
| 926 | break; |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | void VertexManagerBase::OnConfigChange() |
| 931 | { |
| 932 | // Reload index generator function tables in case VS expand config changed |
| 933 | m_index_generator.Init(); |
| 934 | } |
| 935 | |
| 936 | void VertexManagerBase::OnDraw() |
| 937 | { |
| 938 | m_draw_counter++; |
| 939 | |
| 940 | // If the last efb copy was too close to the one before it, don't forget about it until the next |
| 941 | // efb copy happens (which might not be for a long time) |
| 942 | u32 diff = m_draw_counter - m_last_efb_copy_draw_counter; |
| 943 | if (m_unflushed_efb_copy && diff > MINIMUM_DRAW_CALLS_PER_COMMAND_BUFFER_FOR_READBACK) |
| 944 | { |
| 945 | g_gfx->Flush(); |
| 946 | m_unflushed_efb_copy = false; |
| 947 | m_last_efb_copy_draw_counter = m_draw_counter; |
| 948 | } |
| 949 | |
| 950 | // If we didn't have any CPU access last frame, do nothing. |
| 951 | if (m_scheduled_command_buffer_kicks.empty() || !m_allow_background_execution) |
| 952 | return; |
| 953 | |
| 954 | // Check if this draw is scheduled to kick a command buffer. |
| 955 | // The draw counters will always be sorted so a binary search is possible here. |
| 956 | if (std::ranges::binary_search(m_scheduled_command_buffer_kicks, m_draw_counter)) |
| 957 | { |
| 958 | // Kick a command buffer on the background thread. |
| 959 | g_gfx->Flush(); |
| 960 | m_unflushed_efb_copy = false; |
| 961 | m_last_efb_copy_draw_counter = m_draw_counter; |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | void VertexManagerBase::OnCPUEFBAccess() |
| 966 | { |
| 967 | // Check this isn't another access without any draws in between. |
| 968 | if (!m_cpu_accesses_this_frame.empty() && m_cpu_accesses_this_frame.back() == m_draw_counter) |
| 969 | return; |
| 970 | |
| 971 | // Store the current draw counter for scheduling in OnEndFrame. |
| 972 | m_cpu_accesses_this_frame.emplace_back(m_draw_counter); |
| 973 | } |
| 974 | |
| 975 | void VertexManagerBase::OnEFBCopyToRAM() |
| 976 | { |
| 977 | // If we're not deferring, try to preempt it next frame. |
| 978 | if (!g_ActiveConfig.bDeferEFBCopies) |
| 979 | { |
| 980 | OnCPUEFBAccess(); |
| 981 | return; |
| 982 | } |
| 983 | |
| 984 | // Otherwise, only execute if we have at least 10 objects between us and the last copy. |
| 985 | const u32 diff = m_draw_counter - m_last_efb_copy_draw_counter; |
| 986 | m_last_efb_copy_draw_counter = m_draw_counter; |
| 987 | if (diff < MINIMUM_DRAW_CALLS_PER_COMMAND_BUFFER_FOR_READBACK) |
| 988 | { |
| 989 | m_unflushed_efb_copy = true; |
| 990 | return; |
| 991 | } |
| 992 | |
| 993 | m_unflushed_efb_copy = false; |
| 994 | g_gfx->Flush(); |
| 995 | } |
| 996 | |
| 997 | void VertexManagerBase::OnEndFrame() |
| 998 | { |
| 999 | m_draw_counter = 0; |
| 1000 | m_last_efb_copy_draw_counter = 0; |
| 1001 | m_scheduled_command_buffer_kicks.clear(); |
| 1002 | |
| 1003 | // If we have no CPU access at all, leave everything in the one command buffer for maximum |
| 1004 | // parallelism between CPU/GPU, at the cost of slightly higher latency. |
| 1005 | if (m_cpu_accesses_this_frame.empty()) |
| 1006 | return; |
| 1007 | |
| 1008 | // In order to reduce CPU readback latency, we want to kick a command buffer roughly halfway |
| 1009 | // between the draw counters that invoked the readback, or every 250 draws, whichever is |
| 1010 | // smaller. |
| 1011 | if (g_ActiveConfig.iCommandBufferExecuteInterval > 0) |
| 1012 | { |
| 1013 | u32 last_draw_counter = 0; |
| 1014 | u32 interval = static_cast<u32>(g_ActiveConfig.iCommandBufferExecuteInterval); |
| 1015 | for (u32 draw_counter : m_cpu_accesses_this_frame) |
| 1016 | { |
| 1017 | // We don't want to waste executing command buffers for only a few draws, so set a minimum. |
| 1018 | // Leave last_draw_counter as-is, so we get the correct number of draws between submissions. |
| 1019 | u32 draw_count = draw_counter - last_draw_counter; |
| 1020 | if (draw_count < MINIMUM_DRAW_CALLS_PER_COMMAND_BUFFER_FOR_READBACK) |
| 1021 | continue; |
| 1022 | |
| 1023 | if (draw_count <= interval) |
| 1024 | { |
| 1025 | u32 mid_point = draw_count / 2; |
| 1026 | m_scheduled_command_buffer_kicks.emplace_back(last_draw_counter + mid_point); |
| 1027 | } |
| 1028 | else |
| 1029 | { |
| 1030 | u32 counter = interval; |
| 1031 | while (counter < draw_count) |
| 1032 | { |
| 1033 | m_scheduled_command_buffer_kicks.emplace_back(last_draw_counter + counter); |
| 1034 | counter += interval; |
| 1035 | } |
| 1036 | } |
| 1037 | |
| 1038 | last_draw_counter = draw_counter; |
| 1039 | } |
| 1040 | } |
| 1041 | |
| 1042 | m_cpu_accesses_this_frame.clear(); |
| 1043 | |
| 1044 | // We invalidate the pipeline object at the start of the frame. |
| 1045 | // This is for the rare case where only a single pipeline configuration is used, |
| 1046 | // and hybrid ubershaders have compiled the specialized shader, but without any |
| 1047 | // state changes the specialized shader will not take over. |
| 1048 | InvalidatePipelineObject(); |
| 1049 | } |
| 1050 | |
| 1051 | void VertexManagerBase::NotifyCustomShaderCacheOfHostChange(const ShaderHostConfig& host_config) |
| 1052 | { |
| 1053 | m_custom_shader_cache->SetHostConfig(host_config); |
| 1054 | m_custom_shader_cache->Reload(); |
| 1055 | } |
| 1056 | |
| 1057 | void VertexManagerBase::RenderDrawCall( |
| 1058 | PixelShaderManager& pixel_shader_manager, GeometryShaderManager& geometry_shader_manager, |
| 1059 | const CustomPixelShaderContents& custom_pixel_shader_contents, |
| 1060 | std::span<u8> custom_pixel_shader_uniforms, PrimitiveType primitive_type, |
| 1061 | const AbstractPipeline* current_pipeline) |
| 1062 | { |
| 1063 | // Now we can upload uniforms, as nothing else will override them. |
| 1064 | geometry_shader_manager.SetConstants(primitive_type); |
| 1065 | pixel_shader_manager.SetConstants(); |
| 1066 | if (!custom_pixel_shader_uniforms.empty() && |
| 1067 | pixel_shader_manager.custom_constants.data() != custom_pixel_shader_uniforms.data()) |
| 1068 | { |
| 1069 | pixel_shader_manager.custom_constants_dirty = true; |
| 1070 | } |
| 1071 | pixel_shader_manager.custom_constants = custom_pixel_shader_uniforms; |
| 1072 | UploadUniforms(); |
| 1073 | |
| 1074 | g_gfx->SetPipeline(current_pipeline); |
| 1075 | |
| 1076 | u32 base_vertex, base_index; |
| 1077 | CommitBuffer(m_index_generator.GetNumVerts(), |
| 1078 | VertexLoaderManager::GetCurrentVertexFormat()->GetVertexStride(), |
| 1079 | m_index_generator.GetIndexLen(), &base_vertex, &base_index); |
| 1080 | |
| 1081 | if (g_backend_info.api_type != APIType::D3D && g_ActiveConfig.UseVSForLinePointExpand() && |
| 1082 | (primitive_type == PrimitiveType::Points || primitive_type == PrimitiveType::Lines)) |
| 1083 | { |
| 1084 | // VS point/line expansion puts the vertex id at gl_VertexID << 2 |
| 1085 | // That means the base vertex has to be adjusted to match |
| 1086 | // (The shader adds this after shifting right on D3D, so no need to do this) |
| 1087 | base_vertex <<= 2; |
| 1088 | } |
| 1089 | |
| 1090 | if (PerfQueryBase::ShouldEmulate()) |
| 1091 | g_perf_query->EnableQuery(bpmem.zcontrol.early_ztest ? PQG_ZCOMP_ZCOMPLOC : PQG_ZCOMP); |
| 1092 | |
| 1093 | DrawCurrentBatch(base_index, m_index_generator.GetIndexLen(), base_vertex); |
| 1094 | |
| 1095 | // Track the total emulated state draws |
| 1096 | INCSTAT(g_stats.this_frame.num_draw_calls); |
| 1097 | |
| 1098 | if (PerfQueryBase::ShouldEmulate()) |
| 1099 | g_perf_query->DisableQuery(bpmem.zcontrol.early_ztest ? PQG_ZCOMP_ZCOMPLOC : PQG_ZCOMP); |
| 1100 | } |
| 1101 | |
| 1102 | const AbstractPipeline* VertexManagerBase::GetCustomPipeline( |
| 1103 | const CustomPixelShaderContents& custom_pixel_shader_contents, |
| 1104 | const VideoCommon::GXPipelineUid& current_pipeline_config, |
| 1105 | const VideoCommon::GXUberPipelineUid& current_uber_pipeline_config, |
| 1106 | const AbstractPipeline* current_pipeline) const |
| 1107 | { |
| 1108 | if (current_pipeline) |
| 1109 | { |
| 1110 | if (!custom_pixel_shader_contents.shaders.empty()) |
| 1111 | { |
| 1112 | CustomShaderInstance custom_shaders; |
| 1113 | custom_shaders.pixel_contents = custom_pixel_shader_contents; |
| 1114 | switch (g_ActiveConfig.iShaderCompilationMode) |
| 1115 | { |
| 1116 | case ShaderCompilationMode::Synchronous: |
| 1117 | case ShaderCompilationMode::AsynchronousSkipRendering: |
| 1118 | { |
| 1119 | if (auto pipeline = m_custom_shader_cache->GetPipelineAsync( |
| 1120 | current_pipeline_config, custom_shaders, current_pipeline->m_config)) |
| 1121 | { |
| 1122 | return *pipeline; |
| 1123 | } |
| 1124 | } |
| 1125 | break; |
| 1126 | case ShaderCompilationMode::SynchronousUberShaders: |
| 1127 | { |
| 1128 | // D3D has issues compiling large custom ubershaders |
| 1129 | // use specialized shaders instead |
| 1130 | if (g_backend_info.api_type == APIType::D3D) |
| 1131 | { |
| 1132 | if (auto pipeline = m_custom_shader_cache->GetPipelineAsync( |
| 1133 | current_pipeline_config, custom_shaders, current_pipeline->m_config)) |
| 1134 | { |
| 1135 | return *pipeline; |
| 1136 | } |
| 1137 | } |
| 1138 | else |
| 1139 | { |
| 1140 | if (auto pipeline = m_custom_shader_cache->GetPipelineAsync( |
| 1141 | current_uber_pipeline_config, custom_shaders, current_pipeline->m_config)) |
| 1142 | { |
| 1143 | return *pipeline; |
| 1144 | } |
| 1145 | } |
| 1146 | } |
| 1147 | break; |
| 1148 | case ShaderCompilationMode::AsynchronousUberShaders: |
| 1149 | { |
| 1150 | if (auto pipeline = m_custom_shader_cache->GetPipelineAsync( |
| 1151 | current_pipeline_config, custom_shaders, current_pipeline->m_config)) |
| 1152 | { |
| 1153 | return *pipeline; |
| 1154 | } |
| 1155 | else if (auto uber_pipeline = m_custom_shader_cache->GetPipelineAsync( |
| 1156 | current_uber_pipeline_config, custom_shaders, current_pipeline->m_config)) |
| 1157 | { |
| 1158 | return *uber_pipeline; |
| 1159 | } |
| 1160 | } |
| 1161 | break; |
| 1162 | }; |
| 1163 | } |
| 1164 | } |
| 1165 | |
| 1166 | return nullptr; |
| 1167 | } |