Debian Codegraph @

Sources/nCine/Graphics/RHI/RSX/RsxDevice.cpp

raw
1 #if defined(WITH_RHI_RSX)
2
3 #include "RsxDevice.h"
4 #include "RsxRenderTarget.h"
5 #include "RsxTexture.h"
6 #include "RsxShaderProgram.h"
7 #include "RsxBufferObject.h"
8 #include "../../Material.h"
9
10 #include "../../../../Main.h"
11 #include "../../../../Shaders/Generated/RsxGeneratedShaders.h"
12
13 #include <cstring>
14 #include <malloc.h>
15 #include <unistd.h>
16
17 #include <rsx/rsx.h>
18 #include <rsx/commands.h>
19 #include <sysutil/video.h>
20
21 namespace nCine::RHI::RSX
22 {
23 namespace
24 {
25 /**
26 @brief Size of the command FIFO
27
28 Far larger than the 512 KB the SDK's samples reserve, because a frame of this game emits far more
29 than they do: a batched draw writes its whole instance array as constant registers, which is tens
30 of words per sprite. The ring still wraps within a frame at this size - that is what the flush in
31 DrawCommon() is for - but a bigger ring means the GPU has more slack before the write pointer
32 catches up with it.
33 */
34 constexpr std::uint32_t CommandBufferSize = 4 * 1024 * 1024;
35 /**
36 @brief Host region mapped into the GPU's IO window
37
38 Everything the PPE writes and the GPU reads comes out of here - the streamed vertex and index
39 buffers, the uniform staging - so it is sized for the pipeline's ring buffers with room to spare.
40 The console has 256 MB of XDR, so 16 is not a meaningful cost.
41 */
42 constexpr std::uint32_t HostMemorySize = 16 * 1024 * 1024;
43
44 /** @brief Label index used to wait for the GPU to drain (255 is the one the SDK's samples reserve) */
45 constexpr std::uint8_t FinishLabelIndex = 255;
46 std::uint32_t _finishLabelValue = 1;
47
48 /**
49 @brief Display modes tried in order of preference
50
51 720p first: it is the mode the game's logical resolution upscales into most cleanly and the one
52 virtually every display attached to a PS3 accepts. The standard-definition modes follow for a CRT,
53 and 960x1080 is last because it is an unusual anamorphic mode that only some displays report.
54 */
55 constexpr std::uint32_t PreferredResolutions[] = {
56 VIDEO_RESOLUTION_720,
57 VIDEO_RESOLUTION_480,
58 VIDEO_RESOLUTION_576,
59 VIDEO_RESOLUTION_960x1080
60 };
61
62 std::uint16_t TranslateBlendFactor(nCine::BlendingFactor factor)
63 {
64 switch (factor) {
65 case nCine::BlendingFactor::Zero: return GCM_ZERO;
66 case nCine::BlendingFactor::One: return GCM_ONE;
67 case nCine::BlendingFactor::SrcColor: return GCM_SRC_COLOR;
68 case nCine::BlendingFactor::OneMinusSrcColor: return GCM_ONE_MINUS_SRC_COLOR;
69 case nCine::BlendingFactor::SrcAlpha: return GCM_SRC_ALPHA;
70 case nCine::BlendingFactor::OneMinusSrcAlpha: return GCM_ONE_MINUS_SRC_ALPHA;
71 case nCine::BlendingFactor::DstAlpha: return GCM_DST_ALPHA;
72 case nCine::BlendingFactor::OneMinusDstAlpha: return GCM_ONE_MINUS_DST_ALPHA;
73 case nCine::BlendingFactor::DstColor: return GCM_DST_COLOR;
74 case nCine::BlendingFactor::OneMinusDstColor: return GCM_ONE_MINUS_DST_COLOR;
75 case nCine::BlendingFactor::SrcAlphaSaturate: return GCM_SRC_ALPHA_SATURATE;
76 case nCine::BlendingFactor::ConstantColor: return GCM_CONSTANT_COLOR;
77 case nCine::BlendingFactor::OneMinusConstantColor: return GCM_ONE_MINUS_CONSTANT_COLOR;
78 case nCine::BlendingFactor::ConstantAlpha: return GCM_CONSTANT_ALPHA;
79 case nCine::BlendingFactor::OneMinusConstantAlpha: return GCM_ONE_MINUS_CONSTANT_ALPHA;
80 default: return GCM_ONE;
81 }
82 }
83
84 std::uint32_t TranslatePrimitive(PrimitiveType primitive)
85 {
86 switch (primitive) {
87 case PrimitiveType::Points: return GCM_TYPE_POINTS;
88 case PrimitiveType::Lines: return GCM_TYPE_LINES;
89 case PrimitiveType::LineLoop: return GCM_TYPE_LINE_LOOP;
90 case PrimitiveType::LineStrip: return GCM_TYPE_LINE_STRIP;
91 case PrimitiveType::Triangles: return GCM_TYPE_TRIANGLES;
92 case PrimitiveType::TriangleStrip: return GCM_TYPE_TRIANGLE_STRIP;
93 case PrimitiveType::TriangleFan: return GCM_TYPE_TRIANGLE_FAN;
94 default: return GCM_TYPE_TRIANGLES;
95 }
96 }
97
98 /** @brief Packs a colour into the ARGB word `rsxSetClearColor()` takes */
99 std::uint32_t PackClearColor(const Colorf& color)
100 {
101 const auto clamp = [](float v) -> std::uint32_t {
102 const float scaled = v * 255.0f;
103 return std::uint32_t(scaled < 0.0f ? 0.0f : (scaled > 255.0f ? 255.0f : scaled));
104 };
105 return (clamp(color.A) << 24) | (clamp(color.R) << 16) | (clamp(color.G) << 8) | clamp(color.B);
106 }
107 }
108
109 RsxDevice::BlendingState RsxDevice::_blending;
110 RsxDevice::DepthTestState RsxDevice::_depthTest;
111 RsxDevice::CullFaceState RsxDevice::_cullFace;
112 RsxDevice::ScissorState RsxDevice::_scissor;
113 Recti RsxDevice::_viewport;
114 Colorf RsxDevice::_clearColor(0.0f, 0.0f, 0.0f, 1.0f);
115
116 RsxShaderProgram* RsxDevice::_currentProgram = nullptr;
117 const RsxTexture* RsxDevice::_boundTextures[RsxDevice::MaxTextureUnits] = {};
118 RsxDevice::UniformRange RsxDevice::_boundUniformRanges[RsxDevice::MaxUniformBindings] = {};
119 RsxRenderTarget* RsxDevice::_currentRenderTarget = nullptr;
120
121 gcmContextData* RsxDevice::_context = nullptr;
122 void* RsxDevice::_hostMemory = nullptr;
123
124 std::int32_t RsxDevice::_displayWidth = 0;
125 std::int32_t RsxDevice::_displayHeight = 0;
126 RsxVram::Block RsxDevice::_displayBuffers[RsxDevice::DisplayBufferCount];
127 std::uint32_t RsxDevice::_displayPitch = 0;
128 std::uint32_t RsxDevice::_backBufferIndex = 0;
129
130 RsxVram::Block RsxDevice::_screenBuffer;
131 std::uint32_t RsxDevice::_screenPitch = 0;
132 gcmTexture RsxDevice::_screenTexture;
133
134 RsxVram::Block RsxDevice::_depthBuffer;
135 std::uint32_t RsxDevice::_depthPitch = 0;
136
137 bool RsxDevice::_initialized = false;
138 bool RsxDevice::_vsync = true;
139 bool RsxDevice::_firstFlip = true;
140 std::uint32_t RsxDevice::_frameCounter = 0;
141 bool RsxDevice::_surfaceDirty = true;
142 const rsxVertexProgram* RsxDevice::_lastVertexProgram = nullptr;
143 const void* RsxDevice::_lastVertexUcode = nullptr;
144 const rsxFragmentProgram* RsxDevice::_lastFragmentProgram = nullptr;
145 std::uint32_t RsxDevice::_lastFragmentUcodeOffset = 0;
146 std::uint32_t RsxDevice::_boundAttributeRegisters = 0;
147
148 RsxDevice::RetiredBlock RsxDevice::_retiredBlocks[RsxDevice::RetiredBlockCount];
149
150 const rsxVertexProgram* RsxDevice::_presentVertexProgram = nullptr;
151 const rsxFragmentProgram* RsxDevice::_presentFragmentProgram = nullptr;
152 const void* RsxDevice::_presentVertexUcode = nullptr;
153 RsxVram::Block RsxDevice::_presentFragmentUcode;
154 RsxVram::Block RsxDevice::_presentVertices;
155
156 RsxVram::Block RsxDevice::_quadCornerStream;
157 RsxVram::Block RsxDevice::_batchedCornerStream;
158 // -- Session lifecycle ------------------------------------------------------------------------
159
160 bool RsxDevice::ConfigureVideo()
161 {
162 // The console is attached to whatever display the user owns, so the mode is negotiated rather than
163 // assumed: the first entry of the preference list the display accepts wins
164 videoResolution resolution;
165 std::uint32_t chosenId = 0;
166 for (std::uint32_t id : PreferredResolutions) {
167 if (videoGetResolutionAvailability(VIDEO_PRIMARY, id, VIDEO_ASPECT_AUTO, 0) != 1) {
168 continue;
169 }
170 if (videoGetResolution(id, &resolution) == 0) {
171 chosenId = id;
172 break;
173 }
174 }
175 if (chosenId == 0) {
176 LOGE("No usable video mode was reported by the display");
177 return false;
178 }
179
180 _displayWidth = std::int32_t(resolution.width);
181 _displayHeight = std::int32_t(resolution.height);
182
183 videoConfiguration config;
184 std::memset(&config, 0, sizeof(config));
185 config.resolution = std::uint8_t(chosenId);
186 // XRGB rather than ARGB: the scan-out ignores alpha, and asking for a format the display controller
187 // has to interpret differently from what the GPU wrote would only cost a conversion
188 config.format = VIDEO_BUFFER_FORMAT_XRGB;
189 config.aspect = VIDEO_ASPECT_AUTO;
190 config.pitch = std::uint32_t(_displayWidth) * 4;
191
192 if (videoConfigure(VIDEO_PRIMARY, &config, nullptr, 0) != 0) {
193 LOGE("Cannot configure the video output for {}x{}", _displayWidth, _displayHeight);
194 return false;
195 }
196
197 LOGI("Negotiated video mode: {}x{}", _displayWidth, _displayHeight);
198 return true;
199 }
200
201 bool RsxDevice::CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync)
202 {
203 static_cast<void>(windowHandle);
204 static_cast<void>(width);
205 static_cast<void>(height);
206
207 if (_initialized) {
208 return true;
209 }
210 _vsync = vsync;
211
212 // The IO region has to be page-aligned for the mapping the lv2 side performs, and it is handed to
213 // rsxInit() rather than allocated by it - which is also what makes it addressable by the PPE
214 _hostMemory = ::memalign(1024 * 1024, HostMemorySize);
215 if (_hostMemory == nullptr) {
216 LOGE("Cannot reserve {} MB of host memory for the RSX IO window", HostMemorySize / (1024 * 1024));
217 return false;
218 }
219
220 if (rsxInit(&_context, CommandBufferSize, HostMemorySize, _hostMemory) != 0 || _context == nullptr) {
221 LOGE("Cannot initialize the RSX command context");
222 ::free(_hostMemory);
223 _hostMemory = nullptr;
224 return false;
225 }
226
227 if (!ConfigureVideo()) {
228 DestroySwapchain();
229 return false;
230 }
231
232 // The command FIFO is carved out of the FRONT of the region handed to rsxInit() - that is libgcm's
233 // contract - so the suballocator must start behind it. Handing out the whole region instead lets the
234 // first vertex buffer land on top of the FIFO, which the GPU then reads as garbage commands: RPCS3
235 // reports it as "Dead FIFO commands queue state has been detected" once the first frame is submitted.
236 std::uint8_t* heapBase = static_cast<std::uint8_t*>(_hostMemory) + CommandBufferSize;
237 if (!RsxVram::Initialize(heapBase, HostMemorySize - CommandBufferSize)) {
238 DestroySwapchain();
239 return false;
240 }
241
242 gcmSetFlipMode(_vsync ? GCM_FLIP_VSYNC : GCM_FLIP_HSYNC);
243
244 // Display buffers the scan-out cycles between, and the intermediate screen surface the frame is
245 // actually drawn into (bottom-up, see the class documentation)
246 for (std::uint32_t i = 0; i < DisplayBufferCount; i++) {
247 _displayBuffers[i] = RsxVram::AllocSurface(std::uint32_t(_displayWidth), std::uint32_t(_displayHeight), 4, _displayPitch);
248 if (!_displayBuffers[i].IsValid()) {
249 LOGE("Cannot allocate display buffer {}", i);
250 DestroySwapchain();
251 return false;
252 }
253 gcmSetDisplayBuffer(std::uint8_t(i), _displayBuffers[i].Offset, _displayPitch,
254 std::uint32_t(_displayWidth), std::uint32_t(_displayHeight));
255 }
256
257 _screenBuffer = RsxVram::AllocSurface(std::uint32_t(_displayWidth), std::uint32_t(_displayHeight), 4, _screenPitch);
258 if (!_screenBuffer.IsValid()) {
259 LOGE("Cannot allocate the intermediate screen surface");
260 DestroySwapchain();
261 return false;
262 }
263
264 // One depth surface, shared by the screen and every render target (see RsxRenderTarget). Z24S8 even
265 // though nothing here uses stencil: the 16-bit format would halve the memory but costs precision the
266 // layer ordering depends on, and 5 MB is nothing against 256.
267 _depthBuffer = RsxVram::AllocSurface(std::uint32_t(_displayWidth), std::uint32_t(_displayHeight), 4, _depthPitch);
268 if (!_depthBuffer.IsValid()) {
269 LOGE("Cannot allocate the depth surface");
270 DestroySwapchain();
271 return false;
272 }
273
274 // The screen surface is sampled by the present shader, so it also needs a texture description
275 std::memset(&_screenTexture, 0, sizeof(_screenTexture));
276 _screenTexture.format = (GCM_TEXTURE_FORMAT_A8R8G8B8 | GCM_TEXTURE_FORMAT_LIN);
277 _screenTexture.mipmap = 1;
278 _screenTexture.dimension = GCM_TEXTURE_DIMS_2D;
279 _screenTexture.cubemap = GCM_FALSE;
280 _screenTexture.remap = ((GCM_TEXTURE_REMAP_TYPE_REMAP << GCM_TEXTURE_REMAP_TYPE_A_SHIFT) |
281 (GCM_TEXTURE_REMAP_TYPE_REMAP << GCM_TEXTURE_REMAP_TYPE_R_SHIFT) |
282 (GCM_TEXTURE_REMAP_TYPE_REMAP << GCM_TEXTURE_REMAP_TYPE_G_SHIFT) |
283 (GCM_TEXTURE_REMAP_TYPE_REMAP << GCM_TEXTURE_REMAP_TYPE_B_SHIFT) |
284 (GCM_TEXTURE_REMAP_COLOR_A << GCM_TEXTURE_REMAP_COLOR_A_SHIFT) |
285 (GCM_TEXTURE_REMAP_COLOR_R << GCM_TEXTURE_REMAP_COLOR_R_SHIFT) |
286 (GCM_TEXTURE_REMAP_COLOR_G << GCM_TEXTURE_REMAP_COLOR_G_SHIFT) |
287 (GCM_TEXTURE_REMAP_COLOR_B << GCM_TEXTURE_REMAP_COLOR_B_SHIFT));
288 _screenTexture.width = std::uint16_t(_displayWidth);
289 _screenTexture.height = std::uint16_t(_displayHeight);
290 _screenTexture.depth = 1;
291 _screenTexture.location = _screenBuffer.GetGcmLocation();
292 _screenTexture.pitch = _screenPitch;
293 _screenTexture.offset = _screenBuffer.Offset;
294
295 if (!CreateBuiltinResources() || !CreatePresentShader()) {
296 DestroySwapchain();
297 return false;
298 }
299
300 _initialized = true;
301 _firstFlip = true;
302 _backBufferIndex = 0;
303 _surfaceDirty = true;
304 _viewport = Recti(0, 0, _displayWidth, _displayHeight);
305
306 SetupInitialState();
307 return true;
308 }
309
310 void RsxDevice::DestroySwapchain()
311 {
312 if (_context != nullptr) {
313 Finish();
314 }
315
316 ReleaseRetiredBlocks(true);
317 RsxVram::Free(_presentVertices);
318 RsxVram::Free(_presentFragmentUcode);
319 RsxVram::Free(_quadCornerStream);
320 RsxVram::Free(_batchedCornerStream);
321 RsxVram::Free(_depthBuffer);
322 RsxVram::Free(_screenBuffer);
323 for (std::uint32_t i = 0; i < DisplayBufferCount; i++) {
324 RsxVram::Free(_displayBuffers[i]);
325 }
326 RsxVram::Shutdown();
327
328 if (_hostMemory != nullptr) {
329 ::free(_hostMemory);
330 _hostMemory = nullptr;
331 }
332 _context = nullptr;
333 _initialized = false;
334 _currentProgram = nullptr;
335 _currentRenderTarget = nullptr;
336 }
337
338 void RsxDevice::ResizeSwapchain(std::int32_t width, std::int32_t height)
339 {
340 static_cast<void>(width);
341 static_cast<void>(height);
342 }
343
344 gcmContextData* RsxDevice::GetContext()
345 {
346 return _context;
347 }
348
349 std::int32_t RsxDevice::GetDisplayWidth()
350 {
351 return _displayWidth;
352 }
353
354 std::int32_t RsxDevice::GetDisplayHeight()
355 {
356 return _displayHeight;
357 }
358
359 std::uint32_t RsxDevice::GetFrameCounter()
360 {
361 return _frameCounter;
362 }
363
364 void RsxDevice::Finish()
365 {
366 if (_context == nullptr) {
367 return;
368 }
369 // Writes a label the GPU only reaches once it has consumed everything before it, then spins on the
370 // label's memory. The sleep keeps the PPE off the bus while it waits, which matters because the GPU
371 // is reading through it.
372 rsxSetWriteBackendLabel(_context, FinishLabelIndex, _finishLabelValue);
373 rsxFlushBuffer(_context);
374 while (*reinterpret_cast<volatile std::uint32_t*>(gcmGetLabelAddress(FinishLabelIndex)) != _finishLabelValue) {
375 ::usleep(30);
376 }
377 _finishLabelValue++;
378 }
379
380 void RsxDevice::RetireBlock(RsxVram::Block& block)
381 {
382 if (!block.IsValid()) {
383 return;
384 }
385 for (std::uint32_t i = 0; i < RetiredBlockCount; i++) {
386 if (!_retiredBlocks[i].Block.IsValid()) {
387 _retiredBlocks[i].Block = block;
388 _retiredBlocks[i].RetiredAtFrame = _frameCounter;
389 block.Base = nullptr;
390 block.Offset = 0;
391 block.Size = 0;
392 return;
393 }
394 }
395 // The list is full, which means more resources were destroyed within the retirement window than it
396 // was sized for. Waiting is correct rather than convenient: freeing memory the GPU is still reading
397 // from is what the delay exists to prevent, so the only safe way to reclaim a slot is to make the
398 // wait real first.
399 Finish();
400 ReleaseRetiredBlocks(true);
401 _retiredBlocks[0].Block = block;
402 _retiredBlocks[0].RetiredAtFrame = _frameCounter;
403 block.Base = nullptr;
404 block.Offset = 0;
405 block.Size = 0;
406 }
407
408 void RsxDevice::ReleaseRetiredBlocks(bool force)
409 {
410 for (std::uint32_t i = 0; i < RetiredBlockCount; i++) {
411 RetiredBlock& retired = _retiredBlocks[i];
412 if (!retired.Block.IsValid()) {
413 continue;
414 }
415 // Presenting queues a frame rather than completing it, so a block is only safe to reuse once the
416 // GPU is demonstrably past the frame that last referenced it
417 if (!force && _frameCounter - retired.RetiredAtFrame < RetiredBlockFrameDelay) {
418 continue;
419 }
420 RsxVram::Free(retired.Block);
421 }
422 }
423
424 // -- State ------------------------------------------------------------------------------------
425
426 void RsxDevice::SetupInitialState()
427 {
428 if (_context == nullptr) {
429 return;
430 }
431
432 // These program the hardware directly, so the caches that guard the setters have to be put back to
433 // what is about to be written - otherwise a device that comes back up after the pipeline has already
434 // touched this state keeps stale entries and silently drops the first request to change each of them
435 _blending = BlendingState{};
436 _depthTest = DepthTestState{};
437 _cullFace = CullFaceState{};
438
439 // The engine is a 2D renderer: nothing is culled (which one of a sprite's two triangles faces the
440 // camera follows from the winding the bottom-up viewport transform gives it, not from anything the
441 // pipeline controls), and the alpha test is unused because blending covers every case.
442 rsxSetCullFaceEnable(_context, GCM_FALSE);
443 rsxSetAlphaTestEnable(_context, GCM_FALSE);
444 rsxSetDepthTestEnable(_context, GCM_FALSE);
445 rsxSetDepthWriteEnable(_context, GCM_TRUE);
446 rsxSetDepthFunc(_context, GCM_LEQUAL);
447 rsxSetBlendEnable(_context, GCM_FALSE);
448 rsxSetBlendEquation(_context, GCM_FUNC_ADD, GCM_FUNC_ADD);
449 // The factors have to be programmed too, not just the equation: `_blending` starts out claiming
450 // One/Zero, so without this the hardware keeps whatever it powered up with and the first material
451 // that genuinely asks for One/Zero is skipped by the setter's early-out
452 rsxSetBlendFunc(_context, GCM_ONE, GCM_ZERO, GCM_ONE, GCM_ZERO);
453 rsxSetColorMask(_context, GCM_COLOR_MASK_R | GCM_COLOR_MASK_G | GCM_COLOR_MASK_B | GCM_COLOR_MASK_A);
454 rsxSetShadeModel(_context, GCM_SHADE_MODEL_SMOOTH);
455 rsxSetFrontFace(_context, GCM_FRONTFACE_CCW);
456 }
457
458 void RsxDevice::SetBlendingEnabled(bool enabled)
459 {
460 if (_blending.Enabled == enabled) {
461 return;
462 }
463 _blending.Enabled = enabled;
464 if (_context != nullptr) {
465 rsxSetBlendEnable(_context, enabled ? GCM_TRUE : GCM_FALSE);
466 }
467 }
468
469 void RsxDevice::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha)
470 {
471
472 if (_blending.SrcRgb == srcRgb && _blending.DstRgb == dstRgb &&
473 _blending.SrcAlpha == srcAlpha && _blending.DstAlpha == dstAlpha) {
474 return;
475 }
476 _blending.SrcRgb = srcRgb;
477 _blending.DstRgb = dstRgb;
478 _blending.SrcAlpha = srcAlpha;
479 _blending.DstAlpha = dstAlpha;
480 if (_context != nullptr) {
481 rsxSetBlendFunc(_context, TranslateBlendFactor(srcRgb), TranslateBlendFactor(dstRgb),
482 TranslateBlendFactor(srcAlpha), TranslateBlendFactor(dstAlpha));
483 }
484 }
485
486 RsxDevice::BlendingState RsxDevice::GetBlendingState()
487 {
488 return _blending;
489 }
490
491 void RsxDevice::SetBlendingState(const BlendingState& state)
492 {
493 SetBlendingEnabled(state.Enabled);
494 SetBlendingFactors(state.SrcRgb, state.DstRgb, state.SrcAlpha, state.DstAlpha);
495 }
496
497 void RsxDevice::SetDepthTestEnabled(bool enabled)
498 {
499 if (_depthTest.TestEnabled == enabled) {
500 return;
501 }
502 _depthTest.TestEnabled = enabled;
503 if (_context != nullptr) {
504 rsxSetDepthTestEnable(_context, enabled ? GCM_TRUE : GCM_FALSE);
505 }
506 }
507
508 void RsxDevice::SetDepthMaskEnabled(bool enabled)
509 {
510 if (_depthTest.MaskEnabled == enabled) {
511 return;
512 }
513 _depthTest.MaskEnabled = enabled;
514 if (_context != nullptr) {
515 rsxSetDepthWriteEnable(_context, enabled ? GCM_TRUE : GCM_FALSE);
516 }
517 }
518
519 RsxDevice::DepthTestState RsxDevice::GetDepthTestState()
520 {
521 return _depthTest;
522 }
523
524 void RsxDevice::SetDepthTestState(const DepthTestState& state)
525 {
526 SetDepthTestEnabled(state.TestEnabled);
527 SetDepthMaskEnabled(state.MaskEnabled);
528 }
529
530 void RsxDevice::SetCullFaceEnabled(bool enabled)
531 {
532 if (_cullFace.Enabled == enabled) {
533 return;
534 }
535 _cullFace.Enabled = enabled;
536 if (_context != nullptr) {
537 rsxSetCullFaceEnable(_context, enabled ? GCM_TRUE : GCM_FALSE);
538 }
539 }
540
541 RsxDevice::CullFaceState RsxDevice::GetCullFaceState()
542 {
543 return _cullFace;
544 }
545
546 void RsxDevice::SetCullFaceState(const CullFaceState& state)
547 {
548 SetCullFaceEnabled(state.Enabled);
549 if (_cullFace.Mode != state.Mode) {
550 _cullFace.Mode = state.Mode;
551 if (_context != nullptr) {
552 rsxSetCullFace(_context, state.Mode == CullFaceMode::Front ? GCM_CULL_FRONT : GCM_CULL_BACK);
553 }
554 }
555 }
556
557 RsxDevice::ScissorState RsxDevice::GetScissorState()
558 {
559 return _scissor;
560 }
561
562 void RsxDevice::SetScissorState(const ScissorState& state)
563 {
564 _scissor = state;
565 }
566
567 void RsxDevice::SetScissor(const Recti& rect)
568 {
569 _scissor.Enabled = true;
570 _scissor.Rect = rect;
571 }
572
573 void RsxDevice::SetScissorTestEnabled(bool enabled)
574 {
575 _scissor.Enabled = enabled;
576 }
577
578 Recti RsxDevice::GetViewport()
579 {
580 return _viewport;
581 }
582
583 void RsxDevice::SetViewport(const Recti& rect)
584 {
585 _viewport = rect;
586 }
587
588 void RsxDevice::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height)
589 {
590 _viewport = Recti(x, y, width, height);
591 }
592
593 Colorf RsxDevice::GetClearColor()
594 {
595 return _clearColor;
596 }
597
598 void RsxDevice::SetClearColor(const Colorf& color)
599 {
600 _clearColor = color;
601 }
602
603 void RsxDevice::Clear(ClearFlags flags)
604 {
605 if (_context == nullptr) {
606 return;
607 }
608 ApplySurface();
609
610 std::uint32_t mask = 0;
611 if ((flags & ClearFlags::Color) == ClearFlags::Color) {
612 rsxSetClearColor(_context, PackClearColor(_clearColor));
613 mask |= (GCM_CLEAR_R | GCM_CLEAR_G | GCM_CLEAR_B | GCM_CLEAR_A);
614 }
615 if ((flags & ClearFlags::Depth) == ClearFlags::Depth) {
616 rsxSetClearDepthStencil(_context, 0xFFFFFF00u);
617 mask |= GCM_CLEAR_Z;
618 }
619 if ((flags & ClearFlags::Stencil) == ClearFlags::Stencil) {
620 mask |= GCM_CLEAR_S;
621 }
622 if (mask != 0) {
623 // A real hardware clear, unlike the full-screen quad the tile-based sceGxm backend has to draw
624 rsxClearSurface(_context, mask);
625 rsxFlushBuffer(_context);
626 }
627 }
628
629 // -- Target and viewport ----------------------------------------------------------------------
630
631 void RsxDevice::GetCurrentTargetSize(std::int32_t& width, std::int32_t& height)
632 {
633 if (_currentRenderTarget != nullptr) {
634 if (RsxTexture* texture = _currentRenderTarget->GetColorTexture(0)) {
635 width = texture->GetWidth();
636 height = texture->GetHeight();
637 return;
638 }
639 }
640 width = _displayWidth;
641 height = _displayHeight;
642 }
643
644 void RsxDevice::ApplySurface()
645 {
646 if (_context == nullptr) {
647 return;
648 }
649
650 std::int32_t targetWidth = _displayWidth;
651 std::int32_t targetHeight = _displayHeight;
652 gcmSurface surface;
653
654 if (_currentRenderTarget != nullptr && _currentRenderTarget->GetDrawSurface(surface, targetWidth, targetHeight)) {
655 // The depth half is the device's shared surface rather than anything the target owns
656 surface.depthFormat = GCM_SURFACE_ZETA_Z24S8;
657 surface.depthLocation = _depthBuffer.GetGcmLocation();
658 surface.depthOffset = _depthBuffer.Offset;
659 surface.depthPitch = _depthPitch;
660 } else {
661 // No render target: the intermediate screen surface, which PresentFrame() flips out
662 std::memset(&surface, 0, sizeof(surface));
663 surface.colorFormat = GCM_SURFACE_A8R8G8B8;
664 surface.colorTarget = GCM_SURFACE_TARGET_0;
665 surface.colorLocation[0] = _screenBuffer.GetGcmLocation();
666 surface.colorOffset[0] = _screenBuffer.Offset;
667 surface.colorPitch[0] = _screenPitch;
668 for (std::uint32_t i = 1; i < 4; i++) {
669 surface.colorLocation[i] = GCM_LOCATION_RSX;
670 surface.colorOffset[i] = 0;
671 surface.colorPitch[i] = 64;
672 }
673 surface.depthFormat = GCM_SURFACE_ZETA_Z24S8;
674 surface.depthLocation = _depthBuffer.GetGcmLocation();
675 surface.depthOffset = _depthBuffer.Offset;
676 surface.depthPitch = _depthPitch;
677 surface.type = GCM_SURFACE_TYPE_LINEAR;
678 surface.antiAlias = GCM_SURFACE_CENTER_1;
679 surface.width = std::uint32_t(_displayWidth);
680 surface.height = std::uint32_t(_displayHeight);
681 surface.x = 0;
682 surface.y = 0;
683 targetWidth = _displayWidth;
684 targetHeight = _displayHeight;
685 }
686
687 rsxSetSurface(_context, &surface);
688 _surfaceDirty = false;
689 ApplyViewportAndScissor(targetWidth, targetHeight);
690 // Programming a surface resets the ROP state the caches think they own, so blending silently stops
691 // happening: the setters see their cached value already matching and skip the re-enable, and every
692 // sprite from then on draws opaque (a black box around every glyph). Re-assert it here rather than
693 // per draw - this runs once per target change, which is a handful of times a frame.
694 rsxSetBlendEnable(_context, _blending.Enabled ? GCM_TRUE : GCM_FALSE);
695 rsxSetBlendFunc(_context, TranslateBlendFactor(_blending.SrcRgb), TranslateBlendFactor(_blending.DstRgb),
696 TranslateBlendFactor(_blending.SrcAlpha), TranslateBlendFactor(_blending.DstAlpha));
697 rsxSetBlendEquation(_context, GCM_FUNC_ADD, GCM_FUNC_ADD);
698 rsxSetDepthTestEnable(_context, _depthTest.TestEnabled ? GCM_TRUE : GCM_FALSE);
699 rsxSetDepthWriteEnable(_context, _depthTest.MaskEnabled ? GCM_TRUE : GCM_FALSE);
700 }
701
702 void RsxDevice::ApplyViewportAndScissor(std::int32_t targetWidth, std::int32_t targetHeight)
703 {
704 if (_context == nullptr) {
705 return;
706 }
707
708 const std::int32_t x = _viewport.X;
709 const std::int32_t width = _viewport.W;
710 const std::int32_t height = _viewport.H;
711 // The engine's viewport origin is bottom-left (OpenGL); the RSX's is top-left, so the Y is flipped
712 // against the target. Every surface here is stored bottom-up (see the class documentation), which is
713 // what makes this the only place the two conventions have to be reconciled.
714 const std::int32_t y = targetHeight - (_viewport.Y + height);
715
716 // The scale/offset pair is the viewport transform proper: clip space maps onto the half-width and
717 // half-height of the rectangle, centred on it. The Z half maps [-1, 1] onto [0, 1], the depth range
718 // the hardware stores, which is what the engine's projection matrices assume.
719 const float scale[4] = {
720 float(width) * 0.5f,
721 float(height) * 0.5f,
722 0.5f,
723 0.0f
724 };
725 const float offset[4] = {
726 float(x) + float(width) * 0.5f,
727 float(y) + float(height) * 0.5f,
728 0.5f,
729 0.0f
730 };
731 rsxSetViewport(_context, std::uint16_t(x), std::uint16_t(y), std::uint16_t(width), std::uint16_t(height),
732 0.0f, 1.0f, scale, offset);
733
734 if (_scissor.Enabled) {
735 // Clamped into the target before anything is narrowed to 16 bits. A clip rectangle is allowed to
736 // hang off the edge of what it clips - the menu's does - and the flipped Y of one that starts
737 // above the target is NEGATIVE, which as an unsigned 16-bit field becomes ~65000 and puts the
738 // scissor somewhere the target does not reach, so the whole draw is clipped away. The hardware's
739 // fields are 12 bits wide as well, so nothing may exceed 4095 either.
740 // NOT flipped against the target. The vertical flip is already in the viewport transform above -
741 // a positive Y scale with the RSX's top-left origin is exactly what stores the surface bottom-up -
742 // so for a full-target viewport the engine's bottom-left Y maps to the same window Y:
743 // window_y = (2Y/H - 1) * (H/2) + H/2 = Y
744 // Flipping here as well put the scissor on the opposite half of the target, which clipped away
745 // whatever the rectangle was meant to keep.
746 std::int32_t sx = _scissor.Rect.X;
747 std::int32_t sy = _scissor.Rect.Y;
748 std::int32_t sw = _scissor.Rect.W;
749 std::int32_t sh = _scissor.Rect.H;
750 if (sx < 0) { sw += sx; sx = 0; }
751 if (sy < 0) { sh += sy; sy = 0; }
752 if (sw > targetWidth - sx) { sw = targetWidth - sx; }
753 if (sh > targetHeight - sy) { sh = targetHeight - sy; }
754 if (sw < 0) { sw = 0; }
755 if (sh < 0) { sh = 0; }
756 rsxSetScissor(_context, std::uint16_t(std::min(sx, 4095)), std::uint16_t(std::min(sy, 4095)),
757 std::uint16_t(std::min(sw, 4095)), std::uint16_t(std::min(sh, 4095)));
758 } else {
759 // There is no scissor-enable bit on the RSX; a scissor covering the whole target is how it is
760 // turned off, and 4095 is the largest rectangle the command's 12-bit fields can express
761 rsxSetScissor(_context, 0, 0, 4095, 4095);
762 }
763 }
764
765 void RsxDevice::SetRenderTarget(RsxRenderTarget* renderTarget)
766 {
767 if (_currentRenderTarget == renderTarget) {
768 return;
769 }
770 _currentRenderTarget = renderTarget;
771 _surfaceDirty = true;
772 }
773
774 void RsxDevice::UnbindRenderTarget(const RsxRenderTarget* renderTarget)
775 {
776 if (_currentRenderTarget == renderTarget) {
777 _currentRenderTarget = nullptr;
778 _surfaceDirty = true;
779 }
780 }
781
782 // -- Resource binding -------------------------------------------------------------------------
783
784 void RsxDevice::BindProgram(RsxShaderProgram* program)
785 {
786 _currentProgram = program;
787 }
788
789 RsxShaderProgram* RsxDevice::CurrentProgram()
790 {
791 return _currentProgram;
792 }
793
794 void RsxDevice::OnProgramDestroyed(const RsxShaderProgram* program)
795 {
796 if (_currentProgram == program) {
797 _currentProgram = nullptr;
798 }
799 }
800
801 void RsxDevice::BindTexture(std::uint32_t unit, const RsxTexture* texture)
802 {
803 if (unit < MaxTextureUnits) {
804 _boundTextures[unit] = texture;
805 }
806 }
807
808 void RsxDevice::UnbindTexture(const RsxTexture* texture)
809 {
810 for (std::uint32_t i = 0; i < MaxTextureUnits; i++) {
811 if (_boundTextures[i] == texture) {
812 _boundTextures[i] = nullptr;
813 }
814 }
815 }
816
817 const RsxTexture* RsxDevice::GetBoundTexture(std::uint32_t unit)
818 {
819 return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr);
820 }
821
822 void RsxDevice::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size)
823 {
824 if (index < MaxUniformBindings) {
825 _boundUniformRanges[index].Data = data;
826 _boundUniformRanges[index].Size = size;
827 }
828 }
829
830 void RsxDevice::GetUniformRange(std::uint32_t index, const std::uint8_t*& data, std::uint32_t& size)
831 {
832 if (index < MaxUniformBindings) {
833 data = _boundUniformRanges[index].Data;
834 size = _boundUniformRanges[index].Size;
835 } else {
836 data = nullptr;
837 size = 0;
838 }
839 }
840
841 // -- Fences -----------------------------------------------------------------------------------
842
843 FenceHandle RsxDevice::InsertFence()
844 {
845 // The engine only uses fences to keep from overwriting a buffer the GPU may still be reading, and on
846 // this backend the ring is deep enough that the wait can never be the thing that saves it: the PPE is
847 // held to one frame ahead by the `gcmSetWaitFlip()` in PresentFrame() (there are two display buffers),
848 // while RenderBuffersManager cycles its streaming buffers through three sections. A section is
849 // therefore reused two frames after the GPU last read it. Reporting the fence signalled is honest
850 // under that invariant - but it is the RING that provides the safety, not this function, so a backend
851 // change that drops the sections or deepens the run-ahead has to give this a real backend label.
852 return FenceHandle{};
853 }
854
855 void RsxDevice::DeleteFence(FenceHandle& fence)
856 {
857 fence = FenceHandle{};
858 }
859
860 bool RsxDevice::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs)
861 {
862 static_cast<void>(fence);
863 static_cast<void>(timeoutNs);
864 return true;
865 }
866
867 // -- Present ----------------------------------------------------------------------------------
868
869 void RsxDevice::PresentFrame()
870 {
871 if (_context == nullptr) {
872 return;
873 }
874
875 // The frame was drawn bottom-up into the screen surface; the flip into the display buffer is where
876 // the OpenGL convention becomes the scan-out's, and where the logical resolution is scaled to the
877 // panel. Rendering it as a quad rather than blitting is what buys the scale for free.
878 gcmSurface surface;
879 std::memset(&surface, 0, sizeof(surface));
880 surface.colorFormat = GCM_SURFACE_A8R8G8B8;
881 surface.colorTarget = GCM_SURFACE_TARGET_0;
882 surface.colorLocation[0] = _displayBuffers[_backBufferIndex].GetGcmLocation();
883 surface.colorOffset[0] = _displayBuffers[_backBufferIndex].Offset;
884 surface.colorPitch[0] = _displayPitch;
885 for (std::uint32_t i = 1; i < 4; i++) {
886 surface.colorLocation[i] = GCM_LOCATION_RSX;
887 surface.colorOffset[i] = 0;
888 surface.colorPitch[i] = 64;
889 }
890 surface.depthFormat = GCM_SURFACE_ZETA_Z24S8;
891 surface.depthLocation = _depthBuffer.GetGcmLocation();
892 surface.depthOffset = _depthBuffer.Offset;
893 surface.depthPitch = _depthPitch;
894 surface.type = GCM_SURFACE_TYPE_LINEAR;
895 surface.antiAlias = GCM_SURFACE_CENTER_1;
896 surface.width = std::uint32_t(_displayWidth);
897 surface.height = std::uint32_t(_displayHeight);
898 surface.x = 0;
899 surface.y = 0;
900 rsxSetSurface(_context, &surface);
901
902 const float scale[4] = { float(_displayWidth) * 0.5f, float(_displayHeight) * 0.5f, 0.5f, 0.0f };
903 const float offset[4] = { float(_displayWidth) * 0.5f, float(_displayHeight) * 0.5f, 0.5f, 0.0f };
904 rsxSetViewport(_context, 0, 0, std::uint16_t(_displayWidth), std::uint16_t(_displayHeight), 0.0f, 1.0f, scale, offset);
905 rsxSetScissor(_context, 0, 0, 4095, 4095);
906
907 // Through the cached setters, NOT rsxSetBlendEnable()/rsxSetDepthTestEnable() directly: those would
908 // change the hardware while `_blending`/`_depthTest` still claimed the pipeline's last values, and the
909 // early-out in those setters would then swallow the next frame's request to turn blending back on.
910 // The result is that only the first frame blends and every later one draws sprites opaque - which
911 // shows up as a black box around every glyph.
912 SetBlendingEnabled(false);
913 SetDepthTestEnabled(false);
914
915 if (_presentVertexProgram != nullptr && _presentFragmentProgram != nullptr && _presentVertices.IsValid()) {
916 rsxInvalidateTextureCache(_context, GCM_INVALIDATE_TEXTURE);
917 // The present shader replaces whatever the pipeline left bound, so the cache above no longer
918 // describes what the RSX is running
919 _lastVertexProgram = nullptr;
920 _lastVertexUcode = nullptr;
921 _lastFragmentProgram = nullptr;
922 rsxLoadVertexProgram(_context, _presentVertexProgram, _presentVertexUcode);
923 rsxLoadFragmentProgramLocation(_context, _presentFragmentProgram, _presentFragmentUcode.Offset,
924 _presentFragmentUcode.GetGcmLocation());
925
926 rsxLoadTexture(_context, 0, &_screenTexture);
927 rsxTextureControl(_context, 0, GCM_TRUE, 0 << 8, 0 << 8, GCM_TEXTURE_MAX_ANISO_1);
928 rsxTextureFilter(_context, 0, 0, GCM_TEXTURE_LINEAR, GCM_TEXTURE_LINEAR, GCM_TEXTURE_CONVOLUTION_QUINCUNX);
929 rsxTextureWrapMode(_context, 0, GCM_TEXTURE_CLAMP_TO_EDGE, GCM_TEXTURE_CLAMP_TO_EDGE,
930 GCM_TEXTURE_CLAMP_TO_EDGE, 0, GCM_TEXTURE_ZFUNC_LESS, 0);
931
932 // Four vertices of (x, y, u, v), the V already flipped in the data so the shader stays trivial.
933 // The registers are looked up through GetAttrib() rather than the GetAttribIndex() that
934 // rsx_program.h also declares: librsx declares that one but implements no such symbol, so
935 // calling it does not link (the same is true of rsxFragmentProgramGetConstIndex).
936 const rsxProgramAttrib* positionAttrib = rsxVertexProgramGetAttrib(_presentVertexProgram, "aPosition");
937 const rsxProgramAttrib* texCoordAttrib = rsxVertexProgramGetAttrib(_presentVertexProgram, "aTexCoords");
938 const std::int32_t positionReg = (positionAttrib != nullptr ? std::int32_t(positionAttrib->index) : -1);
939 const std::int32_t texCoordReg = (texCoordAttrib != nullptr ? std::int32_t(texCoordAttrib->index) : -1);
940 if (positionReg >= 0) {
941 rsxBindVertexArrayAttrib(_context, std::uint8_t(positionReg), 0, _presentVertices.Offset,
942 16, 2, GCM_VERTEX_DATA_TYPE_F32, _presentVertices.GetGcmLocation());
943 }
944 if (texCoordReg >= 0) {
945 rsxBindVertexArrayAttrib(_context, std::uint8_t(texCoordReg), 0, _presentVertices.Offset + 8,
946 16, 2, GCM_VERTEX_DATA_TYPE_F32, _presentVertices.GetGcmLocation());
947 }
948 rsxDrawVertexArray(_context, GCM_TYPE_TRIANGLE_STRIP, 0, 4);
949 }
950
951 // Queue the flip and let the next frame's commands follow it; gcmSetWaitFlip() is what keeps the GPU
952 // from drawing over a buffer the scan-out has not finished with
953 if (!_firstFlip) {
954 while (gcmGetFlipStatus() != 0) {
955 ::usleep(200);
956 }
957 }
958 gcmResetFlipStatus();
959 gcmSetFlip(_context, std::uint8_t(_backBufferIndex));
960 // The wait has to be in the buffer BEFORE the write pointer is handed over, or it is not part of the
961 // work this flush submits and only takes effect once the next frame happens to flush
962 gcmSetWaitFlip(_context);
963 rsxFlushBuffer(_context);
964
965 _backBufferIndex = (_backBufferIndex + 1) % DisplayBufferCount;
966 _firstFlip = false;
967 _frameCounter++;
968
969 // Blocks retired long enough ago that the GPU cannot still be reading them can go now
970 ReleaseRetiredBlocks();
971
972 // The next frame starts by re-programming whatever it renders into
973 _surfaceDirty = true;
974 }
975
976 // -- Built-in resources -----------------------------------------------------------------------
977
978 bool RsxDevice::CreateBuiltinResources()
979 {
980 // The quad corner stream: {(1,0), (1,1), (0,0), (0,1)}, the order of the single-quad TRIANGLE_STRIP
981 // draw the Cg emitter's gl_VertexID rewrite expects
982 static const float quadCorners[] = {
983 1.0f, 0.0f,
984 1.0f, 1.0f,
985 0.0f, 0.0f,
986 0.0f, 1.0f
987 };
988 _quadCornerStream = RsxVram::Alloc(sizeof(quadCorners), 128, RsxVram::Location::Main);
989 if (!_quadCornerStream.IsValid()) {
990 return false;
991 }
992 std::memcpy(_quadCornerStream.Base, quadCorners, sizeof(quadCorners));
993
994 // The batched stream: six vertices per sprite carrying the corner and the sprite's index in the
995 // batch, so a draw of 6*n vertices reproduces the gl_VertexID/6 instance lookup
996 static const float batchedCorners[6][2] = {
997 { 1.0f, 1.0f }, { 0.0f, 1.0f }, { 0.0f, 0.0f },
998 { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }
999 };
1000 const std::uint32_t batchedSize = std::uint32_t(sizeof(float) * 3 * 6 * MaxBatchSize);
1001 _batchedCornerStream = RsxVram::Alloc(batchedSize, 128, RsxVram::Location::Main);
1002 if (!_batchedCornerStream.IsValid()) {
1003 return false;
1004 }
1005 {
1006 float* out = static_cast<float*>(_batchedCornerStream.Base);
1007 for (std::uint32_t instance = 0; instance < MaxBatchSize; instance++) {
1008 for (std::uint32_t corner = 0; corner < 6; corner++) {
1009 *out++ = batchedCorners[corner][0];
1010 *out++ = batchedCorners[corner][1];
1011 *out++ = float(instance);
1012 }
1013 }
1014 }
1015
1016 // The present quad: (x, y, u, v) per vertex in the TRIANGLE_STRIP order, in clip space. The V is
1017 // flipped here rather than in the shader, which is what keeps the present shader a plain textured
1018 // quad and puts the one convention correction in a place a reader can see.
1019 static const float presentQuad[] = {
1020 -1.0f, -1.0f, 0.0f, 1.0f,
1021 -1.0f, 1.0f, 0.0f, 0.0f,
1022 1.0f, -1.0f, 1.0f, 1.0f,
1023 1.0f, 1.0f, 1.0f, 0.0f
1024 };
1025 _presentVertices = RsxVram::Alloc(sizeof(presentQuad), 128, RsxVram::Location::Main);
1026 if (!_presentVertices.IsValid()) {
1027 return false;
1028 }
1029 std::memcpy(_presentVertices.Base, presentQuad, sizeof(presentQuad));
1030 return true;
1031 }
1032
1033
1034 bool RsxDevice::CreatePresentShader()
1035 {
1036 const GeneratedRsxShader* generated = FindGeneratedRsxShader("__Present", "");
1037 if (generated == nullptr) {
1038 LOGE("The built-in present shader is missing from the generated RSX shader table");
1039 return false;
1040 }
1041
1042 _presentVertexProgram = reinterpret_cast<const rsxVertexProgram*>(generated->VertexProgram);
1043 _presentFragmentProgram = reinterpret_cast<const rsxFragmentProgram*>(generated->FragmentProgram);
1044
1045 std::uint32_t ucodeSize = 0;
1046 void* ucode = nullptr;
1047 rsxVertexProgramGetUCode(_presentVertexProgram, &ucode, &ucodeSize);
1048 _presentVertexUcode = ucode;
1049
1050 rsxFragmentProgramGetUCode(_presentFragmentProgram, &ucode, &ucodeSize);
1051 if (ucode == nullptr || ucodeSize == 0) {
1052 return false;
1053 }
1054 _presentFragmentUcode = RsxVram::AllocFragmentProgram(ucodeSize);
1055 if (!_presentFragmentUcode.IsValid()) {
1056 return false;
1057 }
1058 std::memcpy(_presentFragmentUcode.Base, ucode, ucodeSize);
1059 return true;
1060 }
1061
1062 const void* RsxDevice::GetQuadCornerStream()
1063 {
1064 return _quadCornerStream.Base;
1065 }
1066
1067 const void* RsxDevice::GetBatchedCornerStream()
1068 {
1069 return _batchedCornerStream.Base;
1070 }
1071
1072 std::uint32_t RsxDevice::GetQuadCornerStreamOffset()
1073 {
1074 return _quadCornerStream.Offset;
1075 }
1076
1077 std::uint32_t RsxDevice::GetBatchedCornerStreamOffset()
1078 {
1079 return _batchedCornerStream.Offset;
1080 }
1081
1082 // -- Draw -------------------------------------------------------------------------------------
1083
1084 void RsxDevice::UploadUniforms()
1085 {
1086 RsxShaderProgram* program = _currentProgram;
1087 if (program == nullptr || _context == nullptr) {
1088 return;
1089 }
1090 // Loose uniforms: the value the uniform cache last committed, published through the program
1091 for (const RsxUniformSlot& slot : program->GetVertexUniformSlots()) {
1092 if (const std::uint8_t* data = program->ResolveUniform(slot.Name)) {
1093 rsxSetVertexProgramParameter(_context, program->GetVertexProgram(), slot.Param,
1094 reinterpret_cast<const float*>(data));
1095 }
1096 }
1097
1098 for (const RsxUniformSlot& slot : program->GetFragmentUniformSlots()) {
1099 if (const std::uint8_t* data = program->ResolveUniform(slot.Name)) {
1100 // A fragment constant is patched into the microcode, which is why this needs the program's
1101 // private copy of it rather than the shared blob (see RsxShaderProgram)
1102 rsxSetFragmentProgramParameter(_context, program->GetFragmentProgram(), slot.Param,
1103 reinterpret_cast<const float*>(data), program->GetFragmentUcodeBlock().Offset,
1104 program->GetFragmentUcodeBlock().GetGcmLocation());
1105 }
1106 }
1107
1108 // Uniform-block members, out of the range the pipeline bound to the block's binding point
1109 const auto uploadBlocks = [program](const SmallVector<RsxShaderProgram::RsxBlockUpload, 0>& uploads, bool vertexStage) {
1110 for (const RsxShaderProgram::RsxBlockUpload& upload : uploads) {
1111 const std::uint8_t* data = nullptr;
1112 std::uint32_t size = 0;
1113 GetUniformRange(upload.BindingIndex, data, size);
1114 if (data == nullptr || upload.SourceOffset >= size) {
1115 continue;
1116 }
1117 const std::uint8_t* source = data + upload.SourceOffset;
1118 if (vertexStage) {
1119 rsxSetVertexProgramParameter(_context, program->GetVertexProgram(), upload.Param,
1120 reinterpret_cast<const float*>(source));
1121 } else {
1122 rsxSetFragmentProgramParameter(_context, program->GetFragmentProgram(), upload.Param,
1123 reinterpret_cast<const float*>(source), program->GetFragmentUcodeBlock().Offset,
1124 program->GetFragmentUcodeBlock().GetGcmLocation());
1125 }
1126 }
1127 };
1128 uploadBlocks(program->GetVertexBlockUploads(), true);
1129 uploadBlocks(program->GetFragmentBlockUploads(), false);
1130
1131 UploadInstanceArray();
1132 }
1133
1134 void RsxDevice::UploadInstanceArray()
1135 {
1136 RsxShaderProgram* program = _currentProgram;
1137 if (program == nullptr || _context == nullptr) {
1138 return;
1139 }
1140 const RsxShaderProgram::RsxInstanceArray& array = program->GetInstanceArray();
1141 if (!array.Valid) {
1142 return;
1143 }
1144
1145 const std::uint8_t* data = nullptr;
1146 std::uint32_t size = 0;
1147 GetUniformRange(array.BindingIndex, data, size);
1148 if (data == nullptr || size == 0) {
1149 return;
1150 }
1151
1152 // Repack rather than write field by field. The two sides lay an element out differently - std140
1153 // packs a trailing vec2 and float into one 16-byte slot, the register file gives each its own - so
1154 // the element cannot be handed over as one block; but gathering it into a register-shaped scratch
1155 // buffer first turns what would be one command per FIELD into one command per element.
1156 float scratch[MaxInstanceRegisters * 4];
1157 const std::uint32_t registers = array.RegistersPerElement;
1158 if (registers == 0 || registers > MaxInstanceRegisters) {
1159 return;
1160 }
1161
1162 // Only the elements the bound range actually covers are written: the batcher sizes its range to the
1163 // sprites it collected, which is usually fewer than the batch the shader was compiled for
1164 std::uint32_t elements = (array.SourceStride > 0 ? size / array.SourceStride : 0);
1165 if (elements > array.ElementCount) {
1166 elements = array.ElementCount;
1167 }
1168
1169 for (std::uint32_t element = 0; element < elements; element++) {
1170 const std::uint8_t* source = data + std::size_t(element) * array.SourceStride;
1171 std::memset(scratch, 0, std::size_t(registers) * 4 * sizeof(float));
1172 for (const RsxShaderProgram::RsxInstanceField& field : array.Fields) {
1173 if (field.RegisterOffset + field.RegisterCount > registers) {
1174 continue;
1175 }
1176 std::memcpy(&scratch[field.RegisterOffset * 4], source + field.SourceOffset, field.ByteSize);
1177 }
1178 // NOT rsxSetVertexProgramConstants(): that one writes through `RSX_CONTEXT_CURRENTP`, which is
1179 // `context->current` itself rather than a local cursor, so it advances the write pointer as it
1180 // goes AND THEN advances it again by its whole reservation in RSX_CONTEXT_CURRENT_END(). Every
1181 // call therefore leaves a reservation-sized hole of untouched memory in the command stream. The
1182 // hole is harmless on the first pass through a FIFO fragment (freshly zeroed memory decodes as
1183 // no-ops) but not once the ring has cycled: the stale float payloads left there by the previous
1184 // pass are then executed as commands, and a 1.0f (0x3f800000) has the old JUMP bit set, so the
1185 // GPU jumps to 0x1f800000 and the FIFO dies.
1186 //
1187 // This sibling takes its count in constant REGISTERS rather than floats and writes through an
1188 // index, so the pointer moves exactly once. It also copies the second half of each 32-float
1189 // block from the right place, which the other one gets wrong for elements of 8+ registers.
1190 rsxLoadVertexProgramParameterBlock(_context, array.BaseRegister + element * registers, registers, scratch);
1191 }
1192 }
1193
1194 const rsxProgramAttrib* RsxDevice::FindVertexAttribute(const rsxVertexProgram* program, const char* name)
1195 {
1196 if (program == nullptr || name == nullptr) {
1197 return nullptr;
1198 }
1199 // The generated stages reach cgcomp as members of the Cg entry point's input struct, so what ends up
1200 // in the attribute table is "_input.aQuadCorner" rather than the name the engine and the shader
1201 // source use. Asking librsx for the bare name finds nothing at all, which is silent: the stream never
1202 // gets bound and the stage reads whatever the last draw left in that register. The qualifier is
1203 // therefore matched as a suffix, which also keeps the hand-written present shader - whose attributes
1204 // are unqualified - working through the same path.
1205 const std::uint16_t count = rsxVertexProgramGetNumAttrib(program);
1206 const rsxProgramAttrib* attribs = rsxVertexProgramGetAttribs(program);
1207 if (attribs == nullptr) {
1208 return nullptr;
1209 }
1210 const char* base = reinterpret_cast<const char*>(program);
1211 const std::size_t nameLength = std::strlen(name);
1212 for (std::uint16_t i = 0; i < count; i++) {
1213 const char* attribName = base + attribs[i].name_off;
1214 const std::size_t attribLength = std::strlen(attribName);
1215 if (attribLength < nameLength) {
1216 continue;
1217 }
1218 if (std::strcmp(attribName + (attribLength - nameLength), name) != 0) {
1219 continue;
1220 }
1221 // Either the whole name or a "<qualifier>." prefix in front of it, never a partial word
1222 if (attribLength == nameLength || attribName[attribLength - nameLength - 1] == '.') {
1223 return &attribs[i];
1224 }
1225 }
1226 return nullptr;
1227 }
1228
1229 void RsxDevice::ApplyVertexFormat(std::int32_t baseVertex)
1230 {
1231 RsxShaderProgram* program = _currentProgram;
1232 if (program == nullptr || _context == nullptr) {
1233 return;
1234 }
1235
1236 // The sprite shaders have no vertex-ID input - Cg has none to give them - so the Cg lowering reads
1237 // `aQuadCorner` and, when batched, `aInstanceIndex` instead, and the per-vertex data behind those two
1238 // comes from the device's own static streams rather than from anything the pipeline bound. They
1239 // appear in no reflection, so they are looked up in the microcode's own attribute table, exactly as
1240 // the sceGxm backend does with the same shaders (see GxmShaderProgram::BindStageAttributes()).
1241 // Without this the corner attribute is fed by whatever the previous draw left in that register.
1242 std::uint32_t boundRegisters = 0;
1243 if (const rsxVertexProgram* vertexProgram = program->GetVertexProgram()) {
1244 const rsxProgramAttrib* cornerAttrib = FindVertexAttribute(vertexProgram, Material::QuadCornerAttributeName);
1245 const rsxProgramAttrib* instanceAttrib = FindVertexAttribute(vertexProgram, "aInstanceIndex");
1246 if (cornerAttrib != nullptr || instanceAttrib != nullptr) {
1247 // The batched stream carries the instance index alongside the corner, six vertices per
1248 // sprite; the unbatched one is the bare four-vertex strip corner
1249 const bool batched = (instanceAttrib != nullptr);
1250 const RsxVram::Block& stream = (batched ? _batchedCornerStream : _quadCornerStream);
1251 const std::uint8_t stride = (batched ? std::uint8_t(3 * sizeof(float)) : std::uint8_t(2 * sizeof(float)));
1252 if (stream.IsValid()) {
1253 if (cornerAttrib != nullptr) {
1254 rsxBindVertexArrayAttrib(_context, std::uint8_t(cornerAttrib->index), 0, stream.Offset,
1255 stride, 2, GCM_VERTEX_DATA_TYPE_F32, stream.GetGcmLocation());
1256 boundRegisters |= (1u << cornerAttrib->index);
1257 }
1258 if (instanceAttrib != nullptr) {
1259 rsxBindVertexArrayAttrib(_context, std::uint8_t(instanceAttrib->index), 0,
1260 stream.Offset + std::uint32_t(2 * sizeof(float)), stride, 1,
1261 GCM_VERTEX_DATA_TYPE_F32, stream.GetGcmLocation());
1262 boundRegisters |= (1u << instanceAttrib->index);
1263 }
1264 }
1265 }
1266 }
1267
1268 RsxVertexFormat& format = program->GetVertexFormat();
1269 for (std::uint32_t i = 0; i < format.GetAttributeCount(); i++) {
1270 const RsxVertexFormat::Attribute& attribute = format[i];
1271 if (!attribute.IsEnabled()) {
1272 continue;
1273 }
1274
1275 // The engine's attribute index is a location in the reflection's numbering; the register the
1276 // compiled stage actually reads comes from the microcode's own table. Falling back to the
1277 // location keeps a stage whose attribute the reflection does not name working as before.
1278 const std::int32_t resolved = program->GetAttributeRegisterForLocation(attribute.GetIndex());
1279 const std::int32_t reg = (resolved >= 0 ? resolved : std::int32_t(attribute.GetIndex()));
1280 const RsxBufferObject* vbo = attribute.GetVbo();
1281
1282
1283 if (vbo == nullptr || vbo->GetGpuData() == nullptr) {
1284 continue;
1285 }
1286
1287 std::uint32_t offset = 0;
1288 if (rsxAddressToOffset(vbo->GetGpuData(), &offset) != 0) {
1289 continue;
1290 }
1291 offset += attribute.GetBaseOffset() +
1292 std::uint32_t(reinterpret_cast<std::uintptr_t>(attribute.GetPointer())) +
1293 std::uint32_t(baseVertex) * std::uint32_t(attribute.GetStride());
1294
1295
1296 rsxBindVertexArrayAttrib(_context, std::uint8_t(reg), 0, offset,
1297 std::uint8_t(attribute.GetStride()), std::uint8_t(attribute.GetSize()),
1298 GCM_VERTEX_DATA_TYPE_F32, GCM_LOCATION_CELL);
1299 boundRegisters |= (1u << (reg & 31));
1300 }
1301
1302 // A register this draw did not bind still holds the previous draw's stream, and the buffer behind it
1303 // may since have been freed and handed out again. An element count of zero is how the hardware is
1304 // told an attribute is absent, so anything left over from the last draw is turned off rather than
1305 // left pointing somewhere it no longer owns.
1306 const std::uint32_t staleRegisters = _boundAttributeRegisters & ~boundRegisters;
1307 if (staleRegisters != 0) {
1308 for (std::uint32_t reg = 0; reg < MaxVertexAttributeRegisters; reg++) {
1309 if ((staleRegisters & (1u << reg)) != 0) {
1310 rsxBindVertexArrayAttrib(_context, std::uint8_t(reg), 0, 0, 0, 0,
1311 GCM_VERTEX_DATA_TYPE_F32, GCM_LOCATION_CELL);
1312 }
1313 }
1314 }
1315 _boundAttributeRegisters = boundRegisters;
1316 }
1317
1318 void RsxDevice::DrawCommon(PrimitiveType primitive, std::int32_t firstVertex, std::uint32_t count,
1319 bool indexed, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
1320 {
1321 RsxShaderProgram* program = _currentProgram;
1322 if (_context == nullptr || program == nullptr || !program->IsLinked()) {
1323 return;
1324 }
1325 if (_surfaceDirty) {
1326 ApplySurface();
1327 } else {
1328 // The viewport and scissor are engine state that changes far more often than the target, so they
1329 // are re-programmed per draw while the surface is not
1330 std::int32_t targetWidth, targetHeight;
1331 GetCurrentTargetSize(targetWidth, targetHeight);
1332 ApplyViewportAndScissor(targetWidth, targetHeight);
1333 }
1334
1335 // The whole vertex microcode travels through the FIFO - the fragment side only sends a pointer, because
1336 // its microcode is fetched from local memory. That makes this by far the largest thing a draw writes,
1337 // into a ring of about 28 KB, so it is sent only when the program actually changes. Consecutive draws
1338 // with the same program are the common case in a batched frame, and re-sending a program the RSX is
1339 // already running would be most of that frame's FIFO traffic.
1340 if (_lastVertexProgram != program->GetVertexProgram() || _lastVertexUcode != program->GetVertexUcode()) {
1341 _lastVertexProgram = program->GetVertexProgram();
1342 _lastVertexUcode = program->GetVertexUcode();
1343 rsxLoadVertexProgram(_context, program->GetVertexProgram(), program->GetVertexUcode());
1344 // Which outputs the stage actually writes is not part of the program upload - librsx sends the
1345 // instructions and nothing else - so the mask cgcomp recorded has to be programmed separately.
1346 // Left unset it keeps whatever the last program needed, and a stage writing an output the previous
1347 // one did not has that output discarded; the emulator reports it as the program having no position
1348 // output and NOPs the shader, which is why the batched stages (mask 0x1c000, one bit wider than
1349 // anything else here) drew nothing at all.
1350 rsxSetVertexAttribOutputMask(_context, program->GetVertexProgram()->output_mask);
1351
1352 rsxFlushBuffer(_context);
1353 }
1354 if (_lastFragmentProgram != program->GetFragmentProgram()
1355 || _lastFragmentUcodeOffset != program->GetFragmentUcodeBlock().Offset) {
1356 _lastFragmentProgram = program->GetFragmentProgram();
1357 _lastFragmentUcodeOffset = program->GetFragmentUcodeBlock().Offset;
1358 rsxLoadFragmentProgramLocation(_context, program->GetFragmentProgram(),
1359 program->GetFragmentUcodeBlock().Offset, program->GetFragmentUcodeBlock().GetGcmLocation());
1360 }
1361
1362 // Textures. The unit the shader samples comes from the microcode, the one the pipeline bound to from
1363 // the reflection; they normally agree (see RsxShaderProgram::RsxSamplerBinding).
1364 bool anyTexture = false;
1365 for (const RsxShaderProgram::RsxSamplerBinding& sampler : program->GetFragmentSamplers()) {
1366 const RsxTexture* texture = GetBoundTexture(sampler.EngineUnit);
1367 if (texture == nullptr) {
1368 continue;
1369 }
1370 if (const gcmTexture* gcmTex = texture->GetGcmTexture()) {
1371 rsxLoadTexture(_context, std::uint8_t(sampler.HardwareUnit), gcmTex);
1372 texture->ApplySamplerState(sampler.HardwareUnit);
1373 anyTexture = true;
1374 }
1375 }
1376 if (anyTexture) {
1377 // The texture cache does not observe writes the PPE made to texture memory, so it is dropped
1378 // whenever a draw is about to sample something that may have been uploaded since the last one
1379 rsxInvalidateTextureCache(_context, GCM_INVALIDATE_TEXTURE);
1380 }
1381
1382 UploadUniforms();
1383
1384
1385 // A non-indexed draw's first vertex is folded into the stream offsets rather than handed to
1386 // `rsxDrawVertexArray()` as its start index: `NV40TCL_VTXBUF_ADDRESS` is a full byte offset, so the
1387 // two are equivalent, and this keeps the one path the hardware fetches through identical for indexed
1388 // and non-indexed draws. The engine puts every mesh in a shared per-frame array buffer and expresses
1389 // its position in it as this first vertex (Geometry::Draw()), so it is anything but zero.
1390 ApplyVertexFormat(indexed ? baseVertex : firstVertex);
1391
1392 const std::uint32_t type = TranslatePrimitive(primitive);
1393 if (indexed) {
1394 const RsxBufferObject* ibo = program->GetVertexFormat().GetIbo();
1395 if (ibo == nullptr || ibo->GetGpuData() == nullptr) {
1396 return;
1397 }
1398 std::uint32_t offset = 0;
1399 if (rsxAddressToOffset(ibo->GetGpuData(), &offset) != 0) {
1400 return;
1401 }
1402 offset += std::uint32_t(indexOffset);
1403 rsxDrawIndexArray(_context, std::uint8_t(type), offset, count,
1404 indexFormat == IndexFormat::UInt32 ? GCM_INDEX_TYPE_32B : GCM_INDEX_TYPE_16B,
1405 GCM_LOCATION_CELL);
1406 } else {
1407 rsxDrawVertexArray(_context, type, 0, count);
1408 }
1409
1410
1411 // Hand the commands written so far to the GPU. This is not an optimization but a requirement: the
1412 // FIFO is a ring, and when the write pointer reaches the end librsx's context callback jumps back to
1413 // the start and waits for the GPU to have consumed what is there. The GPU only consumes up to the
1414 // PUT pointer, which nothing but this call advances - so a frame that fills the ring without ever
1415 // flushing either deadlocks or, as here, has its wrapped commands read as garbage ("Unexpected
1416 // command 0x..." from RPCS3). A frame of this game emits far more than the ring holds, chiefly
1417 // because a batched draw writes its whole instance array as constants.
1418 rsxFlushBuffer(_context);
1419
1420 }
1421
1422 void RsxDevice::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1423 {
1424 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices), false, IndexFormat::UInt16, 0, 0);
1425 }
1426
1427 void RsxDevice::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances)
1428 {
1429 // The RSX has no instanced draw, and the engine's batched shaders do not need one: the batcher
1430 // already expands each sprite into its own six vertices carrying the instance index (see
1431 // GetBatchedCornerStream()), so an instanced request is a plain draw of the expanded stream
1432 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices) * std::uint32_t(numInstances),
1433 false, IndexFormat::UInt16, 0, 0);
1434 }
1435
1436 void RsxDevice::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
1437 {
1438 DrawCommon(primitive, 0, numIndices, true, indexFormat, indexOffset, baseVertex);
1439 }
1440
1441 void RsxDevice::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
1442 {
1443 DrawCommon(primitive, 0, numIndices * std::uint32_t(numInstances), true, indexFormat, indexOffset, baseVertex);
1444 }
1445 }
1446
1447 #endif