summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/audio_core/audio_renderer.h2
-rw-r--r--src/audio_core/stream.cpp4
-rw-r--r--src/audio_core/time_stretch.cpp6
-rw-r--r--src/common/logging/backend.cpp11
-rw-r--r--src/common/logging/backend.h14
-rw-r--r--src/common/string_util.cpp57
-rw-r--r--src/common/string_util.h33
-rw-r--r--src/common/telemetry.h4
-rw-r--r--src/core/core.cpp30
-rw-r--r--src/core/core.h31
-rw-r--r--src/core/crypto/key_manager.cpp44
-rw-r--r--src/core/crypto/key_manager.h9
-rw-r--r--src/core/file_sys/content_archive.cpp33
-rw-r--r--src/core/file_sys/content_archive.h7
-rw-r--r--src/core/file_sys/control_metadata.cpp6
-rw-r--r--src/core/file_sys/control_metadata.h1
-rw-r--r--src/core/file_sys/fsmitm_romfsbuild.h1
-rw-r--r--src/core/file_sys/ips_layer.cpp4
-rw-r--r--src/core/file_sys/patch_manager.cpp9
-rw-r--r--src/core/file_sys/registered_cache.cpp62
-rw-r--r--src/core/file_sys/registered_cache.h23
-rw-r--r--src/core/file_sys/savedata_factory.cpp32
-rw-r--r--src/core/file_sys/savedata_factory.h3
-rw-r--r--src/core/file_sys/vfs.cpp4
-rw-r--r--src/core/file_sys/vfs.h8
-rw-r--r--src/core/file_sys/vfs_offset.cpp4
-rw-r--r--src/core/file_sys/vfs_offset.h2
-rw-r--r--src/core/file_sys/vfs_static.h4
-rw-r--r--src/core/hle/ipc_helpers.h3
-rw-r--r--src/core/hle/kernel/hle_ipc.h8
-rw-r--r--src/core/hle/kernel/kernel.cpp4
-rw-r--r--src/core/hle/kernel/mutex.cpp2
-rw-r--r--src/core/hle/kernel/process.cpp82
-rw-r--r--src/core/hle/kernel/process.h22
-rw-r--r--src/core/hle/kernel/server_session.cpp4
-rw-r--r--src/core/hle/kernel/svc.cpp42
-rw-r--r--src/core/hle/kernel/thread.cpp8
-rw-r--r--src/core/hle/kernel/vm_manager.cpp82
-rw-r--r--src/core/hle/kernel/vm_manager.h15
-rw-r--r--src/core/hle/service/acc/acc.cpp24
-rw-r--r--src/core/hle/service/acc/acc.h1
-rw-r--r--src/core/hle/service/acc/acc_su.cpp2
-rw-r--r--src/core/hle/service/acc/acc_u0.cpp2
-rw-r--r--src/core/hle/service/acc/acc_u1.cpp2
-rw-r--r--src/core/hle/service/acc/profile_manager.cpp27
-rw-r--r--src/core/hle/service/acc/profile_manager.h16
-rw-r--r--src/core/hle/service/am/am.cpp79
-rw-r--r--src/core/hle/service/am/am.h29
-rw-r--r--src/core/hle/service/am/applet_ae.cpp34
-rw-r--r--src/core/hle/service/am/applet_ae.h6
-rw-r--r--src/core/hle/service/am/applet_oe.cpp21
-rw-r--r--src/core/hle/service/am/applet_oe.h6
-rw-r--r--src/core/hle/service/audio/audren_u.cpp31
-rw-r--r--src/core/hle/service/audio/hwopus.cpp2
-rw-r--r--src/core/hle/service/filesystem/filesystem.cpp10
-rw-r--r--src/core/hle/service/filesystem/filesystem.h1
-rw-r--r--src/core/hle/service/filesystem/fsp_srv.cpp153
-rw-r--r--src/core/hle/service/filesystem/fsp_srv.h1
-rw-r--r--src/core/hle/service/hid/controllers/npad.cpp6
-rw-r--r--src/core/hle/service/hid/hid.cpp2
-rw-r--r--src/core/hle/service/nfp/nfp.cpp2
-rw-r--r--src/core/hle/service/ns/ns.cpp64
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue.cpp8
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue.h11
-rw-r--r--src/core/hle/service/nvflinger/nvflinger.cpp12
-rw-r--r--src/core/hle/service/service.cpp4
-rw-r--r--src/core/hle/service/spl/module.cpp9
-rw-r--r--src/core/hle/service/spl/module.h4
-rw-r--r--src/core/hle/service/time/interface.cpp2
-rw-r--r--src/core/hle/service/time/time.cpp132
-rw-r--r--src/core/hle/service/time/time.h19
-rw-r--r--src/core/hle/service/usb/usb.cpp6
-rw-r--r--src/core/hle/service/vi/vi.cpp9
-rw-r--r--src/core/loader/loader.h5
-rw-r--r--src/core/loader/nro.cpp5
-rw-r--r--src/core/memory.cpp2
-rw-r--r--src/core/memory_hook.h15
-rw-r--r--src/core/settings.h6
-rw-r--r--src/core/telemetry_session.cpp9
-rw-r--r--src/core/telemetry_session.h6
-rw-r--r--src/tests/core/arm/arm_test_common.cpp10
-rw-r--r--src/tests/core/arm/arm_test_common.h10
-rw-r--r--src/video_core/CMakeLists.txt4
-rw-r--r--src/video_core/command_processor.cpp2
-rw-r--r--src/video_core/engines/maxwell_3d.cpp73
-rw-r--r--src/video_core/engines/maxwell_3d.h76
-rw-r--r--src/video_core/engines/shader_bytecode.h15
-rw-r--r--src/video_core/macro_interpreter.cpp25
-rw-r--r--src/video_core/macro_interpreter.h17
-rw-r--r--src/video_core/memory_manager.cpp77
-rw-r--r--src/video_core/memory_manager.h13
-rw-r--r--src/video_core/rasterizer_cache.cpp7
-rw-r--r--src/video_core/rasterizer_cache.h44
-rw-r--r--src/video_core/renderer_base.cpp1
-rw-r--r--src/video_core/renderer_base.h6
-rw-r--r--src/video_core/renderer_opengl/gl_buffer_cache.cpp6
-rw-r--r--src/video_core/renderer_opengl/gl_buffer_cache.h4
-rw-r--r--src/video_core/renderer_opengl/gl_primitive_assembler.cpp3
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp263
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h24
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.cpp481
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.h880
-rw-r--r--src/video_core/renderer_opengl/gl_resource_manager.cpp186
-rw-r--r--src/video_core/renderer_opengl/gl_resource_manager.h132
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.cpp12
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.h17
-rw-r--r--src/video_core/renderer_opengl/gl_shader_decompiler.cpp268
-rw-r--r--src/video_core/renderer_opengl/gl_shader_decompiler.h8
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.cpp12
-rw-r--r--src/video_core/renderer_opengl/gl_shader_manager.h1
-rw-r--r--src/video_core/renderer_opengl/gl_state.cpp428
-rw-r--r--src/video_core/renderer_opengl/gl_state.h75
-rw-r--r--src/video_core/renderer_opengl/gl_stream_buffer.cpp5
-rw-r--r--src/video_core/renderer_opengl/maxwell_to_gl.h93
-rw-r--r--src/video_core/renderer_opengl/renderer_opengl.cpp11
-rw-r--r--src/video_core/renderer_opengl/renderer_opengl.h3
-rw-r--r--src/video_core/surface.cpp490
-rw-r--r--src/video_core/surface.h477
-rw-r--r--src/video_core/textures/astc.cpp32
-rw-r--r--src/video_core/textures/astc.h2
-rw-r--r--src/video_core/textures/decoders.cpp16
-rw-r--r--src/video_core/textures/decoders.h10
-rw-r--r--src/video_core/textures/texture.h13
-rw-r--r--src/web_service/telemetry_json.cpp21
-rw-r--r--src/web_service/telemetry_json.h1
-rw-r--r--src/yuzu/CMakeLists.txt2
-rw-r--r--src/yuzu/compatdb.cpp27
-rw-r--r--src/yuzu/compatdb.h4
-rw-r--r--src/yuzu/configuration/config.cpp12
-rw-r--r--src/yuzu/configuration/configure_general.cpp32
-rw-r--r--src/yuzu/configuration/configure_general.h1
-rw-r--r--src/yuzu/configuration/configure_input.cpp2
-rw-r--r--src/yuzu/configuration/configure_input.h6
-rw-r--r--src/yuzu/configuration/configure_system.cpp74
-rw-r--r--src/yuzu/configuration/configure_system.ui228
-rw-r--r--src/yuzu/debugger/graphics/graphics_surface.cpp10
-rw-r--r--src/yuzu/debugger/wait_tree.h1
-rw-r--r--src/yuzu/main.cpp22
-rw-r--r--src/yuzu/main.h6
-rw-r--r--src/yuzu/main.ui7
-rw-r--r--src/yuzu/util/limitable_input_dialog.cpp59
-rw-r--r--src/yuzu/util/limitable_input_dialog.h31
-rw-r--r--src/yuzu_cmd/config.cpp7
-rw-r--r--src/yuzu_cmd/default_ini.h5
-rw-r--r--src/yuzu_cmd/yuzu.cpp3
145 files changed, 4100 insertions, 2298 deletions
diff --git a/src/audio_core/audio_renderer.h b/src/audio_core/audio_renderer.h
index 046417da3..71ba4be40 100644
--- a/src/audio_core/audio_renderer.h
+++ b/src/audio_core/audio_renderer.h
@@ -143,7 +143,7 @@ struct AuxInfo {
143 std::array<u8, 24> output_mix_buffers; 143 std::array<u8, 24> output_mix_buffers;
144 u32_le mix_buffer_count; 144 u32_le mix_buffer_count;
145 u32_le sample_rate; // Stored in the aux buffer currently 145 u32_le sample_rate; // Stored in the aux buffer currently
146 u32_le sampe_count; 146 u32_le sample_count;
147 u64_le send_buffer_info; 147 u64_le send_buffer_info;
148 u64_le send_buffer_base; 148 u64_le send_buffer_base;
149 149
diff --git a/src/audio_core/stream.cpp b/src/audio_core/stream.cpp
index 742a5e0a0..f35628e45 100644
--- a/src/audio_core/stream.cpp
+++ b/src/audio_core/stream.cpp
@@ -11,7 +11,6 @@
11#include "audio_core/stream.h" 11#include "audio_core/stream.h"
12#include "common/assert.h" 12#include "common/assert.h"
13#include "common/logging/log.h" 13#include "common/logging/log.h"
14#include "common/microprofile.h"
15#include "core/core_timing.h" 14#include "core/core_timing.h"
16#include "core/core_timing_util.h" 15#include "core/core_timing_util.h"
17#include "core/settings.h" 16#include "core/settings.h"
@@ -104,10 +103,7 @@ void Stream::PlayNextBuffer() {
104 CoreTiming::ScheduleEventThreadsafe(GetBufferReleaseCycles(*active_buffer), release_event, {}); 103 CoreTiming::ScheduleEventThreadsafe(GetBufferReleaseCycles(*active_buffer), release_event, {});
105} 104}
106 105
107MICROPROFILE_DEFINE(AudioOutput, "Audio", "ReleaseActiveBuffer", MP_RGB(100, 100, 255));
108
109void Stream::ReleaseActiveBuffer() { 106void Stream::ReleaseActiveBuffer() {
110 MICROPROFILE_SCOPE(AudioOutput);
111 ASSERT(active_buffer); 107 ASSERT(active_buffer);
112 released_buffers.push(std::move(active_buffer)); 108 released_buffers.push(std::move(active_buffer));
113 release_callback(); 109 release_callback();
diff --git a/src/audio_core/time_stretch.cpp b/src/audio_core/time_stretch.cpp
index cee8b12dd..2fe0b3aef 100644
--- a/src/audio_core/time_stretch.cpp
+++ b/src/audio_core/time_stretch.cpp
@@ -32,10 +32,10 @@ std::size_t TimeStretcher::Process(const s16* in, std::size_t num_in, s16* out,
32 // We were given actual_samples number of samples, and num_samples were requested from us. 32 // We were given actual_samples number of samples, and num_samples were requested from us.
33 double current_ratio = static_cast<double>(num_in) / static_cast<double>(num_out); 33 double current_ratio = static_cast<double>(num_in) / static_cast<double>(num_out);
34 34
35 const double max_latency = 1.0; // seconds 35 const double max_latency = 0.25; // seconds
36 const double max_backlog = m_sample_rate * max_latency; 36 const double max_backlog = m_sample_rate * max_latency;
37 const double backlog_fullness = m_sound_touch.numSamples() / max_backlog; 37 const double backlog_fullness = m_sound_touch.numSamples() / max_backlog;
38 if (backlog_fullness > 5.0) { 38 if (backlog_fullness > 4.0) {
39 // Too many samples in backlog: Don't push anymore on 39 // Too many samples in backlog: Don't push anymore on
40 num_in = 0; 40 num_in = 0;
41 } 41 }
@@ -49,7 +49,7 @@ std::size_t TimeStretcher::Process(const s16* in, std::size_t num_in, s16* out,
49 49
50 // This low-pass filter smoothes out variance in the calculated stretch ratio. 50 // This low-pass filter smoothes out variance in the calculated stretch ratio.
51 // The time-scale determines how responsive this filter is. 51 // The time-scale determines how responsive this filter is.
52 constexpr double lpf_time_scale = 2.0; // seconds 52 constexpr double lpf_time_scale = 0.712; // seconds
53 const double lpf_gain = 1.0 - std::exp(-time_delta / lpf_time_scale); 53 const double lpf_gain = 1.0 - std::exp(-time_delta / lpf_time_scale);
54 m_stretch_ratio += lpf_gain * (current_ratio - m_stretch_ratio); 54 m_stretch_ratio += lpf_gain * (current_ratio - m_stretch_ratio);
55 55
diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp
index 6d5218465..5753b871a 100644
--- a/src/common/logging/backend.cpp
+++ b/src/common/logging/backend.cpp
@@ -12,7 +12,8 @@
12#include <thread> 12#include <thread>
13#include <vector> 13#include <vector>
14#ifdef _WIN32 14#ifdef _WIN32
15#include <share.h> // For _SH_DENYWR 15#include <share.h> // For _SH_DENYWR
16#include <windows.h> // For OutputDebugStringA
16#else 17#else
17#define _SH_DENYWR 0 18#define _SH_DENYWR 0
18#endif 19#endif
@@ -139,12 +140,18 @@ void FileBackend::Write(const Entry& entry) {
139 if (!file.IsOpen() || bytes_written > MAX_BYTES_WRITTEN) { 140 if (!file.IsOpen() || bytes_written > MAX_BYTES_WRITTEN) {
140 return; 141 return;
141 } 142 }
142 bytes_written += file.WriteString(FormatLogMessage(entry) + '\n'); 143 bytes_written += file.WriteString(FormatLogMessage(entry).append(1, '\n'));
143 if (entry.log_level >= Level::Error) { 144 if (entry.log_level >= Level::Error) {
144 file.Flush(); 145 file.Flush();
145 } 146 }
146} 147}
147 148
149void DebuggerBackend::Write(const Entry& entry) {
150#ifdef _WIN32
151 ::OutputDebugStringA(FormatLogMessage(entry).append(1, '\n').c_str());
152#endif
153}
154
148/// Macro listing all log classes. Code should define CLS and SUB as desired before invoking this. 155/// Macro listing all log classes. Code should define CLS and SUB as desired before invoking this.
149#define ALL_LOG_CLASSES() \ 156#define ALL_LOG_CLASSES() \
150 CLS(Log) \ 157 CLS(Log) \
diff --git a/src/common/logging/backend.h b/src/common/logging/backend.h
index 11edbf1b6..91bb0c309 100644
--- a/src/common/logging/backend.h
+++ b/src/common/logging/backend.h
@@ -103,6 +103,20 @@ private:
103 std::size_t bytes_written; 103 std::size_t bytes_written;
104}; 104};
105 105
106/**
107 * Backend that writes to Visual Studio's output window
108 */
109class DebuggerBackend : public Backend {
110public:
111 static const char* Name() {
112 return "debugger";
113 }
114 const char* GetName() const override {
115 return Name();
116 }
117 void Write(const Entry& entry) override;
118};
119
106void AddBackend(std::unique_ptr<Backend> backend); 120void AddBackend(std::unique_ptr<Backend> backend);
107 121
108void RemoveBackend(std::string_view backend_name); 122void RemoveBackend(std::string_view backend_name);
diff --git a/src/common/string_util.cpp b/src/common/string_util.cpp
index 731d1db34..14f7037d8 100644
--- a/src/common/string_util.cpp
+++ b/src/common/string_util.cpp
@@ -4,11 +4,10 @@
4 4
5#include <algorithm> 5#include <algorithm>
6#include <cctype> 6#include <cctype>
7#include <cerrno>
8#include <codecvt> 7#include <codecvt>
9#include <cstdio>
10#include <cstdlib> 8#include <cstdlib>
11#include <cstring> 9#include <locale>
10#include <sstream>
12#include "common/common_paths.h" 11#include "common/common_paths.h"
13#include "common/logging/log.h" 12#include "common/logging/log.h"
14#include "common/string_util.h" 13#include "common/string_util.h"
@@ -33,24 +32,6 @@ std::string ToUpper(std::string str) {
33 return str; 32 return str;
34} 33}
35 34
36// For Debugging. Read out an u8 array.
37std::string ArrayToString(const u8* data, std::size_t size, int line_len, bool spaces) {
38 std::ostringstream oss;
39 oss << std::setfill('0') << std::hex;
40
41 for (int line = 0; size; ++data, --size) {
42 oss << std::setw(2) << (int)*data;
43
44 if (line_len == ++line) {
45 oss << '\n';
46 line = 0;
47 } else if (spaces)
48 oss << ' ';
49 }
50
51 return oss.str();
52}
53
54std::string StringFromBuffer(const std::vector<u8>& data) { 35std::string StringFromBuffer(const std::vector<u8>& data) {
55 return std::string(data.begin(), std::find(data.begin(), data.end(), '\0')); 36 return std::string(data.begin(), std::find(data.begin(), data.end(), '\0'));
56} 37}
@@ -75,40 +56,6 @@ std::string StripQuotes(const std::string& s) {
75 return s; 56 return s;
76} 57}
77 58
78bool TryParse(const std::string& str, u32* const output) {
79 char* endptr = nullptr;
80
81 // Reset errno to a value other than ERANGE
82 errno = 0;
83
84 unsigned long value = strtoul(str.c_str(), &endptr, 0);
85
86 if (!endptr || *endptr)
87 return false;
88
89 if (errno == ERANGE)
90 return false;
91
92#if ULONG_MAX > UINT_MAX
93 if (value >= 0x100000000ull && value <= 0xFFFFFFFF00000000ull)
94 return false;
95#endif
96
97 *output = static_cast<u32>(value);
98 return true;
99}
100
101bool TryParse(const std::string& str, bool* const output) {
102 if ("1" == str || "true" == ToLower(str))
103 *output = true;
104 else if ("0" == str || "false" == ToLower(str))
105 *output = false;
106 else
107 return false;
108
109 return true;
110}
111
112std::string StringFromBool(bool value) { 59std::string StringFromBool(bool value) {
113 return value ? "True" : "False"; 60 return value ? "True" : "False";
114} 61}
diff --git a/src/common/string_util.h b/src/common/string_util.h
index 32bf6a19c..08f96533b 100644
--- a/src/common/string_util.h
+++ b/src/common/string_util.h
@@ -5,8 +5,6 @@
5#pragma once 5#pragma once
6 6
7#include <cstddef> 7#include <cstddef>
8#include <iomanip>
9#include <sstream>
10#include <string> 8#include <string>
11#include <vector> 9#include <vector>
12#include "common/common_types.h" 10#include "common/common_types.h"
@@ -19,44 +17,13 @@ std::string ToLower(std::string str);
19/// Make a string uppercase 17/// Make a string uppercase
20std::string ToUpper(std::string str); 18std::string ToUpper(std::string str);
21 19
22std::string ArrayToString(const u8* data, std::size_t size, int line_len = 20, bool spaces = true);
23
24std::string StringFromBuffer(const std::vector<u8>& data); 20std::string StringFromBuffer(const std::vector<u8>& data);
25 21
26std::string StripSpaces(const std::string& s); 22std::string StripSpaces(const std::string& s);
27std::string StripQuotes(const std::string& s); 23std::string StripQuotes(const std::string& s);
28 24
29// Thousand separator. Turns 12345678 into 12,345,678
30template <typename I>
31std::string ThousandSeparate(I value, int spaces = 0) {
32 std::ostringstream oss;
33
34// std::locale("") seems to be broken on many platforms
35#if defined _WIN32 || (defined __linux__ && !defined __clang__)
36 oss.imbue(std::locale(""));
37#endif
38 oss << std::setw(spaces) << value;
39
40 return oss.str();
41}
42
43std::string StringFromBool(bool value); 25std::string StringFromBool(bool value);
44 26
45bool TryParse(const std::string& str, bool* output);
46bool TryParse(const std::string& str, u32* output);
47
48template <typename N>
49static bool TryParse(const std::string& str, N* const output) {
50 std::istringstream iss(str);
51
52 N tmp = 0;
53 if (iss >> tmp) {
54 *output = tmp;
55 return true;
56 } else
57 return false;
58}
59
60std::string TabsToSpaces(int tab_size, std::string in); 27std::string TabsToSpaces(int tab_size, std::string in);
61 28
62void SplitString(const std::string& str, char delim, std::vector<std::string>& output); 29void SplitString(const std::string& str, char delim, std::vector<std::string>& output);
diff --git a/src/common/telemetry.h b/src/common/telemetry.h
index 8d6ab986b..854a73fae 100644
--- a/src/common/telemetry.h
+++ b/src/common/telemetry.h
@@ -153,6 +153,7 @@ struct VisitorInterface : NonCopyable {
153 153
154 /// Completion method, called once all fields have been visited 154 /// Completion method, called once all fields have been visited
155 virtual void Complete() = 0; 155 virtual void Complete() = 0;
156 virtual bool SubmitTestcase() = 0;
156}; 157};
157 158
158/** 159/**
@@ -178,6 +179,9 @@ struct NullVisitor : public VisitorInterface {
178 void Visit(const Field<std::chrono::microseconds>& /*field*/) override {} 179 void Visit(const Field<std::chrono::microseconds>& /*field*/) override {}
179 180
180 void Complete() override {} 181 void Complete() override {}
182 bool SubmitTestcase() override {
183 return false;
184 }
181}; 185};
182 186
183/// Appends build-specific information to the given FieldCollection, 187/// Appends build-specific information to the given FieldCollection,
diff --git a/src/core/core.cpp b/src/core/core.cpp
index 7cb86ed92..6d5b5a2d0 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -185,7 +185,7 @@ struct System::Impl {
185 LOG_CRITICAL(Core, "Failed to obtain loader for {}!", filepath); 185 LOG_CRITICAL(Core, "Failed to obtain loader for {}!", filepath);
186 return ResultStatus::ErrorGetLoader; 186 return ResultStatus::ErrorGetLoader;
187 } 187 }
188 std::pair<boost::optional<u32>, Loader::ResultStatus> system_mode = 188 std::pair<std::optional<u32>, Loader::ResultStatus> system_mode =
189 app_loader->LoadKernelSystemMode(); 189 app_loader->LoadKernelSystemMode();
190 190
191 if (system_mode.second != Loader::ResultStatus::Success) { 191 if (system_mode.second != Loader::ResultStatus::Success) {
@@ -312,6 +312,10 @@ Cpu& System::CurrentCpuCore() {
312 return impl->CurrentCpuCore(); 312 return impl->CurrentCpuCore();
313} 313}
314 314
315const Cpu& System::CurrentCpuCore() const {
316 return impl->CurrentCpuCore();
317}
318
315System::ResultStatus System::RunLoop(bool tight_loop) { 319System::ResultStatus System::RunLoop(bool tight_loop) {
316 return impl->RunLoop(tight_loop); 320 return impl->RunLoop(tight_loop);
317} 321}
@@ -342,7 +346,11 @@ PerfStatsResults System::GetAndResetPerfStats() {
342 return impl->GetAndResetPerfStats(); 346 return impl->GetAndResetPerfStats();
343} 347}
344 348
345Core::TelemetrySession& System::TelemetrySession() const { 349TelemetrySession& System::TelemetrySession() {
350 return *impl->telemetry_session;
351}
352
353const TelemetrySession& System::TelemetrySession() const {
346 return *impl->telemetry_session; 354 return *impl->telemetry_session;
347} 355}
348 356
@@ -350,7 +358,11 @@ ARM_Interface& System::CurrentArmInterface() {
350 return CurrentCpuCore().ArmInterface(); 358 return CurrentCpuCore().ArmInterface();
351} 359}
352 360
353std::size_t System::CurrentCoreIndex() { 361const ARM_Interface& System::CurrentArmInterface() const {
362 return CurrentCpuCore().ArmInterface();
363}
364
365std::size_t System::CurrentCoreIndex() const {
354 return CurrentCpuCore().CoreIndex(); 366 return CurrentCpuCore().CoreIndex();
355} 367}
356 368
@@ -358,6 +370,10 @@ Kernel::Scheduler& System::CurrentScheduler() {
358 return CurrentCpuCore().Scheduler(); 370 return CurrentCpuCore().Scheduler();
359} 371}
360 372
373const Kernel::Scheduler& System::CurrentScheduler() const {
374 return CurrentCpuCore().Scheduler();
375}
376
361Kernel::Scheduler& System::Scheduler(std::size_t core_index) { 377Kernel::Scheduler& System::Scheduler(std::size_t core_index) {
362 return CpuCore(core_index).Scheduler(); 378 return CpuCore(core_index).Scheduler();
363} 379}
@@ -378,6 +394,10 @@ ARM_Interface& System::ArmInterface(std::size_t core_index) {
378 return CpuCore(core_index).ArmInterface(); 394 return CpuCore(core_index).ArmInterface();
379} 395}
380 396
397const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
398 return CpuCore(core_index).ArmInterface();
399}
400
381Cpu& System::CpuCore(std::size_t core_index) { 401Cpu& System::CpuCore(std::size_t core_index) {
382 ASSERT(core_index < NUM_CPU_CORES); 402 ASSERT(core_index < NUM_CPU_CORES);
383 return *impl->cpu_cores[core_index]; 403 return *impl->cpu_cores[core_index];
@@ -392,6 +412,10 @@ ExclusiveMonitor& System::Monitor() {
392 return *impl->cpu_exclusive_monitor; 412 return *impl->cpu_exclusive_monitor;
393} 413}
394 414
415const ExclusiveMonitor& System::Monitor() const {
416 return *impl->cpu_exclusive_monitor;
417}
418
395Tegra::GPU& System::GPU() { 419Tegra::GPU& System::GPU() {
396 return *impl->gpu_core; 420 return *impl->gpu_core;
397} 421}
diff --git a/src/core/core.h b/src/core/core.h
index 173be45f8..cfacceb81 100644
--- a/src/core/core.h
+++ b/src/core/core.h
@@ -129,11 +129,11 @@ public:
129 */ 129 */
130 bool IsPoweredOn() const; 130 bool IsPoweredOn() const;
131 131
132 /** 132 /// Gets a reference to the telemetry session for this emulation session.
133 * Returns a reference to the telemetry session for this emulation session. 133 Core::TelemetrySession& TelemetrySession();
134 * @returns Reference to the telemetry session. 134
135 */ 135 /// Gets a reference to the telemetry session for this emulation session.
136 Core::TelemetrySession& TelemetrySession() const; 136 const Core::TelemetrySession& TelemetrySession() const;
137 137
138 /// Prepare the core emulation for a reschedule 138 /// Prepare the core emulation for a reschedule
139 void PrepareReschedule(); 139 void PrepareReschedule();
@@ -144,24 +144,36 @@ public:
144 /// Gets an ARM interface to the CPU core that is currently running 144 /// Gets an ARM interface to the CPU core that is currently running
145 ARM_Interface& CurrentArmInterface(); 145 ARM_Interface& CurrentArmInterface();
146 146
147 /// Gets an ARM interface to the CPU core that is currently running
148 const ARM_Interface& CurrentArmInterface() const;
149
147 /// Gets the index of the currently running CPU core 150 /// Gets the index of the currently running CPU core
148 std::size_t CurrentCoreIndex(); 151 std::size_t CurrentCoreIndex() const;
149 152
150 /// Gets the scheduler for the CPU core that is currently running 153 /// Gets the scheduler for the CPU core that is currently running
151 Kernel::Scheduler& CurrentScheduler(); 154 Kernel::Scheduler& CurrentScheduler();
152 155
153 /// Gets an ARM interface to the CPU core with the specified index 156 /// Gets the scheduler for the CPU core that is currently running
157 const Kernel::Scheduler& CurrentScheduler() const;
158
159 /// Gets a reference to an ARM interface for the CPU core with the specified index
154 ARM_Interface& ArmInterface(std::size_t core_index); 160 ARM_Interface& ArmInterface(std::size_t core_index);
155 161
162 /// Gets a const reference to an ARM interface from the CPU core with the specified index
163 const ARM_Interface& ArmInterface(std::size_t core_index) const;
164
156 /// Gets a CPU interface to the CPU core with the specified index 165 /// Gets a CPU interface to the CPU core with the specified index
157 Cpu& CpuCore(std::size_t core_index); 166 Cpu& CpuCore(std::size_t core_index);
158 167
159 /// Gets a CPU interface to the CPU core with the specified index 168 /// Gets a CPU interface to the CPU core with the specified index
160 const Cpu& CpuCore(std::size_t core_index) const; 169 const Cpu& CpuCore(std::size_t core_index) const;
161 170
162 /// Gets the exclusive monitor 171 /// Gets a reference to the exclusive monitor
163 ExclusiveMonitor& Monitor(); 172 ExclusiveMonitor& Monitor();
164 173
174 /// Gets a constant reference to the exclusive monitor
175 const ExclusiveMonitor& Monitor() const;
176
165 /// Gets a mutable reference to the GPU interface 177 /// Gets a mutable reference to the GPU interface
166 Tegra::GPU& GPU(); 178 Tegra::GPU& GPU();
167 179
@@ -230,6 +242,9 @@ private:
230 /// Returns the currently running CPU core 242 /// Returns the currently running CPU core
231 Cpu& CurrentCpuCore(); 243 Cpu& CurrentCpuCore();
232 244
245 /// Returns the currently running CPU core
246 const Cpu& CurrentCpuCore() const;
247
233 /** 248 /**
234 * Initialize the emulated system. 249 * Initialize the emulated system.
235 * @param emu_window Reference to the host-system window used for video output and keyboard 250 * @param emu_window Reference to the host-system window used for video output and keyboard
diff --git a/src/core/crypto/key_manager.cpp b/src/core/crypto/key_manager.cpp
index 89ae79eb3..904afa039 100644
--- a/src/core/crypto/key_manager.cpp
+++ b/src/core/crypto/key_manager.cpp
@@ -141,28 +141,28 @@ Key128 DeriveKeyblobMACKey(const Key128& keyblob_key, const Key128& mac_source)
141 return mac_key; 141 return mac_key;
142} 142}
143 143
144boost::optional<Key128> DeriveSDSeed() { 144std::optional<Key128> DeriveSDSeed() {
145 const FileUtil::IOFile save_43(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) + 145 const FileUtil::IOFile save_43(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
146 "/system/save/8000000000000043", 146 "/system/save/8000000000000043",
147 "rb+"); 147 "rb+");
148 if (!save_43.IsOpen()) 148 if (!save_43.IsOpen())
149 return boost::none; 149 return {};
150 150
151 const FileUtil::IOFile sd_private( 151 const FileUtil::IOFile sd_private(
152 FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir) + "/Nintendo/Contents/private", "rb+"); 152 FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir) + "/Nintendo/Contents/private", "rb+");
153 if (!sd_private.IsOpen()) 153 if (!sd_private.IsOpen())
154 return boost::none; 154 return {};
155 155
156 std::array<u8, 0x10> private_seed{}; 156 std::array<u8, 0x10> private_seed{};
157 if (sd_private.ReadBytes(private_seed.data(), private_seed.size()) != private_seed.size()) { 157 if (sd_private.ReadBytes(private_seed.data(), private_seed.size()) != private_seed.size()) {
158 return boost::none; 158 return {};
159 } 159 }
160 160
161 std::array<u8, 0x10> buffer{}; 161 std::array<u8, 0x10> buffer{};
162 std::size_t offset = 0; 162 std::size_t offset = 0;
163 for (; offset + 0x10 < save_43.GetSize(); ++offset) { 163 for (; offset + 0x10 < save_43.GetSize(); ++offset) {
164 if (!save_43.Seek(offset, SEEK_SET)) { 164 if (!save_43.Seek(offset, SEEK_SET)) {
165 return boost::none; 165 return {};
166 } 166 }
167 167
168 save_43.ReadBytes(buffer.data(), buffer.size()); 168 save_43.ReadBytes(buffer.data(), buffer.size());
@@ -172,12 +172,12 @@ boost::optional<Key128> DeriveSDSeed() {
172 } 172 }
173 173
174 if (!save_43.Seek(offset + 0x10, SEEK_SET)) { 174 if (!save_43.Seek(offset + 0x10, SEEK_SET)) {
175 return boost::none; 175 return {};
176 } 176 }
177 177
178 Key128 seed{}; 178 Key128 seed{};
179 if (save_43.ReadBytes(seed.data(), seed.size()) != seed.size()) { 179 if (save_43.ReadBytes(seed.data(), seed.size()) != seed.size()) {
180 return boost::none; 180 return {};
181 } 181 }
182 return seed; 182 return seed;
183} 183}
@@ -291,26 +291,26 @@ static std::array<u8, target_size> MGF1(const std::array<u8, in_size>& seed) {
291} 291}
292 292
293template <size_t size> 293template <size_t size>
294static boost::optional<u64> FindTicketOffset(const std::array<u8, size>& data) { 294static std::optional<u64> FindTicketOffset(const std::array<u8, size>& data) {
295 u64 offset = 0; 295 u64 offset = 0;
296 for (size_t i = 0x20; i < data.size() - 0x10; ++i) { 296 for (size_t i = 0x20; i < data.size() - 0x10; ++i) {
297 if (data[i] == 0x1) { 297 if (data[i] == 0x1) {
298 offset = i + 1; 298 offset = i + 1;
299 break; 299 break;
300 } else if (data[i] != 0x0) { 300 } else if (data[i] != 0x0) {
301 return boost::none; 301 return {};
302 } 302 }
303 } 303 }
304 304
305 return offset; 305 return offset;
306} 306}
307 307
308boost::optional<std::pair<Key128, Key128>> ParseTicket(const TicketRaw& ticket, 308std::optional<std::pair<Key128, Key128>> ParseTicket(const TicketRaw& ticket,
309 const RSAKeyPair<2048>& key) { 309 const RSAKeyPair<2048>& key) {
310 u32 cert_authority; 310 u32 cert_authority;
311 std::memcpy(&cert_authority, ticket.data() + 0x140, sizeof(cert_authority)); 311 std::memcpy(&cert_authority, ticket.data() + 0x140, sizeof(cert_authority));
312 if (cert_authority == 0) 312 if (cert_authority == 0)
313 return boost::none; 313 return {};
314 if (cert_authority != Common::MakeMagic('R', 'o', 'o', 't')) { 314 if (cert_authority != Common::MakeMagic('R', 'o', 'o', 't')) {
315 LOG_INFO(Crypto, 315 LOG_INFO(Crypto,
316 "Attempting to parse ticket with non-standard certificate authority {:08X}.", 316 "Attempting to parse ticket with non-standard certificate authority {:08X}.",
@@ -321,7 +321,7 @@ boost::optional<std::pair<Key128, Key128>> ParseTicket(const TicketRaw& ticket,
321 std::memcpy(rights_id.data(), ticket.data() + 0x2A0, sizeof(Key128)); 321 std::memcpy(rights_id.data(), ticket.data() + 0x2A0, sizeof(Key128));
322 322
323 if (rights_id == Key128{}) 323 if (rights_id == Key128{})
324 return boost::none; 324 return {};
325 325
326 Key128 key_temp{}; 326 Key128 key_temp{};
327 327
@@ -356,17 +356,17 @@ boost::optional<std::pair<Key128, Key128>> ParseTicket(const TicketRaw& ticket,
356 std::memcpy(m_2.data(), rsa_step.data() + 0x21, m_2.size()); 356 std::memcpy(m_2.data(), rsa_step.data() + 0x21, m_2.size());
357 357
358 if (m_0 != 0) 358 if (m_0 != 0)
359 return boost::none; 359 return {};
360 360
361 m_1 = m_1 ^ MGF1<0x20>(m_2); 361 m_1 = m_1 ^ MGF1<0x20>(m_2);
362 m_2 = m_2 ^ MGF1<0xDF>(m_1); 362 m_2 = m_2 ^ MGF1<0xDF>(m_1);
363 363
364 const auto offset = FindTicketOffset(m_2); 364 const auto offset = FindTicketOffset(m_2);
365 if (offset == boost::none) 365 if (!offset)
366 return boost::none; 366 return {};
367 ASSERT(offset.get() > 0); 367 ASSERT(*offset > 0);
368 368
369 std::memcpy(key_temp.data(), m_2.data() + offset.get(), key_temp.size()); 369 std::memcpy(key_temp.data(), m_2.data() + *offset, key_temp.size());
370 370
371 return std::make_pair(rights_id, key_temp); 371 return std::make_pair(rights_id, key_temp);
372} 372}
@@ -661,8 +661,8 @@ void KeyManager::DeriveSDSeedLazy() {
661 return; 661 return;
662 662
663 const auto res = DeriveSDSeed(); 663 const auto res = DeriveSDSeed();
664 if (res != boost::none) 664 if (res)
665 SetKey(S128KeyType::SDSeed, res.get()); 665 SetKey(S128KeyType::SDSeed, *res);
666} 666}
667 667
668static Key128 CalculateCMAC(const u8* source, size_t size, const Key128& key) { 668static Key128 CalculateCMAC(const u8* source, size_t size, const Key128& key) {
@@ -889,9 +889,9 @@ void KeyManager::DeriveETicket(PartitionDataManager& data) {
889 889
890 for (const auto& raw : res) { 890 for (const auto& raw : res) {
891 const auto pair = ParseTicket(raw, rsa_key); 891 const auto pair = ParseTicket(raw, rsa_key);
892 if (pair == boost::none) 892 if (!pair)
893 continue; 893 continue;
894 const auto& [rid, key] = pair.value(); 894 const auto& [rid, key] = *pair;
895 u128 rights_id; 895 u128 rights_id;
896 std::memcpy(rights_id.data(), rid.data(), rid.size()); 896 std::memcpy(rights_id.data(), rid.data(), rid.size());
897 SetKey(S128KeyType::Titlekey, key, rights_id[1], rights_id[0]); 897 SetKey(S128KeyType::Titlekey, key, rights_id[1], rights_id[0]);
diff --git a/src/core/crypto/key_manager.h b/src/core/crypto/key_manager.h
index cccb3c0ae..22f268c65 100644
--- a/src/core/crypto/key_manager.h
+++ b/src/core/crypto/key_manager.h
@@ -6,9 +6,10 @@
6 6
7#include <array> 7#include <array>
8#include <map> 8#include <map>
9#include <optional>
9#include <string> 10#include <string>
11
10#include <boost/container/flat_map.hpp> 12#include <boost/container/flat_map.hpp>
11#include <boost/optional.hpp>
12#include <fmt/format.h> 13#include <fmt/format.h>
13#include "common/common_types.h" 14#include "common/common_types.h"
14#include "core/crypto/partition_data_manager.h" 15#include "core/crypto/partition_data_manager.h"
@@ -191,14 +192,14 @@ Key128 DeriveMasterKey(const std::array<u8, 0x90>& keyblob, const Key128& master
191std::array<u8, 0x90> DecryptKeyblob(const std::array<u8, 0xB0>& encrypted_keyblob, 192std::array<u8, 0x90> DecryptKeyblob(const std::array<u8, 0xB0>& encrypted_keyblob,
192 const Key128& key); 193 const Key128& key);
193 194
194boost::optional<Key128> DeriveSDSeed(); 195std::optional<Key128> DeriveSDSeed();
195Loader::ResultStatus DeriveSDKeys(std::array<Key256, 2>& sd_keys, KeyManager& keys); 196Loader::ResultStatus DeriveSDKeys(std::array<Key256, 2>& sd_keys, KeyManager& keys);
196 197
197std::vector<TicketRaw> GetTicketblob(const FileUtil::IOFile& ticket_save); 198std::vector<TicketRaw> GetTicketblob(const FileUtil::IOFile& ticket_save);
198 199
199// Returns a pair of {rights_id, titlekey}. Fails if the ticket has no certificate authority (offset 200// Returns a pair of {rights_id, titlekey}. Fails if the ticket has no certificate authority (offset
200// 0x140-0x144 is zero) 201// 0x140-0x144 is zero)
201boost::optional<std::pair<Key128, Key128>> ParseTicket( 202std::optional<std::pair<Key128, Key128>> ParseTicket(const TicketRaw& ticket,
202 const TicketRaw& ticket, const RSAKeyPair<2048>& eticket_extended_key); 203 const RSAKeyPair<2048>& eticket_extended_key);
203 204
204} // namespace Core::Crypto 205} // namespace Core::Crypto
diff --git a/src/core/file_sys/content_archive.cpp b/src/core/file_sys/content_archive.cpp
index 77e04704e..b46fe893c 100644
--- a/src/core/file_sys/content_archive.cpp
+++ b/src/core/file_sys/content_archive.cpp
@@ -4,10 +4,9 @@
4 4
5#include <algorithm> 5#include <algorithm>
6#include <cstring> 6#include <cstring>
7#include <optional>
7#include <utility> 8#include <utility>
8 9
9#include <boost/optional.hpp>
10
11#include "common/logging/log.h" 10#include "common/logging/log.h"
12#include "core/crypto/aes_util.h" 11#include "core/crypto/aes_util.h"
13#include "core/crypto/ctr_encryption_layer.h" 12#include "core/crypto/ctr_encryption_layer.h"
@@ -306,18 +305,18 @@ bool NCA::ReadRomFSSection(const NCASectionHeader& section, const NCASectionTabl
306 subsection_buckets.back().entries.push_back({section.bktr.relocation.offset, {0}, ctr_low}); 305 subsection_buckets.back().entries.push_back({section.bktr.relocation.offset, {0}, ctr_low});
307 subsection_buckets.back().entries.push_back({size, {0}, 0}); 306 subsection_buckets.back().entries.push_back({size, {0}, 0});
308 307
309 boost::optional<Core::Crypto::Key128> key = boost::none; 308 std::optional<Core::Crypto::Key128> key = {};
310 if (encrypted) { 309 if (encrypted) {
311 if (has_rights_id) { 310 if (has_rights_id) {
312 status = Loader::ResultStatus::Success; 311 status = Loader::ResultStatus::Success;
313 key = GetTitlekey(); 312 key = GetTitlekey();
314 if (key == boost::none) { 313 if (!key) {
315 status = Loader::ResultStatus::ErrorMissingTitlekey; 314 status = Loader::ResultStatus::ErrorMissingTitlekey;
316 return false; 315 return false;
317 } 316 }
318 } else { 317 } else {
319 key = GetKeyAreaKey(NCASectionCryptoType::BKTR); 318 key = GetKeyAreaKey(NCASectionCryptoType::BKTR);
320 if (key == boost::none) { 319 if (!key) {
321 status = Loader::ResultStatus::ErrorMissingKeyAreaKey; 320 status = Loader::ResultStatus::ErrorMissingKeyAreaKey;
322 return false; 321 return false;
323 } 322 }
@@ -332,7 +331,7 @@ bool NCA::ReadRomFSSection(const NCASectionHeader& section, const NCASectionTabl
332 auto bktr = std::make_shared<BKTR>( 331 auto bktr = std::make_shared<BKTR>(
333 bktr_base_romfs, std::make_shared<OffsetVfsFile>(file, romfs_size, base_offset), 332 bktr_base_romfs, std::make_shared<OffsetVfsFile>(file, romfs_size, base_offset),
334 relocation_block, relocation_buckets, subsection_block, subsection_buckets, encrypted, 333 relocation_block, relocation_buckets, subsection_block, subsection_buckets, encrypted,
335 encrypted ? key.get() : Core::Crypto::Key128{}, base_offset, bktr_base_ivfc_offset, 334 encrypted ? *key : Core::Crypto::Key128{}, base_offset, bktr_base_ivfc_offset,
336 section.raw.section_ctr); 335 section.raw.section_ctr);
337 336
338 // BKTR applies to entire IVFC, so make an offset version to level 6 337 // BKTR applies to entire IVFC, so make an offset version to level 6
@@ -388,11 +387,11 @@ u8 NCA::GetCryptoRevision() const {
388 return master_key_id; 387 return master_key_id;
389} 388}
390 389
391boost::optional<Core::Crypto::Key128> NCA::GetKeyAreaKey(NCASectionCryptoType type) const { 390std::optional<Core::Crypto::Key128> NCA::GetKeyAreaKey(NCASectionCryptoType type) const {
392 const auto master_key_id = GetCryptoRevision(); 391 const auto master_key_id = GetCryptoRevision();
393 392
394 if (!keys.HasKey(Core::Crypto::S128KeyType::KeyArea, master_key_id, header.key_index)) 393 if (!keys.HasKey(Core::Crypto::S128KeyType::KeyArea, master_key_id, header.key_index))
395 return boost::none; 394 return {};
396 395
397 std::vector<u8> key_area(header.key_area.begin(), header.key_area.end()); 396 std::vector<u8> key_area(header.key_area.begin(), header.key_area.end());
398 Core::Crypto::AESCipher<Core::Crypto::Key128> cipher( 397 Core::Crypto::AESCipher<Core::Crypto::Key128> cipher(
@@ -416,25 +415,25 @@ boost::optional<Core::Crypto::Key128> NCA::GetKeyAreaKey(NCASectionCryptoType ty
416 return out; 415 return out;
417} 416}
418 417
419boost::optional<Core::Crypto::Key128> NCA::GetTitlekey() { 418std::optional<Core::Crypto::Key128> NCA::GetTitlekey() {
420 const auto master_key_id = GetCryptoRevision(); 419 const auto master_key_id = GetCryptoRevision();
421 420
422 u128 rights_id{}; 421 u128 rights_id{};
423 memcpy(rights_id.data(), header.rights_id.data(), 16); 422 memcpy(rights_id.data(), header.rights_id.data(), 16);
424 if (rights_id == u128{}) { 423 if (rights_id == u128{}) {
425 status = Loader::ResultStatus::ErrorInvalidRightsID; 424 status = Loader::ResultStatus::ErrorInvalidRightsID;
426 return boost::none; 425 return {};
427 } 426 }
428 427
429 auto titlekey = keys.GetKey(Core::Crypto::S128KeyType::Titlekey, rights_id[1], rights_id[0]); 428 auto titlekey = keys.GetKey(Core::Crypto::S128KeyType::Titlekey, rights_id[1], rights_id[0]);
430 if (titlekey == Core::Crypto::Key128{}) { 429 if (titlekey == Core::Crypto::Key128{}) {
431 status = Loader::ResultStatus::ErrorMissingTitlekey; 430 status = Loader::ResultStatus::ErrorMissingTitlekey;
432 return boost::none; 431 return {};
433 } 432 }
434 433
435 if (!keys.HasKey(Core::Crypto::S128KeyType::Titlekek, master_key_id)) { 434 if (!keys.HasKey(Core::Crypto::S128KeyType::Titlekek, master_key_id)) {
436 status = Loader::ResultStatus::ErrorMissingTitlekek; 435 status = Loader::ResultStatus::ErrorMissingTitlekek;
437 return boost::none; 436 return {};
438 } 437 }
439 438
440 Core::Crypto::AESCipher<Core::Crypto::Key128> cipher( 439 Core::Crypto::AESCipher<Core::Crypto::Key128> cipher(
@@ -458,25 +457,25 @@ VirtualFile NCA::Decrypt(const NCASectionHeader& s_header, VirtualFile in, u64 s
458 case NCASectionCryptoType::BKTR: 457 case NCASectionCryptoType::BKTR:
459 LOG_DEBUG(Crypto, "called with mode=CTR, starting_offset={:016X}", starting_offset); 458 LOG_DEBUG(Crypto, "called with mode=CTR, starting_offset={:016X}", starting_offset);
460 { 459 {
461 boost::optional<Core::Crypto::Key128> key = boost::none; 460 std::optional<Core::Crypto::Key128> key = {};
462 if (has_rights_id) { 461 if (has_rights_id) {
463 status = Loader::ResultStatus::Success; 462 status = Loader::ResultStatus::Success;
464 key = GetTitlekey(); 463 key = GetTitlekey();
465 if (key == boost::none) { 464 if (!key) {
466 if (status == Loader::ResultStatus::Success) 465 if (status == Loader::ResultStatus::Success)
467 status = Loader::ResultStatus::ErrorMissingTitlekey; 466 status = Loader::ResultStatus::ErrorMissingTitlekey;
468 return nullptr; 467 return nullptr;
469 } 468 }
470 } else { 469 } else {
471 key = GetKeyAreaKey(NCASectionCryptoType::CTR); 470 key = GetKeyAreaKey(NCASectionCryptoType::CTR);
472 if (key == boost::none) { 471 if (!key) {
473 status = Loader::ResultStatus::ErrorMissingKeyAreaKey; 472 status = Loader::ResultStatus::ErrorMissingKeyAreaKey;
474 return nullptr; 473 return nullptr;
475 } 474 }
476 } 475 }
477 476
478 auto out = std::make_shared<Core::Crypto::CTREncryptionLayer>( 477 auto out = std::make_shared<Core::Crypto::CTREncryptionLayer>(std::move(in), *key,
479 std::move(in), key.value(), starting_offset); 478 starting_offset);
480 std::vector<u8> iv(16); 479 std::vector<u8> iv(16);
481 for (u8 i = 0; i < 8; ++i) 480 for (u8 i = 0; i < 8; ++i)
482 iv[i] = s_header.raw.section_ctr[0x8 - i - 1]; 481 iv[i] = s_header.raw.section_ctr[0x8 - i - 1];
diff --git a/src/core/file_sys/content_archive.h b/src/core/file_sys/content_archive.h
index 211946686..4bba55607 100644
--- a/src/core/file_sys/content_archive.h
+++ b/src/core/file_sys/content_archive.h
@@ -6,9 +6,10 @@
6 6
7#include <array> 7#include <array>
8#include <memory> 8#include <memory>
9#include <optional>
9#include <string> 10#include <string>
10#include <vector> 11#include <vector>
11#include <boost/optional.hpp> 12
12#include "common/common_funcs.h" 13#include "common/common_funcs.h"
13#include "common/common_types.h" 14#include "common/common_types.h"
14#include "common/swap.h" 15#include "common/swap.h"
@@ -111,8 +112,8 @@ private:
111 bool ReadPFS0Section(const NCASectionHeader& section, const NCASectionTableEntry& entry); 112 bool ReadPFS0Section(const NCASectionHeader& section, const NCASectionTableEntry& entry);
112 113
113 u8 GetCryptoRevision() const; 114 u8 GetCryptoRevision() const;
114 boost::optional<Core::Crypto::Key128> GetKeyAreaKey(NCASectionCryptoType type) const; 115 std::optional<Core::Crypto::Key128> GetKeyAreaKey(NCASectionCryptoType type) const;
115 boost::optional<Core::Crypto::Key128> GetTitlekey(); 116 std::optional<Core::Crypto::Key128> GetTitlekey();
116 VirtualFile Decrypt(const NCASectionHeader& header, VirtualFile in, u64 starting_offset); 117 VirtualFile Decrypt(const NCASectionHeader& header, VirtualFile in, u64 starting_offset);
117 118
118 std::vector<VirtualDir> dirs; 119 std::vector<VirtualDir> dirs;
diff --git a/src/core/file_sys/control_metadata.cpp b/src/core/file_sys/control_metadata.cpp
index a012c2be9..c8fa912bf 100644
--- a/src/core/file_sys/control_metadata.cpp
+++ b/src/core/file_sys/control_metadata.cpp
@@ -66,4 +66,10 @@ std::string NACP::GetVersionString() const {
66 return Common::StringFromFixedZeroTerminatedBuffer(raw->version_string.data(), 66 return Common::StringFromFixedZeroTerminatedBuffer(raw->version_string.data(),
67 raw->version_string.size()); 67 raw->version_string.size());
68} 68}
69
70std::vector<u8> NACP::GetRawBytes() const {
71 std::vector<u8> out(sizeof(RawNACP));
72 std::memcpy(out.data(), raw.get(), sizeof(RawNACP));
73 return out;
74}
69} // namespace FileSys 75} // namespace FileSys
diff --git a/src/core/file_sys/control_metadata.h b/src/core/file_sys/control_metadata.h
index 141f7e056..bfaad46b4 100644
--- a/src/core/file_sys/control_metadata.h
+++ b/src/core/file_sys/control_metadata.h
@@ -81,6 +81,7 @@ public:
81 u64 GetTitleId() const; 81 u64 GetTitleId() const;
82 u64 GetDLCBaseTitleId() const; 82 u64 GetDLCBaseTitleId() const;
83 std::string GetVersionString() const; 83 std::string GetVersionString() const;
84 std::vector<u8> GetRawBytes() const;
84 85
85private: 86private:
86 std::unique_ptr<RawNACP> raw; 87 std::unique_ptr<RawNACP> raw;
diff --git a/src/core/file_sys/fsmitm_romfsbuild.h b/src/core/file_sys/fsmitm_romfsbuild.h
index 3d377b0af..a62502193 100644
--- a/src/core/file_sys/fsmitm_romfsbuild.h
+++ b/src/core/file_sys/fsmitm_romfsbuild.h
@@ -27,7 +27,6 @@
27#include <map> 27#include <map>
28#include <memory> 28#include <memory>
29#include <string> 29#include <string>
30#include <boost/detail/container_fwd.hpp>
31#include "common/common_types.h" 30#include "common/common_types.h"
32#include "core/file_sys/vfs.h" 31#include "core/file_sys/vfs.h"
33 32
diff --git a/src/core/file_sys/ips_layer.cpp b/src/core/file_sys/ips_layer.cpp
index 999939d5a..485c4913a 100644
--- a/src/core/file_sys/ips_layer.cpp
+++ b/src/core/file_sys/ips_layer.cpp
@@ -103,12 +103,12 @@ VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
103 offset += sizeof(u16); 103 offset += sizeof(u16);
104 104
105 const auto data = ips->ReadByte(offset++); 105 const auto data = ips->ReadByte(offset++);
106 if (data == boost::none) 106 if (!data)
107 return nullptr; 107 return nullptr;
108 108
109 if (real_offset + rle_size > in_data.size()) 109 if (real_offset + rle_size > in_data.size())
110 rle_size = static_cast<u16>(in_data.size() - real_offset); 110 rle_size = static_cast<u16>(in_data.size() - real_offset);
111 std::memset(in_data.data() + real_offset, data.get(), rle_size); 111 std::memset(in_data.data() + real_offset, *data, rle_size);
112 } else { // Standard Patch 112 } else { // Standard Patch
113 auto read = data_size; 113 auto read = data_size;
114 if (real_offset + read > in_data.size()) 114 if (real_offset + read > in_data.size())
diff --git a/src/core/file_sys/patch_manager.cpp b/src/core/file_sys/patch_manager.cpp
index 3a1623ca0..8d062eb3e 100644
--- a/src/core/file_sys/patch_manager.cpp
+++ b/src/core/file_sys/patch_manager.cpp
@@ -66,7 +66,7 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
66 if (update != nullptr && update->GetExeFS() != nullptr && 66 if (update != nullptr && update->GetExeFS() != nullptr &&
67 update->GetStatus() == Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) { 67 update->GetStatus() == Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
68 LOG_INFO(Loader, " ExeFS: Update ({}) applied successfully", 68 LOG_INFO(Loader, " ExeFS: Update ({}) applied successfully",
69 FormatTitleVersion(installed->GetEntryVersion(update_tid).get_value_or(0))); 69 FormatTitleVersion(installed->GetEntryVersion(update_tid).value_or(0)));
70 exefs = update->GetExeFS(); 70 exefs = update->GetExeFS();
71 } 71 }
72 72
@@ -249,7 +249,7 @@ VirtualFile PatchManager::PatchRomFS(VirtualFile romfs, u64 ivfc_offset, Content
249 if (new_nca->GetStatus() == Loader::ResultStatus::Success && 249 if (new_nca->GetStatus() == Loader::ResultStatus::Success &&
250 new_nca->GetRomFS() != nullptr) { 250 new_nca->GetRomFS() != nullptr) {
251 LOG_INFO(Loader, " RomFS: Update ({}) applied successfully", 251 LOG_INFO(Loader, " RomFS: Update ({}) applied successfully",
252 FormatTitleVersion(installed->GetEntryVersion(update_tid).get_value_or(0))); 252 FormatTitleVersion(installed->GetEntryVersion(update_tid).value_or(0)));
253 romfs = new_nca->GetRomFS(); 253 romfs = new_nca->GetRomFS();
254 } 254 }
255 } else if (update_raw != nullptr) { 255 } else if (update_raw != nullptr) {
@@ -293,12 +293,11 @@ std::map<std::string, std::string, std::less<>> PatchManager::GetPatchVersionNam
293 } else { 293 } else {
294 if (installed->HasEntry(update_tid, ContentRecordType::Program)) { 294 if (installed->HasEntry(update_tid, ContentRecordType::Program)) {
295 const auto meta_ver = installed->GetEntryVersion(update_tid); 295 const auto meta_ver = installed->GetEntryVersion(update_tid);
296 if (meta_ver == boost::none || meta_ver.get() == 0) { 296 if (meta_ver.value_or(0) == 0) {
297 out.insert_or_assign("Update", ""); 297 out.insert_or_assign("Update", "");
298 } else { 298 } else {
299 out.insert_or_assign( 299 out.insert_or_assign(
300 "Update", 300 "Update", FormatTitleVersion(*meta_ver, TitleVersionFormat::ThreeElements));
301 FormatTitleVersion(meta_ver.get(), TitleVersionFormat::ThreeElements));
302 } 301 }
303 } else if (update_raw != nullptr) { 302 } else if (update_raw != nullptr) {
304 out.insert_or_assign("Update", "PACKED"); 303 out.insert_or_assign("Update", "PACKED");
diff --git a/src/core/file_sys/registered_cache.cpp b/src/core/file_sys/registered_cache.cpp
index 29b100414..96302a241 100644
--- a/src/core/file_sys/registered_cache.cpp
+++ b/src/core/file_sys/registered_cache.cpp
@@ -159,28 +159,28 @@ VirtualFile RegisteredCache::GetFileAtID(NcaID id) const {
159 return file; 159 return file;
160} 160}
161 161
162static boost::optional<NcaID> CheckMapForContentRecord( 162static std::optional<NcaID> CheckMapForContentRecord(
163 const boost::container::flat_map<u64, CNMT>& map, u64 title_id, ContentRecordType type) { 163 const boost::container::flat_map<u64, CNMT>& map, u64 title_id, ContentRecordType type) {
164 if (map.find(title_id) == map.end()) 164 if (map.find(title_id) == map.end())
165 return boost::none; 165 return {};
166 166
167 const auto& cnmt = map.at(title_id); 167 const auto& cnmt = map.at(title_id);
168 168
169 const auto iter = std::find_if(cnmt.GetContentRecords().begin(), cnmt.GetContentRecords().end(), 169 const auto iter = std::find_if(cnmt.GetContentRecords().begin(), cnmt.GetContentRecords().end(),
170 [type](const ContentRecord& rec) { return rec.type == type; }); 170 [type](const ContentRecord& rec) { return rec.type == type; });
171 if (iter == cnmt.GetContentRecords().end()) 171 if (iter == cnmt.GetContentRecords().end())
172 return boost::none; 172 return {};
173 173
174 return boost::make_optional(iter->nca_id); 174 return std::make_optional(iter->nca_id);
175} 175}
176 176
177boost::optional<NcaID> RegisteredCache::GetNcaIDFromMetadata(u64 title_id, 177std::optional<NcaID> RegisteredCache::GetNcaIDFromMetadata(u64 title_id,
178 ContentRecordType type) const { 178 ContentRecordType type) const {
179 if (type == ContentRecordType::Meta && meta_id.find(title_id) != meta_id.end()) 179 if (type == ContentRecordType::Meta && meta_id.find(title_id) != meta_id.end())
180 return meta_id.at(title_id); 180 return meta_id.at(title_id);
181 181
182 const auto res1 = CheckMapForContentRecord(yuzu_meta, title_id, type); 182 const auto res1 = CheckMapForContentRecord(yuzu_meta, title_id, type);
183 if (res1 != boost::none) 183 if (res1)
184 return res1; 184 return res1;
185 return CheckMapForContentRecord(meta, title_id, type); 185 return CheckMapForContentRecord(meta, title_id, type);
186} 186}
@@ -283,17 +283,14 @@ bool RegisteredCache::HasEntry(RegisteredCacheEntry entry) const {
283 283
284VirtualFile RegisteredCache::GetEntryUnparsed(u64 title_id, ContentRecordType type) const { 284VirtualFile RegisteredCache::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
285 const auto id = GetNcaIDFromMetadata(title_id, type); 285 const auto id = GetNcaIDFromMetadata(title_id, type);
286 if (id == boost::none) 286 return id ? GetFileAtID(*id) : nullptr;
287 return nullptr;
288
289 return GetFileAtID(id.get());
290} 287}
291 288
292VirtualFile RegisteredCache::GetEntryUnparsed(RegisteredCacheEntry entry) const { 289VirtualFile RegisteredCache::GetEntryUnparsed(RegisteredCacheEntry entry) const {
293 return GetEntryUnparsed(entry.title_id, entry.type); 290 return GetEntryUnparsed(entry.title_id, entry.type);
294} 291}
295 292
296boost::optional<u32> RegisteredCache::GetEntryVersion(u64 title_id) const { 293std::optional<u32> RegisteredCache::GetEntryVersion(u64 title_id) const {
297 const auto meta_iter = meta.find(title_id); 294 const auto meta_iter = meta.find(title_id);
298 if (meta_iter != meta.end()) 295 if (meta_iter != meta.end())
299 return meta_iter->second.GetTitleVersion(); 296 return meta_iter->second.GetTitleVersion();
@@ -302,15 +299,12 @@ boost::optional<u32> RegisteredCache::GetEntryVersion(u64 title_id) const {
302 if (yuzu_meta_iter != yuzu_meta.end()) 299 if (yuzu_meta_iter != yuzu_meta.end())
303 return yuzu_meta_iter->second.GetTitleVersion(); 300 return yuzu_meta_iter->second.GetTitleVersion();
304 301
305 return boost::none; 302 return {};
306} 303}
307 304
308VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const { 305VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const {
309 const auto id = GetNcaIDFromMetadata(title_id, type); 306 const auto id = GetNcaIDFromMetadata(title_id, type);
310 if (id == boost::none) 307 return id ? parser(GetFileAtID(*id), *id) : nullptr;
311 return nullptr;
312
313 return parser(GetFileAtID(id.get()), id.get());
314} 308}
315 309
316VirtualFile RegisteredCache::GetEntryRaw(RegisteredCacheEntry entry) const { 310VirtualFile RegisteredCache::GetEntryRaw(RegisteredCacheEntry entry) const {
@@ -364,8 +358,8 @@ std::vector<RegisteredCacheEntry> RegisteredCache::ListEntries() const {
364} 358}
365 359
366std::vector<RegisteredCacheEntry> RegisteredCache::ListEntriesFilter( 360std::vector<RegisteredCacheEntry> RegisteredCache::ListEntriesFilter(
367 boost::optional<TitleType> title_type, boost::optional<ContentRecordType> record_type, 361 std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
368 boost::optional<u64> title_id) const { 362 std::optional<u64> title_id) const {
369 std::vector<RegisteredCacheEntry> out; 363 std::vector<RegisteredCacheEntry> out;
370 IterateAllMetadata<RegisteredCacheEntry>( 364 IterateAllMetadata<RegisteredCacheEntry>(
371 out, 365 out,
@@ -373,11 +367,11 @@ std::vector<RegisteredCacheEntry> RegisteredCache::ListEntriesFilter(
373 return RegisteredCacheEntry{c.GetTitleID(), r.type}; 367 return RegisteredCacheEntry{c.GetTitleID(), r.type};
374 }, 368 },
375 [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) { 369 [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
376 if (title_type != boost::none && title_type.get() != c.GetType()) 370 if (title_type && *title_type != c.GetType())
377 return false; 371 return false;
378 if (record_type != boost::none && record_type.get() != r.type) 372 if (record_type && *record_type != r.type)
379 return false; 373 return false;
380 if (title_id != boost::none && title_id.get() != c.GetTitleID()) 374 if (title_id && *title_id != c.GetTitleID())
381 return false; 375 return false;
382 return true; 376 return true;
383 }); 377 });
@@ -459,7 +453,7 @@ InstallResult RegisteredCache::InstallEntry(std::shared_ptr<NCA> nca, TitleType
459 453
460InstallResult RegisteredCache::RawInstallNCA(std::shared_ptr<NCA> nca, const VfsCopyFunction& copy, 454InstallResult RegisteredCache::RawInstallNCA(std::shared_ptr<NCA> nca, const VfsCopyFunction& copy,
461 bool overwrite_if_exists, 455 bool overwrite_if_exists,
462 boost::optional<NcaID> override_id) { 456 std::optional<NcaID> override_id) {
463 const auto in = nca->GetBaseFile(); 457 const auto in = nca->GetBaseFile();
464 Core::Crypto::SHA256Hash hash{}; 458 Core::Crypto::SHA256Hash hash{};
465 459
@@ -468,12 +462,12 @@ InstallResult RegisteredCache::RawInstallNCA(std::shared_ptr<NCA> nca, const Vfs
468 // game is massive), we're going to cheat and only hash the first MB of the NCA. 462 // game is massive), we're going to cheat and only hash the first MB of the NCA.
469 // Also, for XCIs the NcaID matters, so if the override id isn't none, use that. 463 // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
470 NcaID id{}; 464 NcaID id{};
471 if (override_id == boost::none) { 465 if (override_id) {
466 id = *override_id;
467 } else {
472 const auto& data = in->ReadBytes(0x100000); 468 const auto& data = in->ReadBytes(0x100000);
473 mbedtls_sha256(data.data(), data.size(), hash.data(), 0); 469 mbedtls_sha256(data.data(), data.size(), hash.data(), 0);
474 memcpy(id.data(), hash.data(), 16); 470 memcpy(id.data(), hash.data(), 16);
475 } else {
476 id = override_id.get();
477 } 471 }
478 472
479 std::string path = GetRelativePathFromNcaID(id, false, true); 473 std::string path = GetRelativePathFromNcaID(id, false, true);
@@ -543,14 +537,14 @@ bool RegisteredCacheUnion::HasEntry(RegisteredCacheEntry entry) const {
543 return HasEntry(entry.title_id, entry.type); 537 return HasEntry(entry.title_id, entry.type);
544} 538}
545 539
546boost::optional<u32> RegisteredCacheUnion::GetEntryVersion(u64 title_id) const { 540std::optional<u32> RegisteredCacheUnion::GetEntryVersion(u64 title_id) const {
547 for (const auto& c : caches) { 541 for (const auto& c : caches) {
548 const auto res = c->GetEntryVersion(title_id); 542 const auto res = c->GetEntryVersion(title_id);
549 if (res != boost::none) 543 if (res)
550 return res; 544 return res;
551 } 545 }
552 546
553 return boost::none; 547 return {};
554} 548}
555 549
556VirtualFile RegisteredCacheUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const { 550VirtualFile RegisteredCacheUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
@@ -609,8 +603,8 @@ std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntries() const {
609} 603}
610 604
611std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntriesFilter( 605std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntriesFilter(
612 boost::optional<TitleType> title_type, boost::optional<ContentRecordType> record_type, 606 std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
613 boost::optional<u64> title_id) const { 607 std::optional<u64> title_id) const {
614 std::vector<RegisteredCacheEntry> out; 608 std::vector<RegisteredCacheEntry> out;
615 for (const auto& c : caches) { 609 for (const auto& c : caches) {
616 c->IterateAllMetadata<RegisteredCacheEntry>( 610 c->IterateAllMetadata<RegisteredCacheEntry>(
@@ -619,11 +613,11 @@ std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntriesFilter(
619 return RegisteredCacheEntry{c.GetTitleID(), r.type}; 613 return RegisteredCacheEntry{c.GetTitleID(), r.type};
620 }, 614 },
621 [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) { 615 [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
622 if (title_type != boost::none && title_type.get() != c.GetType()) 616 if (title_type && *title_type != c.GetType())
623 return false; 617 return false;
624 if (record_type != boost::none && record_type.get() != r.type) 618 if (record_type && *record_type != r.type)
625 return false; 619 return false;
626 if (title_id != boost::none && title_id.get() != c.GetTitleID()) 620 if (title_id && *title_id != c.GetTitleID())
627 return false; 621 return false;
628 return true; 622 return true;
629 }); 623 });
diff --git a/src/core/file_sys/registered_cache.h b/src/core/file_sys/registered_cache.h
index 5beceffb3..6cfb16017 100644
--- a/src/core/file_sys/registered_cache.h
+++ b/src/core/file_sys/registered_cache.h
@@ -84,7 +84,7 @@ public:
84 bool HasEntry(u64 title_id, ContentRecordType type) const; 84 bool HasEntry(u64 title_id, ContentRecordType type) const;
85 bool HasEntry(RegisteredCacheEntry entry) const; 85 bool HasEntry(RegisteredCacheEntry entry) const;
86 86
87 boost::optional<u32> GetEntryVersion(u64 title_id) const; 87 std::optional<u32> GetEntryVersion(u64 title_id) const;
88 88
89 VirtualFile GetEntryUnparsed(u64 title_id, ContentRecordType type) const; 89 VirtualFile GetEntryUnparsed(u64 title_id, ContentRecordType type) const;
90 VirtualFile GetEntryUnparsed(RegisteredCacheEntry entry) const; 90 VirtualFile GetEntryUnparsed(RegisteredCacheEntry entry) const;
@@ -96,11 +96,10 @@ public:
96 std::unique_ptr<NCA> GetEntry(RegisteredCacheEntry entry) const; 96 std::unique_ptr<NCA> GetEntry(RegisteredCacheEntry entry) const;
97 97
98 std::vector<RegisteredCacheEntry> ListEntries() const; 98 std::vector<RegisteredCacheEntry> ListEntries() const;
99 // If a parameter is not boost::none, it will be filtered for from all entries. 99 // If a parameter is not std::nullopt, it will be filtered for from all entries.
100 std::vector<RegisteredCacheEntry> ListEntriesFilter( 100 std::vector<RegisteredCacheEntry> ListEntriesFilter(
101 boost::optional<TitleType> title_type = boost::none, 101 std::optional<TitleType> title_type = {}, std::optional<ContentRecordType> record_type = {},
102 boost::optional<ContentRecordType> record_type = boost::none, 102 std::optional<u64> title_id = {}) const;
103 boost::optional<u64> title_id = boost::none) const;
104 103
105 // Raw copies all the ncas from the xci/nsp to the csache. Does some quick checks to make sure 104 // Raw copies all the ncas from the xci/nsp to the csache. Does some quick checks to make sure
106 // there is a meta NCA and all of them are accessible. 105 // there is a meta NCA and all of them are accessible.
@@ -125,12 +124,11 @@ private:
125 std::vector<NcaID> AccumulateFiles() const; 124 std::vector<NcaID> AccumulateFiles() const;
126 void ProcessFiles(const std::vector<NcaID>& ids); 125 void ProcessFiles(const std::vector<NcaID>& ids);
127 void AccumulateYuzuMeta(); 126 void AccumulateYuzuMeta();
128 boost::optional<NcaID> GetNcaIDFromMetadata(u64 title_id, ContentRecordType type) const; 127 std::optional<NcaID> GetNcaIDFromMetadata(u64 title_id, ContentRecordType type) const;
129 VirtualFile GetFileAtID(NcaID id) const; 128 VirtualFile GetFileAtID(NcaID id) const;
130 VirtualFile OpenFileOrDirectoryConcat(const VirtualDir& dir, std::string_view path) const; 129 VirtualFile OpenFileOrDirectoryConcat(const VirtualDir& dir, std::string_view path) const;
131 InstallResult RawInstallNCA(std::shared_ptr<NCA> nca, const VfsCopyFunction& copy, 130 InstallResult RawInstallNCA(std::shared_ptr<NCA> nca, const VfsCopyFunction& copy,
132 bool overwrite_if_exists, 131 bool overwrite_if_exists, std::optional<NcaID> override_id = {});
133 boost::optional<NcaID> override_id = boost::none);
134 bool RawInstallYuzuMeta(const CNMT& cnmt); 132 bool RawInstallYuzuMeta(const CNMT& cnmt);
135 133
136 VirtualDir dir; 134 VirtualDir dir;
@@ -153,7 +151,7 @@ public:
153 bool HasEntry(u64 title_id, ContentRecordType type) const; 151 bool HasEntry(u64 title_id, ContentRecordType type) const;
154 bool HasEntry(RegisteredCacheEntry entry) const; 152 bool HasEntry(RegisteredCacheEntry entry) const;
155 153
156 boost::optional<u32> GetEntryVersion(u64 title_id) const; 154 std::optional<u32> GetEntryVersion(u64 title_id) const;
157 155
158 VirtualFile GetEntryUnparsed(u64 title_id, ContentRecordType type) const; 156 VirtualFile GetEntryUnparsed(u64 title_id, ContentRecordType type) const;
159 VirtualFile GetEntryUnparsed(RegisteredCacheEntry entry) const; 157 VirtualFile GetEntryUnparsed(RegisteredCacheEntry entry) const;
@@ -165,11 +163,10 @@ public:
165 std::unique_ptr<NCA> GetEntry(RegisteredCacheEntry entry) const; 163 std::unique_ptr<NCA> GetEntry(RegisteredCacheEntry entry) const;
166 164
167 std::vector<RegisteredCacheEntry> ListEntries() const; 165 std::vector<RegisteredCacheEntry> ListEntries() const;
168 // If a parameter is not boost::none, it will be filtered for from all entries. 166 // If a parameter is not std::nullopt, it will be filtered for from all entries.
169 std::vector<RegisteredCacheEntry> ListEntriesFilter( 167 std::vector<RegisteredCacheEntry> ListEntriesFilter(
170 boost::optional<TitleType> title_type = boost::none, 168 std::optional<TitleType> title_type = {}, std::optional<ContentRecordType> record_type = {},
171 boost::optional<ContentRecordType> record_type = boost::none, 169 std::optional<u64> title_id = {}) const;
172 boost::optional<u64> title_id = boost::none) const;
173 170
174private: 171private:
175 std::vector<RegisteredCache*> caches; 172 std::vector<RegisteredCache*> caches;
diff --git a/src/core/file_sys/savedata_factory.cpp b/src/core/file_sys/savedata_factory.cpp
index ef1aaebbb..5434f2149 100644
--- a/src/core/file_sys/savedata_factory.cpp
+++ b/src/core/file_sys/savedata_factory.cpp
@@ -83,28 +83,32 @@ ResultVal<VirtualDir> SaveDataFactory::Open(SaveDataSpaceId space, SaveDataDescr
83 return MakeResult<VirtualDir>(std::move(out)); 83 return MakeResult<VirtualDir>(std::move(out));
84} 84}
85 85
86std::string SaveDataFactory::GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id, 86VirtualDir SaveDataFactory::GetSaveDataSpaceDirectory(SaveDataSpaceId space) const {
87 u128 user_id, u64 save_id) { 87 return dir->GetDirectoryRelative(GetSaveDataSpaceIdPath(space));
88 // According to switchbrew, if a save is of type SaveData and the title id field is 0, it should 88}
89 // be interpreted as the title id of the current process.
90 if (type == SaveDataType::SaveData && title_id == 0)
91 title_id = Core::CurrentProcess()->GetTitleID();
92
93 std::string out;
94 89
90std::string SaveDataFactory::GetSaveDataSpaceIdPath(SaveDataSpaceId space) {
95 switch (space) { 91 switch (space) {
96 case SaveDataSpaceId::NandSystem: 92 case SaveDataSpaceId::NandSystem:
97 out = "/system/"; 93 return "/system/";
98 break;
99 case SaveDataSpaceId::NandUser: 94 case SaveDataSpaceId::NandUser:
100 out = "/user/"; 95 return "/user/";
101 break;
102 case SaveDataSpaceId::TemporaryStorage: 96 case SaveDataSpaceId::TemporaryStorage:
103 out = "/temp/"; 97 return "/temp/";
104 break;
105 default: 98 default:
106 ASSERT_MSG(false, "Unrecognized SaveDataSpaceId: {:02X}", static_cast<u8>(space)); 99 ASSERT_MSG(false, "Unrecognized SaveDataSpaceId: {:02X}", static_cast<u8>(space));
100 return "/unrecognized/"; ///< To prevent corruption when ignoring asserts.
107 } 101 }
102}
103
104std::string SaveDataFactory::GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id,
105 u128 user_id, u64 save_id) {
106 // According to switchbrew, if a save is of type SaveData and the title id field is 0, it should
107 // be interpreted as the title id of the current process.
108 if (type == SaveDataType::SaveData && title_id == 0)
109 title_id = Core::CurrentProcess()->GetTitleID();
110
111 std::string out = GetSaveDataSpaceIdPath(space);
108 112
109 switch (type) { 113 switch (type) {
110 case SaveDataType::SystemSaveData: 114 case SaveDataType::SystemSaveData:
diff --git a/src/core/file_sys/savedata_factory.h b/src/core/file_sys/savedata_factory.h
index d69ef6741..2a0088040 100644
--- a/src/core/file_sys/savedata_factory.h
+++ b/src/core/file_sys/savedata_factory.h
@@ -52,6 +52,9 @@ public:
52 52
53 ResultVal<VirtualDir> Open(SaveDataSpaceId space, SaveDataDescriptor meta); 53 ResultVal<VirtualDir> Open(SaveDataSpaceId space, SaveDataDescriptor meta);
54 54
55 VirtualDir GetSaveDataSpaceDirectory(SaveDataSpaceId space) const;
56
57 static std::string GetSaveDataSpaceIdPath(SaveDataSpaceId space);
55 static std::string GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id, 58 static std::string GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id,
56 u128 user_id, u64 save_id); 59 u128 user_id, u64 save_id);
57 60
diff --git a/src/core/file_sys/vfs.cpp b/src/core/file_sys/vfs.cpp
index 3824c74e0..7b584de7f 100644
--- a/src/core/file_sys/vfs.cpp
+++ b/src/core/file_sys/vfs.cpp
@@ -167,13 +167,13 @@ std::string VfsFile::GetExtension() const {
167 167
168VfsDirectory::~VfsDirectory() = default; 168VfsDirectory::~VfsDirectory() = default;
169 169
170boost::optional<u8> VfsFile::ReadByte(std::size_t offset) const { 170std::optional<u8> VfsFile::ReadByte(std::size_t offset) const {
171 u8 out{}; 171 u8 out{};
172 std::size_t size = Read(&out, 1, offset); 172 std::size_t size = Read(&out, 1, offset);
173 if (size == 1) 173 if (size == 1)
174 return out; 174 return out;
175 175
176 return boost::none; 176 return {};
177} 177}
178 178
179std::vector<u8> VfsFile::ReadBytes(std::size_t size, std::size_t offset) const { 179std::vector<u8> VfsFile::ReadBytes(std::size_t size, std::size_t offset) const {
diff --git a/src/core/file_sys/vfs.h b/src/core/file_sys/vfs.h
index 09dc9f288..002f99d4e 100644
--- a/src/core/file_sys/vfs.h
+++ b/src/core/file_sys/vfs.h
@@ -4,13 +4,15 @@
4 4
5#pragma once 5#pragma once
6 6
7#include <functional>
7#include <map> 8#include <map>
8#include <memory> 9#include <memory>
10#include <optional>
9#include <string> 11#include <string>
10#include <string_view> 12#include <string_view>
11#include <type_traits> 13#include <type_traits>
12#include <vector> 14#include <vector>
13#include <boost/optional.hpp> 15
14#include "common/common_types.h" 16#include "common/common_types.h"
15#include "core/file_sys/vfs_types.h" 17#include "core/file_sys/vfs_types.h"
16 18
@@ -103,8 +105,8 @@ public:
103 // into file. Returns number of bytes successfully written. 105 // into file. Returns number of bytes successfully written.
104 virtual std::size_t Write(const u8* data, std::size_t length, std::size_t offset = 0) = 0; 106 virtual std::size_t Write(const u8* data, std::size_t length, std::size_t offset = 0) = 0;
105 107
106 // Reads exactly one byte at the offset provided, returning boost::none on error. 108 // Reads exactly one byte at the offset provided, returning std::nullopt on error.
107 virtual boost::optional<u8> ReadByte(std::size_t offset = 0) const; 109 virtual std::optional<u8> ReadByte(std::size_t offset = 0) const;
108 // Reads size bytes starting at offset in file into a vector. 110 // Reads size bytes starting at offset in file into a vector.
109 virtual std::vector<u8> ReadBytes(std::size_t size, std::size_t offset = 0) const; 111 virtual std::vector<u8> ReadBytes(std::size_t size, std::size_t offset = 0) const;
110 // Reads all the bytes from the file into a vector. Equivalent to 'file->Read(file->GetSize(), 112 // Reads all the bytes from the file into a vector. Equivalent to 'file->Read(file->GetSize(),
diff --git a/src/core/file_sys/vfs_offset.cpp b/src/core/file_sys/vfs_offset.cpp
index a4c6719a0..c96f88488 100644
--- a/src/core/file_sys/vfs_offset.cpp
+++ b/src/core/file_sys/vfs_offset.cpp
@@ -57,11 +57,11 @@ std::size_t OffsetVfsFile::Write(const u8* data, std::size_t length, std::size_t
57 return file->Write(data, TrimToFit(length, r_offset), offset + r_offset); 57 return file->Write(data, TrimToFit(length, r_offset), offset + r_offset);
58} 58}
59 59
60boost::optional<u8> OffsetVfsFile::ReadByte(std::size_t r_offset) const { 60std::optional<u8> OffsetVfsFile::ReadByte(std::size_t r_offset) const {
61 if (r_offset < size) 61 if (r_offset < size)
62 return file->ReadByte(offset + r_offset); 62 return file->ReadByte(offset + r_offset);
63 63
64 return boost::none; 64 return {};
65} 65}
66 66
67std::vector<u8> OffsetVfsFile::ReadBytes(std::size_t r_size, std::size_t r_offset) const { 67std::vector<u8> OffsetVfsFile::ReadBytes(std::size_t r_size, std::size_t r_offset) const {
diff --git a/src/core/file_sys/vfs_offset.h b/src/core/file_sys/vfs_offset.h
index 8062702a7..f7b7a3256 100644
--- a/src/core/file_sys/vfs_offset.h
+++ b/src/core/file_sys/vfs_offset.h
@@ -29,7 +29,7 @@ public:
29 bool IsReadable() const override; 29 bool IsReadable() const override;
30 std::size_t Read(u8* data, std::size_t length, std::size_t offset) const override; 30 std::size_t Read(u8* data, std::size_t length, std::size_t offset) const override;
31 std::size_t Write(const u8* data, std::size_t length, std::size_t offset) override; 31 std::size_t Write(const u8* data, std::size_t length, std::size_t offset) override;
32 boost::optional<u8> ReadByte(std::size_t offset) const override; 32 std::optional<u8> ReadByte(std::size_t offset) const override;
33 std::vector<u8> ReadBytes(std::size_t size, std::size_t offset) const override; 33 std::vector<u8> ReadBytes(std::size_t size, std::size_t offset) const override;
34 std::vector<u8> ReadAllBytes() const override; 34 std::vector<u8> ReadAllBytes() const override;
35 bool WriteByte(u8 data, std::size_t offset) override; 35 bool WriteByte(u8 data, std::size_t offset) override;
diff --git a/src/core/file_sys/vfs_static.h b/src/core/file_sys/vfs_static.h
index 44fab51d1..9f5a90b1b 100644
--- a/src/core/file_sys/vfs_static.h
+++ b/src/core/file_sys/vfs_static.h
@@ -53,10 +53,10 @@ public:
53 return 0; 53 return 0;
54 } 54 }
55 55
56 boost::optional<u8> ReadByte(std::size_t offset) const override { 56 std::optional<u8> ReadByte(std::size_t offset) const override {
57 if (offset < size) 57 if (offset < size)
58 return value; 58 return value;
59 return boost::none; 59 return {};
60 } 60 }
61 61
62 std::vector<u8> ReadBytes(std::size_t length, std::size_t offset) const override { 62 std::vector<u8> ReadBytes(std::size_t length, std::size_t offset) const override {
diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h
index a4bfe2eb0..0a7142ada 100644
--- a/src/core/hle/ipc_helpers.h
+++ b/src/core/hle/ipc_helpers.h
@@ -117,8 +117,7 @@ public:
117 117
118 AlignWithPadding(); 118 AlignWithPadding();
119 119
120 const bool request_has_domain_header{context.GetDomainMessageHeader() != nullptr}; 120 if (context.Session()->IsDomain() && context.HasDomainMessageHeader()) {
121 if (context.Session()->IsDomain() && request_has_domain_header) {
122 IPC::DomainMessageHeader domain_header{}; 121 IPC::DomainMessageHeader domain_header{};
123 domain_header.num_objects = num_domain_objects; 122 domain_header.num_objects = num_domain_objects;
124 PushRaw(domain_header); 123 PushRaw(domain_header);
diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h
index f01491daa..a38e34b74 100644
--- a/src/core/hle/kernel/hle_ipc.h
+++ b/src/core/hle/kernel/hle_ipc.h
@@ -161,8 +161,12 @@ public:
161 return buffer_c_desciptors; 161 return buffer_c_desciptors;
162 } 162 }
163 163
164 const std::shared_ptr<IPC::DomainMessageHeader>& GetDomainMessageHeader() const { 164 const IPC::DomainMessageHeader* GetDomainMessageHeader() const {
165 return domain_message_header; 165 return domain_message_header.get();
166 }
167
168 bool HasDomainMessageHeader() const {
169 return domain_message_header != nullptr;
166 } 170 }
167 171
168 /// Helper function to read a buffer using the appropriate buffer descriptor 172 /// Helper function to read a buffer using the appropriate buffer descriptor
diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index 4b6b32dd5..1fd4ba5d2 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -32,7 +32,7 @@ namespace Kernel {
32 */ 32 */
33static void ThreadWakeupCallback(u64 thread_handle, [[maybe_unused]] int cycles_late) { 33static void ThreadWakeupCallback(u64 thread_handle, [[maybe_unused]] int cycles_late) {
34 const auto proper_handle = static_cast<Handle>(thread_handle); 34 const auto proper_handle = static_cast<Handle>(thread_handle);
35 auto& system = Core::System::GetInstance(); 35 const auto& system = Core::System::GetInstance();
36 36
37 // Lock the global kernel mutex when we enter the kernel HLE. 37 // Lock the global kernel mutex when we enter the kernel HLE.
38 std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock); 38 std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
@@ -90,7 +90,7 @@ static void ThreadWakeupCallback(u64 thread_handle, [[maybe_unused]] int cycles_
90/// The timer callback event, called when a timer is fired 90/// The timer callback event, called when a timer is fired
91static void TimerCallback(u64 timer_handle, int cycles_late) { 91static void TimerCallback(u64 timer_handle, int cycles_late) {
92 const auto proper_handle = static_cast<Handle>(timer_handle); 92 const auto proper_handle = static_cast<Handle>(timer_handle);
93 auto& system = Core::System::GetInstance(); 93 const auto& system = Core::System::GetInstance();
94 SharedPtr<Timer> timer = system.Kernel().RetrieveTimerFromCallbackHandleTable(proper_handle); 94 SharedPtr<Timer> timer = system.Kernel().RetrieveTimerFromCallbackHandleTable(proper_handle);
95 95
96 if (timer == nullptr) { 96 if (timer == nullptr) {
diff --git a/src/core/hle/kernel/mutex.cpp b/src/core/hle/kernel/mutex.cpp
index dd541ffcc..0743670ad 100644
--- a/src/core/hle/kernel/mutex.cpp
+++ b/src/core/hle/kernel/mutex.cpp
@@ -6,8 +6,6 @@
6#include <utility> 6#include <utility>
7#include <vector> 7#include <vector>
8 8
9#include <boost/range/algorithm_ext/erase.hpp>
10
11#include "common/assert.h" 9#include "common/assert.h"
12#include "core/core.h" 10#include "core/core.h"
13#include "core/hle/kernel/errors.h" 11#include "core/hle/kernel/errors.h"
diff --git a/src/core/hle/kernel/process.cpp b/src/core/hle/kernel/process.cpp
index 420218d59..f06b6bb55 100644
--- a/src/core/hle/kernel/process.cpp
+++ b/src/core/hle/kernel/process.cpp
@@ -5,11 +5,9 @@
5#include <algorithm> 5#include <algorithm>
6#include <memory> 6#include <memory>
7#include "common/assert.h" 7#include "common/assert.h"
8#include "common/common_funcs.h"
9#include "common/logging/log.h" 8#include "common/logging/log.h"
10#include "core/core.h" 9#include "core/core.h"
11#include "core/file_sys/program_metadata.h" 10#include "core/file_sys/program_metadata.h"
12#include "core/hle/kernel/errors.h"
13#include "core/hle/kernel/kernel.h" 11#include "core/hle/kernel/kernel.h"
14#include "core/hle/kernel/process.h" 12#include "core/hle/kernel/process.h"
15#include "core/hle/kernel/resource_limit.h" 13#include "core/hle/kernel/resource_limit.h"
@@ -17,6 +15,7 @@
17#include "core/hle/kernel/thread.h" 15#include "core/hle/kernel/thread.h"
18#include "core/hle/kernel/vm_manager.h" 16#include "core/hle/kernel/vm_manager.h"
19#include "core/memory.h" 17#include "core/memory.h"
18#include "core/settings.h"
20 19
21namespace Kernel { 20namespace Kernel {
22 21
@@ -35,6 +34,11 @@ SharedPtr<Process> Process::Create(KernelCore& kernel, std::string&& name) {
35 process->process_id = kernel.CreateNewProcessID(); 34 process->process_id = kernel.CreateNewProcessID();
36 process->svc_access_mask.set(); 35 process->svc_access_mask.set();
37 36
37 std::mt19937 rng(Settings::values.rng_seed.value_or(0));
38 std::uniform_int_distribution<u64> distribution;
39 std::generate(process->random_entropy.begin(), process->random_entropy.end(),
40 [&] { return distribution(rng); });
41
38 kernel.AppendNewProcess(process); 42 kernel.AppendNewProcess(process);
39 return process; 43 return process;
40} 44}
@@ -241,83 +245,15 @@ void Process::LoadModule(CodeSet module_, VAddr base_addr) {
241} 245}
242 246
243ResultVal<VAddr> Process::HeapAllocate(VAddr target, u64 size, VMAPermission perms) { 247ResultVal<VAddr> Process::HeapAllocate(VAddr target, u64 size, VMAPermission perms) {
244 if (target < vm_manager.GetHeapRegionBaseAddress() || 248 return vm_manager.HeapAllocate(target, size, perms);
245 target + size > vm_manager.GetHeapRegionEndAddress() || target + size < target) {
246 return ERR_INVALID_ADDRESS;
247 }
248
249 if (heap_memory == nullptr) {
250 // Initialize heap
251 heap_memory = std::make_shared<std::vector<u8>>();
252 heap_start = heap_end = target;
253 } else {
254 vm_manager.UnmapRange(heap_start, heap_end - heap_start);
255 }
256
257 // If necessary, expand backing vector to cover new heap extents.
258 if (target < heap_start) {
259 heap_memory->insert(begin(*heap_memory), heap_start - target, 0);
260 heap_start = target;
261 vm_manager.RefreshMemoryBlockMappings(heap_memory.get());
262 }
263 if (target + size > heap_end) {
264 heap_memory->insert(end(*heap_memory), (target + size) - heap_end, 0);
265 heap_end = target + size;
266 vm_manager.RefreshMemoryBlockMappings(heap_memory.get());
267 }
268 ASSERT(heap_end - heap_start == heap_memory->size());
269
270 CASCADE_RESULT(auto vma, vm_manager.MapMemoryBlock(target, heap_memory, target - heap_start,
271 size, MemoryState::Heap));
272 vm_manager.Reprotect(vma, perms);
273
274 heap_used = size;
275
276 return MakeResult<VAddr>(heap_end - size);
277} 249}
278 250
279ResultCode Process::HeapFree(VAddr target, u32 size) { 251ResultCode Process::HeapFree(VAddr target, u32 size) {
280 if (target < vm_manager.GetHeapRegionBaseAddress() || 252 return vm_manager.HeapFree(target, size);
281 target + size > vm_manager.GetHeapRegionEndAddress() || target + size < target) {
282 return ERR_INVALID_ADDRESS;
283 }
284
285 if (size == 0) {
286 return RESULT_SUCCESS;
287 }
288
289 ResultCode result = vm_manager.UnmapRange(target, size);
290 if (result.IsError())
291 return result;
292
293 heap_used -= size;
294
295 return RESULT_SUCCESS;
296} 253}
297 254
298ResultCode Process::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size) { 255ResultCode Process::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
299 auto vma = vm_manager.FindVMA(src_addr); 256 return vm_manager.MirrorMemory(dst_addr, src_addr, size);
300
301 ASSERT_MSG(vma != vm_manager.vma_map.end(), "Invalid memory address");
302 ASSERT_MSG(vma->second.backing_block, "Backing block doesn't exist for address");
303
304 // The returned VMA might be a bigger one encompassing the desired address.
305 auto vma_offset = src_addr - vma->first;
306 ASSERT_MSG(vma_offset + size <= vma->second.size,
307 "Shared memory exceeds bounds of mapped block");
308
309 const std::shared_ptr<std::vector<u8>>& backing_block = vma->second.backing_block;
310 std::size_t backing_block_offset = vma->second.offset + vma_offset;
311
312 CASCADE_RESULT(auto new_vma,
313 vm_manager.MapMemoryBlock(dst_addr, backing_block, backing_block_offset, size,
314 MemoryState::Mapped));
315 // Protect mirror with permissions from old region
316 vm_manager.Reprotect(new_vma, vma->second.permissions);
317 // Remove permissions from old region
318 vm_manager.Reprotect(vma, VMAPermission::None);
319
320 return RESULT_SUCCESS;
321} 257}
322 258
323ResultCode Process::UnmapMemory(VAddr dst_addr, VAddr /*src_addr*/, u64 size) { 259ResultCode Process::UnmapMemory(VAddr dst_addr, VAddr /*src_addr*/, u64 size) {
diff --git a/src/core/hle/kernel/process.h b/src/core/hle/kernel/process.h
index 8d2616c79..cf48787ce 100644
--- a/src/core/hle/kernel/process.h
+++ b/src/core/hle/kernel/process.h
@@ -8,6 +8,7 @@
8#include <bitset> 8#include <bitset>
9#include <cstddef> 9#include <cstddef>
10#include <memory> 10#include <memory>
11#include <random>
11#include <string> 12#include <string>
12#include <vector> 13#include <vector>
13#include <boost/container/static_vector.hpp> 14#include <boost/container/static_vector.hpp>
@@ -119,6 +120,8 @@ struct CodeSet final {
119 120
120class Process final : public Object { 121class Process final : public Object {
121public: 122public:
123 static constexpr std::size_t RANDOM_ENTROPY_SIZE = 4;
124
122 static SharedPtr<Process> Create(KernelCore& kernel, std::string&& name); 125 static SharedPtr<Process> Create(KernelCore& kernel, std::string&& name);
123 126
124 std::string GetTypeName() const override { 127 std::string GetTypeName() const override {
@@ -212,6 +215,11 @@ public:
212 total_process_running_time_ticks += ticks; 215 total_process_running_time_ticks += ticks;
213 } 216 }
214 217
218 /// Gets 8 bytes of random data for svcGetInfo RandomEntropy
219 u64 GetRandomEntropy(std::size_t index) const {
220 return random_entropy.at(index);
221 }
222
215 /** 223 /**
216 * Loads process-specifics configuration info with metadata provided 224 * Loads process-specifics configuration info with metadata provided
217 * by an executable. 225 * by an executable.
@@ -292,17 +300,6 @@ private:
292 u32 allowed_thread_priority_mask = 0xFFFFFFFF; 300 u32 allowed_thread_priority_mask = 0xFFFFFFFF;
293 u32 is_virtual_address_memory_enabled = 0; 301 u32 is_virtual_address_memory_enabled = 0;
294 302
295 // Memory used to back the allocations in the regular heap. A single vector is used to cover
296 // the entire virtual address space extents that bound the allocations, including any holes.
297 // This makes deallocation and reallocation of holes fast and keeps process memory contiguous
298 // in the emulator address space, allowing Memory::GetPointer to be reasonably safe.
299 std::shared_ptr<std::vector<u8>> heap_memory;
300
301 // The left/right bounds of the address space covered by heap_memory.
302 VAddr heap_start = 0;
303 VAddr heap_end = 0;
304 u64 heap_used = 0;
305
306 /// The Thread Local Storage area is allocated as processes create threads, 303 /// The Thread Local Storage area is allocated as processes create threads,
307 /// each TLS area is 0x200 bytes, so one page (0x1000) is split up in 8 parts, and each part 304 /// each TLS area is 0x200 bytes, so one page (0x1000) is split up in 8 parts, and each part
308 /// holds the TLS for a specific thread. This vector contains which parts are in use for each 305 /// holds the TLS for a specific thread. This vector contains which parts are in use for each
@@ -321,6 +318,9 @@ private:
321 /// Per-process handle table for storing created object handles in. 318 /// Per-process handle table for storing created object handles in.
322 HandleTable handle_table; 319 HandleTable handle_table;
323 320
321 /// Random values for svcGetInfo RandomEntropy
322 std::array<u64, RANDOM_ENTROPY_SIZE> random_entropy;
323
324 std::string name; 324 std::string name;
325}; 325};
326 326
diff --git a/src/core/hle/kernel/server_session.cpp b/src/core/hle/kernel/server_session.cpp
index 5fc320403..80897f3a4 100644
--- a/src/core/hle/kernel/server_session.cpp
+++ b/src/core/hle/kernel/server_session.cpp
@@ -63,7 +63,7 @@ void ServerSession::Acquire(Thread* thread) {
63} 63}
64 64
65ResultCode ServerSession::HandleDomainSyncRequest(Kernel::HLERequestContext& context) { 65ResultCode ServerSession::HandleDomainSyncRequest(Kernel::HLERequestContext& context) {
66 auto& domain_message_header = context.GetDomainMessageHeader(); 66 auto* const domain_message_header = context.GetDomainMessageHeader();
67 if (domain_message_header) { 67 if (domain_message_header) {
68 // Set domain handlers in HLE context, used for domain objects (IPC interfaces) as inputs 68 // Set domain handlers in HLE context, used for domain objects (IPC interfaces) as inputs
69 context.SetDomainRequestHandlers(domain_request_handlers); 69 context.SetDomainRequestHandlers(domain_request_handlers);
@@ -111,7 +111,7 @@ ResultCode ServerSession::HandleSyncRequest(SharedPtr<Thread> thread) {
111 111
112 ResultCode result = RESULT_SUCCESS; 112 ResultCode result = RESULT_SUCCESS;
113 // If the session has been converted to a domain, handle the domain request 113 // If the session has been converted to a domain, handle the domain request
114 if (IsDomain() && context.GetDomainMessageHeader()) { 114 if (IsDomain() && context.HasDomainMessageHeader()) {
115 result = HandleDomainSyncRequest(context); 115 result = HandleDomainSyncRequest(context);
116 // If there is no domain header, the regular session handler is used 116 // If there is no domain header, the regular session handler is used
117 } else if (hle_handler != nullptr) { 117 } else if (hle_handler != nullptr) {
diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp
index 4e490e2b5..b0b6508d9 100644
--- a/src/core/hle/kernel/svc.cpp
+++ b/src/core/hle/kernel/svc.cpp
@@ -34,6 +34,7 @@
34#include "core/hle/lock.h" 34#include "core/hle/lock.h"
35#include "core/hle/result.h" 35#include "core/hle/result.h"
36#include "core/hle/service/service.h" 36#include "core/hle/service/service.h"
37#include "core/settings.h"
37 38
38namespace Kernel { 39namespace Kernel {
39namespace { 40namespace {
@@ -395,16 +396,42 @@ struct BreakReason {
395/// Break program execution 396/// Break program execution
396static void Break(u32 reason, u64 info1, u64 info2) { 397static void Break(u32 reason, u64 info1, u64 info2) {
397 BreakReason break_reason{reason}; 398 BreakReason break_reason{reason};
399 bool has_dumped_buffer{};
398 400
401 const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
402 if (sz == 0 || addr == 0 || has_dumped_buffer) {
403 return;
404 }
405
406 // This typically is an error code so we're going to assume this is the case
407 if (sz == sizeof(u32)) {
408 LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", Memory::Read32(addr));
409 } else {
410 // We don't know what's in here so we'll hexdump it
411 std::vector<u8> debug_buffer(sz);
412 Memory::ReadBlock(addr, debug_buffer.data(), sz);
413 std::string hexdump;
414 for (std::size_t i = 0; i < debug_buffer.size(); i++) {
415 hexdump += fmt::format("{:02X} ", debug_buffer[i]);
416 if (i != 0 && i % 16 == 0) {
417 hexdump += '\n';
418 }
419 }
420 LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
421 }
422 has_dumped_buffer = true;
423 };
399 switch (break_reason.break_type) { 424 switch (break_reason.break_type) {
400 case BreakType::Panic: 425 case BreakType::Panic:
401 LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}", 426 LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
402 info1, info2); 427 info1, info2);
428 handle_debug_buffer(info1, info2);
403 break; 429 break;
404 case BreakType::AssertionFailed: 430 case BreakType::AssertionFailed:
405 LOG_CRITICAL(Debug_Emulated, 431 LOG_CRITICAL(Debug_Emulated,
406 "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}", 432 "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
407 info1, info2); 433 info1, info2);
434 handle_debug_buffer(info1, info2);
408 break; 435 break;
409 case BreakType::PreNROLoad: 436 case BreakType::PreNROLoad:
410 LOG_WARNING( 437 LOG_WARNING(
@@ -433,6 +460,7 @@ static void Break(u32 reason, u64 info1, u64 info2) {
433 Debug_Emulated, 460 Debug_Emulated,
434 "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}", 461 "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
435 static_cast<u32>(break_reason.break_type.Value()), info1, info2); 462 static_cast<u32>(break_reason.break_type.Value()), info1, info2);
463 handle_debug_buffer(info1, info2);
436 break; 464 break;
437 } 465 }
438 466
@@ -441,6 +469,7 @@ static void Break(u32 reason, u64 info1, u64 info2) {
441 Debug_Emulated, 469 Debug_Emulated,
442 "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}", 470 "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
443 reason, info1, info2); 471 reason, info1, info2);
472 handle_debug_buffer(info1, info2);
444 ASSERT(false); 473 ASSERT(false);
445 474
446 Core::CurrentProcess()->PrepareForTermination(); 475 Core::CurrentProcess()->PrepareForTermination();
@@ -530,7 +559,16 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
530 *result = 0; 559 *result = 0;
531 break; 560 break;
532 case GetInfoType::RandomEntropy: 561 case GetInfoType::RandomEntropy:
533 *result = 0; 562 if (handle != 0) {
563 return ERR_INVALID_HANDLE;
564 }
565
566 if (info_sub_id >= Process::RANDOM_ENTROPY_SIZE) {
567 return ERR_INVALID_COMBINATION_KERNEL;
568 }
569
570 *result = current_process->GetRandomEntropy(info_sub_id);
571 return RESULT_SUCCESS;
534 break; 572 break;
535 case GetInfoType::ASLRRegionBaseAddr: 573 case GetInfoType::ASLRRegionBaseAddr:
536 *result = vm_manager.GetASLRRegionBaseAddress(); 574 *result = vm_manager.GetASLRRegionBaseAddress();
@@ -572,7 +610,7 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
572 return ERR_INVALID_HANDLE; 610 return ERR_INVALID_HANDLE;
573 } 611 }
574 612
575 auto& system = Core::System::GetInstance(); 613 const auto& system = Core::System::GetInstance();
576 const auto& scheduler = system.CurrentScheduler(); 614 const auto& scheduler = system.CurrentScheduler();
577 const auto* const current_thread = scheduler.GetCurrentThread(); 615 const auto* const current_thread = scheduler.GetCurrentThread();
578 const bool same_thread = current_thread == thread; 616 const bool same_thread = current_thread == thread;
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 59bc9e0af..dd5cd9ced 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -4,9 +4,9 @@
4 4
5#include <algorithm> 5#include <algorithm>
6#include <cinttypes> 6#include <cinttypes>
7#include <optional>
7#include <vector> 8#include <vector>
8 9
9#include <boost/optional.hpp>
10#include <boost/range/algorithm_ext/erase.hpp> 10#include <boost/range/algorithm_ext/erase.hpp>
11 11
12#include "common/assert.h" 12#include "common/assert.h"
@@ -94,7 +94,7 @@ void Thread::CancelWakeupTimer() {
94 CoreTiming::UnscheduleEventThreadsafe(kernel.ThreadWakeupCallbackEventType(), callback_handle); 94 CoreTiming::UnscheduleEventThreadsafe(kernel.ThreadWakeupCallbackEventType(), callback_handle);
95} 95}
96 96
97static boost::optional<s32> GetNextProcessorId(u64 mask) { 97static std::optional<s32> GetNextProcessorId(u64 mask) {
98 for (s32 index = 0; index < Core::NUM_CPU_CORES; ++index) { 98 for (s32 index = 0; index < Core::NUM_CPU_CORES; ++index) {
99 if (mask & (1ULL << index)) { 99 if (mask & (1ULL << index)) {
100 if (!Core::System::GetInstance().Scheduler(index).GetCurrentThread()) { 100 if (!Core::System::GetInstance().Scheduler(index).GetCurrentThread()) {
@@ -142,7 +142,7 @@ void Thread::ResumeFromWait() {
142 142
143 status = ThreadStatus::Ready; 143 status = ThreadStatus::Ready;
144 144
145 boost::optional<s32> new_processor_id = GetNextProcessorId(affinity_mask); 145 std::optional<s32> new_processor_id = GetNextProcessorId(affinity_mask);
146 if (!new_processor_id) { 146 if (!new_processor_id) {
147 new_processor_id = processor_id; 147 new_processor_id = processor_id;
148 } 148 }
@@ -369,7 +369,7 @@ void Thread::ChangeCore(u32 core, u64 mask) {
369 return; 369 return;
370 } 370 }
371 371
372 boost::optional<s32> new_processor_id{GetNextProcessorId(affinity_mask)}; 372 std::optional<s32> new_processor_id{GetNextProcessorId(affinity_mask)};
373 373
374 if (!new_processor_id) { 374 if (!new_processor_id) {
375 new_processor_id = processor_id; 375 new_processor_id = processor_id;
diff --git a/src/core/hle/kernel/vm_manager.cpp b/src/core/hle/kernel/vm_manager.cpp
index 1a92c8f70..ec7fd6150 100644
--- a/src/core/hle/kernel/vm_manager.cpp
+++ b/src/core/hle/kernel/vm_manager.cpp
@@ -243,6 +243,85 @@ ResultCode VMManager::ReprotectRange(VAddr target, u64 size, VMAPermission new_p
243 return RESULT_SUCCESS; 243 return RESULT_SUCCESS;
244} 244}
245 245
246ResultVal<VAddr> VMManager::HeapAllocate(VAddr target, u64 size, VMAPermission perms) {
247 if (target < GetHeapRegionBaseAddress() || target + size > GetHeapRegionEndAddress() ||
248 target + size < target) {
249 return ERR_INVALID_ADDRESS;
250 }
251
252 if (heap_memory == nullptr) {
253 // Initialize heap
254 heap_memory = std::make_shared<std::vector<u8>>();
255 heap_start = heap_end = target;
256 } else {
257 UnmapRange(heap_start, heap_end - heap_start);
258 }
259
260 // If necessary, expand backing vector to cover new heap extents.
261 if (target < heap_start) {
262 heap_memory->insert(begin(*heap_memory), heap_start - target, 0);
263 heap_start = target;
264 RefreshMemoryBlockMappings(heap_memory.get());
265 }
266 if (target + size > heap_end) {
267 heap_memory->insert(end(*heap_memory), (target + size) - heap_end, 0);
268 heap_end = target + size;
269 RefreshMemoryBlockMappings(heap_memory.get());
270 }
271 ASSERT(heap_end - heap_start == heap_memory->size());
272
273 CASCADE_RESULT(auto vma, MapMemoryBlock(target, heap_memory, target - heap_start, size,
274 MemoryState::Heap));
275 Reprotect(vma, perms);
276
277 heap_used = size;
278
279 return MakeResult<VAddr>(heap_end - size);
280}
281
282ResultCode VMManager::HeapFree(VAddr target, u64 size) {
283 if (target < GetHeapRegionBaseAddress() || target + size > GetHeapRegionEndAddress() ||
284 target + size < target) {
285 return ERR_INVALID_ADDRESS;
286 }
287
288 if (size == 0) {
289 return RESULT_SUCCESS;
290 }
291
292 const ResultCode result = UnmapRange(target, size);
293 if (result.IsError()) {
294 return result;
295 }
296
297 heap_used -= size;
298 return RESULT_SUCCESS;
299}
300
301ResultCode VMManager::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
302 const auto vma = FindVMA(src_addr);
303
304 ASSERT_MSG(vma != vma_map.end(), "Invalid memory address");
305 ASSERT_MSG(vma->second.backing_block, "Backing block doesn't exist for address");
306
307 // The returned VMA might be a bigger one encompassing the desired address.
308 const auto vma_offset = src_addr - vma->first;
309 ASSERT_MSG(vma_offset + size <= vma->second.size,
310 "Shared memory exceeds bounds of mapped block");
311
312 const std::shared_ptr<std::vector<u8>>& backing_block = vma->second.backing_block;
313 const std::size_t backing_block_offset = vma->second.offset + vma_offset;
314
315 CASCADE_RESULT(auto new_vma, MapMemoryBlock(dst_addr, backing_block, backing_block_offset, size,
316 MemoryState::Mapped));
317 // Protect mirror with permissions from old region
318 Reprotect(new_vma, vma->second.permissions);
319 // Remove permissions from old region
320 Reprotect(vma, VMAPermission::None);
321
322 return RESULT_SUCCESS;
323}
324
246void VMManager::RefreshMemoryBlockMappings(const std::vector<u8>* block) { 325void VMManager::RefreshMemoryBlockMappings(const std::vector<u8>* block) {
247 // If this ever proves to have a noticeable performance impact, allow users of the function to 326 // If this ever proves to have a noticeable performance impact, allow users of the function to
248 // specify a specific range of addresses to limit the scan to. 327 // specify a specific range of addresses to limit the scan to.
@@ -495,8 +574,7 @@ u64 VMManager::GetTotalMemoryUsage() const {
495} 574}
496 575
497u64 VMManager::GetTotalHeapUsage() const { 576u64 VMManager::GetTotalHeapUsage() const {
498 LOG_WARNING(Kernel, "(STUBBED) called"); 577 return heap_used;
499 return 0x0;
500} 578}
501 579
502VAddr VMManager::GetAddressSpaceBaseAddress() const { 580VAddr VMManager::GetAddressSpaceBaseAddress() const {
diff --git a/src/core/hle/kernel/vm_manager.h b/src/core/hle/kernel/vm_manager.h
index 2447cbb8f..248cc46dc 100644
--- a/src/core/hle/kernel/vm_manager.h
+++ b/src/core/hle/kernel/vm_manager.h
@@ -186,6 +186,11 @@ public:
186 /// Changes the permissions of a range of addresses, splitting VMAs as necessary. 186 /// Changes the permissions of a range of addresses, splitting VMAs as necessary.
187 ResultCode ReprotectRange(VAddr target, u64 size, VMAPermission new_perms); 187 ResultCode ReprotectRange(VAddr target, u64 size, VMAPermission new_perms);
188 188
189 ResultVal<VAddr> HeapAllocate(VAddr target, u64 size, VMAPermission perms);
190 ResultCode HeapFree(VAddr target, u64 size);
191
192 ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size);
193
189 /** 194 /**
190 * Scans all VMAs and updates the page table range of any that use the given vector as backing 195 * Scans all VMAs and updates the page table range of any that use the given vector as backing
191 * memory. This should be called after any operation that causes reallocation of the vector. 196 * memory. This should be called after any operation that causes reallocation of the vector.
@@ -343,5 +348,15 @@ private:
343 348
344 VAddr tls_io_region_base = 0; 349 VAddr tls_io_region_base = 0;
345 VAddr tls_io_region_end = 0; 350 VAddr tls_io_region_end = 0;
351
352 // Memory used to back the allocations in the regular heap. A single vector is used to cover
353 // the entire virtual address space extents that bound the allocations, including any holes.
354 // This makes deallocation and reallocation of holes fast and keeps process memory contiguous
355 // in the emulator address space, allowing Memory::GetPointer to be reasonably safe.
356 std::shared_ptr<std::vector<u8>> heap_memory;
357 // The left/right bounds of the address space covered by heap_memory.
358 VAddr heap_start = 0;
359 VAddr heap_end = 0;
360 u64 heap_used = 0;
346}; 361};
347} // namespace Kernel 362} // namespace Kernel
diff --git a/src/core/hle/service/acc/acc.cpp b/src/core/hle/service/acc/acc.cpp
index c6437a671..c629f9357 100644
--- a/src/core/hle/service/acc/acc.cpp
+++ b/src/core/hle/service/acc/acc.cpp
@@ -242,6 +242,30 @@ void Module::Interface::GetBaasAccountManagerForApplication(Kernel::HLERequestCo
242 LOG_DEBUG(Service_ACC, "called"); 242 LOG_DEBUG(Service_ACC, "called");
243} 243}
244 244
245void Module::Interface::TrySelectUserWithoutInteraction(Kernel::HLERequestContext& ctx) {
246 LOG_DEBUG(Service_ACC, "called");
247 // A u8 is passed into this function which we can safely ignore. It's to determine if we have
248 // access to use the network or not by the looks of it
249 IPC::ResponseBuilder rb{ctx, 6};
250 if (profile_manager->GetUserCount() != 1) {
251 rb.Push(RESULT_SUCCESS);
252 rb.PushRaw<u128>(INVALID_UUID);
253 return;
254 }
255
256 const auto user_list = profile_manager->GetAllUsers();
257 if (std::all_of(user_list.begin(), user_list.end(),
258 [](const auto& user) { return user.uuid == INVALID_UUID; })) {
259 rb.Push(ResultCode(-1)); // TODO(ogniK): Find the correct error code
260 rb.PushRaw<u128>(INVALID_UUID);
261 return;
262 }
263
264 // Select the first user we have
265 rb.Push(RESULT_SUCCESS);
266 rb.PushRaw<u128>(profile_manager->GetUser(0)->uuid);
267}
268
245Module::Interface::Interface(std::shared_ptr<Module> module, 269Module::Interface::Interface(std::shared_ptr<Module> module,
246 std::shared_ptr<ProfileManager> profile_manager, const char* name) 270 std::shared_ptr<ProfileManager> profile_manager, const char* name)
247 : ServiceFramework(name), module(std::move(module)), 271 : ServiceFramework(name), module(std::move(module)),
diff --git a/src/core/hle/service/acc/acc.h b/src/core/hle/service/acc/acc.h
index c7ed74351..89b2104fa 100644
--- a/src/core/hle/service/acc/acc.h
+++ b/src/core/hle/service/acc/acc.h
@@ -27,6 +27,7 @@ public:
27 void InitializeApplicationInfo(Kernel::HLERequestContext& ctx); 27 void InitializeApplicationInfo(Kernel::HLERequestContext& ctx);
28 void GetBaasAccountManagerForApplication(Kernel::HLERequestContext& ctx); 28 void GetBaasAccountManagerForApplication(Kernel::HLERequestContext& ctx);
29 void IsUserRegistrationRequestPermitted(Kernel::HLERequestContext& ctx); 29 void IsUserRegistrationRequestPermitted(Kernel::HLERequestContext& ctx);
30 void TrySelectUserWithoutInteraction(Kernel::HLERequestContext& ctx);
30 31
31 protected: 32 protected:
32 std::shared_ptr<Module> module; 33 std::shared_ptr<Module> module;
diff --git a/src/core/hle/service/acc/acc_su.cpp b/src/core/hle/service/acc/acc_su.cpp
index ad455c3a7..5e2030355 100644
--- a/src/core/hle/service/acc/acc_su.cpp
+++ b/src/core/hle/service/acc/acc_su.cpp
@@ -17,7 +17,7 @@ ACC_SU::ACC_SU(std::shared_ptr<Module> module, std::shared_ptr<ProfileManager> p
17 {5, &ACC_SU::GetProfile, "GetProfile"}, 17 {5, &ACC_SU::GetProfile, "GetProfile"},
18 {6, nullptr, "GetProfileDigest"}, 18 {6, nullptr, "GetProfileDigest"},
19 {50, &ACC_SU::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"}, 19 {50, &ACC_SU::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"},
20 {51, nullptr, "TrySelectUserWithoutInteraction"}, 20 {51, &ACC_SU::TrySelectUserWithoutInteraction, "TrySelectUserWithoutInteraction"},
21 {60, nullptr, "ListOpenContextStoredUsers"}, 21 {60, nullptr, "ListOpenContextStoredUsers"},
22 {100, nullptr, "GetUserRegistrationNotifier"}, 22 {100, nullptr, "GetUserRegistrationNotifier"},
23 {101, nullptr, "GetUserStateChangeNotifier"}, 23 {101, nullptr, "GetUserStateChangeNotifier"},
diff --git a/src/core/hle/service/acc/acc_u0.cpp b/src/core/hle/service/acc/acc_u0.cpp
index 72d4adf35..a4d705b45 100644
--- a/src/core/hle/service/acc/acc_u0.cpp
+++ b/src/core/hle/service/acc/acc_u0.cpp
@@ -17,7 +17,7 @@ ACC_U0::ACC_U0(std::shared_ptr<Module> module, std::shared_ptr<ProfileManager> p
17 {5, &ACC_U0::GetProfile, "GetProfile"}, 17 {5, &ACC_U0::GetProfile, "GetProfile"},
18 {6, nullptr, "GetProfileDigest"}, 18 {6, nullptr, "GetProfileDigest"},
19 {50, &ACC_U0::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"}, 19 {50, &ACC_U0::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"},
20 {51, nullptr, "TrySelectUserWithoutInteraction"}, 20 {51, &ACC_U0::TrySelectUserWithoutInteraction, "TrySelectUserWithoutInteraction"},
21 {60, nullptr, "ListOpenContextStoredUsers"}, 21 {60, nullptr, "ListOpenContextStoredUsers"},
22 {100, &ACC_U0::InitializeApplicationInfo, "InitializeApplicationInfo"}, 22 {100, &ACC_U0::InitializeApplicationInfo, "InitializeApplicationInfo"},
23 {101, &ACC_U0::GetBaasAccountManagerForApplication, "GetBaasAccountManagerForApplication"}, 23 {101, &ACC_U0::GetBaasAccountManagerForApplication, "GetBaasAccountManagerForApplication"},
diff --git a/src/core/hle/service/acc/acc_u1.cpp b/src/core/hle/service/acc/acc_u1.cpp
index d480f08e5..8fffc93b5 100644
--- a/src/core/hle/service/acc/acc_u1.cpp
+++ b/src/core/hle/service/acc/acc_u1.cpp
@@ -17,7 +17,7 @@ ACC_U1::ACC_U1(std::shared_ptr<Module> module, std::shared_ptr<ProfileManager> p
17 {5, &ACC_U1::GetProfile, "GetProfile"}, 17 {5, &ACC_U1::GetProfile, "GetProfile"},
18 {6, nullptr, "GetProfileDigest"}, 18 {6, nullptr, "GetProfileDigest"},
19 {50, &ACC_U1::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"}, 19 {50, &ACC_U1::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"},
20 {51, nullptr, "TrySelectUserWithoutInteraction"}, 20 {51, &ACC_U1::TrySelectUserWithoutInteraction, "TrySelectUserWithoutInteraction"},
21 {60, nullptr, "ListOpenContextStoredUsers"}, 21 {60, nullptr, "ListOpenContextStoredUsers"},
22 {100, nullptr, "GetUserRegistrationNotifier"}, 22 {100, nullptr, "GetUserRegistrationNotifier"},
23 {101, nullptr, "GetUserStateChangeNotifier"}, 23 {101, nullptr, "GetUserStateChangeNotifier"},
diff --git a/src/core/hle/service/acc/profile_manager.cpp b/src/core/hle/service/acc/profile_manager.cpp
index 3cac1b4ff..968263846 100644
--- a/src/core/hle/service/acc/profile_manager.cpp
+++ b/src/core/hle/service/acc/profile_manager.cpp
@@ -2,8 +2,11 @@
2// Licensed under GPLv2 or any later version 2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <cstring>
5#include <random> 6#include <random>
6 7
8#include <fmt/format.h>
9
7#include "common/file_util.h" 10#include "common/file_util.h"
8#include "core/hle/service/acc/profile_manager.h" 11#include "core/hle/service/acc/profile_manager.h"
9#include "core/settings.h" 12#include "core/settings.h"
@@ -39,6 +42,19 @@ UUID UUID::Generate() {
39 return UUID{distribution(gen), distribution(gen)}; 42 return UUID{distribution(gen), distribution(gen)};
40} 43}
41 44
45std::string UUID::Format() const {
46 return fmt::format("0x{:016X}{:016X}", uuid[1], uuid[0]);
47}
48
49std::string UUID::FormatSwitch() const {
50 std::array<u8, 16> s{};
51 std::memcpy(s.data(), uuid.data(), sizeof(u128));
52 return fmt::format("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{"
53 ":02x}{:02x}{:02x}{:02x}{:02x}",
54 s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11],
55 s[12], s[13], s[14], s[15]);
56}
57
42ProfileManager::ProfileManager() { 58ProfileManager::ProfileManager() {
43 ParseUserSaveFile(); 59 ParseUserSaveFile();
44 60
@@ -195,7 +211,7 @@ std::size_t ProfileManager::GetOpenUserCount() const {
195 211
196/// Checks if a user id exists in our profile manager 212/// Checks if a user id exists in our profile manager
197bool ProfileManager::UserExists(UUID uuid) const { 213bool ProfileManager::UserExists(UUID uuid) const {
198 return GetUserIndex(uuid) != std::nullopt; 214 return GetUserIndex(uuid).has_value();
199} 215}
200 216
201bool ProfileManager::UserExistsIndex(std::size_t index) const { 217bool ProfileManager::UserExistsIndex(std::size_t index) const {
@@ -325,11 +341,12 @@ void ProfileManager::ParseUserSaveFile() {
325 return; 341 return;
326 } 342 }
327 343
328 for (std::size_t i = 0; i < MAX_USERS; ++i) { 344 for (const auto& user : data.users) {
329 const auto& user = data.users[i]; 345 if (user.uuid == UUID(INVALID_UUID)) {
346 continue;
347 }
330 348
331 if (user.uuid != UUID(INVALID_UUID)) 349 AddUser({user.uuid, user.username, user.timestamp, {}, false});
332 AddUser({user.uuid, user.username, user.timestamp, {}, false});
333 } 350 }
334 351
335 std::stable_partition(profiles.begin(), profiles.end(), 352 std::stable_partition(profiles.begin(), profiles.end(),
diff --git a/src/core/hle/service/acc/profile_manager.h b/src/core/hle/service/acc/profile_manager.h
index 1cd2e51b2..d2d8e6c6b 100644
--- a/src/core/hle/service/acc/profile_manager.h
+++ b/src/core/hle/service/acc/profile_manager.h
@@ -42,22 +42,14 @@ struct UUID {
42 void Invalidate() { 42 void Invalidate() {
43 uuid = INVALID_UUID; 43 uuid = INVALID_UUID;
44 } 44 }
45 std::string Format() const {
46 return fmt::format("0x{:016X}{:016X}", uuid[1], uuid[0]);
47 }
48 45
49 std::string FormatSwitch() const { 46 std::string Format() const;
50 std::array<u8, 16> s{}; 47 std::string FormatSwitch() const;
51 std::memcpy(s.data(), uuid.data(), sizeof(u128));
52 return fmt::format("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{"
53 ":02x}{:02x}{:02x}{:02x}{:02x}",
54 s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11],
55 s[12], s[13], s[14], s[15]);
56 }
57}; 48};
58static_assert(sizeof(UUID) == 16, "UUID is an invalid size!"); 49static_assert(sizeof(UUID) == 16, "UUID is an invalid size!");
59 50
60using ProfileUsername = std::array<u8, 0x20>; 51constexpr std::size_t profile_username_size = 32;
52using ProfileUsername = std::array<u8, profile_username_size>;
61using ProfileData = std::array<u8, MAX_DATA>; 53using ProfileData = std::array<u8, MAX_DATA>;
62using UserIDArray = std::array<UUID, MAX_USERS>; 54using UserIDArray = std::array<UUID, MAX_USERS>;
63 55
diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp
index 59aafd616..0477ce66e 100644
--- a/src/core/hle/service/am/am.cpp
+++ b/src/core/hle/service/am/am.cpp
@@ -338,7 +338,54 @@ void ISelfController::GetIdleTimeDetectionExtension(Kernel::HLERequestContext& c
338 LOG_WARNING(Service_AM, "(STUBBED) called"); 338 LOG_WARNING(Service_AM, "(STUBBED) called");
339} 339}
340 340
341ICommonStateGetter::ICommonStateGetter() : ServiceFramework("ICommonStateGetter") { 341AppletMessageQueue::AppletMessageQueue() {
342 auto& kernel = Core::System::GetInstance().Kernel();
343 on_new_message = Kernel::Event::Create(kernel, Kernel::ResetType::Sticky,
344 "AMMessageQueue:OnMessageRecieved");
345 on_operation_mode_changed = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
346 "AMMessageQueue:OperationModeChanged");
347}
348
349AppletMessageQueue::~AppletMessageQueue() = default;
350
351const Kernel::SharedPtr<Kernel::Event>& AppletMessageQueue::GetMesssageRecieveEvent() const {
352 return on_new_message;
353}
354
355const Kernel::SharedPtr<Kernel::Event>& AppletMessageQueue::GetOperationModeChangedEvent() const {
356 return on_operation_mode_changed;
357}
358
359void AppletMessageQueue::PushMessage(AppletMessage msg) {
360 messages.push(msg);
361 on_new_message->Signal();
362}
363
364AppletMessageQueue::AppletMessage AppletMessageQueue::PopMessage() {
365 if (messages.empty()) {
366 on_new_message->Clear();
367 return AppletMessage::NoMessage;
368 }
369 auto msg = messages.front();
370 messages.pop();
371 if (messages.empty()) {
372 on_new_message->Clear();
373 }
374 return msg;
375}
376
377std::size_t AppletMessageQueue::GetMessageCount() const {
378 return messages.size();
379}
380
381void AppletMessageQueue::OperationModeChanged() {
382 PushMessage(AppletMessage::OperationModeChanged);
383 PushMessage(AppletMessage::PerformanceModeChanged);
384 on_operation_mode_changed->Signal();
385}
386
387ICommonStateGetter::ICommonStateGetter(std::shared_ptr<AppletMessageQueue> msg_queue)
388 : ServiceFramework("ICommonStateGetter"), msg_queue(std::move(msg_queue)) {
342 // clang-format off 389 // clang-format off
343 static const FunctionInfo functions[] = { 390 static const FunctionInfo functions[] = {
344 {0, &ICommonStateGetter::GetEventHandle, "GetEventHandle"}, 391 {0, &ICommonStateGetter::GetEventHandle, "GetEventHandle"},
@@ -388,21 +435,19 @@ void ICommonStateGetter::GetBootMode(Kernel::HLERequestContext& ctx) {
388} 435}
389 436
390void ICommonStateGetter::GetEventHandle(Kernel::HLERequestContext& ctx) { 437void ICommonStateGetter::GetEventHandle(Kernel::HLERequestContext& ctx) {
391 event->Signal();
392
393 IPC::ResponseBuilder rb{ctx, 2, 1}; 438 IPC::ResponseBuilder rb{ctx, 2, 1};
394 rb.Push(RESULT_SUCCESS); 439 rb.Push(RESULT_SUCCESS);
395 rb.PushCopyObjects(event); 440 rb.PushCopyObjects(msg_queue->GetMesssageRecieveEvent());
396 441
397 LOG_WARNING(Service_AM, "(STUBBED) called"); 442 LOG_DEBUG(Service_AM, "called");
398} 443}
399 444
400void ICommonStateGetter::ReceiveMessage(Kernel::HLERequestContext& ctx) { 445void ICommonStateGetter::ReceiveMessage(Kernel::HLERequestContext& ctx) {
401 IPC::ResponseBuilder rb{ctx, 3}; 446 IPC::ResponseBuilder rb{ctx, 3};
402 rb.Push(RESULT_SUCCESS); 447 rb.Push(RESULT_SUCCESS);
403 rb.Push<u32>(15); 448 rb.PushEnum<AppletMessageQueue::AppletMessage>(msg_queue->PopMessage());
404 449
405 LOG_WARNING(Service_AM, "(STUBBED) called"); 450 LOG_DEBUG(Service_AM, "called");
406} 451}
407 452
408void ICommonStateGetter::GetCurrentFocusState(Kernel::HLERequestContext& ctx) { 453void ICommonStateGetter::GetCurrentFocusState(Kernel::HLERequestContext& ctx) {
@@ -414,13 +459,11 @@ void ICommonStateGetter::GetCurrentFocusState(Kernel::HLERequestContext& ctx) {
414} 459}
415 460
416void ICommonStateGetter::GetDefaultDisplayResolutionChangeEvent(Kernel::HLERequestContext& ctx) { 461void ICommonStateGetter::GetDefaultDisplayResolutionChangeEvent(Kernel::HLERequestContext& ctx) {
417 event->Signal();
418
419 IPC::ResponseBuilder rb{ctx, 2, 1}; 462 IPC::ResponseBuilder rb{ctx, 2, 1};
420 rb.Push(RESULT_SUCCESS); 463 rb.Push(RESULT_SUCCESS);
421 rb.PushCopyObjects(event); 464 rb.PushCopyObjects(msg_queue->GetOperationModeChangedEvent());
422 465
423 LOG_WARNING(Service_AM, "(STUBBED) called"); 466 LOG_DEBUG(Service_AM, "called");
424} 467}
425 468
426void ICommonStateGetter::GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx) { 469void ICommonStateGetter::GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx) {
@@ -444,7 +487,7 @@ void ICommonStateGetter::GetOperationMode(Kernel::HLERequestContext& ctx) {
444 rb.Push(RESULT_SUCCESS); 487 rb.Push(RESULT_SUCCESS);
445 rb.Push(static_cast<u8>(use_docked_mode ? OperationMode::Docked : OperationMode::Handheld)); 488 rb.Push(static_cast<u8>(use_docked_mode ? OperationMode::Docked : OperationMode::Handheld));
446 489
447 LOG_WARNING(Service_AM, "(STUBBED) called"); 490 LOG_DEBUG(Service_AM, "called");
448} 491}
449 492
450void ICommonStateGetter::GetPerformanceMode(Kernel::HLERequestContext& ctx) { 493void ICommonStateGetter::GetPerformanceMode(Kernel::HLERequestContext& ctx) {
@@ -454,7 +497,7 @@ void ICommonStateGetter::GetPerformanceMode(Kernel::HLERequestContext& ctx) {
454 rb.Push(static_cast<u32>(use_docked_mode ? APM::PerformanceMode::Docked 497 rb.Push(static_cast<u32>(use_docked_mode ? APM::PerformanceMode::Docked
455 : APM::PerformanceMode::Handheld)); 498 : APM::PerformanceMode::Handheld));
456 499
457 LOG_WARNING(Service_AM, "(STUBBED) called"); 500 LOG_DEBUG(Service_AM, "called");
458} 501}
459 502
460class IStorageAccessor final : public ServiceFramework<IStorageAccessor> { 503class IStorageAccessor final : public ServiceFramework<IStorageAccessor> {
@@ -743,7 +786,7 @@ void IApplicationFunctions::PopLaunchParameter(Kernel::HLERequestContext& ctx) {
743 786
744 Account::ProfileManager profile_manager{}; 787 Account::ProfileManager profile_manager{};
745 const auto uuid = profile_manager.GetUser(Settings::values.current_user); 788 const auto uuid = profile_manager.GetUser(Settings::values.current_user);
746 ASSERT(uuid != std::nullopt); 789 ASSERT(uuid);
747 params.current_user = uuid->uuid; 790 params.current_user = uuid->uuid;
748 791
749 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 792 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
@@ -840,8 +883,12 @@ void IApplicationFunctions::GetPseudoDeviceId(Kernel::HLERequestContext& ctx) {
840 883
841void InstallInterfaces(SM::ServiceManager& service_manager, 884void InstallInterfaces(SM::ServiceManager& service_manager,
842 std::shared_ptr<NVFlinger::NVFlinger> nvflinger) { 885 std::shared_ptr<NVFlinger::NVFlinger> nvflinger) {
843 std::make_shared<AppletAE>(nvflinger)->InstallAsService(service_manager); 886 auto message_queue = std::make_shared<AppletMessageQueue>();
844 std::make_shared<AppletOE>(nvflinger)->InstallAsService(service_manager); 887 message_queue->PushMessage(
888 AppletMessageQueue::AppletMessage::FocusStateChanged); // Needed on game boot
889
890 std::make_shared<AppletAE>(nvflinger, message_queue)->InstallAsService(service_manager);
891 std::make_shared<AppletOE>(nvflinger, message_queue)->InstallAsService(service_manager);
845 std::make_shared<IdleSys>()->InstallAsService(service_manager); 892 std::make_shared<IdleSys>()->InstallAsService(service_manager);
846 std::make_shared<OMM>()->InstallAsService(service_manager); 893 std::make_shared<OMM>()->InstallAsService(service_manager);
847 std::make_shared<SPSM>()->InstallAsService(service_manager); 894 std::make_shared<SPSM>()->InstallAsService(service_manager);
diff --git a/src/core/hle/service/am/am.h b/src/core/hle/service/am/am.h
index 095f94851..2f1c20bce 100644
--- a/src/core/hle/service/am/am.h
+++ b/src/core/hle/service/am/am.h
@@ -5,6 +5,7 @@
5#pragma once 5#pragma once
6 6
7#include <memory> 7#include <memory>
8#include <queue>
8#include "core/hle/service/service.h" 9#include "core/hle/service/service.h"
9 10
10namespace Kernel { 11namespace Kernel {
@@ -39,6 +40,31 @@ enum SystemLanguage {
39 TraditionalChinese = 16, 40 TraditionalChinese = 16,
40}; 41};
41 42
43class AppletMessageQueue {
44public:
45 enum class AppletMessage : u32 {
46 NoMessage = 0,
47 FocusStateChanged = 15,
48 OperationModeChanged = 30,
49 PerformanceModeChanged = 31,
50 };
51
52 AppletMessageQueue();
53 ~AppletMessageQueue();
54
55 const Kernel::SharedPtr<Kernel::Event>& GetMesssageRecieveEvent() const;
56 const Kernel::SharedPtr<Kernel::Event>& GetOperationModeChangedEvent() const;
57 void PushMessage(AppletMessage msg);
58 AppletMessage PopMessage();
59 std::size_t GetMessageCount() const;
60 void OperationModeChanged();
61
62private:
63 std::queue<AppletMessage> messages;
64 Kernel::SharedPtr<Kernel::Event> on_new_message;
65 Kernel::SharedPtr<Kernel::Event> on_operation_mode_changed;
66};
67
42class IWindowController final : public ServiceFramework<IWindowController> { 68class IWindowController final : public ServiceFramework<IWindowController> {
43public: 69public:
44 IWindowController(); 70 IWindowController();
@@ -102,7 +128,7 @@ private:
102 128
103class ICommonStateGetter final : public ServiceFramework<ICommonStateGetter> { 129class ICommonStateGetter final : public ServiceFramework<ICommonStateGetter> {
104public: 130public:
105 ICommonStateGetter(); 131 explicit ICommonStateGetter(std::shared_ptr<AppletMessageQueue> msg_queue);
106 ~ICommonStateGetter() override; 132 ~ICommonStateGetter() override;
107 133
108private: 134private:
@@ -126,6 +152,7 @@ private:
126 void GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx); 152 void GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx);
127 153
128 Kernel::SharedPtr<Kernel::Event> event; 154 Kernel::SharedPtr<Kernel::Event> event;
155 std::shared_ptr<AppletMessageQueue> msg_queue;
129}; 156};
130 157
131class ILibraryAppletCreator final : public ServiceFramework<ILibraryAppletCreator> { 158class ILibraryAppletCreator final : public ServiceFramework<ILibraryAppletCreator> {
diff --git a/src/core/hle/service/am/applet_ae.cpp b/src/core/hle/service/am/applet_ae.cpp
index 68ea778e8..ec93e3529 100644
--- a/src/core/hle/service/am/applet_ae.cpp
+++ b/src/core/hle/service/am/applet_ae.cpp
@@ -12,8 +12,10 @@ namespace Service::AM {
12 12
13class ILibraryAppletProxy final : public ServiceFramework<ILibraryAppletProxy> { 13class ILibraryAppletProxy final : public ServiceFramework<ILibraryAppletProxy> {
14public: 14public:
15 explicit ILibraryAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger) 15 explicit ILibraryAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
16 : ServiceFramework("ILibraryAppletProxy"), nvflinger(std::move(nvflinger)) { 16 std::shared_ptr<AppletMessageQueue> msg_queue)
17 : ServiceFramework("ILibraryAppletProxy"), nvflinger(std::move(nvflinger)),
18 msg_queue(std::move(msg_queue)) {
17 static const FunctionInfo functions[] = { 19 static const FunctionInfo functions[] = {
18 {0, &ILibraryAppletProxy::GetCommonStateGetter, "GetCommonStateGetter"}, 20 {0, &ILibraryAppletProxy::GetCommonStateGetter, "GetCommonStateGetter"},
19 {1, &ILibraryAppletProxy::GetSelfController, "GetSelfController"}, 21 {1, &ILibraryAppletProxy::GetSelfController, "GetSelfController"},
@@ -32,7 +34,7 @@ private:
32 void GetCommonStateGetter(Kernel::HLERequestContext& ctx) { 34 void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
33 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 35 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
34 rb.Push(RESULT_SUCCESS); 36 rb.Push(RESULT_SUCCESS);
35 rb.PushIpcInterface<ICommonStateGetter>(); 37 rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
36 LOG_DEBUG(Service_AM, "called"); 38 LOG_DEBUG(Service_AM, "called");
37 } 39 }
38 40
@@ -93,12 +95,15 @@ private:
93 } 95 }
94 96
95 std::shared_ptr<NVFlinger::NVFlinger> nvflinger; 97 std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
98 std::shared_ptr<AppletMessageQueue> msg_queue;
96}; 99};
97 100
98class ISystemAppletProxy final : public ServiceFramework<ISystemAppletProxy> { 101class ISystemAppletProxy final : public ServiceFramework<ISystemAppletProxy> {
99public: 102public:
100 explicit ISystemAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger) 103 explicit ISystemAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
101 : ServiceFramework("ISystemAppletProxy"), nvflinger(std::move(nvflinger)) { 104 std::shared_ptr<AppletMessageQueue> msg_queue)
105 : ServiceFramework("ISystemAppletProxy"), nvflinger(std::move(nvflinger)),
106 msg_queue(std::move(msg_queue)) {
102 static const FunctionInfo functions[] = { 107 static const FunctionInfo functions[] = {
103 {0, &ISystemAppletProxy::GetCommonStateGetter, "GetCommonStateGetter"}, 108 {0, &ISystemAppletProxy::GetCommonStateGetter, "GetCommonStateGetter"},
104 {1, &ISystemAppletProxy::GetSelfController, "GetSelfController"}, 109 {1, &ISystemAppletProxy::GetSelfController, "GetSelfController"},
@@ -119,7 +124,7 @@ private:
119 void GetCommonStateGetter(Kernel::HLERequestContext& ctx) { 124 void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
120 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 125 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
121 rb.Push(RESULT_SUCCESS); 126 rb.Push(RESULT_SUCCESS);
122 rb.PushIpcInterface<ICommonStateGetter>(); 127 rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
123 LOG_DEBUG(Service_AM, "called"); 128 LOG_DEBUG(Service_AM, "called");
124 } 129 }
125 130
@@ -186,31 +191,34 @@ private:
186 LOG_DEBUG(Service_AM, "called"); 191 LOG_DEBUG(Service_AM, "called");
187 } 192 }
188 std::shared_ptr<NVFlinger::NVFlinger> nvflinger; 193 std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
194 std::shared_ptr<AppletMessageQueue> msg_queue;
189}; 195};
190 196
191void AppletAE::OpenSystemAppletProxy(Kernel::HLERequestContext& ctx) { 197void AppletAE::OpenSystemAppletProxy(Kernel::HLERequestContext& ctx) {
192 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 198 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
193 rb.Push(RESULT_SUCCESS); 199 rb.Push(RESULT_SUCCESS);
194 rb.PushIpcInterface<ISystemAppletProxy>(nvflinger); 200 rb.PushIpcInterface<ISystemAppletProxy>(nvflinger, msg_queue);
195 LOG_DEBUG(Service_AM, "called"); 201 LOG_DEBUG(Service_AM, "called");
196} 202}
197 203
198void AppletAE::OpenLibraryAppletProxy(Kernel::HLERequestContext& ctx) { 204void AppletAE::OpenLibraryAppletProxy(Kernel::HLERequestContext& ctx) {
199 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 205 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
200 rb.Push(RESULT_SUCCESS); 206 rb.Push(RESULT_SUCCESS);
201 rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger); 207 rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger, msg_queue);
202 LOG_DEBUG(Service_AM, "called"); 208 LOG_DEBUG(Service_AM, "called");
203} 209}
204 210
205void AppletAE::OpenLibraryAppletProxyOld(Kernel::HLERequestContext& ctx) { 211void AppletAE::OpenLibraryAppletProxyOld(Kernel::HLERequestContext& ctx) {
206 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 212 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
207 rb.Push(RESULT_SUCCESS); 213 rb.Push(RESULT_SUCCESS);
208 rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger); 214 rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger, msg_queue);
209 LOG_DEBUG(Service_AM, "called"); 215 LOG_DEBUG(Service_AM, "called");
210} 216}
211 217
212AppletAE::AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger) 218AppletAE::AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
213 : ServiceFramework("appletAE"), nvflinger(std::move(nvflinger)) { 219 std::shared_ptr<AppletMessageQueue> msg_queue)
220 : ServiceFramework("appletAE"), nvflinger(std::move(nvflinger)),
221 msg_queue(std::move(msg_queue)) {
214 // clang-format off 222 // clang-format off
215 static const FunctionInfo functions[] = { 223 static const FunctionInfo functions[] = {
216 {100, &AppletAE::OpenSystemAppletProxy, "OpenSystemAppletProxy"}, 224 {100, &AppletAE::OpenSystemAppletProxy, "OpenSystemAppletProxy"},
@@ -228,4 +236,8 @@ AppletAE::AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
228 236
229AppletAE::~AppletAE() = default; 237AppletAE::~AppletAE() = default;
230 238
239const std::shared_ptr<AppletMessageQueue>& AppletAE::GetMessageQueue() const {
240 return msg_queue;
241}
242
231} // namespace Service::AM 243} // namespace Service::AM
diff --git a/src/core/hle/service/am/applet_ae.h b/src/core/hle/service/am/applet_ae.h
index 1ed77baa4..902db2665 100644
--- a/src/core/hle/service/am/applet_ae.h
+++ b/src/core/hle/service/am/applet_ae.h
@@ -17,15 +17,19 @@ namespace AM {
17 17
18class AppletAE final : public ServiceFramework<AppletAE> { 18class AppletAE final : public ServiceFramework<AppletAE> {
19public: 19public:
20 explicit AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger); 20 explicit AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
21 std::shared_ptr<AppletMessageQueue> msg_queue);
21 ~AppletAE() override; 22 ~AppletAE() override;
22 23
24 const std::shared_ptr<AppletMessageQueue>& GetMessageQueue() const;
25
23private: 26private:
24 void OpenSystemAppletProxy(Kernel::HLERequestContext& ctx); 27 void OpenSystemAppletProxy(Kernel::HLERequestContext& ctx);
25 void OpenLibraryAppletProxy(Kernel::HLERequestContext& ctx); 28 void OpenLibraryAppletProxy(Kernel::HLERequestContext& ctx);
26 void OpenLibraryAppletProxyOld(Kernel::HLERequestContext& ctx); 29 void OpenLibraryAppletProxyOld(Kernel::HLERequestContext& ctx);
27 30
28 std::shared_ptr<NVFlinger::NVFlinger> nvflinger; 31 std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
32 std::shared_ptr<AppletMessageQueue> msg_queue;
29}; 33};
30 34
31} // namespace AM 35} // namespace AM
diff --git a/src/core/hle/service/am/applet_oe.cpp b/src/core/hle/service/am/applet_oe.cpp
index 60717afd9..20c8d5fff 100644
--- a/src/core/hle/service/am/applet_oe.cpp
+++ b/src/core/hle/service/am/applet_oe.cpp
@@ -12,8 +12,10 @@ namespace Service::AM {
12 12
13class IApplicationProxy final : public ServiceFramework<IApplicationProxy> { 13class IApplicationProxy final : public ServiceFramework<IApplicationProxy> {
14public: 14public:
15 explicit IApplicationProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger) 15 explicit IApplicationProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
16 : ServiceFramework("IApplicationProxy"), nvflinger(std::move(nvflinger)) { 16 std::shared_ptr<AppletMessageQueue> msg_queue)
17 : ServiceFramework("IApplicationProxy"), nvflinger(std::move(nvflinger)),
18 msg_queue(std::move(msg_queue)) {
17 // clang-format off 19 // clang-format off
18 static const FunctionInfo functions[] = { 20 static const FunctionInfo functions[] = {
19 {0, &IApplicationProxy::GetCommonStateGetter, "GetCommonStateGetter"}, 21 {0, &IApplicationProxy::GetCommonStateGetter, "GetCommonStateGetter"},
@@ -70,7 +72,7 @@ private:
70 void GetCommonStateGetter(Kernel::HLERequestContext& ctx) { 72 void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
71 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 73 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
72 rb.Push(RESULT_SUCCESS); 74 rb.Push(RESULT_SUCCESS);
73 rb.PushIpcInterface<ICommonStateGetter>(); 75 rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
74 LOG_DEBUG(Service_AM, "called"); 76 LOG_DEBUG(Service_AM, "called");
75 } 77 }
76 78
@@ -89,17 +91,20 @@ private:
89 } 91 }
90 92
91 std::shared_ptr<NVFlinger::NVFlinger> nvflinger; 93 std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
94 std::shared_ptr<AppletMessageQueue> msg_queue;
92}; 95};
93 96
94void AppletOE::OpenApplicationProxy(Kernel::HLERequestContext& ctx) { 97void AppletOE::OpenApplicationProxy(Kernel::HLERequestContext& ctx) {
95 IPC::ResponseBuilder rb{ctx, 2, 0, 1}; 98 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
96 rb.Push(RESULT_SUCCESS); 99 rb.Push(RESULT_SUCCESS);
97 rb.PushIpcInterface<IApplicationProxy>(nvflinger); 100 rb.PushIpcInterface<IApplicationProxy>(nvflinger, msg_queue);
98 LOG_DEBUG(Service_AM, "called"); 101 LOG_DEBUG(Service_AM, "called");
99} 102}
100 103
101AppletOE::AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger) 104AppletOE::AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
102 : ServiceFramework("appletOE"), nvflinger(std::move(nvflinger)) { 105 std::shared_ptr<AppletMessageQueue> msg_queue)
106 : ServiceFramework("appletOE"), nvflinger(std::move(nvflinger)),
107 msg_queue(std::move(msg_queue)) {
103 static const FunctionInfo functions[] = { 108 static const FunctionInfo functions[] = {
104 {0, &AppletOE::OpenApplicationProxy, "OpenApplicationProxy"}, 109 {0, &AppletOE::OpenApplicationProxy, "OpenApplicationProxy"},
105 }; 110 };
@@ -108,4 +113,8 @@ AppletOE::AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
108 113
109AppletOE::~AppletOE() = default; 114AppletOE::~AppletOE() = default;
110 115
116const std::shared_ptr<AppletMessageQueue>& AppletOE::GetMessageQueue() const {
117 return msg_queue;
118}
119
111} // namespace Service::AM 120} // namespace Service::AM
diff --git a/src/core/hle/service/am/applet_oe.h b/src/core/hle/service/am/applet_oe.h
index 60cfdfd9d..bbd0108ef 100644
--- a/src/core/hle/service/am/applet_oe.h
+++ b/src/core/hle/service/am/applet_oe.h
@@ -17,13 +17,17 @@ namespace AM {
17 17
18class AppletOE final : public ServiceFramework<AppletOE> { 18class AppletOE final : public ServiceFramework<AppletOE> {
19public: 19public:
20 explicit AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger); 20 explicit AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
21 std::shared_ptr<AppletMessageQueue> msg_queue);
21 ~AppletOE() override; 22 ~AppletOE() override;
22 23
24 const std::shared_ptr<AppletMessageQueue>& GetMessageQueue() const;
25
23private: 26private:
24 void OpenApplicationProxy(Kernel::HLERequestContext& ctx); 27 void OpenApplicationProxy(Kernel::HLERequestContext& ctx);
25 28
26 std::shared_ptr<NVFlinger::NVFlinger> nvflinger; 29 std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
30 std::shared_ptr<AppletMessageQueue> msg_queue;
27}; 31};
28 32
29} // namespace AM 33} // namespace AM
diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp
index fac6785a5..d3ea57ea7 100644
--- a/src/core/hle/service/audio/audren_u.cpp
+++ b/src/core/hle/service/audio/audren_u.cpp
@@ -28,13 +28,13 @@ public:
28 {1, &IAudioRenderer::GetSampleCount, "GetSampleCount"}, 28 {1, &IAudioRenderer::GetSampleCount, "GetSampleCount"},
29 {2, &IAudioRenderer::GetMixBufferCount, "GetMixBufferCount"}, 29 {2, &IAudioRenderer::GetMixBufferCount, "GetMixBufferCount"},
30 {3, &IAudioRenderer::GetState, "GetState"}, 30 {3, &IAudioRenderer::GetState, "GetState"},
31 {4, &IAudioRenderer::RequestUpdate, "RequestUpdate"}, 31 {4, &IAudioRenderer::RequestUpdateImpl, "RequestUpdate"},
32 {5, &IAudioRenderer::Start, "Start"}, 32 {5, &IAudioRenderer::Start, "Start"},
33 {6, &IAudioRenderer::Stop, "Stop"}, 33 {6, &IAudioRenderer::Stop, "Stop"},
34 {7, &IAudioRenderer::QuerySystemEvent, "QuerySystemEvent"}, 34 {7, &IAudioRenderer::QuerySystemEvent, "QuerySystemEvent"},
35 {8, nullptr, "SetRenderingTimeLimit"}, 35 {8, &IAudioRenderer::SetRenderingTimeLimit, "SetRenderingTimeLimit"},
36 {9, nullptr, "GetRenderingTimeLimit"}, 36 {9, &IAudioRenderer::GetRenderingTimeLimit, "GetRenderingTimeLimit"},
37 {10, nullptr, "RequestUpdateAuto"}, 37 {10, &IAudioRenderer::RequestUpdateImpl, "RequestUpdateAuto"},
38 {11, nullptr, "ExecuteAudioRendererRendering"}, 38 {11, nullptr, "ExecuteAudioRendererRendering"},
39 }; 39 };
40 // clang-format on 40 // clang-format on
@@ -79,7 +79,7 @@ private:
79 LOG_DEBUG(Service_Audio, "called"); 79 LOG_DEBUG(Service_Audio, "called");
80 } 80 }
81 81
82 void RequestUpdate(Kernel::HLERequestContext& ctx) { 82 void RequestUpdateImpl(Kernel::HLERequestContext& ctx) {
83 ctx.WriteBuffer(renderer->UpdateAudioRenderer(ctx.ReadBuffer())); 83 ctx.WriteBuffer(renderer->UpdateAudioRenderer(ctx.ReadBuffer()));
84 IPC::ResponseBuilder rb{ctx, 2}; 84 IPC::ResponseBuilder rb{ctx, 2};
85 rb.Push(RESULT_SUCCESS); 85 rb.Push(RESULT_SUCCESS);
@@ -110,8 +110,29 @@ private:
110 LOG_WARNING(Service_Audio, "(STUBBED) called"); 110 LOG_WARNING(Service_Audio, "(STUBBED) called");
111 } 111 }
112 112
113 void SetRenderingTimeLimit(Kernel::HLERequestContext& ctx) {
114 IPC::RequestParser rp{ctx};
115 rendering_time_limit_percent = rp.Pop<u32>();
116 ASSERT(rendering_time_limit_percent >= 0 && rendering_time_limit_percent <= 100);
117
118 IPC::ResponseBuilder rb{ctx, 2};
119 rb.Push(RESULT_SUCCESS);
120
121 LOG_DEBUG(Service_Audio, "called. rendering_time_limit_percent={}",
122 rendering_time_limit_percent);
123 }
124
125 void GetRenderingTimeLimit(Kernel::HLERequestContext& ctx) {
126 LOG_DEBUG(Service_Audio, "called");
127
128 IPC::ResponseBuilder rb{ctx, 3};
129 rb.Push(RESULT_SUCCESS);
130 rb.Push(rendering_time_limit_percent);
131 }
132
113 Kernel::SharedPtr<Kernel::Event> system_event; 133 Kernel::SharedPtr<Kernel::Event> system_event;
114 std::unique_ptr<AudioCore::AudioRenderer> renderer; 134 std::unique_ptr<AudioCore::AudioRenderer> renderer;
135 u32 rendering_time_limit_percent = 100;
115}; 136};
116 137
117class IAudioDevice final : public ServiceFramework<IAudioDevice> { 138class IAudioDevice final : public ServiceFramework<IAudioDevice> {
diff --git a/src/core/hle/service/audio/hwopus.cpp b/src/core/hle/service/audio/hwopus.cpp
index 7168c6a10..783c39503 100644
--- a/src/core/hle/service/audio/hwopus.cpp
+++ b/src/core/hle/service/audio/hwopus.cpp
@@ -161,7 +161,7 @@ void HwOpus::OpenOpusDecoder(Kernel::HLERequestContext& ctx) {
161 ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count"); 161 ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
162 162
163 std::size_t worker_sz = WorkerBufferSize(channel_count); 163 std::size_t worker_sz = WorkerBufferSize(channel_count);
164 ASSERT_MSG(buffer_sz < worker_sz, "Worker buffer too large"); 164 ASSERT_MSG(buffer_sz >= worker_sz, "Worker buffer too large");
165 std::unique_ptr<OpusDecoder, OpusDeleter> decoder{ 165 std::unique_ptr<OpusDecoder, OpusDeleter> decoder{
166 static_cast<OpusDecoder*>(operator new(worker_sz))}; 166 static_cast<OpusDecoder*>(operator new(worker_sz))};
167 if (opus_decoder_init(decoder.get(), sample_rate, channel_count)) { 167 if (opus_decoder_init(decoder.get(), sample_rate, channel_count)) {
diff --git a/src/core/hle/service/filesystem/filesystem.cpp b/src/core/hle/service/filesystem/filesystem.cpp
index 234a8687b..a92cf7815 100644
--- a/src/core/hle/service/filesystem/filesystem.cpp
+++ b/src/core/hle/service/filesystem/filesystem.cpp
@@ -309,6 +309,16 @@ ResultVal<FileSys::VirtualDir> OpenSaveData(FileSys::SaveDataSpaceId space,
309 return save_data_factory->Open(space, save_struct); 309 return save_data_factory->Open(space, save_struct);
310} 310}
311 311
312ResultVal<FileSys::VirtualDir> OpenSaveDataSpace(FileSys::SaveDataSpaceId space) {
313 LOG_TRACE(Service_FS, "Opening Save Data Space for space_id={:01X}", static_cast<u8>(space));
314
315 if (save_data_factory == nullptr) {
316 return ResultCode(ErrorModule::FS, FileSys::ErrCodes::TitleNotFound);
317 }
318
319 return MakeResult(save_data_factory->GetSaveDataSpaceDirectory(space));
320}
321
312ResultVal<FileSys::VirtualDir> OpenSDMC() { 322ResultVal<FileSys::VirtualDir> OpenSDMC() {
313 LOG_TRACE(Service_FS, "Opening SDMC"); 323 LOG_TRACE(Service_FS, "Opening SDMC");
314 324
diff --git a/src/core/hle/service/filesystem/filesystem.h b/src/core/hle/service/filesystem/filesystem.h
index b18652a68..e38f02869 100644
--- a/src/core/hle/service/filesystem/filesystem.h
+++ b/src/core/hle/service/filesystem/filesystem.h
@@ -45,6 +45,7 @@ ResultVal<FileSys::VirtualFile> OpenRomFS(u64 title_id, FileSys::StorageId stora
45 FileSys::ContentRecordType type); 45 FileSys::ContentRecordType type);
46ResultVal<FileSys::VirtualDir> OpenSaveData(FileSys::SaveDataSpaceId space, 46ResultVal<FileSys::VirtualDir> OpenSaveData(FileSys::SaveDataSpaceId space,
47 FileSys::SaveDataDescriptor save_struct); 47 FileSys::SaveDataDescriptor save_struct);
48ResultVal<FileSys::VirtualDir> OpenSaveDataSpace(FileSys::SaveDataSpaceId space);
48ResultVal<FileSys::VirtualDir> OpenSDMC(); 49ResultVal<FileSys::VirtualDir> OpenSDMC();
49 50
50std::unique_ptr<FileSys::RegisteredCacheUnion> GetUnionContents(); 51std::unique_ptr<FileSys::RegisteredCacheUnion> GetUnionContents();
diff --git a/src/core/hle/service/filesystem/fsp_srv.cpp b/src/core/hle/service/filesystem/fsp_srv.cpp
index c1c83a11d..b9a1d5105 100644
--- a/src/core/hle/service/filesystem/fsp_srv.cpp
+++ b/src/core/hle/service/filesystem/fsp_srv.cpp
@@ -11,6 +11,7 @@
11 11
12#include "common/assert.h" 12#include "common/assert.h"
13#include "common/common_types.h" 13#include "common/common_types.h"
14#include "common/hex_util.h"
14#include "common/logging/log.h" 15#include "common/logging/log.h"
15#include "common/string_util.h" 16#include "common/string_util.h"
16#include "core/file_sys/directory.h" 17#include "core/file_sys/directory.h"
@@ -451,7 +452,147 @@ private:
451 VfsDirectoryServiceWrapper backend; 452 VfsDirectoryServiceWrapper backend;
452}; 453};
453 454
455class ISaveDataInfoReader final : public ServiceFramework<ISaveDataInfoReader> {
456public:
457 explicit ISaveDataInfoReader(FileSys::SaveDataSpaceId space)
458 : ServiceFramework("ISaveDataInfoReader") {
459 static const FunctionInfo functions[] = {
460 {0, &ISaveDataInfoReader::ReadSaveDataInfo, "ReadSaveDataInfo"},
461 };
462 RegisterHandlers(functions);
463
464 FindAllSaves(space);
465 }
466
467 void ReadSaveDataInfo(Kernel::HLERequestContext& ctx) {
468 // Calculate how many entries we can fit in the output buffer
469 const u64 count_entries = ctx.GetWriteBufferSize() / sizeof(SaveDataInfo);
470
471 // Cap at total number of entries.
472 const u64 actual_entries = std::min(count_entries, info.size() - next_entry_index);
473
474 // Determine data start and end
475 const auto* begin = reinterpret_cast<u8*>(info.data() + next_entry_index);
476 const auto* end = reinterpret_cast<u8*>(info.data() + next_entry_index + actual_entries);
477 const auto range_size = static_cast<std::size_t>(std::distance(begin, end));
478
479 next_entry_index += actual_entries;
480
481 // Write the data to memory
482 ctx.WriteBuffer(begin, range_size);
483
484 IPC::ResponseBuilder rb{ctx, 3};
485 rb.Push(RESULT_SUCCESS);
486 rb.Push<u32>(static_cast<u32>(actual_entries));
487 }
488
489private:
490 static u64 stoull_be(std::string_view str) {
491 if (str.size() != 16)
492 return 0;
493
494 const auto bytes = Common::HexStringToArray<0x8>(str);
495 u64 out{};
496 std::memcpy(&out, bytes.data(), sizeof(u64));
497
498 return Common::swap64(out);
499 }
500
501 void FindAllSaves(FileSys::SaveDataSpaceId space) {
502 const auto save_root = OpenSaveDataSpace(space);
503 ASSERT(save_root.Succeeded());
504
505 for (const auto& type : (*save_root)->GetSubdirectories()) {
506 if (type->GetName() == "save") {
507 for (const auto& save_id : type->GetSubdirectories()) {
508 for (const auto& user_id : save_id->GetSubdirectories()) {
509 const auto save_id_numeric = stoull_be(save_id->GetName());
510 auto user_id_numeric = Common::HexStringToArray<0x10>(user_id->GetName());
511 std::reverse(user_id_numeric.begin(), user_id_numeric.end());
512
513 if (save_id_numeric != 0) {
514 // System Save Data
515 info.emplace_back(SaveDataInfo{
516 0,
517 space,
518 FileSys::SaveDataType::SystemSaveData,
519 {},
520 user_id_numeric,
521 save_id_numeric,
522 0,
523 user_id->GetSize(),
524 {},
525 });
526
527 continue;
528 }
529
530 for (const auto& title_id : user_id->GetSubdirectories()) {
531 const auto device =
532 std::all_of(user_id_numeric.begin(), user_id_numeric.end(),
533 [](u8 val) { return val == 0; });
534 info.emplace_back(SaveDataInfo{
535 0,
536 space,
537 device ? FileSys::SaveDataType::DeviceSaveData
538 : FileSys::SaveDataType::SaveData,
539 {},
540 user_id_numeric,
541 save_id_numeric,
542 stoull_be(title_id->GetName()),
543 title_id->GetSize(),
544 {},
545 });
546 }
547 }
548 }
549 } else if (space == FileSys::SaveDataSpaceId::TemporaryStorage) {
550 // Temporary Storage
551 for (const auto& user_id : type->GetSubdirectories()) {
552 for (const auto& title_id : user_id->GetSubdirectories()) {
553 if (!title_id->GetFiles().empty() ||
554 !title_id->GetSubdirectories().empty()) {
555 auto user_id_numeric =
556 Common::HexStringToArray<0x10>(user_id->GetName());
557 std::reverse(user_id_numeric.begin(), user_id_numeric.end());
558
559 info.emplace_back(SaveDataInfo{
560 0,
561 space,
562 FileSys::SaveDataType::TemporaryStorage,
563 {},
564 user_id_numeric,
565 stoull_be(type->GetName()),
566 stoull_be(title_id->GetName()),
567 title_id->GetSize(),
568 {},
569 });
570 }
571 }
572 }
573 }
574 }
575 }
576
577 struct SaveDataInfo {
578 u64_le save_id_unknown;
579 FileSys::SaveDataSpaceId space;
580 FileSys::SaveDataType type;
581 INSERT_PADDING_BYTES(0x6);
582 std::array<u8, 0x10> user_id;
583 u64_le save_id;
584 u64_le title_id;
585 u64_le save_image_size;
586 INSERT_PADDING_BYTES(0x28);
587 };
588 static_assert(sizeof(SaveDataInfo) == 0x60, "SaveDataInfo has incorrect size.");
589
590 std::vector<SaveDataInfo> info;
591 u64 next_entry_index = 0;
592};
593
454FSP_SRV::FSP_SRV() : ServiceFramework("fsp-srv") { 594FSP_SRV::FSP_SRV() : ServiceFramework("fsp-srv") {
595 // clang-format off
455 static const FunctionInfo functions[] = { 596 static const FunctionInfo functions[] = {
456 {0, nullptr, "MountContent"}, 597 {0, nullptr, "MountContent"},
457 {1, &FSP_SRV::Initialize, "Initialize"}, 598 {1, &FSP_SRV::Initialize, "Initialize"},
@@ -485,7 +626,7 @@ FSP_SRV::FSP_SRV() : ServiceFramework("fsp-srv") {
485 {58, nullptr, "ReadSaveDataFileSystemExtraData"}, 626 {58, nullptr, "ReadSaveDataFileSystemExtraData"},
486 {59, nullptr, "WriteSaveDataFileSystemExtraData"}, 627 {59, nullptr, "WriteSaveDataFileSystemExtraData"},
487 {60, nullptr, "OpenSaveDataInfoReader"}, 628 {60, nullptr, "OpenSaveDataInfoReader"},
488 {61, nullptr, "OpenSaveDataInfoReaderBySaveDataSpaceId"}, 629 {61, &FSP_SRV::OpenSaveDataInfoReaderBySaveDataSpaceId, "OpenSaveDataInfoReaderBySaveDataSpaceId"},
489 {62, nullptr, "OpenCacheStorageList"}, 630 {62, nullptr, "OpenCacheStorageList"},
490 {64, nullptr, "OpenSaveDataInternalStorageFileSystem"}, 631 {64, nullptr, "OpenSaveDataInternalStorageFileSystem"},
491 {65, nullptr, "UpdateSaveDataMacForDebug"}, 632 {65, nullptr, "UpdateSaveDataMacForDebug"},
@@ -544,6 +685,7 @@ FSP_SRV::FSP_SRV() : ServiceFramework("fsp-srv") {
544 {1009, nullptr, "GetAndClearMemoryReportInfo"}, 685 {1009, nullptr, "GetAndClearMemoryReportInfo"},
545 {1100, nullptr, "OverrideSaveDataTransferTokenSignVerificationKey"}, 686 {1100, nullptr, "OverrideSaveDataTransferTokenSignVerificationKey"},
546 }; 687 };
688 // clang-format on
547 RegisterHandlers(functions); 689 RegisterHandlers(functions);
548} 690}
549 691
@@ -618,6 +760,15 @@ void FSP_SRV::OpenReadOnlySaveDataFileSystem(Kernel::HLERequestContext& ctx) {
618 MountSaveData(ctx); 760 MountSaveData(ctx);
619} 761}
620 762
763void FSP_SRV::OpenSaveDataInfoReaderBySaveDataSpaceId(Kernel::HLERequestContext& ctx) {
764 IPC::RequestParser rp{ctx};
765 const auto space = rp.PopRaw<FileSys::SaveDataSpaceId>();
766
767 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
768 rb.Push(RESULT_SUCCESS);
769 rb.PushIpcInterface<ISaveDataInfoReader>(std::make_shared<ISaveDataInfoReader>(space));
770}
771
621void FSP_SRV::GetGlobalAccessLogMode(Kernel::HLERequestContext& ctx) { 772void FSP_SRV::GetGlobalAccessLogMode(Kernel::HLERequestContext& ctx) {
622 LOG_WARNING(Service_FS, "(STUBBED) called"); 773 LOG_WARNING(Service_FS, "(STUBBED) called");
623 774
diff --git a/src/core/hle/service/filesystem/fsp_srv.h b/src/core/hle/service/filesystem/fsp_srv.h
index 4aa0358cb..e7abec0a3 100644
--- a/src/core/hle/service/filesystem/fsp_srv.h
+++ b/src/core/hle/service/filesystem/fsp_srv.h
@@ -25,6 +25,7 @@ private:
25 void CreateSaveData(Kernel::HLERequestContext& ctx); 25 void CreateSaveData(Kernel::HLERequestContext& ctx);
26 void MountSaveData(Kernel::HLERequestContext& ctx); 26 void MountSaveData(Kernel::HLERequestContext& ctx);
27 void OpenReadOnlySaveDataFileSystem(Kernel::HLERequestContext& ctx); 27 void OpenReadOnlySaveDataFileSystem(Kernel::HLERequestContext& ctx);
28 void OpenSaveDataInfoReaderBySaveDataSpaceId(Kernel::HLERequestContext& ctx);
28 void GetGlobalAccessLogMode(Kernel::HLERequestContext& ctx); 29 void GetGlobalAccessLogMode(Kernel::HLERequestContext& ctx);
29 void OpenDataStorageByCurrentProcess(Kernel::HLERequestContext& ctx); 30 void OpenDataStorageByCurrentProcess(Kernel::HLERequestContext& ctx);
30 void OpenDataStorageByDataId(Kernel::HLERequestContext& ctx); 31 void OpenDataStorageByDataId(Kernel::HLERequestContext& ctx);
diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp
index 4b4d1324f..56c415e4e 100644
--- a/src/core/hle/service/hid/controllers/npad.cpp
+++ b/src/core/hle/service/hid/controllers/npad.cpp
@@ -310,6 +310,7 @@ void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
310 dual_entry.pad_states.raw = pad_state.raw; 310 dual_entry.pad_states.raw = pad_state.raw;
311 dual_entry.l_stick = lstick_entry; 311 dual_entry.l_stick = lstick_entry;
312 dual_entry.r_stick = rstick_entry; 312 dual_entry.r_stick = rstick_entry;
313 break;
313 case NPadControllerType::JoyLeft: 314 case NPadControllerType::JoyLeft:
314 left_entry.connection_status.raw = 0; 315 left_entry.connection_status.raw = 0;
315 316
@@ -392,8 +393,10 @@ std::size_t Controller_NPad::GetSupportedNPadIdTypesSize() const {
392} 393}
393 394
394void Controller_NPad::SetHoldType(NpadHoldType joy_hold_type) { 395void Controller_NPad::SetHoldType(NpadHoldType joy_hold_type) {
396 styleset_changed_event->Signal();
395 hold_type = joy_hold_type; 397 hold_type = joy_hold_type;
396} 398}
399
397Controller_NPad::NpadHoldType Controller_NPad::GetHoldType() const { 400Controller_NPad::NpadHoldType Controller_NPad::GetHoldType() const {
398 return hold_type; 401 return hold_type;
399} 402}
@@ -427,6 +430,9 @@ void Controller_NPad::VibrateController(const std::vector<u32>& controller_ids,
427} 430}
428 431
429Kernel::SharedPtr<Kernel::Event> Controller_NPad::GetStyleSetChangedEvent() const { 432Kernel::SharedPtr<Kernel::Event> Controller_NPad::GetStyleSetChangedEvent() const {
433 // TODO(ogniK): Figure out the best time to signal this event. This event seems that it should
434 // be signalled at least once, and signaled after a new controller is connected?
435 styleset_changed_event->Signal();
430 return styleset_changed_event; 436 return styleset_changed_event;
431} 437}
432 438
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index a9aa9ec78..a45fd4954 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -96,6 +96,8 @@ public:
96 // TODO(shinyquagsire23): Other update callbacks? (accel, gyro?) 96 // TODO(shinyquagsire23): Other update callbacks? (accel, gyro?)
97 97
98 CoreTiming::ScheduleEvent(pad_update_ticks, pad_update_event); 98 CoreTiming::ScheduleEvent(pad_update_ticks, pad_update_event);
99
100 ReloadInputDevices();
99 } 101 }
100 102
101 void ActivateController(HidController controller) { 103 void ActivateController(HidController controller) {
diff --git a/src/core/hle/service/nfp/nfp.cpp b/src/core/hle/service/nfp/nfp.cpp
index c1af878fe..1d6e7756f 100644
--- a/src/core/hle/service/nfp/nfp.cpp
+++ b/src/core/hle/service/nfp/nfp.cpp
@@ -212,7 +212,7 @@ private:
212 IPC::ResponseBuilder rb{ctx, 2}; 212 IPC::ResponseBuilder rb{ctx, 2};
213 auto amiibo = nfp_interface.GetAmiiboBuffer(); 213 auto amiibo = nfp_interface.GetAmiiboBuffer();
214 TagInfo tag_info{}; 214 TagInfo tag_info{};
215 std::memcpy(tag_info.uuid.data(), amiibo.uuid.data(), sizeof(tag_info.uuid.size())); 215 tag_info.uuid = amiibo.uuid;
216 tag_info.uuid_length = static_cast<u8>(tag_info.uuid.size()); 216 tag_info.uuid_length = static_cast<u8>(tag_info.uuid.size());
217 217
218 tag_info.protocol = 1; // TODO(ogniK): Figure out actual values 218 tag_info.protocol = 1; // TODO(ogniK): Figure out actual values
diff --git a/src/core/hle/service/ns/ns.cpp b/src/core/hle/service/ns/ns.cpp
index 07c1381fe..1d2978f24 100644
--- a/src/core/hle/service/ns/ns.cpp
+++ b/src/core/hle/service/ns/ns.cpp
@@ -2,6 +2,9 @@
2// Licensed under GPLv2 or any later version 2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include "common/logging/log.h"
6#include "core/file_sys/control_metadata.h"
7#include "core/file_sys/patch_manager.h"
5#include "core/hle/ipc_helpers.h" 8#include "core/hle/ipc_helpers.h"
6#include "core/hle/kernel/hle_ipc.h" 9#include "core/hle/kernel/hle_ipc.h"
7#include "core/hle/service/ns/ns.h" 10#include "core/hle/service/ns/ns.h"
@@ -118,7 +121,7 @@ public:
118 {305, nullptr, "TerminateSystemApplet"}, 121 {305, nullptr, "TerminateSystemApplet"},
119 {306, nullptr, "LaunchOverlayApplet"}, 122 {306, nullptr, "LaunchOverlayApplet"},
120 {307, nullptr, "TerminateOverlayApplet"}, 123 {307, nullptr, "TerminateOverlayApplet"},
121 {400, nullptr, "GetApplicationControlData"}, 124 {400, &IApplicationManagerInterface::GetApplicationControlData, "GetApplicationControlData"},
122 {401, nullptr, "InvalidateAllApplicationControlCache"}, 125 {401, nullptr, "InvalidateAllApplicationControlCache"},
123 {402, nullptr, "RequestDownloadApplicationControlData"}, 126 {402, nullptr, "RequestDownloadApplicationControlData"},
124 {403, nullptr, "GetMaxApplicationControlCacheCount"}, 127 {403, nullptr, "GetMaxApplicationControlCacheCount"},
@@ -243,6 +246,65 @@ public:
243 246
244 RegisterHandlers(functions); 247 RegisterHandlers(functions);
245 } 248 }
249
250 void GetApplicationControlData(Kernel::HLERequestContext& ctx) {
251 IPC::RequestParser rp{ctx};
252 const auto flag = rp.PopRaw<u64>();
253 LOG_DEBUG(Service_NS, "called with flag={:016X}", flag);
254
255 const auto title_id = rp.PopRaw<u64>();
256
257 const auto size = ctx.GetWriteBufferSize();
258
259 const FileSys::PatchManager pm{title_id};
260 const auto control = pm.GetControlMetadata();
261
262 std::vector<u8> out;
263
264 if (control.first != nullptr) {
265 if (size < 0x4000) {
266 LOG_ERROR(Service_NS,
267 "output buffer is too small! (actual={:016X}, expected_min=0x4000)",
268 size);
269 IPC::ResponseBuilder rb{ctx, 2};
270 // TODO(DarkLordZach): Find a better error code for this.
271 rb.Push(ResultCode(-1));
272 return;
273 }
274
275 out.resize(0x4000);
276 const auto bytes = control.first->GetRawBytes();
277 std::memcpy(out.data(), bytes.data(), bytes.size());
278 } else {
279 LOG_WARNING(Service_NS, "missing NACP data for title_id={:016X}, defaulting to zeros.",
280 title_id);
281 out.resize(std::min<u64>(0x4000, size));
282 }
283
284 if (control.second != nullptr) {
285 if (size < 0x4000 + control.second->GetSize()) {
286 LOG_ERROR(Service_NS,
287 "output buffer is too small! (actual={:016X}, expected_min={:016X})",
288 size, 0x4000 + control.second->GetSize());
289 IPC::ResponseBuilder rb{ctx, 2};
290 // TODO(DarkLordZach): Find a better error code for this.
291 rb.Push(ResultCode(-1));
292 return;
293 }
294
295 out.resize(0x4000 + control.second->GetSize());
296 control.second->Read(out.data() + 0x4000, control.second->GetSize());
297 } else {
298 LOG_WARNING(Service_NS, "missing icon data for title_id={:016X}, defaulting to zeros.",
299 title_id);
300 }
301
302 ctx.WriteBuffer(out);
303
304 IPC::ResponseBuilder rb{ctx, 3};
305 rb.Push(RESULT_SUCCESS);
306 rb.Push<u32>(static_cast<u32>(out.size()));
307 }
246}; 308};
247 309
248class IApplicationVersionInterface final : public ServiceFramework<IApplicationVersionInterface> { 310class IApplicationVersionInterface final : public ServiceFramework<IApplicationVersionInterface> {
diff --git a/src/core/hle/service/nvflinger/buffer_queue.cpp b/src/core/hle/service/nvflinger/buffer_queue.cpp
index fd98d541d..630ebbfc7 100644
--- a/src/core/hle/service/nvflinger/buffer_queue.cpp
+++ b/src/core/hle/service/nvflinger/buffer_queue.cpp
@@ -31,7 +31,7 @@ void BufferQueue::SetPreallocatedBuffer(u32 slot, const IGBPBuffer& igbp_buffer)
31 buffer_wait_event->Signal(); 31 buffer_wait_event->Signal();
32} 32}
33 33
34boost::optional<u32> BufferQueue::DequeueBuffer(u32 width, u32 height) { 34std::optional<u32> BufferQueue::DequeueBuffer(u32 width, u32 height) {
35 auto itr = std::find_if(queue.begin(), queue.end(), [&](const Buffer& buffer) { 35 auto itr = std::find_if(queue.begin(), queue.end(), [&](const Buffer& buffer) {
36 // Only consider free buffers. Buffers become free once again after they've been Acquired 36 // Only consider free buffers. Buffers become free once again after they've been Acquired
37 // and Released by the compositor, see the NVFlinger::Compose method. 37 // and Released by the compositor, see the NVFlinger::Compose method.
@@ -44,7 +44,7 @@ boost::optional<u32> BufferQueue::DequeueBuffer(u32 width, u32 height) {
44 }); 44 });
45 45
46 if (itr == queue.end()) { 46 if (itr == queue.end()) {
47 return boost::none; 47 return {};
48 } 48 }
49 49
50 itr->status = Buffer::Status::Dequeued; 50 itr->status = Buffer::Status::Dequeued;
@@ -70,12 +70,12 @@ void BufferQueue::QueueBuffer(u32 slot, BufferTransformFlags transform,
70 itr->crop_rect = crop_rect; 70 itr->crop_rect = crop_rect;
71} 71}
72 72
73boost::optional<const BufferQueue::Buffer&> BufferQueue::AcquireBuffer() { 73std::optional<std::reference_wrapper<const BufferQueue::Buffer>> BufferQueue::AcquireBuffer() {
74 auto itr = std::find_if(queue.begin(), queue.end(), [](const Buffer& buffer) { 74 auto itr = std::find_if(queue.begin(), queue.end(), [](const Buffer& buffer) {
75 return buffer.status == Buffer::Status::Queued; 75 return buffer.status == Buffer::Status::Queued;
76 }); 76 });
77 if (itr == queue.end()) 77 if (itr == queue.end())
78 return boost::none; 78 return {};
79 itr->status = Buffer::Status::Acquired; 79 itr->status = Buffer::Status::Acquired;
80 return *itr; 80 return *itr;
81} 81}
diff --git a/src/core/hle/service/nvflinger/buffer_queue.h b/src/core/hle/service/nvflinger/buffer_queue.h
index 50b767732..8cff5eb71 100644
--- a/src/core/hle/service/nvflinger/buffer_queue.h
+++ b/src/core/hle/service/nvflinger/buffer_queue.h
@@ -4,8 +4,9 @@
4 4
5#pragma once 5#pragma once
6 6
7#include <optional>
7#include <vector> 8#include <vector>
8#include <boost/optional.hpp> 9
9#include "common/common_funcs.h" 10#include "common/common_funcs.h"
10#include "common/math_util.h" 11#include "common/math_util.h"
11#include "common/swap.h" 12#include "common/swap.h"
@@ -57,9 +58,9 @@ public:
57 /// Rotate source image 90 degrees clockwise 58 /// Rotate source image 90 degrees clockwise
58 Rotate90 = 0x04, 59 Rotate90 = 0x04,
59 /// Rotate source image 180 degrees 60 /// Rotate source image 180 degrees
60 Roate180 = 0x03, 61 Rotate180 = 0x03,
61 /// Rotate source image 270 degrees clockwise 62 /// Rotate source image 270 degrees clockwise
62 Roate270 = 0x07, 63 Rotate270 = 0x07,
63 }; 64 };
64 65
65 struct Buffer { 66 struct Buffer {
@@ -73,11 +74,11 @@ public:
73 }; 74 };
74 75
75 void SetPreallocatedBuffer(u32 slot, const IGBPBuffer& igbp_buffer); 76 void SetPreallocatedBuffer(u32 slot, const IGBPBuffer& igbp_buffer);
76 boost::optional<u32> DequeueBuffer(u32 width, u32 height); 77 std::optional<u32> DequeueBuffer(u32 width, u32 height);
77 const IGBPBuffer& RequestBuffer(u32 slot) const; 78 const IGBPBuffer& RequestBuffer(u32 slot) const;
78 void QueueBuffer(u32 slot, BufferTransformFlags transform, 79 void QueueBuffer(u32 slot, BufferTransformFlags transform,
79 const MathUtil::Rectangle<int>& crop_rect); 80 const MathUtil::Rectangle<int>& crop_rect);
80 boost::optional<const Buffer&> AcquireBuffer(); 81 std::optional<std::reference_wrapper<const Buffer>> AcquireBuffer();
81 void ReleaseBuffer(u32 slot); 82 void ReleaseBuffer(u32 slot);
82 u32 Query(QueryType type); 83 u32 Query(QueryType type);
83 84
diff --git a/src/core/hle/service/nvflinger/nvflinger.cpp b/src/core/hle/service/nvflinger/nvflinger.cpp
index d47b6f659..214e6d1b3 100644
--- a/src/core/hle/service/nvflinger/nvflinger.cpp
+++ b/src/core/hle/service/nvflinger/nvflinger.cpp
@@ -3,7 +3,7 @@
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <algorithm> 5#include <algorithm>
6#include <boost/optional.hpp> 6#include <optional>
7 7
8#include "common/alignment.h" 8#include "common/alignment.h"
9#include "common/assert.h" 9#include "common/assert.h"
@@ -134,7 +134,7 @@ void NVFlinger::Compose() {
134 134
135 MicroProfileFlip(); 135 MicroProfileFlip();
136 136
137 if (buffer == boost::none) { 137 if (!buffer) {
138 auto& system_instance = Core::System::GetInstance(); 138 auto& system_instance = Core::System::GetInstance();
139 139
140 // There was no queued buffer to draw, render previous frame 140 // There was no queued buffer to draw, render previous frame
@@ -143,7 +143,7 @@ void NVFlinger::Compose() {
143 continue; 143 continue;
144 } 144 }
145 145
146 auto& igbp_buffer = buffer->igbp_buffer; 146 auto& igbp_buffer = buffer->get().igbp_buffer;
147 147
148 // Now send the buffer to the GPU for drawing. 148 // Now send the buffer to the GPU for drawing.
149 // TODO(Subv): Support more than just disp0. The display device selection is probably based 149 // TODO(Subv): Support more than just disp0. The display device selection is probably based
@@ -152,10 +152,10 @@ void NVFlinger::Compose() {
152 ASSERT(nvdisp); 152 ASSERT(nvdisp);
153 153
154 nvdisp->flip(igbp_buffer.gpu_buffer_id, igbp_buffer.offset, igbp_buffer.format, 154 nvdisp->flip(igbp_buffer.gpu_buffer_id, igbp_buffer.offset, igbp_buffer.format,
155 igbp_buffer.width, igbp_buffer.height, igbp_buffer.stride, buffer->transform, 155 igbp_buffer.width, igbp_buffer.height, igbp_buffer.stride,
156 buffer->crop_rect); 156 buffer->get().transform, buffer->get().crop_rect);
157 157
158 buffer_queue->ReleaseBuffer(buffer->slot); 158 buffer_queue->ReleaseBuffer(buffer->get().slot);
159 } 159 }
160} 160}
161 161
diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp
index a4cf45267..1ec340466 100644
--- a/src/core/hle/service/service.cpp
+++ b/src/core/hle/service/service.cpp
@@ -80,8 +80,8 @@ namespace Service {
80 * Creates a function string for logging, complete with the name (or header code, depending 80 * Creates a function string for logging, complete with the name (or header code, depending
81 * on what's passed in) the port name, and all the cmd_buff arguments. 81 * on what's passed in) the port name, and all the cmd_buff arguments.
82 */ 82 */
83static std::string MakeFunctionString(const char* name, const char* port_name, 83[[maybe_unused]] static std::string MakeFunctionString(const char* name, const char* port_name,
84 const u32* cmd_buff) { 84 const u32* cmd_buff) {
85 // Number of params == bits 0-5 + bits 6-11 85 // Number of params == bits 0-5 + bits 6-11
86 int num_params = (cmd_buff[0] & 0x3F) + ((cmd_buff[0] >> 6) & 0x3F); 86 int num_params = (cmd_buff[0] & 0x3F) + ((cmd_buff[0] >> 6) & 0x3F);
87 87
diff --git a/src/core/hle/service/spl/module.cpp b/src/core/hle/service/spl/module.cpp
index 44a6717d0..69c260408 100644
--- a/src/core/hle/service/spl/module.cpp
+++ b/src/core/hle/service/spl/module.cpp
@@ -3,18 +3,23 @@
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <algorithm> 5#include <algorithm>
6#include <chrono>
6#include <cstdlib> 7#include <cstdlib>
8#include <ctime>
9#include <functional>
7#include <vector> 10#include <vector>
8#include "common/logging/log.h" 11#include "common/logging/log.h"
9#include "core/hle/ipc_helpers.h" 12#include "core/hle/ipc_helpers.h"
10#include "core/hle/service/spl/csrng.h" 13#include "core/hle/service/spl/csrng.h"
11#include "core/hle/service/spl/module.h" 14#include "core/hle/service/spl/module.h"
12#include "core/hle/service/spl/spl.h" 15#include "core/hle/service/spl/spl.h"
16#include "core/settings.h"
13 17
14namespace Service::SPL { 18namespace Service::SPL {
15 19
16Module::Interface::Interface(std::shared_ptr<Module> module, const char* name) 20Module::Interface::Interface(std::shared_ptr<Module> module, const char* name)
17 : ServiceFramework(name), module(std::move(module)) {} 21 : ServiceFramework(name), module(std::move(module)),
22 rng(Settings::values.rng_seed.value_or(std::time(nullptr))) {}
18 23
19Module::Interface::~Interface() = default; 24Module::Interface::~Interface() = default;
20 25
@@ -24,7 +29,7 @@ void Module::Interface::GetRandomBytes(Kernel::HLERequestContext& ctx) {
24 std::size_t size = ctx.GetWriteBufferSize(); 29 std::size_t size = ctx.GetWriteBufferSize();
25 30
26 std::vector<u8> data(size); 31 std::vector<u8> data(size);
27 std::generate(data.begin(), data.end(), std::rand); 32 std::generate(data.begin(), data.end(), rng);
28 33
29 ctx.WriteBuffer(data); 34 ctx.WriteBuffer(data);
30 35
diff --git a/src/core/hle/service/spl/module.h b/src/core/hle/service/spl/module.h
index 48fda6099..afa1f0295 100644
--- a/src/core/hle/service/spl/module.h
+++ b/src/core/hle/service/spl/module.h
@@ -4,6 +4,7 @@
4 4
5#pragma once 5#pragma once
6 6
7#include <random>
7#include "core/hle/service/service.h" 8#include "core/hle/service/service.h"
8 9
9namespace Service::SPL { 10namespace Service::SPL {
@@ -19,6 +20,9 @@ public:
19 20
20 protected: 21 protected:
21 std::shared_ptr<Module> module; 22 std::shared_ptr<Module> module;
23
24 private:
25 std::mt19937 rng;
22 }; 26 };
23}; 27};
24 28
diff --git a/src/core/hle/service/time/interface.cpp b/src/core/hle/service/time/interface.cpp
index 18a5d71d5..e3cbd7004 100644
--- a/src/core/hle/service/time/interface.cpp
+++ b/src/core/hle/service/time/interface.cpp
@@ -21,7 +21,7 @@ Time::Time(std::shared_ptr<Module> time, const char* name)
21 {102, nullptr, "GetStandardUserSystemClockInitialYear"}, 21 {102, nullptr, "GetStandardUserSystemClockInitialYear"},
22 {200, nullptr, "IsStandardNetworkSystemClockAccuracySufficient"}, 22 {200, nullptr, "IsStandardNetworkSystemClockAccuracySufficient"},
23 {300, nullptr, "CalculateMonotonicSystemClockBaseTimePoint"}, 23 {300, nullptr, "CalculateMonotonicSystemClockBaseTimePoint"},
24 {400, nullptr, "GetClockSnapshot"}, 24 {400, &Time::GetClockSnapshot, "GetClockSnapshot"},
25 {401, nullptr, "GetClockSnapshotFromSystemClockContext"}, 25 {401, nullptr, "GetClockSnapshotFromSystemClockContext"},
26 {500, nullptr, "CalculateStandardUserSystemClockDifferenceByUser"}, 26 {500, nullptr, "CalculateStandardUserSystemClockDifferenceByUser"},
27 {501, nullptr, "CalculateSpanBetween"}, 27 {501, nullptr, "CalculateSpanBetween"},
diff --git a/src/core/hle/service/time/time.cpp b/src/core/hle/service/time/time.cpp
index 28fd8debc..85e7b1195 100644
--- a/src/core/hle/service/time/time.cpp
+++ b/src/core/hle/service/time/time.cpp
@@ -15,6 +15,44 @@
15 15
16namespace Service::Time { 16namespace Service::Time {
17 17
18static void PosixToCalendar(u64 posix_time, CalendarTime& calendar_time,
19 CalendarAdditionalInfo& additional_info,
20 [[maybe_unused]] const TimeZoneRule& /*rule*/) {
21 const std::time_t time(posix_time);
22 const std::tm* tm = std::localtime(&time);
23 if (tm == nullptr) {
24 calendar_time = {};
25 additional_info = {};
26 return;
27 }
28 calendar_time.year = tm->tm_year + 1900;
29 calendar_time.month = tm->tm_mon + 1;
30 calendar_time.day = tm->tm_mday;
31 calendar_time.hour = tm->tm_hour;
32 calendar_time.minute = tm->tm_min;
33 calendar_time.second = tm->tm_sec;
34
35 additional_info.day_of_week = tm->tm_wday;
36 additional_info.day_of_year = tm->tm_yday;
37 std::memcpy(additional_info.name.data(), "UTC", sizeof("UTC"));
38 additional_info.utc_offset = 0;
39}
40
41static u64 CalendarToPosix(const CalendarTime& calendar_time,
42 [[maybe_unused]] const TimeZoneRule& /*rule*/) {
43 std::tm time{};
44 time.tm_year = calendar_time.year - 1900;
45 time.tm_mon = calendar_time.month - 1;
46 time.tm_mday = calendar_time.day;
47
48 time.tm_hour = calendar_time.hour;
49 time.tm_min = calendar_time.minute;
50 time.tm_sec = calendar_time.second;
51
52 std::time_t epoch_time = std::mktime(&time);
53 return static_cast<u64>(epoch_time);
54}
55
18class ISystemClock final : public ServiceFramework<ISystemClock> { 56class ISystemClock final : public ServiceFramework<ISystemClock> {
19public: 57public:
20 ISystemClock() : ServiceFramework("ISystemClock") { 58 ISystemClock() : ServiceFramework("ISystemClock") {
@@ -80,8 +118,8 @@ public:
80 {5, nullptr, "GetTimeZoneRuleVersion"}, 118 {5, nullptr, "GetTimeZoneRuleVersion"},
81 {100, &ITimeZoneService::ToCalendarTime, "ToCalendarTime"}, 119 {100, &ITimeZoneService::ToCalendarTime, "ToCalendarTime"},
82 {101, &ITimeZoneService::ToCalendarTimeWithMyRule, "ToCalendarTimeWithMyRule"}, 120 {101, &ITimeZoneService::ToCalendarTimeWithMyRule, "ToCalendarTimeWithMyRule"},
83 {201, nullptr, "ToPosixTime"}, 121 {201, &ITimeZoneService::ToPosixTime, "ToPosixTime"},
84 {202, nullptr, "ToPosixTimeWithMyRule"}, 122 {202, &ITimeZoneService::ToPosixTimeWithMyRule, "ToPosixTimeWithMyRule"},
85 }; 123 };
86 RegisterHandlers(functions); 124 RegisterHandlers(functions);
87 } 125 }
@@ -151,24 +189,29 @@ private:
151 rb.PushRaw(additional_info); 189 rb.PushRaw(additional_info);
152 } 190 }
153 191
154 void PosixToCalendar(u64 posix_time, CalendarTime& calendar_time, 192 void ToPosixTime(Kernel::HLERequestContext& ctx) {
155 CalendarAdditionalInfo& additional_info, const TimeZoneRule& /*rule*/) { 193 // TODO(ogniK): Figure out how to handle multiple times
156 std::time_t t(posix_time); 194 LOG_WARNING(Service_Time, "(STUBBED) called");
157 std::tm* tm = std::localtime(&t); 195 IPC::RequestParser rp{ctx};
158 if (!tm) { 196 auto calendar_time = rp.PopRaw<CalendarTime>();
159 return; 197 auto posix_time = CalendarToPosix(calendar_time, {});
160 } 198
161 calendar_time.year = tm->tm_year + 1900; 199 IPC::ResponseBuilder rb{ctx, 3};
162 calendar_time.month = tm->tm_mon + 1; 200 rb.Push(RESULT_SUCCESS);
163 calendar_time.day = tm->tm_mday; 201 rb.PushRaw<u32>(1); // Amount of times we're returning
164 calendar_time.hour = tm->tm_hour; 202 ctx.WriteBuffer(&posix_time, sizeof(u64));
165 calendar_time.minute = tm->tm_min; 203 }
166 calendar_time.second = tm->tm_sec; 204
167 205 void ToPosixTimeWithMyRule(Kernel::HLERequestContext& ctx) {
168 additional_info.day_of_week = tm->tm_wday; 206 LOG_WARNING(Service_Time, "(STUBBED) called");
169 additional_info.day_of_year = tm->tm_yday; 207 IPC::RequestParser rp{ctx};
170 std::memcpy(additional_info.name.data(), "UTC", sizeof("UTC")); 208 auto calendar_time = rp.PopRaw<CalendarTime>();
171 additional_info.utc_offset = 0; 209 auto posix_time = CalendarToPosix(calendar_time, {});
210
211 IPC::ResponseBuilder rb{ctx, 3};
212 rb.Push(RESULT_SUCCESS);
213 rb.PushRaw<u32>(1); // Amount of times we're returning
214 ctx.WriteBuffer(&posix_time, sizeof(u64));
172 } 215 }
173}; 216};
174 217
@@ -207,6 +250,55 @@ void Module::Interface::GetStandardLocalSystemClock(Kernel::HLERequestContext& c
207 LOG_DEBUG(Service_Time, "called"); 250 LOG_DEBUG(Service_Time, "called");
208} 251}
209 252
253void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
254 LOG_DEBUG(Service_Time, "called");
255
256 IPC::RequestParser rp{ctx};
257 auto unknown_u8 = rp.PopRaw<u8>();
258
259 ClockSnapshot clock_snapshot{};
260
261 const s64 time_since_epoch{std::chrono::duration_cast<std::chrono::seconds>(
262 std::chrono::system_clock::now().time_since_epoch())
263 .count()};
264 CalendarTime calendar_time{};
265 const std::time_t time(time_since_epoch);
266 const std::tm* tm = std::localtime(&time);
267 if (tm == nullptr) {
268 IPC::ResponseBuilder rb{ctx, 2};
269 rb.Push(ResultCode(-1)); // TODO(ogniK): Find appropriate error code
270 return;
271 }
272 SteadyClockTimePoint steady_clock_time_point{CoreTiming::cyclesToMs(CoreTiming::GetTicks()) /
273 1000};
274
275 LocationName location_name{"UTC"};
276 calendar_time.year = tm->tm_year + 1900;
277 calendar_time.month = tm->tm_mon + 1;
278 calendar_time.day = tm->tm_mday;
279 calendar_time.hour = tm->tm_hour;
280 calendar_time.minute = tm->tm_min;
281 calendar_time.second = tm->tm_sec;
282 clock_snapshot.system_posix_time = time_since_epoch;
283 clock_snapshot.network_posix_time = time_since_epoch;
284 clock_snapshot.system_calendar_time = calendar_time;
285 clock_snapshot.network_calendar_time = calendar_time;
286
287 CalendarAdditionalInfo additional_info{};
288 PosixToCalendar(time_since_epoch, calendar_time, additional_info, {});
289
290 clock_snapshot.system_calendar_info = additional_info;
291 clock_snapshot.network_calendar_info = additional_info;
292
293 clock_snapshot.steady_clock_timepoint = steady_clock_time_point;
294 clock_snapshot.location_name = location_name;
295 clock_snapshot.clock_auto_adjustment_enabled = 1;
296 clock_snapshot.ipc_u8 = unknown_u8;
297 IPC::ResponseBuilder rb{ctx, 2};
298 rb.Push(RESULT_SUCCESS);
299 ctx.WriteBuffer(&clock_snapshot, sizeof(ClockSnapshot));
300}
301
210Module::Interface::Interface(std::shared_ptr<Module> time, const char* name) 302Module::Interface::Interface(std::shared_ptr<Module> time, const char* name)
211 : ServiceFramework(name), time(std::move(time)) {} 303 : ServiceFramework(name), time(std::move(time)) {}
212 304
diff --git a/src/core/hle/service/time/time.h b/src/core/hle/service/time/time.h
index 5659ecad3..77871ae07 100644
--- a/src/core/hle/service/time/time.h
+++ b/src/core/hle/service/time/time.h
@@ -5,6 +5,7 @@
5#pragma once 5#pragma once
6 6
7#include <array> 7#include <array>
8#include "common/common_funcs.h"
8#include "core/hle/service/service.h" 9#include "core/hle/service/service.h"
9 10
10namespace Service::Time { 11namespace Service::Time {
@@ -53,6 +54,23 @@ struct SystemClockContext {
53static_assert(sizeof(SystemClockContext) == 0x20, 54static_assert(sizeof(SystemClockContext) == 0x20,
54 "SystemClockContext structure has incorrect size"); 55 "SystemClockContext structure has incorrect size");
55 56
57struct ClockSnapshot {
58 SystemClockContext user_clock_context;
59 SystemClockContext network_clock_context;
60 s64_le system_posix_time;
61 s64_le network_posix_time;
62 CalendarTime system_calendar_time;
63 CalendarTime network_calendar_time;
64 CalendarAdditionalInfo system_calendar_info;
65 CalendarAdditionalInfo network_calendar_info;
66 SteadyClockTimePoint steady_clock_timepoint;
67 LocationName location_name;
68 u8 clock_auto_adjustment_enabled;
69 u8 ipc_u8;
70 INSERT_PADDING_BYTES(2);
71};
72static_assert(sizeof(ClockSnapshot) == 0xd0, "ClockSnapshot is an invalid size");
73
56class Module final { 74class Module final {
57public: 75public:
58 class Interface : public ServiceFramework<Interface> { 76 class Interface : public ServiceFramework<Interface> {
@@ -65,6 +83,7 @@ public:
65 void GetStandardSteadyClock(Kernel::HLERequestContext& ctx); 83 void GetStandardSteadyClock(Kernel::HLERequestContext& ctx);
66 void GetTimeZoneService(Kernel::HLERequestContext& ctx); 84 void GetTimeZoneService(Kernel::HLERequestContext& ctx);
67 void GetStandardLocalSystemClock(Kernel::HLERequestContext& ctx); 85 void GetStandardLocalSystemClock(Kernel::HLERequestContext& ctx);
86 void GetClockSnapshot(Kernel::HLERequestContext& ctx);
68 87
69 protected: 88 protected:
70 std::shared_ptr<Module> time; 89 std::shared_ptr<Module> time;
diff --git a/src/core/hle/service/usb/usb.cpp b/src/core/hle/service/usb/usb.cpp
index c489da071..f0a831d45 100644
--- a/src/core/hle/service/usb/usb.cpp
+++ b/src/core/hle/service/usb/usb.cpp
@@ -132,11 +132,11 @@ public:
132 // clang-format off 132 // clang-format off
133 static const FunctionInfo functions[] = { 133 static const FunctionInfo functions[] = {
134 {0, nullptr, "BindNoticeEvent"}, 134 {0, nullptr, "BindNoticeEvent"},
135 {1, nullptr, "Unknown1"}, 135 {1, nullptr, "UnbindNoticeEvent"},
136 {2, nullptr, "GetStatus"}, 136 {2, nullptr, "GetStatus"},
137 {3, nullptr, "GetNotice"}, 137 {3, nullptr, "GetNotice"},
138 {4, nullptr, "Unknown2"}, 138 {4, nullptr, "EnablePowerRequestNotice"},
139 {5, nullptr, "Unknown3"}, 139 {5, nullptr, "DisablePowerRequestNotice"},
140 {6, nullptr, "ReplyPowerRequest"}, 140 {6, nullptr, "ReplyPowerRequest"},
141 }; 141 };
142 // clang-format on 142 // clang-format on
diff --git a/src/core/hle/service/vi/vi.cpp b/src/core/hle/service/vi/vi.cpp
index 184537daa..d764b2406 100644
--- a/src/core/hle/service/vi/vi.cpp
+++ b/src/core/hle/service/vi/vi.cpp
@@ -6,9 +6,10 @@
6#include <array> 6#include <array>
7#include <cstring> 7#include <cstring>
8#include <memory> 8#include <memory>
9#include <optional>
9#include <type_traits> 10#include <type_traits>
10#include <utility> 11#include <utility>
11#include <boost/optional.hpp> 12
12#include "common/alignment.h" 13#include "common/alignment.h"
13#include "common/assert.h" 14#include "common/assert.h"
14#include "common/common_funcs.h" 15#include "common/common_funcs.h"
@@ -506,9 +507,9 @@ private:
506 IGBPDequeueBufferRequestParcel request{ctx.ReadBuffer()}; 507 IGBPDequeueBufferRequestParcel request{ctx.ReadBuffer()};
507 const u32 width{request.data.width}; 508 const u32 width{request.data.width};
508 const u32 height{request.data.height}; 509 const u32 height{request.data.height};
509 boost::optional<u32> slot = buffer_queue->DequeueBuffer(width, height); 510 std::optional<u32> slot = buffer_queue->DequeueBuffer(width, height);
510 511
511 if (slot != boost::none) { 512 if (slot) {
512 // Buffer is available 513 // Buffer is available
513 IGBPDequeueBufferResponseParcel response{*slot}; 514 IGBPDequeueBufferResponseParcel response{*slot};
514 ctx.WriteBuffer(response.Serialize()); 515 ctx.WriteBuffer(response.Serialize());
@@ -520,7 +521,7 @@ private:
520 Kernel::ThreadWakeupReason reason) { 521 Kernel::ThreadWakeupReason reason) {
521 // Repeat TransactParcel DequeueBuffer when a buffer is available 522 // Repeat TransactParcel DequeueBuffer when a buffer is available
522 auto buffer_queue = nv_flinger->GetBufferQueue(id); 523 auto buffer_queue = nv_flinger->GetBufferQueue(id);
523 boost::optional<u32> slot = buffer_queue->DequeueBuffer(width, height); 524 std::optional<u32> slot = buffer_queue->DequeueBuffer(width, height);
524 IGBPDequeueBufferResponseParcel response{*slot}; 525 IGBPDequeueBufferResponseParcel response{*slot};
525 ctx.WriteBuffer(response.Serialize()); 526 ctx.WriteBuffer(response.Serialize());
526 IPC::ResponseBuilder rb{ctx, 2}; 527 IPC::ResponseBuilder rb{ctx, 2};
diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h
index e562b3a04..7686634bf 100644
--- a/src/core/loader/loader.h
+++ b/src/core/loader/loader.h
@@ -6,10 +6,11 @@
6 6
7#include <iosfwd> 7#include <iosfwd>
8#include <memory> 8#include <memory>
9#include <optional>
9#include <string> 10#include <string>
10#include <utility> 11#include <utility>
11#include <vector> 12#include <vector>
12#include <boost/optional.hpp> 13
13#include "common/common_types.h" 14#include "common/common_types.h"
14#include "core/file_sys/vfs.h" 15#include "core/file_sys/vfs.h"
15 16
@@ -145,7 +146,7 @@ public:
145 * information. 146 * information.
146 * @returns A pair with the optional system mode, and and the status. 147 * @returns A pair with the optional system mode, and and the status.
147 */ 148 */
148 virtual std::pair<boost::optional<u32>, ResultStatus> LoadKernelSystemMode() { 149 virtual std::pair<std::optional<u32>, ResultStatus> LoadKernelSystemMode() {
149 // 96MB allocated to the application. 150 // 96MB allocated to the application.
150 return std::make_pair(2, ResultStatus::Success); 151 return std::make_pair(2, ResultStatus::Success);
151 } 152 }
diff --git a/src/core/loader/nro.cpp b/src/core/loader/nro.cpp
index bc8e402a8..c8e491fec 100644
--- a/src/core/loader/nro.cpp
+++ b/src/core/loader/nro.cpp
@@ -12,10 +12,12 @@
12#include "common/swap.h" 12#include "common/swap.h"
13#include "core/core.h" 13#include "core/core.h"
14#include "core/file_sys/control_metadata.h" 14#include "core/file_sys/control_metadata.h"
15#include "core/file_sys/romfs_factory.h"
15#include "core/file_sys/vfs_offset.h" 16#include "core/file_sys/vfs_offset.h"
16#include "core/gdbstub/gdbstub.h" 17#include "core/gdbstub/gdbstub.h"
17#include "core/hle/kernel/process.h" 18#include "core/hle/kernel/process.h"
18#include "core/hle/kernel/vm_manager.h" 19#include "core/hle/kernel/vm_manager.h"
20#include "core/hle/service/filesystem/filesystem.h"
19#include "core/loader/nro.h" 21#include "core/loader/nro.h"
20#include "core/loader/nso.h" 22#include "core/loader/nso.h"
21#include "core/memory.h" 23#include "core/memory.h"
@@ -208,6 +210,9 @@ ResultStatus AppLoader_NRO::Load(Kernel::Process& process) {
208 return ResultStatus::ErrorLoadingNRO; 210 return ResultStatus::ErrorLoadingNRO;
209 } 211 }
210 212
213 if (romfs != nullptr)
214 Service::FileSystem::RegisterRomFS(std::make_unique<FileSys::RomFSFactory>(*this));
215
211 process.Run(base_address, Kernel::THREADPRIO_DEFAULT, Memory::DEFAULT_STACK_SIZE); 216 process.Run(base_address, Kernel::THREADPRIO_DEFAULT, Memory::DEFAULT_STACK_SIZE);
212 217
213 is_loaded = true; 218 is_loaded = true;
diff --git a/src/core/memory.cpp b/src/core/memory.cpp
index 014298ed6..70abd856a 100644
--- a/src/core/memory.cpp
+++ b/src/core/memory.cpp
@@ -4,9 +4,9 @@
4 4
5#include <algorithm> 5#include <algorithm>
6#include <cstring> 6#include <cstring>
7#include <optional>
7#include <utility> 8#include <utility>
8 9
9#include <boost/optional.hpp>
10#include "common/assert.h" 10#include "common/assert.h"
11#include "common/common_types.h" 11#include "common/common_types.h"
12#include "common/logging/log.h" 12#include "common/logging/log.h"
diff --git a/src/core/memory_hook.h b/src/core/memory_hook.h
index 0269c7ff1..940777107 100644
--- a/src/core/memory_hook.h
+++ b/src/core/memory_hook.h
@@ -5,7 +5,8 @@
5#pragma once 5#pragma once
6 6
7#include <memory> 7#include <memory>
8#include <boost/optional.hpp> 8#include <optional>
9
9#include "common/common_types.h" 10#include "common/common_types.h"
10 11
11namespace Memory { 12namespace Memory {
@@ -18,19 +19,19 @@ namespace Memory {
18 * 19 *
19 * A hook may be mapped to multiple regions of memory. 20 * A hook may be mapped to multiple regions of memory.
20 * 21 *
21 * If a boost::none or false is returned from a function, the read/write request is passed through 22 * If a std::nullopt or false is returned from a function, the read/write request is passed through
22 * to the underlying memory region. 23 * to the underlying memory region.
23 */ 24 */
24class MemoryHook { 25class MemoryHook {
25public: 26public:
26 virtual ~MemoryHook(); 27 virtual ~MemoryHook();
27 28
28 virtual boost::optional<bool> IsValidAddress(VAddr addr) = 0; 29 virtual std::optional<bool> IsValidAddress(VAddr addr) = 0;
29 30
30 virtual boost::optional<u8> Read8(VAddr addr) = 0; 31 virtual std::optional<u8> Read8(VAddr addr) = 0;
31 virtual boost::optional<u16> Read16(VAddr addr) = 0; 32 virtual std::optional<u16> Read16(VAddr addr) = 0;
32 virtual boost::optional<u32> Read32(VAddr addr) = 0; 33 virtual std::optional<u32> Read32(VAddr addr) = 0;
33 virtual boost::optional<u64> Read64(VAddr addr) = 0; 34 virtual std::optional<u64> Read64(VAddr addr) = 0;
34 35
35 virtual bool ReadBlock(VAddr src_addr, void* dest_buffer, std::size_t size) = 0; 36 virtual bool ReadBlock(VAddr src_addr, void* dest_buffer, std::size_t size) = 0;
36 37
diff --git a/src/core/settings.h b/src/core/settings.h
index 0af9dd416..e424479f2 100644
--- a/src/core/settings.h
+++ b/src/core/settings.h
@@ -6,6 +6,7 @@
6 6
7#include <array> 7#include <array>
8#include <atomic> 8#include <atomic>
9#include <optional>
9#include <string> 10#include <string>
10#include "common/common_types.h" 11#include "common/common_types.h"
11 12
@@ -114,8 +115,9 @@ struct Values {
114 // System 115 // System
115 bool use_docked_mode; 116 bool use_docked_mode;
116 bool enable_nfc; 117 bool enable_nfc;
117 int current_user; 118 std::optional<u32> rng_seed;
118 int language_index; 119 s32 current_user;
120 s32 language_index;
119 121
120 // Controls 122 // Controls
121 std::array<std::string, NativeButton::NumButtons> buttons; 123 std::array<std::string, NativeButton::NumButtons> buttons;
diff --git a/src/core/telemetry_session.cpp b/src/core/telemetry_session.cpp
index 0de13edd3..a3b08c740 100644
--- a/src/core/telemetry_session.cpp
+++ b/src/core/telemetry_session.cpp
@@ -184,4 +184,13 @@ TelemetrySession::~TelemetrySession() {
184 backend = nullptr; 184 backend = nullptr;
185} 185}
186 186
187bool TelemetrySession::SubmitTestcase() {
188#ifdef ENABLE_WEB_SERVICE
189 field_collection.Accept(*backend);
190 return backend->SubmitTestcase();
191#else
192 return false;
193#endif
194}
195
187} // namespace Core 196} // namespace Core
diff --git a/src/core/telemetry_session.h b/src/core/telemetry_session.h
index 2a4845797..023612b79 100644
--- a/src/core/telemetry_session.h
+++ b/src/core/telemetry_session.h
@@ -31,6 +31,12 @@ public:
31 field_collection.AddField(type, name, std::move(value)); 31 field_collection.AddField(type, name, std::move(value));
32 } 32 }
33 33
34 /**
35 * Submits a Testcase.
36 * @returns A bool indicating whether the submission succeeded
37 */
38 bool SubmitTestcase();
39
34private: 40private:
35 Telemetry::FieldCollection field_collection; ///< Tracks all added fields for the session 41 Telemetry::FieldCollection field_collection; ///< Tracks all added fields for the session
36 std::unique_ptr<Telemetry::VisitorInterface> backend; ///< Backend interface that logs fields 42 std::unique_ptr<Telemetry::VisitorInterface> backend; ///< Backend interface that logs fields
diff --git a/src/tests/core/arm/arm_test_common.cpp b/src/tests/core/arm/arm_test_common.cpp
index 37e15bad0..9b8a44fa1 100644
--- a/src/tests/core/arm/arm_test_common.cpp
+++ b/src/tests/core/arm/arm_test_common.cpp
@@ -64,11 +64,11 @@ void TestEnvironment::ClearWriteRecords() {
64 64
65TestEnvironment::TestMemory::~TestMemory() {} 65TestEnvironment::TestMemory::~TestMemory() {}
66 66
67boost::optional<bool> TestEnvironment::TestMemory::IsValidAddress(VAddr addr) { 67std::optional<bool> TestEnvironment::TestMemory::IsValidAddress(VAddr addr) {
68 return true; 68 return true;
69} 69}
70 70
71boost::optional<u8> TestEnvironment::TestMemory::Read8(VAddr addr) { 71std::optional<u8> TestEnvironment::TestMemory::Read8(VAddr addr) {
72 const auto iter = data.find(addr); 72 const auto iter = data.find(addr);
73 73
74 if (iter == data.end()) { 74 if (iter == data.end()) {
@@ -79,15 +79,15 @@ boost::optional<u8> TestEnvironment::TestMemory::Read8(VAddr addr) {
79 return iter->second; 79 return iter->second;
80} 80}
81 81
82boost::optional<u16> TestEnvironment::TestMemory::Read16(VAddr addr) { 82std::optional<u16> TestEnvironment::TestMemory::Read16(VAddr addr) {
83 return *Read8(addr) | static_cast<u16>(*Read8(addr + 1)) << 8; 83 return *Read8(addr) | static_cast<u16>(*Read8(addr + 1)) << 8;
84} 84}
85 85
86boost::optional<u32> TestEnvironment::TestMemory::Read32(VAddr addr) { 86std::optional<u32> TestEnvironment::TestMemory::Read32(VAddr addr) {
87 return *Read16(addr) | static_cast<u32>(*Read16(addr + 2)) << 16; 87 return *Read16(addr) | static_cast<u32>(*Read16(addr + 2)) << 16;
88} 88}
89 89
90boost::optional<u64> TestEnvironment::TestMemory::Read64(VAddr addr) { 90std::optional<u64> TestEnvironment::TestMemory::Read64(VAddr addr) {
91 return *Read32(addr) | static_cast<u64>(*Read32(addr + 4)) << 32; 91 return *Read32(addr) | static_cast<u64>(*Read32(addr + 4)) << 32;
92} 92}
93 93
diff --git a/src/tests/core/arm/arm_test_common.h b/src/tests/core/arm/arm_test_common.h
index 5de8dab4e..0b7539601 100644
--- a/src/tests/core/arm/arm_test_common.h
+++ b/src/tests/core/arm/arm_test_common.h
@@ -64,12 +64,12 @@ private:
64 64
65 ~TestMemory() override; 65 ~TestMemory() override;
66 66
67 boost::optional<bool> IsValidAddress(VAddr addr) override; 67 std::optional<bool> IsValidAddress(VAddr addr) override;
68 68
69 boost::optional<u8> Read8(VAddr addr) override; 69 std::optional<u8> Read8(VAddr addr) override;
70 boost::optional<u16> Read16(VAddr addr) override; 70 std::optional<u16> Read16(VAddr addr) override;
71 boost::optional<u32> Read32(VAddr addr) override; 71 std::optional<u32> Read32(VAddr addr) override;
72 boost::optional<u64> Read64(VAddr addr) override; 72 std::optional<u64> Read64(VAddr addr) override;
73 73
74 bool ReadBlock(VAddr src_addr, void* dest_buffer, std::size_t size) override; 74 bool ReadBlock(VAddr src_addr, void* dest_buffer, std::size_t size) override;
75 75
diff --git a/src/video_core/CMakeLists.txt b/src/video_core/CMakeLists.txt
index c5f7128ec..a780215c1 100644
--- a/src/video_core/CMakeLists.txt
+++ b/src/video_core/CMakeLists.txt
@@ -21,6 +21,7 @@ add_library(video_core STATIC
21 macro_interpreter.h 21 macro_interpreter.h
22 memory_manager.cpp 22 memory_manager.cpp
23 memory_manager.h 23 memory_manager.h
24 rasterizer_cache.cpp
24 rasterizer_cache.h 25 rasterizer_cache.h
25 rasterizer_interface.h 26 rasterizer_interface.h
26 renderer_base.cpp 27 renderer_base.cpp
@@ -33,6 +34,7 @@ add_library(video_core STATIC
33 renderer_opengl/gl_rasterizer.h 34 renderer_opengl/gl_rasterizer.h
34 renderer_opengl/gl_rasterizer_cache.cpp 35 renderer_opengl/gl_rasterizer_cache.cpp
35 renderer_opengl/gl_rasterizer_cache.h 36 renderer_opengl/gl_rasterizer_cache.h
37 renderer_opengl/gl_resource_manager.cpp
36 renderer_opengl/gl_resource_manager.h 38 renderer_opengl/gl_resource_manager.h
37 renderer_opengl/gl_shader_cache.cpp 39 renderer_opengl/gl_shader_cache.cpp
38 renderer_opengl/gl_shader_cache.h 40 renderer_opengl/gl_shader_cache.h
@@ -53,6 +55,8 @@ add_library(video_core STATIC
53 renderer_opengl/renderer_opengl.h 55 renderer_opengl/renderer_opengl.h
54 renderer_opengl/utils.cpp 56 renderer_opengl/utils.cpp
55 renderer_opengl/utils.h 57 renderer_opengl/utils.h
58 surface.cpp
59 surface.h
56 textures/astc.cpp 60 textures/astc.cpp
57 textures/astc.h 61 textures/astc.h
58 textures/decoders.cpp 62 textures/decoders.cpp
diff --git a/src/video_core/command_processor.cpp b/src/video_core/command_processor.cpp
index f1aa6091b..28e8c13aa 100644
--- a/src/video_core/command_processor.cpp
+++ b/src/video_core/command_processor.cpp
@@ -81,7 +81,7 @@ void GPU::ProcessCommandLists(const std::vector<CommandListHeader>& commands) {
81 for (auto entry : commands) { 81 for (auto entry : commands) {
82 Tegra::GPUVAddr address = entry.Address(); 82 Tegra::GPUVAddr address = entry.Address();
83 u32 size = entry.sz; 83 u32 size = entry.sz;
84 const boost::optional<VAddr> head_address = memory_manager->GpuToCpuAddress(address); 84 const std::optional<VAddr> head_address = memory_manager->GpuToCpuAddress(address);
85 VAddr current_addr = *head_address; 85 VAddr current_addr = *head_address;
86 while (current_addr < *head_address + size * sizeof(CommandHeader)) { 86 while (current_addr < *head_address + size * sizeof(CommandHeader)) {
87 const CommandHeader header = {Memory::Read32(current_addr)}; 87 const CommandHeader header = {Memory::Read32(current_addr)};
diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index 27ef865a2..6de07ea56 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -37,21 +37,52 @@ void Maxwell3D::InitializeRegisterDefaults() {
37 regs.viewport[viewport].depth_range_near = 0.0f; 37 regs.viewport[viewport].depth_range_near = 0.0f;
38 regs.viewport[viewport].depth_range_far = 1.0f; 38 regs.viewport[viewport].depth_range_far = 1.0f;
39 } 39 }
40 // Doom and Bomberman seems to use the uninitialized registers and just enable blend
41 // so initialize blend registers with sane values
42 regs.blend.equation_rgb = Regs::Blend::Equation::Add;
43 regs.blend.factor_source_rgb = Regs::Blend::Factor::One;
44 regs.blend.factor_dest_rgb = Regs::Blend::Factor::Zero;
45 regs.blend.equation_a = Regs::Blend::Equation::Add;
46 regs.blend.factor_source_a = Regs::Blend::Factor::One;
47 regs.blend.factor_dest_a = Regs::Blend::Factor::Zero;
48 for (std::size_t blend_index = 0; blend_index < Regs::NumRenderTargets; blend_index++) {
49 regs.independent_blend[blend_index].equation_rgb = Regs::Blend::Equation::Add;
50 regs.independent_blend[blend_index].factor_source_rgb = Regs::Blend::Factor::One;
51 regs.independent_blend[blend_index].factor_dest_rgb = Regs::Blend::Factor::Zero;
52 regs.independent_blend[blend_index].equation_a = Regs::Blend::Equation::Add;
53 regs.independent_blend[blend_index].factor_source_a = Regs::Blend::Factor::One;
54 regs.independent_blend[blend_index].factor_dest_a = Regs::Blend::Factor::Zero;
55 }
56 regs.stencil_front_op_fail = Regs::StencilOp::Keep;
57 regs.stencil_front_op_zfail = Regs::StencilOp::Keep;
58 regs.stencil_front_op_zpass = Regs::StencilOp::Keep;
59 regs.stencil_front_func_func = Regs::ComparisonOp::Always;
60 regs.stencil_front_func_mask = 0xFFFFFFFF;
61 regs.stencil_front_mask = 0xFFFFFFFF;
62 regs.stencil_two_side_enable = 1;
63 regs.stencil_back_op_fail = Regs::StencilOp::Keep;
64 regs.stencil_back_op_zfail = Regs::StencilOp::Keep;
65 regs.stencil_back_op_zpass = Regs::StencilOp::Keep;
66 regs.stencil_back_func_func = Regs::ComparisonOp::Always;
67 regs.stencil_back_func_mask = 0xFFFFFFFF;
68 regs.stencil_back_mask = 0xFFFFFFFF;
40} 69}
41 70
42void Maxwell3D::CallMacroMethod(u32 method, std::vector<u32> parameters) { 71void Maxwell3D::CallMacroMethod(u32 method, std::vector<u32> parameters) {
43 // Reset the current macro. 72 // Reset the current macro.
44 executing_macro = 0; 73 executing_macro = 0;
45 74
46 // The requested macro must have been uploaded already. 75 // Lookup the macro offset
47 auto macro_code = uploaded_macros.find(method); 76 const u32 entry{(method - MacroRegistersStart) >> 1};
48 if (macro_code == uploaded_macros.end()) { 77 const auto& search{macro_offsets.find(entry)};
49 LOG_ERROR(HW_GPU, "Macro {:04X} was not uploaded", method); 78 if (search == macro_offsets.end()) {
79 LOG_CRITICAL(HW_GPU, "macro not found for method 0x{:X}!", method);
80 UNREACHABLE();
50 return; 81 return;
51 } 82 }
52 83
53 // Execute the current macro. 84 // Execute the current macro.
54 macro_interpreter.Execute(macro_code->second, std::move(parameters)); 85 macro_interpreter.Execute(search->second, std::move(parameters));
55} 86}
56 87
57void Maxwell3D::WriteReg(u32 method, u32 value, u32 remaining_params) { 88void Maxwell3D::WriteReg(u32 method, u32 value, u32 remaining_params) {
@@ -90,13 +121,23 @@ void Maxwell3D::WriteReg(u32 method, u32 value, u32 remaining_params) {
90 debug_context->OnEvent(Tegra::DebugContext::Event::MaxwellCommandLoaded, nullptr); 121 debug_context->OnEvent(Tegra::DebugContext::Event::MaxwellCommandLoaded, nullptr);
91 } 122 }
92 123
93 regs.reg_array[method] = value; 124 if (regs.reg_array[method] != value) {
125 regs.reg_array[method] = value;
126 if (method >= MAXWELL3D_REG_INDEX(vertex_attrib_format) &&
127 method < MAXWELL3D_REG_INDEX(vertex_attrib_format) + regs.vertex_attrib_format.size()) {
128 dirty_flags.vertex_attrib_format = true;
129 }
130 }
94 131
95 switch (method) { 132 switch (method) {
96 case MAXWELL3D_REG_INDEX(macros.data): { 133 case MAXWELL3D_REG_INDEX(macros.data): {
97 ProcessMacroUpload(value); 134 ProcessMacroUpload(value);
98 break; 135 break;
99 } 136 }
137 case MAXWELL3D_REG_INDEX(macros.bind): {
138 ProcessMacroBind(value);
139 break;
140 }
100 case MAXWELL3D_REG_INDEX(const_buffer.cb_data[0]): 141 case MAXWELL3D_REG_INDEX(const_buffer.cb_data[0]):
101 case MAXWELL3D_REG_INDEX(const_buffer.cb_data[1]): 142 case MAXWELL3D_REG_INDEX(const_buffer.cb_data[1]):
102 case MAXWELL3D_REG_INDEX(const_buffer.cb_data[2]): 143 case MAXWELL3D_REG_INDEX(const_buffer.cb_data[2]):
@@ -158,16 +199,20 @@ void Maxwell3D::WriteReg(u32 method, u32 value, u32 remaining_params) {
158} 199}
159 200
160void Maxwell3D::ProcessMacroUpload(u32 data) { 201void Maxwell3D::ProcessMacroUpload(u32 data) {
161 // Store the uploaded macro code to interpret them when they're called. 202 ASSERT_MSG(regs.macros.upload_address < macro_memory.size(),
162 auto& macro = uploaded_macros[regs.macros.entry * 2 + MacroRegistersStart]; 203 "upload_address exceeded macro_memory size!");
163 macro.push_back(data); 204 macro_memory[regs.macros.upload_address++] = data;
205}
206
207void Maxwell3D::ProcessMacroBind(u32 data) {
208 macro_offsets[regs.macros.entry] = data;
164} 209}
165 210
166void Maxwell3D::ProcessQueryGet() { 211void Maxwell3D::ProcessQueryGet() {
167 GPUVAddr sequence_address = regs.query.QueryAddress(); 212 GPUVAddr sequence_address = regs.query.QueryAddress();
168 // Since the sequence address is given as a GPU VAddr, we have to convert it to an application 213 // Since the sequence address is given as a GPU VAddr, we have to convert it to an application
169 // VAddr before writing. 214 // VAddr before writing.
170 boost::optional<VAddr> address = memory_manager.GpuToCpuAddress(sequence_address); 215 std::optional<VAddr> address = memory_manager.GpuToCpuAddress(sequence_address);
171 216
172 // TODO(Subv): Support the other query units. 217 // TODO(Subv): Support the other query units.
173 ASSERT_MSG(regs.query.query_get.unit == Regs::QueryUnit::Crop, 218 ASSERT_MSG(regs.query.query_get.unit == Regs::QueryUnit::Crop,
@@ -285,7 +330,7 @@ void Maxwell3D::ProcessCBData(u32 value) {
285 // Don't allow writing past the end of the buffer. 330 // Don't allow writing past the end of the buffer.
286 ASSERT(regs.const_buffer.cb_pos + sizeof(u32) <= regs.const_buffer.cb_size); 331 ASSERT(regs.const_buffer.cb_pos + sizeof(u32) <= regs.const_buffer.cb_size);
287 332
288 boost::optional<VAddr> address = 333 std::optional<VAddr> address =
289 memory_manager.GpuToCpuAddress(buffer_address + regs.const_buffer.cb_pos); 334 memory_manager.GpuToCpuAddress(buffer_address + regs.const_buffer.cb_pos);
290 335
291 Memory::Write32(*address, value); 336 Memory::Write32(*address, value);
@@ -298,7 +343,7 @@ Texture::TICEntry Maxwell3D::GetTICEntry(u32 tic_index) const {
298 GPUVAddr tic_base_address = regs.tic.TICAddress(); 343 GPUVAddr tic_base_address = regs.tic.TICAddress();
299 344
300 GPUVAddr tic_address_gpu = tic_base_address + tic_index * sizeof(Texture::TICEntry); 345 GPUVAddr tic_address_gpu = tic_base_address + tic_index * sizeof(Texture::TICEntry);
301 boost::optional<VAddr> tic_address_cpu = memory_manager.GpuToCpuAddress(tic_address_gpu); 346 std::optional<VAddr> tic_address_cpu = memory_manager.GpuToCpuAddress(tic_address_gpu);
302 347
303 Texture::TICEntry tic_entry; 348 Texture::TICEntry tic_entry;
304 Memory::ReadBlock(*tic_address_cpu, &tic_entry, sizeof(Texture::TICEntry)); 349 Memory::ReadBlock(*tic_address_cpu, &tic_entry, sizeof(Texture::TICEntry));
@@ -322,7 +367,7 @@ Texture::TSCEntry Maxwell3D::GetTSCEntry(u32 tsc_index) const {
322 GPUVAddr tsc_base_address = regs.tsc.TSCAddress(); 367 GPUVAddr tsc_base_address = regs.tsc.TSCAddress();
323 368
324 GPUVAddr tsc_address_gpu = tsc_base_address + tsc_index * sizeof(Texture::TSCEntry); 369 GPUVAddr tsc_address_gpu = tsc_base_address + tsc_index * sizeof(Texture::TSCEntry);
325 boost::optional<VAddr> tsc_address_cpu = memory_manager.GpuToCpuAddress(tsc_address_gpu); 370 std::optional<VAddr> tsc_address_cpu = memory_manager.GpuToCpuAddress(tsc_address_gpu);
326 371
327 Texture::TSCEntry tsc_entry; 372 Texture::TSCEntry tsc_entry;
328 Memory::ReadBlock(*tsc_address_cpu, &tsc_entry, sizeof(Texture::TSCEntry)); 373 Memory::ReadBlock(*tsc_address_cpu, &tsc_entry, sizeof(Texture::TSCEntry));
@@ -386,7 +431,7 @@ Texture::FullTextureInfo Maxwell3D::GetStageTexture(Regs::ShaderStage stage,
386 431
387 ASSERT(tex_info_address < tex_info_buffer.address + tex_info_buffer.size); 432 ASSERT(tex_info_address < tex_info_buffer.address + tex_info_buffer.size);
388 433
389 boost::optional<VAddr> tex_address_cpu = memory_manager.GpuToCpuAddress(tex_info_address); 434 std::optional<VAddr> tex_address_cpu = memory_manager.GpuToCpuAddress(tex_info_address);
390 Texture::TextureHandle tex_handle{Memory::Read32(*tex_address_cpu)}; 435 Texture::TextureHandle tex_handle{Memory::Read32(*tex_address_cpu)};
391 436
392 Texture::FullTextureInfo tex_info{}; 437 Texture::FullTextureInfo tex_info{};
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index 443affc36..91ca57883 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -345,6 +345,14 @@ public:
345 Invert = 6, 345 Invert = 6,
346 IncrWrap = 7, 346 IncrWrap = 7,
347 DecrWrap = 8, 347 DecrWrap = 8,
348 KeepOGL = 0x1E00,
349 ZeroOGL = 0,
350 ReplaceOGL = 0x1E01,
351 IncrOGL = 0x1E02,
352 DecrOGL = 0x1E03,
353 InvertOGL = 0x150A,
354 IncrWrapOGL = 0x8507,
355 DecrWrapOGL = 0x8508,
348 }; 356 };
349 357
350 enum class MemoryLayout : u32 { 358 enum class MemoryLayout : u32 {
@@ -462,6 +470,16 @@ public:
462 } 470 }
463 }; 471 };
464 472
473 struct ColorMask {
474 union {
475 u32 raw;
476 BitField<0, 4, u32> R;
477 BitField<4, 4, u32> G;
478 BitField<8, 4, u32> B;
479 BitField<12, 4, u32> A;
480 };
481 };
482
465 bool IsShaderConfigEnabled(std::size_t index) const { 483 bool IsShaderConfigEnabled(std::size_t index) const {
466 // The VertexB is always enabled. 484 // The VertexB is always enabled.
467 if (index == static_cast<std::size_t>(Regs::ShaderProgram::VertexB)) { 485 if (index == static_cast<std::size_t>(Regs::ShaderProgram::VertexB)) {
@@ -475,12 +493,13 @@ public:
475 INSERT_PADDING_WORDS(0x45); 493 INSERT_PADDING_WORDS(0x45);
476 494
477 struct { 495 struct {
478 INSERT_PADDING_WORDS(1); 496 u32 upload_address;
479 u32 data; 497 u32 data;
480 u32 entry; 498 u32 entry;
499 u32 bind;
481 } macros; 500 } macros;
482 501
483 INSERT_PADDING_WORDS(0x189); 502 INSERT_PADDING_WORDS(0x188);
484 503
485 u32 tfb_enabled; 504 u32 tfb_enabled;
486 505
@@ -570,7 +589,11 @@ public:
570 u32 stencil_back_mask; 589 u32 stencil_back_mask;
571 u32 stencil_back_func_mask; 590 u32 stencil_back_func_mask;
572 591
573 INSERT_PADDING_WORDS(0x13); 592 INSERT_PADDING_WORDS(0xC);
593
594 u32 color_mask_common;
595
596 INSERT_PADDING_WORDS(0x6);
574 597
575 u32 rt_separate_frag_data; 598 u32 rt_separate_frag_data;
576 599
@@ -645,8 +668,14 @@ public:
645 ComparisonOp depth_test_func; 668 ComparisonOp depth_test_func;
646 float alpha_test_ref; 669 float alpha_test_ref;
647 ComparisonOp alpha_test_func; 670 ComparisonOp alpha_test_func;
648 671 u32 draw_tfb_stride;
649 INSERT_PADDING_WORDS(0x9); 672 struct {
673 float r;
674 float g;
675 float b;
676 float a;
677 } blend_color;
678 INSERT_PADDING_WORDS(0x4);
650 679
651 struct { 680 struct {
652 u32 separate_alpha; 681 u32 separate_alpha;
@@ -840,8 +869,9 @@ public:
840 BitField<6, 4, u32> RT; 869 BitField<6, 4, u32> RT;
841 BitField<10, 11, u32> layer; 870 BitField<10, 11, u32> layer;
842 } clear_buffers; 871 } clear_buffers;
843 872 INSERT_PADDING_WORDS(0xB);
844 INSERT_PADDING_WORDS(0x4B); 873 std::array<ColorMask, NumRenderTargets> color_mask;
874 INSERT_PADDING_WORDS(0x38);
845 875
846 struct { 876 struct {
847 u32 query_address_high; 877 u32 query_address_high;
@@ -982,6 +1012,12 @@ public:
982 State state{}; 1012 State state{};
983 MemoryManager& memory_manager; 1013 MemoryManager& memory_manager;
984 1014
1015 struct DirtyFlags {
1016 bool vertex_attrib_format = true;
1017 };
1018
1019 DirtyFlags dirty_flags;
1020
985 /// Reads a register value located at the input method address 1021 /// Reads a register value located at the input method address
986 u32 GetRegisterValue(u32 method) const; 1022 u32 GetRegisterValue(u32 method) const;
987 1023
@@ -994,12 +1030,25 @@ public:
994 /// Returns the texture information for a specific texture in a specific shader stage. 1030 /// Returns the texture information for a specific texture in a specific shader stage.
995 Texture::FullTextureInfo GetStageTexture(Regs::ShaderStage stage, std::size_t offset) const; 1031 Texture::FullTextureInfo GetStageTexture(Regs::ShaderStage stage, std::size_t offset) const;
996 1032
1033 /// Memory for macro code - it's undetermined how big this is, however 1MB is much larger than
1034 /// we've seen used.
1035 using MacroMemory = std::array<u32, 0x40000>;
1036
1037 /// Gets a reference to macro memory.
1038 const MacroMemory& GetMacroMemory() const {
1039 return macro_memory;
1040 }
1041
997private: 1042private:
998 void InitializeRegisterDefaults(); 1043 void InitializeRegisterDefaults();
999 1044
1000 VideoCore::RasterizerInterface& rasterizer; 1045 VideoCore::RasterizerInterface& rasterizer;
1001 1046
1002 std::unordered_map<u32, std::vector<u32>> uploaded_macros; 1047 /// Start offsets of each macro in macro_memory
1048 std::unordered_map<u32, u32> macro_offsets;
1049
1050 /// Memory for macro code
1051 MacroMemory macro_memory;
1003 1052
1004 /// Macro method that is currently being executed / being fed parameters. 1053 /// Macro method that is currently being executed / being fed parameters.
1005 u32 executing_macro = 0; 1054 u32 executing_macro = 0;
@@ -1022,9 +1071,12 @@ private:
1022 */ 1071 */
1023 void CallMacroMethod(u32 method, std::vector<u32> parameters); 1072 void CallMacroMethod(u32 method, std::vector<u32> parameters);
1024 1073
1025 /// Handles writes to the macro uploading registers. 1074 /// Handles writes to the macro uploading register.
1026 void ProcessMacroUpload(u32 data); 1075 void ProcessMacroUpload(u32 data);
1027 1076
1077 /// Handles writes to the macro bind register.
1078 void ProcessMacroBind(u32 data);
1079
1028 /// Handles a write to the CLEAR_BUFFERS register. 1080 /// Handles a write to the CLEAR_BUFFERS register.
1029 void ProcessClearBuffers(); 1081 void ProcessClearBuffers();
1030 1082
@@ -1058,6 +1110,7 @@ ASSERT_REG_POSITION(scissor_test, 0x380);
1058ASSERT_REG_POSITION(stencil_back_func_ref, 0x3D5); 1110ASSERT_REG_POSITION(stencil_back_func_ref, 0x3D5);
1059ASSERT_REG_POSITION(stencil_back_mask, 0x3D6); 1111ASSERT_REG_POSITION(stencil_back_mask, 0x3D6);
1060ASSERT_REG_POSITION(stencil_back_func_mask, 0x3D7); 1112ASSERT_REG_POSITION(stencil_back_func_mask, 0x3D7);
1113ASSERT_REG_POSITION(color_mask_common, 0x3E4);
1061ASSERT_REG_POSITION(rt_separate_frag_data, 0x3EB); 1114ASSERT_REG_POSITION(rt_separate_frag_data, 0x3EB);
1062ASSERT_REG_POSITION(zeta, 0x3F8); 1115ASSERT_REG_POSITION(zeta, 0x3F8);
1063ASSERT_REG_POSITION(vertex_attrib_format, 0x458); 1116ASSERT_REG_POSITION(vertex_attrib_format, 0x458);
@@ -1070,6 +1123,10 @@ ASSERT_REG_POSITION(depth_write_enabled, 0x4BA);
1070ASSERT_REG_POSITION(alpha_test_enabled, 0x4BB); 1123ASSERT_REG_POSITION(alpha_test_enabled, 0x4BB);
1071ASSERT_REG_POSITION(d3d_cull_mode, 0x4C2); 1124ASSERT_REG_POSITION(d3d_cull_mode, 0x4C2);
1072ASSERT_REG_POSITION(depth_test_func, 0x4C3); 1125ASSERT_REG_POSITION(depth_test_func, 0x4C3);
1126ASSERT_REG_POSITION(alpha_test_ref, 0x4C4);
1127ASSERT_REG_POSITION(alpha_test_func, 0x4C5);
1128ASSERT_REG_POSITION(draw_tfb_stride, 0x4C6);
1129ASSERT_REG_POSITION(blend_color, 0x4C7);
1073ASSERT_REG_POSITION(blend, 0x4CF); 1130ASSERT_REG_POSITION(blend, 0x4CF);
1074ASSERT_REG_POSITION(stencil_enable, 0x4E0); 1131ASSERT_REG_POSITION(stencil_enable, 0x4E0);
1075ASSERT_REG_POSITION(stencil_front_op_fail, 0x4E1); 1132ASSERT_REG_POSITION(stencil_front_op_fail, 0x4E1);
@@ -1100,6 +1157,7 @@ ASSERT_REG_POSITION(instanced_arrays, 0x620);
1100ASSERT_REG_POSITION(cull, 0x646); 1157ASSERT_REG_POSITION(cull, 0x646);
1101ASSERT_REG_POSITION(logic_op, 0x671); 1158ASSERT_REG_POSITION(logic_op, 0x671);
1102ASSERT_REG_POSITION(clear_buffers, 0x674); 1159ASSERT_REG_POSITION(clear_buffers, 0x674);
1160ASSERT_REG_POSITION(color_mask, 0x680);
1103ASSERT_REG_POSITION(query, 0x6C0); 1161ASSERT_REG_POSITION(query, 0x6C0);
1104ASSERT_REG_POSITION(vertex_array[0], 0x700); 1162ASSERT_REG_POSITION(vertex_array[0], 0x700);
1105ASSERT_REG_POSITION(independent_blend, 0x780); 1163ASSERT_REG_POSITION(independent_blend, 0x780);
diff --git a/src/video_core/engines/shader_bytecode.h b/src/video_core/engines/shader_bytecode.h
index 141b9159b..83a6fd875 100644
--- a/src/video_core/engines/shader_bytecode.h
+++ b/src/video_core/engines/shader_bytecode.h
@@ -5,12 +5,11 @@
5#pragma once 5#pragma once
6 6
7#include <bitset> 7#include <bitset>
8#include <optional>
8#include <string> 9#include <string>
9#include <tuple> 10#include <tuple>
10#include <vector> 11#include <vector>
11 12
12#include <boost/optional.hpp>
13
14#include "common/assert.h" 13#include "common/assert.h"
15#include "common/bit_field.h" 14#include "common/bit_field.h"
16#include "common/common_types.h" 15#include "common/common_types.h"
@@ -579,6 +578,10 @@ union Instruction {
579 } fmul32; 578 } fmul32;
580 579
581 union { 580 union {
581 BitField<52, 1, u64> generates_cc;
582 } op_32;
583
584 union {
582 BitField<48, 1, u64> is_signed; 585 BitField<48, 1, u64> is_signed;
583 } shift; 586 } shift;
584 587
@@ -1232,6 +1235,7 @@ union Instruction {
1232 BitField<60, 1, u64> is_b_gpr; 1235 BitField<60, 1, u64> is_b_gpr;
1233 BitField<59, 1, u64> is_c_gpr; 1236 BitField<59, 1, u64> is_c_gpr;
1234 BitField<20, 24, s64> smem_imm; 1237 BitField<20, 24, s64> smem_imm;
1238 BitField<0, 5, ControlCode> flow_control_code;
1235 1239
1236 Attribute attribute; 1240 Attribute attribute;
1237 Sampler sampler; 1241 Sampler sampler;
@@ -1456,7 +1460,7 @@ public:
1456 Type type; 1460 Type type;
1457 }; 1461 };
1458 1462
1459 static boost::optional<const Matcher&> Decode(Instruction instr) { 1463 static std::optional<std::reference_wrapper<const Matcher>> Decode(Instruction instr) {
1460 static const auto table{GetDecodeTable()}; 1464 static const auto table{GetDecodeTable()};
1461 1465
1462 const auto matches_instruction = [instr](const auto& matcher) { 1466 const auto matches_instruction = [instr](const auto& matcher) {
@@ -1464,7 +1468,8 @@ public:
1464 }; 1468 };
1465 1469
1466 auto iter = std::find_if(table.begin(), table.end(), matches_instruction); 1470 auto iter = std::find_if(table.begin(), table.end(), matches_instruction);
1467 return iter != table.end() ? boost::optional<const Matcher&>(*iter) : boost::none; 1471 return iter != table.end() ? std::optional<std::reference_wrapper<const Matcher>>(*iter)
1472 : std::nullopt;
1468 } 1473 }
1469 1474
1470private: 1475private:
@@ -1658,4 +1663,4 @@ private:
1658 } 1663 }
1659}; 1664};
1660 1665
1661} // namespace Tegra::Shader \ No newline at end of file 1666} // namespace Tegra::Shader
diff --git a/src/video_core/macro_interpreter.cpp b/src/video_core/macro_interpreter.cpp
index 377bd66ab..335a8d407 100644
--- a/src/video_core/macro_interpreter.cpp
+++ b/src/video_core/macro_interpreter.cpp
@@ -11,7 +11,7 @@ namespace Tegra {
11 11
12MacroInterpreter::MacroInterpreter(Engines::Maxwell3D& maxwell3d) : maxwell3d(maxwell3d) {} 12MacroInterpreter::MacroInterpreter(Engines::Maxwell3D& maxwell3d) : maxwell3d(maxwell3d) {}
13 13
14void MacroInterpreter::Execute(const std::vector<u32>& code, std::vector<u32> parameters) { 14void MacroInterpreter::Execute(u32 offset, std::vector<u32> parameters) {
15 Reset(); 15 Reset();
16 registers[1] = parameters[0]; 16 registers[1] = parameters[0];
17 this->parameters = std::move(parameters); 17 this->parameters = std::move(parameters);
@@ -19,7 +19,7 @@ void MacroInterpreter::Execute(const std::vector<u32>& code, std::vector<u32> pa
19 // Execute the code until we hit an exit condition. 19 // Execute the code until we hit an exit condition.
20 bool keep_executing = true; 20 bool keep_executing = true;
21 while (keep_executing) { 21 while (keep_executing) {
22 keep_executing = Step(code, false); 22 keep_executing = Step(offset, false);
23 } 23 }
24 24
25 // Assert the the macro used all the input parameters 25 // Assert the the macro used all the input parameters
@@ -29,7 +29,7 @@ void MacroInterpreter::Execute(const std::vector<u32>& code, std::vector<u32> pa
29void MacroInterpreter::Reset() { 29void MacroInterpreter::Reset() {
30 registers = {}; 30 registers = {};
31 pc = 0; 31 pc = 0;
32 delayed_pc = boost::none; 32 delayed_pc = {};
33 method_address.raw = 0; 33 method_address.raw = 0;
34 parameters.clear(); 34 parameters.clear();
35 // The next parameter index starts at 1, because $r1 already has the value of the first 35 // The next parameter index starts at 1, because $r1 already has the value of the first
@@ -37,17 +37,17 @@ void MacroInterpreter::Reset() {
37 next_parameter_index = 1; 37 next_parameter_index = 1;
38} 38}
39 39
40bool MacroInterpreter::Step(const std::vector<u32>& code, bool is_delay_slot) { 40bool MacroInterpreter::Step(u32 offset, bool is_delay_slot) {
41 u32 base_address = pc; 41 u32 base_address = pc;
42 42
43 Opcode opcode = GetOpcode(code); 43 Opcode opcode = GetOpcode(offset);
44 pc += 4; 44 pc += 4;
45 45
46 // Update the program counter if we were delayed 46 // Update the program counter if we were delayed
47 if (delayed_pc != boost::none) { 47 if (delayed_pc) {
48 ASSERT(is_delay_slot); 48 ASSERT(is_delay_slot);
49 pc = *delayed_pc; 49 pc = *delayed_pc;
50 delayed_pc = boost::none; 50 delayed_pc = {};
51 } 51 }
52 52
53 switch (opcode.operation) { 53 switch (opcode.operation) {
@@ -108,7 +108,7 @@ bool MacroInterpreter::Step(const std::vector<u32>& code, bool is_delay_slot) {
108 108
109 delayed_pc = base_address + opcode.GetBranchTarget(); 109 delayed_pc = base_address + opcode.GetBranchTarget();
110 // Execute one more instruction due to the delay slot. 110 // Execute one more instruction due to the delay slot.
111 return Step(code, true); 111 return Step(offset, true);
112 } 112 }
113 break; 113 break;
114 } 114 }
@@ -121,17 +121,18 @@ bool MacroInterpreter::Step(const std::vector<u32>& code, bool is_delay_slot) {
121 // Exit has a delay slot, execute the next instruction 121 // Exit has a delay slot, execute the next instruction
122 // Note: Executing an exit during a branch delay slot will cause the instruction at the 122 // Note: Executing an exit during a branch delay slot will cause the instruction at the
123 // branch target to be executed before exiting. 123 // branch target to be executed before exiting.
124 Step(code, true); 124 Step(offset, true);
125 return false; 125 return false;
126 } 126 }
127 127
128 return true; 128 return true;
129} 129}
130 130
131MacroInterpreter::Opcode MacroInterpreter::GetOpcode(const std::vector<u32>& code) const { 131MacroInterpreter::Opcode MacroInterpreter::GetOpcode(u32 offset) const {
132 const auto& macro_memory{maxwell3d.GetMacroMemory()};
132 ASSERT((pc % sizeof(u32)) == 0); 133 ASSERT((pc % sizeof(u32)) == 0);
133 ASSERT(pc < code.size() * sizeof(u32)); 134 ASSERT((pc + offset) < macro_memory.size() * sizeof(u32));
134 return {code[pc / sizeof(u32)]}; 135 return {macro_memory[offset + pc / sizeof(u32)]};
135} 136}
136 137
137u32 MacroInterpreter::GetALUResult(ALUOperation operation, u32 src_a, u32 src_b) const { 138u32 MacroInterpreter::GetALUResult(ALUOperation operation, u32 src_a, u32 src_b) const {
diff --git a/src/video_core/macro_interpreter.h b/src/video_core/macro_interpreter.h
index cee0baaf3..62d1ce289 100644
--- a/src/video_core/macro_interpreter.h
+++ b/src/video_core/macro_interpreter.h
@@ -5,8 +5,9 @@
5#pragma once 5#pragma once
6 6
7#include <array> 7#include <array>
8#include <optional>
8#include <vector> 9#include <vector>
9#include <boost/optional.hpp> 10
10#include "common/bit_field.h" 11#include "common/bit_field.h"
11#include "common/common_types.h" 12#include "common/common_types.h"
12 13
@@ -21,10 +22,10 @@ public:
21 22
22 /** 23 /**
23 * Executes the macro code with the specified input parameters. 24 * Executes the macro code with the specified input parameters.
24 * @param code The macro byte code to execute 25 * @param offset Offset to start execution at.
25 * @param parameters The parameters of the macro 26 * @param parameters The parameters of the macro.
26 */ 27 */
27 void Execute(const std::vector<u32>& code, std::vector<u32> parameters); 28 void Execute(u32 offset, std::vector<u32> parameters);
28 29
29private: 30private:
30 enum class Operation : u32 { 31 enum class Operation : u32 {
@@ -109,11 +110,11 @@ private:
109 /** 110 /**
110 * Executes a single macro instruction located at the current program counter. Returns whether 111 * Executes a single macro instruction located at the current program counter. Returns whether
111 * the interpreter should keep running. 112 * the interpreter should keep running.
112 * @param code The macro code to execute. 113 * @param offset Offset to start execution at.
113 * @param is_delay_slot Whether the current step is being executed due to a delay slot in a 114 * @param is_delay_slot Whether the current step is being executed due to a delay slot in a
114 * previous instruction. 115 * previous instruction.
115 */ 116 */
116 bool Step(const std::vector<u32>& code, bool is_delay_slot); 117 bool Step(u32 offset, bool is_delay_slot);
117 118
118 /// Calculates the result of an ALU operation. src_a OP src_b; 119 /// Calculates the result of an ALU operation. src_a OP src_b;
119 u32 GetALUResult(ALUOperation operation, u32 src_a, u32 src_b) const; 120 u32 GetALUResult(ALUOperation operation, u32 src_a, u32 src_b) const;
@@ -126,7 +127,7 @@ private:
126 bool EvaluateBranchCondition(BranchCondition cond, u32 value) const; 127 bool EvaluateBranchCondition(BranchCondition cond, u32 value) const;
127 128
128 /// Reads an opcode at the current program counter location. 129 /// Reads an opcode at the current program counter location.
129 Opcode GetOpcode(const std::vector<u32>& code) const; 130 Opcode GetOpcode(u32 offset) const;
130 131
131 /// Returns the specified register's value. Register 0 is hardcoded to always return 0. 132 /// Returns the specified register's value. Register 0 is hardcoded to always return 0.
132 u32 GetRegister(u32 register_id) const; 133 u32 GetRegister(u32 register_id) const;
@@ -149,7 +150,7 @@ private:
149 Engines::Maxwell3D& maxwell3d; 150 Engines::Maxwell3D& maxwell3d;
150 151
151 u32 pc; ///< Current program counter 152 u32 pc; ///< Current program counter
152 boost::optional<u32> 153 std::optional<u32>
153 delayed_pc; ///< Program counter to execute at after the delay slot is executed. 154 delayed_pc; ///< Program counter to execute at after the delay slot is executed.
154 155
155 static constexpr std::size_t NumMacroRegisters = 8; 156 static constexpr std::size_t NumMacroRegisters = 8;
diff --git a/src/video_core/memory_manager.cpp b/src/video_core/memory_manager.cpp
index 022d4ab74..77a20bb84 100644
--- a/src/video_core/memory_manager.cpp
+++ b/src/video_core/memory_manager.cpp
@@ -4,18 +4,21 @@
4 4
5#include "common/alignment.h" 5#include "common/alignment.h"
6#include "common/assert.h" 6#include "common/assert.h"
7#include "common/logging/log.h"
7#include "video_core/memory_manager.h" 8#include "video_core/memory_manager.h"
8 9
9namespace Tegra { 10namespace Tegra {
10 11
11GPUVAddr MemoryManager::AllocateSpace(u64 size, u64 align) { 12GPUVAddr MemoryManager::AllocateSpace(u64 size, u64 align) {
12 boost::optional<GPUVAddr> gpu_addr = FindFreeBlock(size, align); 13 const std::optional<GPUVAddr> gpu_addr{FindFreeBlock(0, size, align, PageStatus::Unmapped)};
13 ASSERT(gpu_addr);
14 14
15 for (u64 offset = 0; offset < size; offset += PAGE_SIZE) { 15 ASSERT_MSG(gpu_addr, "unable to find available GPU memory");
16 VAddr& slot = PageSlot(*gpu_addr + offset); 16
17 for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
18 VAddr& slot{PageSlot(*gpu_addr + offset)};
17 19
18 ASSERT(slot == static_cast<u64>(PageStatus::Unmapped)); 20 ASSERT(slot == static_cast<u64>(PageStatus::Unmapped));
21
19 slot = static_cast<u64>(PageStatus::Allocated); 22 slot = static_cast<u64>(PageStatus::Allocated);
20 } 23 }
21 24
@@ -23,10 +26,11 @@ GPUVAddr MemoryManager::AllocateSpace(u64 size, u64 align) {
23} 26}
24 27
25GPUVAddr MemoryManager::AllocateSpace(GPUVAddr gpu_addr, u64 size, u64 align) { 28GPUVAddr MemoryManager::AllocateSpace(GPUVAddr gpu_addr, u64 size, u64 align) {
26 for (u64 offset = 0; offset < size; offset += PAGE_SIZE) { 29 for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
27 VAddr& slot = PageSlot(gpu_addr + offset); 30 VAddr& slot{PageSlot(gpu_addr + offset)};
28 31
29 ASSERT(slot == static_cast<u64>(PageStatus::Unmapped)); 32 ASSERT(slot == static_cast<u64>(PageStatus::Unmapped));
33
30 slot = static_cast<u64>(PageStatus::Allocated); 34 slot = static_cast<u64>(PageStatus::Allocated);
31 } 35 }
32 36
@@ -34,17 +38,19 @@ GPUVAddr MemoryManager::AllocateSpace(GPUVAddr gpu_addr, u64 size, u64 align) {
34} 38}
35 39
36GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, u64 size) { 40GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, u64 size) {
37 boost::optional<GPUVAddr> gpu_addr = FindFreeBlock(size, PAGE_SIZE); 41 const std::optional<GPUVAddr> gpu_addr{FindFreeBlock(0, size, PAGE_SIZE, PageStatus::Unmapped)};
38 ASSERT(gpu_addr); 42
43 ASSERT_MSG(gpu_addr, "unable to find available GPU memory");
39 44
40 for (u64 offset = 0; offset < size; offset += PAGE_SIZE) { 45 for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
41 VAddr& slot = PageSlot(*gpu_addr + offset); 46 VAddr& slot{PageSlot(*gpu_addr + offset)};
42 47
43 ASSERT(slot == static_cast<u64>(PageStatus::Unmapped)); 48 ASSERT(slot == static_cast<u64>(PageStatus::Unmapped));
49
44 slot = cpu_addr + offset; 50 slot = cpu_addr + offset;
45 } 51 }
46 52
47 MappedRegion region{cpu_addr, *gpu_addr, size}; 53 const MappedRegion region{cpu_addr, *gpu_addr, size};
48 mapped_regions.push_back(region); 54 mapped_regions.push_back(region);
49 55
50 return *gpu_addr; 56 return *gpu_addr;
@@ -53,14 +59,31 @@ GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, u64 size) {
53GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, GPUVAddr gpu_addr, u64 size) { 59GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, GPUVAddr gpu_addr, u64 size) {
54 ASSERT((gpu_addr & PAGE_MASK) == 0); 60 ASSERT((gpu_addr & PAGE_MASK) == 0);
55 61
56 for (u64 offset = 0; offset < size; offset += PAGE_SIZE) { 62 if (PageSlot(gpu_addr) != static_cast<u64>(PageStatus::Allocated)) {
57 VAddr& slot = PageSlot(gpu_addr + offset); 63 // Page has been already mapped. In this case, we must find a new area of memory to use that
64 // is different than the specified one. Super Mario Odyssey hits this scenario when changing
65 // areas, but we do not want to overwrite the old pages.
66 // TODO(bunnei): We need to write a hardware test to confirm this behavior.
67
68 LOG_ERROR(HW_GPU, "attempting to map addr 0x{:016X}, which is not available!", gpu_addr);
69
70 const std::optional<GPUVAddr> new_gpu_addr{
71 FindFreeBlock(gpu_addr, size, PAGE_SIZE, PageStatus::Allocated)};
72
73 ASSERT_MSG(new_gpu_addr, "unable to find available GPU memory");
74
75 gpu_addr = *new_gpu_addr;
76 }
77
78 for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
79 VAddr& slot{PageSlot(gpu_addr + offset)};
58 80
59 ASSERT(slot == static_cast<u64>(PageStatus::Allocated)); 81 ASSERT(slot == static_cast<u64>(PageStatus::Allocated));
82
60 slot = cpu_addr + offset; 83 slot = cpu_addr + offset;
61 } 84 }
62 85
63 MappedRegion region{cpu_addr, gpu_addr, size}; 86 const MappedRegion region{cpu_addr, gpu_addr, size};
64 mapped_regions.push_back(region); 87 mapped_regions.push_back(region);
65 88
66 return gpu_addr; 89 return gpu_addr;
@@ -69,11 +92,12 @@ GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, GPUVAddr gpu_addr, u64 size)
69GPUVAddr MemoryManager::UnmapBuffer(GPUVAddr gpu_addr, u64 size) { 92GPUVAddr MemoryManager::UnmapBuffer(GPUVAddr gpu_addr, u64 size) {
70 ASSERT((gpu_addr & PAGE_MASK) == 0); 93 ASSERT((gpu_addr & PAGE_MASK) == 0);
71 94
72 for (u64 offset = 0; offset < size; offset += PAGE_SIZE) { 95 for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
73 VAddr& slot = PageSlot(gpu_addr + offset); 96 VAddr& slot{PageSlot(gpu_addr + offset)};
74 97
75 ASSERT(slot != static_cast<u64>(PageStatus::Allocated) && 98 ASSERT(slot != static_cast<u64>(PageStatus::Allocated) &&
76 slot != static_cast<u64>(PageStatus::Unmapped)); 99 slot != static_cast<u64>(PageStatus::Unmapped));
100
77 slot = static_cast<u64>(PageStatus::Unmapped); 101 slot = static_cast<u64>(PageStatus::Unmapped);
78 } 102 }
79 103
@@ -97,13 +121,14 @@ GPUVAddr MemoryManager::GetRegionEnd(GPUVAddr region_start) const {
97 return {}; 121 return {};
98} 122}
99 123
100boost::optional<GPUVAddr> MemoryManager::FindFreeBlock(u64 size, u64 align) { 124std::optional<GPUVAddr> MemoryManager::FindFreeBlock(GPUVAddr region_start, u64 size, u64 align,
101 GPUVAddr gpu_addr = 0; 125 PageStatus status) {
102 u64 free_space = 0; 126 GPUVAddr gpu_addr{region_start};
127 u64 free_space{};
103 align = (align + PAGE_MASK) & ~PAGE_MASK; 128 align = (align + PAGE_MASK) & ~PAGE_MASK;
104 129
105 while (gpu_addr + free_space < MAX_ADDRESS) { 130 while (gpu_addr + free_space < MAX_ADDRESS) {
106 if (!IsPageMapped(gpu_addr + free_space)) { 131 if (PageSlot(gpu_addr + free_space) == static_cast<u64>(status)) {
107 free_space += PAGE_SIZE; 132 free_space += PAGE_SIZE;
108 if (free_space >= size) { 133 if (free_space >= size) {
109 return gpu_addr; 134 return gpu_addr;
@@ -118,8 +143,8 @@ boost::optional<GPUVAddr> MemoryManager::FindFreeBlock(u64 size, u64 align) {
118 return {}; 143 return {};
119} 144}
120 145
121boost::optional<VAddr> MemoryManager::GpuToCpuAddress(GPUVAddr gpu_addr) { 146std::optional<VAddr> MemoryManager::GpuToCpuAddress(GPUVAddr gpu_addr) {
122 VAddr base_addr = PageSlot(gpu_addr); 147 const VAddr base_addr{PageSlot(gpu_addr)};
123 148
124 if (base_addr == static_cast<u64>(PageStatus::Allocated) || 149 if (base_addr == static_cast<u64>(PageStatus::Allocated) ||
125 base_addr == static_cast<u64>(PageStatus::Unmapped)) { 150 base_addr == static_cast<u64>(PageStatus::Unmapped)) {
@@ -133,19 +158,15 @@ std::vector<GPUVAddr> MemoryManager::CpuToGpuAddress(VAddr cpu_addr) const {
133 std::vector<GPUVAddr> results; 158 std::vector<GPUVAddr> results;
134 for (const auto& region : mapped_regions) { 159 for (const auto& region : mapped_regions) {
135 if (cpu_addr >= region.cpu_addr && cpu_addr < (region.cpu_addr + region.size)) { 160 if (cpu_addr >= region.cpu_addr && cpu_addr < (region.cpu_addr + region.size)) {
136 u64 offset = cpu_addr - region.cpu_addr; 161 const u64 offset{cpu_addr - region.cpu_addr};
137 results.push_back(region.gpu_addr + offset); 162 results.push_back(region.gpu_addr + offset);
138 } 163 }
139 } 164 }
140 return results; 165 return results;
141} 166}
142 167
143bool MemoryManager::IsPageMapped(GPUVAddr gpu_addr) {
144 return PageSlot(gpu_addr) != static_cast<u64>(PageStatus::Unmapped);
145}
146
147VAddr& MemoryManager::PageSlot(GPUVAddr gpu_addr) { 168VAddr& MemoryManager::PageSlot(GPUVAddr gpu_addr) {
148 auto& block = page_table[(gpu_addr >> (PAGE_BITS + PAGE_TABLE_BITS)) & PAGE_TABLE_MASK]; 169 auto& block{page_table[(gpu_addr >> (PAGE_BITS + PAGE_TABLE_BITS)) & PAGE_TABLE_MASK]};
149 if (!block) { 170 if (!block) {
150 block = std::make_unique<PageBlock>(); 171 block = std::make_unique<PageBlock>();
151 block->fill(static_cast<VAddr>(PageStatus::Unmapped)); 172 block->fill(static_cast<VAddr>(PageStatus::Unmapped));
diff --git a/src/video_core/memory_manager.h b/src/video_core/memory_manager.h
index caf80093f..4eb338aa2 100644
--- a/src/video_core/memory_manager.h
+++ b/src/video_core/memory_manager.h
@@ -6,10 +6,9 @@
6 6
7#include <array> 7#include <array>
8#include <memory> 8#include <memory>
9#include <optional>
9#include <vector> 10#include <vector>
10 11
11#include <boost/optional.hpp>
12
13#include "common/common_types.h" 12#include "common/common_types.h"
14 13
15namespace Tegra { 14namespace Tegra {
@@ -27,7 +26,7 @@ public:
27 GPUVAddr MapBufferEx(VAddr cpu_addr, GPUVAddr gpu_addr, u64 size); 26 GPUVAddr MapBufferEx(VAddr cpu_addr, GPUVAddr gpu_addr, u64 size);
28 GPUVAddr UnmapBuffer(GPUVAddr gpu_addr, u64 size); 27 GPUVAddr UnmapBuffer(GPUVAddr gpu_addr, u64 size);
29 GPUVAddr GetRegionEnd(GPUVAddr region_start) const; 28 GPUVAddr GetRegionEnd(GPUVAddr region_start) const;
30 boost::optional<VAddr> GpuToCpuAddress(GPUVAddr gpu_addr); 29 std::optional<VAddr> GpuToCpuAddress(GPUVAddr gpu_addr);
31 std::vector<GPUVAddr> CpuToGpuAddress(VAddr cpu_addr) const; 30 std::vector<GPUVAddr> CpuToGpuAddress(VAddr cpu_addr) const;
32 31
33 static constexpr u64 PAGE_BITS = 16; 32 static constexpr u64 PAGE_BITS = 16;
@@ -35,15 +34,15 @@ public:
35 static constexpr u64 PAGE_MASK = PAGE_SIZE - 1; 34 static constexpr u64 PAGE_MASK = PAGE_SIZE - 1;
36 35
37private: 36private:
38 boost::optional<GPUVAddr> FindFreeBlock(u64 size, u64 align = 1);
39 bool IsPageMapped(GPUVAddr gpu_addr);
40 VAddr& PageSlot(GPUVAddr gpu_addr);
41
42 enum class PageStatus : u64 { 37 enum class PageStatus : u64 {
43 Unmapped = 0xFFFFFFFFFFFFFFFFULL, 38 Unmapped = 0xFFFFFFFFFFFFFFFFULL,
44 Allocated = 0xFFFFFFFFFFFFFFFEULL, 39 Allocated = 0xFFFFFFFFFFFFFFFEULL,
45 }; 40 };
46 41
42 std::optional<GPUVAddr> FindFreeBlock(GPUVAddr region_start, u64 size, u64 align,
43 PageStatus status);
44 VAddr& PageSlot(GPUVAddr gpu_addr);
45
47 static constexpr u64 MAX_ADDRESS{0x10000000000ULL}; 46 static constexpr u64 MAX_ADDRESS{0x10000000000ULL};
48 static constexpr u64 PAGE_TABLE_BITS{10}; 47 static constexpr u64 PAGE_TABLE_BITS{10};
49 static constexpr u64 PAGE_TABLE_SIZE{1 << PAGE_TABLE_BITS}; 48 static constexpr u64 PAGE_TABLE_SIZE{1 << PAGE_TABLE_BITS};
diff --git a/src/video_core/rasterizer_cache.cpp b/src/video_core/rasterizer_cache.cpp
new file mode 100644
index 000000000..093b2cdf4
--- /dev/null
+++ b/src/video_core/rasterizer_cache.cpp
@@ -0,0 +1,7 @@
1// Copyright 2018 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "video_core/rasterizer_cache.h"
6
7RasterizerCacheObject::~RasterizerCacheObject() = default;
diff --git a/src/video_core/rasterizer_cache.h b/src/video_core/rasterizer_cache.h
index 0a3b3951e..bcf0c15a4 100644
--- a/src/video_core/rasterizer_cache.h
+++ b/src/video_core/rasterizer_cache.h
@@ -5,18 +5,19 @@
5#pragma once 5#pragma once
6 6
7#include <set> 7#include <set>
8#include <unordered_map>
8 9
9#include <boost/icl/interval_map.hpp> 10#include <boost/icl/interval_map.hpp>
10#include <boost/range/iterator_range_core.hpp> 11#include <boost/range/iterator_range_core.hpp>
11 12
12#include "common/common_types.h" 13#include "common/common_types.h"
13#include "core/core.h"
14#include "core/settings.h" 14#include "core/settings.h"
15#include "video_core/rasterizer_interface.h" 15#include "video_core/rasterizer_interface.h"
16#include "video_core/renderer_base.h"
17 16
18class RasterizerCacheObject { 17class RasterizerCacheObject {
19public: 18public:
19 virtual ~RasterizerCacheObject();
20
20 /// Gets the address of the shader in guest memory, required for cache management 21 /// Gets the address of the shader in guest memory, required for cache management
21 virtual VAddr GetAddr() const = 0; 22 virtual VAddr GetAddr() const = 0;
22 23
@@ -64,6 +65,8 @@ class RasterizerCache : NonCopyable {
64 friend class RasterizerCacheObject; 65 friend class RasterizerCacheObject;
65 66
66public: 67public:
68 explicit RasterizerCache(VideoCore::RasterizerInterface& rasterizer) : rasterizer{rasterizer} {}
69
67 /// Write any cached resources overlapping the specified region back to memory 70 /// Write any cached resources overlapping the specified region back to memory
68 void FlushRegion(Tegra::GPUVAddr addr, size_t size) { 71 void FlushRegion(Tegra::GPUVAddr addr, size_t size) {
69 const auto& objects{GetSortedObjectsFromRegion(addr, size)}; 72 const auto& objects{GetSortedObjectsFromRegion(addr, size)};
@@ -86,45 +89,39 @@ public:
86 89
87 /// Invalidates everything in the cache 90 /// Invalidates everything in the cache
88 void InvalidateAll() { 91 void InvalidateAll() {
89 while (object_cache.begin() != object_cache.end()) { 92 while (interval_cache.begin() != interval_cache.end()) {
90 Unregister(*object_cache.begin()->second.begin()); 93 Unregister(*interval_cache.begin()->second.begin());
91 } 94 }
92 } 95 }
93 96
94protected: 97protected:
95 /// Tries to get an object from the cache with the specified address 98 /// Tries to get an object from the cache with the specified address
96 T TryGet(VAddr addr) const { 99 T TryGet(VAddr addr) const {
97 const ObjectInterval interval{addr}; 100 const auto iter = map_cache.find(addr);
98 for (auto& pair : boost::make_iterator_range(object_cache.equal_range(interval))) { 101 if (iter != map_cache.end())
99 for (auto& cached_object : pair.second) { 102 return iter->second;
100 if (cached_object->GetAddr() == addr) {
101 return cached_object;
102 }
103 }
104 }
105 return nullptr; 103 return nullptr;
106 } 104 }
107 105
108 /// Register an object into the cache 106 /// Register an object into the cache
109 void Register(const T& object) { 107 void Register(const T& object) {
110 object->SetIsRegistered(true); 108 object->SetIsRegistered(true);
111 object_cache.add({GetInterval(object), ObjectSet{object}}); 109 interval_cache.add({GetInterval(object), ObjectSet{object}});
112 auto& rasterizer = Core::System::GetInstance().Renderer().Rasterizer(); 110 map_cache.insert({object->GetAddr(), object});
113 rasterizer.UpdatePagesCachedCount(object->GetAddr(), object->GetSizeInBytes(), 1); 111 rasterizer.UpdatePagesCachedCount(object->GetAddr(), object->GetSizeInBytes(), 1);
114 } 112 }
115 113
116 /// Unregisters an object from the cache 114 /// Unregisters an object from the cache
117 void Unregister(const T& object) { 115 void Unregister(const T& object) {
118 object->SetIsRegistered(false); 116 object->SetIsRegistered(false);
119 auto& rasterizer = Core::System::GetInstance().Renderer().Rasterizer();
120 rasterizer.UpdatePagesCachedCount(object->GetAddr(), object->GetSizeInBytes(), -1); 117 rasterizer.UpdatePagesCachedCount(object->GetAddr(), object->GetSizeInBytes(), -1);
121
122 // Only flush if use_accurate_gpu_emulation is enabled, as it incurs a performance hit 118 // Only flush if use_accurate_gpu_emulation is enabled, as it incurs a performance hit
123 if (Settings::values.use_accurate_gpu_emulation) { 119 if (Settings::values.use_accurate_gpu_emulation) {
124 FlushObject(object); 120 FlushObject(object);
125 } 121 }
126 122
127 object_cache.subtract({GetInterval(object), ObjectSet{object}}); 123 interval_cache.subtract({GetInterval(object), ObjectSet{object}});
124 map_cache.erase(object->GetAddr());
128 } 125 }
129 126
130 /// Returns a ticks counter used for tracking when cached objects were last modified 127 /// Returns a ticks counter used for tracking when cached objects were last modified
@@ -141,7 +138,7 @@ private:
141 138
142 std::vector<T> objects; 139 std::vector<T> objects;
143 const ObjectInterval interval{addr, addr + size}; 140 const ObjectInterval interval{addr, addr + size};
144 for (auto& pair : boost::make_iterator_range(object_cache.equal_range(interval))) { 141 for (auto& pair : boost::make_iterator_range(interval_cache.equal_range(interval))) {
145 for (auto& cached_object : pair.second) { 142 for (auto& cached_object : pair.second) {
146 if (!cached_object) { 143 if (!cached_object) {
147 continue; 144 continue;
@@ -167,14 +164,17 @@ private:
167 } 164 }
168 165
169 using ObjectSet = std::set<T>; 166 using ObjectSet = std::set<T>;
170 using ObjectCache = boost::icl::interval_map<VAddr, ObjectSet>; 167 using ObjectCache = std::unordered_map<VAddr, T>;
171 using ObjectInterval = typename ObjectCache::interval_type; 168 using IntervalCache = boost::icl::interval_map<VAddr, ObjectSet>;
169 using ObjectInterval = typename IntervalCache::interval_type;
172 170
173 static auto GetInterval(const T& object) { 171 static auto GetInterval(const T& object) {
174 return ObjectInterval::right_open(object->GetAddr(), 172 return ObjectInterval::right_open(object->GetAddr(),
175 object->GetAddr() + object->GetSizeInBytes()); 173 object->GetAddr() + object->GetSizeInBytes());
176 } 174 }
177 175
178 ObjectCache object_cache; ///< Cache of objects 176 ObjectCache map_cache;
179 u64 modified_ticks{}; ///< Counter of cache state ticks, used for in-order flushing 177 IntervalCache interval_cache; ///< Cache of objects
178 u64 modified_ticks{}; ///< Counter of cache state ticks, used for in-order flushing
179 VideoCore::RasterizerInterface& rasterizer;
180}; 180};
diff --git a/src/video_core/renderer_base.cpp b/src/video_core/renderer_base.cpp
index 0df3725c2..1482cdb40 100644
--- a/src/video_core/renderer_base.cpp
+++ b/src/video_core/renderer_base.cpp
@@ -5,7 +5,6 @@
5#include "core/frontend/emu_window.h" 5#include "core/frontend/emu_window.h"
6#include "core/settings.h" 6#include "core/settings.h"
7#include "video_core/renderer_base.h" 7#include "video_core/renderer_base.h"
8#include "video_core/renderer_opengl/gl_rasterizer.h"
9 8
10namespace VideoCore { 9namespace VideoCore {
11 10
diff --git a/src/video_core/renderer_base.h b/src/video_core/renderer_base.h
index 2cd0738ff..669e26e15 100644
--- a/src/video_core/renderer_base.h
+++ b/src/video_core/renderer_base.h
@@ -6,7 +6,8 @@
6 6
7#include <atomic> 7#include <atomic>
8#include <memory> 8#include <memory>
9#include <boost/optional.hpp> 9#include <optional>
10
10#include "common/common_types.h" 11#include "common/common_types.h"
11#include "video_core/gpu.h" 12#include "video_core/gpu.h"
12#include "video_core/rasterizer_interface.h" 13#include "video_core/rasterizer_interface.h"
@@ -28,7 +29,8 @@ public:
28 virtual ~RendererBase(); 29 virtual ~RendererBase();
29 30
30 /// Swap buffers (render frame) 31 /// Swap buffers (render frame)
31 virtual void SwapBuffers(boost::optional<const Tegra::FramebufferConfig&> framebuffer) = 0; 32 virtual void SwapBuffers(
33 std::optional<std::reference_wrapper<const Tegra::FramebufferConfig>> framebuffer) = 0;
32 34
33 /// Initialize the renderer 35 /// Initialize the renderer
34 virtual bool Init() = 0; 36 virtual bool Init() = 0;
diff --git a/src/video_core/renderer_opengl/gl_buffer_cache.cpp b/src/video_core/renderer_opengl/gl_buffer_cache.cpp
index c142095c5..075192c3f 100644
--- a/src/video_core/renderer_opengl/gl_buffer_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_buffer_cache.cpp
@@ -9,15 +9,17 @@
9#include "core/core.h" 9#include "core/core.h"
10#include "core/memory.h" 10#include "core/memory.h"
11#include "video_core/renderer_opengl/gl_buffer_cache.h" 11#include "video_core/renderer_opengl/gl_buffer_cache.h"
12#include "video_core/renderer_opengl/gl_rasterizer.h"
12 13
13namespace OpenGL { 14namespace OpenGL {
14 15
15OGLBufferCache::OGLBufferCache(std::size_t size) : stream_buffer(GL_ARRAY_BUFFER, size) {} 16OGLBufferCache::OGLBufferCache(RasterizerOpenGL& rasterizer, std::size_t size)
17 : RasterizerCache{rasterizer}, stream_buffer(GL_ARRAY_BUFFER, size) {}
16 18
17GLintptr OGLBufferCache::UploadMemory(Tegra::GPUVAddr gpu_addr, std::size_t size, 19GLintptr OGLBufferCache::UploadMemory(Tegra::GPUVAddr gpu_addr, std::size_t size,
18 std::size_t alignment, bool cache) { 20 std::size_t alignment, bool cache) {
19 auto& memory_manager = Core::System::GetInstance().GPU().MemoryManager(); 21 auto& memory_manager = Core::System::GetInstance().GPU().MemoryManager();
20 const boost::optional<VAddr> cpu_addr{memory_manager.GpuToCpuAddress(gpu_addr)}; 22 const std::optional<VAddr> cpu_addr{memory_manager.GpuToCpuAddress(gpu_addr)};
21 23
22 // Cache management is a big overhead, so only cache entries with a given size. 24 // Cache management is a big overhead, so only cache entries with a given size.
23 // TODO: Figure out which size is the best for given games. 25 // TODO: Figure out which size is the best for given games.
diff --git a/src/video_core/renderer_opengl/gl_buffer_cache.h b/src/video_core/renderer_opengl/gl_buffer_cache.h
index be29dc8be..91fca3f6c 100644
--- a/src/video_core/renderer_opengl/gl_buffer_cache.h
+++ b/src/video_core/renderer_opengl/gl_buffer_cache.h
@@ -15,6 +15,8 @@
15 15
16namespace OpenGL { 16namespace OpenGL {
17 17
18class RasterizerOpenGL;
19
18struct CachedBufferEntry final : public RasterizerCacheObject { 20struct CachedBufferEntry final : public RasterizerCacheObject {
19 VAddr GetAddr() const override { 21 VAddr GetAddr() const override {
20 return addr; 22 return addr;
@@ -35,7 +37,7 @@ struct CachedBufferEntry final : public RasterizerCacheObject {
35 37
36class OGLBufferCache final : public RasterizerCache<std::shared_ptr<CachedBufferEntry>> { 38class OGLBufferCache final : public RasterizerCache<std::shared_ptr<CachedBufferEntry>> {
37public: 39public:
38 explicit OGLBufferCache(std::size_t size); 40 explicit OGLBufferCache(RasterizerOpenGL& rasterizer, std::size_t size);
39 41
40 /// Uploads data from a guest GPU address. Returns host's buffer offset where it's been 42 /// Uploads data from a guest GPU address. Returns host's buffer offset where it's been
41 /// allocated. 43 /// allocated.
diff --git a/src/video_core/renderer_opengl/gl_primitive_assembler.cpp b/src/video_core/renderer_opengl/gl_primitive_assembler.cpp
index ee1d9601b..d9ed08437 100644
--- a/src/video_core/renderer_opengl/gl_primitive_assembler.cpp
+++ b/src/video_core/renderer_opengl/gl_primitive_assembler.cpp
@@ -6,6 +6,7 @@
6#include <array> 6#include <array>
7#include "common/assert.h" 7#include "common/assert.h"
8#include "common/common_types.h" 8#include "common/common_types.h"
9#include "core/core.h"
9#include "core/memory.h" 10#include "core/memory.h"
10#include "video_core/renderer_opengl/gl_buffer_cache.h" 11#include "video_core/renderer_opengl/gl_buffer_cache.h"
11#include "video_core/renderer_opengl/gl_primitive_assembler.h" 12#include "video_core/renderer_opengl/gl_primitive_assembler.h"
@@ -45,7 +46,7 @@ GLintptr PrimitiveAssembler::MakeQuadIndexed(Tegra::GPUVAddr gpu_addr, std::size
45 auto [dst_pointer, index_offset] = buffer_cache.ReserveMemory(map_size); 46 auto [dst_pointer, index_offset] = buffer_cache.ReserveMemory(map_size);
46 47
47 auto& memory_manager = Core::System::GetInstance().GPU().MemoryManager(); 48 auto& memory_manager = Core::System::GetInstance().GPU().MemoryManager();
48 const boost::optional<VAddr> cpu_addr{memory_manager.GpuToCpuAddress(gpu_addr)}; 49 const std::optional<VAddr> cpu_addr{memory_manager.GpuToCpuAddress(gpu_addr)};
49 const u8* source{Memory::GetPointer(*cpu_addr)}; 50 const u8* source{Memory::GetPointer(*cpu_addr)};
50 51
51 for (u32 primitive = 0; primitive < count / 4; ++primitive) { 52 for (u32 primitive = 0; primitive < count / 4; ++primitive) {
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index cb180b93c..54cc47a9b 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -30,10 +30,11 @@
30namespace OpenGL { 30namespace OpenGL {
31 31
32using Maxwell = Tegra::Engines::Maxwell3D::Regs; 32using Maxwell = Tegra::Engines::Maxwell3D::Regs;
33using PixelFormat = SurfaceParams::PixelFormat; 33using PixelFormat = VideoCore::Surface::PixelFormat;
34using SurfaceType = SurfaceParams::SurfaceType; 34using SurfaceType = VideoCore::Surface::SurfaceType;
35 35
36MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Array Setup", MP_RGB(128, 128, 192)); 36MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
37MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
37MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192)); 38MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
38MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192)); 39MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
39MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192)); 40MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
@@ -79,7 +80,8 @@ struct DrawParameters {
79}; 80};
80 81
81RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo& info) 82RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo& info)
82 : emu_window{window}, screen_info{info}, buffer_cache(STREAM_BUFFER_SIZE) { 83 : res_cache{*this}, shader_cache{*this}, emu_window{window}, screen_info{info},
84 buffer_cache(*this, STREAM_BUFFER_SIZE) {
83 // Create sampler objects 85 // Create sampler objects
84 for (std::size_t i = 0; i < texture_samplers.size(); ++i) { 86 for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
85 texture_samplers[i].Create(); 87 texture_samplers[i].Create();
@@ -104,7 +106,7 @@ RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo
104 } 106 }
105 107
106 ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported"); 108 ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported");
107 109 OpenGLState::ApplyDefaultState();
108 // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0 110 // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0
109 state.clip_distance[0] = true; 111 state.clip_distance[0] = true;
110 112
@@ -115,8 +117,6 @@ RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo
115 state.draw.shader_program = 0; 117 state.draw.shader_program = 0;
116 state.Apply(); 118 state.Apply();
117 119
118 glEnable(GL_BLEND);
119
120 glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment); 120 glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
121 121
122 LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!"); 122 LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
@@ -124,18 +124,23 @@ RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo
124 124
125RasterizerOpenGL::~RasterizerOpenGL() {} 125RasterizerOpenGL::~RasterizerOpenGL() {}
126 126
127void RasterizerOpenGL::SetupVertexArrays() { 127void RasterizerOpenGL::SetupVertexFormat() {
128 MICROPROFILE_SCOPE(OpenGL_VAO); 128 auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
129 const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
130 const auto& regs = gpu.regs; 129 const auto& regs = gpu.regs;
131 130
131 if (!gpu.dirty_flags.vertex_attrib_format)
132 return;
133 gpu.dirty_flags.vertex_attrib_format = false;
134
135 MICROPROFILE_SCOPE(OpenGL_VAO);
136
132 auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format); 137 auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
133 auto& VAO = iter->second; 138 auto& VAO = iter->second;
134 139
135 if (is_cache_miss) { 140 if (is_cache_miss) {
136 VAO.Create(); 141 VAO.Create();
137 state.draw.vertex_array = VAO.handle; 142 state.draw.vertex_array = VAO.handle;
138 state.Apply(); 143 state.ApplyVertexBufferState();
139 144
140 // The index buffer binding is stored within the VAO. Stupid OpenGL, but easy to work 145 // The index buffer binding is stored within the VAO. Stupid OpenGL, but easy to work
141 // around. 146 // around.
@@ -177,8 +182,13 @@ void RasterizerOpenGL::SetupVertexArrays() {
177 } 182 }
178 } 183 }
179 state.draw.vertex_array = VAO.handle; 184 state.draw.vertex_array = VAO.handle;
180 state.draw.vertex_buffer = buffer_cache.GetHandle(); 185 state.ApplyVertexBufferState();
181 state.Apply(); 186}
187
188void RasterizerOpenGL::SetupVertexBuffer() {
189 MICROPROFILE_SCOPE(OpenGL_VB);
190 const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
191 const auto& regs = gpu.regs;
182 192
183 // Upload all guest vertex arrays sequentially to our buffer 193 // Upload all guest vertex arrays sequentially to our buffer
184 for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) { 194 for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
@@ -205,6 +215,9 @@ void RasterizerOpenGL::SetupVertexArrays() {
205 glVertexBindingDivisor(index, 0); 215 glVertexBindingDivisor(index, 0);
206 } 216 }
207 } 217 }
218
219 // Implicit set by glBindVertexBuffer. Stupid glstate handling...
220 state.draw.vertex_buffer = buffer_cache.GetHandle();
208} 221}
209 222
210DrawParameters RasterizerOpenGL::SetupDraw() { 223DrawParameters RasterizerOpenGL::SetupDraw() {
@@ -329,8 +342,6 @@ void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
329 index++; 342 index++;
330 } 343 }
331 } 344 }
332
333 state.Apply();
334} 345}
335 346
336std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const { 347std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
@@ -399,9 +410,9 @@ void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
399 cached_pages.add({pages_interval, delta}); 410 cached_pages.add({pages_interval, delta});
400} 411}
401 412
402void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_depth_fb, 413void RasterizerOpenGL::ConfigureFramebuffers(OpenGLState& current_state, bool using_color_fb,
403 bool preserve_contents, 414 bool using_depth_fb, bool preserve_contents,
404 boost::optional<std::size_t> single_color_target) { 415 std::optional<std::size_t> single_color_target) {
405 MICROPROFILE_SCOPE(OpenGL_Framebuffer); 416 MICROPROFILE_SCOPE(OpenGL_Framebuffer);
406 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs; 417 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
407 418
@@ -416,9 +427,9 @@ void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_dep
416 ASSERT_MSG(regs.rt_separate_frag_data == 0, "Unimplemented"); 427 ASSERT_MSG(regs.rt_separate_frag_data == 0, "Unimplemented");
417 428
418 // Bind the framebuffer surfaces 429 // Bind the framebuffer surfaces
419 state.draw.draw_framebuffer = framebuffer.handle; 430 current_state.draw.draw_framebuffer = framebuffer.handle;
420 state.Apply(); 431 current_state.ApplyFramebufferState();
421 state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0; 432 current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
422 433
423 if (using_color_fb) { 434 if (using_color_fb) {
424 if (single_color_target) { 435 if (single_color_target) {
@@ -496,10 +507,7 @@ void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_dep
496 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 507 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
497 0); 508 0);
498 } 509 }
499 510 SyncViewport(current_state);
500 SyncViewport();
501
502 state.Apply();
503} 511}
504 512
505void RasterizerOpenGL::Clear() { 513void RasterizerOpenGL::Clear() {
@@ -512,22 +520,23 @@ void RasterizerOpenGL::Clear() {
512 bool use_stencil{}; 520 bool use_stencil{};
513 521
514 OpenGLState clear_state; 522 OpenGLState clear_state;
515 clear_state.draw.draw_framebuffer = framebuffer.handle;
516 clear_state.color_mask.red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
517 clear_state.color_mask.green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
518 clear_state.color_mask.blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
519 clear_state.color_mask.alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
520
521 if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B || 523 if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
522 regs.clear_buffers.A) { 524 regs.clear_buffers.A) {
523 use_color = true; 525 use_color = true;
524 } 526 }
527 if (use_color) {
528 clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
529 clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
530 clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
531 clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
532 }
525 if (regs.clear_buffers.Z) { 533 if (regs.clear_buffers.Z) {
526 ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!"); 534 ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
527 use_depth = true; 535 use_depth = true;
528 536
529 // Always enable the depth write when clearing the depth buffer. The depth write mask is 537 // Always enable the depth write when clearing the depth buffer. The depth write mask is
530 // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to true. 538 // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
539 // true.
531 clear_state.depth.test_enabled = true; 540 clear_state.depth.test_enabled = true;
532 clear_state.depth.test_func = GL_ALWAYS; 541 clear_state.depth.test_func = GL_ALWAYS;
533 } 542 }
@@ -544,11 +553,8 @@ void RasterizerOpenGL::Clear() {
544 553
545 ScopeAcquireGLContext acquire_context{emu_window}; 554 ScopeAcquireGLContext acquire_context{emu_window};
546 555
547 ConfigureFramebuffers(use_color, use_depth || use_stencil, false, 556 ConfigureFramebuffers(clear_state, use_color, use_depth || use_stencil, false,
548 regs.clear_buffers.RT.Value()); 557 regs.clear_buffers.RT.Value());
549 // Copy the sRGB setting to the clear state to avoid problem with
550 // specific driver implementations
551 clear_state.framebuffer_srgb.enabled = state.framebuffer_srgb.enabled;
552 clear_state.Apply(); 558 clear_state.Apply();
553 559
554 if (use_color) { 560 if (use_color) {
@@ -574,15 +580,14 @@ void RasterizerOpenGL::DrawArrays() {
574 580
575 ScopeAcquireGLContext acquire_context{emu_window}; 581 ScopeAcquireGLContext acquire_context{emu_window};
576 582
577 ConfigureFramebuffers(); 583 ConfigureFramebuffers(state);
578 584 SyncColorMask();
579 SyncDepthTestState(); 585 SyncDepthTestState();
580 SyncStencilTestState(); 586 SyncStencilTestState();
581 SyncBlendState(); 587 SyncBlendState();
582 SyncLogicOpState(); 588 SyncLogicOpState();
583 SyncCullMode(); 589 SyncCullMode();
584 SyncPrimitiveRestart(); 590 SyncPrimitiveRestart();
585 SyncDepthRange();
586 SyncScissorTest(); 591 SyncScissorTest();
587 // Alpha Testing is synced on shaders. 592 // Alpha Testing is synced on shaders.
588 SyncTransformFeedback(); 593 SyncTransformFeedback();
@@ -596,7 +601,7 @@ void RasterizerOpenGL::DrawArrays() {
596 const bool is_indexed = accelerate_draw == AccelDraw::Indexed; 601 const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
597 602
598 state.draw.vertex_buffer = buffer_cache.GetHandle(); 603 state.draw.vertex_buffer = buffer_cache.GetHandle();
599 state.Apply(); 604 state.ApplyVertexBufferState();
600 605
601 std::size_t buffer_size = CalculateVertexArraysSize(); 606 std::size_t buffer_size = CalculateVertexArraysSize();
602 607
@@ -623,7 +628,8 @@ void RasterizerOpenGL::DrawArrays() {
623 628
624 buffer_cache.Map(buffer_size); 629 buffer_cache.Map(buffer_size);
625 630
626 SetupVertexArrays(); 631 SetupVertexFormat();
632 SetupVertexBuffer();
627 DrawParameters params = SetupDraw(); 633 DrawParameters params = SetupDraw();
628 SetupShaders(params.primitive_mode); 634 SetupShaders(params.primitive_mode);
629 635
@@ -703,7 +709,8 @@ bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
703 709
704 // Verify that the cached surface is the same size and format as the requested framebuffer 710 // Verify that the cached surface is the same size and format as the requested framebuffer
705 const auto& params{surface->GetSurfaceParams()}; 711 const auto& params{surface->GetSurfaceParams()};
706 const auto& pixel_format{SurfaceParams::PixelFormatFromGPUPixelFormat(config.pixel_format)}; 712 const auto& pixel_format{
713 VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
707 ASSERT_MSG(params.width == config.width, "Framebuffer width is different"); 714 ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
708 ASSERT_MSG(params.height == config.height, "Framebuffer height is different"); 715 ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
709 ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different"); 716 ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different");
@@ -726,16 +733,20 @@ void RasterizerOpenGL::SamplerInfo::Create() {
726 glSamplerParameteri(sampler.handle, GL_TEXTURE_COMPARE_FUNC, GL_NEVER); 733 glSamplerParameteri(sampler.handle, GL_TEXTURE_COMPARE_FUNC, GL_NEVER);
727} 734}
728 735
729void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) { 736void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::FullTextureInfo& info) {
730 const GLuint s = sampler.handle; 737 const GLuint s = sampler.handle;
731 738 const Tegra::Texture::TSCEntry& config = info.tsc;
732 if (mag_filter != config.mag_filter) { 739 if (mag_filter != config.mag_filter) {
733 mag_filter = config.mag_filter; 740 mag_filter = config.mag_filter;
734 glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, MaxwellToGL::TextureFilterMode(mag_filter)); 741 glSamplerParameteri(
742 s, GL_TEXTURE_MAG_FILTER,
743 MaxwellToGL::TextureFilterMode(mag_filter, Tegra::Texture::TextureMipmapFilter::None));
735 } 744 }
736 if (min_filter != config.min_filter) { 745 if (min_filter != config.min_filter || mip_filter != config.mip_filter) {
737 min_filter = config.min_filter; 746 min_filter = config.min_filter;
738 glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, MaxwellToGL::TextureFilterMode(min_filter)); 747 mip_filter = config.mip_filter;
748 glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER,
749 MaxwellToGL::TextureFilterMode(min_filter, mip_filter));
739 } 750 }
740 751
741 if (wrap_u != config.wrap_u) { 752 if (wrap_u != config.wrap_u) {
@@ -775,6 +786,22 @@ void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntr
775 glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data()); 786 glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
776 } 787 }
777 } 788 }
789 if (info.tic.use_header_opt_control == 0) {
790 if (GLAD_GL_ARB_texture_filter_anisotropic) {
791 glSamplerParameterf(s, GL_TEXTURE_MAX_ANISOTROPY,
792 static_cast<float>(1 << info.tic.max_anisotropy.Value()));
793 } else if (GLAD_GL_EXT_texture_filter_anisotropic) {
794 glSamplerParameterf(s, GL_TEXTURE_MAX_ANISOTROPY_EXT,
795 static_cast<float>(1 << info.tic.max_anisotropy.Value()));
796 }
797 glSamplerParameterf(s, GL_TEXTURE_MIN_LOD,
798 static_cast<float>(info.tic.res_min_mip_level.Value()));
799 glSamplerParameterf(s, GL_TEXTURE_MAX_LOD,
800 static_cast<float>(info.tic.res_max_mip_level.Value() == 0
801 ? 16
802 : info.tic.res_max_mip_level.Value()));
803 glSamplerParameterf(s, GL_TEXTURE_LOD_BIAS, info.tic.mip_lod_bias.Value() / 256.f);
804 }
778} 805}
779 806
780u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader, 807u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
@@ -872,7 +899,7 @@ u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
872 continue; 899 continue;
873 } 900 }
874 901
875 texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc); 902 texture_samplers[current_bindpoint].SyncWithConfig(texture);
876 Surface surface = res_cache.GetTextureSurface(texture, entry); 903 Surface surface = res_cache.GetTextureSurface(texture, entry);
877 if (surface != nullptr) { 904 if (surface != nullptr) {
878 state.texture_units[current_bindpoint].texture = surface->Texture().handle; 905 state.texture_units[current_bindpoint].texture = surface->Texture().handle;
@@ -894,14 +921,18 @@ u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
894 return current_unit + static_cast<u32>(entries.size()); 921 return current_unit + static_cast<u32>(entries.size());
895} 922}
896 923
897void RasterizerOpenGL::SyncViewport() { 924void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
898 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs; 925 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
899 const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()}; 926 for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
900 927 const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
901 state.viewport.x = viewport_rect.left; 928 auto& viewport = current_state.viewports[i];
902 state.viewport.y = viewport_rect.bottom; 929 viewport.x = viewport_rect.left;
903 state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth()); 930 viewport.y = viewport_rect.bottom;
904 state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight()); 931 viewport.width = static_cast<GLfloat>(viewport_rect.GetWidth());
932 viewport.height = static_cast<GLfloat>(viewport_rect.GetHeight());
933 viewport.depth_range_far = regs.viewport[i].depth_range_far;
934 viewport.depth_range_near = regs.viewport[i].depth_range_near;
935 }
905} 936}
906 937
907void RasterizerOpenGL::SyncClipEnabled() { 938void RasterizerOpenGL::SyncClipEnabled() {
@@ -943,13 +974,6 @@ void RasterizerOpenGL::SyncPrimitiveRestart() {
943 state.primitive_restart.index = regs.primitive_restart.index; 974 state.primitive_restart.index = regs.primitive_restart.index;
944} 975}
945 976
946void RasterizerOpenGL::SyncDepthRange() {
947 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
948
949 state.depth.depth_range_near = regs.viewport->depth_range_near;
950 state.depth.depth_range_far = regs.viewport->depth_range_far;
951}
952
953void RasterizerOpenGL::SyncDepthTestState() { 977void RasterizerOpenGL::SyncDepthTestState() {
954 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs; 978 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
955 979
@@ -970,9 +994,6 @@ void RasterizerOpenGL::SyncStencilTestState() {
970 return; 994 return;
971 } 995 }
972 996
973 // TODO(bunnei): Verify behavior when this is not set
974 ASSERT(regs.stencil_two_side_enable);
975
976 state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func); 997 state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
977 state.stencil.front.test_ref = regs.stencil_front_func_ref; 998 state.stencil.front.test_ref = regs.stencil_front_func_ref;
978 state.stencil.front.test_mask = regs.stencil_front_func_mask; 999 state.stencil.front.test_mask = regs.stencil_front_func_mask;
@@ -980,36 +1001,79 @@ void RasterizerOpenGL::SyncStencilTestState() {
980 state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail); 1001 state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
981 state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass); 1002 state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
982 state.stencil.front.write_mask = regs.stencil_front_mask; 1003 state.stencil.front.write_mask = regs.stencil_front_mask;
1004 if (regs.stencil_two_side_enable) {
1005 state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
1006 state.stencil.back.test_ref = regs.stencil_back_func_ref;
1007 state.stencil.back.test_mask = regs.stencil_back_func_mask;
1008 state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
1009 state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
1010 state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
1011 state.stencil.back.write_mask = regs.stencil_back_mask;
1012 } else {
1013 state.stencil.back.test_func = GL_ALWAYS;
1014 state.stencil.back.test_ref = 0;
1015 state.stencil.back.test_mask = 0xFFFFFFFF;
1016 state.stencil.back.write_mask = 0xFFFFFFFF;
1017 state.stencil.back.action_stencil_fail = GL_KEEP;
1018 state.stencil.back.action_depth_fail = GL_KEEP;
1019 state.stencil.back.action_depth_pass = GL_KEEP;
1020 }
1021}
983 1022
984 state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func); 1023void RasterizerOpenGL::SyncColorMask() {
985 state.stencil.back.test_ref = regs.stencil_back_func_ref; 1024 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
986 state.stencil.back.test_mask = regs.stencil_back_func_mask; 1025 for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
987 state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail); 1026 const auto& source = regs.color_mask[regs.color_mask_common ? 0 : i];
988 state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail); 1027 auto& dest = state.color_mask[i];
989 state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass); 1028 dest.red_enabled = (source.R == 0) ? GL_FALSE : GL_TRUE;
990 state.stencil.back.write_mask = regs.stencil_back_mask; 1029 dest.green_enabled = (source.G == 0) ? GL_FALSE : GL_TRUE;
1030 dest.blue_enabled = (source.B == 0) ? GL_FALSE : GL_TRUE;
1031 dest.alpha_enabled = (source.A == 0) ? GL_FALSE : GL_TRUE;
1032 }
991} 1033}
992 1034
993void RasterizerOpenGL::SyncBlendState() { 1035void RasterizerOpenGL::SyncBlendState() {
994 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs; 1036 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
995 1037
996 // TODO(Subv): Support more than just render target 0. 1038 state.blend_color.red = regs.blend_color.r;
997 state.blend.enabled = regs.blend.enable[0] != 0; 1039 state.blend_color.green = regs.blend_color.g;
998 1040 state.blend_color.blue = regs.blend_color.b;
999 if (!state.blend.enabled) 1041 state.blend_color.alpha = regs.blend_color.a;
1042
1043 state.independant_blend.enabled = regs.independent_blend_enable;
1044 if (!state.independant_blend.enabled) {
1045 auto& blend = state.blend[0];
1046 blend.enabled = regs.blend.enable[0] != 0;
1047 blend.separate_alpha = regs.blend.separate_alpha;
1048 blend.rgb_equation = MaxwellToGL::BlendEquation(regs.blend.equation_rgb);
1049 blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.blend.factor_source_rgb);
1050 blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.blend.factor_dest_rgb);
1051 if (blend.separate_alpha) {
1052 blend.a_equation = MaxwellToGL::BlendEquation(regs.blend.equation_a);
1053 blend.src_a_func = MaxwellToGL::BlendFunc(regs.blend.factor_source_a);
1054 blend.dst_a_func = MaxwellToGL::BlendFunc(regs.blend.factor_dest_a);
1055 }
1056 for (size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
1057 state.blend[i].enabled = false;
1058 }
1000 return; 1059 return;
1060 }
1001 1061
1002 ASSERT_MSG(regs.logic_op.enable == 0, 1062 for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
1003 "Blending and logic op can't be enabled at the same time."); 1063 auto& blend = state.blend[i];
1004 1064 blend.enabled = regs.blend.enable[i] != 0;
1005 ASSERT_MSG(regs.independent_blend_enable == 1, "Only independent blending is implemented"); 1065 if (!blend.enabled)
1006 ASSERT_MSG(!regs.independent_blend[0].separate_alpha, "Unimplemented"); 1066 continue;
1007 state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_rgb); 1067 blend.separate_alpha = regs.independent_blend[i].separate_alpha;
1008 state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_rgb); 1068 blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[i].equation_rgb);
1009 state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_rgb); 1069 blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[i].factor_source_rgb);
1010 state.blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_a); 1070 blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[i].factor_dest_rgb);
1011 state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_a); 1071 if (blend.separate_alpha) {
1012 state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_a); 1072 blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[i].equation_a);
1073 blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[i].factor_source_a);
1074 blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[i].factor_dest_a);
1075 }
1076 }
1013} 1077}
1014 1078
1015void RasterizerOpenGL::SyncLogicOpState() { 1079void RasterizerOpenGL::SyncLogicOpState() {
@@ -1028,19 +1092,19 @@ void RasterizerOpenGL::SyncLogicOpState() {
1028} 1092}
1029 1093
1030void RasterizerOpenGL::SyncScissorTest() { 1094void RasterizerOpenGL::SyncScissorTest() {
1095 // TODO: what is the correct behavior here, a single scissor for all targets
1096 // or scissor disabled for the rest of the targets?
1031 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs; 1097 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
1032
1033 state.scissor.enabled = (regs.scissor_test.enable != 0); 1098 state.scissor.enabled = (regs.scissor_test.enable != 0);
1034 // TODO(Blinkhawk): Figure if the hardware supports scissor testing per viewport and how it's 1099 if (regs.scissor_test.enable == 0) {
1035 // implemented. 1100 return;
1036 if (regs.scissor_test.enable != 0) {
1037 const u32 width = regs.scissor_test.max_x - regs.scissor_test.min_x;
1038 const u32 height = regs.scissor_test.max_y - regs.scissor_test.min_y;
1039 state.scissor.x = regs.scissor_test.min_x;
1040 state.scissor.y = regs.scissor_test.min_y;
1041 state.scissor.width = width;
1042 state.scissor.height = height;
1043 } 1101 }
1102 const u32 width = regs.scissor_test.max_x - regs.scissor_test.min_x;
1103 const u32 height = regs.scissor_test.max_y - regs.scissor_test.min_y;
1104 state.scissor.x = regs.scissor_test.min_x;
1105 state.scissor.y = regs.scissor_test.min_y;
1106 state.scissor.width = width;
1107 state.scissor.height = height;
1044} 1108}
1045 1109
1046void RasterizerOpenGL::SyncTransformFeedback() { 1110void RasterizerOpenGL::SyncTransformFeedback() {
@@ -1065,9 +1129,8 @@ void RasterizerOpenGL::CheckAlphaTests() {
1065 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs; 1129 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
1066 1130
1067 if (regs.alpha_test_enabled != 0 && regs.rt_control.count > 1) { 1131 if (regs.alpha_test_enabled != 0 && regs.rt_control.count > 1) {
1068 LOG_CRITICAL( 1132 LOG_CRITICAL(Render_OpenGL, "Alpha Testing is enabled with Multiple Render Targets, "
1069 Render_OpenGL, 1133 "this behavior is undefined.");
1070 "Alpha Testing is enabled with Multiple Render Targets, this behavior is undefined.");
1071 UNREACHABLE(); 1134 UNREACHABLE();
1072 } 1135 }
1073} 1136}
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index 5020a5392..8ef0f6c12 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -8,12 +8,12 @@
8#include <cstddef> 8#include <cstddef>
9#include <map> 9#include <map>
10#include <memory> 10#include <memory>
11#include <optional>
11#include <tuple> 12#include <tuple>
12#include <utility> 13#include <utility>
13#include <vector> 14#include <vector>
14 15
15#include <boost/icl/interval_map.hpp> 16#include <boost/icl/interval_map.hpp>
16#include <boost/optional.hpp>
17#include <boost/range/iterator_range.hpp> 17#include <boost/range/iterator_range.hpp>
18#include <glad/glad.h> 18#include <glad/glad.h>
19 19
@@ -88,11 +88,12 @@ private:
88 /// SamplerInfo struct. 88 /// SamplerInfo struct.
89 void Create(); 89 void Create();
90 /// Syncs the sampler object with the config, updating any necessary state. 90 /// Syncs the sampler object with the config, updating any necessary state.
91 void SyncWithConfig(const Tegra::Texture::TSCEntry& config); 91 void SyncWithConfig(const Tegra::Texture::FullTextureInfo& info);
92 92
93 private: 93 private:
94 Tegra::Texture::TextureFilter mag_filter; 94 Tegra::Texture::TextureFilter mag_filter;
95 Tegra::Texture::TextureFilter min_filter; 95 Tegra::Texture::TextureFilter min_filter;
96 Tegra::Texture::TextureMipmapFilter mip_filter;
96 Tegra::Texture::WrapMode wrap_u; 97 Tegra::Texture::WrapMode wrap_u;
97 Tegra::Texture::WrapMode wrap_v; 98 Tegra::Texture::WrapMode wrap_v;
98 Tegra::Texture::WrapMode wrap_p; 99 Tegra::Texture::WrapMode wrap_p;
@@ -108,9 +109,9 @@ private:
108 * @param preserve_contents If true, tries to preserve data from a previously used framebuffer. 109 * @param preserve_contents If true, tries to preserve data from a previously used framebuffer.
109 * @param single_color_target Specifies if a single color buffer target should be used. 110 * @param single_color_target Specifies if a single color buffer target should be used.
110 */ 111 */
111 void ConfigureFramebuffers(bool use_color_fb = true, bool using_depth_fb = true, 112 void ConfigureFramebuffers(OpenGLState& current_state, bool use_color_fb = true,
112 bool preserve_contents = true, 113 bool using_depth_fb = true, bool preserve_contents = true,
113 boost::optional<std::size_t> single_color_target = {}); 114 std::optional<std::size_t> single_color_target = {});
114 115
115 /* 116 /*
116 * Configures the current constbuffers to use for the draw command. 117 * Configures the current constbuffers to use for the draw command.
@@ -132,8 +133,8 @@ private:
132 u32 SetupTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader, 133 u32 SetupTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader,
133 GLenum primitive_mode, u32 current_unit); 134 GLenum primitive_mode, u32 current_unit);
134 135
135 /// Syncs the viewport to match the guest state 136 /// Syncs the viewport and depth range to match the guest state
136 void SyncViewport(); 137 void SyncViewport(OpenGLState& current_state);
137 138
138 /// Syncs the clip enabled status to match the guest state 139 /// Syncs the clip enabled status to match the guest state
139 void SyncClipEnabled(); 140 void SyncClipEnabled();
@@ -147,9 +148,6 @@ private:
147 /// Syncs the primitve restart to match the guest state 148 /// Syncs the primitve restart to match the guest state
148 void SyncPrimitiveRestart(); 149 void SyncPrimitiveRestart();
149 150
150 /// Syncs the depth range to match the guest state
151 void SyncDepthRange();
152
153 /// Syncs the depth test state to match the guest state 151 /// Syncs the depth test state to match the guest state
154 void SyncDepthTestState(); 152 void SyncDepthTestState();
155 153
@@ -171,6 +169,9 @@ private:
171 /// Syncs the point state to match the guest state 169 /// Syncs the point state to match the guest state
172 void SyncPointState(); 170 void SyncPointState();
173 171
172 /// Syncs Color Mask
173 void SyncColorMask();
174
174 /// Check asserts for alpha testing. 175 /// Check asserts for alpha testing.
175 void CheckAlphaTests(); 176 void CheckAlphaTests();
176 177
@@ -206,7 +207,8 @@ private:
206 207
207 std::size_t CalculateIndexBufferSize() const; 208 std::size_t CalculateIndexBufferSize() const;
208 209
209 void SetupVertexArrays(); 210 void SetupVertexFormat();
211 void SetupVertexBuffer();
210 212
211 DrawParameters SetupDraw(); 213 DrawParameters SetupDraw();
212 214
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
index 30c2803f5..26711e6f7 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
@@ -15,17 +15,24 @@
15#include "core/memory.h" 15#include "core/memory.h"
16#include "core/settings.h" 16#include "core/settings.h"
17#include "video_core/engines/maxwell_3d.h" 17#include "video_core/engines/maxwell_3d.h"
18#include "video_core/renderer_opengl/gl_rasterizer.h"
18#include "video_core/renderer_opengl/gl_rasterizer_cache.h" 19#include "video_core/renderer_opengl/gl_rasterizer_cache.h"
20#include "video_core/renderer_opengl/gl_state.h"
19#include "video_core/renderer_opengl/utils.h" 21#include "video_core/renderer_opengl/utils.h"
22#include "video_core/surface.h"
20#include "video_core/textures/astc.h" 23#include "video_core/textures/astc.h"
21#include "video_core/textures/decoders.h" 24#include "video_core/textures/decoders.h"
22#include "video_core/utils.h" 25#include "video_core/utils.h"
23 26
24namespace OpenGL { 27namespace OpenGL {
25 28
26using SurfaceType = SurfaceParams::SurfaceType; 29using VideoCore::Surface::ComponentTypeFromDepthFormat;
27using PixelFormat = SurfaceParams::PixelFormat; 30using VideoCore::Surface::ComponentTypeFromRenderTarget;
28using ComponentType = SurfaceParams::ComponentType; 31using VideoCore::Surface::ComponentTypeFromTexture;
32using VideoCore::Surface::PixelFormatFromDepthFormat;
33using VideoCore::Surface::PixelFormatFromRenderTargetFormat;
34using VideoCore::Surface::PixelFormatFromTextureFormat;
35using VideoCore::Surface::SurfaceTargetFromTextureType;
29 36
30struct FormatTuple { 37struct FormatTuple {
31 GLint internal_format; 38 GLint internal_format;
@@ -35,46 +42,6 @@ struct FormatTuple {
35 bool compressed; 42 bool compressed;
36}; 43};
37 44
38static bool IsPixelFormatASTC(PixelFormat format) {
39 switch (format) {
40 case PixelFormat::ASTC_2D_4X4:
41 case PixelFormat::ASTC_2D_5X4:
42 case PixelFormat::ASTC_2D_8X8:
43 case PixelFormat::ASTC_2D_8X5:
44 case PixelFormat::ASTC_2D_4X4_SRGB:
45 case PixelFormat::ASTC_2D_5X4_SRGB:
46 case PixelFormat::ASTC_2D_8X8_SRGB:
47 case PixelFormat::ASTC_2D_8X5_SRGB:
48 return true;
49 default:
50 return false;
51 }
52}
53
54static std::pair<u32, u32> GetASTCBlockSize(PixelFormat format) {
55 switch (format) {
56 case PixelFormat::ASTC_2D_4X4:
57 return {4, 4};
58 case PixelFormat::ASTC_2D_5X4:
59 return {5, 4};
60 case PixelFormat::ASTC_2D_8X8:
61 return {8, 8};
62 case PixelFormat::ASTC_2D_8X5:
63 return {8, 5};
64 case PixelFormat::ASTC_2D_4X4_SRGB:
65 return {4, 4};
66 case PixelFormat::ASTC_2D_5X4_SRGB:
67 return {5, 4};
68 case PixelFormat::ASTC_2D_8X8_SRGB:
69 return {8, 8};
70 case PixelFormat::ASTC_2D_8X5_SRGB:
71 return {8, 5};
72 default:
73 LOG_CRITICAL(HW_GPU, "Unhandled format: {}", static_cast<u32>(format));
74 UNREACHABLE();
75 }
76}
77
78void SurfaceParams::InitCacheParameters(Tegra::GPUVAddr gpu_addr_) { 45void SurfaceParams::InitCacheParameters(Tegra::GPUVAddr gpu_addr_) {
79 auto& memory_manager{Core::System::GetInstance().GPU().MemoryManager()}; 46 auto& memory_manager{Core::System::GetInstance().GPU().MemoryManager()};
80 const auto cpu_addr{memory_manager.GpuToCpuAddress(gpu_addr_)}; 47 const auto cpu_addr{memory_manager.GpuToCpuAddress(gpu_addr_)};
@@ -91,27 +58,34 @@ void SurfaceParams::InitCacheParameters(Tegra::GPUVAddr gpu_addr_) {
91 } 58 }
92} 59}
93 60
94std::size_t SurfaceParams::InnerMemorySize(bool layer_only) const { 61std::size_t SurfaceParams::InnerMipmapMemorySize(u32 mip_level, bool force_gl, bool layer_only,
95 const u32 compression_factor{GetCompressionFactor(pixel_format)}; 62 bool uncompressed) const {
63 const u32 tile_x{GetDefaultBlockWidth(pixel_format)};
64 const u32 tile_y{GetDefaultBlockHeight(pixel_format)};
96 const u32 bytes_per_pixel{GetBytesPerPixel(pixel_format)}; 65 const u32 bytes_per_pixel{GetBytesPerPixel(pixel_format)};
97 u32 m_depth = (layer_only ? 1U : depth); 66 u32 m_depth = (layer_only ? 1U : depth);
98 u32 m_width = std::max(1U, width / compression_factor); 67 u32 m_width = MipWidth(mip_level);
99 u32 m_height = std::max(1U, height / compression_factor); 68 u32 m_height = MipHeight(mip_level);
100 std::size_t size = Tegra::Texture::CalculateSize(is_tiled, bytes_per_pixel, m_width, m_height, 69 m_width = uncompressed ? m_width : std::max(1U, (m_width + tile_x - 1) / tile_x);
101 m_depth, block_height, block_depth); 70 m_height = uncompressed ? m_height : std::max(1U, (m_height + tile_y - 1) / tile_y);
102 u32 m_block_height = block_height; 71 m_depth = std::max(1U, m_depth >> mip_level);
103 u32 m_block_depth = block_depth; 72 u32 m_block_height = MipBlockHeight(mip_level);
104 std::size_t block_size_bytes = 512 * block_height * block_depth; // 512 is GOB size 73 u32 m_block_depth = MipBlockDepth(mip_level);
105 for (u32 i = 1; i < max_mip_level; i++) { 74 return Tegra::Texture::CalculateSize(force_gl ? false : is_tiled, bytes_per_pixel, m_width,
106 m_width = std::max(1U, m_width / 2); 75 m_height, m_depth, m_block_height, m_block_depth);
107 m_height = std::max(1U, m_height / 2); 76}
108 m_depth = std::max(1U, m_depth / 2); 77
109 m_block_height = std::max(1U, m_block_height / 2); 78std::size_t SurfaceParams::InnerMemorySize(bool force_gl, bool layer_only,
110 m_block_depth = std::max(1U, m_block_depth / 2); 79 bool uncompressed) const {
111 size += Tegra::Texture::CalculateSize(is_tiled, bytes_per_pixel, m_width, m_height, m_depth, 80 std::size_t block_size_bytes = Tegra::Texture::GetGOBSize() * block_height * block_depth;
112 m_block_height, m_block_depth); 81 std::size_t size = 0;
82 for (u32 i = 0; i < max_mip_level; i++) {
83 size += InnerMipmapMemorySize(i, force_gl, layer_only, uncompressed);
84 }
85 if (!force_gl && is_tiled) {
86 size = Common::AlignUp(size, block_size_bytes);
113 } 87 }
114 return is_tiled ? Common::AlignUp(size, block_size_bytes) : size; 88 return size;
115} 89}
116 90
117/*static*/ SurfaceParams SurfaceParams::CreateForTexture( 91/*static*/ SurfaceParams SurfaceParams::CreateForTexture(
@@ -154,6 +128,13 @@ std::size_t SurfaceParams::InnerMemorySize(bool layer_only) const {
154 params.target = SurfaceTarget::Texture2D; 128 params.target = SurfaceTarget::Texture2D;
155 } 129 }
156 break; 130 break;
131 case SurfaceTarget::TextureCubeArray:
132 params.depth = config.tic.Depth() * 6;
133 if (!entry.IsArray()) {
134 ASSERT(params.depth == 6);
135 params.target = SurfaceTarget::TextureCubemap;
136 }
137 break;
157 default: 138 default:
158 LOG_CRITICAL(HW_GPU, "Unknown depth for target={}", static_cast<u32>(params.target)); 139 LOG_CRITICAL(HW_GPU, "Unknown depth for target={}", static_cast<u32>(params.target));
159 UNREACHABLE(); 140 UNREACHABLE();
@@ -189,7 +170,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool layer_only) const {
189 params.unaligned_height = config.height; 170 params.unaligned_height = config.height;
190 params.target = SurfaceTarget::Texture2D; 171 params.target = SurfaceTarget::Texture2D;
191 params.depth = 1; 172 params.depth = 1;
192 params.max_mip_level = 0; 173 params.max_mip_level = 1;
193 params.is_layered = false; 174 params.is_layered = false;
194 175
195 // Render target specific parameters, not used for caching 176 // Render target specific parameters, not used for caching
@@ -223,7 +204,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool layer_only) const {
223 params.unaligned_height = zeta_height; 204 params.unaligned_height = zeta_height;
224 params.target = SurfaceTarget::Texture2D; 205 params.target = SurfaceTarget::Texture2D;
225 params.depth = 1; 206 params.depth = 1;
226 params.max_mip_level = 0; 207 params.max_mip_level = 1;
227 params.is_layered = false; 208 params.is_layered = false;
228 params.rt = {}; 209 params.rt = {};
229 210
@@ -250,7 +231,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool layer_only) const {
250 params.unaligned_height = config.height; 231 params.unaligned_height = config.height;
251 params.target = SurfaceTarget::Texture2D; 232 params.target = SurfaceTarget::Texture2D;
252 params.depth = 1; 233 params.depth = 1;
253 params.max_mip_level = 0; 234 params.max_mip_level = 1;
254 params.rt = {}; 235 params.rt = {};
255 236
256 params.InitCacheParameters(config.Address()); 237 params.InitCacheParameters(config.Address());
@@ -258,7 +239,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool layer_only) const {
258 return params; 239 return params;
259} 240}
260 241
261static constexpr std::array<FormatTuple, SurfaceParams::MaxPixelFormat> tex_format_tuples = {{ 242static constexpr std::array<FormatTuple, VideoCore::Surface::MaxPixelFormat> tex_format_tuples = {{
262 {GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, ComponentType::UNorm, false}, // ABGR8U 243 {GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, ComponentType::UNorm, false}, // ABGR8U
263 {GL_RGBA8, GL_RGBA, GL_BYTE, ComponentType::SNorm, false}, // ABGR8S 244 {GL_RGBA8, GL_RGBA, GL_BYTE, ComponentType::SNorm, false}, // ABGR8S
264 {GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, ComponentType::UInt, false}, // ABGR8UI 245 {GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, ComponentType::UInt, false}, // ABGR8UI
@@ -331,6 +312,10 @@ static constexpr std::array<FormatTuple, SurfaceParams::MaxPixelFormat> tex_form
331 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_8X8_SRGB 312 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_8X8_SRGB
332 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_8X5_SRGB 313 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_8X5_SRGB
333 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_5X4_SRGB 314 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_5X4_SRGB
315 {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_5X5
316 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_5X5_SRGB
317 {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_10X8
318 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_10X8_SRGB
334 319
335 // Depth formats 320 // Depth formats
336 {GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, ComponentType::Float, false}, // Z32F 321 {GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, ComponentType::Float, false}, // Z32F
@@ -346,20 +331,22 @@ static constexpr std::array<FormatTuple, SurfaceParams::MaxPixelFormat> tex_form
346 ComponentType::Float, false}, // Z32FS8 331 ComponentType::Float, false}, // Z32FS8
347}}; 332}};
348 333
349static GLenum SurfaceTargetToGL(SurfaceParams::SurfaceTarget target) { 334static GLenum SurfaceTargetToGL(SurfaceTarget target) {
350 switch (target) { 335 switch (target) {
351 case SurfaceParams::SurfaceTarget::Texture1D: 336 case SurfaceTarget::Texture1D:
352 return GL_TEXTURE_1D; 337 return GL_TEXTURE_1D;
353 case SurfaceParams::SurfaceTarget::Texture2D: 338 case SurfaceTarget::Texture2D:
354 return GL_TEXTURE_2D; 339 return GL_TEXTURE_2D;
355 case SurfaceParams::SurfaceTarget::Texture3D: 340 case SurfaceTarget::Texture3D:
356 return GL_TEXTURE_3D; 341 return GL_TEXTURE_3D;
357 case SurfaceParams::SurfaceTarget::Texture1DArray: 342 case SurfaceTarget::Texture1DArray:
358 return GL_TEXTURE_1D_ARRAY; 343 return GL_TEXTURE_1D_ARRAY;
359 case SurfaceParams::SurfaceTarget::Texture2DArray: 344 case SurfaceTarget::Texture2DArray:
360 return GL_TEXTURE_2D_ARRAY; 345 return GL_TEXTURE_2D_ARRAY;
361 case SurfaceParams::SurfaceTarget::TextureCubemap: 346 case SurfaceTarget::TextureCubemap:
362 return GL_TEXTURE_CUBE_MAP; 347 return GL_TEXTURE_CUBE_MAP;
348 case SurfaceTarget::TextureCubeArray:
349 return GL_TEXTURE_CUBE_MAP_ARRAY_ARB;
363 } 350 }
364 LOG_CRITICAL(Render_OpenGL, "Unimplemented texture target={}", static_cast<u32>(target)); 351 LOG_CRITICAL(Render_OpenGL, "Unimplemented texture target={}", static_cast<u32>(target));
365 UNREACHABLE(); 352 UNREACHABLE();
@@ -374,59 +361,41 @@ static const FormatTuple& GetFormatTuple(PixelFormat pixel_format, ComponentType
374 return format; 361 return format;
375} 362}
376 363
377MathUtil::Rectangle<u32> SurfaceParams::GetRect() const { 364MathUtil::Rectangle<u32> SurfaceParams::GetRect(u32 mip_level) const {
378 u32 actual_height{unaligned_height}; 365 u32 actual_height{std::max(1U, unaligned_height >> mip_level)};
379 if (IsPixelFormatASTC(pixel_format)) { 366 if (IsPixelFormatASTC(pixel_format)) {
380 // ASTC formats must stop at the ATSC block size boundary 367 // ASTC formats must stop at the ATSC block size boundary
381 actual_height = Common::AlignDown(actual_height, GetASTCBlockSize(pixel_format).second); 368 actual_height = Common::AlignDown(actual_height, GetASTCBlockSize(pixel_format).second);
382 } 369 }
383 return {0, actual_height, width, 0}; 370 return {0, actual_height, MipWidth(mip_level), 0};
384}
385
386/// Returns true if the specified PixelFormat is a BCn format, e.g. DXT or DXN
387static bool IsFormatBCn(PixelFormat format) {
388 switch (format) {
389 case PixelFormat::DXT1:
390 case PixelFormat::DXT23:
391 case PixelFormat::DXT45:
392 case PixelFormat::DXN1:
393 case PixelFormat::DXN2SNORM:
394 case PixelFormat::DXN2UNORM:
395 case PixelFormat::BC7U:
396 case PixelFormat::BC6H_UF16:
397 case PixelFormat::BC6H_SF16:
398 case PixelFormat::DXT1_SRGB:
399 case PixelFormat::DXT23_SRGB:
400 case PixelFormat::DXT45_SRGB:
401 case PixelFormat::BC7U_SRGB:
402 return true;
403 }
404 return false;
405} 371}
406 372
407template <bool morton_to_gl, PixelFormat format> 373template <bool morton_to_gl, PixelFormat format>
408void MortonCopy(u32 stride, u32 block_height, u32 height, u32 block_depth, u32 depth, u8* gl_buffer, 374void MortonCopy(u32 stride, u32 block_height, u32 height, u32 block_depth, u32 depth, u8* gl_buffer,
409 std::size_t gl_buffer_size, VAddr addr) { 375 std::size_t gl_buffer_size, VAddr addr) {
410 constexpr u32 bytes_per_pixel = SurfaceParams::GetBytesPerPixel(format); 376 constexpr u32 bytes_per_pixel = GetBytesPerPixel(format);
411 377
412 // With the BCn formats (DXT and DXN), each 4x4 tile is swizzled instead of just individual 378 // With the BCn formats (DXT and DXN), each 4x4 tile is swizzled instead of just individual
413 // pixel values. 379 // pixel values.
414 const u32 tile_size{IsFormatBCn(format) ? 4U : 1U}; 380 const u32 tile_size_x{GetDefaultBlockWidth(format)};
381 const u32 tile_size_y{GetDefaultBlockHeight(format)};
415 382
416 if (morton_to_gl) { 383 if (morton_to_gl) {
417 const std::vector<u8> data = Tegra::Texture::UnswizzleTexture( 384 const std::vector<u8> data =
418 addr, tile_size, bytes_per_pixel, stride, height, depth, block_height, block_depth); 385 Tegra::Texture::UnswizzleTexture(addr, tile_size_x, tile_size_y, bytes_per_pixel,
386 stride, height, depth, block_height, block_depth);
419 const std::size_t size_to_copy{std::min(gl_buffer_size, data.size())}; 387 const std::size_t size_to_copy{std::min(gl_buffer_size, data.size())};
420 memcpy(gl_buffer, data.data(), size_to_copy); 388 memcpy(gl_buffer, data.data(), size_to_copy);
421 } else { 389 } else {
422 Tegra::Texture::CopySwizzledData(stride / tile_size, height / tile_size, depth, 390 Tegra::Texture::CopySwizzledData((stride + tile_size_x - 1) / tile_size_x,
391 (height + tile_size_y - 1) / tile_size_y, depth,
423 bytes_per_pixel, bytes_per_pixel, Memory::GetPointer(addr), 392 bytes_per_pixel, bytes_per_pixel, Memory::GetPointer(addr),
424 gl_buffer, false, block_height, block_depth); 393 gl_buffer, false, block_height, block_depth);
425 } 394 }
426} 395}
427 396
428using GLConversionArray = std::array<void (*)(u32, u32, u32, u32, u32, u8*, std::size_t, VAddr), 397using GLConversionArray = std::array<void (*)(u32, u32, u32, u32, u32, u8*, std::size_t, VAddr),
429 SurfaceParams::MaxPixelFormat>; 398 VideoCore::Surface::MaxPixelFormat>;
430 399
431static constexpr GLConversionArray morton_to_gl_fns = { 400static constexpr GLConversionArray morton_to_gl_fns = {
432 // clang-format off 401 // clang-format off
@@ -487,6 +456,10 @@ static constexpr GLConversionArray morton_to_gl_fns = {
487 MortonCopy<true, PixelFormat::ASTC_2D_8X8_SRGB>, 456 MortonCopy<true, PixelFormat::ASTC_2D_8X8_SRGB>,
488 MortonCopy<true, PixelFormat::ASTC_2D_8X5_SRGB>, 457 MortonCopy<true, PixelFormat::ASTC_2D_8X5_SRGB>,
489 MortonCopy<true, PixelFormat::ASTC_2D_5X4_SRGB>, 458 MortonCopy<true, PixelFormat::ASTC_2D_5X4_SRGB>,
459 MortonCopy<true, PixelFormat::ASTC_2D_5X5>,
460 MortonCopy<true, PixelFormat::ASTC_2D_5X5_SRGB>,
461 MortonCopy<true, PixelFormat::ASTC_2D_10X8>,
462 MortonCopy<true, PixelFormat::ASTC_2D_10X8_SRGB>,
490 MortonCopy<true, PixelFormat::Z32F>, 463 MortonCopy<true, PixelFormat::Z32F>,
491 MortonCopy<true, PixelFormat::Z16>, 464 MortonCopy<true, PixelFormat::Z16>,
492 MortonCopy<true, PixelFormat::Z24S8>, 465 MortonCopy<true, PixelFormat::Z24S8>,
@@ -555,6 +528,10 @@ static constexpr GLConversionArray gl_to_morton_fns = {
555 nullptr, 528 nullptr,
556 nullptr, 529 nullptr,
557 nullptr, 530 nullptr,
531 nullptr,
532 nullptr,
533 nullptr,
534 nullptr,
558 MortonCopy<false, PixelFormat::Z32F>, 535 MortonCopy<false, PixelFormat::Z32F>,
559 MortonCopy<false, PixelFormat::Z16>, 536 MortonCopy<false, PixelFormat::Z16>,
560 MortonCopy<false, PixelFormat::Z24S8>, 537 MortonCopy<false, PixelFormat::Z24S8>,
@@ -564,34 +541,39 @@ static constexpr GLConversionArray gl_to_morton_fns = {
564}; 541};
565 542
566void SwizzleFunc(const GLConversionArray& functions, const SurfaceParams& params, 543void SwizzleFunc(const GLConversionArray& functions, const SurfaceParams& params,
567 std::vector<u8>& gl_buffer) { 544 std::vector<u8>& gl_buffer, u32 mip_level) {
568 u32 depth = params.depth; 545 u32 depth = params.MipDepth(mip_level);
569 if (params.target == SurfaceParams::SurfaceTarget::Texture2D) { 546 if (params.target == SurfaceTarget::Texture2D) {
570 // TODO(Blinkhawk): Eliminate this condition once all texture types are implemented. 547 // TODO(Blinkhawk): Eliminate this condition once all texture types are implemented.
571 depth = 1U; 548 depth = 1U;
572 } 549 }
573 if (params.is_layered) { 550 if (params.is_layered) {
574 u64 offset = 0; 551 u64 offset = params.GetMipmapLevelOffset(mip_level);
575 u64 offset_gl = 0; 552 u64 offset_gl = 0;
576 u64 layer_size = params.LayerMemorySize(); 553 u64 layer_size = params.LayerMemorySize();
577 u64 gl_size = params.LayerSizeGL(); 554 u64 gl_size = params.LayerSizeGL(mip_level);
578 for (u32 i = 0; i < depth; i++) { 555 for (u32 i = 0; i < params.depth; i++) {
579 functions[static_cast<std::size_t>(params.pixel_format)]( 556 functions[static_cast<std::size_t>(params.pixel_format)](
580 params.width, params.block_height, params.height, params.block_depth, 1, 557 params.MipWidth(mip_level), params.MipBlockHeight(mip_level),
558 params.MipHeight(mip_level), params.MipBlockDepth(mip_level), 1,
581 gl_buffer.data() + offset_gl, gl_size, params.addr + offset); 559 gl_buffer.data() + offset_gl, gl_size, params.addr + offset);
582 offset += layer_size; 560 offset += layer_size;
583 offset_gl += gl_size; 561 offset_gl += gl_size;
584 } 562 }
585 } else { 563 } else {
564 u64 offset = params.GetMipmapLevelOffset(mip_level);
586 functions[static_cast<std::size_t>(params.pixel_format)]( 565 functions[static_cast<std::size_t>(params.pixel_format)](
587 params.width, params.block_height, params.height, params.block_depth, depth, 566 params.MipWidth(mip_level), params.MipBlockHeight(mip_level),
588 gl_buffer.data(), gl_buffer.size(), params.addr); 567 params.MipHeight(mip_level), params.MipBlockDepth(mip_level), depth, gl_buffer.data(),
568 gl_buffer.size(), params.addr + offset);
589 } 569 }
590} 570}
591 571
572MICROPROFILE_DEFINE(OpenGL_BlitSurface, "OpenGL", "BlitSurface", MP_RGB(128, 192, 64));
592static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface, 573static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
593 GLuint read_fb_handle, GLuint draw_fb_handle, GLenum src_attachment = 0, 574 GLuint read_fb_handle, GLuint draw_fb_handle, GLenum src_attachment = 0,
594 GLenum dst_attachment = 0, std::size_t cubemap_face = 0) { 575 GLenum dst_attachment = 0, std::size_t cubemap_face = 0) {
576 MICROPROFILE_SCOPE(OpenGL_BlitSurface);
595 577
596 const auto& src_params{src_surface->GetSurfaceParams()}; 578 const auto& src_params{src_surface->GetSurfaceParams()};
597 const auto& dst_params{dst_surface->GetSurfaceParams()}; 579 const auto& dst_params{dst_surface->GetSurfaceParams()};
@@ -604,19 +586,19 @@ static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
604 state.draw.draw_framebuffer = draw_fb_handle; 586 state.draw.draw_framebuffer = draw_fb_handle;
605 // Set sRGB enabled if the destination surfaces need it 587 // Set sRGB enabled if the destination surfaces need it
606 state.framebuffer_srgb.enabled = dst_params.srgb_conversion; 588 state.framebuffer_srgb.enabled = dst_params.srgb_conversion;
607 state.Apply(); 589 state.ApplyFramebufferState();
608 590
609 u32 buffers{}; 591 u32 buffers{};
610 592
611 if (src_params.type == SurfaceType::ColorTexture) { 593 if (src_params.type == SurfaceType::ColorTexture) {
612 switch (src_params.target) { 594 switch (src_params.target) {
613 case SurfaceParams::SurfaceTarget::Texture2D: 595 case SurfaceTarget::Texture2D:
614 glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment, 596 glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
615 GL_TEXTURE_2D, src_surface->Texture().handle, 0); 597 GL_TEXTURE_2D, src_surface->Texture().handle, 0);
616 glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 598 glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
617 0, 0); 599 0, 0);
618 break; 600 break;
619 case SurfaceParams::SurfaceTarget::TextureCubemap: 601 case SurfaceTarget::TextureCubemap:
620 glFramebufferTexture2D( 602 glFramebufferTexture2D(
621 GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment, 603 GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
622 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 604 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face),
@@ -625,12 +607,12 @@ static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
625 GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 607 GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
626 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 0, 0); 608 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 0, 0);
627 break; 609 break;
628 case SurfaceParams::SurfaceTarget::Texture2DArray: 610 case SurfaceTarget::Texture2DArray:
629 glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment, 611 glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
630 src_surface->Texture().handle, 0, 0); 612 src_surface->Texture().handle, 0, 0);
631 glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 0, 0, 0); 613 glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 0, 0, 0);
632 break; 614 break;
633 case SurfaceParams::SurfaceTarget::Texture3D: 615 case SurfaceTarget::Texture3D:
634 glFramebufferTexture3D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment, 616 glFramebufferTexture3D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
635 SurfaceTargetToGL(src_params.target), 617 SurfaceTargetToGL(src_params.target),
636 src_surface->Texture().handle, 0, 0); 618 src_surface->Texture().handle, 0, 0);
@@ -646,13 +628,13 @@ static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
646 } 628 }
647 629
648 switch (dst_params.target) { 630 switch (dst_params.target) {
649 case SurfaceParams::SurfaceTarget::Texture2D: 631 case SurfaceTarget::Texture2D:
650 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment, 632 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
651 GL_TEXTURE_2D, dst_surface->Texture().handle, 0); 633 GL_TEXTURE_2D, dst_surface->Texture().handle, 0);
652 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 634 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
653 0, 0); 635 0, 0);
654 break; 636 break;
655 case SurfaceParams::SurfaceTarget::TextureCubemap: 637 case SurfaceTarget::TextureCubemap:
656 glFramebufferTexture2D( 638 glFramebufferTexture2D(
657 GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment, 639 GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
658 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 640 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face),
@@ -661,13 +643,13 @@ static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
661 GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 643 GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
662 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 0, 0); 644 static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 0, 0);
663 break; 645 break;
664 case SurfaceParams::SurfaceTarget::Texture2DArray: 646 case SurfaceTarget::Texture2DArray:
665 glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment, 647 glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
666 dst_surface->Texture().handle, 0, 0); 648 dst_surface->Texture().handle, 0, 0);
667 glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 0, 0, 0); 649 glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 0, 0, 0);
668 break; 650 break;
669 651
670 case SurfaceParams::SurfaceTarget::Texture3D: 652 case SurfaceTarget::Texture3D:
671 glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment, 653 glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
672 SurfaceTargetToGL(dst_params.target), 654 SurfaceTargetToGL(dst_params.target),
673 dst_surface->Texture().handle, 0, 0); 655 dst_surface->Texture().handle, 0, 0);
@@ -731,18 +713,20 @@ static void FastCopySurface(const Surface& src_surface, const Surface& dst_surfa
731 0, 0, width, height, 1); 713 0, 0, width, height, 1);
732} 714}
733 715
716MICROPROFILE_DEFINE(OpenGL_CopySurface, "OpenGL", "CopySurface", MP_RGB(128, 192, 64));
734static void CopySurface(const Surface& src_surface, const Surface& dst_surface, 717static void CopySurface(const Surface& src_surface, const Surface& dst_surface,
735 GLuint copy_pbo_handle, GLenum src_attachment = 0, 718 const GLuint copy_pbo_handle, const GLenum src_attachment = 0,
736 GLenum dst_attachment = 0, std::size_t cubemap_face = 0) { 719 const GLenum dst_attachment = 0, const std::size_t cubemap_face = 0) {
720 MICROPROFILE_SCOPE(OpenGL_CopySurface);
737 ASSERT_MSG(dst_attachment == 0, "Unimplemented"); 721 ASSERT_MSG(dst_attachment == 0, "Unimplemented");
738 722
739 const auto& src_params{src_surface->GetSurfaceParams()}; 723 const auto& src_params{src_surface->GetSurfaceParams()};
740 const auto& dst_params{dst_surface->GetSurfaceParams()}; 724 const auto& dst_params{dst_surface->GetSurfaceParams()};
741 725
742 auto source_format = GetFormatTuple(src_params.pixel_format, src_params.component_type); 726 const auto source_format = GetFormatTuple(src_params.pixel_format, src_params.component_type);
743 auto dest_format = GetFormatTuple(dst_params.pixel_format, dst_params.component_type); 727 const auto dest_format = GetFormatTuple(dst_params.pixel_format, dst_params.component_type);
744 728
745 std::size_t buffer_size = std::max(src_params.size_in_bytes, dst_params.size_in_bytes); 729 const std::size_t buffer_size = std::max(src_params.size_in_bytes, dst_params.size_in_bytes);
746 730
747 glBindBuffer(GL_PIXEL_PACK_BUFFER, copy_pbo_handle); 731 glBindBuffer(GL_PIXEL_PACK_BUFFER, copy_pbo_handle);
748 glBufferData(GL_PIXEL_PACK_BUFFER, buffer_size, nullptr, GL_STREAM_DRAW_ARB); 732 glBufferData(GL_PIXEL_PACK_BUFFER, buffer_size, nullptr, GL_STREAM_DRAW_ARB);
@@ -766,13 +750,10 @@ static void CopySurface(const Surface& src_surface, const Surface& dst_surface,
766 LOG_DEBUG(HW_GPU, "Trying to upload extra texture data from the CPU during " 750 LOG_DEBUG(HW_GPU, "Trying to upload extra texture data from the CPU during "
767 "reinterpretation but the texture is tiled."); 751 "reinterpretation but the texture is tiled.");
768 } 752 }
769 std::size_t remaining_size = dst_params.size_in_bytes - src_params.size_in_bytes; 753 const std::size_t remaining_size = dst_params.size_in_bytes - src_params.size_in_bytes;
770 std::vector<u8> data(remaining_size);
771 std::memcpy(data.data(), Memory::GetPointer(dst_params.addr + src_params.size_in_bytes),
772 data.size());
773 754
774 glBufferSubData(GL_PIXEL_PACK_BUFFER, src_params.size_in_bytes, remaining_size, 755 glBufferSubData(GL_PIXEL_PACK_BUFFER, src_params.size_in_bytes, remaining_size,
775 data.data()); 756 Memory::GetPointer(dst_params.addr + src_params.size_in_bytes));
776 } 757 }
777 758
778 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); 759 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
@@ -788,21 +769,22 @@ static void CopySurface(const Surface& src_surface, const Surface& dst_surface,
788 UNREACHABLE(); 769 UNREACHABLE();
789 } else { 770 } else {
790 switch (dst_params.target) { 771 switch (dst_params.target) {
791 case SurfaceParams::SurfaceTarget::Texture1D: 772 case SurfaceTarget::Texture1D:
792 glTextureSubImage1D(dst_surface->Texture().handle, 0, 0, width, dest_format.format, 773 glTextureSubImage1D(dst_surface->Texture().handle, 0, 0, width, dest_format.format,
793 dest_format.type, nullptr); 774 dest_format.type, nullptr);
794 break; 775 break;
795 case SurfaceParams::SurfaceTarget::Texture2D: 776 case SurfaceTarget::Texture2D:
796 glTextureSubImage2D(dst_surface->Texture().handle, 0, 0, 0, width, height, 777 glTextureSubImage2D(dst_surface->Texture().handle, 0, 0, 0, width, height,
797 dest_format.format, dest_format.type, nullptr); 778 dest_format.format, dest_format.type, nullptr);
798 break; 779 break;
799 case SurfaceParams::SurfaceTarget::Texture3D: 780 case SurfaceTarget::Texture3D:
800 case SurfaceParams::SurfaceTarget::Texture2DArray: 781 case SurfaceTarget::Texture2DArray:
782 case SurfaceTarget::TextureCubeArray:
801 glTextureSubImage3D(dst_surface->Texture().handle, 0, 0, 0, 0, width, height, 783 glTextureSubImage3D(dst_surface->Texture().handle, 0, 0, 0, 0, width, height,
802 static_cast<GLsizei>(dst_params.depth), dest_format.format, 784 static_cast<GLsizei>(dst_params.depth), dest_format.format,
803 dest_format.type, nullptr); 785 dest_format.type, nullptr);
804 break; 786 break;
805 case SurfaceParams::SurfaceTarget::TextureCubemap: 787 case SurfaceTarget::TextureCubemap:
806 glTextureSubImage3D(dst_surface->Texture().handle, 0, 0, 0, 788 glTextureSubImage3D(dst_surface->Texture().handle, 0, 0, 0,
807 static_cast<GLint>(cubemap_face), width, height, 1, 789 static_cast<GLint>(cubemap_face), width, height, 1,
808 dest_format.format, dest_format.type, nullptr); 790 dest_format.format, dest_format.type, nullptr);
@@ -839,32 +821,40 @@ CachedSurface::CachedSurface(const SurfaceParams& params)
839 if (!format_tuple.compressed) { 821 if (!format_tuple.compressed) {
840 // Only pre-create the texture for non-compressed textures. 822 // Only pre-create the texture for non-compressed textures.
841 switch (params.target) { 823 switch (params.target) {
842 case SurfaceParams::SurfaceTarget::Texture1D: 824 case SurfaceTarget::Texture1D:
843 glTexStorage1D(SurfaceTargetToGL(params.target), 1, format_tuple.internal_format, 825 glTexStorage1D(SurfaceTargetToGL(params.target), params.max_mip_level,
844 rect.GetWidth()); 826 format_tuple.internal_format, rect.GetWidth());
845 break; 827 break;
846 case SurfaceParams::SurfaceTarget::Texture2D: 828 case SurfaceTarget::Texture2D:
847 case SurfaceParams::SurfaceTarget::TextureCubemap: 829 case SurfaceTarget::TextureCubemap:
848 glTexStorage2D(SurfaceTargetToGL(params.target), 1, format_tuple.internal_format, 830 glTexStorage2D(SurfaceTargetToGL(params.target), params.max_mip_level,
849 rect.GetWidth(), rect.GetHeight()); 831 format_tuple.internal_format, rect.GetWidth(), rect.GetHeight());
850 break; 832 break;
851 case SurfaceParams::SurfaceTarget::Texture3D: 833 case SurfaceTarget::Texture3D:
852 case SurfaceParams::SurfaceTarget::Texture2DArray: 834 case SurfaceTarget::Texture2DArray:
853 glTexStorage3D(SurfaceTargetToGL(params.target), 1, format_tuple.internal_format, 835 case SurfaceTarget::TextureCubeArray:
854 rect.GetWidth(), rect.GetHeight(), params.depth); 836 glTexStorage3D(SurfaceTargetToGL(params.target), params.max_mip_level,
837 format_tuple.internal_format, rect.GetWidth(), rect.GetHeight(),
838 params.depth);
855 break; 839 break;
856 default: 840 default:
857 LOG_CRITICAL(Render_OpenGL, "Unimplemented surface target={}", 841 LOG_CRITICAL(Render_OpenGL, "Unimplemented surface target={}",
858 static_cast<u32>(params.target)); 842 static_cast<u32>(params.target));
859 UNREACHABLE(); 843 UNREACHABLE();
860 glTexStorage2D(GL_TEXTURE_2D, 1, format_tuple.internal_format, rect.GetWidth(), 844 glTexStorage2D(GL_TEXTURE_2D, params.max_mip_level, format_tuple.internal_format,
861 rect.GetHeight()); 845 rect.GetWidth(), rect.GetHeight());
862 } 846 }
863 } 847 }
864 848
865 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_MIN_FILTER, GL_LINEAR); 849 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_MIN_FILTER, GL_LINEAR);
850 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
866 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 851 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
867 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 852 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
853 glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_MAX_LEVEL,
854 params.max_mip_level - 1);
855 if (params.max_mip_level == 1) {
856 glTexParameterf(SurfaceTargetToGL(params.target), GL_TEXTURE_LOD_BIAS, 1000.0);
857 }
868 858
869 LabelGLObject(GL_TEXTURE, texture.handle, params.addr, 859 LabelGLObject(GL_TEXTURE, texture.handle, params.addr,
870 SurfaceParams::SurfaceTargetName(params.target)); 860 SurfaceParams::SurfaceTargetName(params.target));
@@ -897,7 +887,7 @@ static void ConvertS8Z24ToZ24S8(std::vector<u8>& data, u32 width, u32 height, bo
897 887
898 S8Z24 s8z24_pixel{}; 888 S8Z24 s8z24_pixel{};
899 Z24S8 z24s8_pixel{}; 889 Z24S8 z24s8_pixel{};
900 constexpr auto bpp{SurfaceParams::GetBytesPerPixel(PixelFormat::S8Z24)}; 890 constexpr auto bpp{GetBytesPerPixel(PixelFormat::S8Z24)};
901 for (std::size_t y = 0; y < height; ++y) { 891 for (std::size_t y = 0; y < height; ++y) {
902 for (std::size_t x = 0; x < width; ++x) { 892 for (std::size_t x = 0; x < width; ++x) {
903 const std::size_t offset{bpp * (y * width + x)}; 893 const std::size_t offset{bpp * (y * width + x)};
@@ -917,7 +907,7 @@ static void ConvertS8Z24ToZ24S8(std::vector<u8>& data, u32 width, u32 height, bo
917} 907}
918 908
919static void ConvertG8R8ToR8G8(std::vector<u8>& data, u32 width, u32 height) { 909static void ConvertG8R8ToR8G8(std::vector<u8>& data, u32 width, u32 height) {
920 constexpr auto bpp{SurfaceParams::GetBytesPerPixel(PixelFormat::G8R8U)}; 910 constexpr auto bpp{GetBytesPerPixel(PixelFormat::G8R8U)};
921 for (std::size_t y = 0; y < height; ++y) { 911 for (std::size_t y = 0; y < height; ++y) {
922 for (std::size_t x = 0; x < width; ++x) { 912 for (std::size_t x = 0; x < width; ++x) {
923 const std::size_t offset{bpp * (y * width + x)}; 913 const std::size_t offset{bpp * (y * width + x)};
@@ -934,21 +924,26 @@ static void ConvertG8R8ToR8G8(std::vector<u8>& data, u32 width, u32 height) {
934 * typical desktop GPUs. 924 * typical desktop GPUs.
935 */ 925 */
936static void ConvertFormatAsNeeded_LoadGLBuffer(std::vector<u8>& data, PixelFormat pixel_format, 926static void ConvertFormatAsNeeded_LoadGLBuffer(std::vector<u8>& data, PixelFormat pixel_format,
937 u32 width, u32 height) { 927 u32 width, u32 height, u32 depth) {
938 switch (pixel_format) { 928 switch (pixel_format) {
939 case PixelFormat::ASTC_2D_4X4: 929 case PixelFormat::ASTC_2D_4X4:
940 case PixelFormat::ASTC_2D_8X8: 930 case PixelFormat::ASTC_2D_8X8:
941 case PixelFormat::ASTC_2D_8X5: 931 case PixelFormat::ASTC_2D_8X5:
942 case PixelFormat::ASTC_2D_5X4: 932 case PixelFormat::ASTC_2D_5X4:
933 case PixelFormat::ASTC_2D_5X5:
943 case PixelFormat::ASTC_2D_4X4_SRGB: 934 case PixelFormat::ASTC_2D_4X4_SRGB:
944 case PixelFormat::ASTC_2D_8X8_SRGB: 935 case PixelFormat::ASTC_2D_8X8_SRGB:
945 case PixelFormat::ASTC_2D_8X5_SRGB: 936 case PixelFormat::ASTC_2D_8X5_SRGB:
946 case PixelFormat::ASTC_2D_5X4_SRGB: { 937 case PixelFormat::ASTC_2D_5X4_SRGB:
938 case PixelFormat::ASTC_2D_5X5_SRGB:
939 case PixelFormat::ASTC_2D_10X8:
940 case PixelFormat::ASTC_2D_10X8_SRGB: {
947 // Convert ASTC pixel formats to RGBA8, as most desktop GPUs do not support ASTC. 941 // Convert ASTC pixel formats to RGBA8, as most desktop GPUs do not support ASTC.
948 u32 block_width{}; 942 u32 block_width{};
949 u32 block_height{}; 943 u32 block_height{};
950 std::tie(block_width, block_height) = GetASTCBlockSize(pixel_format); 944 std::tie(block_width, block_height) = GetASTCBlockSize(pixel_format);
951 data = Tegra::Texture::ASTC::Decompress(data, width, height, block_width, block_height); 945 data =
946 Tegra::Texture::ASTC::Decompress(data, width, height, depth, block_width, block_height);
952 break; 947 break;
953 } 948 }
954 case PixelFormat::S8Z24: 949 case PixelFormat::S8Z24:
@@ -977,7 +972,11 @@ static void ConvertFormatAsNeeded_FlushGLBuffer(std::vector<u8>& data, PixelForm
977 case PixelFormat::ASTC_2D_4X4: 972 case PixelFormat::ASTC_2D_4X4:
978 case PixelFormat::ASTC_2D_8X8: 973 case PixelFormat::ASTC_2D_8X8:
979 case PixelFormat::ASTC_2D_4X4_SRGB: 974 case PixelFormat::ASTC_2D_4X4_SRGB:
980 case PixelFormat::ASTC_2D_8X8_SRGB: { 975 case PixelFormat::ASTC_2D_8X8_SRGB:
976 case PixelFormat::ASTC_2D_5X5:
977 case PixelFormat::ASTC_2D_5X5_SRGB:
978 case PixelFormat::ASTC_2D_10X8:
979 case PixelFormat::ASTC_2D_10X8_SRGB: {
981 LOG_CRITICAL(HW_GPU, "Conversion of format {} after texture flushing is not implemented", 980 LOG_CRITICAL(HW_GPU, "Conversion of format {} after texture flushing is not implemented",
982 static_cast<u32>(pixel_format)); 981 static_cast<u32>(pixel_format));
983 UNREACHABLE(); 982 UNREACHABLE();
@@ -990,23 +989,25 @@ static void ConvertFormatAsNeeded_FlushGLBuffer(std::vector<u8>& data, PixelForm
990 } 989 }
991} 990}
992 991
993MICROPROFILE_DEFINE(OpenGL_SurfaceLoad, "OpenGL", "Surface Load", MP_RGB(128, 64, 192)); 992MICROPROFILE_DEFINE(OpenGL_SurfaceLoad, "OpenGL", "Surface Load", MP_RGB(128, 192, 64));
994void CachedSurface::LoadGLBuffer() { 993void CachedSurface::LoadGLBuffer() {
995 MICROPROFILE_SCOPE(OpenGL_SurfaceLoad); 994 MICROPROFILE_SCOPE(OpenGL_SurfaceLoad);
996 995 gl_buffer.resize(params.max_mip_level);
997 gl_buffer.resize(params.size_in_bytes_gl); 996 for (u32 i = 0; i < params.max_mip_level; i++)
997 gl_buffer[i].resize(params.GetMipmapSizeGL(i));
998 if (params.is_tiled) { 998 if (params.is_tiled) {
999 ASSERT_MSG(params.block_width == 1, "Block width is defined as {} on texture type {}", 999 ASSERT_MSG(params.block_width == 1, "Block width is defined as {} on texture type {}",
1000 params.block_width, static_cast<u32>(params.target)); 1000 params.block_width, static_cast<u32>(params.target));
1001 1001 for (u32 i = 0; i < params.max_mip_level; i++)
1002 SwizzleFunc(morton_to_gl_fns, params, gl_buffer); 1002 SwizzleFunc(morton_to_gl_fns, params, gl_buffer[i], i);
1003 } else { 1003 } else {
1004 const auto texture_src_data{Memory::GetPointer(params.addr)}; 1004 const auto texture_src_data{Memory::GetPointer(params.addr)};
1005 const auto texture_src_data_end{texture_src_data + params.size_in_bytes_gl}; 1005 const auto texture_src_data_end{texture_src_data + params.size_in_bytes_gl};
1006 gl_buffer.assign(texture_src_data, texture_src_data_end); 1006 gl_buffer[0].assign(texture_src_data, texture_src_data_end);
1007 } 1007 }
1008 1008 for (u32 i = 0; i < params.max_mip_level; i++)
1009 ConvertFormatAsNeeded_LoadGLBuffer(gl_buffer, params.pixel_format, params.width, params.height); 1009 ConvertFormatAsNeeded_LoadGLBuffer(gl_buffer[i], params.pixel_format, params.MipWidth(i),
1010 params.MipHeight(i), params.MipDepth(i));
1010} 1011}
1011 1012
1012MICROPROFILE_DEFINE(OpenGL_SurfaceFlush, "OpenGL", "Surface Flush", MP_RGB(128, 192, 64)); 1013MICROPROFILE_DEFINE(OpenGL_SurfaceFlush, "OpenGL", "Surface Flush", MP_RGB(128, 192, 64));
@@ -1016,18 +1017,19 @@ void CachedSurface::FlushGLBuffer() {
1016 ASSERT_MSG(!IsPixelFormatASTC(params.pixel_format), "Unimplemented"); 1017 ASSERT_MSG(!IsPixelFormatASTC(params.pixel_format), "Unimplemented");
1017 1018
1018 // OpenGL temporary buffer needs to be big enough to store raw texture size 1019 // OpenGL temporary buffer needs to be big enough to store raw texture size
1019 gl_buffer.resize(GetSizeInBytes()); 1020 gl_buffer.resize(1);
1021 gl_buffer[0].resize(GetSizeInBytes());
1020 1022
1021 const FormatTuple& tuple = GetFormatTuple(params.pixel_format, params.component_type); 1023 const FormatTuple& tuple = GetFormatTuple(params.pixel_format, params.component_type);
1022 // Ensure no bad interactions with GL_UNPACK_ALIGNMENT 1024 // Ensure no bad interactions with GL_UNPACK_ALIGNMENT
1023 ASSERT(params.width * SurfaceParams::GetBytesPerPixel(params.pixel_format) % 4 == 0); 1025 ASSERT(params.width * GetBytesPerPixel(params.pixel_format) % 4 == 0);
1024 glPixelStorei(GL_PACK_ROW_LENGTH, static_cast<GLint>(params.width)); 1026 glPixelStorei(GL_PACK_ROW_LENGTH, static_cast<GLint>(params.width));
1025 ASSERT(!tuple.compressed); 1027 ASSERT(!tuple.compressed);
1026 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); 1028 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1027 glGetTextureImage(texture.handle, 0, tuple.format, tuple.type, 1029 glGetTextureImage(texture.handle, 0, tuple.format, tuple.type,
1028 static_cast<GLsizei>(gl_buffer.size()), gl_buffer.data()); 1030 static_cast<GLsizei>(gl_buffer[0].size()), gl_buffer[0].data());
1029 glPixelStorei(GL_PACK_ROW_LENGTH, 0); 1031 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
1030 ConvertFormatAsNeeded_FlushGLBuffer(gl_buffer, params.pixel_format, params.width, 1032 ConvertFormatAsNeeded_FlushGLBuffer(gl_buffer[0], params.pixel_format, params.width,
1031 params.height); 1033 params.height);
1032 ASSERT(params.type != SurfaceType::Fill); 1034 ASSERT(params.type != SurfaceType::Fill);
1033 const u8* const texture_src_data = Memory::GetPointer(params.addr); 1035 const u8* const texture_src_data = Memory::GetPointer(params.addr);
@@ -1036,28 +1038,23 @@ void CachedSurface::FlushGLBuffer() {
1036 ASSERT_MSG(params.block_width == 1, "Block width is defined as {} on texture type {}", 1038 ASSERT_MSG(params.block_width == 1, "Block width is defined as {} on texture type {}",
1037 params.block_width, static_cast<u32>(params.target)); 1039 params.block_width, static_cast<u32>(params.target));
1038 1040
1039 SwizzleFunc(gl_to_morton_fns, params, gl_buffer); 1041 SwizzleFunc(gl_to_morton_fns, params, gl_buffer[0], 0);
1040 } else { 1042 } else {
1041 std::memcpy(Memory::GetPointer(GetAddr()), gl_buffer.data(), GetSizeInBytes()); 1043 std::memcpy(Memory::GetPointer(GetAddr()), gl_buffer[0].data(), GetSizeInBytes());
1042 } 1044 }
1043} 1045}
1044 1046
1045MICROPROFILE_DEFINE(OpenGL_TextureUL, "OpenGL", "Texture Upload", MP_RGB(128, 64, 192)); 1047void CachedSurface::UploadGLMipmapTexture(u32 mip_map, GLuint read_fb_handle,
1046void CachedSurface::UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle) { 1048 GLuint draw_fb_handle) {
1047 if (params.type == SurfaceType::Fill) 1049 const auto& rect{params.GetRect(mip_map)};
1048 return;
1049
1050 MICROPROFILE_SCOPE(OpenGL_TextureUL);
1051
1052 const auto& rect{params.GetRect()};
1053 1050
1054 // Load data from memory to the surface 1051 // Load data from memory to the surface
1055 const GLint x0 = static_cast<GLint>(rect.left); 1052 const GLint x0 = static_cast<GLint>(rect.left);
1056 const GLint y0 = static_cast<GLint>(rect.bottom); 1053 const GLint y0 = static_cast<GLint>(rect.bottom);
1057 std::size_t buffer_offset = 1054 std::size_t buffer_offset =
1058 static_cast<std::size_t>(static_cast<std::size_t>(y0) * params.width + 1055 static_cast<std::size_t>(static_cast<std::size_t>(y0) * params.MipWidth(mip_map) +
1059 static_cast<std::size_t>(x0)) * 1056 static_cast<std::size_t>(x0)) *
1060 SurfaceParams::GetBytesPerPixel(params.pixel_format); 1057 GetBytesPerPixel(params.pixel_format);
1061 1058
1062 const FormatTuple& tuple = GetFormatTuple(params.pixel_format, params.component_type); 1059 const FormatTuple& tuple = GetFormatTuple(params.pixel_format, params.component_type);
1063 const GLuint target_tex = texture.handle; 1060 const GLuint target_tex = texture.handle;
@@ -1073,89 +1070,120 @@ void CachedSurface::UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle
1073 cur_state.Apply(); 1070 cur_state.Apply();
1074 1071
1075 // Ensure no bad interactions with GL_UNPACK_ALIGNMENT 1072 // Ensure no bad interactions with GL_UNPACK_ALIGNMENT
1076 ASSERT(params.width * SurfaceParams::GetBytesPerPixel(params.pixel_format) % 4 == 0); 1073 ASSERT(params.MipWidth(mip_map) * GetBytesPerPixel(params.pixel_format) % 4 == 0);
1077 glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(params.width)); 1074 glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(params.MipWidth(mip_map)));
1078 1075
1076 GLsizei image_size = static_cast<GLsizei>(params.GetMipmapSizeGL(mip_map, false));
1079 glActiveTexture(GL_TEXTURE0); 1077 glActiveTexture(GL_TEXTURE0);
1080 if (tuple.compressed) { 1078 if (tuple.compressed) {
1081 switch (params.target) { 1079 switch (params.target) {
1082 case SurfaceParams::SurfaceTarget::Texture2D: 1080 case SurfaceTarget::Texture2D:
1083 glCompressedTexImage2D( 1081 glCompressedTexImage2D(SurfaceTargetToGL(params.target), mip_map, tuple.internal_format,
1084 SurfaceTargetToGL(params.target), 0, tuple.internal_format, 1082 static_cast<GLsizei>(params.MipWidth(mip_map)),
1085 static_cast<GLsizei>(params.width), static_cast<GLsizei>(params.height), 0, 1083 static_cast<GLsizei>(params.MipHeight(mip_map)), 0, image_size,
1086 static_cast<GLsizei>(params.size_in_bytes_gl), &gl_buffer[buffer_offset]); 1084 &gl_buffer[mip_map][buffer_offset]);
1087 break; 1085 break;
1088 case SurfaceParams::SurfaceTarget::Texture3D: 1086 case SurfaceTarget::Texture3D:
1089 case SurfaceParams::SurfaceTarget::Texture2DArray: 1087 glCompressedTexImage3D(SurfaceTargetToGL(params.target), mip_map, tuple.internal_format,
1090 glCompressedTexImage3D( 1088 static_cast<GLsizei>(params.MipWidth(mip_map)),
1091 SurfaceTargetToGL(params.target), 0, tuple.internal_format, 1089 static_cast<GLsizei>(params.MipHeight(mip_map)),
1092 static_cast<GLsizei>(params.width), static_cast<GLsizei>(params.height), 1090 static_cast<GLsizei>(params.MipDepth(mip_map)), 0, image_size,
1093 static_cast<GLsizei>(params.depth), 0, 1091 &gl_buffer[mip_map][buffer_offset]);
1094 static_cast<GLsizei>(params.size_in_bytes_gl), &gl_buffer[buffer_offset]);
1095 break; 1092 break;
1096 case SurfaceParams::SurfaceTarget::TextureCubemap: 1093 case SurfaceTarget::Texture2DArray:
1094 case SurfaceTarget::TextureCubeArray:
1095 glCompressedTexImage3D(SurfaceTargetToGL(params.target), mip_map, tuple.internal_format,
1096 static_cast<GLsizei>(params.MipWidth(mip_map)),
1097 static_cast<GLsizei>(params.MipHeight(mip_map)),
1098 static_cast<GLsizei>(params.depth), 0, image_size,
1099 &gl_buffer[mip_map][buffer_offset]);
1100 break;
1101 case SurfaceTarget::TextureCubemap: {
1102 GLsizei layer_size = static_cast<GLsizei>(params.LayerSizeGL(mip_map));
1097 for (std::size_t face = 0; face < params.depth; ++face) { 1103 for (std::size_t face = 0; face < params.depth; ++face) {
1098 glCompressedTexImage2D(static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), 1104 glCompressedTexImage2D(static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face),
1099 0, tuple.internal_format, static_cast<GLsizei>(params.width), 1105 mip_map, tuple.internal_format,
1100 static_cast<GLsizei>(params.height), 0, 1106 static_cast<GLsizei>(params.MipWidth(mip_map)),
1101 static_cast<GLsizei>(params.SizeInBytesCubeFaceGL()), 1107 static_cast<GLsizei>(params.MipHeight(mip_map)), 0,
1102 &gl_buffer[buffer_offset]); 1108 layer_size, &gl_buffer[mip_map][buffer_offset]);
1103 buffer_offset += params.SizeInBytesCubeFace(); 1109 buffer_offset += layer_size;
1104 } 1110 }
1105 break; 1111 break;
1112 }
1106 default: 1113 default:
1107 LOG_CRITICAL(Render_OpenGL, "Unimplemented surface target={}", 1114 LOG_CRITICAL(Render_OpenGL, "Unimplemented surface target={}",
1108 static_cast<u32>(params.target)); 1115 static_cast<u32>(params.target));
1109 UNREACHABLE(); 1116 UNREACHABLE();
1110 glCompressedTexImage2D( 1117 glCompressedTexImage2D(GL_TEXTURE_2D, mip_map, tuple.internal_format,
1111 GL_TEXTURE_2D, 0, tuple.internal_format, static_cast<GLsizei>(params.width), 1118 static_cast<GLsizei>(params.MipWidth(mip_map)),
1112 static_cast<GLsizei>(params.height), 0, 1119 static_cast<GLsizei>(params.MipHeight(mip_map)), 0,
1113 static_cast<GLsizei>(params.size_in_bytes_gl), &gl_buffer[buffer_offset]); 1120 static_cast<GLsizei>(params.size_in_bytes_gl),
1121 &gl_buffer[mip_map][buffer_offset]);
1114 } 1122 }
1115 } else { 1123 } else {
1116 1124
1117 switch (params.target) { 1125 switch (params.target) {
1118 case SurfaceParams::SurfaceTarget::Texture1D: 1126 case SurfaceTarget::Texture1D:
1119 glTexSubImage1D(SurfaceTargetToGL(params.target), 0, x0, 1127 glTexSubImage1D(SurfaceTargetToGL(params.target), mip_map, x0,
1120 static_cast<GLsizei>(rect.GetWidth()), tuple.format, tuple.type, 1128 static_cast<GLsizei>(rect.GetWidth()), tuple.format, tuple.type,
1121 &gl_buffer[buffer_offset]); 1129 &gl_buffer[mip_map][buffer_offset]);
1122 break; 1130 break;
1123 case SurfaceParams::SurfaceTarget::Texture2D: 1131 case SurfaceTarget::Texture2D:
1124 glTexSubImage2D(SurfaceTargetToGL(params.target), 0, x0, y0, 1132 glTexSubImage2D(SurfaceTargetToGL(params.target), mip_map, x0, y0,
1125 static_cast<GLsizei>(rect.GetWidth()), 1133 static_cast<GLsizei>(rect.GetWidth()),
1126 static_cast<GLsizei>(rect.GetHeight()), tuple.format, tuple.type, 1134 static_cast<GLsizei>(rect.GetHeight()), tuple.format, tuple.type,
1127 &gl_buffer[buffer_offset]); 1135 &gl_buffer[mip_map][buffer_offset]);
1128 break; 1136 break;
1129 case SurfaceParams::SurfaceTarget::Texture3D: 1137 case SurfaceTarget::Texture3D:
1130 case SurfaceParams::SurfaceTarget::Texture2DArray: 1138 glTexSubImage3D(SurfaceTargetToGL(params.target), mip_map, x0, y0, 0,
1131 glTexSubImage3D(SurfaceTargetToGL(params.target), 0, x0, y0, 0, 1139 static_cast<GLsizei>(rect.GetWidth()),
1140 static_cast<GLsizei>(rect.GetHeight()), params.MipDepth(mip_map),
1141 tuple.format, tuple.type, &gl_buffer[mip_map][buffer_offset]);
1142 break;
1143 case SurfaceTarget::Texture2DArray:
1144 case SurfaceTarget::TextureCubeArray:
1145 glTexSubImage3D(SurfaceTargetToGL(params.target), mip_map, x0, y0, 0,
1132 static_cast<GLsizei>(rect.GetWidth()), 1146 static_cast<GLsizei>(rect.GetWidth()),
1133 static_cast<GLsizei>(rect.GetHeight()), params.depth, tuple.format, 1147 static_cast<GLsizei>(rect.GetHeight()), params.depth, tuple.format,
1134 tuple.type, &gl_buffer[buffer_offset]); 1148 tuple.type, &gl_buffer[mip_map][buffer_offset]);
1135 break; 1149 break;
1136 case SurfaceParams::SurfaceTarget::TextureCubemap: 1150 case SurfaceTarget::TextureCubemap: {
1151 std::size_t start = buffer_offset;
1137 for (std::size_t face = 0; face < params.depth; ++face) { 1152 for (std::size_t face = 0; face < params.depth; ++face) {
1138 glTexSubImage2D(static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, x0, 1153 glTexSubImage2D(static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), mip_map,
1139 y0, static_cast<GLsizei>(rect.GetWidth()), 1154 x0, y0, static_cast<GLsizei>(rect.GetWidth()),
1140 static_cast<GLsizei>(rect.GetHeight()), tuple.format, tuple.type, 1155 static_cast<GLsizei>(rect.GetHeight()), tuple.format, tuple.type,
1141 &gl_buffer[buffer_offset]); 1156 &gl_buffer[mip_map][buffer_offset]);
1142 buffer_offset += params.SizeInBytesCubeFace(); 1157 buffer_offset += params.LayerSizeGL(mip_map);
1143 } 1158 }
1144 break; 1159 break;
1160 }
1145 default: 1161 default:
1146 LOG_CRITICAL(Render_OpenGL, "Unimplemented surface target={}", 1162 LOG_CRITICAL(Render_OpenGL, "Unimplemented surface target={}",
1147 static_cast<u32>(params.target)); 1163 static_cast<u32>(params.target));
1148 UNREACHABLE(); 1164 UNREACHABLE();
1149 glTexSubImage2D(GL_TEXTURE_2D, 0, x0, y0, static_cast<GLsizei>(rect.GetWidth()), 1165 glTexSubImage2D(GL_TEXTURE_2D, mip_map, x0, y0, static_cast<GLsizei>(rect.GetWidth()),
1150 static_cast<GLsizei>(rect.GetHeight()), tuple.format, tuple.type, 1166 static_cast<GLsizei>(rect.GetHeight()), tuple.format, tuple.type,
1151 &gl_buffer[buffer_offset]); 1167 &gl_buffer[mip_map][buffer_offset]);
1152 } 1168 }
1153 } 1169 }
1154 1170
1155 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); 1171 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1156} 1172}
1157 1173
1158RasterizerCacheOpenGL::RasterizerCacheOpenGL() { 1174MICROPROFILE_DEFINE(OpenGL_TextureUL, "OpenGL", "Texture Upload", MP_RGB(128, 192, 64));
1175void CachedSurface::UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle) {
1176 if (params.type == SurfaceType::Fill)
1177 return;
1178
1179 MICROPROFILE_SCOPE(OpenGL_TextureUL);
1180
1181 for (u32 i = 0; i < params.max_mip_level; i++)
1182 UploadGLMipmapTexture(i, read_fb_handle, draw_fb_handle);
1183}
1184
1185RasterizerCacheOpenGL::RasterizerCacheOpenGL(RasterizerOpenGL& rasterizer)
1186 : RasterizerCache{rasterizer} {
1159 read_framebuffer.Create(); 1187 read_framebuffer.Create();
1160 draw_framebuffer.Create(); 1188 draw_framebuffer.Create();
1161 copy_pbo.Create(); 1189 copy_pbo.Create();
@@ -1295,8 +1323,7 @@ Surface RasterizerCacheOpenGL::RecreateSurface(const Surface& old_surface,
1295 // For compatible surfaces, we can just do fast glCopyImageSubData based copy 1323 // For compatible surfaces, we can just do fast glCopyImageSubData based copy
1296 if (old_params.target == new_params.target && old_params.type == new_params.type && 1324 if (old_params.target == new_params.target && old_params.type == new_params.type &&
1297 old_params.depth == new_params.depth && old_params.depth == 1 && 1325 old_params.depth == new_params.depth && old_params.depth == 1 &&
1298 SurfaceParams::GetFormatBpp(old_params.pixel_format) == 1326 GetFormatBpp(old_params.pixel_format) == GetFormatBpp(new_params.pixel_format)) {
1299 SurfaceParams::GetFormatBpp(new_params.pixel_format)) {
1300 FastCopySurface(old_surface, new_surface); 1327 FastCopySurface(old_surface, new_surface);
1301 return new_surface; 1328 return new_surface;
1302 } 1329 }
@@ -1309,15 +1336,17 @@ Surface RasterizerCacheOpenGL::RecreateSurface(const Surface& old_surface,
1309 const bool is_blit{old_params.pixel_format == new_params.pixel_format}; 1336 const bool is_blit{old_params.pixel_format == new_params.pixel_format};
1310 1337
1311 switch (new_params.target) { 1338 switch (new_params.target) {
1312 case SurfaceParams::SurfaceTarget::Texture2D: 1339 case SurfaceTarget::Texture2D:
1313 if (is_blit) { 1340 if (is_blit) {
1314 BlitSurface(old_surface, new_surface, read_framebuffer.handle, draw_framebuffer.handle); 1341 BlitSurface(old_surface, new_surface, read_framebuffer.handle, draw_framebuffer.handle);
1315 } else { 1342 } else {
1316 CopySurface(old_surface, new_surface, copy_pbo.handle); 1343 CopySurface(old_surface, new_surface, copy_pbo.handle);
1317 } 1344 }
1318 break; 1345 break;
1319 case SurfaceParams::SurfaceTarget::TextureCubemap: 1346 case SurfaceTarget::TextureCubemap:
1320 case SurfaceParams::SurfaceTarget::Texture3D: 1347 case SurfaceTarget::Texture3D:
1348 case SurfaceTarget::Texture2DArray:
1349 case SurfaceTarget::TextureCubeArray:
1321 AccurateCopySurface(old_surface, new_surface); 1350 AccurateCopySurface(old_surface, new_surface);
1322 break; 1351 break;
1323 default: 1352 default:
@@ -1327,7 +1356,7 @@ Surface RasterizerCacheOpenGL::RecreateSurface(const Surface& old_surface,
1327 } 1356 }
1328 1357
1329 return new_surface; 1358 return new_surface;
1330} // namespace OpenGL 1359}
1331 1360
1332Surface RasterizerCacheOpenGL::TryFindFramebufferSurface(VAddr addr) const { 1361Surface RasterizerCacheOpenGL::TryFindFramebufferSurface(VAddr addr) const {
1333 return TryGet(addr); 1362 return TryGet(addr);
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.h b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
index 6a49880c2..494f6b903 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
@@ -7,6 +7,7 @@
7#include <array> 7#include <array>
8#include <map> 8#include <map>
9#include <memory> 9#include <memory>
10#include <string>
10#include <vector> 11#include <vector>
11 12
12#include "common/alignment.h" 13#include "common/alignment.h"
@@ -18,6 +19,7 @@
18#include "video_core/rasterizer_cache.h" 19#include "video_core/rasterizer_cache.h"
19#include "video_core/renderer_opengl/gl_resource_manager.h" 20#include "video_core/renderer_opengl/gl_resource_manager.h"
20#include "video_core/renderer_opengl/gl_shader_gen.h" 21#include "video_core/renderer_opengl/gl_shader_gen.h"
22#include "video_core/surface.h"
21#include "video_core/textures/decoders.h" 23#include "video_core/textures/decoders.h"
22#include "video_core/textures/texture.h" 24#include "video_core/textures/texture.h"
23 25
@@ -27,135 +29,12 @@ class CachedSurface;
27using Surface = std::shared_ptr<CachedSurface>; 29using Surface = std::shared_ptr<CachedSurface>;
28using SurfaceSurfaceRect_Tuple = std::tuple<Surface, Surface, MathUtil::Rectangle<u32>>; 30using SurfaceSurfaceRect_Tuple = std::tuple<Surface, Surface, MathUtil::Rectangle<u32>>;
29 31
30struct SurfaceParams { 32using SurfaceTarget = VideoCore::Surface::SurfaceTarget;
31 enum class PixelFormat { 33using SurfaceType = VideoCore::Surface::SurfaceType;
32 ABGR8U = 0, 34using PixelFormat = VideoCore::Surface::PixelFormat;
33 ABGR8S = 1, 35using ComponentType = VideoCore::Surface::ComponentType;
34 ABGR8UI = 2,
35 B5G6R5U = 3,
36 A2B10G10R10U = 4,
37 A1B5G5R5U = 5,
38 R8U = 6,
39 R8UI = 7,
40 RGBA16F = 8,
41 RGBA16U = 9,
42 RGBA16UI = 10,
43 R11FG11FB10F = 11,
44 RGBA32UI = 12,
45 DXT1 = 13,
46 DXT23 = 14,
47 DXT45 = 15,
48 DXN1 = 16, // This is also known as BC4
49 DXN2UNORM = 17,
50 DXN2SNORM = 18,
51 BC7U = 19,
52 BC6H_UF16 = 20,
53 BC6H_SF16 = 21,
54 ASTC_2D_4X4 = 22,
55 G8R8U = 23,
56 G8R8S = 24,
57 BGRA8 = 25,
58 RGBA32F = 26,
59 RG32F = 27,
60 R32F = 28,
61 R16F = 29,
62 R16U = 30,
63 R16S = 31,
64 R16UI = 32,
65 R16I = 33,
66 RG16 = 34,
67 RG16F = 35,
68 RG16UI = 36,
69 RG16I = 37,
70 RG16S = 38,
71 RGB32F = 39,
72 RGBA8_SRGB = 40,
73 RG8U = 41,
74 RG8S = 42,
75 RG32UI = 43,
76 R32UI = 44,
77 ASTC_2D_8X8 = 45,
78 ASTC_2D_8X5 = 46,
79 ASTC_2D_5X4 = 47,
80 BGRA8_SRGB = 48,
81 DXT1_SRGB = 49,
82 DXT23_SRGB = 50,
83 DXT45_SRGB = 51,
84 BC7U_SRGB = 52,
85 ASTC_2D_4X4_SRGB = 53,
86 ASTC_2D_8X8_SRGB = 54,
87 ASTC_2D_8X5_SRGB = 55,
88 ASTC_2D_5X4_SRGB = 56,
89
90 MaxColorFormat,
91
92 // Depth formats
93 Z32F = 57,
94 Z16 = 58,
95
96 MaxDepthFormat,
97
98 // DepthStencil formats
99 Z24S8 = 59,
100 S8Z24 = 60,
101 Z32FS8 = 61,
102
103 MaxDepthStencilFormat,
104
105 Max = MaxDepthStencilFormat,
106 Invalid = 255,
107 };
108
109 static constexpr std::size_t MaxPixelFormat = static_cast<std::size_t>(PixelFormat::Max);
110
111 enum class ComponentType {
112 Invalid = 0,
113 SNorm = 1,
114 UNorm = 2,
115 SInt = 3,
116 UInt = 4,
117 Float = 5,
118 };
119
120 enum class SurfaceType {
121 ColorTexture = 0,
122 Depth = 1,
123 DepthStencil = 2,
124 Fill = 3,
125 Invalid = 4,
126 };
127
128 enum class SurfaceTarget {
129 Texture1D,
130 Texture2D,
131 Texture3D,
132 Texture1DArray,
133 Texture2DArray,
134 TextureCubemap,
135 };
136
137 static SurfaceTarget SurfaceTargetFromTextureType(Tegra::Texture::TextureType texture_type) {
138 switch (texture_type) {
139 case Tegra::Texture::TextureType::Texture1D:
140 return SurfaceTarget::Texture1D;
141 case Tegra::Texture::TextureType::Texture2D:
142 case Tegra::Texture::TextureType::Texture2DNoMipmap:
143 return SurfaceTarget::Texture2D;
144 case Tegra::Texture::TextureType::Texture3D:
145 return SurfaceTarget::Texture3D;
146 case Tegra::Texture::TextureType::TextureCubemap:
147 return SurfaceTarget::TextureCubemap;
148 case Tegra::Texture::TextureType::Texture1DArray:
149 return SurfaceTarget::Texture1DArray;
150 case Tegra::Texture::TextureType::Texture2DArray:
151 return SurfaceTarget::Texture2DArray;
152 default:
153 LOG_CRITICAL(HW_GPU, "Unimplemented texture_type={}", static_cast<u32>(texture_type));
154 UNREACHABLE();
155 return SurfaceTarget::Texture2D;
156 }
157 }
158 36
37struct SurfaceParams {
159 static std::string SurfaceTargetName(SurfaceTarget target) { 38 static std::string SurfaceTargetName(SurfaceTarget target) {
160 switch (target) { 39 switch (target) {
161 case SurfaceTarget::Texture1D: 40 case SurfaceTarget::Texture1D:
@@ -170,6 +49,8 @@ struct SurfaceParams {
170 return "Texture2DArray"; 49 return "Texture2DArray";
171 case SurfaceTarget::TextureCubemap: 50 case SurfaceTarget::TextureCubemap:
172 return "TextureCubemap"; 51 return "TextureCubemap";
52 case SurfaceTarget::TextureCubeArray:
53 return "TextureCubeArray";
173 default: 54 default:
174 LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target)); 55 LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target));
175 UNREACHABLE(); 56 UNREACHABLE();
@@ -177,664 +58,12 @@ struct SurfaceParams {
177 } 58 }
178 } 59 }
179 60
180 static bool SurfaceTargetIsLayered(SurfaceTarget target) {
181 switch (target) {
182 case SurfaceTarget::Texture1D:
183 case SurfaceTarget::Texture2D:
184 case SurfaceTarget::Texture3D:
185 return false;
186 case SurfaceTarget::Texture1DArray:
187 case SurfaceTarget::Texture2DArray:
188 case SurfaceTarget::TextureCubemap:
189 return true;
190 default:
191 LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target));
192 UNREACHABLE();
193 return false;
194 }
195 }
196
197 /**
198 * Gets the compression factor for the specified PixelFormat. This applies to just the
199 * "compressed width" and "compressed height", not the overall compression factor of a
200 * compressed image. This is used for maintaining proper surface sizes for compressed
201 * texture formats.
202 */
203 static constexpr u32 GetCompressionFactor(PixelFormat format) {
204 if (format == PixelFormat::Invalid)
205 return 0;
206
207 constexpr std::array<u32, MaxPixelFormat> compression_factor_table = {{
208 1, // ABGR8U
209 1, // ABGR8S
210 1, // ABGR8UI
211 1, // B5G6R5U
212 1, // A2B10G10R10U
213 1, // A1B5G5R5U
214 1, // R8U
215 1, // R8UI
216 1, // RGBA16F
217 1, // RGBA16U
218 1, // RGBA16UI
219 1, // R11FG11FB10F
220 1, // RGBA32UI
221 4, // DXT1
222 4, // DXT23
223 4, // DXT45
224 4, // DXN1
225 4, // DXN2UNORM
226 4, // DXN2SNORM
227 4, // BC7U
228 4, // BC6H_UF16
229 4, // BC6H_SF16
230 4, // ASTC_2D_4X4
231 1, // G8R8U
232 1, // G8R8S
233 1, // BGRA8
234 1, // RGBA32F
235 1, // RG32F
236 1, // R32F
237 1, // R16F
238 1, // R16U
239 1, // R16S
240 1, // R16UI
241 1, // R16I
242 1, // RG16
243 1, // RG16F
244 1, // RG16UI
245 1, // RG16I
246 1, // RG16S
247 1, // RGB32F
248 1, // RGBA8_SRGB
249 1, // RG8U
250 1, // RG8S
251 1, // RG32UI
252 1, // R32UI
253 4, // ASTC_2D_8X8
254 4, // ASTC_2D_8X5
255 4, // ASTC_2D_5X4
256 1, // BGRA8_SRGB
257 4, // DXT1_SRGB
258 4, // DXT23_SRGB
259 4, // DXT45_SRGB
260 4, // BC7U_SRGB
261 4, // ASTC_2D_4X4_SRGB
262 4, // ASTC_2D_8X8_SRGB
263 4, // ASTC_2D_8X5_SRGB
264 4, // ASTC_2D_5X4_SRGB
265 1, // Z32F
266 1, // Z16
267 1, // Z24S8
268 1, // S8Z24
269 1, // Z32FS8
270 }};
271
272 ASSERT(static_cast<std::size_t>(format) < compression_factor_table.size());
273 return compression_factor_table[static_cast<std::size_t>(format)];
274 }
275
276 static constexpr u32 GetDefaultBlockHeight(PixelFormat format) {
277 if (format == PixelFormat::Invalid)
278 return 0;
279 constexpr std::array<u32, MaxPixelFormat> block_height_table = {{
280 1, // ABGR8U
281 1, // ABGR8S
282 1, // ABGR8UI
283 1, // B5G6R5U
284 1, // A2B10G10R10U
285 1, // A1B5G5R5U
286 1, // R8U
287 1, // R8UI
288 1, // RGBA16F
289 1, // RGBA16U
290 1, // RGBA16UI
291 1, // R11FG11FB10F
292 1, // RGBA32UI
293 4, // DXT1
294 4, // DXT23
295 4, // DXT45
296 4, // DXN1
297 4, // DXN2UNORM
298 4, // DXN2SNORM
299 4, // BC7U
300 4, // BC6H_UF16
301 4, // BC6H_SF16
302 4, // ASTC_2D_4X4
303 1, // G8R8U
304 1, // G8R8S
305 1, // BGRA8
306 1, // RGBA32F
307 1, // RG32F
308 1, // R32F
309 1, // R16F
310 1, // R16U
311 1, // R16S
312 1, // R16UI
313 1, // R16I
314 1, // RG16
315 1, // RG16F
316 1, // RG16UI
317 1, // RG16I
318 1, // RG16S
319 1, // RGB32F
320 1, // RGBA8_SRGB
321 1, // RG8U
322 1, // RG8S
323 1, // RG32UI
324 1, // R32UI
325 8, // ASTC_2D_8X8
326 5, // ASTC_2D_8X5
327 4, // ASTC_2D_5X4
328 1, // BGRA8_SRGB
329 4, // DXT1_SRGB
330 4, // DXT23_SRGB
331 4, // DXT45_SRGB
332 4, // BC7U_SRGB
333 4, // ASTC_2D_4X4_SRGB
334 8, // ASTC_2D_8X8_SRGB
335 5, // ASTC_2D_8X5_SRGB
336 4, // ASTC_2D_5X4_SRGB
337 1, // Z32F
338 1, // Z16
339 1, // Z24S8
340 1, // S8Z24
341 1, // Z32FS8
342 }};
343 ASSERT(static_cast<std::size_t>(format) < block_height_table.size());
344 return block_height_table[static_cast<std::size_t>(format)];
345 }
346
347 static constexpr u32 GetFormatBpp(PixelFormat format) {
348 if (format == PixelFormat::Invalid)
349 return 0;
350
351 constexpr std::array<u32, MaxPixelFormat> bpp_table = {{
352 32, // ABGR8U
353 32, // ABGR8S
354 32, // ABGR8UI
355 16, // B5G6R5U
356 32, // A2B10G10R10U
357 16, // A1B5G5R5U
358 8, // R8U
359 8, // R8UI
360 64, // RGBA16F
361 64, // RGBA16U
362 64, // RGBA16UI
363 32, // R11FG11FB10F
364 128, // RGBA32UI
365 64, // DXT1
366 128, // DXT23
367 128, // DXT45
368 64, // DXN1
369 128, // DXN2UNORM
370 128, // DXN2SNORM
371 128, // BC7U
372 128, // BC6H_UF16
373 128, // BC6H_SF16
374 32, // ASTC_2D_4X4
375 16, // G8R8U
376 16, // G8R8S
377 32, // BGRA8
378 128, // RGBA32F
379 64, // RG32F
380 32, // R32F
381 16, // R16F
382 16, // R16U
383 16, // R16S
384 16, // R16UI
385 16, // R16I
386 32, // RG16
387 32, // RG16F
388 32, // RG16UI
389 32, // RG16I
390 32, // RG16S
391 96, // RGB32F
392 32, // RGBA8_SRGB
393 16, // RG8U
394 16, // RG8S
395 64, // RG32UI
396 32, // R32UI
397 16, // ASTC_2D_8X8
398 16, // ASTC_2D_8X5
399 32, // ASTC_2D_5X4
400 32, // BGRA8_SRGB
401 64, // DXT1_SRGB
402 128, // DXT23_SRGB
403 128, // DXT45_SRGB
404 128, // BC7U
405 32, // ASTC_2D_4X4_SRGB
406 16, // ASTC_2D_8X8_SRGB
407 16, // ASTC_2D_8X5_SRGB
408 32, // ASTC_2D_5X4_SRGB
409 32, // Z32F
410 16, // Z16
411 32, // Z24S8
412 32, // S8Z24
413 64, // Z32FS8
414 }};
415
416 ASSERT(static_cast<std::size_t>(format) < bpp_table.size());
417 return bpp_table[static_cast<std::size_t>(format)];
418 }
419
420 u32 GetFormatBpp() const { 61 u32 GetFormatBpp() const {
421 return GetFormatBpp(pixel_format); 62 return VideoCore::Surface::GetFormatBpp(pixel_format);
422 }
423
424 static PixelFormat PixelFormatFromDepthFormat(Tegra::DepthFormat format) {
425 switch (format) {
426 case Tegra::DepthFormat::S8_Z24_UNORM:
427 return PixelFormat::S8Z24;
428 case Tegra::DepthFormat::Z24_S8_UNORM:
429 return PixelFormat::Z24S8;
430 case Tegra::DepthFormat::Z32_FLOAT:
431 return PixelFormat::Z32F;
432 case Tegra::DepthFormat::Z16_UNORM:
433 return PixelFormat::Z16;
434 case Tegra::DepthFormat::Z32_S8_X24_FLOAT:
435 return PixelFormat::Z32FS8;
436 default:
437 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
438 UNREACHABLE();
439 }
440 }
441
442 static PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format) {
443 switch (format) {
444 // TODO (Hexagon12): Converting SRGBA to RGBA is a hack and doesn't completely correct the
445 // gamma.
446 case Tegra::RenderTargetFormat::RGBA8_SRGB:
447 return PixelFormat::RGBA8_SRGB;
448 case Tegra::RenderTargetFormat::RGBA8_UNORM:
449 return PixelFormat::ABGR8U;
450 case Tegra::RenderTargetFormat::RGBA8_SNORM:
451 return PixelFormat::ABGR8S;
452 case Tegra::RenderTargetFormat::RGBA8_UINT:
453 return PixelFormat::ABGR8UI;
454 case Tegra::RenderTargetFormat::BGRA8_SRGB:
455 return PixelFormat::BGRA8_SRGB;
456 case Tegra::RenderTargetFormat::BGRA8_UNORM:
457 return PixelFormat::BGRA8;
458 case Tegra::RenderTargetFormat::RGB10_A2_UNORM:
459 return PixelFormat::A2B10G10R10U;
460 case Tegra::RenderTargetFormat::RGBA16_FLOAT:
461 return PixelFormat::RGBA16F;
462 case Tegra::RenderTargetFormat::RGBA16_UNORM:
463 return PixelFormat::RGBA16U;
464 case Tegra::RenderTargetFormat::RGBA16_UINT:
465 return PixelFormat::RGBA16UI;
466 case Tegra::RenderTargetFormat::RGBA32_FLOAT:
467 return PixelFormat::RGBA32F;
468 case Tegra::RenderTargetFormat::RG32_FLOAT:
469 return PixelFormat::RG32F;
470 case Tegra::RenderTargetFormat::R11G11B10_FLOAT:
471 return PixelFormat::R11FG11FB10F;
472 case Tegra::RenderTargetFormat::B5G6R5_UNORM:
473 return PixelFormat::B5G6R5U;
474 case Tegra::RenderTargetFormat::BGR5A1_UNORM:
475 return PixelFormat::A1B5G5R5U;
476 case Tegra::RenderTargetFormat::RGBA32_UINT:
477 return PixelFormat::RGBA32UI;
478 case Tegra::RenderTargetFormat::R8_UNORM:
479 return PixelFormat::R8U;
480 case Tegra::RenderTargetFormat::R8_UINT:
481 return PixelFormat::R8UI;
482 case Tegra::RenderTargetFormat::RG16_FLOAT:
483 return PixelFormat::RG16F;
484 case Tegra::RenderTargetFormat::RG16_UINT:
485 return PixelFormat::RG16UI;
486 case Tegra::RenderTargetFormat::RG16_SINT:
487 return PixelFormat::RG16I;
488 case Tegra::RenderTargetFormat::RG16_UNORM:
489 return PixelFormat::RG16;
490 case Tegra::RenderTargetFormat::RG16_SNORM:
491 return PixelFormat::RG16S;
492 case Tegra::RenderTargetFormat::RG8_UNORM:
493 return PixelFormat::RG8U;
494 case Tegra::RenderTargetFormat::RG8_SNORM:
495 return PixelFormat::RG8S;
496 case Tegra::RenderTargetFormat::R16_FLOAT:
497 return PixelFormat::R16F;
498 case Tegra::RenderTargetFormat::R16_UNORM:
499 return PixelFormat::R16U;
500 case Tegra::RenderTargetFormat::R16_SNORM:
501 return PixelFormat::R16S;
502 case Tegra::RenderTargetFormat::R16_UINT:
503 return PixelFormat::R16UI;
504 case Tegra::RenderTargetFormat::R16_SINT:
505 return PixelFormat::R16I;
506 case Tegra::RenderTargetFormat::R32_FLOAT:
507 return PixelFormat::R32F;
508 case Tegra::RenderTargetFormat::R32_UINT:
509 return PixelFormat::R32UI;
510 case Tegra::RenderTargetFormat::RG32_UINT:
511 return PixelFormat::RG32UI;
512 default:
513 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
514 UNREACHABLE();
515 }
516 }
517
518 static PixelFormat PixelFormatFromTextureFormat(Tegra::Texture::TextureFormat format,
519 Tegra::Texture::ComponentType component_type,
520 bool is_srgb) {
521 // TODO(Subv): Properly implement this
522 switch (format) {
523 case Tegra::Texture::TextureFormat::A8R8G8B8:
524 if (is_srgb) {
525 return PixelFormat::RGBA8_SRGB;
526 }
527 switch (component_type) {
528 case Tegra::Texture::ComponentType::UNORM:
529 return PixelFormat::ABGR8U;
530 case Tegra::Texture::ComponentType::SNORM:
531 return PixelFormat::ABGR8S;
532 case Tegra::Texture::ComponentType::UINT:
533 return PixelFormat::ABGR8UI;
534 }
535 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
536 static_cast<u32>(component_type));
537 UNREACHABLE();
538 case Tegra::Texture::TextureFormat::B5G6R5:
539 switch (component_type) {
540 case Tegra::Texture::ComponentType::UNORM:
541 return PixelFormat::B5G6R5U;
542 }
543 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
544 static_cast<u32>(component_type));
545 UNREACHABLE();
546 case Tegra::Texture::TextureFormat::A2B10G10R10:
547 switch (component_type) {
548 case Tegra::Texture::ComponentType::UNORM:
549 return PixelFormat::A2B10G10R10U;
550 }
551 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
552 static_cast<u32>(component_type));
553 UNREACHABLE();
554 case Tegra::Texture::TextureFormat::A1B5G5R5:
555 switch (component_type) {
556 case Tegra::Texture::ComponentType::UNORM:
557 return PixelFormat::A1B5G5R5U;
558 }
559 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
560 static_cast<u32>(component_type));
561 UNREACHABLE();
562 case Tegra::Texture::TextureFormat::R8:
563 switch (component_type) {
564 case Tegra::Texture::ComponentType::UNORM:
565 return PixelFormat::R8U;
566 case Tegra::Texture::ComponentType::UINT:
567 return PixelFormat::R8UI;
568 }
569 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
570 static_cast<u32>(component_type));
571 UNREACHABLE();
572 case Tegra::Texture::TextureFormat::G8R8:
573 switch (component_type) {
574 case Tegra::Texture::ComponentType::UNORM:
575 return PixelFormat::G8R8U;
576 case Tegra::Texture::ComponentType::SNORM:
577 return PixelFormat::G8R8S;
578 }
579 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
580 static_cast<u32>(component_type));
581 UNREACHABLE();
582 case Tegra::Texture::TextureFormat::R16_G16_B16_A16:
583 switch (component_type) {
584 case Tegra::Texture::ComponentType::UNORM:
585 return PixelFormat::RGBA16U;
586 case Tegra::Texture::ComponentType::FLOAT:
587 return PixelFormat::RGBA16F;
588 }
589 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
590 static_cast<u32>(component_type));
591 UNREACHABLE();
592 case Tegra::Texture::TextureFormat::BF10GF11RF11:
593 switch (component_type) {
594 case Tegra::Texture::ComponentType::FLOAT:
595 return PixelFormat::R11FG11FB10F;
596 }
597 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
598 static_cast<u32>(component_type));
599 UNREACHABLE();
600 case Tegra::Texture::TextureFormat::R32_G32_B32_A32:
601 switch (component_type) {
602 case Tegra::Texture::ComponentType::FLOAT:
603 return PixelFormat::RGBA32F;
604 case Tegra::Texture::ComponentType::UINT:
605 return PixelFormat::RGBA32UI;
606 }
607 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
608 static_cast<u32>(component_type));
609 UNREACHABLE();
610 case Tegra::Texture::TextureFormat::R32_G32:
611 switch (component_type) {
612 case Tegra::Texture::ComponentType::FLOAT:
613 return PixelFormat::RG32F;
614 case Tegra::Texture::ComponentType::UINT:
615 return PixelFormat::RG32UI;
616 }
617 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
618 static_cast<u32>(component_type));
619 UNREACHABLE();
620 case Tegra::Texture::TextureFormat::R32_G32_B32:
621 switch (component_type) {
622 case Tegra::Texture::ComponentType::FLOAT:
623 return PixelFormat::RGB32F;
624 }
625 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
626 static_cast<u32>(component_type));
627 UNREACHABLE();
628 case Tegra::Texture::TextureFormat::R16:
629 switch (component_type) {
630 case Tegra::Texture::ComponentType::FLOAT:
631 return PixelFormat::R16F;
632 case Tegra::Texture::ComponentType::UNORM:
633 return PixelFormat::R16U;
634 case Tegra::Texture::ComponentType::SNORM:
635 return PixelFormat::R16S;
636 case Tegra::Texture::ComponentType::UINT:
637 return PixelFormat::R16UI;
638 case Tegra::Texture::ComponentType::SINT:
639 return PixelFormat::R16I;
640 }
641 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
642 static_cast<u32>(component_type));
643 UNREACHABLE();
644 case Tegra::Texture::TextureFormat::R32:
645 switch (component_type) {
646 case Tegra::Texture::ComponentType::FLOAT:
647 return PixelFormat::R32F;
648 case Tegra::Texture::ComponentType::UINT:
649 return PixelFormat::R32UI;
650 }
651 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
652 static_cast<u32>(component_type));
653 UNREACHABLE();
654 case Tegra::Texture::TextureFormat::ZF32:
655 return PixelFormat::Z32F;
656 case Tegra::Texture::TextureFormat::Z16:
657 return PixelFormat::Z16;
658 case Tegra::Texture::TextureFormat::Z24S8:
659 return PixelFormat::Z24S8;
660 case Tegra::Texture::TextureFormat::DXT1:
661 return is_srgb ? PixelFormat::DXT1_SRGB : PixelFormat::DXT1;
662 case Tegra::Texture::TextureFormat::DXT23:
663 return is_srgb ? PixelFormat::DXT23_SRGB : PixelFormat::DXT23;
664 case Tegra::Texture::TextureFormat::DXT45:
665 return is_srgb ? PixelFormat::DXT45_SRGB : PixelFormat::DXT45;
666 case Tegra::Texture::TextureFormat::DXN1:
667 return PixelFormat::DXN1;
668 case Tegra::Texture::TextureFormat::DXN2:
669 switch (component_type) {
670 case Tegra::Texture::ComponentType::UNORM:
671 return PixelFormat::DXN2UNORM;
672 case Tegra::Texture::ComponentType::SNORM:
673 return PixelFormat::DXN2SNORM;
674 }
675 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
676 static_cast<u32>(component_type));
677 UNREACHABLE();
678 case Tegra::Texture::TextureFormat::BC7U:
679 return is_srgb ? PixelFormat::BC7U_SRGB : PixelFormat::BC7U;
680 case Tegra::Texture::TextureFormat::BC6H_UF16:
681 return PixelFormat::BC6H_UF16;
682 case Tegra::Texture::TextureFormat::BC6H_SF16:
683 return PixelFormat::BC6H_SF16;
684 case Tegra::Texture::TextureFormat::ASTC_2D_4X4:
685 return is_srgb ? PixelFormat::ASTC_2D_4X4_SRGB : PixelFormat::ASTC_2D_4X4;
686 case Tegra::Texture::TextureFormat::ASTC_2D_5X4:
687 return is_srgb ? PixelFormat::ASTC_2D_5X4_SRGB : PixelFormat::ASTC_2D_5X4;
688 case Tegra::Texture::TextureFormat::ASTC_2D_8X8:
689 return is_srgb ? PixelFormat::ASTC_2D_8X8_SRGB : PixelFormat::ASTC_2D_8X8;
690 case Tegra::Texture::TextureFormat::ASTC_2D_8X5:
691 return is_srgb ? PixelFormat::ASTC_2D_8X5_SRGB : PixelFormat::ASTC_2D_8X5;
692 case Tegra::Texture::TextureFormat::R16_G16:
693 switch (component_type) {
694 case Tegra::Texture::ComponentType::FLOAT:
695 return PixelFormat::RG16F;
696 case Tegra::Texture::ComponentType::UNORM:
697 return PixelFormat::RG16;
698 case Tegra::Texture::ComponentType::SNORM:
699 return PixelFormat::RG16S;
700 case Tegra::Texture::ComponentType::UINT:
701 return PixelFormat::RG16UI;
702 case Tegra::Texture::ComponentType::SINT:
703 return PixelFormat::RG16I;
704 }
705 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}",
706 static_cast<u32>(component_type));
707 UNREACHABLE();
708 default:
709 LOG_CRITICAL(HW_GPU, "Unimplemented format={}, component_type={}",
710 static_cast<u32>(format), static_cast<u32>(component_type));
711 UNREACHABLE();
712 }
713 }
714
715 static ComponentType ComponentTypeFromTexture(Tegra::Texture::ComponentType type) {
716 // TODO(Subv): Implement more component types
717 switch (type) {
718 case Tegra::Texture::ComponentType::UNORM:
719 return ComponentType::UNorm;
720 case Tegra::Texture::ComponentType::FLOAT:
721 return ComponentType::Float;
722 case Tegra::Texture::ComponentType::SNORM:
723 return ComponentType::SNorm;
724 case Tegra::Texture::ComponentType::UINT:
725 return ComponentType::UInt;
726 case Tegra::Texture::ComponentType::SINT:
727 return ComponentType::SInt;
728 default:
729 LOG_CRITICAL(HW_GPU, "Unimplemented component type={}", static_cast<u32>(type));
730 UNREACHABLE();
731 }
732 }
733
734 static ComponentType ComponentTypeFromRenderTarget(Tegra::RenderTargetFormat format) {
735 // TODO(Subv): Implement more render targets
736 switch (format) {
737 case Tegra::RenderTargetFormat::RGBA8_UNORM:
738 case Tegra::RenderTargetFormat::RGBA8_SRGB:
739 case Tegra::RenderTargetFormat::BGRA8_UNORM:
740 case Tegra::RenderTargetFormat::BGRA8_SRGB:
741 case Tegra::RenderTargetFormat::RGB10_A2_UNORM:
742 case Tegra::RenderTargetFormat::R8_UNORM:
743 case Tegra::RenderTargetFormat::RG16_UNORM:
744 case Tegra::RenderTargetFormat::R16_UNORM:
745 case Tegra::RenderTargetFormat::B5G6R5_UNORM:
746 case Tegra::RenderTargetFormat::BGR5A1_UNORM:
747 case Tegra::RenderTargetFormat::RG8_UNORM:
748 case Tegra::RenderTargetFormat::RGBA16_UNORM:
749 return ComponentType::UNorm;
750 case Tegra::RenderTargetFormat::RGBA8_SNORM:
751 case Tegra::RenderTargetFormat::RG16_SNORM:
752 case Tegra::RenderTargetFormat::R16_SNORM:
753 case Tegra::RenderTargetFormat::RG8_SNORM:
754 return ComponentType::SNorm;
755 case Tegra::RenderTargetFormat::RGBA16_FLOAT:
756 case Tegra::RenderTargetFormat::R11G11B10_FLOAT:
757 case Tegra::RenderTargetFormat::RGBA32_FLOAT:
758 case Tegra::RenderTargetFormat::RG32_FLOAT:
759 case Tegra::RenderTargetFormat::RG16_FLOAT:
760 case Tegra::RenderTargetFormat::R16_FLOAT:
761 case Tegra::RenderTargetFormat::R32_FLOAT:
762 return ComponentType::Float;
763 case Tegra::RenderTargetFormat::RGBA32_UINT:
764 case Tegra::RenderTargetFormat::RGBA16_UINT:
765 case Tegra::RenderTargetFormat::RG16_UINT:
766 case Tegra::RenderTargetFormat::R8_UINT:
767 case Tegra::RenderTargetFormat::R16_UINT:
768 case Tegra::RenderTargetFormat::RG32_UINT:
769 case Tegra::RenderTargetFormat::R32_UINT:
770 case Tegra::RenderTargetFormat::RGBA8_UINT:
771 return ComponentType::UInt;
772 case Tegra::RenderTargetFormat::RG16_SINT:
773 case Tegra::RenderTargetFormat::R16_SINT:
774 return ComponentType::SInt;
775 default:
776 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
777 UNREACHABLE();
778 }
779 }
780
781 static PixelFormat PixelFormatFromGPUPixelFormat(Tegra::FramebufferConfig::PixelFormat format) {
782 switch (format) {
783 case Tegra::FramebufferConfig::PixelFormat::ABGR8:
784 return PixelFormat::ABGR8U;
785 default:
786 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
787 UNREACHABLE();
788 }
789 }
790
791 static ComponentType ComponentTypeFromDepthFormat(Tegra::DepthFormat format) {
792 switch (format) {
793 case Tegra::DepthFormat::Z16_UNORM:
794 case Tegra::DepthFormat::S8_Z24_UNORM:
795 case Tegra::DepthFormat::Z24_S8_UNORM:
796 return ComponentType::UNorm;
797 case Tegra::DepthFormat::Z32_FLOAT:
798 case Tegra::DepthFormat::Z32_S8_X24_FLOAT:
799 return ComponentType::Float;
800 default:
801 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
802 UNREACHABLE();
803 }
804 }
805
806 static SurfaceType GetFormatType(PixelFormat pixel_format) {
807 if (static_cast<std::size_t>(pixel_format) <
808 static_cast<std::size_t>(PixelFormat::MaxColorFormat)) {
809 return SurfaceType::ColorTexture;
810 }
811
812 if (static_cast<std::size_t>(pixel_format) <
813 static_cast<std::size_t>(PixelFormat::MaxDepthFormat)) {
814 return SurfaceType::Depth;
815 }
816
817 if (static_cast<std::size_t>(pixel_format) <
818 static_cast<std::size_t>(PixelFormat::MaxDepthStencilFormat)) {
819 return SurfaceType::DepthStencil;
820 }
821
822 // TODO(Subv): Implement the other formats
823 ASSERT(false);
824
825 return SurfaceType::Invalid;
826 }
827
828 /// Returns the sizer in bytes of the specified pixel format
829 static constexpr u32 GetBytesPerPixel(PixelFormat pixel_format) {
830 if (pixel_format == SurfaceParams::PixelFormat::Invalid) {
831 return 0;
832 }
833 return GetFormatBpp(pixel_format) / CHAR_BIT;
834 } 63 }
835 64
836 /// Returns the rectangle corresponding to this surface 65 /// Returns the rectangle corresponding to this surface
837 MathUtil::Rectangle<u32> GetRect() const; 66 MathUtil::Rectangle<u32> GetRect(u32 mip_level = 0) const;
838 67
839 /// Returns the total size of this surface in bytes, adjusted for compression 68 /// Returns the total size of this surface in bytes, adjusted for compression
840 std::size_t SizeInBytesRaw(bool ignore_tiled = false) const { 69 std::size_t SizeInBytesRaw(bool ignore_tiled = false) const {
@@ -865,7 +94,7 @@ struct SurfaceParams {
865 94
866 /// Returns the exact size of memory occupied by the texture in VRAM, including mipmaps. 95 /// Returns the exact size of memory occupied by the texture in VRAM, including mipmaps.
867 std::size_t MemorySize() const { 96 std::size_t MemorySize() const {
868 std::size_t size = InnerMemorySize(is_layered); 97 std::size_t size = InnerMemorySize(false, is_layered);
869 if (is_layered) 98 if (is_layered)
870 return size * depth; 99 return size * depth;
871 return size; 100 return size;
@@ -874,12 +103,78 @@ struct SurfaceParams {
874 /// Returns the exact size of the memory occupied by a layer in a texture in VRAM, including 103 /// Returns the exact size of the memory occupied by a layer in a texture in VRAM, including
875 /// mipmaps. 104 /// mipmaps.
876 std::size_t LayerMemorySize() const { 105 std::size_t LayerMemorySize() const {
877 return InnerMemorySize(true); 106 return InnerMemorySize(false, true);
878 } 107 }
879 108
880 /// Returns the size of a layer of this surface in OpenGL. 109 /// Returns the size of a layer of this surface in OpenGL.
881 std::size_t LayerSizeGL() const { 110 std::size_t LayerSizeGL(u32 mip_level) const {
882 return SizeInBytesRaw(true) / depth; 111 return InnerMipmapMemorySize(mip_level, true, is_layered, false);
112 }
113
114 std::size_t GetMipmapSizeGL(u32 mip_level, bool ignore_compressed = true) const {
115 std::size_t size = InnerMipmapMemorySize(mip_level, true, is_layered, ignore_compressed);
116 if (is_layered)
117 return size * depth;
118 return size;
119 }
120
121 std::size_t GetMipmapLevelOffset(u32 mip_level) const {
122 std::size_t offset = 0;
123 for (u32 i = 0; i < mip_level; i++)
124 offset += InnerMipmapMemorySize(i, false, is_layered);
125 return offset;
126 }
127
128 std::size_t GetMipmapLevelOffsetGL(u32 mip_level) const {
129 std::size_t offset = 0;
130 for (u32 i = 0; i < mip_level; i++)
131 offset += InnerMipmapMemorySize(i, true, is_layered);
132 return offset;
133 }
134
135 u32 MipWidth(u32 mip_level) const {
136 return std::max(1U, width >> mip_level);
137 }
138
139 u32 MipHeight(u32 mip_level) const {
140 return std::max(1U, height >> mip_level);
141 }
142
143 u32 MipDepth(u32 mip_level) const {
144 return is_layered ? depth : std::max(1U, depth >> mip_level);
145 }
146
147 // Auto block resizing algorithm from:
148 // https://cgit.freedesktop.org/mesa/mesa/tree/src/gallium/drivers/nouveau/nv50/nv50_miptree.c
149 u32 MipBlockHeight(u32 mip_level) const {
150 if (mip_level == 0)
151 return block_height;
152 u32 alt_height = MipHeight(mip_level);
153 u32 h = GetDefaultBlockHeight(pixel_format);
154 u32 blocks_in_y = (alt_height + h - 1) / h;
155 u32 bh = 16;
156 while (bh > 1 && blocks_in_y <= bh * 4) {
157 bh >>= 1;
158 }
159 return bh;
160 }
161
162 u32 MipBlockDepth(u32 mip_level) const {
163 if (mip_level == 0)
164 return block_depth;
165 if (is_layered)
166 return 1;
167 u32 depth = MipDepth(mip_level);
168 u32 bd = 32;
169 while (bd > 1 && depth * 2 <= bd) {
170 bd >>= 1;
171 }
172 if (bd == 32) {
173 u32 bh = MipBlockHeight(mip_level);
174 if (bh >= 4)
175 return 16;
176 }
177 return bd;
883 } 178 }
884 179
885 /// Creates SurfaceParams from a texture configuration 180 /// Creates SurfaceParams from a texture configuration
@@ -940,7 +235,10 @@ struct SurfaceParams {
940 } rt; 235 } rt;
941 236
942private: 237private:
943 std::size_t InnerMemorySize(bool layer_only = false) const; 238 std::size_t InnerMipmapMemorySize(u32 mip_level, bool force_gl = false, bool layer_only = false,
239 bool uncompressed = false) const;
240 std::size_t InnerMemorySize(bool force_gl = false, bool layer_only = false,
241 bool uncompressed = false) const;
944}; 242};
945 243
946}; // namespace OpenGL 244}; // namespace OpenGL
@@ -966,6 +264,8 @@ struct hash<SurfaceReserveKey> {
966 264
967namespace OpenGL { 265namespace OpenGL {
968 266
267class RasterizerOpenGL;
268
969class CachedSurface final : public RasterizerCacheObject { 269class CachedSurface final : public RasterizerCacheObject {
970public: 270public:
971 CachedSurface(const SurfaceParams& params); 271 CachedSurface(const SurfaceParams& params);
@@ -1002,8 +302,10 @@ public:
1002 void UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle); 302 void UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle);
1003 303
1004private: 304private:
305 void UploadGLMipmapTexture(u32 mip_map, GLuint read_fb_handle, GLuint draw_fb_handle);
306
1005 OGLTexture texture; 307 OGLTexture texture;
1006 std::vector<u8> gl_buffer; 308 std::vector<std::vector<u8>> gl_buffer;
1007 SurfaceParams params; 309 SurfaceParams params;
1008 GLenum gl_target; 310 GLenum gl_target;
1009 std::size_t cached_size_in_bytes; 311 std::size_t cached_size_in_bytes;
@@ -1011,7 +313,7 @@ private:
1011 313
1012class RasterizerCacheOpenGL final : public RasterizerCache<Surface> { 314class RasterizerCacheOpenGL final : public RasterizerCache<Surface> {
1013public: 315public:
1014 RasterizerCacheOpenGL(); 316 explicit RasterizerCacheOpenGL(RasterizerOpenGL& rasterizer);
1015 317
1016 /// Get a surface based on the texture configuration 318 /// Get a surface based on the texture configuration
1017 Surface GetTextureSurface(const Tegra::Texture::FullTextureInfo& config, 319 Surface GetTextureSurface(const Tegra::Texture::FullTextureInfo& config,
diff --git a/src/video_core/renderer_opengl/gl_resource_manager.cpp b/src/video_core/renderer_opengl/gl_resource_manager.cpp
new file mode 100644
index 000000000..c17d5ac00
--- /dev/null
+++ b/src/video_core/renderer_opengl/gl_resource_manager.cpp
@@ -0,0 +1,186 @@
1// Copyright 2015 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <utility>
6#include <glad/glad.h>
7#include "common/common_types.h"
8#include "common/microprofile.h"
9#include "video_core/renderer_opengl/gl_resource_manager.h"
10#include "video_core/renderer_opengl/gl_shader_util.h"
11#include "video_core/renderer_opengl/gl_state.h"
12
13MICROPROFILE_DEFINE(OpenGL_ResourceCreation, "OpenGL", "Resource Creation", MP_RGB(128, 128, 192));
14MICROPROFILE_DEFINE(OpenGL_ResourceDeletion, "OpenGL", "Resource Deletion", MP_RGB(128, 128, 192));
15
16namespace OpenGL {
17
18void OGLTexture::Create() {
19 if (handle != 0)
20 return;
21
22 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
23 glGenTextures(1, &handle);
24}
25
26void OGLTexture::Release() {
27 if (handle == 0)
28 return;
29
30 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
31 glDeleteTextures(1, &handle);
32 OpenGLState::GetCurState().UnbindTexture(handle).Apply();
33 handle = 0;
34}
35
36void OGLSampler::Create() {
37 if (handle != 0)
38 return;
39
40 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
41 glGenSamplers(1, &handle);
42}
43
44void OGLSampler::Release() {
45 if (handle == 0)
46 return;
47
48 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
49 glDeleteSamplers(1, &handle);
50 OpenGLState::GetCurState().ResetSampler(handle).Apply();
51 handle = 0;
52}
53
54void OGLShader::Create(const char* source, GLenum type) {
55 if (handle != 0)
56 return;
57 if (source == nullptr)
58 return;
59
60 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
61 handle = GLShader::LoadShader(source, type);
62}
63
64void OGLShader::Release() {
65 if (handle == 0)
66 return;
67
68 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
69 glDeleteShader(handle);
70 handle = 0;
71}
72
73void OGLProgram::CreateFromSource(const char* vert_shader, const char* geo_shader,
74 const char* frag_shader, bool separable_program) {
75 OGLShader vert, geo, frag;
76 if (vert_shader)
77 vert.Create(vert_shader, GL_VERTEX_SHADER);
78 if (geo_shader)
79 geo.Create(geo_shader, GL_GEOMETRY_SHADER);
80 if (frag_shader)
81 frag.Create(frag_shader, GL_FRAGMENT_SHADER);
82
83 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
84 Create(separable_program, vert.handle, geo.handle, frag.handle);
85}
86
87void OGLProgram::Release() {
88 if (handle == 0)
89 return;
90
91 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
92 glDeleteProgram(handle);
93 OpenGLState::GetCurState().ResetProgram(handle).Apply();
94 handle = 0;
95}
96
97void OGLPipeline::Create() {
98 if (handle != 0)
99 return;
100
101 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
102 glGenProgramPipelines(1, &handle);
103}
104
105void OGLPipeline::Release() {
106 if (handle == 0)
107 return;
108
109 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
110 glDeleteProgramPipelines(1, &handle);
111 OpenGLState::GetCurState().ResetPipeline(handle).Apply();
112 handle = 0;
113}
114
115void OGLBuffer::Create() {
116 if (handle != 0)
117 return;
118
119 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
120 glGenBuffers(1, &handle);
121}
122
123void OGLBuffer::Release() {
124 if (handle == 0)
125 return;
126
127 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
128 glDeleteBuffers(1, &handle);
129 OpenGLState::GetCurState().ResetBuffer(handle).Apply();
130 handle = 0;
131}
132
133void OGLSync::Create() {
134 if (handle != 0)
135 return;
136
137 // Don't profile here, this one is expected to happen ingame.
138 handle = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
139}
140
141void OGLSync::Release() {
142 if (handle == 0)
143 return;
144
145 // Don't profile here, this one is expected to happen ingame.
146 glDeleteSync(handle);
147 handle = 0;
148}
149
150void OGLVertexArray::Create() {
151 if (handle != 0)
152 return;
153
154 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
155 glGenVertexArrays(1, &handle);
156}
157
158void OGLVertexArray::Release() {
159 if (handle == 0)
160 return;
161
162 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
163 glDeleteVertexArrays(1, &handle);
164 OpenGLState::GetCurState().ResetVertexArray(handle).Apply();
165 handle = 0;
166}
167
168void OGLFramebuffer::Create() {
169 if (handle != 0)
170 return;
171
172 MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
173 glGenFramebuffers(1, &handle);
174}
175
176void OGLFramebuffer::Release() {
177 if (handle == 0)
178 return;
179
180 MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
181 glDeleteFramebuffers(1, &handle);
182 OpenGLState::GetCurState().ResetFramebuffer(handle).Apply();
183 handle = 0;
184}
185
186} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_resource_manager.h b/src/video_core/renderer_opengl/gl_resource_manager.h
index 3bc1b83b5..e33f1e973 100644
--- a/src/video_core/renderer_opengl/gl_resource_manager.h
+++ b/src/video_core/renderer_opengl/gl_resource_manager.h
@@ -8,7 +8,6 @@
8#include <glad/glad.h> 8#include <glad/glad.h>
9#include "common/common_types.h" 9#include "common/common_types.h"
10#include "video_core/renderer_opengl/gl_shader_util.h" 10#include "video_core/renderer_opengl/gl_shader_util.h"
11#include "video_core/renderer_opengl/gl_state.h"
12 11
13namespace OpenGL { 12namespace OpenGL {
14 13
@@ -29,20 +28,10 @@ public:
29 } 28 }
30 29
31 /// Creates a new internal OpenGL resource and stores the handle 30 /// Creates a new internal OpenGL resource and stores the handle
32 void Create() { 31 void Create();
33 if (handle != 0)
34 return;
35 glGenTextures(1, &handle);
36 }
37 32
38 /// Deletes the internal OpenGL resource 33 /// Deletes the internal OpenGL resource
39 void Release() { 34 void Release();
40 if (handle == 0)
41 return;
42 glDeleteTextures(1, &handle);
43 OpenGLState::GetCurState().UnbindTexture(handle).Apply();
44 handle = 0;
45 }
46 35
47 GLuint handle = 0; 36 GLuint handle = 0;
48}; 37};
@@ -64,20 +53,10 @@ public:
64 } 53 }
65 54
66 /// Creates a new internal OpenGL resource and stores the handle 55 /// Creates a new internal OpenGL resource and stores the handle
67 void Create() { 56 void Create();
68 if (handle != 0)
69 return;
70 glGenSamplers(1, &handle);
71 }
72 57
73 /// Deletes the internal OpenGL resource 58 /// Deletes the internal OpenGL resource
74 void Release() { 59 void Release();
75 if (handle == 0)
76 return;
77 glDeleteSamplers(1, &handle);
78 OpenGLState::GetCurState().ResetSampler(handle).Apply();
79 handle = 0;
80 }
81 60
82 GLuint handle = 0; 61 GLuint handle = 0;
83}; 62};
@@ -98,20 +77,9 @@ public:
98 return *this; 77 return *this;
99 } 78 }
100 79
101 void Create(const char* source, GLenum type) { 80 void Create(const char* source, GLenum type);
102 if (handle != 0)
103 return;
104 if (source == nullptr)
105 return;
106 handle = GLShader::LoadShader(source, type);
107 }
108 81
109 void Release() { 82 void Release();
110 if (handle == 0)
111 return;
112 glDeleteShader(handle);
113 handle = 0;
114 }
115 83
116 GLuint handle = 0; 84 GLuint handle = 0;
117}; 85};
@@ -141,25 +109,10 @@ public:
141 109
142 /// Creates a new internal OpenGL resource and stores the handle 110 /// Creates a new internal OpenGL resource and stores the handle
143 void CreateFromSource(const char* vert_shader, const char* geo_shader, const char* frag_shader, 111 void CreateFromSource(const char* vert_shader, const char* geo_shader, const char* frag_shader,
144 bool separable_program = false) { 112 bool separable_program = false);
145 OGLShader vert, geo, frag;
146 if (vert_shader)
147 vert.Create(vert_shader, GL_VERTEX_SHADER);
148 if (geo_shader)
149 geo.Create(geo_shader, GL_GEOMETRY_SHADER);
150 if (frag_shader)
151 frag.Create(frag_shader, GL_FRAGMENT_SHADER);
152 Create(separable_program, vert.handle, geo.handle, frag.handle);
153 }
154 113
155 /// Deletes the internal OpenGL resource 114 /// Deletes the internal OpenGL resource
156 void Release() { 115 void Release();
157 if (handle == 0)
158 return;
159 glDeleteProgram(handle);
160 OpenGLState::GetCurState().ResetProgram(handle).Apply();
161 handle = 0;
162 }
163 116
164 GLuint handle = 0; 117 GLuint handle = 0;
165}; 118};
@@ -178,20 +131,10 @@ public:
178 } 131 }
179 132
180 /// Creates a new internal OpenGL resource and stores the handle 133 /// Creates a new internal OpenGL resource and stores the handle
181 void Create() { 134 void Create();
182 if (handle != 0)
183 return;
184 glGenProgramPipelines(1, &handle);
185 }
186 135
187 /// Deletes the internal OpenGL resource 136 /// Deletes the internal OpenGL resource
188 void Release() { 137 void Release();
189 if (handle == 0)
190 return;
191 glDeleteProgramPipelines(1, &handle);
192 OpenGLState::GetCurState().ResetPipeline(handle).Apply();
193 handle = 0;
194 }
195 138
196 GLuint handle = 0; 139 GLuint handle = 0;
197}; 140};
@@ -213,20 +156,10 @@ public:
213 } 156 }
214 157
215 /// Creates a new internal OpenGL resource and stores the handle 158 /// Creates a new internal OpenGL resource and stores the handle
216 void Create() { 159 void Create();
217 if (handle != 0)
218 return;
219 glGenBuffers(1, &handle);
220 }
221 160
222 /// Deletes the internal OpenGL resource 161 /// Deletes the internal OpenGL resource
223 void Release() { 162 void Release();
224 if (handle == 0)
225 return;
226 glDeleteBuffers(1, &handle);
227 OpenGLState::GetCurState().ResetBuffer(handle).Apply();
228 handle = 0;
229 }
230 163
231 GLuint handle = 0; 164 GLuint handle = 0;
232}; 165};
@@ -247,19 +180,10 @@ public:
247 } 180 }
248 181
249 /// Creates a new internal OpenGL resource and stores the handle 182 /// Creates a new internal OpenGL resource and stores the handle
250 void Create() { 183 void Create();
251 if (handle != 0)
252 return;
253 handle = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
254 }
255 184
256 /// Deletes the internal OpenGL resource 185 /// Deletes the internal OpenGL resource
257 void Release() { 186 void Release();
258 if (handle == 0)
259 return;
260 glDeleteSync(handle);
261 handle = 0;
262 }
263 187
264 GLsync handle = 0; 188 GLsync handle = 0;
265}; 189};
@@ -281,20 +205,10 @@ public:
281 } 205 }
282 206
283 /// Creates a new internal OpenGL resource and stores the handle 207 /// Creates a new internal OpenGL resource and stores the handle
284 void Create() { 208 void Create();
285 if (handle != 0)
286 return;
287 glGenVertexArrays(1, &handle);
288 }
289 209
290 /// Deletes the internal OpenGL resource 210 /// Deletes the internal OpenGL resource
291 void Release() { 211 void Release();
292 if (handle == 0)
293 return;
294 glDeleteVertexArrays(1, &handle);
295 OpenGLState::GetCurState().ResetVertexArray(handle).Apply();
296 handle = 0;
297 }
298 212
299 GLuint handle = 0; 213 GLuint handle = 0;
300}; 214};
@@ -316,20 +230,10 @@ public:
316 } 230 }
317 231
318 /// Creates a new internal OpenGL resource and stores the handle 232 /// Creates a new internal OpenGL resource and stores the handle
319 void Create() { 233 void Create();
320 if (handle != 0)
321 return;
322 glGenFramebuffers(1, &handle);
323 }
324 234
325 /// Deletes the internal OpenGL resource 235 /// Deletes the internal OpenGL resource
326 void Release() { 236 void Release();
327 if (handle == 0)
328 return;
329 glDeleteFramebuffers(1, &handle);
330 OpenGLState::GetCurState().ResetFramebuffer(handle).Apply();
331 handle = 0;
332 }
333 237
334 GLuint handle = 0; 238 GLuint handle = 0;
335}; 239};
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.cpp b/src/video_core/renderer_opengl/gl_shader_cache.cpp
index 9522fd344..a85a7c0c5 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_cache.cpp
@@ -6,10 +6,10 @@
6#include "core/core.h" 6#include "core/core.h"
7#include "core/memory.h" 7#include "core/memory.h"
8#include "video_core/engines/maxwell_3d.h" 8#include "video_core/engines/maxwell_3d.h"
9#include "video_core/renderer_opengl/gl_rasterizer.h"
9#include "video_core/renderer_opengl/gl_shader_cache.h" 10#include "video_core/renderer_opengl/gl_shader_cache.h"
10#include "video_core/renderer_opengl/gl_shader_manager.h" 11#include "video_core/renderer_opengl/gl_shader_manager.h"
11#include "video_core/renderer_opengl/utils.h" 12#include "video_core/renderer_opengl/utils.h"
12#include "video_core/utils.h"
13 13
14namespace OpenGL { 14namespace OpenGL {
15 15
@@ -121,12 +121,16 @@ GLint CachedShader::GetUniformLocation(const GLShader::SamplerEntry& sampler) {
121} 121}
122 122
123GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program, 123GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program,
124 const std::string& glsl_topology, 124 const std::string& glsl_topology, u32 max_vertices,
125 const std::string& debug_name) { 125 const std::string& debug_name) {
126 if (target_program.handle != 0) { 126 if (target_program.handle != 0) {
127 return target_program.handle; 127 return target_program.handle;
128 } 128 }
129 const std::string source{geometry_programs.code + "layout (" + glsl_topology + ") in;\n"}; 129 std::string source = "#version 430 core\n";
130 source += "layout (" + glsl_topology + ") in;\n";
131 source += "#define MAX_VERTEX_INPUT " + std::to_string(max_vertices) + '\n';
132 source += geometry_programs.code;
133
130 OGLShader shader; 134 OGLShader shader;
131 shader.Create(source.c_str(), GL_GEOMETRY_SHADER); 135 shader.Create(source.c_str(), GL_GEOMETRY_SHADER);
132 target_program.Create(true, shader.handle); 136 target_program.Create(true, shader.handle);
@@ -135,6 +139,8 @@ GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program,
135 return target_program.handle; 139 return target_program.handle;
136}; 140};
137 141
142ShaderCacheOpenGL::ShaderCacheOpenGL(RasterizerOpenGL& rasterizer) : RasterizerCache{rasterizer} {}
143
138Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) { 144Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) {
139 const VAddr program_addr{GetShaderAddress(program)}; 145 const VAddr program_addr{GetShaderAddress(program)};
140 146
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.h b/src/video_core/renderer_opengl/gl_shader_cache.h
index a210f1731..ffbf21831 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.h
+++ b/src/video_core/renderer_opengl/gl_shader_cache.h
@@ -16,6 +16,8 @@
16namespace OpenGL { 16namespace OpenGL {
17 17
18class CachedShader; 18class CachedShader;
19class RasterizerOpenGL;
20
19using Shader = std::shared_ptr<CachedShader>; 21using Shader = std::shared_ptr<CachedShader>;
20using Maxwell = Tegra::Engines::Maxwell3D::Regs; 22using Maxwell = Tegra::Engines::Maxwell3D::Regs;
21 23
@@ -46,22 +48,23 @@ public:
46 } 48 }
47 switch (primitive_mode) { 49 switch (primitive_mode) {
48 case GL_POINTS: 50 case GL_POINTS:
49 return LazyGeometryProgram(geometry_programs.points, "points", "ShaderPoints"); 51 return LazyGeometryProgram(geometry_programs.points, "points", 1, "ShaderPoints");
50 case GL_LINES: 52 case GL_LINES:
51 case GL_LINE_STRIP: 53 case GL_LINE_STRIP:
52 return LazyGeometryProgram(geometry_programs.lines, "lines", "ShaderLines"); 54 return LazyGeometryProgram(geometry_programs.lines, "lines", 2, "ShaderLines");
53 case GL_LINES_ADJACENCY: 55 case GL_LINES_ADJACENCY:
54 case GL_LINE_STRIP_ADJACENCY: 56 case GL_LINE_STRIP_ADJACENCY:
55 return LazyGeometryProgram(geometry_programs.lines_adjacency, "lines_adjacency", 57 return LazyGeometryProgram(geometry_programs.lines_adjacency, "lines_adjacency", 4,
56 "ShaderLinesAdjacency"); 58 "ShaderLinesAdjacency");
57 case GL_TRIANGLES: 59 case GL_TRIANGLES:
58 case GL_TRIANGLE_STRIP: 60 case GL_TRIANGLE_STRIP:
59 case GL_TRIANGLE_FAN: 61 case GL_TRIANGLE_FAN:
60 return LazyGeometryProgram(geometry_programs.triangles, "triangles", "ShaderTriangles"); 62 return LazyGeometryProgram(geometry_programs.triangles, "triangles", 3,
63 "ShaderTriangles");
61 case GL_TRIANGLES_ADJACENCY: 64 case GL_TRIANGLES_ADJACENCY:
62 case GL_TRIANGLE_STRIP_ADJACENCY: 65 case GL_TRIANGLE_STRIP_ADJACENCY:
63 return LazyGeometryProgram(geometry_programs.triangles_adjacency, "triangles_adjacency", 66 return LazyGeometryProgram(geometry_programs.triangles_adjacency, "triangles_adjacency",
64 "ShaderLines"); 67 6, "ShaderTrianglesAdjacency");
65 default: 68 default:
66 UNREACHABLE_MSG("Unknown primitive mode."); 69 UNREACHABLE_MSG("Unknown primitive mode.");
67 } 70 }
@@ -76,7 +79,7 @@ public:
76private: 79private:
77 /// Generates a geometry shader or returns one that already exists. 80 /// Generates a geometry shader or returns one that already exists.
78 GLuint LazyGeometryProgram(OGLProgram& target_program, const std::string& glsl_topology, 81 GLuint LazyGeometryProgram(OGLProgram& target_program, const std::string& glsl_topology,
79 const std::string& debug_name); 82 u32 max_vertices, const std::string& debug_name);
80 83
81 VAddr addr; 84 VAddr addr;
82 Maxwell::ShaderProgram program_type; 85 Maxwell::ShaderProgram program_type;
@@ -104,6 +107,8 @@ private:
104 107
105class ShaderCacheOpenGL final : public RasterizerCache<Shader> { 108class ShaderCacheOpenGL final : public RasterizerCache<Shader> {
106public: 109public:
110 explicit ShaderCacheOpenGL(RasterizerOpenGL& rasterizer);
111
107 /// Gets the current specified shader stage program 112 /// Gets the current specified shader stage program
108 Shader GetStageProgram(Maxwell::ShaderProgram program); 113 Shader GetStageProgram(Maxwell::ShaderProgram program);
109}; 114};
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
index dcf6941b0..5fde22ad4 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
@@ -3,12 +3,12 @@
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <map> 5#include <map>
6#include <optional>
6#include <set> 7#include <set>
7#include <string> 8#include <string>
8#include <string_view> 9#include <string_view>
9#include <unordered_set> 10#include <unordered_set>
10 11
11#include <boost/optional.hpp>
12#include <fmt/format.h> 12#include <fmt/format.h>
13 13
14#include "common/assert.h" 14#include "common/assert.h"
@@ -144,7 +144,7 @@ private:
144 for (u32 offset = begin; offset != end && offset != PROGRAM_END; ++offset) { 144 for (u32 offset = begin; offset != end && offset != PROGRAM_END; ++offset) {
145 const Instruction instr = {program_code[offset]}; 145 const Instruction instr = {program_code[offset]};
146 if (const auto opcode = OpCode::Decode(instr)) { 146 if (const auto opcode = OpCode::Decode(instr)) {
147 switch (opcode->GetId()) { 147 switch (opcode->get().GetId()) {
148 case OpCode::Id::EXIT: { 148 case OpCode::Id::EXIT: {
149 // The EXIT instruction can be predicated, which means that the shader can 149 // The EXIT instruction can be predicated, which means that the shader can
150 // conditionally end on this instruction. We have to consider the case where the 150 // conditionally end on this instruction. We have to consider the case where the
@@ -373,6 +373,7 @@ public:
373 if (sets_cc) { 373 if (sets_cc) {
374 const std::string zero_condition = "( " + ConvertIntegerSize(value, size) + " == 0 )"; 374 const std::string zero_condition = "( " + ConvertIntegerSize(value, size) + " == 0 )";
375 SetInternalFlag(InternalFlag::ZeroFlag, zero_condition); 375 SetInternalFlag(InternalFlag::ZeroFlag, zero_condition);
376 LOG_WARNING(HW_GPU, "Control Codes Imcomplete.");
376 } 377 }
377 } 378 }
378 379
@@ -430,7 +431,7 @@ public:
430 */ 431 */
431 void SetRegisterToInputAttibute(const Register& reg, u64 elem, Attribute::Index attribute, 432 void SetRegisterToInputAttibute(const Register& reg, u64 elem, Attribute::Index attribute,
432 const Tegra::Shader::IpaMode& input_mode, 433 const Tegra::Shader::IpaMode& input_mode,
433 boost::optional<Register> vertex = {}) { 434 std::optional<Register> vertex = {}) {
434 const std::string dest = GetRegisterAsFloat(reg); 435 const std::string dest = GetRegisterAsFloat(reg);
435 const std::string src = GetInputAttribute(attribute, input_mode, vertex) + GetSwizzle(elem); 436 const std::string src = GetInputAttribute(attribute, input_mode, vertex) + GetSwizzle(elem);
436 shader.AddLine(dest + " = " + src + ';'); 437 shader.AddLine(dest + " = " + src + ';');
@@ -493,10 +494,10 @@ public:
493 // instruction for now. 494 // instruction for now.
494 if (stage == Maxwell3D::Regs::ShaderStage::Geometry) { 495 if (stage == Maxwell3D::Regs::ShaderStage::Geometry) {
495 // TODO(Rodrigo): nouveau sets some attributes after setting emitting a geometry 496 // TODO(Rodrigo): nouveau sets some attributes after setting emitting a geometry
496 // shader. These instructions use a dirty register as buffer index. To avoid some 497 // shader. These instructions use a dirty register as buffer index, to avoid some
497 // drivers from complaining for the out of boundary writes, guard them. 498 // drivers from complaining about out of boundary writes, guard them.
498 const std::string buf_index{"min(" + GetRegisterAsInteger(buf_reg) + ", " + 499 const std::string buf_index{"((" + GetRegisterAsInteger(buf_reg) + ") % " +
499 std::to_string(MAX_GEOMETRY_BUFFERS - 1) + ')'}; 500 std::to_string(MAX_GEOMETRY_BUFFERS) + ')'};
500 shader.AddLine("amem[" + buf_index + "][" + 501 shader.AddLine("amem[" + buf_index + "][" +
501 std::to_string(static_cast<u32>(attribute)) + ']' + 502 std::to_string(static_cast<u32>(attribute)) + ']' +
502 GetSwizzle(elem) + " = " + src + ';'); 503 GetSwizzle(elem) + " = " + src + ';');
@@ -807,10 +808,14 @@ private:
807 /// Generates code representing an input attribute register. 808 /// Generates code representing an input attribute register.
808 std::string GetInputAttribute(Attribute::Index attribute, 809 std::string GetInputAttribute(Attribute::Index attribute,
809 const Tegra::Shader::IpaMode& input_mode, 810 const Tegra::Shader::IpaMode& input_mode,
810 boost::optional<Register> vertex = {}) { 811 std::optional<Register> vertex = {}) {
811 auto GeometryPass = [&](const std::string& name) { 812 auto GeometryPass = [&](const std::string& name) {
812 if (stage == Maxwell3D::Regs::ShaderStage::Geometry && vertex) { 813 if (stage == Maxwell3D::Regs::ShaderStage::Geometry && vertex) {
813 return "gs_" + name + '[' + GetRegisterAsInteger(vertex.value(), 0, false) + ']'; 814 // TODO(Rodrigo): Guard geometry inputs against out of bound reads. Some games set
815 // an 0x80000000 index for those and the shader fails to build. Find out why this
816 // happens and what's its intent.
817 return "gs_" + name + '[' + GetRegisterAsInteger(*vertex, 0, false) +
818 " % MAX_VERTEX_INPUT]";
814 } 819 }
815 return name; 820 return name;
816 }; 821 };
@@ -1465,7 +1470,7 @@ private:
1465 } 1470 }
1466 1471
1467 shader.AddLine( 1472 shader.AddLine(
1468 fmt::format("// {}: {} (0x{:016x})", offset, opcode->GetName(), instr.value)); 1473 fmt::format("// {}: {} (0x{:016x})", offset, opcode->get().GetName(), instr.value));
1469 1474
1470 using Tegra::Shader::Pred; 1475 using Tegra::Shader::Pred;
1471 ASSERT_MSG(instr.pred.full_pred != Pred::NeverExecute, 1476 ASSERT_MSG(instr.pred.full_pred != Pred::NeverExecute,
@@ -1473,7 +1478,7 @@ private:
1473 1478
1474 // Some instructions (like SSY) don't have a predicate field, they are always 1479 // Some instructions (like SSY) don't have a predicate field, they are always
1475 // unconditionally executed. 1480 // unconditionally executed.
1476 bool can_be_predicated = OpCode::IsPredicatedInstruction(opcode->GetId()); 1481 bool can_be_predicated = OpCode::IsPredicatedInstruction(opcode->get().GetId());
1477 1482
1478 if (can_be_predicated && instr.pred.pred_index != static_cast<u64>(Pred::UnusedIndex)) { 1483 if (can_be_predicated && instr.pred.pred_index != static_cast<u64>(Pred::UnusedIndex)) {
1479 shader.AddLine("if (" + 1484 shader.AddLine("if (" +
@@ -1483,7 +1488,7 @@ private:
1483 ++shader.scope; 1488 ++shader.scope;
1484 } 1489 }
1485 1490
1486 switch (opcode->GetType()) { 1491 switch (opcode->get().GetType()) {
1487 case OpCode::Type::Arithmetic: { 1492 case OpCode::Type::Arithmetic: {
1488 std::string op_a = regs.GetRegisterAsFloat(instr.gpr8); 1493 std::string op_a = regs.GetRegisterAsFloat(instr.gpr8);
1489 1494
@@ -1500,7 +1505,7 @@ private:
1500 } 1505 }
1501 } 1506 }
1502 1507
1503 switch (opcode->GetId()) { 1508 switch (opcode->get().GetId()) {
1504 case OpCode::Id::MOV_C: 1509 case OpCode::Id::MOV_C:
1505 case OpCode::Id::MOV_R: { 1510 case OpCode::Id::MOV_R: {
1506 // MOV does not have neither 'abs' nor 'neg' bits. 1511 // MOV does not have neither 'abs' nor 'neg' bits.
@@ -1525,6 +1530,10 @@ private:
1525 1530
1526 regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " * " + op_b, 1, 1, 1531 regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " * " + op_b, 1, 1,
1527 instr.alu.saturate_d, 0, true); 1532 instr.alu.saturate_d, 0, true);
1533 if (instr.generates_cc) {
1534 LOG_CRITICAL(HW_GPU, "FMUL Generates an unhandled Control Code");
1535 UNREACHABLE();
1536 }
1528 break; 1537 break;
1529 } 1538 }
1530 case OpCode::Id::FADD_C: 1539 case OpCode::Id::FADD_C:
@@ -1535,6 +1544,10 @@ private:
1535 1544
1536 regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1, 1545 regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1,
1537 instr.alu.saturate_d, 0, true); 1546 instr.alu.saturate_d, 0, true);
1547 if (instr.generates_cc) {
1548 LOG_CRITICAL(HW_GPU, "FADD Generates an unhandled Control Code");
1549 UNREACHABLE();
1550 }
1538 break; 1551 break;
1539 } 1552 }
1540 case OpCode::Id::MUFU: { 1553 case OpCode::Id::MUFU: {
@@ -1588,6 +1601,10 @@ private:
1588 '(' + condition + ") ? min(" + parameters + ") : max(" + 1601 '(' + condition + ") ? min(" + parameters + ") : max(" +
1589 parameters + ')', 1602 parameters + ')',
1590 1, 1, false, 0, true); 1603 1, 1, false, 0, true);
1604 if (instr.generates_cc) {
1605 LOG_CRITICAL(HW_GPU, "FMNMX Generates an unhandled Control Code");
1606 UNREACHABLE();
1607 }
1591 break; 1608 break;
1592 } 1609 }
1593 case OpCode::Id::RRO_C: 1610 case OpCode::Id::RRO_C:
@@ -1600,14 +1617,15 @@ private:
1600 break; 1617 break;
1601 } 1618 }
1602 default: { 1619 default: {
1603 LOG_CRITICAL(HW_GPU, "Unhandled arithmetic instruction: {}", opcode->GetName()); 1620 LOG_CRITICAL(HW_GPU, "Unhandled arithmetic instruction: {}",
1621 opcode->get().GetName());
1604 UNREACHABLE(); 1622 UNREACHABLE();
1605 } 1623 }
1606 } 1624 }
1607 break; 1625 break;
1608 } 1626 }
1609 case OpCode::Type::ArithmeticImmediate: { 1627 case OpCode::Type::ArithmeticImmediate: {
1610 switch (opcode->GetId()) { 1628 switch (opcode->get().GetId()) {
1611 case OpCode::Id::MOV32_IMM: { 1629 case OpCode::Id::MOV32_IMM: {
1612 regs.SetRegisterToFloat(instr.gpr0, 0, GetImmediate32(instr), 1, 1); 1630 regs.SetRegisterToFloat(instr.gpr0, 0, GetImmediate32(instr), 1, 1);
1613 break; 1631 break;
@@ -1617,6 +1635,10 @@ private:
1617 regs.GetRegisterAsFloat(instr.gpr8) + " * " + 1635 regs.GetRegisterAsFloat(instr.gpr8) + " * " +
1618 GetImmediate32(instr), 1636 GetImmediate32(instr),
1619 1, 1, instr.fmul32.saturate, 0, true); 1637 1, 1, instr.fmul32.saturate, 0, true);
1638 if (instr.op_32.generates_cc) {
1639 LOG_CRITICAL(HW_GPU, "FMUL32 Generates an unhandled Control Code");
1640 UNREACHABLE();
1641 }
1620 break; 1642 break;
1621 } 1643 }
1622 case OpCode::Id::FADD32I: { 1644 case OpCode::Id::FADD32I: {
@@ -1640,6 +1662,10 @@ private:
1640 } 1662 }
1641 1663
1642 regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1, false, 0, true); 1664 regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1, false, 0, true);
1665 if (instr.op_32.generates_cc) {
1666 LOG_CRITICAL(HW_GPU, "FADD32 Generates an unhandled Control Code");
1667 UNREACHABLE();
1668 }
1643 break; 1669 break;
1644 } 1670 }
1645 } 1671 }
@@ -1651,7 +1677,7 @@ private:
1651 std::string op_a = instr.bfe.negate_a ? "-" : ""; 1677 std::string op_a = instr.bfe.negate_a ? "-" : "";
1652 op_a += regs.GetRegisterAsInteger(instr.gpr8); 1678 op_a += regs.GetRegisterAsInteger(instr.gpr8);
1653 1679
1654 switch (opcode->GetId()) { 1680 switch (opcode->get().GetId()) {
1655 case OpCode::Id::BFE_IMM: { 1681 case OpCode::Id::BFE_IMM: {
1656 std::string inner_shift = 1682 std::string inner_shift =
1657 '(' + op_a + " << " + std::to_string(instr.bfe.GetLeftShiftValue()) + ')'; 1683 '(' + op_a + " << " + std::to_string(instr.bfe.GetLeftShiftValue()) + ')';
@@ -1660,10 +1686,14 @@ private:
1660 std::to_string(instr.bfe.GetLeftShiftValue() + instr.bfe.shift_position) + ')'; 1686 std::to_string(instr.bfe.GetLeftShiftValue() + instr.bfe.shift_position) + ')';
1661 1687
1662 regs.SetRegisterToInteger(instr.gpr0, true, 0, outer_shift, 1, 1); 1688 regs.SetRegisterToInteger(instr.gpr0, true, 0, outer_shift, 1, 1);
1689 if (instr.generates_cc) {
1690 LOG_CRITICAL(HW_GPU, "BFE Generates an unhandled Control Code");
1691 UNREACHABLE();
1692 }
1663 break; 1693 break;
1664 } 1694 }
1665 default: { 1695 default: {
1666 LOG_CRITICAL(HW_GPU, "Unhandled BFE instruction: {}", opcode->GetName()); 1696 LOG_CRITICAL(HW_GPU, "Unhandled BFE instruction: {}", opcode->get().GetName());
1667 UNREACHABLE(); 1697 UNREACHABLE();
1668 } 1698 }
1669 } 1699 }
@@ -1685,7 +1715,7 @@ private:
1685 } 1715 }
1686 } 1716 }
1687 1717
1688 switch (opcode->GetId()) { 1718 switch (opcode->get().GetId()) {
1689 case OpCode::Id::SHR_C: 1719 case OpCode::Id::SHR_C:
1690 case OpCode::Id::SHR_R: 1720 case OpCode::Id::SHR_R:
1691 case OpCode::Id::SHR_IMM: { 1721 case OpCode::Id::SHR_IMM: {
@@ -1697,15 +1727,23 @@ private:
1697 // Cast to int is superfluous for arithmetic shift, it's only for a logical shift 1727 // Cast to int is superfluous for arithmetic shift, it's only for a logical shift
1698 regs.SetRegisterToInteger(instr.gpr0, true, 0, "int(" + op_a + " >> " + op_b + ')', 1728 regs.SetRegisterToInteger(instr.gpr0, true, 0, "int(" + op_a + " >> " + op_b + ')',
1699 1, 1); 1729 1, 1);
1730 if (instr.generates_cc) {
1731 LOG_CRITICAL(HW_GPU, "SHR Generates an unhandled Control Code");
1732 UNREACHABLE();
1733 }
1700 break; 1734 break;
1701 } 1735 }
1702 case OpCode::Id::SHL_C: 1736 case OpCode::Id::SHL_C:
1703 case OpCode::Id::SHL_R: 1737 case OpCode::Id::SHL_R:
1704 case OpCode::Id::SHL_IMM: 1738 case OpCode::Id::SHL_IMM:
1705 regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " << " + op_b, 1, 1); 1739 regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " << " + op_b, 1, 1);
1740 if (instr.generates_cc) {
1741 LOG_CRITICAL(HW_GPU, "SHL Generates an unhandled Control Code");
1742 UNREACHABLE();
1743 }
1706 break; 1744 break;
1707 default: { 1745 default: {
1708 LOG_CRITICAL(HW_GPU, "Unhandled shift instruction: {}", opcode->GetName()); 1746 LOG_CRITICAL(HW_GPU, "Unhandled shift instruction: {}", opcode->get().GetName());
1709 UNREACHABLE(); 1747 UNREACHABLE();
1710 } 1748 }
1711 } 1749 }
@@ -1715,13 +1753,17 @@ private:
1715 std::string op_a = regs.GetRegisterAsInteger(instr.gpr8); 1753 std::string op_a = regs.GetRegisterAsInteger(instr.gpr8);
1716 std::string op_b = std::to_string(instr.alu.imm20_32.Value()); 1754 std::string op_b = std::to_string(instr.alu.imm20_32.Value());
1717 1755
1718 switch (opcode->GetId()) { 1756 switch (opcode->get().GetId()) {
1719 case OpCode::Id::IADD32I: 1757 case OpCode::Id::IADD32I:
1720 if (instr.iadd32i.negate_a) 1758 if (instr.iadd32i.negate_a)
1721 op_a = "-(" + op_a + ')'; 1759 op_a = "-(" + op_a + ')';
1722 1760
1723 regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1, 1761 regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1,
1724 instr.iadd32i.saturate != 0); 1762 instr.iadd32i.saturate != 0);
1763 if (instr.op_32.generates_cc) {
1764 LOG_CRITICAL(HW_GPU, "IADD32 Generates an unhandled Control Code");
1765 UNREACHABLE();
1766 }
1725 break; 1767 break;
1726 case OpCode::Id::LOP32I: { 1768 case OpCode::Id::LOP32I: {
1727 if (instr.alu.lop32i.invert_a) 1769 if (instr.alu.lop32i.invert_a)
@@ -1733,11 +1775,15 @@ private:
1733 WriteLogicOperation(instr.gpr0, instr.alu.lop32i.operation, op_a, op_b, 1775 WriteLogicOperation(instr.gpr0, instr.alu.lop32i.operation, op_a, op_b,
1734 Tegra::Shader::PredicateResultMode::None, 1776 Tegra::Shader::PredicateResultMode::None,
1735 Tegra::Shader::Pred::UnusedIndex); 1777 Tegra::Shader::Pred::UnusedIndex);
1778 if (instr.op_32.generates_cc) {
1779 LOG_CRITICAL(HW_GPU, "LOP32I Generates an unhandled Control Code");
1780 UNREACHABLE();
1781 }
1736 break; 1782 break;
1737 } 1783 }
1738 default: { 1784 default: {
1739 LOG_CRITICAL(HW_GPU, "Unhandled ArithmeticIntegerImmediate instruction: {}", 1785 LOG_CRITICAL(HW_GPU, "Unhandled ArithmeticIntegerImmediate instruction: {}",
1740 opcode->GetName()); 1786 opcode->get().GetName());
1741 UNREACHABLE(); 1787 UNREACHABLE();
1742 } 1788 }
1743 } 1789 }
@@ -1757,7 +1803,7 @@ private:
1757 } 1803 }
1758 } 1804 }
1759 1805
1760 switch (opcode->GetId()) { 1806 switch (opcode->get().GetId()) {
1761 case OpCode::Id::IADD_C: 1807 case OpCode::Id::IADD_C:
1762 case OpCode::Id::IADD_R: 1808 case OpCode::Id::IADD_R:
1763 case OpCode::Id::IADD_IMM: { 1809 case OpCode::Id::IADD_IMM: {
@@ -1769,6 +1815,10 @@ private:
1769 1815
1770 regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1, 1816 regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1,
1771 instr.alu.saturate_d); 1817 instr.alu.saturate_d);
1818 if (instr.generates_cc) {
1819 LOG_CRITICAL(HW_GPU, "IADD Generates an unhandled Control Code");
1820 UNREACHABLE();
1821 }
1772 break; 1822 break;
1773 } 1823 }
1774 case OpCode::Id::IADD3_C: 1824 case OpCode::Id::IADD3_C:
@@ -1793,7 +1843,7 @@ private:
1793 } 1843 }
1794 }; 1844 };
1795 1845
1796 if (opcode->GetId() == OpCode::Id::IADD3_R) { 1846 if (opcode->get().GetId() == OpCode::Id::IADD3_R) {
1797 apply_height(instr.iadd3.height_a, op_a); 1847 apply_height(instr.iadd3.height_a, op_a);
1798 apply_height(instr.iadd3.height_b, op_b); 1848 apply_height(instr.iadd3.height_b, op_b);
1799 apply_height(instr.iadd3.height_c, op_c); 1849 apply_height(instr.iadd3.height_c, op_c);
@@ -1809,7 +1859,7 @@ private:
1809 op_c = "-(" + op_c + ')'; 1859 op_c = "-(" + op_c + ')';
1810 1860
1811 std::string result; 1861 std::string result;
1812 if (opcode->GetId() == OpCode::Id::IADD3_R) { 1862 if (opcode->get().GetId() == OpCode::Id::IADD3_R) {
1813 switch (instr.iadd3.mode) { 1863 switch (instr.iadd3.mode) {
1814 case Tegra::Shader::IAdd3Mode::RightShift: 1864 case Tegra::Shader::IAdd3Mode::RightShift:
1815 // TODO(tech4me): According to 1865 // TODO(tech4me): According to
@@ -1830,6 +1880,11 @@ private:
1830 } 1880 }
1831 1881
1832 regs.SetRegisterToInteger(instr.gpr0, true, 0, result, 1, 1); 1882 regs.SetRegisterToInteger(instr.gpr0, true, 0, result, 1, 1);
1883
1884 if (instr.generates_cc) {
1885 LOG_CRITICAL(HW_GPU, "IADD3 Generates an unhandled Control Code");
1886 UNREACHABLE();
1887 }
1833 break; 1888 break;
1834 } 1889 }
1835 case OpCode::Id::ISCADD_C: 1890 case OpCode::Id::ISCADD_C:
@@ -1845,6 +1900,10 @@ private:
1845 1900
1846 regs.SetRegisterToInteger(instr.gpr0, true, 0, 1901 regs.SetRegisterToInteger(instr.gpr0, true, 0,
1847 "((" + op_a + " << " + shift + ") + " + op_b + ')', 1, 1); 1902 "((" + op_a + " << " + shift + ") + " + op_b + ')', 1, 1);
1903 if (instr.generates_cc) {
1904 LOG_CRITICAL(HW_GPU, "ISCADD Generates an unhandled Control Code");
1905 UNREACHABLE();
1906 }
1848 break; 1907 break;
1849 } 1908 }
1850 case OpCode::Id::POPC_C: 1909 case OpCode::Id::POPC_C:
@@ -1876,6 +1935,10 @@ private:
1876 1935
1877 WriteLogicOperation(instr.gpr0, instr.alu.lop.operation, op_a, op_b, 1936 WriteLogicOperation(instr.gpr0, instr.alu.lop.operation, op_a, op_b,
1878 instr.alu.lop.pred_result_mode, instr.alu.lop.pred48); 1937 instr.alu.lop.pred_result_mode, instr.alu.lop.pred48);
1938 if (instr.generates_cc) {
1939 LOG_CRITICAL(HW_GPU, "LOP Generates an unhandled Control Code");
1940 UNREACHABLE();
1941 }
1879 break; 1942 break;
1880 } 1943 }
1881 case OpCode::Id::LOP3_C: 1944 case OpCode::Id::LOP3_C:
@@ -1884,13 +1947,17 @@ private:
1884 const std::string op_c = regs.GetRegisterAsInteger(instr.gpr39); 1947 const std::string op_c = regs.GetRegisterAsInteger(instr.gpr39);
1885 std::string lut; 1948 std::string lut;
1886 1949
1887 if (opcode->GetId() == OpCode::Id::LOP3_R) { 1950 if (opcode->get().GetId() == OpCode::Id::LOP3_R) {
1888 lut = '(' + std::to_string(instr.alu.lop3.GetImmLut28()) + ')'; 1951 lut = '(' + std::to_string(instr.alu.lop3.GetImmLut28()) + ')';
1889 } else { 1952 } else {
1890 lut = '(' + std::to_string(instr.alu.lop3.GetImmLut48()) + ')'; 1953 lut = '(' + std::to_string(instr.alu.lop3.GetImmLut48()) + ')';
1891 } 1954 }
1892 1955
1893 WriteLop3Instruction(instr.gpr0, op_a, op_b, op_c, lut); 1956 WriteLop3Instruction(instr.gpr0, op_a, op_b, op_c, lut);
1957 if (instr.generates_cc) {
1958 LOG_CRITICAL(HW_GPU, "LOP3 Generates an unhandled Control Code");
1959 UNREACHABLE();
1960 }
1894 break; 1961 break;
1895 } 1962 }
1896 case OpCode::Id::IMNMX_C: 1963 case OpCode::Id::IMNMX_C:
@@ -1905,6 +1972,10 @@ private:
1905 '(' + condition + ") ? min(" + parameters + ") : max(" + 1972 '(' + condition + ") ? min(" + parameters + ") : max(" +
1906 parameters + ')', 1973 parameters + ')',
1907 1, 1); 1974 1, 1);
1975 if (instr.generates_cc) {
1976 LOG_CRITICAL(HW_GPU, "IMNMX Generates an unhandled Control Code");
1977 UNREACHABLE();
1978 }
1908 break; 1979 break;
1909 } 1980 }
1910 case OpCode::Id::LEA_R2: 1981 case OpCode::Id::LEA_R2:
@@ -1914,7 +1985,7 @@ private:
1914 case OpCode::Id::LEA_HI: { 1985 case OpCode::Id::LEA_HI: {
1915 std::string op_c; 1986 std::string op_c;
1916 1987
1917 switch (opcode->GetId()) { 1988 switch (opcode->get().GetId()) {
1918 case OpCode::Id::LEA_R2: { 1989 case OpCode::Id::LEA_R2: {
1919 op_a = regs.GetRegisterAsInteger(instr.gpr20); 1990 op_a = regs.GetRegisterAsInteger(instr.gpr20);
1920 op_b = regs.GetRegisterAsInteger(instr.gpr39); 1991 op_b = regs.GetRegisterAsInteger(instr.gpr39);
@@ -1959,7 +2030,8 @@ private:
1959 op_b = regs.GetRegisterAsInteger(instr.gpr8); 2030 op_b = regs.GetRegisterAsInteger(instr.gpr8);
1960 op_a = std::to_string(instr.lea.imm.entry_a); 2031 op_a = std::to_string(instr.lea.imm.entry_a);
1961 op_c = std::to_string(instr.lea.imm.entry_b); 2032 op_c = std::to_string(instr.lea.imm.entry_b);
1962 LOG_CRITICAL(HW_GPU, "Unhandled LEA subinstruction: {}", opcode->GetName()); 2033 LOG_CRITICAL(HW_GPU, "Unhandled LEA subinstruction: {}",
2034 opcode->get().GetName());
1963 UNREACHABLE(); 2035 UNREACHABLE();
1964 } 2036 }
1965 } 2037 }
@@ -1974,7 +2046,7 @@ private:
1974 } 2046 }
1975 default: { 2047 default: {
1976 LOG_CRITICAL(HW_GPU, "Unhandled ArithmeticInteger instruction: {}", 2048 LOG_CRITICAL(HW_GPU, "Unhandled ArithmeticInteger instruction: {}",
1977 opcode->GetName()); 2049 opcode->get().GetName());
1978 UNREACHABLE(); 2050 UNREACHABLE();
1979 } 2051 }
1980 } 2052 }
@@ -1982,20 +2054,21 @@ private:
1982 break; 2054 break;
1983 } 2055 }
1984 case OpCode::Type::ArithmeticHalf: { 2056 case OpCode::Type::ArithmeticHalf: {
1985 if (opcode->GetId() == OpCode::Id::HADD2_C || opcode->GetId() == OpCode::Id::HADD2_R) { 2057 if (opcode->get().GetId() == OpCode::Id::HADD2_C ||
2058 opcode->get().GetId() == OpCode::Id::HADD2_R) {
1986 ASSERT_MSG(instr.alu_half.ftz == 0, "Unimplemented"); 2059 ASSERT_MSG(instr.alu_half.ftz == 0, "Unimplemented");
1987 } 2060 }
1988 const bool negate_a = 2061 const bool negate_a =
1989 opcode->GetId() != OpCode::Id::HMUL2_R && instr.alu_half.negate_a != 0; 2062 opcode->get().GetId() != OpCode::Id::HMUL2_R && instr.alu_half.negate_a != 0;
1990 const bool negate_b = 2063 const bool negate_b =
1991 opcode->GetId() != OpCode::Id::HMUL2_C && instr.alu_half.negate_b != 0; 2064 opcode->get().GetId() != OpCode::Id::HMUL2_C && instr.alu_half.negate_b != 0;
1992 2065
1993 const std::string op_a = 2066 const std::string op_a =
1994 GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.alu_half.type_a, 2067 GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.alu_half.type_a,
1995 instr.alu_half.abs_a != 0, negate_a); 2068 instr.alu_half.abs_a != 0, negate_a);
1996 2069
1997 std::string op_b; 2070 std::string op_b;
1998 switch (opcode->GetId()) { 2071 switch (opcode->get().GetId()) {
1999 case OpCode::Id::HADD2_C: 2072 case OpCode::Id::HADD2_C:
2000 case OpCode::Id::HMUL2_C: 2073 case OpCode::Id::HMUL2_C:
2001 op_b = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset, 2074 op_b = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
@@ -2013,7 +2086,7 @@ private:
2013 op_b = GetHalfFloat(op_b, instr.alu_half.type_b, instr.alu_half.abs_b != 0, negate_b); 2086 op_b = GetHalfFloat(op_b, instr.alu_half.type_b, instr.alu_half.abs_b != 0, negate_b);
2014 2087
2015 const std::string result = [&]() { 2088 const std::string result = [&]() {
2016 switch (opcode->GetId()) { 2089 switch (opcode->get().GetId()) {
2017 case OpCode::Id::HADD2_C: 2090 case OpCode::Id::HADD2_C:
2018 case OpCode::Id::HADD2_R: 2091 case OpCode::Id::HADD2_R:
2019 return '(' + op_a + " + " + op_b + ')'; 2092 return '(' + op_a + " + " + op_b + ')';
@@ -2021,7 +2094,8 @@ private:
2021 case OpCode::Id::HMUL2_R: 2094 case OpCode::Id::HMUL2_R:
2022 return '(' + op_a + " * " + op_b + ')'; 2095 return '(' + op_a + " * " + op_b + ')';
2023 default: 2096 default:
2024 LOG_CRITICAL(HW_GPU, "Unhandled half float instruction: {}", opcode->GetName()); 2097 LOG_CRITICAL(HW_GPU, "Unhandled half float instruction: {}",
2098 opcode->get().GetName());
2025 UNREACHABLE(); 2099 UNREACHABLE();
2026 return std::string("0"); 2100 return std::string("0");
2027 } 2101 }
@@ -2032,7 +2106,7 @@ private:
2032 break; 2106 break;
2033 } 2107 }
2034 case OpCode::Type::ArithmeticHalfImmediate: { 2108 case OpCode::Type::ArithmeticHalfImmediate: {
2035 if (opcode->GetId() == OpCode::Id::HADD2_IMM) { 2109 if (opcode->get().GetId() == OpCode::Id::HADD2_IMM) {
2036 ASSERT_MSG(instr.alu_half_imm.ftz == 0, "Unimplemented"); 2110 ASSERT_MSG(instr.alu_half_imm.ftz == 0, "Unimplemented");
2037 } else { 2111 } else {
2038 ASSERT_MSG(instr.alu_half_imm.precision == Tegra::Shader::HalfPrecision::None, 2112 ASSERT_MSG(instr.alu_half_imm.precision == Tegra::Shader::HalfPrecision::None,
@@ -2046,7 +2120,7 @@ private:
2046 const std::string op_b = UnpackHalfImmediate(instr, true); 2120 const std::string op_b = UnpackHalfImmediate(instr, true);
2047 2121
2048 const std::string result = [&]() { 2122 const std::string result = [&]() {
2049 switch (opcode->GetId()) { 2123 switch (opcode->get().GetId()) {
2050 case OpCode::Id::HADD2_IMM: 2124 case OpCode::Id::HADD2_IMM:
2051 return op_a + " + " + op_b; 2125 return op_a + " + " + op_b;
2052 case OpCode::Id::HMUL2_IMM: 2126 case OpCode::Id::HMUL2_IMM:
@@ -2072,7 +2146,7 @@ private:
2072 ASSERT_MSG(instr.ffma.tab5980_1 == 0, "FFMA tab5980_1({}) not implemented", 2146 ASSERT_MSG(instr.ffma.tab5980_1 == 0, "FFMA tab5980_1({}) not implemented",
2073 instr.ffma.tab5980_1.Value()); 2147 instr.ffma.tab5980_1.Value());
2074 2148
2075 switch (opcode->GetId()) { 2149 switch (opcode->get().GetId()) {
2076 case OpCode::Id::FFMA_CR: { 2150 case OpCode::Id::FFMA_CR: {
2077 op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset, 2151 op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
2078 GLSLRegister::Type::Float); 2152 GLSLRegister::Type::Float);
@@ -2096,25 +2170,29 @@ private:
2096 break; 2170 break;
2097 } 2171 }
2098 default: { 2172 default: {
2099 LOG_CRITICAL(HW_GPU, "Unhandled FFMA instruction: {}", opcode->GetName()); 2173 LOG_CRITICAL(HW_GPU, "Unhandled FFMA instruction: {}", opcode->get().GetName());
2100 UNREACHABLE(); 2174 UNREACHABLE();
2101 } 2175 }
2102 } 2176 }
2103 2177
2104 regs.SetRegisterToFloat(instr.gpr0, 0, "fma(" + op_a + ", " + op_b + ", " + op_c + ')', 2178 regs.SetRegisterToFloat(instr.gpr0, 0, "fma(" + op_a + ", " + op_b + ", " + op_c + ')',
2105 1, 1, instr.alu.saturate_d, 0, true); 2179 1, 1, instr.alu.saturate_d, 0, true);
2180 if (instr.generates_cc) {
2181 LOG_CRITICAL(HW_GPU, "FFMA Generates an unhandled Control Code");
2182 UNREACHABLE();
2183 }
2106 2184
2107 break; 2185 break;
2108 } 2186 }
2109 case OpCode::Type::Hfma2: { 2187 case OpCode::Type::Hfma2: {
2110 if (opcode->GetId() == OpCode::Id::HFMA2_RR) { 2188 if (opcode->get().GetId() == OpCode::Id::HFMA2_RR) {
2111 ASSERT_MSG(instr.hfma2.rr.precision == Tegra::Shader::HalfPrecision::None, 2189 ASSERT_MSG(instr.hfma2.rr.precision == Tegra::Shader::HalfPrecision::None,
2112 "Unimplemented"); 2190 "Unimplemented");
2113 } else { 2191 } else {
2114 ASSERT_MSG(instr.hfma2.precision == Tegra::Shader::HalfPrecision::None, 2192 ASSERT_MSG(instr.hfma2.precision == Tegra::Shader::HalfPrecision::None,
2115 "Unimplemented"); 2193 "Unimplemented");
2116 } 2194 }
2117 const bool saturate = opcode->GetId() == OpCode::Id::HFMA2_RR 2195 const bool saturate = opcode->get().GetId() == OpCode::Id::HFMA2_RR
2118 ? instr.hfma2.rr.saturate != 0 2196 ? instr.hfma2.rr.saturate != 0
2119 : instr.hfma2.saturate != 0; 2197 : instr.hfma2.saturate != 0;
2120 2198
@@ -2122,7 +2200,7 @@ private:
2122 GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.hfma2.type_a); 2200 GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.hfma2.type_a);
2123 std::string op_b, op_c; 2201 std::string op_b, op_c;
2124 2202
2125 switch (opcode->GetId()) { 2203 switch (opcode->get().GetId()) {
2126 case OpCode::Id::HFMA2_CR: 2204 case OpCode::Id::HFMA2_CR:
2127 op_b = GetHalfFloat(regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset, 2205 op_b = GetHalfFloat(regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
2128 GLSLRegister::Type::UnsignedInteger), 2206 GLSLRegister::Type::UnsignedInteger),
@@ -2160,7 +2238,7 @@ private:
2160 break; 2238 break;
2161 } 2239 }
2162 case OpCode::Type::Conversion: { 2240 case OpCode::Type::Conversion: {
2163 switch (opcode->GetId()) { 2241 switch (opcode->get().GetId()) {
2164 case OpCode::Id::I2I_R: { 2242 case OpCode::Id::I2I_R: {
2165 ASSERT_MSG(!instr.conversion.selector, "Unimplemented"); 2243 ASSERT_MSG(!instr.conversion.selector, "Unimplemented");
2166 2244
@@ -2208,6 +2286,11 @@ private:
2208 } 2286 }
2209 2287
2210 regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1); 2288 regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1);
2289
2290 if (instr.generates_cc) {
2291 LOG_CRITICAL(HW_GPU, "I2F Generates an unhandled Control Code");
2292 UNREACHABLE();
2293 }
2211 break; 2294 break;
2212 } 2295 }
2213 case OpCode::Id::F2F_R: { 2296 case OpCode::Id::F2F_R: {
@@ -2246,6 +2329,11 @@ private:
2246 } 2329 }
2247 2330
2248 regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1, instr.alu.saturate_d); 2331 regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1, instr.alu.saturate_d);
2332
2333 if (instr.generates_cc) {
2334 LOG_CRITICAL(HW_GPU, "F2F Generates an unhandled Control Code");
2335 UNREACHABLE();
2336 }
2249 break; 2337 break;
2250 } 2338 }
2251 case OpCode::Id::F2I_R: 2339 case OpCode::Id::F2I_R:
@@ -2295,17 +2383,22 @@ private:
2295 2383
2296 regs.SetRegisterToInteger(instr.gpr0, instr.conversion.is_output_signed, 0, op_a, 1, 2384 regs.SetRegisterToInteger(instr.gpr0, instr.conversion.is_output_signed, 0, op_a, 1,
2297 1, false, 0, instr.conversion.dest_size); 2385 1, false, 0, instr.conversion.dest_size);
2386 if (instr.generates_cc) {
2387 LOG_CRITICAL(HW_GPU, "F2I Generates an unhandled Control Code");
2388 UNREACHABLE();
2389 }
2298 break; 2390 break;
2299 } 2391 }
2300 default: { 2392 default: {
2301 LOG_CRITICAL(HW_GPU, "Unhandled conversion instruction: {}", opcode->GetName()); 2393 LOG_CRITICAL(HW_GPU, "Unhandled conversion instruction: {}",
2394 opcode->get().GetName());
2302 UNREACHABLE(); 2395 UNREACHABLE();
2303 } 2396 }
2304 } 2397 }
2305 break; 2398 break;
2306 } 2399 }
2307 case OpCode::Type::Memory: { 2400 case OpCode::Type::Memory: {
2308 switch (opcode->GetId()) { 2401 switch (opcode->get().GetId()) {
2309 case OpCode::Id::LD_A: { 2402 case OpCode::Id::LD_A: {
2310 // Note: Shouldn't this be interp mode flat? As in no interpolation made. 2403 // Note: Shouldn't this be interp mode flat? As in no interpolation made.
2311 ASSERT_MSG(instr.gpr8.Value() == Register::ZeroIndex, 2404 ASSERT_MSG(instr.gpr8.Value() == Register::ZeroIndex,
@@ -2653,12 +2746,12 @@ private:
2653 } 2746 }
2654 case 3: { 2747 case 3: {
2655 if (is_array) { 2748 if (is_array) {
2656 UNIMPLEMENTED_MSG("3-coordinate arrays not fully implemented"); 2749 const std::string index = regs.GetRegisterAsInteger(instr.gpr8);
2657 const std::string x = regs.GetRegisterAsFloat(instr.gpr8); 2750 const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
2658 const std::string y = regs.GetRegisterAsFloat(instr.gpr20); 2751 const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 2);
2659 coord = "vec2 coords = vec2(" + x + ", " + y + ");"; 2752 const std::string z = regs.GetRegisterAsFloat(instr.gpr20);
2660 texture_type = Tegra::Shader::TextureType::Texture2D; 2753 coord =
2661 is_array = false; 2754 "vec4 coords = vec4(" + x + ", " + y + ", " + z + ", " + index + ");";
2662 } else { 2755 } else {
2663 const std::string x = regs.GetRegisterAsFloat(instr.gpr8); 2756 const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
2664 const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1); 2757 const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
@@ -2688,7 +2781,11 @@ private:
2688 break; 2781 break;
2689 } 2782 }
2690 case Tegra::Shader::TextureProcessMode::LZ: { 2783 case Tegra::Shader::TextureProcessMode::LZ: {
2691 texture = "textureLod(" + sampler + ", coords, 0.0)"; 2784 if (depth_compare && is_array) {
2785 texture = "texture(" + sampler + ", coords)";
2786 } else {
2787 texture = "textureLod(" + sampler + ", coords, 0.0)";
2788 }
2692 break; 2789 break;
2693 } 2790 }
2694 case Tegra::Shader::TextureProcessMode::LL: { 2791 case Tegra::Shader::TextureProcessMode::LL: {
@@ -2949,7 +3046,7 @@ private:
2949 break; 3046 break;
2950 } 3047 }
2951 default: { 3048 default: {
2952 LOG_CRITICAL(HW_GPU, "Unhandled memory instruction: {}", opcode->GetName()); 3049 LOG_CRITICAL(HW_GPU, "Unhandled memory instruction: {}", opcode->get().GetName());
2953 UNREACHABLE(); 3050 UNREACHABLE();
2954 } 3051 }
2955 } 3052 }
@@ -3043,7 +3140,7 @@ private:
3043 instr.hsetp2.abs_a, instr.hsetp2.negate_a); 3140 instr.hsetp2.abs_a, instr.hsetp2.negate_a);
3044 3141
3045 const std::string op_b = [&]() { 3142 const std::string op_b = [&]() {
3046 switch (opcode->GetId()) { 3143 switch (opcode->get().GetId()) {
3047 case OpCode::Id::HSETP2_R: 3144 case OpCode::Id::HSETP2_R:
3048 return GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr20, 0, false), 3145 return GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr20, 0, false),
3049 instr.hsetp2.type_b, instr.hsetp2.abs_a, 3146 instr.hsetp2.type_b, instr.hsetp2.abs_a,
@@ -3102,10 +3199,15 @@ private:
3102 regs.SetRegisterToFloat(instr.gpr0, 0, value, 1, 1); 3199 regs.SetRegisterToFloat(instr.gpr0, 0, value, 1, 1);
3103 } 3200 }
3104 3201
3202 if (instr.generates_cc) {
3203 LOG_CRITICAL(HW_GPU, "PSET Generates an unhandled Control Code");
3204 UNREACHABLE();
3205 }
3206
3105 break; 3207 break;
3106 } 3208 }
3107 case OpCode::Type::PredicateSetPredicate: { 3209 case OpCode::Type::PredicateSetPredicate: {
3108 switch (opcode->GetId()) { 3210 switch (opcode->get().GetId()) {
3109 case OpCode::Id::PSETP: { 3211 case OpCode::Id::PSETP: {
3110 const std::string op_a = 3212 const std::string op_a =
3111 GetPredicateCondition(instr.psetp.pred12, instr.psetp.neg_pred12 != 0); 3213 GetPredicateCondition(instr.psetp.pred12, instr.psetp.neg_pred12 != 0);
@@ -3151,7 +3253,8 @@ private:
3151 break; 3253 break;
3152 } 3254 }
3153 default: { 3255 default: {
3154 LOG_CRITICAL(HW_GPU, "Unhandled predicate instruction: {}", opcode->GetName()); 3256 LOG_CRITICAL(HW_GPU, "Unhandled predicate instruction: {}",
3257 opcode->get().GetName());
3155 UNREACHABLE(); 3258 UNREACHABLE();
3156 } 3259 }
3157 } 3260 }
@@ -3239,7 +3342,7 @@ private:
3239 instr.hset2.abs_a != 0, instr.hset2.negate_a != 0); 3342 instr.hset2.abs_a != 0, instr.hset2.negate_a != 0);
3240 3343
3241 const std::string op_b = [&]() { 3344 const std::string op_b = [&]() {
3242 switch (opcode->GetId()) { 3345 switch (opcode->get().GetId()) {
3243 case OpCode::Id::HSET2_R: 3346 case OpCode::Id::HSET2_R:
3244 return GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr20, 0, false), 3347 return GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr20, 0, false),
3245 instr.hset2.type_b, instr.hset2.abs_b != 0, 3348 instr.hset2.type_b, instr.hset2.abs_b != 0,
@@ -3288,7 +3391,7 @@ private:
3288 const bool is_signed{instr.xmad.sign_a == 1}; 3391 const bool is_signed{instr.xmad.sign_a == 1};
3289 3392
3290 bool is_merge{}; 3393 bool is_merge{};
3291 switch (opcode->GetId()) { 3394 switch (opcode->get().GetId()) {
3292 case OpCode::Id::XMAD_CR: { 3395 case OpCode::Id::XMAD_CR: {
3293 is_merge = instr.xmad.merge_56; 3396 is_merge = instr.xmad.merge_56;
3294 op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset, 3397 op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
@@ -3317,7 +3420,7 @@ private:
3317 break; 3420 break;
3318 } 3421 }
3319 default: { 3422 default: {
3320 LOG_CRITICAL(HW_GPU, "Unhandled XMAD instruction: {}", opcode->GetName()); 3423 LOG_CRITICAL(HW_GPU, "Unhandled XMAD instruction: {}", opcode->get().GetName());
3321 UNREACHABLE(); 3424 UNREACHABLE();
3322 } 3425 }
3323 } 3426 }
@@ -3366,15 +3469,25 @@ private:
3366 } 3469 }
3367 3470
3368 regs.SetRegisterToInteger(instr.gpr0, is_signed, 0, sum, 1, 1); 3471 regs.SetRegisterToInteger(instr.gpr0, is_signed, 0, sum, 1, 1);
3472 if (instr.generates_cc) {
3473 LOG_CRITICAL(HW_GPU, "XMAD Generates an unhandled Control Code");
3474 UNREACHABLE();
3475 }
3369 break; 3476 break;
3370 } 3477 }
3371 default: { 3478 default: {
3372 switch (opcode->GetId()) { 3479 switch (opcode->get().GetId()) {
3373 case OpCode::Id::EXIT: { 3480 case OpCode::Id::EXIT: {
3374 if (stage == Maxwell3D::Regs::ShaderStage::Fragment) { 3481 if (stage == Maxwell3D::Regs::ShaderStage::Fragment) {
3375 EmitFragmentOutputsWrite(); 3482 EmitFragmentOutputsWrite();
3376 } 3483 }
3377 3484
3485 const Tegra::Shader::ControlCode cc = instr.flow_control_code;
3486 if (cc != Tegra::Shader::ControlCode::T) {
3487 LOG_CRITICAL(HW_GPU, "EXIT Control Code used: {}", static_cast<u32>(cc));
3488 UNREACHABLE();
3489 }
3490
3378 switch (instr.flow.cond) { 3491 switch (instr.flow.cond) {
3379 case Tegra::Shader::FlowCondition::Always: 3492 case Tegra::Shader::FlowCondition::Always:
3380 shader.AddLine("return true;"); 3493 shader.AddLine("return true;");
@@ -3404,6 +3517,11 @@ private:
3404 3517
3405 // Enclose "discard" in a conditional, so that GLSL compilation does not complain 3518 // Enclose "discard" in a conditional, so that GLSL compilation does not complain
3406 // about unexecuted instructions that may follow this. 3519 // about unexecuted instructions that may follow this.
3520 const Tegra::Shader::ControlCode cc = instr.flow_control_code;
3521 if (cc != Tegra::Shader::ControlCode::T) {
3522 LOG_CRITICAL(HW_GPU, "KIL Control Code used: {}", static_cast<u32>(cc));
3523 UNREACHABLE();
3524 }
3407 shader.AddLine("if (true) {"); 3525 shader.AddLine("if (true) {");
3408 ++shader.scope; 3526 ++shader.scope;
3409 shader.AddLine("discard;"); 3527 shader.AddLine("discard;");
@@ -3461,6 +3579,11 @@ private:
3461 case OpCode::Id::BRA: { 3579 case OpCode::Id::BRA: {
3462 ASSERT_MSG(instr.bra.constant_buffer == 0, 3580 ASSERT_MSG(instr.bra.constant_buffer == 0,
3463 "BRA with constant buffers are not implemented"); 3581 "BRA with constant buffers are not implemented");
3582 const Tegra::Shader::ControlCode cc = instr.flow_control_code;
3583 if (cc != Tegra::Shader::ControlCode::T) {
3584 LOG_CRITICAL(HW_GPU, "BRA Control Code used: {}", static_cast<u32>(cc));
3585 UNREACHABLE();
3586 }
3464 const u32 target = offset + instr.bra.GetBranchTarget(); 3587 const u32 target = offset + instr.bra.GetBranchTarget();
3465 shader.AddLine("{ jmp_to = " + std::to_string(target) + "u; break; }"); 3588 shader.AddLine("{ jmp_to = " + std::to_string(target) + "u; break; }");
3466 break; 3589 break;
@@ -3501,13 +3624,21 @@ private:
3501 } 3624 }
3502 case OpCode::Id::SYNC: { 3625 case OpCode::Id::SYNC: {
3503 // The SYNC opcode jumps to the address previously set by the SSY opcode 3626 // The SYNC opcode jumps to the address previously set by the SSY opcode
3504 ASSERT(instr.flow.cond == Tegra::Shader::FlowCondition::Always); 3627 const Tegra::Shader::ControlCode cc = instr.flow_control_code;
3628 if (cc != Tegra::Shader::ControlCode::T) {
3629 LOG_CRITICAL(HW_GPU, "SYNC Control Code used: {}", static_cast<u32>(cc));
3630 UNREACHABLE();
3631 }
3505 EmitPopFromFlowStack(); 3632 EmitPopFromFlowStack();
3506 break; 3633 break;
3507 } 3634 }
3508 case OpCode::Id::BRK: { 3635 case OpCode::Id::BRK: {
3509 // The BRK opcode jumps to the address previously set by the PBK opcode 3636 // The BRK opcode jumps to the address previously set by the PBK opcode
3510 ASSERT(instr.flow.cond == Tegra::Shader::FlowCondition::Always); 3637 const Tegra::Shader::ControlCode cc = instr.flow_control_code;
3638 if (cc != Tegra::Shader::ControlCode::T) {
3639 LOG_CRITICAL(HW_GPU, "BRK Control Code used: {}", static_cast<u32>(cc));
3640 UNREACHABLE();
3641 }
3511 EmitPopFromFlowStack(); 3642 EmitPopFromFlowStack();
3512 break; 3643 break;
3513 } 3644 }
@@ -3537,6 +3668,11 @@ private:
3537 regs.SetRegisterToInteger(instr.gpr0, result_signed, 1, result, 1, 1, 3668 regs.SetRegisterToInteger(instr.gpr0, result_signed, 1, result, 1, 1,
3538 instr.vmad.saturate == 1, 0, Register::Size::Word, 3669 instr.vmad.saturate == 1, 0, Register::Size::Word,
3539 instr.vmad.cc); 3670 instr.vmad.cc);
3671 if (instr.generates_cc) {
3672 LOG_CRITICAL(HW_GPU, "VMAD Generates an unhandled Control Code");
3673 UNREACHABLE();
3674 }
3675
3540 break; 3676 break;
3541 } 3677 }
3542 case OpCode::Id::VSETP: { 3678 case OpCode::Id::VSETP: {
@@ -3564,7 +3700,7 @@ private:
3564 break; 3700 break;
3565 } 3701 }
3566 default: { 3702 default: {
3567 LOG_CRITICAL(HW_GPU, "Unhandled instruction: {}", opcode->GetName()); 3703 LOG_CRITICAL(HW_GPU, "Unhandled instruction: {}", opcode->get().GetName());
3568 UNREACHABLE(); 3704 UNREACHABLE();
3569 } 3705 }
3570 } 3706 }
@@ -3705,9 +3841,9 @@ std::string GetCommonDeclarations() {
3705 RasterizerOpenGL::MaxConstbufferSize / sizeof(GLvec4)); 3841 RasterizerOpenGL::MaxConstbufferSize / sizeof(GLvec4));
3706} 3842}
3707 3843
3708boost::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code, u32 main_offset, 3844std::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code, u32 main_offset,
3709 Maxwell3D::Regs::ShaderStage stage, 3845 Maxwell3D::Regs::ShaderStage stage,
3710 const std::string& suffix) { 3846 const std::string& suffix) {
3711 try { 3847 try {
3712 const auto subroutines = 3848 const auto subroutines =
3713 ControlFlowAnalyzer(program_code, main_offset, suffix).GetSubroutines(); 3849 ControlFlowAnalyzer(program_code, main_offset, suffix).GetSubroutines();
@@ -3716,7 +3852,7 @@ boost::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code,
3716 } catch (const DecompileFail& exception) { 3852 } catch (const DecompileFail& exception) {
3717 LOG_ERROR(HW_GPU, "Shader decompilation failed: {}", exception.what()); 3853 LOG_ERROR(HW_GPU, "Shader decompilation failed: {}", exception.what());
3718 } 3854 }
3719 return boost::none; 3855 return {};
3720} 3856}
3721 3857
3722} // namespace OpenGL::GLShader::Decompiler 3858} // namespace OpenGL::GLShader::Decompiler
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.h b/src/video_core/renderer_opengl/gl_shader_decompiler.h
index b20cc4bfa..d01a4a7ee 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.h
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.h
@@ -6,8 +6,8 @@
6 6
7#include <array> 7#include <array>
8#include <functional> 8#include <functional>
9#include <optional>
9#include <string> 10#include <string>
10#include <boost/optional.hpp>
11#include "common/common_types.h" 11#include "common/common_types.h"
12#include "video_core/engines/maxwell_3d.h" 12#include "video_core/engines/maxwell_3d.h"
13#include "video_core/renderer_opengl/gl_shader_gen.h" 13#include "video_core/renderer_opengl/gl_shader_gen.h"
@@ -18,8 +18,8 @@ using Tegra::Engines::Maxwell3D;
18 18
19std::string GetCommonDeclarations(); 19std::string GetCommonDeclarations();
20 20
21boost::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code, u32 main_offset, 21std::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code, u32 main_offset,
22 Maxwell3D::Regs::ShaderStage stage, 22 Maxwell3D::Regs::ShaderStage stage,
23 const std::string& suffix); 23 const std::string& suffix);
24 24
25} // namespace OpenGL::GLShader::Decompiler 25} // namespace OpenGL::GLShader::Decompiler
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp
index dfb562706..eea090e52 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp
@@ -37,7 +37,7 @@ layout(std140) uniform vs_config {
37 ProgramResult program = 37 ProgramResult program =
38 Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET, 38 Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET,
39 Maxwell3D::Regs::ShaderStage::Vertex, "vertex") 39 Maxwell3D::Regs::ShaderStage::Vertex, "vertex")
40 .get_value_or({}); 40 .value_or(ProgramResult());
41 41
42 out += program.first; 42 out += program.first;
43 43
@@ -45,7 +45,7 @@ layout(std140) uniform vs_config {
45 ProgramResult program_b = 45 ProgramResult program_b =
46 Decompiler::DecompileProgram(setup.program.code_b, PROGRAM_OFFSET, 46 Decompiler::DecompileProgram(setup.program.code_b, PROGRAM_OFFSET,
47 Maxwell3D::Regs::ShaderStage::Vertex, "vertex_b") 47 Maxwell3D::Regs::ShaderStage::Vertex, "vertex_b")
48 .get_value_or({}); 48 .value_or(ProgramResult());
49 out += program_b.first; 49 out += program_b.first;
50 } 50 }
51 51
@@ -82,15 +82,15 @@ void main() {
82} 82}
83 83
84ProgramResult GenerateGeometryShader(const ShaderSetup& setup) { 84ProgramResult GenerateGeometryShader(const ShaderSetup& setup) {
85 std::string out = "#version 430 core\n"; 85 // Version is intentionally skipped in shader generation, it's added by the lazy compilation.
86 out += "#extension GL_ARB_separate_shader_objects : enable\n\n"; 86 std::string out = "#extension GL_ARB_separate_shader_objects : enable\n\n";
87 out += Decompiler::GetCommonDeclarations(); 87 out += Decompiler::GetCommonDeclarations();
88 out += "bool exec_geometry();\n"; 88 out += "bool exec_geometry();\n";
89 89
90 ProgramResult program = 90 ProgramResult program =
91 Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET, 91 Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET,
92 Maxwell3D::Regs::ShaderStage::Geometry, "geometry") 92 Maxwell3D::Regs::ShaderStage::Geometry, "geometry")
93 .get_value_or({}); 93 .value_or(ProgramResult());
94 out += R"( 94 out += R"(
95out gl_PerVertex { 95out gl_PerVertex {
96 vec4 gl_Position; 96 vec4 gl_Position;
@@ -124,7 +124,7 @@ ProgramResult GenerateFragmentShader(const ShaderSetup& setup) {
124 ProgramResult program = 124 ProgramResult program =
125 Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET, 125 Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET,
126 Maxwell3D::Regs::ShaderStage::Fragment, "fragment") 126 Maxwell3D::Regs::ShaderStage::Fragment, "fragment")
127 .get_value_or({}); 127 .value_or(ProgramResult());
128 out += R"( 128 out += R"(
129layout(location = 0) out vec4 FragColor0; 129layout(location = 0) out vec4 FragColor0;
130layout(location = 1) out vec4 FragColor1; 130layout(location = 1) out vec4 FragColor1;
diff --git a/src/video_core/renderer_opengl/gl_shader_manager.h b/src/video_core/renderer_opengl/gl_shader_manager.h
index 36fe1f04c..2a069cdd8 100644
--- a/src/video_core/renderer_opengl/gl_shader_manager.h
+++ b/src/video_core/renderer_opengl/gl_shader_manager.h
@@ -7,6 +7,7 @@
7#include <glad/glad.h> 7#include <glad/glad.h>
8 8
9#include "video_core/renderer_opengl/gl_resource_manager.h" 9#include "video_core/renderer_opengl/gl_resource_manager.h"
10#include "video_core/renderer_opengl/gl_state.h"
10#include "video_core/renderer_opengl/maxwell_to_gl.h" 11#include "video_core/renderer_opengl/maxwell_to_gl.h"
11 12
12namespace OpenGL::GLShader { 13namespace OpenGL::GLShader {
diff --git a/src/video_core/renderer_opengl/gl_state.cpp b/src/video_core/renderer_opengl/gl_state.cpp
index d8a43cc94..2635f2b0c 100644
--- a/src/video_core/renderer_opengl/gl_state.cpp
+++ b/src/video_core/renderer_opengl/gl_state.cpp
@@ -22,17 +22,15 @@ OpenGLState::OpenGLState() {
22 depth.test_enabled = false; 22 depth.test_enabled = false;
23 depth.test_func = GL_LESS; 23 depth.test_func = GL_LESS;
24 depth.write_mask = GL_TRUE; 24 depth.write_mask = GL_TRUE;
25 depth.depth_range_near = 0.0f;
26 depth.depth_range_far = 1.0f;
27 25
28 primitive_restart.enabled = false; 26 primitive_restart.enabled = false;
29 primitive_restart.index = 0; 27 primitive_restart.index = 0;
30 28 for (auto& item : color_mask) {
31 color_mask.red_enabled = GL_TRUE; 29 item.red_enabled = GL_TRUE;
32 color_mask.green_enabled = GL_TRUE; 30 item.green_enabled = GL_TRUE;
33 color_mask.blue_enabled = GL_TRUE; 31 item.blue_enabled = GL_TRUE;
34 color_mask.alpha_enabled = GL_TRUE; 32 item.alpha_enabled = GL_TRUE;
35 33 }
36 stencil.test_enabled = false; 34 stencil.test_enabled = false;
37 auto reset_stencil = [](auto& config) { 35 auto reset_stencil = [](auto& config) {
38 config.test_func = GL_ALWAYS; 36 config.test_func = GL_ALWAYS;
@@ -45,19 +43,33 @@ OpenGLState::OpenGLState() {
45 }; 43 };
46 reset_stencil(stencil.front); 44 reset_stencil(stencil.front);
47 reset_stencil(stencil.back); 45 reset_stencil(stencil.back);
48 46 for (auto& item : viewports) {
49 blend.enabled = true; 47 item.x = 0;
50 blend.rgb_equation = GL_FUNC_ADD; 48 item.y = 0;
51 blend.a_equation = GL_FUNC_ADD; 49 item.width = 0;
52 blend.src_rgb_func = GL_ONE; 50 item.height = 0;
53 blend.dst_rgb_func = GL_ZERO; 51 item.depth_range_near = 0.0f;
54 blend.src_a_func = GL_ONE; 52 item.depth_range_far = 1.0f;
55 blend.dst_a_func = GL_ZERO; 53 }
56 blend.color.red = 0.0f; 54 scissor.enabled = false;
57 blend.color.green = 0.0f; 55 scissor.x = 0;
58 blend.color.blue = 0.0f; 56 scissor.y = 0;
59 blend.color.alpha = 0.0f; 57 scissor.width = 0;
60 58 scissor.height = 0;
59 for (auto& item : blend) {
60 item.enabled = true;
61 item.rgb_equation = GL_FUNC_ADD;
62 item.a_equation = GL_FUNC_ADD;
63 item.src_rgb_func = GL_ONE;
64 item.dst_rgb_func = GL_ZERO;
65 item.src_a_func = GL_ONE;
66 item.dst_a_func = GL_ZERO;
67 }
68 independant_blend.enabled = false;
69 blend_color.red = 0.0f;
70 blend_color.green = 0.0f;
71 blend_color.blue = 0.0f;
72 blend_color.alpha = 0.0f;
61 logic_op.enabled = false; 73 logic_op.enabled = false;
62 logic_op.operation = GL_COPY; 74 logic_op.operation = GL_COPY;
63 75
@@ -73,23 +85,23 @@ OpenGLState::OpenGLState() {
73 draw.shader_program = 0; 85 draw.shader_program = 0;
74 draw.program_pipeline = 0; 86 draw.program_pipeline = 0;
75 87
76 scissor.enabled = false;
77 scissor.x = 0;
78 scissor.y = 0;
79 scissor.width = 0;
80 scissor.height = 0;
81
82 viewport.x = 0;
83 viewport.y = 0;
84 viewport.width = 0;
85 viewport.height = 0;
86
87 clip_distance = {}; 88 clip_distance = {};
88 89
89 point.size = 1; 90 point.size = 1;
90} 91}
91 92
92void OpenGLState::Apply() const { 93void OpenGLState::ApplyDefaultState() {
94 glDisable(GL_FRAMEBUFFER_SRGB);
95 glDisable(GL_CULL_FACE);
96 glDisable(GL_DEPTH_TEST);
97 glDisable(GL_PRIMITIVE_RESTART);
98 glDisable(GL_STENCIL_TEST);
99 glEnable(GL_BLEND);
100 glDisable(GL_COLOR_LOGIC_OP);
101 glDisable(GL_SCISSOR_TEST);
102}
103
104void OpenGLState::ApplySRgb() const {
93 // sRGB 105 // sRGB
94 if (framebuffer_srgb.enabled != cur_state.framebuffer_srgb.enabled) { 106 if (framebuffer_srgb.enabled != cur_state.framebuffer_srgb.enabled) {
95 if (framebuffer_srgb.enabled) { 107 if (framebuffer_srgb.enabled) {
@@ -100,139 +112,281 @@ void OpenGLState::Apply() const {
100 glDisable(GL_FRAMEBUFFER_SRGB); 112 glDisable(GL_FRAMEBUFFER_SRGB);
101 } 113 }
102 } 114 }
115}
116
117void OpenGLState::ApplyCulling() const {
103 // Culling 118 // Culling
104 if (cull.enabled != cur_state.cull.enabled) { 119 const bool cull_changed = cull.enabled != cur_state.cull.enabled;
120 if (cull_changed) {
105 if (cull.enabled) { 121 if (cull.enabled) {
106 glEnable(GL_CULL_FACE); 122 glEnable(GL_CULL_FACE);
107 } else { 123 } else {
108 glDisable(GL_CULL_FACE); 124 glDisable(GL_CULL_FACE);
109 } 125 }
110 } 126 }
127 if (cull.enabled) {
128 if (cull_changed || cull.mode != cur_state.cull.mode) {
129 glCullFace(cull.mode);
130 }
111 131
112 if (cull.mode != cur_state.cull.mode) { 132 if (cull_changed || cull.front_face != cur_state.cull.front_face) {
113 glCullFace(cull.mode); 133 glFrontFace(cull.front_face);
134 }
114 } 135 }
136}
115 137
116 if (cull.front_face != cur_state.cull.front_face) { 138void OpenGLState::ApplyColorMask() const {
117 glFrontFace(cull.front_face); 139 if (GLAD_GL_ARB_viewport_array) {
140 for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
141 const auto& updated = color_mask[i];
142 const auto& current = cur_state.color_mask[i];
143 if (updated.red_enabled != current.red_enabled ||
144 updated.green_enabled != current.green_enabled ||
145 updated.blue_enabled != current.blue_enabled ||
146 updated.alpha_enabled != current.alpha_enabled) {
147 glColorMaski(static_cast<GLuint>(i), updated.red_enabled, updated.green_enabled,
148 updated.blue_enabled, updated.alpha_enabled);
149 }
150 }
151 } else {
152 const auto& updated = color_mask[0];
153 const auto& current = cur_state.color_mask[0];
154 if (updated.red_enabled != current.red_enabled ||
155 updated.green_enabled != current.green_enabled ||
156 updated.blue_enabled != current.blue_enabled ||
157 updated.alpha_enabled != current.alpha_enabled) {
158 glColorMask(updated.red_enabled, updated.green_enabled, updated.blue_enabled,
159 updated.alpha_enabled);
160 }
118 } 161 }
162}
119 163
164void OpenGLState::ApplyDepth() const {
120 // Depth test 165 // Depth test
121 if (depth.test_enabled != cur_state.depth.test_enabled) { 166 const bool depth_test_changed = depth.test_enabled != cur_state.depth.test_enabled;
167 if (depth_test_changed) {
122 if (depth.test_enabled) { 168 if (depth.test_enabled) {
123 glEnable(GL_DEPTH_TEST); 169 glEnable(GL_DEPTH_TEST);
124 } else { 170 } else {
125 glDisable(GL_DEPTH_TEST); 171 glDisable(GL_DEPTH_TEST);
126 } 172 }
127 } 173 }
128 174 if (depth.test_enabled &&
129 if (depth.test_func != cur_state.depth.test_func) { 175 (depth_test_changed || depth.test_func != cur_state.depth.test_func)) {
130 glDepthFunc(depth.test_func); 176 glDepthFunc(depth.test_func);
131 } 177 }
132
133 // Depth mask 178 // Depth mask
134 if (depth.write_mask != cur_state.depth.write_mask) { 179 if (depth.write_mask != cur_state.depth.write_mask) {
135 glDepthMask(depth.write_mask); 180 glDepthMask(depth.write_mask);
136 } 181 }
182}
137 183
138 // Depth range 184void OpenGLState::ApplyPrimitiveRestart() const {
139 if (depth.depth_range_near != cur_state.depth.depth_range_near || 185 const bool primitive_restart_changed =
140 depth.depth_range_far != cur_state.depth.depth_range_far) { 186 primitive_restart.enabled != cur_state.primitive_restart.enabled;
141 glDepthRange(depth.depth_range_near, depth.depth_range_far); 187 if (primitive_restart_changed) {
142 }
143
144 // Primitive restart
145 if (primitive_restart.enabled != cur_state.primitive_restart.enabled) {
146 if (primitive_restart.enabled) { 188 if (primitive_restart.enabled) {
147 glEnable(GL_PRIMITIVE_RESTART); 189 glEnable(GL_PRIMITIVE_RESTART);
148 } else { 190 } else {
149 glDisable(GL_PRIMITIVE_RESTART); 191 glDisable(GL_PRIMITIVE_RESTART);
150 } 192 }
151 } 193 }
152 if (primitive_restart.index != cur_state.primitive_restart.index) { 194 if (primitive_restart_changed ||
195 (primitive_restart.enabled &&
196 primitive_restart.index != cur_state.primitive_restart.index)) {
153 glPrimitiveRestartIndex(primitive_restart.index); 197 glPrimitiveRestartIndex(primitive_restart.index);
154 } 198 }
199}
155 200
156 // Color mask 201void OpenGLState::ApplyStencilTest() const {
157 if (color_mask.red_enabled != cur_state.color_mask.red_enabled || 202 const bool stencil_test_changed = stencil.test_enabled != cur_state.stencil.test_enabled;
158 color_mask.green_enabled != cur_state.color_mask.green_enabled || 203 if (stencil_test_changed) {
159 color_mask.blue_enabled != cur_state.color_mask.blue_enabled ||
160 color_mask.alpha_enabled != cur_state.color_mask.alpha_enabled) {
161 glColorMask(color_mask.red_enabled, color_mask.green_enabled, color_mask.blue_enabled,
162 color_mask.alpha_enabled);
163 }
164
165 // Stencil test
166 if (stencil.test_enabled != cur_state.stencil.test_enabled) {
167 if (stencil.test_enabled) { 204 if (stencil.test_enabled) {
168 glEnable(GL_STENCIL_TEST); 205 glEnable(GL_STENCIL_TEST);
169 } else { 206 } else {
170 glDisable(GL_STENCIL_TEST); 207 glDisable(GL_STENCIL_TEST);
171 } 208 }
172 } 209 }
173 auto config_stencil = [](GLenum face, const auto& config, const auto& prev_config) { 210 if (stencil.test_enabled) {
174 if (config.test_func != prev_config.test_func || config.test_ref != prev_config.test_ref || 211 auto config_stencil = [stencil_test_changed](GLenum face, const auto& config,
175 config.test_mask != prev_config.test_mask) { 212 const auto& prev_config) {
176 glStencilFuncSeparate(face, config.test_func, config.test_ref, config.test_mask); 213 if (stencil_test_changed || config.test_func != prev_config.test_func ||
214 config.test_ref != prev_config.test_ref ||
215 config.test_mask != prev_config.test_mask) {
216 glStencilFuncSeparate(face, config.test_func, config.test_ref, config.test_mask);
217 }
218 if (stencil_test_changed || config.action_depth_fail != prev_config.action_depth_fail ||
219 config.action_depth_pass != prev_config.action_depth_pass ||
220 config.action_stencil_fail != prev_config.action_stencil_fail) {
221 glStencilOpSeparate(face, config.action_stencil_fail, config.action_depth_fail,
222 config.action_depth_pass);
223 }
224 if (config.write_mask != prev_config.write_mask) {
225 glStencilMaskSeparate(face, config.write_mask);
226 }
227 };
228 config_stencil(GL_FRONT, stencil.front, cur_state.stencil.front);
229 config_stencil(GL_BACK, stencil.back, cur_state.stencil.back);
230 }
231}
232
233void OpenGLState::ApplyScissor() const {
234 const bool scissor_changed = scissor.enabled != cur_state.scissor.enabled;
235 if (scissor_changed) {
236 if (scissor.enabled) {
237 glEnable(GL_SCISSOR_TEST);
238 } else {
239 glDisable(GL_SCISSOR_TEST);
177 } 240 }
178 if (config.action_depth_fail != prev_config.action_depth_fail || 241 }
179 config.action_depth_pass != prev_config.action_depth_pass || 242 if (scissor.enabled &&
180 config.action_stencil_fail != prev_config.action_stencil_fail) { 243 (scissor_changed || scissor.x != cur_state.scissor.x || scissor.y != cur_state.scissor.y ||
181 glStencilOpSeparate(face, config.action_stencil_fail, config.action_depth_fail, 244 scissor.width != cur_state.scissor.width || scissor.height != cur_state.scissor.height)) {
182 config.action_depth_pass); 245 glScissor(scissor.x, scissor.y, scissor.width, scissor.height);
246 }
247}
248
249void OpenGLState::ApplyViewport() const {
250 if (GLAD_GL_ARB_viewport_array) {
251 for (GLuint i = 0;
252 i < static_cast<GLuint>(Tegra::Engines::Maxwell3D::Regs::NumRenderTargets); i++) {
253 const auto& current = cur_state.viewports[i];
254 const auto& updated = viewports[i];
255 if (updated.x != current.x || updated.y != current.y ||
256 updated.width != current.width || updated.height != current.height) {
257 glViewportIndexedf(i, updated.x, updated.y, updated.width, updated.height);
258 }
259 if (updated.depth_range_near != current.depth_range_near ||
260 updated.depth_range_far != current.depth_range_far) {
261 glDepthRangeIndexed(i, updated.depth_range_near, updated.depth_range_far);
262 }
183 } 263 }
184 if (config.write_mask != prev_config.write_mask) { 264 } else {
185 glStencilMaskSeparate(face, config.write_mask); 265 const auto& current = cur_state.viewports[0];
266 const auto& updated = viewports[0];
267 if (updated.x != current.x || updated.y != current.y || updated.width != current.width ||
268 updated.height != current.height) {
269 glViewport(updated.x, updated.y, updated.width, updated.height);
186 } 270 }
187 }; 271 if (updated.depth_range_near != current.depth_range_near ||
188 config_stencil(GL_FRONT, stencil.front, cur_state.stencil.front); 272 updated.depth_range_far != current.depth_range_far) {
189 config_stencil(GL_BACK, stencil.back, cur_state.stencil.back); 273 glDepthRange(updated.depth_range_near, updated.depth_range_far);
274 }
275 }
276}
190 277
191 // Blending 278void OpenGLState::ApplyGlobalBlending() const {
192 if (blend.enabled != cur_state.blend.enabled) { 279 const Blend& current = cur_state.blend[0];
193 if (blend.enabled) { 280 const Blend& updated = blend[0];
194 ASSERT(!logic_op.enabled); 281 const bool blend_changed = updated.enabled != current.enabled;
282 if (blend_changed) {
283 if (updated.enabled) {
195 glEnable(GL_BLEND); 284 glEnable(GL_BLEND);
196 } else { 285 } else {
197 glDisable(GL_BLEND); 286 glDisable(GL_BLEND);
198 } 287 }
199 } 288 }
289 if (!updated.enabled) {
290 return;
291 }
292 if (updated.separate_alpha) {
293 if (blend_changed || updated.src_rgb_func != current.src_rgb_func ||
294 updated.dst_rgb_func != current.dst_rgb_func ||
295 updated.src_a_func != current.src_a_func || updated.dst_a_func != current.dst_a_func) {
296 glBlendFuncSeparate(updated.src_rgb_func, updated.dst_rgb_func, updated.src_a_func,
297 updated.dst_a_func);
298 }
299
300 if (blend_changed || updated.rgb_equation != current.rgb_equation ||
301 updated.a_equation != current.a_equation) {
302 glBlendEquationSeparate(updated.rgb_equation, updated.a_equation);
303 }
304 } else {
305 if (blend_changed || updated.src_rgb_func != current.src_rgb_func ||
306 updated.dst_rgb_func != current.dst_rgb_func) {
307 glBlendFunc(updated.src_rgb_func, updated.dst_rgb_func);
308 }
200 309
201 if (blend.color.red != cur_state.blend.color.red || 310 if (blend_changed || updated.rgb_equation != current.rgb_equation) {
202 blend.color.green != cur_state.blend.color.green || 311 glBlendEquation(updated.rgb_equation);
203 blend.color.blue != cur_state.blend.color.blue || 312 }
204 blend.color.alpha != cur_state.blend.color.alpha) {
205 glBlendColor(blend.color.red, blend.color.green, blend.color.blue, blend.color.alpha);
206 } 313 }
314}
207 315
208 if (blend.src_rgb_func != cur_state.blend.src_rgb_func || 316void OpenGLState::ApplyTargetBlending(int target, bool force) const {
209 blend.dst_rgb_func != cur_state.blend.dst_rgb_func || 317 const Blend& updated = blend[target];
210 blend.src_a_func != cur_state.blend.src_a_func || 318 const Blend& current = cur_state.blend[target];
211 blend.dst_a_func != cur_state.blend.dst_a_func) { 319 const bool blend_changed = updated.enabled != current.enabled || force;
212 glBlendFuncSeparate(blend.src_rgb_func, blend.dst_rgb_func, blend.src_a_func, 320 if (blend_changed) {
213 blend.dst_a_func); 321 if (updated.enabled) {
322 glEnablei(GL_BLEND, static_cast<GLuint>(target));
323 } else {
324 glDisablei(GL_BLEND, static_cast<GLuint>(target));
325 }
326 }
327 if (!updated.enabled) {
328 return;
214 } 329 }
330 if (updated.separate_alpha) {
331 if (blend_changed || updated.src_rgb_func != current.src_rgb_func ||
332 updated.dst_rgb_func != current.dst_rgb_func ||
333 updated.src_a_func != current.src_a_func || updated.dst_a_func != current.dst_a_func) {
334 glBlendFuncSeparateiARB(static_cast<GLuint>(target), updated.src_rgb_func,
335 updated.dst_rgb_func, updated.src_a_func, updated.dst_a_func);
336 }
215 337
216 if (blend.rgb_equation != cur_state.blend.rgb_equation || 338 if (blend_changed || updated.rgb_equation != current.rgb_equation ||
217 blend.a_equation != cur_state.blend.a_equation) { 339 updated.a_equation != current.a_equation) {
218 glBlendEquationSeparate(blend.rgb_equation, blend.a_equation); 340 glBlendEquationSeparateiARB(static_cast<GLuint>(target), updated.rgb_equation,
341 updated.a_equation);
342 }
343 } else {
344 if (blend_changed || updated.src_rgb_func != current.src_rgb_func ||
345 updated.dst_rgb_func != current.dst_rgb_func) {
346 glBlendFunciARB(static_cast<GLuint>(target), updated.src_rgb_func,
347 updated.dst_rgb_func);
348 }
349
350 if (blend_changed || updated.rgb_equation != current.rgb_equation) {
351 glBlendEquationiARB(static_cast<GLuint>(target), updated.rgb_equation);
352 }
219 } 353 }
354}
220 355
221 // Logic Operation 356void OpenGLState::ApplyBlending() const {
222 if (logic_op.enabled != cur_state.logic_op.enabled) { 357 if (independant_blend.enabled) {
358 for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
359 ApplyTargetBlending(i,
360 independant_blend.enabled != cur_state.independant_blend.enabled);
361 }
362 } else {
363 ApplyGlobalBlending();
364 }
365 if (blend_color.red != cur_state.blend_color.red ||
366 blend_color.green != cur_state.blend_color.green ||
367 blend_color.blue != cur_state.blend_color.blue ||
368 blend_color.alpha != cur_state.blend_color.alpha) {
369 glBlendColor(blend_color.red, blend_color.green, blend_color.blue, blend_color.alpha);
370 }
371}
372
373void OpenGLState::ApplyLogicOp() const {
374 const bool logic_op_changed = logic_op.enabled != cur_state.logic_op.enabled;
375 if (logic_op_changed) {
223 if (logic_op.enabled) { 376 if (logic_op.enabled) {
224 ASSERT(!blend.enabled);
225 glEnable(GL_COLOR_LOGIC_OP); 377 glEnable(GL_COLOR_LOGIC_OP);
226 } else { 378 } else {
227 glDisable(GL_COLOR_LOGIC_OP); 379 glDisable(GL_COLOR_LOGIC_OP);
228 } 380 }
229 } 381 }
230 382
231 if (logic_op.operation != cur_state.logic_op.operation) { 383 if (logic_op.enabled &&
384 (logic_op_changed || logic_op.operation != cur_state.logic_op.operation)) {
232 glLogicOp(logic_op.operation); 385 glLogicOp(logic_op.operation);
233 } 386 }
387}
234 388
235 // Textures 389void OpenGLState::ApplyTextures() const {
236 for (std::size_t i = 0; i < std::size(texture_units); ++i) { 390 for (std::size_t i = 0; i < std::size(texture_units); ++i) {
237 const auto& texture_unit = texture_units[i]; 391 const auto& texture_unit = texture_units[i];
238 const auto& cur_state_texture_unit = cur_state.texture_units[i]; 392 const auto& cur_state_texture_unit = cur_state.texture_units[i];
@@ -251,28 +405,29 @@ void OpenGLState::Apply() const {
251 glTexParameteriv(texture_unit.target, GL_TEXTURE_SWIZZLE_RGBA, mask.data()); 405 glTexParameteriv(texture_unit.target, GL_TEXTURE_SWIZZLE_RGBA, mask.data());
252 } 406 }
253 } 407 }
408}
254 409
255 // Samplers 410void OpenGLState::ApplySamplers() const {
256 { 411 bool has_delta{};
257 bool has_delta{}; 412 std::size_t first{}, last{};
258 std::size_t first{}, last{}; 413 std::array<GLuint, Tegra::Engines::Maxwell3D::Regs::NumTextureSamplers> samplers;
259 std::array<GLuint, Tegra::Engines::Maxwell3D::Regs::NumTextureSamplers> samplers; 414 for (std::size_t i = 0; i < std::size(samplers); ++i) {
260 for (std::size_t i = 0; i < std::size(samplers); ++i) { 415 samplers[i] = texture_units[i].sampler;
261 samplers[i] = texture_units[i].sampler; 416 if (samplers[i] != cur_state.texture_units[i].sampler) {
262 if (samplers[i] != cur_state.texture_units[i].sampler) { 417 if (!has_delta) {
263 if (!has_delta) { 418 first = i;
264 first = i; 419 has_delta = true;
265 has_delta = true;
266 }
267 last = i;
268 } 420 }
421 last = i;
269 } 422 }
270 if (has_delta) {
271 glBindSamplers(static_cast<GLuint>(first), static_cast<GLsizei>(last - first + 1),
272 samplers.data());
273 }
274 } 423 }
424 if (has_delta) {
425 glBindSamplers(static_cast<GLuint>(first), static_cast<GLsizei>(last - first + 1),
426 samplers.data());
427 }
428}
275 429
430void OpenGLState::ApplyFramebufferState() const {
276 // Framebuffer 431 // Framebuffer
277 if (draw.read_framebuffer != cur_state.draw.read_framebuffer) { 432 if (draw.read_framebuffer != cur_state.draw.read_framebuffer) {
278 glBindFramebuffer(GL_READ_FRAMEBUFFER, draw.read_framebuffer); 433 glBindFramebuffer(GL_READ_FRAMEBUFFER, draw.read_framebuffer);
@@ -280,7 +435,9 @@ void OpenGLState::Apply() const {
280 if (draw.draw_framebuffer != cur_state.draw.draw_framebuffer) { 435 if (draw.draw_framebuffer != cur_state.draw.draw_framebuffer) {
281 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw.draw_framebuffer); 436 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw.draw_framebuffer);
282 } 437 }
438}
283 439
440void OpenGLState::ApplyVertexBufferState() const {
284 // Vertex array 441 // Vertex array
285 if (draw.vertex_array != cur_state.draw.vertex_array) { 442 if (draw.vertex_array != cur_state.draw.vertex_array) {
286 glBindVertexArray(draw.vertex_array); 443 glBindVertexArray(draw.vertex_array);
@@ -290,7 +447,11 @@ void OpenGLState::Apply() const {
290 if (draw.vertex_buffer != cur_state.draw.vertex_buffer) { 447 if (draw.vertex_buffer != cur_state.draw.vertex_buffer) {
291 glBindBuffer(GL_ARRAY_BUFFER, draw.vertex_buffer); 448 glBindBuffer(GL_ARRAY_BUFFER, draw.vertex_buffer);
292 } 449 }
450}
293 451
452void OpenGLState::Apply() const {
453 ApplyFramebufferState();
454 ApplyVertexBufferState();
294 // Uniform buffer 455 // Uniform buffer
295 if (draw.uniform_buffer != cur_state.draw.uniform_buffer) { 456 if (draw.uniform_buffer != cur_state.draw.uniform_buffer) {
296 glBindBuffer(GL_UNIFORM_BUFFER, draw.uniform_buffer); 457 glBindBuffer(GL_UNIFORM_BUFFER, draw.uniform_buffer);
@@ -305,27 +466,6 @@ void OpenGLState::Apply() const {
305 if (draw.program_pipeline != cur_state.draw.program_pipeline) { 466 if (draw.program_pipeline != cur_state.draw.program_pipeline) {
306 glBindProgramPipeline(draw.program_pipeline); 467 glBindProgramPipeline(draw.program_pipeline);
307 } 468 }
308
309 // Scissor test
310 if (scissor.enabled != cur_state.scissor.enabled) {
311 if (scissor.enabled) {
312 glEnable(GL_SCISSOR_TEST);
313 } else {
314 glDisable(GL_SCISSOR_TEST);
315 }
316 }
317
318 if (scissor.x != cur_state.scissor.x || scissor.y != cur_state.scissor.y ||
319 scissor.width != cur_state.scissor.width || scissor.height != cur_state.scissor.height) {
320 glScissor(scissor.x, scissor.y, scissor.width, scissor.height);
321 }
322
323 if (viewport.x != cur_state.viewport.x || viewport.y != cur_state.viewport.y ||
324 viewport.width != cur_state.viewport.width ||
325 viewport.height != cur_state.viewport.height) {
326 glViewport(viewport.x, viewport.y, viewport.width, viewport.height);
327 }
328
329 // Clip distance 469 // Clip distance
330 for (std::size_t i = 0; i < clip_distance.size(); ++i) { 470 for (std::size_t i = 0; i < clip_distance.size(); ++i) {
331 if (clip_distance[i] != cur_state.clip_distance[i]) { 471 if (clip_distance[i] != cur_state.clip_distance[i]) {
@@ -336,12 +476,22 @@ void OpenGLState::Apply() const {
336 } 476 }
337 } 477 }
338 } 478 }
339
340 // Point 479 // Point
341 if (point.size != cur_state.point.size) { 480 if (point.size != cur_state.point.size) {
342 glPointSize(point.size); 481 glPointSize(point.size);
343 } 482 }
344 483 ApplyColorMask();
484 ApplyViewport();
485 ApplyScissor();
486 ApplyStencilTest();
487 ApplySRgb();
488 ApplyCulling();
489 ApplyDepth();
490 ApplyPrimitiveRestart();
491 ApplyBlending();
492 ApplyLogicOp();
493 ApplyTextures();
494 ApplySamplers();
345 cur_state = *this; 495 cur_state = *this;
346} 496}
347 497
diff --git a/src/video_core/renderer_opengl/gl_state.h b/src/video_core/renderer_opengl/gl_state.h
index 9e2c573b5..eacca0b9c 100644
--- a/src/video_core/renderer_opengl/gl_state.h
+++ b/src/video_core/renderer_opengl/gl_state.h
@@ -46,11 +46,9 @@ public:
46 } cull; 46 } cull;
47 47
48 struct { 48 struct {
49 bool test_enabled; // GL_DEPTH_TEST 49 bool test_enabled; // GL_DEPTH_TEST
50 GLenum test_func; // GL_DEPTH_FUNC 50 GLenum test_func; // GL_DEPTH_FUNC
51 GLboolean write_mask; // GL_DEPTH_WRITEMASK 51 GLboolean write_mask; // GL_DEPTH_WRITEMASK
52 GLfloat depth_range_near; // GL_DEPTH_RANGE
53 GLfloat depth_range_far; // GL_DEPTH_RANGE
54 } depth; 52 } depth;
55 53
56 struct { 54 struct {
@@ -58,13 +56,14 @@ public:
58 GLuint index; 56 GLuint index;
59 } primitive_restart; // GL_PRIMITIVE_RESTART 57 } primitive_restart; // GL_PRIMITIVE_RESTART
60 58
61 struct { 59 struct ColorMask {
62 GLboolean red_enabled; 60 GLboolean red_enabled;
63 GLboolean green_enabled; 61 GLboolean green_enabled;
64 GLboolean blue_enabled; 62 GLboolean blue_enabled;
65 GLboolean alpha_enabled; 63 GLboolean alpha_enabled;
66 } color_mask; // GL_COLOR_WRITEMASK 64 };
67 65 std::array<ColorMask, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets>
66 color_mask; // GL_COLOR_WRITEMASK
68 struct { 67 struct {
69 bool test_enabled; // GL_STENCIL_TEST 68 bool test_enabled; // GL_STENCIL_TEST
70 struct { 69 struct {
@@ -78,22 +77,28 @@ public:
78 } front, back; 77 } front, back;
79 } stencil; 78 } stencil;
80 79
81 struct { 80 struct Blend {
82 bool enabled; // GL_BLEND 81 bool enabled; // GL_BLEND
82 bool separate_alpha; // Independent blend enabled
83 GLenum rgb_equation; // GL_BLEND_EQUATION_RGB 83 GLenum rgb_equation; // GL_BLEND_EQUATION_RGB
84 GLenum a_equation; // GL_BLEND_EQUATION_ALPHA 84 GLenum a_equation; // GL_BLEND_EQUATION_ALPHA
85 GLenum src_rgb_func; // GL_BLEND_SRC_RGB 85 GLenum src_rgb_func; // GL_BLEND_SRC_RGB
86 GLenum dst_rgb_func; // GL_BLEND_DST_RGB 86 GLenum dst_rgb_func; // GL_BLEND_DST_RGB
87 GLenum src_a_func; // GL_BLEND_SRC_ALPHA 87 GLenum src_a_func; // GL_BLEND_SRC_ALPHA
88 GLenum dst_a_func; // GL_BLEND_DST_ALPHA 88 GLenum dst_a_func; // GL_BLEND_DST_ALPHA
89 };
90 std::array<Blend, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> blend;
89 91
90 struct { 92 struct {
91 GLclampf red; 93 bool enabled;
92 GLclampf green; 94 } independant_blend;
93 GLclampf blue; 95
94 GLclampf alpha; 96 struct {
95 } color; // GL_BLEND_COLOR 97 GLclampf red;
96 } blend; 98 GLclampf green;
99 GLclampf blue;
100 GLclampf alpha;
101 } blend_color; // GL_BLEND_COLOR
97 102
98 struct { 103 struct {
99 bool enabled; // GL_LOGIC_OP_MODE 104 bool enabled; // GL_LOGIC_OP_MODE
@@ -138,6 +143,16 @@ public:
138 GLuint program_pipeline; // GL_PROGRAM_PIPELINE_BINDING 143 GLuint program_pipeline; // GL_PROGRAM_PIPELINE_BINDING
139 } draw; 144 } draw;
140 145
146 struct viewport {
147 GLfloat x;
148 GLfloat y;
149 GLfloat width;
150 GLfloat height;
151 GLfloat depth_range_near; // GL_DEPTH_RANGE
152 GLfloat depth_range_far; // GL_DEPTH_RANGE
153 };
154 std::array<viewport, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> viewports;
155
141 struct { 156 struct {
142 bool enabled; // GL_SCISSOR_TEST 157 bool enabled; // GL_SCISSOR_TEST
143 GLint x; 158 GLint x;
@@ -147,13 +162,6 @@ public:
147 } scissor; 162 } scissor;
148 163
149 struct { 164 struct {
150 GLint x;
151 GLint y;
152 GLsizei width;
153 GLsizei height;
154 } viewport;
155
156 struct {
157 float size; // GL_POINT_SIZE 165 float size; // GL_POINT_SIZE
158 } point; 166 } point;
159 167
@@ -173,7 +181,12 @@ public:
173 } 181 }
174 /// Apply this state as the current OpenGL state 182 /// Apply this state as the current OpenGL state
175 void Apply() const; 183 void Apply() const;
176 184 /// Apply only the state afecting the framebuffer
185 void ApplyFramebufferState() const;
186 /// Apply only the state afecting the vertex buffer
187 void ApplyVertexBufferState() const;
188 /// Set the initial OpenGL state
189 static void ApplyDefaultState();
177 /// Resets any references to the given resource 190 /// Resets any references to the given resource
178 OpenGLState& UnbindTexture(GLuint handle); 191 OpenGLState& UnbindTexture(GLuint handle);
179 OpenGLState& ResetSampler(GLuint handle); 192 OpenGLState& ResetSampler(GLuint handle);
@@ -188,6 +201,20 @@ private:
188 // Workaround for sRGB problems caused by 201 // Workaround for sRGB problems caused by
189 // QT not supporting srgb output 202 // QT not supporting srgb output
190 static bool s_rgb_used; 203 static bool s_rgb_used;
204 void ApplySRgb() const;
205 void ApplyCulling() const;
206 void ApplyColorMask() const;
207 void ApplyDepth() const;
208 void ApplyPrimitiveRestart() const;
209 void ApplyStencilTest() const;
210 void ApplyViewport() const;
211 void ApplyTargetBlending(int target, bool force) const;
212 void ApplyGlobalBlending() const;
213 void ApplyBlending() const;
214 void ApplyLogicOp() const;
215 void ApplyTextures() const;
216 void ApplySamplers() const;
217 void ApplyScissor() const;
191}; 218};
192 219
193} // namespace OpenGL 220} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_stream_buffer.cpp b/src/video_core/renderer_opengl/gl_stream_buffer.cpp
index e409228cc..b97b895a4 100644
--- a/src/video_core/renderer_opengl/gl_stream_buffer.cpp
+++ b/src/video_core/renderer_opengl/gl_stream_buffer.cpp
@@ -6,9 +6,13 @@
6#include <vector> 6#include <vector>
7#include "common/alignment.h" 7#include "common/alignment.h"
8#include "common/assert.h" 8#include "common/assert.h"
9#include "common/microprofile.h"
9#include "video_core/renderer_opengl/gl_state.h" 10#include "video_core/renderer_opengl/gl_state.h"
10#include "video_core/renderer_opengl/gl_stream_buffer.h" 11#include "video_core/renderer_opengl/gl_stream_buffer.h"
11 12
13MICROPROFILE_DEFINE(OpenGL_StreamBuffer, "OpenGL", "Stream Buffer Orphaning",
14 MP_RGB(128, 128, 192));
15
12namespace OpenGL { 16namespace OpenGL {
13 17
14OGLStreamBuffer::OGLStreamBuffer(GLenum target, GLsizeiptr size, bool prefer_coherent) 18OGLStreamBuffer::OGLStreamBuffer(GLenum target, GLsizeiptr size, bool prefer_coherent)
@@ -75,6 +79,7 @@ std::tuple<u8*, GLintptr, bool> OGLStreamBuffer::Map(GLsizeiptr size, GLintptr a
75 } 79 }
76 80
77 if (invalidate || !persistent) { 81 if (invalidate || !persistent) {
82 MICROPROFILE_SCOPE(OpenGL_StreamBuffer);
78 GLbitfield flags = GL_MAP_WRITE_BIT | (persistent ? GL_MAP_PERSISTENT_BIT : 0) | 83 GLbitfield flags = GL_MAP_WRITE_BIT | (persistent ? GL_MAP_PERSISTENT_BIT : 0) |
79 (coherent ? GL_MAP_COHERENT_BIT : GL_MAP_FLUSH_EXPLICIT_BIT) | 84 (coherent ? GL_MAP_COHERENT_BIT : GL_MAP_FLUSH_EXPLICIT_BIT) |
80 (invalidate ? GL_MAP_INVALIDATE_BUFFER_BIT : GL_MAP_UNSYNCHRONIZED_BIT); 85 (invalidate ? GL_MAP_INVALIDATE_BUFFER_BIT : GL_MAP_UNSYNCHRONIZED_BIT);
diff --git a/src/video_core/renderer_opengl/maxwell_to_gl.h b/src/video_core/renderer_opengl/maxwell_to_gl.h
index 0f6dcab2b..3ce2cc6d2 100644
--- a/src/video_core/renderer_opengl/maxwell_to_gl.h
+++ b/src/video_core/renderer_opengl/maxwell_to_gl.h
@@ -135,17 +135,32 @@ inline GLenum PrimitiveTopology(Maxwell::PrimitiveTopology topology) {
135 return {}; 135 return {};
136} 136}
137 137
138inline GLenum TextureFilterMode(Tegra::Texture::TextureFilter filter_mode) { 138inline GLenum TextureFilterMode(Tegra::Texture::TextureFilter filter_mode,
139 Tegra::Texture::TextureMipmapFilter mip_filter_mode) {
139 switch (filter_mode) { 140 switch (filter_mode) {
140 case Tegra::Texture::TextureFilter::Linear: 141 case Tegra::Texture::TextureFilter::Linear: {
141 return GL_LINEAR; 142 switch (mip_filter_mode) {
142 case Tegra::Texture::TextureFilter::Nearest: 143 case Tegra::Texture::TextureMipmapFilter::None:
143 return GL_NEAREST; 144 return GL_LINEAR;
145 case Tegra::Texture::TextureMipmapFilter::Nearest:
146 return GL_NEAREST_MIPMAP_LINEAR;
147 case Tegra::Texture::TextureMipmapFilter::Linear:
148 return GL_LINEAR_MIPMAP_LINEAR;
149 }
144 } 150 }
145 LOG_CRITICAL(Render_OpenGL, "Unimplemented texture filter mode={}", 151 case Tegra::Texture::TextureFilter::Nearest: {
146 static_cast<u32>(filter_mode)); 152 switch (mip_filter_mode) {
147 UNREACHABLE(); 153 case Tegra::Texture::TextureMipmapFilter::None:
148 return {}; 154 return GL_NEAREST;
155 case Tegra::Texture::TextureMipmapFilter::Nearest:
156 return GL_NEAREST_MIPMAP_NEAREST;
157 case Tegra::Texture::TextureMipmapFilter::Linear:
158 return GL_LINEAR_MIPMAP_NEAREST;
159 }
160 }
161 }
162 LOG_ERROR(Render_OpenGL, "Unimplemented texture filter mode={}", static_cast<u32>(filter_mode));
163 return GL_LINEAR;
149} 164}
150 165
151inline GLenum WrapMode(Tegra::Texture::WrapMode wrap_mode) { 166inline GLenum WrapMode(Tegra::Texture::WrapMode wrap_mode) {
@@ -166,9 +181,8 @@ inline GLenum WrapMode(Tegra::Texture::WrapMode wrap_mode) {
166 case Tegra::Texture::WrapMode::MirrorOnceClampToEdge: 181 case Tegra::Texture::WrapMode::MirrorOnceClampToEdge:
167 return GL_MIRROR_CLAMP_TO_EDGE; 182 return GL_MIRROR_CLAMP_TO_EDGE;
168 } 183 }
169 LOG_CRITICAL(Render_OpenGL, "Unimplemented texture wrap mode={}", static_cast<u32>(wrap_mode)); 184 LOG_ERROR(Render_OpenGL, "Unimplemented texture wrap mode={}", static_cast<u32>(wrap_mode));
170 UNREACHABLE(); 185 return GL_REPEAT;
171 return {};
172} 186}
173 187
174inline GLenum DepthCompareFunc(Tegra::Texture::DepthCompareFunc func) { 188inline GLenum DepthCompareFunc(Tegra::Texture::DepthCompareFunc func) {
@@ -190,10 +204,9 @@ inline GLenum DepthCompareFunc(Tegra::Texture::DepthCompareFunc func) {
190 case Tegra::Texture::DepthCompareFunc::Always: 204 case Tegra::Texture::DepthCompareFunc::Always:
191 return GL_ALWAYS; 205 return GL_ALWAYS;
192 } 206 }
193 LOG_CRITICAL(Render_OpenGL, "Unimplemented texture depth compare function ={}", 207 LOG_ERROR(Render_OpenGL, "Unimplemented texture depth compare function ={}",
194 static_cast<u32>(func)); 208 static_cast<u32>(func));
195 UNREACHABLE(); 209 return GL_GREATER;
196 return {};
197} 210}
198 211
199inline GLenum BlendEquation(Maxwell::Blend::Equation equation) { 212inline GLenum BlendEquation(Maxwell::Blend::Equation equation) {
@@ -209,9 +222,8 @@ inline GLenum BlendEquation(Maxwell::Blend::Equation equation) {
209 case Maxwell::Blend::Equation::Max: 222 case Maxwell::Blend::Equation::Max:
210 return GL_MAX; 223 return GL_MAX;
211 } 224 }
212 LOG_CRITICAL(Render_OpenGL, "Unimplemented blend equation={}", static_cast<u32>(equation)); 225 LOG_ERROR(Render_OpenGL, "Unimplemented blend equation={}", static_cast<u32>(equation));
213 UNREACHABLE(); 226 return GL_FUNC_ADD;
214 return {};
215} 227}
216 228
217inline GLenum BlendFunc(Maxwell::Blend::Factor factor) { 229inline GLenum BlendFunc(Maxwell::Blend::Factor factor) {
@@ -274,9 +286,8 @@ inline GLenum BlendFunc(Maxwell::Blend::Factor factor) {
274 case Maxwell::Blend::Factor::OneMinusConstantAlphaGL: 286 case Maxwell::Blend::Factor::OneMinusConstantAlphaGL:
275 return GL_ONE_MINUS_CONSTANT_ALPHA; 287 return GL_ONE_MINUS_CONSTANT_ALPHA;
276 } 288 }
277 LOG_CRITICAL(Render_OpenGL, "Unimplemented blend factor={}", static_cast<u32>(factor)); 289 LOG_ERROR(Render_OpenGL, "Unimplemented blend factor={}", static_cast<u32>(factor));
278 UNREACHABLE(); 290 return GL_ZERO;
279 return {};
280} 291}
281 292
282inline GLenum SwizzleSource(Tegra::Texture::SwizzleSource source) { 293inline GLenum SwizzleSource(Tegra::Texture::SwizzleSource source) {
@@ -295,9 +306,8 @@ inline GLenum SwizzleSource(Tegra::Texture::SwizzleSource source) {
295 case Tegra::Texture::SwizzleSource::OneFloat: 306 case Tegra::Texture::SwizzleSource::OneFloat:
296 return GL_ONE; 307 return GL_ONE;
297 } 308 }
298 LOG_CRITICAL(Render_OpenGL, "Unimplemented swizzle source={}", static_cast<u32>(source)); 309 LOG_ERROR(Render_OpenGL, "Unimplemented swizzle source={}", static_cast<u32>(source));
299 UNREACHABLE(); 310 return GL_ZERO;
300 return {};
301} 311}
302 312
303inline GLenum ComparisonOp(Maxwell::ComparisonOp comparison) { 313inline GLenum ComparisonOp(Maxwell::ComparisonOp comparison) {
@@ -327,33 +337,39 @@ inline GLenum ComparisonOp(Maxwell::ComparisonOp comparison) {
327 case Maxwell::ComparisonOp::AlwaysOld: 337 case Maxwell::ComparisonOp::AlwaysOld:
328 return GL_ALWAYS; 338 return GL_ALWAYS;
329 } 339 }
330 LOG_CRITICAL(Render_OpenGL, "Unimplemented comparison op={}", static_cast<u32>(comparison)); 340 LOG_ERROR(Render_OpenGL, "Unimplemented comparison op={}", static_cast<u32>(comparison));
331 UNREACHABLE(); 341 return GL_ALWAYS;
332 return {};
333} 342}
334 343
335inline GLenum StencilOp(Maxwell::StencilOp stencil) { 344inline GLenum StencilOp(Maxwell::StencilOp stencil) {
336 switch (stencil) { 345 switch (stencil) {
337 case Maxwell::StencilOp::Keep: 346 case Maxwell::StencilOp::Keep:
347 case Maxwell::StencilOp::KeepOGL:
338 return GL_KEEP; 348 return GL_KEEP;
339 case Maxwell::StencilOp::Zero: 349 case Maxwell::StencilOp::Zero:
350 case Maxwell::StencilOp::ZeroOGL:
340 return GL_ZERO; 351 return GL_ZERO;
341 case Maxwell::StencilOp::Replace: 352 case Maxwell::StencilOp::Replace:
353 case Maxwell::StencilOp::ReplaceOGL:
342 return GL_REPLACE; 354 return GL_REPLACE;
343 case Maxwell::StencilOp::Incr: 355 case Maxwell::StencilOp::Incr:
356 case Maxwell::StencilOp::IncrOGL:
344 return GL_INCR; 357 return GL_INCR;
345 case Maxwell::StencilOp::Decr: 358 case Maxwell::StencilOp::Decr:
359 case Maxwell::StencilOp::DecrOGL:
346 return GL_DECR; 360 return GL_DECR;
347 case Maxwell::StencilOp::Invert: 361 case Maxwell::StencilOp::Invert:
362 case Maxwell::StencilOp::InvertOGL:
348 return GL_INVERT; 363 return GL_INVERT;
349 case Maxwell::StencilOp::IncrWrap: 364 case Maxwell::StencilOp::IncrWrap:
365 case Maxwell::StencilOp::IncrWrapOGL:
350 return GL_INCR_WRAP; 366 return GL_INCR_WRAP;
351 case Maxwell::StencilOp::DecrWrap: 367 case Maxwell::StencilOp::DecrWrap:
368 case Maxwell::StencilOp::DecrWrapOGL:
352 return GL_DECR_WRAP; 369 return GL_DECR_WRAP;
353 } 370 }
354 LOG_CRITICAL(Render_OpenGL, "Unimplemented stencil op={}", static_cast<u32>(stencil)); 371 LOG_ERROR(Render_OpenGL, "Unimplemented stencil op={}", static_cast<u32>(stencil));
355 UNREACHABLE(); 372 return GL_KEEP;
356 return {};
357} 373}
358 374
359inline GLenum FrontFace(Maxwell::Cull::FrontFace front_face) { 375inline GLenum FrontFace(Maxwell::Cull::FrontFace front_face) {
@@ -363,9 +379,8 @@ inline GLenum FrontFace(Maxwell::Cull::FrontFace front_face) {
363 case Maxwell::Cull::FrontFace::CounterClockWise: 379 case Maxwell::Cull::FrontFace::CounterClockWise:
364 return GL_CCW; 380 return GL_CCW;
365 } 381 }
366 LOG_CRITICAL(Render_OpenGL, "Unimplemented front face cull={}", static_cast<u32>(front_face)); 382 LOG_ERROR(Render_OpenGL, "Unimplemented front face cull={}", static_cast<u32>(front_face));
367 UNREACHABLE(); 383 return GL_CCW;
368 return {};
369} 384}
370 385
371inline GLenum CullFace(Maxwell::Cull::CullFace cull_face) { 386inline GLenum CullFace(Maxwell::Cull::CullFace cull_face) {
@@ -377,9 +392,8 @@ inline GLenum CullFace(Maxwell::Cull::CullFace cull_face) {
377 case Maxwell::Cull::CullFace::FrontAndBack: 392 case Maxwell::Cull::CullFace::FrontAndBack:
378 return GL_FRONT_AND_BACK; 393 return GL_FRONT_AND_BACK;
379 } 394 }
380 LOG_CRITICAL(Render_OpenGL, "Unimplemented cull face={}", static_cast<u32>(cull_face)); 395 LOG_ERROR(Render_OpenGL, "Unimplemented cull face={}", static_cast<u32>(cull_face));
381 UNREACHABLE(); 396 return GL_BACK;
382 return {};
383} 397}
384 398
385inline GLenum LogicOp(Maxwell::LogicOperation operation) { 399inline GLenum LogicOp(Maxwell::LogicOperation operation) {
@@ -417,9 +431,8 @@ inline GLenum LogicOp(Maxwell::LogicOperation operation) {
417 case Maxwell::LogicOperation::Set: 431 case Maxwell::LogicOperation::Set:
418 return GL_SET; 432 return GL_SET;
419 } 433 }
420 LOG_CRITICAL(Render_OpenGL, "Unimplemented logic operation={}", static_cast<u32>(operation)); 434 LOG_ERROR(Render_OpenGL, "Unimplemented logic operation={}", static_cast<u32>(operation));
421 UNREACHABLE(); 435 return GL_COPY;
422 return {};
423} 436}
424 437
425} // namespace MaxwellToGL 438} // namespace MaxwellToGL
diff --git a/src/video_core/renderer_opengl/renderer_opengl.cpp b/src/video_core/renderer_opengl/renderer_opengl.cpp
index 90b68943d..ea38da932 100644
--- a/src/video_core/renderer_opengl/renderer_opengl.cpp
+++ b/src/video_core/renderer_opengl/renderer_opengl.cpp
@@ -115,7 +115,8 @@ RendererOpenGL::RendererOpenGL(Core::Frontend::EmuWindow& window)
115RendererOpenGL::~RendererOpenGL() = default; 115RendererOpenGL::~RendererOpenGL() = default;
116 116
117/// Swap buffers (render frame) 117/// Swap buffers (render frame)
118void RendererOpenGL::SwapBuffers(boost::optional<const Tegra::FramebufferConfig&> framebuffer) { 118void RendererOpenGL::SwapBuffers(
119 std::optional<std::reference_wrapper<const Tegra::FramebufferConfig>> framebuffer) {
119 ScopeAcquireGLContext acquire_context{render_window}; 120 ScopeAcquireGLContext acquire_context{render_window};
120 121
121 Core::System::GetInstance().GetPerfStats().EndSystemFrame(); 122 Core::System::GetInstance().GetPerfStats().EndSystemFrame();
@@ -124,11 +125,11 @@ void RendererOpenGL::SwapBuffers(boost::optional<const Tegra::FramebufferConfig&
124 OpenGLState prev_state = OpenGLState::GetCurState(); 125 OpenGLState prev_state = OpenGLState::GetCurState();
125 state.Apply(); 126 state.Apply();
126 127
127 if (framebuffer != boost::none) { 128 if (framebuffer) {
128 // If framebuffer is provided, reload it from memory to a texture 129 // If framebuffer is provided, reload it from memory to a texture
129 if (screen_info.texture.width != (GLsizei)framebuffer->width || 130 if (screen_info.texture.width != (GLsizei)framebuffer->get().width ||
130 screen_info.texture.height != (GLsizei)framebuffer->height || 131 screen_info.texture.height != (GLsizei)framebuffer->get().height ||
131 screen_info.texture.pixel_format != framebuffer->pixel_format) { 132 screen_info.texture.pixel_format != framebuffer->get().pixel_format) {
132 // Reallocate texture if the framebuffer size has changed. 133 // Reallocate texture if the framebuffer size has changed.
133 // This is expected to not happen very often and hence should not be a 134 // This is expected to not happen very often and hence should not be a
134 // performance problem. 135 // performance problem.
diff --git a/src/video_core/renderer_opengl/renderer_opengl.h b/src/video_core/renderer_opengl/renderer_opengl.h
index 961467a62..c0868c0e4 100644
--- a/src/video_core/renderer_opengl/renderer_opengl.h
+++ b/src/video_core/renderer_opengl/renderer_opengl.h
@@ -51,7 +51,8 @@ public:
51 ~RendererOpenGL() override; 51 ~RendererOpenGL() override;
52 52
53 /// Swap buffers (render frame) 53 /// Swap buffers (render frame)
54 void SwapBuffers(boost::optional<const Tegra::FramebufferConfig&> framebuffer) override; 54 void SwapBuffers(
55 std::optional<std::reference_wrapper<const Tegra::FramebufferConfig>> framebuffer) override;
55 56
56 /// Initialize the renderer 57 /// Initialize the renderer
57 bool Init() override; 58 bool Init() override;
diff --git a/src/video_core/surface.cpp b/src/video_core/surface.cpp
new file mode 100644
index 000000000..9582dd2ca
--- /dev/null
+++ b/src/video_core/surface.cpp
@@ -0,0 +1,490 @@
1// Copyright 2014 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/common_types.h"
6#include "common/math_util.h"
7#include "video_core/surface.h"
8
9namespace VideoCore::Surface {
10
11SurfaceTarget SurfaceTargetFromTextureType(Tegra::Texture::TextureType texture_type) {
12 switch (texture_type) {
13 case Tegra::Texture::TextureType::Texture1D:
14 return SurfaceTarget::Texture1D;
15 case Tegra::Texture::TextureType::Texture2D:
16 case Tegra::Texture::TextureType::Texture2DNoMipmap:
17 return SurfaceTarget::Texture2D;
18 case Tegra::Texture::TextureType::Texture3D:
19 return SurfaceTarget::Texture3D;
20 case Tegra::Texture::TextureType::TextureCubemap:
21 return SurfaceTarget::TextureCubemap;
22 case Tegra::Texture::TextureType::TextureCubeArray:
23 return SurfaceTarget::TextureCubeArray;
24 case Tegra::Texture::TextureType::Texture1DArray:
25 return SurfaceTarget::Texture1DArray;
26 case Tegra::Texture::TextureType::Texture2DArray:
27 return SurfaceTarget::Texture2DArray;
28 default:
29 LOG_CRITICAL(HW_GPU, "Unimplemented texture_type={}", static_cast<u32>(texture_type));
30 UNREACHABLE();
31 return SurfaceTarget::Texture2D;
32 }
33}
34
35bool SurfaceTargetIsLayered(SurfaceTarget target) {
36 switch (target) {
37 case SurfaceTarget::Texture1D:
38 case SurfaceTarget::Texture2D:
39 case SurfaceTarget::Texture3D:
40 return false;
41 case SurfaceTarget::Texture1DArray:
42 case SurfaceTarget::Texture2DArray:
43 case SurfaceTarget::TextureCubemap:
44 case SurfaceTarget::TextureCubeArray:
45 return true;
46 default:
47 LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target));
48 UNREACHABLE();
49 return false;
50 }
51}
52
53PixelFormat PixelFormatFromDepthFormat(Tegra::DepthFormat format) {
54 switch (format) {
55 case Tegra::DepthFormat::S8_Z24_UNORM:
56 return PixelFormat::S8Z24;
57 case Tegra::DepthFormat::Z24_S8_UNORM:
58 return PixelFormat::Z24S8;
59 case Tegra::DepthFormat::Z32_FLOAT:
60 return PixelFormat::Z32F;
61 case Tegra::DepthFormat::Z16_UNORM:
62 return PixelFormat::Z16;
63 case Tegra::DepthFormat::Z32_S8_X24_FLOAT:
64 return PixelFormat::Z32FS8;
65 default:
66 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
67 UNREACHABLE();
68 }
69}
70
71PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format) {
72 switch (format) {
73 // TODO (Hexagon12): Converting SRGBA to RGBA is a hack and doesn't completely correct the
74 // gamma.
75 case Tegra::RenderTargetFormat::RGBA8_SRGB:
76 return PixelFormat::RGBA8_SRGB;
77 case Tegra::RenderTargetFormat::RGBA8_UNORM:
78 return PixelFormat::ABGR8U;
79 case Tegra::RenderTargetFormat::RGBA8_SNORM:
80 return PixelFormat::ABGR8S;
81 case Tegra::RenderTargetFormat::RGBA8_UINT:
82 return PixelFormat::ABGR8UI;
83 case Tegra::RenderTargetFormat::BGRA8_SRGB:
84 return PixelFormat::BGRA8_SRGB;
85 case Tegra::RenderTargetFormat::BGRA8_UNORM:
86 return PixelFormat::BGRA8;
87 case Tegra::RenderTargetFormat::RGB10_A2_UNORM:
88 return PixelFormat::A2B10G10R10U;
89 case Tegra::RenderTargetFormat::RGBA16_FLOAT:
90 return PixelFormat::RGBA16F;
91 case Tegra::RenderTargetFormat::RGBA16_UNORM:
92 return PixelFormat::RGBA16U;
93 case Tegra::RenderTargetFormat::RGBA16_UINT:
94 return PixelFormat::RGBA16UI;
95 case Tegra::RenderTargetFormat::RGBA32_FLOAT:
96 return PixelFormat::RGBA32F;
97 case Tegra::RenderTargetFormat::RG32_FLOAT:
98 return PixelFormat::RG32F;
99 case Tegra::RenderTargetFormat::R11G11B10_FLOAT:
100 return PixelFormat::R11FG11FB10F;
101 case Tegra::RenderTargetFormat::B5G6R5_UNORM:
102 return PixelFormat::B5G6R5U;
103 case Tegra::RenderTargetFormat::BGR5A1_UNORM:
104 return PixelFormat::A1B5G5R5U;
105 case Tegra::RenderTargetFormat::RGBA32_UINT:
106 return PixelFormat::RGBA32UI;
107 case Tegra::RenderTargetFormat::R8_UNORM:
108 return PixelFormat::R8U;
109 case Tegra::RenderTargetFormat::R8_UINT:
110 return PixelFormat::R8UI;
111 case Tegra::RenderTargetFormat::RG16_FLOAT:
112 return PixelFormat::RG16F;
113 case Tegra::RenderTargetFormat::RG16_UINT:
114 return PixelFormat::RG16UI;
115 case Tegra::RenderTargetFormat::RG16_SINT:
116 return PixelFormat::RG16I;
117 case Tegra::RenderTargetFormat::RG16_UNORM:
118 return PixelFormat::RG16;
119 case Tegra::RenderTargetFormat::RG16_SNORM:
120 return PixelFormat::RG16S;
121 case Tegra::RenderTargetFormat::RG8_UNORM:
122 return PixelFormat::RG8U;
123 case Tegra::RenderTargetFormat::RG8_SNORM:
124 return PixelFormat::RG8S;
125 case Tegra::RenderTargetFormat::R16_FLOAT:
126 return PixelFormat::R16F;
127 case Tegra::RenderTargetFormat::R16_UNORM:
128 return PixelFormat::R16U;
129 case Tegra::RenderTargetFormat::R16_SNORM:
130 return PixelFormat::R16S;
131 case Tegra::RenderTargetFormat::R16_UINT:
132 return PixelFormat::R16UI;
133 case Tegra::RenderTargetFormat::R16_SINT:
134 return PixelFormat::R16I;
135 case Tegra::RenderTargetFormat::R32_FLOAT:
136 return PixelFormat::R32F;
137 case Tegra::RenderTargetFormat::R32_UINT:
138 return PixelFormat::R32UI;
139 case Tegra::RenderTargetFormat::RG32_UINT:
140 return PixelFormat::RG32UI;
141 default:
142 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
143 UNREACHABLE();
144 }
145}
146
147PixelFormat PixelFormatFromTextureFormat(Tegra::Texture::TextureFormat format,
148 Tegra::Texture::ComponentType component_type,
149 bool is_srgb) {
150 // TODO(Subv): Properly implement this
151 switch (format) {
152 case Tegra::Texture::TextureFormat::A8R8G8B8:
153 if (is_srgb) {
154 return PixelFormat::RGBA8_SRGB;
155 }
156 switch (component_type) {
157 case Tegra::Texture::ComponentType::UNORM:
158 return PixelFormat::ABGR8U;
159 case Tegra::Texture::ComponentType::SNORM:
160 return PixelFormat::ABGR8S;
161 case Tegra::Texture::ComponentType::UINT:
162 return PixelFormat::ABGR8UI;
163 }
164 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
165 UNREACHABLE();
166 case Tegra::Texture::TextureFormat::B5G6R5:
167 switch (component_type) {
168 case Tegra::Texture::ComponentType::UNORM:
169 return PixelFormat::B5G6R5U;
170 }
171 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
172 UNREACHABLE();
173 case Tegra::Texture::TextureFormat::A2B10G10R10:
174 switch (component_type) {
175 case Tegra::Texture::ComponentType::UNORM:
176 return PixelFormat::A2B10G10R10U;
177 }
178 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
179 UNREACHABLE();
180 case Tegra::Texture::TextureFormat::A1B5G5R5:
181 switch (component_type) {
182 case Tegra::Texture::ComponentType::UNORM:
183 return PixelFormat::A1B5G5R5U;
184 }
185 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
186 UNREACHABLE();
187 case Tegra::Texture::TextureFormat::R8:
188 switch (component_type) {
189 case Tegra::Texture::ComponentType::UNORM:
190 return PixelFormat::R8U;
191 case Tegra::Texture::ComponentType::UINT:
192 return PixelFormat::R8UI;
193 }
194 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
195 UNREACHABLE();
196 case Tegra::Texture::TextureFormat::G8R8:
197 switch (component_type) {
198 case Tegra::Texture::ComponentType::UNORM:
199 return PixelFormat::G8R8U;
200 case Tegra::Texture::ComponentType::SNORM:
201 return PixelFormat::G8R8S;
202 }
203 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
204 UNREACHABLE();
205 case Tegra::Texture::TextureFormat::R16_G16_B16_A16:
206 switch (component_type) {
207 case Tegra::Texture::ComponentType::UNORM:
208 return PixelFormat::RGBA16U;
209 case Tegra::Texture::ComponentType::FLOAT:
210 return PixelFormat::RGBA16F;
211 }
212 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
213 UNREACHABLE();
214 case Tegra::Texture::TextureFormat::BF10GF11RF11:
215 switch (component_type) {
216 case Tegra::Texture::ComponentType::FLOAT:
217 return PixelFormat::R11FG11FB10F;
218 }
219 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
220 UNREACHABLE();
221 case Tegra::Texture::TextureFormat::R32_G32_B32_A32:
222 switch (component_type) {
223 case Tegra::Texture::ComponentType::FLOAT:
224 return PixelFormat::RGBA32F;
225 case Tegra::Texture::ComponentType::UINT:
226 return PixelFormat::RGBA32UI;
227 }
228 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
229 UNREACHABLE();
230 case Tegra::Texture::TextureFormat::R32_G32:
231 switch (component_type) {
232 case Tegra::Texture::ComponentType::FLOAT:
233 return PixelFormat::RG32F;
234 case Tegra::Texture::ComponentType::UINT:
235 return PixelFormat::RG32UI;
236 }
237 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
238 UNREACHABLE();
239 case Tegra::Texture::TextureFormat::R32_G32_B32:
240 switch (component_type) {
241 case Tegra::Texture::ComponentType::FLOAT:
242 return PixelFormat::RGB32F;
243 }
244 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
245 UNREACHABLE();
246 case Tegra::Texture::TextureFormat::R16:
247 switch (component_type) {
248 case Tegra::Texture::ComponentType::FLOAT:
249 return PixelFormat::R16F;
250 case Tegra::Texture::ComponentType::UNORM:
251 return PixelFormat::R16U;
252 case Tegra::Texture::ComponentType::SNORM:
253 return PixelFormat::R16S;
254 case Tegra::Texture::ComponentType::UINT:
255 return PixelFormat::R16UI;
256 case Tegra::Texture::ComponentType::SINT:
257 return PixelFormat::R16I;
258 }
259 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
260 UNREACHABLE();
261 case Tegra::Texture::TextureFormat::R32:
262 switch (component_type) {
263 case Tegra::Texture::ComponentType::FLOAT:
264 return PixelFormat::R32F;
265 case Tegra::Texture::ComponentType::UINT:
266 return PixelFormat::R32UI;
267 }
268 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
269 UNREACHABLE();
270 case Tegra::Texture::TextureFormat::ZF32:
271 return PixelFormat::Z32F;
272 case Tegra::Texture::TextureFormat::Z16:
273 return PixelFormat::Z16;
274 case Tegra::Texture::TextureFormat::Z24S8:
275 return PixelFormat::Z24S8;
276 case Tegra::Texture::TextureFormat::DXT1:
277 return is_srgb ? PixelFormat::DXT1_SRGB : PixelFormat::DXT1;
278 case Tegra::Texture::TextureFormat::DXT23:
279 return is_srgb ? PixelFormat::DXT23_SRGB : PixelFormat::DXT23;
280 case Tegra::Texture::TextureFormat::DXT45:
281 return is_srgb ? PixelFormat::DXT45_SRGB : PixelFormat::DXT45;
282 case Tegra::Texture::TextureFormat::DXN1:
283 return PixelFormat::DXN1;
284 case Tegra::Texture::TextureFormat::DXN2:
285 switch (component_type) {
286 case Tegra::Texture::ComponentType::UNORM:
287 return PixelFormat::DXN2UNORM;
288 case Tegra::Texture::ComponentType::SNORM:
289 return PixelFormat::DXN2SNORM;
290 }
291 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
292 UNREACHABLE();
293 case Tegra::Texture::TextureFormat::BC7U:
294 return is_srgb ? PixelFormat::BC7U_SRGB : PixelFormat::BC7U;
295 case Tegra::Texture::TextureFormat::BC6H_UF16:
296 return PixelFormat::BC6H_UF16;
297 case Tegra::Texture::TextureFormat::BC6H_SF16:
298 return PixelFormat::BC6H_SF16;
299 case Tegra::Texture::TextureFormat::ASTC_2D_4X4:
300 return is_srgb ? PixelFormat::ASTC_2D_4X4_SRGB : PixelFormat::ASTC_2D_4X4;
301 case Tegra::Texture::TextureFormat::ASTC_2D_5X4:
302 return is_srgb ? PixelFormat::ASTC_2D_5X4_SRGB : PixelFormat::ASTC_2D_5X4;
303 case Tegra::Texture::TextureFormat::ASTC_2D_5X5:
304 return is_srgb ? PixelFormat::ASTC_2D_5X5_SRGB : PixelFormat::ASTC_2D_5X5;
305 case Tegra::Texture::TextureFormat::ASTC_2D_8X8:
306 return is_srgb ? PixelFormat::ASTC_2D_8X8_SRGB : PixelFormat::ASTC_2D_8X8;
307 case Tegra::Texture::TextureFormat::ASTC_2D_8X5:
308 return is_srgb ? PixelFormat::ASTC_2D_8X5_SRGB : PixelFormat::ASTC_2D_8X5;
309 case Tegra::Texture::TextureFormat::ASTC_2D_10X8:
310 return is_srgb ? PixelFormat::ASTC_2D_10X8_SRGB : PixelFormat::ASTC_2D_10X8;
311 case Tegra::Texture::TextureFormat::R16_G16:
312 switch (component_type) {
313 case Tegra::Texture::ComponentType::FLOAT:
314 return PixelFormat::RG16F;
315 case Tegra::Texture::ComponentType::UNORM:
316 return PixelFormat::RG16;
317 case Tegra::Texture::ComponentType::SNORM:
318 return PixelFormat::RG16S;
319 case Tegra::Texture::ComponentType::UINT:
320 return PixelFormat::RG16UI;
321 case Tegra::Texture::ComponentType::SINT:
322 return PixelFormat::RG16I;
323 }
324 LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
325 UNREACHABLE();
326 default:
327 LOG_CRITICAL(HW_GPU, "Unimplemented format={}, component_type={}", static_cast<u32>(format),
328 static_cast<u32>(component_type));
329 UNREACHABLE();
330 }
331}
332
333ComponentType ComponentTypeFromTexture(Tegra::Texture::ComponentType type) {
334 // TODO(Subv): Implement more component types
335 switch (type) {
336 case Tegra::Texture::ComponentType::UNORM:
337 return ComponentType::UNorm;
338 case Tegra::Texture::ComponentType::FLOAT:
339 return ComponentType::Float;
340 case Tegra::Texture::ComponentType::SNORM:
341 return ComponentType::SNorm;
342 case Tegra::Texture::ComponentType::UINT:
343 return ComponentType::UInt;
344 case Tegra::Texture::ComponentType::SINT:
345 return ComponentType::SInt;
346 default:
347 LOG_CRITICAL(HW_GPU, "Unimplemented component type={}", static_cast<u32>(type));
348 UNREACHABLE();
349 }
350}
351
352ComponentType ComponentTypeFromRenderTarget(Tegra::RenderTargetFormat format) {
353 // TODO(Subv): Implement more render targets
354 switch (format) {
355 case Tegra::RenderTargetFormat::RGBA8_UNORM:
356 case Tegra::RenderTargetFormat::RGBA8_SRGB:
357 case Tegra::RenderTargetFormat::BGRA8_UNORM:
358 case Tegra::RenderTargetFormat::BGRA8_SRGB:
359 case Tegra::RenderTargetFormat::RGB10_A2_UNORM:
360 case Tegra::RenderTargetFormat::R8_UNORM:
361 case Tegra::RenderTargetFormat::RG16_UNORM:
362 case Tegra::RenderTargetFormat::R16_UNORM:
363 case Tegra::RenderTargetFormat::B5G6R5_UNORM:
364 case Tegra::RenderTargetFormat::BGR5A1_UNORM:
365 case Tegra::RenderTargetFormat::RG8_UNORM:
366 case Tegra::RenderTargetFormat::RGBA16_UNORM:
367 return ComponentType::UNorm;
368 case Tegra::RenderTargetFormat::RGBA8_SNORM:
369 case Tegra::RenderTargetFormat::RG16_SNORM:
370 case Tegra::RenderTargetFormat::R16_SNORM:
371 case Tegra::RenderTargetFormat::RG8_SNORM:
372 return ComponentType::SNorm;
373 case Tegra::RenderTargetFormat::RGBA16_FLOAT:
374 case Tegra::RenderTargetFormat::R11G11B10_FLOAT:
375 case Tegra::RenderTargetFormat::RGBA32_FLOAT:
376 case Tegra::RenderTargetFormat::RG32_FLOAT:
377 case Tegra::RenderTargetFormat::RG16_FLOAT:
378 case Tegra::RenderTargetFormat::R16_FLOAT:
379 case Tegra::RenderTargetFormat::R32_FLOAT:
380 return ComponentType::Float;
381 case Tegra::RenderTargetFormat::RGBA32_UINT:
382 case Tegra::RenderTargetFormat::RGBA16_UINT:
383 case Tegra::RenderTargetFormat::RG16_UINT:
384 case Tegra::RenderTargetFormat::R8_UINT:
385 case Tegra::RenderTargetFormat::R16_UINT:
386 case Tegra::RenderTargetFormat::RG32_UINT:
387 case Tegra::RenderTargetFormat::R32_UINT:
388 case Tegra::RenderTargetFormat::RGBA8_UINT:
389 return ComponentType::UInt;
390 case Tegra::RenderTargetFormat::RG16_SINT:
391 case Tegra::RenderTargetFormat::R16_SINT:
392 return ComponentType::SInt;
393 default:
394 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
395 UNREACHABLE();
396 }
397}
398
399PixelFormat PixelFormatFromGPUPixelFormat(Tegra::FramebufferConfig::PixelFormat format) {
400 switch (format) {
401 case Tegra::FramebufferConfig::PixelFormat::ABGR8:
402 return PixelFormat::ABGR8U;
403 default:
404 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
405 UNREACHABLE();
406 }
407}
408
409ComponentType ComponentTypeFromDepthFormat(Tegra::DepthFormat format) {
410 switch (format) {
411 case Tegra::DepthFormat::Z16_UNORM:
412 case Tegra::DepthFormat::S8_Z24_UNORM:
413 case Tegra::DepthFormat::Z24_S8_UNORM:
414 return ComponentType::UNorm;
415 case Tegra::DepthFormat::Z32_FLOAT:
416 case Tegra::DepthFormat::Z32_S8_X24_FLOAT:
417 return ComponentType::Float;
418 default:
419 LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
420 UNREACHABLE();
421 }
422}
423
424SurfaceType GetFormatType(PixelFormat pixel_format) {
425 if (static_cast<std::size_t>(pixel_format) <
426 static_cast<std::size_t>(PixelFormat::MaxColorFormat)) {
427 return SurfaceType::ColorTexture;
428 }
429
430 if (static_cast<std::size_t>(pixel_format) <
431 static_cast<std::size_t>(PixelFormat::MaxDepthFormat)) {
432 return SurfaceType::Depth;
433 }
434
435 if (static_cast<std::size_t>(pixel_format) <
436 static_cast<std::size_t>(PixelFormat::MaxDepthStencilFormat)) {
437 return SurfaceType::DepthStencil;
438 }
439
440 // TODO(Subv): Implement the other formats
441 ASSERT(false);
442
443 return SurfaceType::Invalid;
444}
445
446bool IsPixelFormatASTC(PixelFormat format) {
447 switch (format) {
448 case PixelFormat::ASTC_2D_4X4:
449 case PixelFormat::ASTC_2D_5X4:
450 case PixelFormat::ASTC_2D_5X5:
451 case PixelFormat::ASTC_2D_8X8:
452 case PixelFormat::ASTC_2D_8X5:
453 case PixelFormat::ASTC_2D_4X4_SRGB:
454 case PixelFormat::ASTC_2D_5X4_SRGB:
455 case PixelFormat::ASTC_2D_5X5_SRGB:
456 case PixelFormat::ASTC_2D_8X8_SRGB:
457 case PixelFormat::ASTC_2D_8X5_SRGB:
458 case PixelFormat::ASTC_2D_10X8:
459 case PixelFormat::ASTC_2D_10X8_SRGB:
460 return true;
461 default:
462 return false;
463 }
464}
465
466std::pair<u32, u32> GetASTCBlockSize(PixelFormat format) {
467 return {GetDefaultBlockWidth(format), GetDefaultBlockHeight(format)};
468}
469
470bool IsFormatBCn(PixelFormat format) {
471 switch (format) {
472 case PixelFormat::DXT1:
473 case PixelFormat::DXT23:
474 case PixelFormat::DXT45:
475 case PixelFormat::DXN1:
476 case PixelFormat::DXN2SNORM:
477 case PixelFormat::DXN2UNORM:
478 case PixelFormat::BC7U:
479 case PixelFormat::BC6H_UF16:
480 case PixelFormat::BC6H_SF16:
481 case PixelFormat::DXT1_SRGB:
482 case PixelFormat::DXT23_SRGB:
483 case PixelFormat::DXT45_SRGB:
484 case PixelFormat::BC7U_SRGB:
485 return true;
486 }
487 return false;
488}
489
490} // namespace VideoCore::Surface
diff --git a/src/video_core/surface.h b/src/video_core/surface.h
new file mode 100644
index 000000000..0dd3eb2e4
--- /dev/null
+++ b/src/video_core/surface.h
@@ -0,0 +1,477 @@
1// Copyright 2014 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <climits>
8#include <utility>
9#include "common/assert.h"
10#include "common/common_types.h"
11#include "common/logging/log.h"
12#include "video_core/gpu.h"
13#include "video_core/textures/texture.h"
14
15namespace VideoCore::Surface {
16
17enum class PixelFormat {
18 ABGR8U = 0,
19 ABGR8S = 1,
20 ABGR8UI = 2,
21 B5G6R5U = 3,
22 A2B10G10R10U = 4,
23 A1B5G5R5U = 5,
24 R8U = 6,
25 R8UI = 7,
26 RGBA16F = 8,
27 RGBA16U = 9,
28 RGBA16UI = 10,
29 R11FG11FB10F = 11,
30 RGBA32UI = 12,
31 DXT1 = 13,
32 DXT23 = 14,
33 DXT45 = 15,
34 DXN1 = 16, // This is also known as BC4
35 DXN2UNORM = 17,
36 DXN2SNORM = 18,
37 BC7U = 19,
38 BC6H_UF16 = 20,
39 BC6H_SF16 = 21,
40 ASTC_2D_4X4 = 22,
41 G8R8U = 23,
42 G8R8S = 24,
43 BGRA8 = 25,
44 RGBA32F = 26,
45 RG32F = 27,
46 R32F = 28,
47 R16F = 29,
48 R16U = 30,
49 R16S = 31,
50 R16UI = 32,
51 R16I = 33,
52 RG16 = 34,
53 RG16F = 35,
54 RG16UI = 36,
55 RG16I = 37,
56 RG16S = 38,
57 RGB32F = 39,
58 RGBA8_SRGB = 40,
59 RG8U = 41,
60 RG8S = 42,
61 RG32UI = 43,
62 R32UI = 44,
63 ASTC_2D_8X8 = 45,
64 ASTC_2D_8X5 = 46,
65 ASTC_2D_5X4 = 47,
66 BGRA8_SRGB = 48,
67 DXT1_SRGB = 49,
68 DXT23_SRGB = 50,
69 DXT45_SRGB = 51,
70 BC7U_SRGB = 52,
71 ASTC_2D_4X4_SRGB = 53,
72 ASTC_2D_8X8_SRGB = 54,
73 ASTC_2D_8X5_SRGB = 55,
74 ASTC_2D_5X4_SRGB = 56,
75 ASTC_2D_5X5 = 57,
76 ASTC_2D_5X5_SRGB = 58,
77 ASTC_2D_10X8 = 59,
78 ASTC_2D_10X8_SRGB = 60,
79
80 MaxColorFormat,
81
82 // Depth formats
83 Z32F = 61,
84 Z16 = 62,
85
86 MaxDepthFormat,
87
88 // DepthStencil formats
89 Z24S8 = 63,
90 S8Z24 = 64,
91 Z32FS8 = 65,
92
93 MaxDepthStencilFormat,
94
95 Max = MaxDepthStencilFormat,
96 Invalid = 255,
97};
98
99static constexpr std::size_t MaxPixelFormat = static_cast<std::size_t>(PixelFormat::Max);
100
101enum class ComponentType {
102 Invalid = 0,
103 SNorm = 1,
104 UNorm = 2,
105 SInt = 3,
106 UInt = 4,
107 Float = 5,
108};
109
110enum class SurfaceType {
111 ColorTexture = 0,
112 Depth = 1,
113 DepthStencil = 2,
114 Fill = 3,
115 Invalid = 4,
116};
117
118enum class SurfaceTarget {
119 Texture1D,
120 Texture2D,
121 Texture3D,
122 Texture1DArray,
123 Texture2DArray,
124 TextureCubemap,
125 TextureCubeArray,
126};
127
128/**
129 * Gets the compression factor for the specified PixelFormat. This applies to just the
130 * "compressed width" and "compressed height", not the overall compression factor of a
131 * compressed image. This is used for maintaining proper surface sizes for compressed
132 * texture formats.
133 */
134static constexpr u32 GetCompressionFactor(PixelFormat format) {
135 if (format == PixelFormat::Invalid)
136 return 0;
137
138 constexpr std::array<u32, MaxPixelFormat> compression_factor_table = {{
139 1, // ABGR8U
140 1, // ABGR8S
141 1, // ABGR8UI
142 1, // B5G6R5U
143 1, // A2B10G10R10U
144 1, // A1B5G5R5U
145 1, // R8U
146 1, // R8UI
147 1, // RGBA16F
148 1, // RGBA16U
149 1, // RGBA16UI
150 1, // R11FG11FB10F
151 1, // RGBA32UI
152 4, // DXT1
153 4, // DXT23
154 4, // DXT45
155 4, // DXN1
156 4, // DXN2UNORM
157 4, // DXN2SNORM
158 4, // BC7U
159 4, // BC6H_UF16
160 4, // BC6H_SF16
161 4, // ASTC_2D_4X4
162 1, // G8R8U
163 1, // G8R8S
164 1, // BGRA8
165 1, // RGBA32F
166 1, // RG32F
167 1, // R32F
168 1, // R16F
169 1, // R16U
170 1, // R16S
171 1, // R16UI
172 1, // R16I
173 1, // RG16
174 1, // RG16F
175 1, // RG16UI
176 1, // RG16I
177 1, // RG16S
178 1, // RGB32F
179 1, // RGBA8_SRGB
180 1, // RG8U
181 1, // RG8S
182 1, // RG32UI
183 1, // R32UI
184 4, // ASTC_2D_8X8
185 4, // ASTC_2D_8X5
186 4, // ASTC_2D_5X4
187 1, // BGRA8_SRGB
188 4, // DXT1_SRGB
189 4, // DXT23_SRGB
190 4, // DXT45_SRGB
191 4, // BC7U_SRGB
192 4, // ASTC_2D_4X4_SRGB
193 4, // ASTC_2D_8X8_SRGB
194 4, // ASTC_2D_8X5_SRGB
195 4, // ASTC_2D_5X4_SRGB
196 4, // ASTC_2D_5X5
197 4, // ASTC_2D_5X5_SRGB
198 4, // ASTC_2D_10X8
199 4, // ASTC_2D_10X8_SRGB
200 1, // Z32F
201 1, // Z16
202 1, // Z24S8
203 1, // S8Z24
204 1, // Z32FS8
205 }};
206
207 ASSERT(static_cast<std::size_t>(format) < compression_factor_table.size());
208 return compression_factor_table[static_cast<std::size_t>(format)];
209}
210
211static constexpr u32 GetDefaultBlockWidth(PixelFormat format) {
212 if (format == PixelFormat::Invalid)
213 return 0;
214 constexpr std::array<u32, MaxPixelFormat> block_width_table = {{
215 1, // ABGR8U
216 1, // ABGR8S
217 1, // ABGR8UI
218 1, // B5G6R5U
219 1, // A2B10G10R10U
220 1, // A1B5G5R5U
221 1, // R8U
222 1, // R8UI
223 1, // RGBA16F
224 1, // RGBA16U
225 1, // RGBA16UI
226 1, // R11FG11FB10F
227 1, // RGBA32UI
228 4, // DXT1
229 4, // DXT23
230 4, // DXT45
231 4, // DXN1
232 4, // DXN2UNORM
233 4, // DXN2SNORM
234 4, // BC7U
235 4, // BC6H_UF16
236 4, // BC6H_SF16
237 4, // ASTC_2D_4X4
238 1, // G8R8U
239 1, // G8R8S
240 1, // BGRA8
241 1, // RGBA32F
242 1, // RG32F
243 1, // R32F
244 1, // R16F
245 1, // R16U
246 1, // R16S
247 1, // R16UI
248 1, // R16I
249 1, // RG16
250 1, // RG16F
251 1, // RG16UI
252 1, // RG16I
253 1, // RG16S
254 1, // RGB32F
255 1, // RGBA8_SRGB
256 1, // RG8U
257 1, // RG8S
258 1, // RG32UI
259 1, // R32UI
260 8, // ASTC_2D_8X8
261 8, // ASTC_2D_8X5
262 5, // ASTC_2D_5X4
263 1, // BGRA8_SRGB
264 4, // DXT1_SRGB
265 4, // DXT23_SRGB
266 4, // DXT45_SRGB
267 4, // BC7U_SRGB
268 4, // ASTC_2D_4X4_SRGB
269 8, // ASTC_2D_8X8_SRGB
270 8, // ASTC_2D_8X5_SRGB
271 5, // ASTC_2D_5X4_SRGB
272 5, // ASTC_2D_5X5
273 5, // ASTC_2D_5X5_SRGB
274 10, // ASTC_2D_10X8
275 10, // ASTC_2D_10X8_SRGB
276 1, // Z32F
277 1, // Z16
278 1, // Z24S8
279 1, // S8Z24
280 1, // Z32FS8
281 }};
282 ASSERT(static_cast<std::size_t>(format) < block_width_table.size());
283 return block_width_table[static_cast<std::size_t>(format)];
284}
285
286static constexpr u32 GetDefaultBlockHeight(PixelFormat format) {
287 if (format == PixelFormat::Invalid)
288 return 0;
289
290 constexpr std::array<u32, MaxPixelFormat> block_height_table = {{
291 1, // ABGR8U
292 1, // ABGR8S
293 1, // ABGR8UI
294 1, // B5G6R5U
295 1, // A2B10G10R10U
296 1, // A1B5G5R5U
297 1, // R8U
298 1, // R8UI
299 1, // RGBA16F
300 1, // RGBA16U
301 1, // RGBA16UI
302 1, // R11FG11FB10F
303 1, // RGBA32UI
304 4, // DXT1
305 4, // DXT23
306 4, // DXT45
307 4, // DXN1
308 4, // DXN2UNORM
309 4, // DXN2SNORM
310 4, // BC7U
311 4, // BC6H_UF16
312 4, // BC6H_SF16
313 4, // ASTC_2D_4X4
314 1, // G8R8U
315 1, // G8R8S
316 1, // BGRA8
317 1, // RGBA32F
318 1, // RG32F
319 1, // R32F
320 1, // R16F
321 1, // R16U
322 1, // R16S
323 1, // R16UI
324 1, // R16I
325 1, // RG16
326 1, // RG16F
327 1, // RG16UI
328 1, // RG16I
329 1, // RG16S
330 1, // RGB32F
331 1, // RGBA8_SRGB
332 1, // RG8U
333 1, // RG8S
334 1, // RG32UI
335 1, // R32UI
336 8, // ASTC_2D_8X8
337 5, // ASTC_2D_8X5
338 4, // ASTC_2D_5X4
339 1, // BGRA8_SRGB
340 4, // DXT1_SRGB
341 4, // DXT23_SRGB
342 4, // DXT45_SRGB
343 4, // BC7U_SRGB
344 4, // ASTC_2D_4X4_SRGB
345 8, // ASTC_2D_8X8_SRGB
346 5, // ASTC_2D_8X5_SRGB
347 4, // ASTC_2D_5X4_SRGB
348 5, // ASTC_2D_5X5
349 5, // ASTC_2D_5X5_SRGB
350 8, // ASTC_2D_10X8
351 8, // ASTC_2D_10X8_SRGB
352 1, // Z32F
353 1, // Z16
354 1, // Z24S8
355 1, // S8Z24
356 1, // Z32FS8
357 }};
358
359 ASSERT(static_cast<std::size_t>(format) < block_height_table.size());
360 return block_height_table[static_cast<std::size_t>(format)];
361}
362
363static constexpr u32 GetFormatBpp(PixelFormat format) {
364 if (format == PixelFormat::Invalid)
365 return 0;
366
367 constexpr std::array<u32, MaxPixelFormat> bpp_table = {{
368 32, // ABGR8U
369 32, // ABGR8S
370 32, // ABGR8UI
371 16, // B5G6R5U
372 32, // A2B10G10R10U
373 16, // A1B5G5R5U
374 8, // R8U
375 8, // R8UI
376 64, // RGBA16F
377 64, // RGBA16U
378 64, // RGBA16UI
379 32, // R11FG11FB10F
380 128, // RGBA32UI
381 64, // DXT1
382 128, // DXT23
383 128, // DXT45
384 64, // DXN1
385 128, // DXN2UNORM
386 128, // DXN2SNORM
387 128, // BC7U
388 128, // BC6H_UF16
389 128, // BC6H_SF16
390 128, // ASTC_2D_4X4
391 16, // G8R8U
392 16, // G8R8S
393 32, // BGRA8
394 128, // RGBA32F
395 64, // RG32F
396 32, // R32F
397 16, // R16F
398 16, // R16U
399 16, // R16S
400 16, // R16UI
401 16, // R16I
402 32, // RG16
403 32, // RG16F
404 32, // RG16UI
405 32, // RG16I
406 32, // RG16S
407 96, // RGB32F
408 32, // RGBA8_SRGB
409 16, // RG8U
410 16, // RG8S
411 64, // RG32UI
412 32, // R32UI
413 128, // ASTC_2D_8X8
414 128, // ASTC_2D_8X5
415 128, // ASTC_2D_5X4
416 32, // BGRA8_SRGB
417 64, // DXT1_SRGB
418 128, // DXT23_SRGB
419 128, // DXT45_SRGB
420 128, // BC7U
421 128, // ASTC_2D_4X4_SRGB
422 128, // ASTC_2D_8X8_SRGB
423 128, // ASTC_2D_8X5_SRGB
424 128, // ASTC_2D_5X4_SRGB
425 128, // ASTC_2D_5X5
426 128, // ASTC_2D_5X5_SRGB
427 128, // ASTC_2D_10X8
428 128, // ASTC_2D_10X8_SRGB
429 32, // Z32F
430 16, // Z16
431 32, // Z24S8
432 32, // S8Z24
433 64, // Z32FS8
434 }};
435
436 ASSERT(static_cast<std::size_t>(format) < bpp_table.size());
437 return bpp_table[static_cast<std::size_t>(format)];
438}
439
440/// Returns the sizer in bytes of the specified pixel format
441static constexpr u32 GetBytesPerPixel(PixelFormat pixel_format) {
442 if (pixel_format == PixelFormat::Invalid) {
443 return 0;
444 }
445 return GetFormatBpp(pixel_format) / CHAR_BIT;
446}
447
448SurfaceTarget SurfaceTargetFromTextureType(Tegra::Texture::TextureType texture_type);
449
450bool SurfaceTargetIsLayered(SurfaceTarget target);
451
452PixelFormat PixelFormatFromDepthFormat(Tegra::DepthFormat format);
453
454PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format);
455
456PixelFormat PixelFormatFromTextureFormat(Tegra::Texture::TextureFormat format,
457 Tegra::Texture::ComponentType component_type,
458 bool is_srgb);
459
460ComponentType ComponentTypeFromTexture(Tegra::Texture::ComponentType type);
461
462ComponentType ComponentTypeFromRenderTarget(Tegra::RenderTargetFormat format);
463
464PixelFormat PixelFormatFromGPUPixelFormat(Tegra::FramebufferConfig::PixelFormat format);
465
466ComponentType ComponentTypeFromDepthFormat(Tegra::DepthFormat format);
467
468SurfaceType GetFormatType(PixelFormat pixel_format);
469
470bool IsPixelFormatASTC(PixelFormat format);
471
472std::pair<u32, u32> GetASTCBlockSize(PixelFormat format);
473
474/// Returns true if the specified PixelFormat is a BCn format, e.g. DXT or DXN
475bool IsFormatBCn(PixelFormat format);
476
477} // namespace VideoCore::Surface
diff --git a/src/video_core/textures/astc.cpp b/src/video_core/textures/astc.cpp
index b1feacae9..bc50a4876 100644
--- a/src/video_core/textures/astc.cpp
+++ b/src/video_core/textures/astc.cpp
@@ -1598,27 +1598,29 @@ static void DecompressBlock(uint8_t inBuf[16], const uint32_t blockWidth,
1598namespace Tegra::Texture::ASTC { 1598namespace Tegra::Texture::ASTC {
1599 1599
1600std::vector<uint8_t> Decompress(std::vector<uint8_t>& data, uint32_t width, uint32_t height, 1600std::vector<uint8_t> Decompress(std::vector<uint8_t>& data, uint32_t width, uint32_t height,
1601 uint32_t block_width, uint32_t block_height) { 1601 uint32_t depth, uint32_t block_width, uint32_t block_height) {
1602 uint32_t blockIdx = 0; 1602 uint32_t blockIdx = 0;
1603 std::vector<uint8_t> outData(height * width * 4); 1603 std::vector<uint8_t> outData(height * width * depth * 4);
1604 for (uint32_t j = 0; j < height; j += block_height) { 1604 for (uint32_t k = 0; k < depth; k++) {
1605 for (uint32_t i = 0; i < width; i += block_width) { 1605 for (uint32_t j = 0; j < height; j += block_height) {
1606 for (uint32_t i = 0; i < width; i += block_width) {
1606 1607
1607 uint8_t* blockPtr = data.data() + blockIdx * 16; 1608 uint8_t* blockPtr = data.data() + blockIdx * 16;
1608 1609
1609 // Blocks can be at most 12x12 1610 // Blocks can be at most 12x12
1610 uint32_t uncompData[144]; 1611 uint32_t uncompData[144];
1611 ASTCC::DecompressBlock(blockPtr, block_width, block_height, uncompData); 1612 ASTCC::DecompressBlock(blockPtr, block_width, block_height, uncompData);
1612 1613
1613 uint32_t decompWidth = std::min(block_width, width - i); 1614 uint32_t decompWidth = std::min(block_width, width - i);
1614 uint32_t decompHeight = std::min(block_height, height - j); 1615 uint32_t decompHeight = std::min(block_height, height - j);
1615 1616
1616 uint8_t* outRow = outData.data() + (j * width + i) * 4; 1617 uint8_t* outRow = outData.data() + (j * width + i) * 4;
1617 for (uint32_t jj = 0; jj < decompHeight; jj++) { 1618 for (uint32_t jj = 0; jj < decompHeight; jj++) {
1618 memcpy(outRow + jj * width * 4, uncompData + jj * block_width, decompWidth * 4); 1619 memcpy(outRow + jj * width * 4, uncompData + jj * block_width, decompWidth * 4);
1619 } 1620 }
1620 1621
1621 blockIdx++; 1622 blockIdx++;
1623 }
1622 } 1624 }
1623 } 1625 }
1624 1626
diff --git a/src/video_core/textures/astc.h b/src/video_core/textures/astc.h
index f0d7c0e56..d419dd025 100644
--- a/src/video_core/textures/astc.h
+++ b/src/video_core/textures/astc.h
@@ -10,6 +10,6 @@
10namespace Tegra::Texture::ASTC { 10namespace Tegra::Texture::ASTC {
11 11
12std::vector<uint8_t> Decompress(std::vector<uint8_t>& data, uint32_t width, uint32_t height, 12std::vector<uint8_t> Decompress(std::vector<uint8_t>& data, uint32_t width, uint32_t height,
13 uint32_t block_width, uint32_t block_height); 13 uint32_t depth, uint32_t block_width, uint32_t block_height);
14 14
15} // namespace Tegra::Texture::ASTC 15} // namespace Tegra::Texture::ASTC
diff --git a/src/video_core/textures/decoders.cpp b/src/video_core/textures/decoders.cpp
index 550ca856c..a9d134d14 100644
--- a/src/video_core/textures/decoders.cpp
+++ b/src/video_core/textures/decoders.cpp
@@ -202,6 +202,8 @@ u32 BytesPerPixel(TextureFormat format) {
202 case TextureFormat::ASTC_2D_5X4: 202 case TextureFormat::ASTC_2D_5X4:
203 case TextureFormat::ASTC_2D_8X8: 203 case TextureFormat::ASTC_2D_8X8:
204 case TextureFormat::ASTC_2D_8X5: 204 case TextureFormat::ASTC_2D_8X5:
205 case TextureFormat::ASTC_2D_10X8:
206 case TextureFormat::ASTC_2D_5X5:
205 case TextureFormat::A8R8G8B8: 207 case TextureFormat::A8R8G8B8:
206 case TextureFormat::A2B10G10R10: 208 case TextureFormat::A2B10G10R10:
207 case TextureFormat::BF10GF11RF11: 209 case TextureFormat::BF10GF11RF11:
@@ -227,12 +229,14 @@ u32 BytesPerPixel(TextureFormat format) {
227 } 229 }
228} 230}
229 231
230std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size, u32 bytes_per_pixel, u32 width, 232std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size_x, u32 tile_size_y,
231 u32 height, u32 depth, u32 block_height, u32 block_depth) { 233 u32 bytes_per_pixel, u32 width, u32 height, u32 depth,
234 u32 block_height, u32 block_depth) {
232 std::vector<u8> unswizzled_data(width * height * depth * bytes_per_pixel); 235 std::vector<u8> unswizzled_data(width * height * depth * bytes_per_pixel);
233 CopySwizzledData(width / tile_size, height / tile_size, depth, bytes_per_pixel, bytes_per_pixel, 236 CopySwizzledData((width + tile_size_x - 1) / tile_size_x,
234 Memory::GetPointer(address), unswizzled_data.data(), true, block_height, 237 (height + tile_size_y - 1) / tile_size_y, depth, bytes_per_pixel,
235 block_depth); 238 bytes_per_pixel, Memory::GetPointer(address), unswizzled_data.data(), true,
239 block_height, block_depth);
236 return unswizzled_data; 240 return unswizzled_data;
237} 241}
238 242
@@ -292,6 +296,8 @@ std::vector<u8> DecodeTexture(const std::vector<u8>& texture_data, TextureFormat
292 case TextureFormat::BC6H_SF16: 296 case TextureFormat::BC6H_SF16:
293 case TextureFormat::ASTC_2D_4X4: 297 case TextureFormat::ASTC_2D_4X4:
294 case TextureFormat::ASTC_2D_8X8: 298 case TextureFormat::ASTC_2D_8X8:
299 case TextureFormat::ASTC_2D_5X5:
300 case TextureFormat::ASTC_2D_10X8:
295 case TextureFormat::A8R8G8B8: 301 case TextureFormat::A8R8G8B8:
296 case TextureFormat::A2B10G10R10: 302 case TextureFormat::A2B10G10R10:
297 case TextureFormat::A1B5G5R5: 303 case TextureFormat::A1B5G5R5:
diff --git a/src/video_core/textures/decoders.h b/src/video_core/textures/decoders.h
index 4726f54a5..ba065510b 100644
--- a/src/video_core/textures/decoders.h
+++ b/src/video_core/textures/decoders.h
@@ -10,11 +10,17 @@
10 10
11namespace Tegra::Texture { 11namespace Tegra::Texture {
12 12
13// GOBSize constant. Calculated by 64 bytes in x multiplied by 8 y coords, represents
14// an small rect of (64/bytes_per_pixel)X8.
15inline std::size_t GetGOBSize() {
16 return 512;
17}
18
13/** 19/**
14 * Unswizzles a swizzled texture without changing its format. 20 * Unswizzles a swizzled texture without changing its format.
15 */ 21 */
16std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size, u32 bytes_per_pixel, u32 width, 22std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size_x, u32 tile_size_y,
17 u32 height, u32 depth, 23 u32 bytes_per_pixel, u32 width, u32 height, u32 depth,
18 u32 block_height = TICEntry::DefaultBlockHeight, 24 u32 block_height = TICEntry::DefaultBlockHeight,
19 u32 block_depth = TICEntry::DefaultBlockHeight); 25 u32 block_depth = TICEntry::DefaultBlockHeight);
20 26
diff --git a/src/video_core/textures/texture.h b/src/video_core/textures/texture.h
index d12d2ecb8..e199d019a 100644
--- a/src/video_core/textures/texture.h
+++ b/src/video_core/textures/texture.h
@@ -168,20 +168,29 @@ struct TICEntry {
168 168
169 // High 16 bits of the pitch value 169 // High 16 bits of the pitch value
170 BitField<0, 16, u32> pitch_high; 170 BitField<0, 16, u32> pitch_high;
171 171 BitField<26, 1, u32> use_header_opt_control;
172 BitField<27, 1, u32> depth_texture;
172 BitField<28, 4, u32> max_mip_level; 173 BitField<28, 4, u32> max_mip_level;
173 }; 174 };
174 union { 175 union {
175 BitField<0, 16, u32> width_minus_1; 176 BitField<0, 16, u32> width_minus_1;
176 BitField<22, 1, u32> srgb_conversion; 177 BitField<22, 1, u32> srgb_conversion;
177 BitField<23, 4, TextureType> texture_type; 178 BitField<23, 4, TextureType> texture_type;
179 BitField<29, 3, u32> border_size;
178 }; 180 };
179 union { 181 union {
180 BitField<0, 16, u32> height_minus_1; 182 BitField<0, 16, u32> height_minus_1;
181 BitField<16, 15, u32> depth_minus_1; 183 BitField<16, 15, u32> depth_minus_1;
182 }; 184 };
185 union {
186 BitField<6, 13, u32> mip_lod_bias;
187 BitField<27, 3, u32> max_anisotropy;
188 };
183 189
184 INSERT_PADDING_BYTES(8); 190 union {
191 BitField<0, 4, u32> res_min_mip_level;
192 BitField<4, 4, u32> res_max_mip_level;
193 };
185 194
186 GPUVAddr Address() const { 195 GPUVAddr Address() const {
187 return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) | address_low); 196 return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) | address_low);
diff --git a/src/web_service/telemetry_json.cpp b/src/web_service/telemetry_json.cpp
index 0a8f2bd9e..9156ce802 100644
--- a/src/web_service/telemetry_json.cpp
+++ b/src/web_service/telemetry_json.cpp
@@ -102,16 +102,27 @@ void TelemetryJson::Complete() {
102 impl->SerializeSection(Telemetry::FieldType::App, "App"); 102 impl->SerializeSection(Telemetry::FieldType::App, "App");
103 impl->SerializeSection(Telemetry::FieldType::Session, "Session"); 103 impl->SerializeSection(Telemetry::FieldType::Session, "Session");
104 impl->SerializeSection(Telemetry::FieldType::Performance, "Performance"); 104 impl->SerializeSection(Telemetry::FieldType::Performance, "Performance");
105 impl->SerializeSection(Telemetry::FieldType::UserFeedback, "UserFeedback");
106 impl->SerializeSection(Telemetry::FieldType::UserConfig, "UserConfig"); 105 impl->SerializeSection(Telemetry::FieldType::UserConfig, "UserConfig");
107 impl->SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem"); 106 impl->SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem");
108 107
109 auto content = impl->TopSection().dump(); 108 auto content = impl->TopSection().dump();
110 // Send the telemetry async but don't handle the errors since they were written to the log 109 // Send the telemetry async but don't handle the errors since they were written to the log
111 Common::DetachedTasks::AddTask( 110 Common::DetachedTasks::AddTask([host{impl->host}, content]() {
112 [host{impl->host}, username{impl->username}, token{impl->token}, content]() { 111 Client{host, "", ""}.PostJson("/telemetry", content, true);
113 Client{host, username, token}.PostJson("/telemetry", content, true); 112 });
114 }); 113}
114
115bool TelemetryJson::SubmitTestcase() {
116 impl->SerializeSection(Telemetry::FieldType::App, "App");
117 impl->SerializeSection(Telemetry::FieldType::Session, "Session");
118 impl->SerializeSection(Telemetry::FieldType::UserFeedback, "UserFeedback");
119 impl->SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem");
120
121 auto content = impl->TopSection().dump();
122 Client client(impl->host, impl->username, impl->token);
123 auto value = client.PostJson("/gamedb/testcase", content, false);
124
125 return value.result_code == Common::WebResult::Code::Success;
115} 126}
116 127
117} // namespace WebService 128} // namespace WebService
diff --git a/src/web_service/telemetry_json.h b/src/web_service/telemetry_json.h
index 93371414a..dfd202829 100644
--- a/src/web_service/telemetry_json.h
+++ b/src/web_service/telemetry_json.h
@@ -35,6 +35,7 @@ public:
35 void Visit(const Telemetry::Field<std::chrono::microseconds>& field) override; 35 void Visit(const Telemetry::Field<std::chrono::microseconds>& field) override;
36 36
37 void Complete() override; 37 void Complete() override;
38 bool SubmitTestcase() override;
38 39
39private: 40private:
40 struct Impl; 41 struct Impl;
diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt
index 9379d9110..f9ca2948e 100644
--- a/src/yuzu/CMakeLists.txt
+++ b/src/yuzu/CMakeLists.txt
@@ -56,6 +56,8 @@ add_executable(yuzu
56 main.h 56 main.h
57 ui_settings.cpp 57 ui_settings.cpp
58 ui_settings.h 58 ui_settings.h
59 util/limitable_input_dialog.cpp
60 util/limitable_input_dialog.h
59 util/spinbox.cpp 61 util/spinbox.cpp
60 util/spinbox.h 62 util/spinbox.h
61 util/util.cpp 63 util/util.cpp
diff --git a/src/yuzu/compatdb.cpp b/src/yuzu/compatdb.cpp
index 91e754274..5f0896f84 100644
--- a/src/yuzu/compatdb.cpp
+++ b/src/yuzu/compatdb.cpp
@@ -5,6 +5,7 @@
5#include <QButtonGroup> 5#include <QButtonGroup>
6#include <QMessageBox> 6#include <QMessageBox>
7#include <QPushButton> 7#include <QPushButton>
8#include <QtConcurrent/qtconcurrentrun.h>
8#include "common/logging/log.h" 9#include "common/logging/log.h"
9#include "common/telemetry.h" 10#include "common/telemetry.h"
10#include "core/core.h" 11#include "core/core.h"
@@ -23,6 +24,8 @@ CompatDB::CompatDB(QWidget* parent)
23 connect(ui->radioButton_IntroMenu, &QRadioButton::clicked, this, &CompatDB::EnableNext); 24 connect(ui->radioButton_IntroMenu, &QRadioButton::clicked, this, &CompatDB::EnableNext);
24 connect(ui->radioButton_WontBoot, &QRadioButton::clicked, this, &CompatDB::EnableNext); 25 connect(ui->radioButton_WontBoot, &QRadioButton::clicked, this, &CompatDB::EnableNext);
25 connect(button(NextButton), &QPushButton::clicked, this, &CompatDB::Submit); 26 connect(button(NextButton), &QPushButton::clicked, this, &CompatDB::Submit);
27 connect(&testcase_watcher, &QFutureWatcher<bool>::finished, this,
28 &CompatDB::OnTestcaseSubmitted);
26} 29}
27 30
28CompatDB::~CompatDB() = default; 31CompatDB::~CompatDB() = default;
@@ -48,18 +51,38 @@ void CompatDB::Submit() {
48 } 51 }
49 break; 52 break;
50 case CompatDBPage::Final: 53 case CompatDBPage::Final:
54 back();
51 LOG_DEBUG(Frontend, "Compatibility Rating: {}", compatibility->checkedId()); 55 LOG_DEBUG(Frontend, "Compatibility Rating: {}", compatibility->checkedId());
52 Core::Telemetry().AddField(Telemetry::FieldType::UserFeedback, "Compatibility", 56 Core::Telemetry().AddField(Telemetry::FieldType::UserFeedback, "Compatibility",
53 compatibility->checkedId()); 57 compatibility->checkedId());
54 // older versions of QT don't support the "NoCancelButtonOnLastPage" option, this is a 58
55 // workaround 59 button(NextButton)->setEnabled(false);
60 button(NextButton)->setText(tr("Submitting"));
56 button(QWizard::CancelButton)->setVisible(false); 61 button(QWizard::CancelButton)->setVisible(false);
62
63 testcase_watcher.setFuture(QtConcurrent::run(
64 [this]() { return Core::System::GetInstance().TelemetrySession().SubmitTestcase(); }));
57 break; 65 break;
58 default: 66 default:
59 LOG_ERROR(Frontend, "Unexpected page: {}", currentId()); 67 LOG_ERROR(Frontend, "Unexpected page: {}", currentId());
60 } 68 }
61} 69}
62 70
71void CompatDB::OnTestcaseSubmitted() {
72 if (!testcase_watcher.result()) {
73 QMessageBox::critical(this, tr("Communication error"),
74 tr("An error occured while sending the Testcase"));
75 button(NextButton)->setEnabled(true);
76 button(NextButton)->setText(tr("Next"));
77 button(QWizard::CancelButton)->setVisible(true);
78 } else {
79 next();
80 // older versions of QT don't support the "NoCancelButtonOnLastPage" option, this is a
81 // workaround
82 button(QWizard::CancelButton)->setVisible(false);
83 }
84}
85
63void CompatDB::EnableNext() { 86void CompatDB::EnableNext() {
64 button(NextButton)->setEnabled(true); 87 button(NextButton)->setEnabled(true);
65} 88}
diff --git a/src/yuzu/compatdb.h b/src/yuzu/compatdb.h
index ca0dd11d6..5381f67f7 100644
--- a/src/yuzu/compatdb.h
+++ b/src/yuzu/compatdb.h
@@ -5,6 +5,7 @@
5#pragma once 5#pragma once
6 6
7#include <memory> 7#include <memory>
8#include <QFutureWatcher>
8#include <QWizard> 9#include <QWizard>
9 10
10namespace Ui { 11namespace Ui {
@@ -19,8 +20,11 @@ public:
19 ~CompatDB(); 20 ~CompatDB();
20 21
21private: 22private:
23 QFutureWatcher<bool> testcase_watcher;
24
22 std::unique_ptr<Ui::CompatDB> ui; 25 std::unique_ptr<Ui::CompatDB> ui;
23 26
24 void Submit(); 27 void Submit();
28 void OnTestcaseSubmitted();
25 void EnableNext(); 29 void EnableNext();
26}; 30};
diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp
index b85011cd6..60606bb33 100644
--- a/src/yuzu/configuration/config.cpp
+++ b/src/yuzu/configuration/config.cpp
@@ -134,6 +134,14 @@ void Config::ReadValues() {
134 Service::Account::MAX_USERS - 1); 134 Service::Account::MAX_USERS - 1);
135 135
136 Settings::values.language_index = qt_config->value("language_index", 1).toInt(); 136 Settings::values.language_index = qt_config->value("language_index", 1).toInt();
137
138 const auto enabled = qt_config->value("rng_seed_enabled", false).toBool();
139 if (enabled) {
140 Settings::values.rng_seed = qt_config->value("rng_seed", 0).toULongLong();
141 } else {
142 Settings::values.rng_seed = std::nullopt;
143 }
144
137 qt_config->endGroup(); 145 qt_config->endGroup();
138 146
139 qt_config->beginGroup("Miscellaneous"); 147 qt_config->beginGroup("Miscellaneous");
@@ -273,6 +281,10 @@ void Config::SaveValues() {
273 qt_config->setValue("current_user", Settings::values.current_user); 281 qt_config->setValue("current_user", Settings::values.current_user);
274 282
275 qt_config->setValue("language_index", Settings::values.language_index); 283 qt_config->setValue("language_index", Settings::values.language_index);
284
285 qt_config->setValue("rng_seed_enabled", Settings::values.rng_seed.has_value());
286 qt_config->setValue("rng_seed", Settings::values.rng_seed.value_or(0));
287
276 qt_config->endGroup(); 288 qt_config->endGroup();
277 289
278 qt_config->beginGroup("Miscellaneous"); 290 qt_config->beginGroup("Miscellaneous");
diff --git a/src/yuzu/configuration/configure_general.cpp b/src/yuzu/configuration/configure_general.cpp
index 537d6e576..b322258a0 100644
--- a/src/yuzu/configuration/configure_general.cpp
+++ b/src/yuzu/configuration/configure_general.cpp
@@ -3,6 +3,10 @@
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include "core/core.h" 5#include "core/core.h"
6#include "core/hle/service/am/am.h"
7#include "core/hle/service/am/applet_ae.h"
8#include "core/hle/service/am/applet_oe.h"
9#include "core/hle/service/sm/sm.h"
6#include "core/settings.h" 10#include "core/settings.h"
7#include "ui_configure_general.h" 11#include "ui_configure_general.h"
8#include "yuzu/configuration/configure_general.h" 12#include "yuzu/configuration/configure_general.h"
@@ -20,7 +24,6 @@ ConfigureGeneral::ConfigureGeneral(QWidget* parent)
20 this->setConfiguration(); 24 this->setConfiguration();
21 25
22 ui->use_cpu_jit->setEnabled(!Core::System::GetInstance().IsPoweredOn()); 26 ui->use_cpu_jit->setEnabled(!Core::System::GetInstance().IsPoweredOn());
23 ui->use_docked_mode->setEnabled(!Core::System::GetInstance().IsPoweredOn());
24} 27}
25 28
26ConfigureGeneral::~ConfigureGeneral() = default; 29ConfigureGeneral::~ConfigureGeneral() = default;
@@ -38,6 +41,30 @@ void ConfigureGeneral::PopulateHotkeyList(const HotkeyRegistry& registry) {
38 ui->widget->Populate(registry); 41 ui->widget->Populate(registry);
39} 42}
40 43
44void ConfigureGeneral::OnDockedModeChanged(bool last_state, bool new_state) {
45 if (last_state == new_state) {
46 return;
47 }
48
49 Core::System& system{Core::System::GetInstance()};
50 Service::SM::ServiceManager& sm = system.ServiceManager();
51
52 // Message queue is shared between these services, we just need to signal an operation
53 // change to one and it will handle both automatically
54 auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
55 auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
56 bool has_signalled = false;
57
58 if (applet_oe != nullptr) {
59 applet_oe->GetMessageQueue()->OperationModeChanged();
60 has_signalled = true;
61 }
62
63 if (applet_ae != nullptr && !has_signalled) {
64 applet_ae->GetMessageQueue()->OperationModeChanged();
65 }
66}
67
41void ConfigureGeneral::applyConfiguration() { 68void ConfigureGeneral::applyConfiguration() {
42 UISettings::values.gamedir_deepscan = ui->toggle_deepscan->isChecked(); 69 UISettings::values.gamedir_deepscan = ui->toggle_deepscan->isChecked();
43 UISettings::values.confirm_before_closing = ui->toggle_check_exit->isChecked(); 70 UISettings::values.confirm_before_closing = ui->toggle_check_exit->isChecked();
@@ -45,6 +72,9 @@ void ConfigureGeneral::applyConfiguration() {
45 ui->theme_combobox->itemData(ui->theme_combobox->currentIndex()).toString(); 72 ui->theme_combobox->itemData(ui->theme_combobox->currentIndex()).toString();
46 73
47 Settings::values.use_cpu_jit = ui->use_cpu_jit->isChecked(); 74 Settings::values.use_cpu_jit = ui->use_cpu_jit->isChecked();
75 const bool pre_docked_mode = Settings::values.use_docked_mode;
48 Settings::values.use_docked_mode = ui->use_docked_mode->isChecked(); 76 Settings::values.use_docked_mode = ui->use_docked_mode->isChecked();
77 OnDockedModeChanged(pre_docked_mode, Settings::values.use_docked_mode);
78
49 Settings::values.enable_nfc = ui->enable_nfc->isChecked(); 79 Settings::values.enable_nfc = ui->enable_nfc->isChecked();
50} 80}
diff --git a/src/yuzu/configuration/configure_general.h b/src/yuzu/configuration/configure_general.h
index 4770034cc..2210d48da 100644
--- a/src/yuzu/configuration/configure_general.h
+++ b/src/yuzu/configuration/configure_general.h
@@ -25,6 +25,7 @@ public:
25 25
26private: 26private:
27 void setConfiguration(); 27 void setConfiguration();
28 void OnDockedModeChanged(bool last_state, bool new_state);
28 29
29 std::unique_ptr<Ui::ConfigureGeneral> ui; 30 std::unique_ptr<Ui::ConfigureGeneral> ui;
30}; 31};
diff --git a/src/yuzu/configuration/configure_input.cpp b/src/yuzu/configuration/configure_input.cpp
index 94789c064..42a7beac6 100644
--- a/src/yuzu/configuration/configure_input.cpp
+++ b/src/yuzu/configuration/configure_input.cpp
@@ -322,7 +322,7 @@ void ConfigureInput::setPollingResult(const Common::ParamPackage& params, bool a
322 } 322 }
323 323
324 updateButtonLabels(); 324 updateButtonLabels();
325 input_setter = boost::none; 325 input_setter = {};
326} 326}
327 327
328void ConfigureInput::keyPressEvent(QKeyEvent* event) { 328void ConfigureInput::keyPressEvent(QKeyEvent* event) {
diff --git a/src/yuzu/configuration/configure_input.h b/src/yuzu/configuration/configure_input.h
index d1198db81..32c7183f9 100644
--- a/src/yuzu/configuration/configure_input.h
+++ b/src/yuzu/configuration/configure_input.h
@@ -7,11 +7,13 @@
7#include <array> 7#include <array>
8#include <functional> 8#include <functional>
9#include <memory> 9#include <memory>
10#include <optional>
10#include <string> 11#include <string>
11#include <unordered_map> 12#include <unordered_map>
13
12#include <QKeyEvent> 14#include <QKeyEvent>
13#include <QWidget> 15#include <QWidget>
14#include <boost/optional.hpp> 16
15#include "common/param_package.h" 17#include "common/param_package.h"
16#include "core/settings.h" 18#include "core/settings.h"
17#include "input_common/main.h" 19#include "input_common/main.h"
@@ -41,7 +43,7 @@ private:
41 std::unique_ptr<QTimer> poll_timer; 43 std::unique_ptr<QTimer> poll_timer;
42 44
43 /// This will be the the setting function when an input is awaiting configuration. 45 /// This will be the the setting function when an input is awaiting configuration.
44 boost::optional<std::function<void(const Common::ParamPackage&)>> input_setter; 46 std::optional<std::function<void(const Common::ParamPackage&)>> input_setter;
45 47
46 std::array<Common::ParamPackage, Settings::NativeButton::NumButtons> buttons_param; 48 std::array<Common::ParamPackage, Settings::NativeButton::NumButtons> buttons_param;
47 std::array<Common::ParamPackage, Settings::NativeAnalog::NumAnalogs> analogs_param; 49 std::array<Common::ParamPackage, Settings::NativeAnalog::NumAnalogs> analogs_param;
diff --git a/src/yuzu/configuration/configure_system.cpp b/src/yuzu/configuration/configure_system.cpp
index 4b34c1e28..ab5d46492 100644
--- a/src/yuzu/configuration/configure_system.cpp
+++ b/src/yuzu/configuration/configure_system.cpp
@@ -6,20 +6,20 @@
6#include <QFileDialog> 6#include <QFileDialog>
7#include <QGraphicsItem> 7#include <QGraphicsItem>
8#include <QGraphicsScene> 8#include <QGraphicsScene>
9#include <QInputDialog> 9#include <QHeaderView>
10#include <QMessageBox> 10#include <QMessageBox>
11#include <QStandardItemModel> 11#include <QStandardItemModel>
12#include <QTreeView> 12#include <QTreeView>
13#include <QVBoxLayout> 13#include <QVBoxLayout>
14#include "common/common_paths.h" 14#include "common/assert.h"
15#include "common/logging/backend.h" 15#include "common/file_util.h"
16#include "common/string_util.h" 16#include "common/string_util.h"
17#include "core/core.h" 17#include "core/core.h"
18#include "core/hle/service/acc/profile_manager.h" 18#include "core/hle/service/acc/profile_manager.h"
19#include "core/settings.h" 19#include "core/settings.h"
20#include "ui_configure_system.h" 20#include "ui_configure_system.h"
21#include "yuzu/configuration/configure_system.h" 21#include "yuzu/configuration/configure_system.h"
22#include "yuzu/main.h" 22#include "yuzu/util/limitable_input_dialog.h"
23 23
24namespace { 24namespace {
25constexpr std::array<int, 12> days_in_month = {{ 25constexpr std::array<int, 12> days_in_month = {{
@@ -78,11 +78,17 @@ QPixmap GetIcon(Service::Account::UUID uuid) {
78 78
79 if (!icon) { 79 if (!icon) {
80 icon.fill(Qt::black); 80 icon.fill(Qt::black);
81 icon.loadFromData(backup_jpeg.data(), backup_jpeg.size()); 81 icon.loadFromData(backup_jpeg.data(), static_cast<u32>(backup_jpeg.size()));
82 } 82 }
83 83
84 return icon.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); 84 return icon.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
85} 85}
86
87QString GetProfileUsernameFromUser(QWidget* parent, const QString& description_text) {
88 return LimitableInputDialog::GetText(parent, ConfigureSystem::tr("Enter Username"),
89 description_text, 1,
90 static_cast<int>(Service::Account::profile_username_size));
91}
86} // Anonymous namespace 92} // Anonymous namespace
87 93
88ConfigureSystem::ConfigureSystem(QWidget* parent) 94ConfigureSystem::ConfigureSystem(QWidget* parent)
@@ -131,6 +137,12 @@ ConfigureSystem::ConfigureSystem(QWidget* parent)
131 connect(ui->pm_remove, &QPushButton::pressed, this, &ConfigureSystem::DeleteUser); 137 connect(ui->pm_remove, &QPushButton::pressed, this, &ConfigureSystem::DeleteUser);
132 connect(ui->pm_set_image, &QPushButton::pressed, this, &ConfigureSystem::SetUserImage); 138 connect(ui->pm_set_image, &QPushButton::pressed, this, &ConfigureSystem::SetUserImage);
133 139
140 connect(ui->rng_seed_checkbox, &QCheckBox::stateChanged, this, [this](bool checked) {
141 ui->rng_seed_edit->setEnabled(checked);
142 if (!checked)
143 ui->rng_seed_edit->setText(QStringLiteral("00000000"));
144 });
145
134 scene = new QGraphicsScene; 146 scene = new QGraphicsScene;
135 ui->current_user_icon->setScene(scene); 147 ui->current_user_icon->setScene(scene);
136 148
@@ -149,6 +161,13 @@ void ConfigureSystem::setConfiguration() {
149 161
150 PopulateUserList(); 162 PopulateUserList();
151 UpdateCurrentUser(); 163 UpdateCurrentUser();
164
165 ui->rng_seed_checkbox->setChecked(Settings::values.rng_seed.has_value());
166 ui->rng_seed_edit->setEnabled(Settings::values.rng_seed.has_value());
167
168 const auto rng_seed =
169 QString("%1").arg(Settings::values.rng_seed.value_or(0), 8, 16, QLatin1Char{'0'}).toUpper();
170 ui->rng_seed_edit->setText(rng_seed);
152} 171}
153 172
154void ConfigureSystem::PopulateUserList() { 173void ConfigureSystem::PopulateUserList() {
@@ -173,7 +192,7 @@ void ConfigureSystem::UpdateCurrentUser() {
173 ui->pm_add->setEnabled(profile_manager->GetUserCount() < Service::Account::MAX_USERS); 192 ui->pm_add->setEnabled(profile_manager->GetUserCount() < Service::Account::MAX_USERS);
174 193
175 const auto& current_user = profile_manager->GetUser(Settings::values.current_user); 194 const auto& current_user = profile_manager->GetUser(Settings::values.current_user);
176 ASSERT(current_user != std::nullopt); 195 ASSERT(current_user);
177 const auto username = GetAccountUsername(*profile_manager, *current_user); 196 const auto username = GetAccountUsername(*profile_manager, *current_user);
178 197
179 scene->clear(); 198 scene->clear();
@@ -189,6 +208,12 @@ void ConfigureSystem::applyConfiguration() {
189 return; 208 return;
190 209
191 Settings::values.language_index = ui->combo_language->currentIndex(); 210 Settings::values.language_index = ui->combo_language->currentIndex();
211
212 if (ui->rng_seed_checkbox->isChecked())
213 Settings::values.rng_seed = ui->rng_seed_edit->text().toULongLong(nullptr, 16);
214 else
215 Settings::values.rng_seed = std::nullopt;
216
192 Settings::Apply(); 217 Settings::Apply();
193} 218}
194 219
@@ -234,7 +259,7 @@ void ConfigureSystem::RefreshConsoleID() {
234 259
235void ConfigureSystem::SelectUser(const QModelIndex& index) { 260void ConfigureSystem::SelectUser(const QModelIndex& index) {
236 Settings::values.current_user = 261 Settings::values.current_user =
237 std::clamp<std::size_t>(index.row(), 0, profile_manager->GetUserCount() - 1); 262 std::clamp<s32>(index.row(), 0, static_cast<s32>(profile_manager->GetUserCount() - 1));
238 263
239 UpdateCurrentUser(); 264 UpdateCurrentUser();
240 265
@@ -244,15 +269,13 @@ void ConfigureSystem::SelectUser(const QModelIndex& index) {
244} 269}
245 270
246void ConfigureSystem::AddUser() { 271void ConfigureSystem::AddUser() {
247 const auto uuid = Service::Account::UUID::Generate();
248
249 bool ok = false;
250 const auto username = 272 const auto username =
251 QInputDialog::getText(this, tr("Enter Username"), tr("Enter a username for the new user:"), 273 GetProfileUsernameFromUser(this, tr("Enter a username for the new user:"));
252 QLineEdit::Normal, QString(), &ok); 274 if (username.isEmpty()) {
253 if (!ok)
254 return; 275 return;
276 }
255 277
278 const auto uuid = Service::Account::UUID::Generate();
256 profile_manager->CreateNewUser(uuid, username.toStdString()); 279 profile_manager->CreateNewUser(uuid, username.toStdString());
257 280
258 item_model->appendRow(new QStandardItem{GetIcon(uuid), FormatUserEntryText(username, uuid)}); 281 item_model->appendRow(new QStandardItem{GetIcon(uuid), FormatUserEntryText(username, uuid)});
@@ -261,29 +284,20 @@ void ConfigureSystem::AddUser() {
261void ConfigureSystem::RenameUser() { 284void ConfigureSystem::RenameUser() {
262 const auto user = tree_view->currentIndex().row(); 285 const auto user = tree_view->currentIndex().row();
263 const auto uuid = profile_manager->GetUser(user); 286 const auto uuid = profile_manager->GetUser(user);
264 ASSERT(uuid != std::nullopt); 287 ASSERT(uuid);
265 288
266 Service::Account::ProfileBase profile; 289 Service::Account::ProfileBase profile;
267 if (!profile_manager->GetProfileBase(*uuid, profile)) 290 if (!profile_manager->GetProfileBase(*uuid, profile))
268 return; 291 return;
269 292
270 bool ok = false; 293 const auto new_username = GetProfileUsernameFromUser(this, tr("Enter a new username:"));
271 const auto old_username = GetAccountUsername(*profile_manager, *uuid); 294 if (new_username.isEmpty()) {
272 const auto new_username =
273 QInputDialog::getText(this, tr("Enter Username"), tr("Enter a new username:"),
274 QLineEdit::Normal, old_username, &ok);
275
276 if (!ok)
277 return; 295 return;
296 }
278 297
279 std::fill(profile.username.begin(), profile.username.end(), '\0');
280 const auto username_std = new_username.toStdString(); 298 const auto username_std = new_username.toStdString();
281 if (username_std.size() > profile.username.size()) { 299 std::fill(profile.username.begin(), profile.username.end(), '\0');
282 std::copy_n(username_std.begin(), std::min(profile.username.size(), username_std.size()), 300 std::copy(username_std.begin(), username_std.end(), profile.username.begin());
283 profile.username.begin());
284 } else {
285 std::copy(username_std.begin(), username_std.end(), profile.username.begin());
286 }
287 301
288 profile_manager->SetProfileBase(*uuid, profile); 302 profile_manager->SetProfileBase(*uuid, profile);
289 303
@@ -297,7 +311,7 @@ void ConfigureSystem::RenameUser() {
297void ConfigureSystem::DeleteUser() { 311void ConfigureSystem::DeleteUser() {
298 const auto index = tree_view->currentIndex().row(); 312 const auto index = tree_view->currentIndex().row();
299 const auto uuid = profile_manager->GetUser(index); 313 const auto uuid = profile_manager->GetUser(index);
300 ASSERT(uuid != std::nullopt); 314 ASSERT(uuid);
301 const auto username = GetAccountUsername(*profile_manager, *uuid); 315 const auto username = GetAccountUsername(*profile_manager, *uuid);
302 316
303 const auto confirm = QMessageBox::question( 317 const auto confirm = QMessageBox::question(
@@ -324,7 +338,7 @@ void ConfigureSystem::DeleteUser() {
324void ConfigureSystem::SetUserImage() { 338void ConfigureSystem::SetUserImage() {
325 const auto index = tree_view->currentIndex().row(); 339 const auto index = tree_view->currentIndex().row();
326 const auto uuid = profile_manager->GetUser(index); 340 const auto uuid = profile_manager->GetUser(index);
327 ASSERT(uuid != std::nullopt); 341 ASSERT(uuid);
328 342
329 const auto file = QFileDialog::getOpenFileName(this, tr("Select User Image"), QString(), 343 const auto file = QFileDialog::getOpenFileName(this, tr("Select User Image"), QString(),
330 tr("JPEG Images (*.jpg *.jpeg)")); 344 tr("JPEG Images (*.jpg *.jpeg)"));
diff --git a/src/yuzu/configuration/configure_system.ui b/src/yuzu/configuration/configure_system.ui
index 020b32a37..a91580893 100644
--- a/src/yuzu/configuration/configure_system.ui
+++ b/src/yuzu/configuration/configure_system.ui
@@ -6,7 +6,7 @@
6 <rect> 6 <rect>
7 <x>0</x> 7 <x>0</x>
8 <y>0</y> 8 <y>0</y>
9 <width>360</width> 9 <width>366</width>
10 <height>483</height> 10 <height>483</height>
11 </rect> 11 </rect>
12 </property> 12 </property>
@@ -22,98 +22,6 @@
22 <string>System Settings</string> 22 <string>System Settings</string>
23 </property> 23 </property>
24 <layout class="QGridLayout" name="gridLayout"> 24 <layout class="QGridLayout" name="gridLayout">
25 <item row="1" column="0">
26 <widget class="QLabel" name="label_language">
27 <property name="text">
28 <string>Language</string>
29 </property>
30 </widget>
31 </item>
32 <item row="0" column="0">
33 <widget class="QLabel" name="label_birthday">
34 <property name="text">
35 <string>Birthday</string>
36 </property>
37 </widget>
38 </item>
39 <item row="3" column="0">
40 <widget class="QLabel" name="label_console_id">
41 <property name="text">
42 <string>Console ID:</string>
43 </property>
44 </widget>
45 </item>
46 <item row="0" column="1">
47 <layout class="QHBoxLayout" name="horizontalLayout_birthday2">
48 <item>
49 <widget class="QComboBox" name="combo_birthmonth">
50 <item>
51 <property name="text">
52 <string>January</string>
53 </property>
54 </item>
55 <item>
56 <property name="text">
57 <string>February</string>
58 </property>
59 </item>
60 <item>
61 <property name="text">
62 <string>March</string>
63 </property>
64 </item>
65 <item>
66 <property name="text">
67 <string>April</string>
68 </property>
69 </item>
70 <item>
71 <property name="text">
72 <string>May</string>
73 </property>
74 </item>
75 <item>
76 <property name="text">
77 <string>June</string>
78 </property>
79 </item>
80 <item>
81 <property name="text">
82 <string>July</string>
83 </property>
84 </item>
85 <item>
86 <property name="text">
87 <string>August</string>
88 </property>
89 </item>
90 <item>
91 <property name="text">
92 <string>September</string>
93 </property>
94 </item>
95 <item>
96 <property name="text">
97 <string>October</string>
98 </property>
99 </item>
100 <item>
101 <property name="text">
102 <string>November</string>
103 </property>
104 </item>
105 <item>
106 <property name="text">
107 <string>December</string>
108 </property>
109 </item>
110 </widget>
111 </item>
112 <item>
113 <widget class="QComboBox" name="combo_birthday"/>
114 </item>
115 </layout>
116 </item>
117 <item row="1" column="1"> 25 <item row="1" column="1">
118 <widget class="QComboBox" name="combo_language"> 26 <widget class="QComboBox" name="combo_language">
119 <property name="toolTip"> 27 <property name="toolTip">
@@ -206,6 +114,13 @@
206 </item> 114 </item>
207 </widget> 115 </widget>
208 </item> 116 </item>
117 <item row="3" column="0">
118 <widget class="QLabel" name="label_console_id">
119 <property name="text">
120 <string>Console ID:</string>
121 </property>
122 </widget>
123 </item>
209 <item row="2" column="0"> 124 <item row="2" column="0">
210 <widget class="QLabel" name="label_sound"> 125 <widget class="QLabel" name="label_sound">
211 <property name="text"> 126 <property name="text">
@@ -213,6 +128,100 @@
213 </property> 128 </property>
214 </widget> 129 </widget>
215 </item> 130 </item>
131 <item row="0" column="0">
132 <widget class="QLabel" name="label_birthday">
133 <property name="text">
134 <string>Birthday</string>
135 </property>
136 </widget>
137 </item>
138 <item row="0" column="1">
139 <layout class="QHBoxLayout" name="horizontalLayout_birthday2">
140 <item>
141 <widget class="QComboBox" name="combo_birthmonth">
142 <item>
143 <property name="text">
144 <string>January</string>
145 </property>
146 </item>
147 <item>
148 <property name="text">
149 <string>February</string>
150 </property>
151 </item>
152 <item>
153 <property name="text">
154 <string>March</string>
155 </property>
156 </item>
157 <item>
158 <property name="text">
159 <string>April</string>
160 </property>
161 </item>
162 <item>
163 <property name="text">
164 <string>May</string>
165 </property>
166 </item>
167 <item>
168 <property name="text">
169 <string>June</string>
170 </property>
171 </item>
172 <item>
173 <property name="text">
174 <string>July</string>
175 </property>
176 </item>
177 <item>
178 <property name="text">
179 <string>August</string>
180 </property>
181 </item>
182 <item>
183 <property name="text">
184 <string>September</string>
185 </property>
186 </item>
187 <item>
188 <property name="text">
189 <string>October</string>
190 </property>
191 </item>
192 <item>
193 <property name="text">
194 <string>November</string>
195 </property>
196 </item>
197 <item>
198 <property name="text">
199 <string>December</string>
200 </property>
201 </item>
202 </widget>
203 </item>
204 <item>
205 <widget class="QComboBox" name="combo_birthday"/>
206 </item>
207 </layout>
208 </item>
209 <item row="3" column="1">
210 <widget class="QPushButton" name="button_regenerate_console_id">
211 <property name="sizePolicy">
212 <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
213 <horstretch>0</horstretch>
214 <verstretch>0</verstretch>
215 </sizepolicy>
216 </property>
217 <property name="layoutDirection">
218 <enum>Qt::RightToLeft</enum>
219 </property>
220 <property name="text">
221 <string>Regenerate</string>
222 </property>
223 </widget>
224 </item>
216 <item row="2" column="1"> 225 <item row="2" column="1">
217 <widget class="QComboBox" name="combo_sound"> 226 <widget class="QComboBox" name="combo_sound">
218 <item> 227 <item>
@@ -232,19 +241,38 @@
232 </item> 241 </item>
233 </widget> 242 </widget>
234 </item> 243 </item>
235 <item row="3" column="1"> 244 <item row="1" column="0">
236 <widget class="QPushButton" name="button_regenerate_console_id"> 245 <widget class="QLabel" name="label_language">
246 <property name="text">
247 <string>Language</string>
248 </property>
249 </widget>
250 </item>
251 <item row="4" column="0">
252 <widget class="QCheckBox" name="rng_seed_checkbox">
253 <property name="text">
254 <string>RNG Seed</string>
255 </property>
256 </widget>
257 </item>
258 <item row="4" column="1">
259 <widget class="QLineEdit" name="rng_seed_edit">
237 <property name="sizePolicy"> 260 <property name="sizePolicy">
238 <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> 261 <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
239 <horstretch>0</horstretch> 262 <horstretch>0</horstretch>
240 <verstretch>0</verstretch> 263 <verstretch>0</verstretch>
241 </sizepolicy> 264 </sizepolicy>
242 </property> 265 </property>
243 <property name="layoutDirection"> 266 <property name="font">
244 <enum>Qt::RightToLeft</enum> 267 <font>
268 <family>Lucida Console</family>
269 </font>
245 </property> 270 </property>
246 <property name="text"> 271 <property name="inputMask">
247 <string>Regenerate</string> 272 <string notr="true">HHHHHHHH</string>
273 </property>
274 <property name="maxLength">
275 <number>8</number>
248 </property> 276 </property>
249 </widget> 277 </widget>
250 </item> 278 </item>
diff --git a/src/yuzu/debugger/graphics/graphics_surface.cpp b/src/yuzu/debugger/graphics/graphics_surface.cpp
index 44d423da2..707747422 100644
--- a/src/yuzu/debugger/graphics/graphics_surface.cpp
+++ b/src/yuzu/debugger/graphics/graphics_surface.cpp
@@ -382,13 +382,13 @@ void GraphicsSurfaceWidget::OnUpdate() {
382 // TODO: Implement a good way to visualize alpha components! 382 // TODO: Implement a good way to visualize alpha components!
383 383
384 QImage decoded_image(surface_width, surface_height, QImage::Format_ARGB32); 384 QImage decoded_image(surface_width, surface_height, QImage::Format_ARGB32);
385 boost::optional<VAddr> address = gpu.MemoryManager().GpuToCpuAddress(surface_address); 385 std::optional<VAddr> address = gpu.MemoryManager().GpuToCpuAddress(surface_address);
386 386
387 // TODO(bunnei): Will not work with BCn formats that swizzle 4x4 tiles. 387 // TODO(bunnei): Will not work with BCn formats that swizzle 4x4 tiles.
388 // Needs to be fixed if we plan to use this feature more, otherwise we may remove it. 388 // Needs to be fixed if we plan to use this feature more, otherwise we may remove it.
389 auto unswizzled_data = 389 auto unswizzled_data = Tegra::Texture::UnswizzleTexture(
390 Tegra::Texture::UnswizzleTexture(*address, 1, Tegra::Texture::BytesPerPixel(surface_format), 390 *address, 1, 1, Tegra::Texture::BytesPerPixel(surface_format), surface_width,
391 surface_width, surface_height, 1U); 391 surface_height, 1U);
392 392
393 auto texture_data = Tegra::Texture::DecodeTexture(unswizzled_data, surface_format, 393 auto texture_data = Tegra::Texture::DecodeTexture(unswizzled_data, surface_format,
394 surface_width, surface_height); 394 surface_width, surface_height);
@@ -444,7 +444,7 @@ void GraphicsSurfaceWidget::SaveSurface() {
444 pixmap->save(&file, "PNG"); 444 pixmap->save(&file, "PNG");
445 } else if (selectedFilter == bin_filter) { 445 } else if (selectedFilter == bin_filter) {
446 auto& gpu = Core::System::GetInstance().GPU(); 446 auto& gpu = Core::System::GetInstance().GPU();
447 boost::optional<VAddr> address = gpu.MemoryManager().GpuToCpuAddress(surface_address); 447 std::optional<VAddr> address = gpu.MemoryManager().GpuToCpuAddress(surface_address);
448 448
449 const u8* buffer = Memory::GetPointer(*address); 449 const u8* buffer = Memory::GetPointer(*address);
450 ASSERT_MSG(buffer != nullptr, "Memory not accessible"); 450 ASSERT_MSG(buffer != nullptr, "Memory not accessible");
diff --git a/src/yuzu/debugger/wait_tree.h b/src/yuzu/debugger/wait_tree.h
index defbf734f..331f89885 100644
--- a/src/yuzu/debugger/wait_tree.h
+++ b/src/yuzu/debugger/wait_tree.h
@@ -11,7 +11,6 @@
11#include <QAbstractItemModel> 11#include <QAbstractItemModel>
12#include <QDockWidget> 12#include <QDockWidget>
13#include <QTreeView> 13#include <QTreeView>
14#include <boost/container/flat_set.hpp>
15#include "common/common_types.h" 14#include "common/common_types.h"
16#include "core/hle/kernel/object.h" 15#include "core/hle/kernel/object.h"
17 16
diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp
index b5bfa6741..131ad19de 100644
--- a/src/yuzu/main.cpp
+++ b/src/yuzu/main.cpp
@@ -142,6 +142,9 @@ static void InitializeLogging() {
142 const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir); 142 const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
143 FileUtil::CreateFullPath(log_dir); 143 FileUtil::CreateFullPath(log_dir);
144 Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE)); 144 Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
145#ifdef _WIN32
146 Log::AddBackend(std::make_unique<Log::DebuggerBackend>());
147#endif
145} 148}
146 149
147GMainWindow::GMainWindow() 150GMainWindow::GMainWindow()
@@ -454,6 +457,7 @@ void GMainWindow::ConnectMenuEvents() {
454 connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen); 457 connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
455 458
456 // Help 459 // Help
460 connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
457 connect(ui.action_Rederive, &QAction::triggered, this, 461 connect(ui.action_Rederive, &QAction::triggered, this,
458 std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning)); 462 std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
459 connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout); 463 connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
@@ -786,7 +790,7 @@ void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target
786 ASSERT(index != -1 && index < 8); 790 ASSERT(index != -1 && index < 8);
787 791
788 const auto user_id = manager.GetUser(index); 792 const auto user_id = manager.GetUser(index);
789 ASSERT(user_id != std::nullopt); 793 ASSERT(user_id);
790 path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser, 794 path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
791 FileSys::SaveDataType::SaveData, 795 FileSys::SaveDataType::SaveData,
792 program_id, user_id->uuid, 0); 796 program_id, user_id->uuid, 0);
@@ -929,7 +933,8 @@ void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_pa
929 const auto full = res == "Full"; 933 const auto full = res == "Full";
930 const auto entry_size = CalculateRomFSEntrySize(extracted, full); 934 const auto entry_size = CalculateRomFSEntrySize(extracted, full);
931 935
932 QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0, entry_size, this); 936 QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
937 static_cast<s32>(entry_size), this);
933 progress.setWindowModality(Qt::WindowModal); 938 progress.setWindowModality(Qt::WindowModal);
934 progress.setMinimumDuration(100); 939 progress.setMinimumDuration(100);
935 940
@@ -1374,6 +1379,11 @@ void GMainWindow::OnLoadAmiibo() {
1374 } 1379 }
1375} 1380}
1376 1381
1382void GMainWindow::OnOpenYuzuFolder() {
1383 QDesktopServices::openUrl(QUrl::fromLocalFile(
1384 QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
1385}
1386
1377void GMainWindow::OnAbout() { 1387void GMainWindow::OnAbout() {
1378 AboutDialog aboutDialog(this); 1388 AboutDialog aboutDialog(this);
1379 aboutDialog.exec(); 1389 aboutDialog.exec();
@@ -1532,7 +1542,7 @@ void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
1532 "derivation. It will be attempted but may not complete.<br><br>") + 1542 "derivation. It will be attempted but may not complete.<br><br>") +
1533 errors + 1543 errors +
1534 tr("<br><br>You can get all of these and dump all of your games easily by " 1544 tr("<br><br>You can get all of these and dump all of your games easily by "
1535 "following <a href='https://yuzu-emu.org/help/quickstart/quickstart/'>the " 1545 "following <a href='https://yuzu-emu.org/help/quickstart/'>the "
1536 "quickstart guide</a>. Alternatively, you can use another method of dumping " 1546 "quickstart guide</a>. Alternatively, you can use another method of dumping "
1537 "to obtain all of your keys.")); 1547 "to obtain all of your keys."));
1538 } 1548 }
@@ -1560,7 +1570,7 @@ void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
1560 } 1570 }
1561} 1571}
1562 1572
1563boost::optional<u64> GMainWindow::SelectRomFSDumpTarget( 1573std::optional<u64> GMainWindow::SelectRomFSDumpTarget(
1564 const FileSys::RegisteredCacheUnion& installed, u64 program_id) { 1574 const FileSys::RegisteredCacheUnion& installed, u64 program_id) {
1565 const auto dlc_entries = 1575 const auto dlc_entries =
1566 installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data); 1576 installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
@@ -1587,7 +1597,7 @@ boost::optional<u64> GMainWindow::SelectRomFSDumpTarget(
1587 this, tr("Select RomFS Dump Target"), 1597 this, tr("Select RomFS Dump Target"),
1588 tr("Please select which RomFS you would like to dump."), list, 0, false, &ok); 1598 tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
1589 if (!ok) { 1599 if (!ok) {
1590 return boost::none; 1600 return {};
1591 } 1601 }
1592 1602
1593 return romfs_tids[list.indexOf(res)]; 1603 return romfs_tids[list.indexOf(res)];
@@ -1612,7 +1622,7 @@ void GMainWindow::closeEvent(QCloseEvent* event) {
1612 return; 1622 return;
1613 } 1623 }
1614 1624
1615 if (ui.action_Fullscreen->isChecked()) { 1625 if (!ui.action_Fullscreen->isChecked()) {
1616 UISettings::values.geometry = saveGeometry(); 1626 UISettings::values.geometry = saveGeometry();
1617 UISettings::values.renderwindow_geometry = render_window->saveGeometry(); 1627 UISettings::values.renderwindow_geometry = render_window->saveGeometry();
1618 } 1628 }
diff --git a/src/yuzu/main.h b/src/yuzu/main.h
index 7c7c223e1..929250e8c 100644
--- a/src/yuzu/main.h
+++ b/src/yuzu/main.h
@@ -5,12 +5,12 @@
5#pragma once 5#pragma once
6 6
7#include <memory> 7#include <memory>
8#include <optional>
8#include <unordered_map> 9#include <unordered_map>
9 10
10#include <QMainWindow> 11#include <QMainWindow>
11#include <QTimer> 12#include <QTimer>
12 13
13#include <boost/optional.hpp>
14#include "common/common_types.h" 14#include "common/common_types.h"
15#include "core/core.h" 15#include "core/core.h"
16#include "ui_main.h" 16#include "ui_main.h"
@@ -167,6 +167,7 @@ private slots:
167 void OnMenuRecentFile(); 167 void OnMenuRecentFile();
168 void OnConfigure(); 168 void OnConfigure();
169 void OnLoadAmiibo(); 169 void OnLoadAmiibo();
170 void OnOpenYuzuFolder();
170 void OnAbout(); 171 void OnAbout();
171 void OnToggleFilterBar(); 172 void OnToggleFilterBar();
172 void OnDisplayTitleBars(bool); 173 void OnDisplayTitleBars(bool);
@@ -178,8 +179,7 @@ private slots:
178 void OnReinitializeKeys(ReinitializeKeyBehavior behavior); 179 void OnReinitializeKeys(ReinitializeKeyBehavior behavior);
179 180
180private: 181private:
181 boost::optional<u64> SelectRomFSDumpTarget(const FileSys::RegisteredCacheUnion&, 182 std::optional<u64> SelectRomFSDumpTarget(const FileSys::RegisteredCacheUnion&, u64 program_id);
182 u64 program_id);
183 void UpdateStatusBar(); 183 void UpdateStatusBar();
184 184
185 Ui::MainWindow ui; 185 Ui::MainWindow ui;
diff --git a/src/yuzu/main.ui b/src/yuzu/main.ui
index 48d099591..75e96387f 100644
--- a/src/yuzu/main.ui
+++ b/src/yuzu/main.ui
@@ -70,6 +70,8 @@
70 <addaction name="separator"/> 70 <addaction name="separator"/>
71 <addaction name="action_Load_Amiibo"/> 71 <addaction name="action_Load_Amiibo"/>
72 <addaction name="separator"/> 72 <addaction name="separator"/>
73 <addaction name="action_Open_yuzu_Folder"/>
74 <addaction name="separator"/>
73 <addaction name="action_Exit"/> 75 <addaction name="action_Exit"/>
74 </widget> 76 </widget>
75 <widget class="QMenu" name="menu_Emulation"> 77 <widget class="QMenu" name="menu_Emulation">
@@ -277,6 +279,11 @@
277 <bool>false</bool> 279 <bool>false</bool>
278 </property> 280 </property>
279 </action> 281 </action>
282 <action name="action_Open_yuzu_Folder">
283 <property name="text">
284 <string>Open yuzu Folder</string>
285 </property>
286 </action>
280 </widget> 287 </widget>
281 <resources/> 288 <resources/>
282 <connections/> 289 <connections/>
diff --git a/src/yuzu/util/limitable_input_dialog.cpp b/src/yuzu/util/limitable_input_dialog.cpp
new file mode 100644
index 000000000..edd78e579
--- /dev/null
+++ b/src/yuzu/util/limitable_input_dialog.cpp
@@ -0,0 +1,59 @@
1// Copyright 2018 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <QDialogButtonBox>
6#include <QLabel>
7#include <QLineEdit>
8#include <QPushButton>
9#include <QVBoxLayout>
10#include "yuzu/util/limitable_input_dialog.h"
11
12LimitableInputDialog::LimitableInputDialog(QWidget* parent) : QDialog{parent} {
13 CreateUI();
14 ConnectEvents();
15}
16
17LimitableInputDialog::~LimitableInputDialog() = default;
18
19void LimitableInputDialog::CreateUI() {
20 setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
21
22 text_label = new QLabel(this);
23 text_entry = new QLineEdit(this);
24 buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
25
26 auto* const layout = new QVBoxLayout;
27 layout->addWidget(text_label);
28 layout->addWidget(text_entry);
29 layout->addWidget(buttons);
30
31 setLayout(layout);
32}
33
34void LimitableInputDialog::ConnectEvents() {
35 connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept);
36 connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
37}
38
39QString LimitableInputDialog::GetText(QWidget* parent, const QString& title, const QString& text,
40 int min_character_limit, int max_character_limit) {
41 Q_ASSERT(min_character_limit <= max_character_limit);
42
43 LimitableInputDialog dialog{parent};
44 dialog.setWindowTitle(title);
45 dialog.text_label->setText(text);
46 dialog.text_entry->setMaxLength(max_character_limit);
47
48 auto* const ok_button = dialog.buttons->button(QDialogButtonBox::Ok);
49 ok_button->setEnabled(false);
50 connect(dialog.text_entry, &QLineEdit::textEdited, [&](const QString& new_text) {
51 ok_button->setEnabled(new_text.length() >= min_character_limit);
52 });
53
54 if (dialog.exec() != QDialog::Accepted) {
55 return {};
56 }
57
58 return dialog.text_entry->text();
59}
diff --git a/src/yuzu/util/limitable_input_dialog.h b/src/yuzu/util/limitable_input_dialog.h
new file mode 100644
index 000000000..164ad7301
--- /dev/null
+++ b/src/yuzu/util/limitable_input_dialog.h
@@ -0,0 +1,31 @@
1// Copyright 2018 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <QDialog>
8
9class QDialogButtonBox;
10class QLabel;
11class QLineEdit;
12
13/// A QDialog that functions similarly to QInputDialog, however, it allows
14/// restricting the minimum and total number of characters that can be entered.
15class LimitableInputDialog final : public QDialog {
16 Q_OBJECT
17public:
18 explicit LimitableInputDialog(QWidget* parent = nullptr);
19 ~LimitableInputDialog() override;
20
21 static QString GetText(QWidget* parent, const QString& title, const QString& text,
22 int min_character_limit, int max_character_limit);
23
24private:
25 void CreateUI();
26 void ConnectEvents();
27
28 QLabel* text_label;
29 QLineEdit* text_entry;
30 QDialogButtonBox* buttons;
31};
diff --git a/src/yuzu_cmd/config.cpp b/src/yuzu_cmd/config.cpp
index f20b3a1b3..9cc409fd5 100644
--- a/src/yuzu_cmd/config.cpp
+++ b/src/yuzu_cmd/config.cpp
@@ -132,6 +132,13 @@ void Config::ReadValues() {
132 Settings::values.current_user = std::clamp<int>( 132 Settings::values.current_user = std::clamp<int>(
133 sdl2_config->GetInteger("System", "current_user", 0), 0, Service::Account::MAX_USERS - 1); 133 sdl2_config->GetInteger("System", "current_user", 0), 0, Service::Account::MAX_USERS - 1);
134 134
135 const auto enabled = sdl2_config->GetBoolean("System", "rng_seed_enabled", false);
136 if (enabled) {
137 Settings::values.rng_seed = sdl2_config->GetInteger("System", "rng_seed", 0);
138 } else {
139 Settings::values.rng_seed = std::nullopt;
140 }
141
135 // Miscellaneous 142 // Miscellaneous
136 Settings::values.log_filter = sdl2_config->Get("Miscellaneous", "log_filter", "*:Trace"); 143 Settings::values.log_filter = sdl2_config->Get("Miscellaneous", "log_filter", "*:Trace");
137 Settings::values.use_dev_keys = sdl2_config->GetBoolean("Miscellaneous", "use_dev_keys", false); 144 Settings::values.use_dev_keys = sdl2_config->GetBoolean("Miscellaneous", "use_dev_keys", false);
diff --git a/src/yuzu_cmd/default_ini.h b/src/yuzu_cmd/default_ini.h
index d83498358..ecf625e7b 100644
--- a/src/yuzu_cmd/default_ini.h
+++ b/src/yuzu_cmd/default_ini.h
@@ -178,6 +178,11 @@ use_docked_mode =
178# 1 (default): Yes, 0 : No 178# 1 (default): Yes, 0 : No
179enable_nfc = 179enable_nfc =
180 180
181# Sets the seed for the RNG generator built into the switch
182# rng_seed will be ignored and randomly generated if rng_seed_enabled is false
183rng_seed_enabled =
184rng_seed =
185
181# Sets the account username, max length is 32 characters 186# Sets the account username, max length is 32 characters
182# yuzu (default) 187# yuzu (default)
183username = yuzu 188username = yuzu
diff --git a/src/yuzu_cmd/yuzu.cpp b/src/yuzu_cmd/yuzu.cpp
index c8b93b85b..806127b12 100644
--- a/src/yuzu_cmd/yuzu.cpp
+++ b/src/yuzu_cmd/yuzu.cpp
@@ -76,6 +76,9 @@ static void InitializeLogging() {
76 const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir); 76 const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
77 FileUtil::CreateFullPath(log_dir); 77 FileUtil::CreateFullPath(log_dir);
78 Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE)); 78 Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
79#ifdef _WIN32
80 Log::AddBackend(std::make_unique<Log::DebuggerBackend>());
81#endif
79} 82}
80 83
81/// Application entry point 84/// Application entry point