summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/audio_core/audio_renderer.cpp89
-rw-r--r--src/audio_core/audio_renderer.h49
-rw-r--r--src/core/arm/dynarmic/arm_dynarmic.cpp2
-rw-r--r--src/core/core.cpp7
-rw-r--r--src/core/core.h10
-rw-r--r--src/core/file_sys/ips_layer.cpp75
-rw-r--r--src/core/file_sys/ips_layer.h11
-rw-r--r--src/core/file_sys/patch_manager.cpp15
-rw-r--r--src/core/file_sys/patch_manager.h5
-rw-r--r--src/core/hle/kernel/kernel.cpp12
-rw-r--r--src/core/hle/kernel/kernel.h10
-rw-r--r--src/core/hle/kernel/scheduler.cpp8
-rw-r--r--src/core/hle/kernel/svc.cpp37
-rw-r--r--src/core/hle/kernel/thread.cpp8
-rw-r--r--src/core/hle/kernel/thread.h8
-rw-r--r--src/core/loader/nsp.cpp2
-rw-r--r--src/core/loader/nsp.h2
-rw-r--r--src/core/loader/xci.cpp2
-rw-r--r--src/core/loader/xci.h2
-rw-r--r--src/core/telemetry_session.cpp12
-rw-r--r--src/core/telemetry_session.h4
-rw-r--r--src/tests/core/arm/arm_test_common.cpp3
-rw-r--r--src/video_core/engines/shader_bytecode.h112
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp40
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h6
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.cpp34
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.h46
-rw-r--r--src/video_core/renderer_opengl/gl_shader_decompiler.cpp306
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.cpp84
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.h6
-rw-r--r--src/video_core/renderer_opengl/gl_shader_manager.cpp8
-rw-r--r--src/video_core/renderer_opengl/gl_shader_manager.h7
-rw-r--r--src/video_core/utils.h24
-rw-r--r--src/yuzu/bootmanager.cpp71
-rw-r--r--src/yuzu/bootmanager.h10
-rw-r--r--src/yuzu/game_list_worker.cpp11
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2.cpp48
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2.h12
38 files changed, 951 insertions, 247 deletions
diff --git a/src/audio_core/audio_renderer.cpp b/src/audio_core/audio_renderer.cpp
index 6f0ff953a..23e5d3f10 100644
--- a/src/audio_core/audio_renderer.cpp
+++ b/src/audio_core/audio_renderer.cpp
@@ -30,7 +30,7 @@ public:
30 return info; 30 return info;
31 } 31 }
32 32
33 VoiceInfo& Info() { 33 VoiceInfo& GetInfo() {
34 return info; 34 return info;
35 } 35 }
36 36
@@ -51,9 +51,30 @@ private:
51 VoiceInfo info{}; 51 VoiceInfo info{};
52}; 52};
53 53
54class AudioRenderer::EffectState {
55public:
56 const EffectOutStatus& GetOutStatus() const {
57 return out_status;
58 }
59
60 const EffectInStatus& GetInfo() const {
61 return info;
62 }
63
64 EffectInStatus& GetInfo() {
65 return info;
66 }
67
68 void UpdateState();
69
70private:
71 EffectOutStatus out_status{};
72 EffectInStatus info{};
73};
54AudioRenderer::AudioRenderer(AudioRendererParameter params, 74AudioRenderer::AudioRenderer(AudioRendererParameter params,
55 Kernel::SharedPtr<Kernel::Event> buffer_event) 75 Kernel::SharedPtr<Kernel::Event> buffer_event)
56 : worker_params{params}, buffer_event{buffer_event}, voices(params.voice_count) { 76 : worker_params{params}, buffer_event{buffer_event}, voices(params.voice_count),
77 effects(params.effect_count) {
57 78
58 audio_out = std::make_unique<AudioCore::AudioOut>(); 79 audio_out = std::make_unique<AudioCore::AudioOut>();
59 stream = audio_out->OpenStream(STREAM_SAMPLE_RATE, STREAM_NUM_CHANNELS, "AudioRenderer", 80 stream = audio_out->OpenStream(STREAM_SAMPLE_RATE, STREAM_NUM_CHANNELS, "AudioRenderer",
@@ -96,11 +117,29 @@ std::vector<u8> AudioRenderer::UpdateAudioRenderer(const std::vector<u8>& input_
96 memory_pool_count * sizeof(MemoryPoolInfo)); 117 memory_pool_count * sizeof(MemoryPoolInfo));
97 118
98 // Copy VoiceInfo structs 119 // Copy VoiceInfo structs
99 std::size_t offset{sizeof(UpdateDataHeader) + config.behavior_size + config.memory_pools_size + 120 std::size_t voice_offset{sizeof(UpdateDataHeader) + config.behavior_size +
100 config.voice_resource_size}; 121 config.memory_pools_size + config.voice_resource_size};
101 for (auto& voice : voices) { 122 for (auto& voice : voices) {
102 std::memcpy(&voice.Info(), input_params.data() + offset, sizeof(VoiceInfo)); 123 std::memcpy(&voice.GetInfo(), input_params.data() + voice_offset, sizeof(VoiceInfo));
103 offset += sizeof(VoiceInfo); 124 voice_offset += sizeof(VoiceInfo);
125 }
126
127 std::size_t effect_offset{sizeof(UpdateDataHeader) + config.behavior_size +
128 config.memory_pools_size + config.voice_resource_size +
129 config.voices_size};
130 for (auto& effect : effects) {
131 std::memcpy(&effect.GetInfo(), input_params.data() + effect_offset, sizeof(EffectInStatus));
132 effect_offset += sizeof(EffectInStatus);
133 }
134
135 // Update memory pool state
136 std::vector<MemoryPoolEntry> memory_pool(memory_pool_count);
137 for (std::size_t index = 0; index < memory_pool.size(); ++index) {
138 if (mem_pool_info[index].pool_state == MemoryPoolStates::RequestAttach) {
139 memory_pool[index].state = MemoryPoolStates::Attached;
140 } else if (mem_pool_info[index].pool_state == MemoryPoolStates::RequestDetach) {
141 memory_pool[index].state = MemoryPoolStates::Detached;
142 }
104 } 143 }
105 144
106 // Update voices 145 // Update voices
@@ -114,14 +153,8 @@ std::vector<u8> AudioRenderer::UpdateAudioRenderer(const std::vector<u8>& input_
114 } 153 }
115 } 154 }
116 155
117 // Update memory pool state 156 for (auto& effect : effects) {
118 std::vector<MemoryPoolEntry> memory_pool(memory_pool_count); 157 effect.UpdateState();
119 for (std::size_t index = 0; index < memory_pool.size(); ++index) {
120 if (mem_pool_info[index].pool_state == MemoryPoolStates::RequestAttach) {
121 memory_pool[index].state = MemoryPoolStates::Attached;
122 } else if (mem_pool_info[index].pool_state == MemoryPoolStates::RequestDetach) {
123 memory_pool[index].state = MemoryPoolStates::Detached;
124 }
125 } 158 }
126 159
127 // Release previous buffers and queue next ones for playback 160 // Release previous buffers and queue next ones for playback
@@ -144,6 +177,14 @@ std::vector<u8> AudioRenderer::UpdateAudioRenderer(const std::vector<u8>& input_
144 voice_out_status_offset += sizeof(VoiceOutStatus); 177 voice_out_status_offset += sizeof(VoiceOutStatus);
145 } 178 }
146 179
180 std::size_t effect_out_status_offset{
181 sizeof(UpdateDataHeader) + response_data.memory_pools_size + response_data.voices_size +
182 response_data.voice_resource_size};
183 for (const auto& effect : effects) {
184 std::memcpy(output_params.data() + effect_out_status_offset, &effect.GetOutStatus(),
185 sizeof(EffectOutStatus));
186 effect_out_status_offset += sizeof(EffectOutStatus);
187 }
147 return output_params; 188 return output_params;
148} 189}
149 190
@@ -244,11 +285,29 @@ void AudioRenderer::VoiceState::RefreshBuffer() {
244 break; 285 break;
245 } 286 }
246 287
247 samples = Interpolate(interp_state, std::move(samples), Info().sample_rate, STREAM_SAMPLE_RATE); 288 samples =
289 Interpolate(interp_state, std::move(samples), GetInfo().sample_rate, STREAM_SAMPLE_RATE);
248 290
249 is_refresh_pending = false; 291 is_refresh_pending = false;
250} 292}
251 293
294void AudioRenderer::EffectState::UpdateState() {
295 if (info.is_new) {
296 out_status.state = EffectStatus::New;
297 } else {
298 if (info.type == Effect::Aux) {
299 ASSERT_MSG(Memory::Read32(info.aux_info.return_buffer_info) == 0,
300 "Aux buffers tried to update");
301 ASSERT_MSG(Memory::Read32(info.aux_info.send_buffer_info) == 0,
302 "Aux buffers tried to update");
303 ASSERT_MSG(Memory::Read32(info.aux_info.return_buffer_base) == 0,
304 "Aux buffers tried to update");
305 ASSERT_MSG(Memory::Read32(info.aux_info.send_buffer_base) == 0,
306 "Aux buffers tried to update");
307 }
308 }
309}
310
252static constexpr s16 ClampToS16(s32 value) { 311static constexpr s16 ClampToS16(s32 value) {
253 return static_cast<s16>(std::clamp(value, -32768, 32767)); 312 return static_cast<s16>(std::clamp(value, -32768, 32767));
254} 313}
diff --git a/src/audio_core/audio_renderer.h b/src/audio_core/audio_renderer.h
index dfef89e1d..046417da3 100644
--- a/src/audio_core/audio_renderer.h
+++ b/src/audio_core/audio_renderer.h
@@ -28,6 +28,16 @@ enum class PlayState : u8 {
28 Paused = 2, 28 Paused = 2,
29}; 29};
30 30
31enum class Effect : u8 {
32 None = 0,
33 Aux = 2,
34};
35
36enum class EffectStatus : u8 {
37 None = 0,
38 New = 1,
39};
40
31struct AudioRendererParameter { 41struct AudioRendererParameter {
32 u32_le sample_rate; 42 u32_le sample_rate;
33 u32_le sample_count; 43 u32_le sample_count;
@@ -128,6 +138,43 @@ struct VoiceOutStatus {
128}; 138};
129static_assert(sizeof(VoiceOutStatus) == 0x10, "VoiceOutStatus has wrong size"); 139static_assert(sizeof(VoiceOutStatus) == 0x10, "VoiceOutStatus has wrong size");
130 140
141struct AuxInfo {
142 std::array<u8, 24> input_mix_buffers;
143 std::array<u8, 24> output_mix_buffers;
144 u32_le mix_buffer_count;
145 u32_le sample_rate; // Stored in the aux buffer currently
146 u32_le sampe_count;
147 u64_le send_buffer_info;
148 u64_le send_buffer_base;
149
150 u64_le return_buffer_info;
151 u64_le return_buffer_base;
152};
153static_assert(sizeof(AuxInfo) == 0x60, "AuxInfo is an invalid size");
154
155struct EffectInStatus {
156 Effect type;
157 u8 is_new;
158 u8 is_enabled;
159 INSERT_PADDING_BYTES(1);
160 u32_le mix_id;
161 u64_le buffer_base;
162 u64_le buffer_sz;
163 s32_le priority;
164 INSERT_PADDING_BYTES(4);
165 union {
166 std::array<u8, 0xa0> raw;
167 AuxInfo aux_info;
168 };
169};
170static_assert(sizeof(EffectInStatus) == 0xc0, "EffectInStatus is an invalid size");
171
172struct EffectOutStatus {
173 EffectStatus state;
174 INSERT_PADDING_BYTES(0xf);
175};
176static_assert(sizeof(EffectOutStatus) == 0x10, "EffectOutStatus is an invalid size");
177
131struct UpdateDataHeader { 178struct UpdateDataHeader {
132 UpdateDataHeader() {} 179 UpdateDataHeader() {}
133 180
@@ -173,11 +220,13 @@ public:
173 Stream::State GetStreamState() const; 220 Stream::State GetStreamState() const;
174 221
175private: 222private:
223 class EffectState;
176 class VoiceState; 224 class VoiceState;
177 225
178 AudioRendererParameter worker_params; 226 AudioRendererParameter worker_params;
179 Kernel::SharedPtr<Kernel::Event> buffer_event; 227 Kernel::SharedPtr<Kernel::Event> buffer_event;
180 std::vector<VoiceState> voices; 228 std::vector<VoiceState> voices;
229 std::vector<EffectState> effects;
181 std::unique_ptr<AudioOut> audio_out; 230 std::unique_ptr<AudioOut> audio_out;
182 AudioCore::StreamPtr stream; 231 AudioCore::StreamPtr stream;
183}; 232};
diff --git a/src/core/arm/dynarmic/arm_dynarmic.cpp b/src/core/arm/dynarmic/arm_dynarmic.cpp
index 7e978cf7a..0762321a9 100644
--- a/src/core/arm/dynarmic/arm_dynarmic.cpp
+++ b/src/core/arm/dynarmic/arm_dynarmic.cpp
@@ -129,7 +129,7 @@ public:
129}; 129};
130 130
131std::unique_ptr<Dynarmic::A64::Jit> ARM_Dynarmic::MakeJit() const { 131std::unique_ptr<Dynarmic::A64::Jit> ARM_Dynarmic::MakeJit() const {
132 auto& current_process = Core::CurrentProcess(); 132 auto* current_process = Core::CurrentProcess();
133 auto** const page_table = current_process->VMManager().page_table.pointers.data(); 133 auto** const page_table = current_process->VMManager().page_table.pointers.data();
134 134
135 Dynarmic::A64::UserConfig config; 135 Dynarmic::A64::UserConfig config;
diff --git a/src/core/core.cpp b/src/core/core.cpp
index b6acfb3e4..e2fb9e038 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -136,7 +136,8 @@ struct System::Impl {
136 if (virtual_filesystem == nullptr) 136 if (virtual_filesystem == nullptr)
137 virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>(); 137 virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
138 138
139 kernel.MakeCurrentProcess(Kernel::Process::Create(kernel, "main")); 139 auto main_process = Kernel::Process::Create(kernel, "main");
140 kernel.MakeCurrentProcess(main_process.get());
140 141
141 cpu_barrier = std::make_shared<CpuBarrier>(); 142 cpu_barrier = std::make_shared<CpuBarrier>();
142 cpu_exclusive_monitor = Cpu::MakeExclusiveMonitor(cpu_cores.size()); 143 cpu_exclusive_monitor = Cpu::MakeExclusiveMonitor(cpu_cores.size());
@@ -361,11 +362,11 @@ const std::shared_ptr<Kernel::Scheduler>& System::Scheduler(std::size_t core_ind
361 return impl->cpu_cores[core_index]->Scheduler(); 362 return impl->cpu_cores[core_index]->Scheduler();
362} 363}
363 364
364Kernel::SharedPtr<Kernel::Process>& System::CurrentProcess() { 365Kernel::Process* System::CurrentProcess() {
365 return impl->kernel.CurrentProcess(); 366 return impl->kernel.CurrentProcess();
366} 367}
367 368
368const Kernel::SharedPtr<Kernel::Process>& System::CurrentProcess() const { 369const Kernel::Process* System::CurrentProcess() const {
369 return impl->kernel.CurrentProcess(); 370 return impl->kernel.CurrentProcess();
370} 371}
371 372
diff --git a/src/core/core.h b/src/core/core.h
index f9a3e97e3..ea4d53914 100644
--- a/src/core/core.h
+++ b/src/core/core.h
@@ -174,11 +174,11 @@ public:
174 /// Gets the scheduler for the CPU core with the specified index 174 /// Gets the scheduler for the CPU core with the specified index
175 const std::shared_ptr<Kernel::Scheduler>& Scheduler(std::size_t core_index); 175 const std::shared_ptr<Kernel::Scheduler>& Scheduler(std::size_t core_index);
176 176
177 /// Provides a reference to the current process 177 /// Provides a pointer to the current process
178 Kernel::SharedPtr<Kernel::Process>& CurrentProcess(); 178 Kernel::Process* CurrentProcess();
179 179
180 /// Provides a constant reference to the current process. 180 /// Provides a constant pointer to the current process.
181 const Kernel::SharedPtr<Kernel::Process>& CurrentProcess() const; 181 const Kernel::Process* CurrentProcess() const;
182 182
183 /// Provides a reference to the kernel instance. 183 /// Provides a reference to the kernel instance.
184 Kernel::KernelCore& Kernel(); 184 Kernel::KernelCore& Kernel();
@@ -246,7 +246,7 @@ inline TelemetrySession& Telemetry() {
246 return System::GetInstance().TelemetrySession(); 246 return System::GetInstance().TelemetrySession();
247} 247}
248 248
249inline Kernel::SharedPtr<Kernel::Process>& CurrentProcess() { 249inline Kernel::Process* CurrentProcess() {
250 return System::GetInstance().CurrentProcess(); 250 return System::GetInstance().CurrentProcess();
251} 251}
252 252
diff --git a/src/core/file_sys/ips_layer.cpp b/src/core/file_sys/ips_layer.cpp
index 0cadbc375..554eae9bc 100644
--- a/src/core/file_sys/ips_layer.cpp
+++ b/src/core/file_sys/ips_layer.cpp
@@ -2,9 +2,15 @@
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 <algorithm>
6#include <cstring>
7#include <map>
5#include <sstream> 8#include <sstream>
6#include "common/assert.h" 9#include <string>
10#include <utility>
11
7#include "common/hex_util.h" 12#include "common/hex_util.h"
13#include "common/logging/log.h"
8#include "common/swap.h" 14#include "common/swap.h"
9#include "core/file_sys/ips_layer.h" 15#include "core/file_sys/ips_layer.h"
10#include "core/file_sys/vfs_vector.h" 16#include "core/file_sys/vfs_vector.h"
@@ -17,22 +23,48 @@ enum class IPSFileType {
17 Error, 23 Error,
18}; 24};
19 25
20constexpr std::array<std::pair<const char*, const char*>, 11> ESCAPE_CHARACTER_MAP{ 26constexpr std::array<std::pair<const char*, const char*>, 11> ESCAPE_CHARACTER_MAP{{
21 std::pair{"\\a", "\a"}, {"\\b", "\b"}, {"\\f", "\f"}, {"\\n", "\n"}, 27 {"\\a", "\a"},
22 {"\\r", "\r"}, {"\\t", "\t"}, {"\\v", "\v"}, {"\\\\", "\\"}, 28 {"\\b", "\b"},
23 {"\\\'", "\'"}, {"\\\"", "\""}, {"\\\?", "\?"}, 29 {"\\f", "\f"},
24}; 30 {"\\n", "\n"},
31 {"\\r", "\r"},
32 {"\\t", "\t"},
33 {"\\v", "\v"},
34 {"\\\\", "\\"},
35 {"\\\'", "\'"},
36 {"\\\"", "\""},
37 {"\\\?", "\?"},
38}};
25 39
26static IPSFileType IdentifyMagic(const std::vector<u8>& magic) { 40static IPSFileType IdentifyMagic(const std::vector<u8>& magic) {
27 if (magic.size() != 5) 41 if (magic.size() != 5) {
28 return IPSFileType::Error; 42 return IPSFileType::Error;
29 if (magic == std::vector<u8>{'P', 'A', 'T', 'C', 'H'}) 43 }
44
45 constexpr std::array<u8, 5> patch_magic{{'P', 'A', 'T', 'C', 'H'}};
46 if (std::equal(magic.begin(), magic.end(), patch_magic.begin())) {
30 return IPSFileType::IPS; 47 return IPSFileType::IPS;
31 if (magic == std::vector<u8>{'I', 'P', 'S', '3', '2'}) 48 }
49
50 constexpr std::array<u8, 5> ips32_magic{{'I', 'P', 'S', '3', '2'}};
51 if (std::equal(magic.begin(), magic.end(), ips32_magic.begin())) {
32 return IPSFileType::IPS32; 52 return IPSFileType::IPS32;
53 }
54
33 return IPSFileType::Error; 55 return IPSFileType::Error;
34} 56}
35 57
58static bool IsEOF(IPSFileType type, const std::vector<u8>& data) {
59 constexpr std::array<u8, 3> eof{{'E', 'O', 'F'}};
60 if (type == IPSFileType::IPS && std::equal(data.begin(), data.end(), eof.begin())) {
61 return true;
62 }
63
64 constexpr std::array<u8, 4> eeof{{'E', 'E', 'O', 'F'}};
65 return type == IPSFileType::IPS32 && std::equal(data.begin(), data.end(), eeof.begin());
66}
67
36VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) { 68VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
37 if (in == nullptr || ips == nullptr) 69 if (in == nullptr || ips == nullptr)
38 return nullptr; 70 return nullptr;
@@ -47,8 +79,7 @@ VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
47 u64 offset = 5; // After header 79 u64 offset = 5; // After header
48 while (ips->Read(temp.data(), temp.size(), offset) == temp.size()) { 80 while (ips->Read(temp.data(), temp.size(), offset) == temp.size()) {
49 offset += temp.size(); 81 offset += temp.size();
50 if (type == IPSFileType::IPS32 && temp == std::vector<u8>{'E', 'E', 'O', 'F'} || 82 if (IsEOF(type, temp)) {
51 type == IPSFileType::IPS && temp == std::vector<u8>{'E', 'O', 'F'}) {
52 break; 83 break;
53 } 84 }
54 85
@@ -76,23 +107,32 @@ VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
76 return nullptr; 107 return nullptr;
77 108
78 if (real_offset + rle_size > in_data.size()) 109 if (real_offset + rle_size > in_data.size())
79 rle_size = in_data.size() - real_offset; 110 rle_size = static_cast<u16>(in_data.size() - real_offset);
80 std::memset(in_data.data() + real_offset, data.get(), rle_size); 111 std::memset(in_data.data() + real_offset, data.get(), rle_size);
81 } else { // Standard Patch 112 } else { // Standard Patch
82 auto read = data_size; 113 auto read = data_size;
83 if (real_offset + read > in_data.size()) 114 if (real_offset + read > in_data.size())
84 read = in_data.size() - real_offset; 115 read = static_cast<u16>(in_data.size() - real_offset);
85 if (ips->Read(in_data.data() + real_offset, read, offset) != data_size) 116 if (ips->Read(in_data.data() + real_offset, read, offset) != data_size)
86 return nullptr; 117 return nullptr;
87 offset += data_size; 118 offset += data_size;
88 } 119 }
89 } 120 }
90 121
91 if (temp != std::vector<u8>{'E', 'E', 'O', 'F'} && temp != std::vector<u8>{'E', 'O', 'F'}) 122 if (!IsEOF(type, temp)) {
92 return nullptr; 123 return nullptr;
93 return std::make_shared<VectorVfsFile>(in_data, in->GetName(), in->GetContainingDirectory()); 124 }
125
126 return std::make_shared<VectorVfsFile>(std::move(in_data), in->GetName(),
127 in->GetContainingDirectory());
94} 128}
95 129
130struct IPSwitchCompiler::IPSwitchPatch {
131 std::string name;
132 bool enabled;
133 std::map<u32, std::vector<u8>> records;
134};
135
96IPSwitchCompiler::IPSwitchCompiler(VirtualFile patch_text_) : patch_text(std::move(patch_text_)) { 136IPSwitchCompiler::IPSwitchCompiler(VirtualFile patch_text_) : patch_text(std::move(patch_text_)) {
97 Parse(); 137 Parse();
98} 138}
@@ -225,7 +265,7 @@ void IPSwitchCompiler::Parse() {
225 if (patch_line.length() < 11) 265 if (patch_line.length() < 11)
226 break; 266 break;
227 auto offset = std::stoul(patch_line.substr(0, 8), nullptr, 16); 267 auto offset = std::stoul(patch_line.substr(0, 8), nullptr, 16);
228 offset += offset_shift; 268 offset += static_cast<unsigned long>(offset_shift);
229 269
230 std::vector<u8> replace; 270 std::vector<u8> replace;
231 // 9 - first char of replacement val 271 // 9 - first char of replacement val
@@ -291,7 +331,8 @@ VirtualFile IPSwitchCompiler::Apply(const VirtualFile& in) const {
291 } 331 }
292 } 332 }
293 333
294 return std::make_shared<VectorVfsFile>(in_data, in->GetName(), in->GetContainingDirectory()); 334 return std::make_shared<VectorVfsFile>(std::move(in_data), in->GetName(),
335 in->GetContainingDirectory());
295} 336}
296 337
297} // namespace FileSys 338} // namespace FileSys
diff --git a/src/core/file_sys/ips_layer.h b/src/core/file_sys/ips_layer.h
index 57da00da8..450b2f71e 100644
--- a/src/core/file_sys/ips_layer.h
+++ b/src/core/file_sys/ips_layer.h
@@ -4,8 +4,11 @@
4 4
5#pragma once 5#pragma once
6 6
7#include <array>
7#include <memory> 8#include <memory>
9#include <vector>
8 10
11#include "common/common_types.h"
9#include "core/file_sys/vfs.h" 12#include "core/file_sys/vfs.h"
10 13
11namespace FileSys { 14namespace FileSys {
@@ -22,17 +25,13 @@ public:
22 VirtualFile Apply(const VirtualFile& in) const; 25 VirtualFile Apply(const VirtualFile& in) const;
23 26
24private: 27private:
28 struct IPSwitchPatch;
29
25 void ParseFlag(const std::string& flag); 30 void ParseFlag(const std::string& flag);
26 void Parse(); 31 void Parse();
27 32
28 bool valid = false; 33 bool valid = false;
29 34
30 struct IPSwitchPatch {
31 std::string name;
32 bool enabled;
33 std::map<u32, std::vector<u8>> records;
34 };
35
36 VirtualFile patch_text; 35 VirtualFile patch_text;
37 std::vector<IPSwitchPatch> patches; 36 std::vector<IPSwitchPatch> patches;
38 std::array<u8, 0x20> nso_build_id{}; 37 std::array<u8, 0x20> nso_build_id{};
diff --git a/src/core/file_sys/patch_manager.cpp b/src/core/file_sys/patch_manager.cpp
index b14d7cb0a..019caebe9 100644
--- a/src/core/file_sys/patch_manager.cpp
+++ b/src/core/file_sys/patch_manager.cpp
@@ -345,23 +345,22 @@ std::map<std::string, std::string, std::less<>> PatchManager::GetPatchVersionNam
345 return out; 345 return out;
346} 346}
347 347
348std::pair<std::shared_ptr<NACP>, VirtualFile> PatchManager::GetControlMetadata() const { 348std::pair<std::unique_ptr<NACP>, VirtualFile> PatchManager::GetControlMetadata() const {
349 const auto& installed{Service::FileSystem::GetUnionContents()}; 349 const auto& installed{Service::FileSystem::GetUnionContents()};
350 350
351 const auto base_control_nca = installed->GetEntry(title_id, ContentRecordType::Control); 351 const auto base_control_nca = installed->GetEntry(title_id, ContentRecordType::Control);
352 if (base_control_nca == nullptr) 352 if (base_control_nca == nullptr)
353 return {}; 353 return {};
354 354
355 return ParseControlNCA(base_control_nca); 355 return ParseControlNCA(*base_control_nca);
356} 356}
357 357
358std::pair<std::shared_ptr<NACP>, VirtualFile> PatchManager::ParseControlNCA( 358std::pair<std::unique_ptr<NACP>, VirtualFile> PatchManager::ParseControlNCA(const NCA& nca) const {
359 const std::shared_ptr<NCA>& nca) const { 359 const auto base_romfs = nca.GetRomFS();
360 const auto base_romfs = nca->GetRomFS();
361 if (base_romfs == nullptr) 360 if (base_romfs == nullptr)
362 return {}; 361 return {};
363 362
364 const auto romfs = PatchRomFS(base_romfs, nca->GetBaseIVFCOffset(), ContentRecordType::Control); 363 const auto romfs = PatchRomFS(base_romfs, nca.GetBaseIVFCOffset(), ContentRecordType::Control);
365 if (romfs == nullptr) 364 if (romfs == nullptr)
366 return {}; 365 return {};
367 366
@@ -373,7 +372,7 @@ std::pair<std::shared_ptr<NACP>, VirtualFile> PatchManager::ParseControlNCA(
373 if (nacp_file == nullptr) 372 if (nacp_file == nullptr)
374 nacp_file = extracted->GetFile("Control.nacp"); 373 nacp_file = extracted->GetFile("Control.nacp");
375 374
376 const auto nacp = nacp_file == nullptr ? nullptr : std::make_shared<NACP>(nacp_file); 375 auto nacp = nacp_file == nullptr ? nullptr : std::make_unique<NACP>(nacp_file);
377 376
378 VirtualFile icon_file; 377 VirtualFile icon_file;
379 for (const auto& language : FileSys::LANGUAGE_NAMES) { 378 for (const auto& language : FileSys::LANGUAGE_NAMES) {
@@ -382,6 +381,6 @@ std::pair<std::shared_ptr<NACP>, VirtualFile> PatchManager::ParseControlNCA(
382 break; 381 break;
383 } 382 }
384 383
385 return {nacp, icon_file}; 384 return {std::move(nacp), icon_file};
386} 385}
387} // namespace FileSys 386} // namespace FileSys
diff --git a/src/core/file_sys/patch_manager.h b/src/core/file_sys/patch_manager.h
index eb6fc4607..7d168837f 100644
--- a/src/core/file_sys/patch_manager.h
+++ b/src/core/file_sys/patch_manager.h
@@ -57,11 +57,10 @@ public:
57 57
58 // Given title_id of the program, attempts to get the control data of the update and parse it, 58 // Given title_id of the program, attempts to get the control data of the update and parse it,
59 // falling back to the base control data. 59 // falling back to the base control data.
60 std::pair<std::shared_ptr<NACP>, VirtualFile> GetControlMetadata() const; 60 std::pair<std::unique_ptr<NACP>, VirtualFile> GetControlMetadata() const;
61 61
62 // Version of GetControlMetadata that takes an arbitrary NCA 62 // Version of GetControlMetadata that takes an arbitrary NCA
63 std::pair<std::shared_ptr<NACP>, VirtualFile> ParseControlNCA( 63 std::pair<std::unique_ptr<NACP>, VirtualFile> ParseControlNCA(const NCA& nca) const;
64 const std::shared_ptr<NCA>& nca) const;
65 64
66private: 65private:
67 u64 title_id; 66 u64 title_id;
diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index 98eb74298..bd680adfe 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -116,7 +116,7 @@ struct KernelCore::Impl {
116 next_thread_id = 1; 116 next_thread_id = 1;
117 117
118 process_list.clear(); 118 process_list.clear();
119 current_process.reset(); 119 current_process = nullptr;
120 120
121 handle_table.Clear(); 121 handle_table.Clear();
122 resource_limits.fill(nullptr); 122 resource_limits.fill(nullptr);
@@ -207,7 +207,7 @@ struct KernelCore::Impl {
207 207
208 // Lists all processes that exist in the current session. 208 // Lists all processes that exist in the current session.
209 std::vector<SharedPtr<Process>> process_list; 209 std::vector<SharedPtr<Process>> process_list;
210 SharedPtr<Process> current_process; 210 Process* current_process = nullptr;
211 211
212 Kernel::HandleTable handle_table; 212 Kernel::HandleTable handle_table;
213 std::array<SharedPtr<ResourceLimit>, 4> resource_limits; 213 std::array<SharedPtr<ResourceLimit>, 4> resource_limits;
@@ -266,15 +266,15 @@ void KernelCore::AppendNewProcess(SharedPtr<Process> process) {
266 impl->process_list.push_back(std::move(process)); 266 impl->process_list.push_back(std::move(process));
267} 267}
268 268
269void KernelCore::MakeCurrentProcess(SharedPtr<Process> process) { 269void KernelCore::MakeCurrentProcess(Process* process) {
270 impl->current_process = std::move(process); 270 impl->current_process = process;
271} 271}
272 272
273SharedPtr<Process>& KernelCore::CurrentProcess() { 273Process* KernelCore::CurrentProcess() {
274 return impl->current_process; 274 return impl->current_process;
275} 275}
276 276
277const SharedPtr<Process>& KernelCore::CurrentProcess() const { 277const Process* KernelCore::CurrentProcess() const {
278 return impl->current_process; 278 return impl->current_process;
279} 279}
280 280
diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h
index c0771ecf0..41554821f 100644
--- a/src/core/hle/kernel/kernel.h
+++ b/src/core/hle/kernel/kernel.h
@@ -66,13 +66,13 @@ public:
66 void AppendNewProcess(SharedPtr<Process> process); 66 void AppendNewProcess(SharedPtr<Process> process);
67 67
68 /// Makes the given process the new current process. 68 /// Makes the given process the new current process.
69 void MakeCurrentProcess(SharedPtr<Process> process); 69 void MakeCurrentProcess(Process* process);
70 70
71 /// Retrieves a reference to the current process. 71 /// Retrieves a pointer to the current process.
72 SharedPtr<Process>& CurrentProcess(); 72 Process* CurrentProcess();
73 73
74 /// Retrieves a const reference to the current process. 74 /// Retrieves a const pointer to the current process.
75 const SharedPtr<Process>& CurrentProcess() const; 75 const Process* CurrentProcess() const;
76 76
77 /// Adds a port to the named port table 77 /// Adds a port to the named port table
78 void AddNamedPort(std::string name, SharedPtr<ClientPort> port); 78 void AddNamedPort(std::string name, SharedPtr<ClientPort> port);
diff --git a/src/core/hle/kernel/scheduler.cpp b/src/core/hle/kernel/scheduler.cpp
index cfd6e1bad..1342c597e 100644
--- a/src/core/hle/kernel/scheduler.cpp
+++ b/src/core/hle/kernel/scheduler.cpp
@@ -9,7 +9,7 @@
9#include "common/logging/log.h" 9#include "common/logging/log.h"
10#include "core/arm/arm_interface.h" 10#include "core/arm/arm_interface.h"
11#include "core/core.h" 11#include "core/core.h"
12#include "core/core_timing.h" 12#include "core/hle/kernel/kernel.h"
13#include "core/hle/kernel/process.h" 13#include "core/hle/kernel/process.h"
14#include "core/hle/kernel/scheduler.h" 14#include "core/hle/kernel/scheduler.h"
15 15
@@ -78,16 +78,16 @@ void Scheduler::SwitchContext(Thread* new_thread) {
78 // Cancel any outstanding wakeup events for this thread 78 // Cancel any outstanding wakeup events for this thread
79 new_thread->CancelWakeupTimer(); 79 new_thread->CancelWakeupTimer();
80 80
81 auto previous_process = Core::CurrentProcess(); 81 auto* const previous_process = Core::CurrentProcess();
82 82
83 current_thread = new_thread; 83 current_thread = new_thread;
84 84
85 ready_queue.remove(new_thread->GetPriority(), new_thread); 85 ready_queue.remove(new_thread->GetPriority(), new_thread);
86 new_thread->SetStatus(ThreadStatus::Running); 86 new_thread->SetStatus(ThreadStatus::Running);
87 87
88 const auto thread_owner_process = current_thread->GetOwnerProcess(); 88 auto* const thread_owner_process = current_thread->GetOwnerProcess();
89 if (previous_process != thread_owner_process) { 89 if (previous_process != thread_owner_process) {
90 Core::CurrentProcess() = thread_owner_process; 90 Core::System::GetInstance().Kernel().MakeCurrentProcess(thread_owner_process);
91 SetCurrentPageTable(&Core::CurrentProcess()->VMManager().page_table); 91 SetCurrentPageTable(&Core::CurrentProcess()->VMManager().page_table);
92 } 92 }
93 93
diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp
index 6c4af7e47..3afcce3fe 100644
--- a/src/core/hle/kernel/svc.cpp
+++ b/src/core/hle/kernel/svc.cpp
@@ -301,13 +301,28 @@ static ResultCode ArbitrateUnlock(VAddr mutex_addr) {
301 return Mutex::Release(mutex_addr); 301 return Mutex::Release(mutex_addr);
302} 302}
303 303
304struct BreakReason {
305 union {
306 u64 raw;
307 BitField<31, 1, u64> dont_kill_application;
308 };
309};
310
304/// Break program execution 311/// Break program execution
305static void Break(u64 reason, u64 info1, u64 info2) { 312static void Break(u64 reason, u64 info1, u64 info2) {
306 LOG_CRITICAL( 313 BreakReason break_reason{reason};
307 Debug_Emulated, 314 if (break_reason.dont_kill_application) {
308 "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}", 315 LOG_ERROR(
309 reason, info1, info2); 316 Debug_Emulated,
310 ASSERT(false); 317 "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
318 reason, info1, info2);
319 } else {
320 LOG_CRITICAL(
321 Debug_Emulated,
322 "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
323 reason, info1, info2);
324 ASSERT(false);
325 }
311} 326}
312 327
313/// Used to output a message on a debug hardware unit - does nothing on a retail unit 328/// Used to output a message on a debug hardware unit - does nothing on a retail unit
@@ -326,7 +341,7 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
326 LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id, 341 LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
327 info_sub_id, handle); 342 info_sub_id, handle);
328 343
329 const auto& current_process = Core::CurrentProcess(); 344 const auto* current_process = Core::CurrentProcess();
330 const auto& vm_manager = current_process->VMManager(); 345 const auto& vm_manager = current_process->VMManager();
331 346
332 switch (static_cast<GetInfoType>(info_id)) { 347 switch (static_cast<GetInfoType>(info_id)) {
@@ -424,7 +439,7 @@ static ResultCode GetThreadContext(VAddr thread_context, Handle handle) {
424 return ERR_INVALID_HANDLE; 439 return ERR_INVALID_HANDLE;
425 } 440 }
426 441
427 const auto current_process = Core::CurrentProcess(); 442 const auto* current_process = Core::CurrentProcess();
428 if (thread->GetOwnerProcess() != current_process) { 443 if (thread->GetOwnerProcess() != current_process) {
429 return ERR_INVALID_HANDLE; 444 return ERR_INVALID_HANDLE;
430 } 445 }
@@ -516,7 +531,7 @@ static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 s
516 return ERR_INVALID_HANDLE; 531 return ERR_INVALID_HANDLE;
517 } 532 }
518 533
519 return shared_memory->Map(Core::CurrentProcess().get(), addr, permissions_type, 534 return shared_memory->Map(Core::CurrentProcess(), addr, permissions_type,
520 MemoryPermission::DontCare); 535 MemoryPermission::DontCare);
521} 536}
522 537
@@ -535,7 +550,7 @@ static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64
535 auto& kernel = Core::System::GetInstance().Kernel(); 550 auto& kernel = Core::System::GetInstance().Kernel();
536 auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle); 551 auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
537 552
538 return shared_memory->Unmap(Core::CurrentProcess().get(), addr); 553 return shared_memory->Unmap(Core::CurrentProcess(), addr);
539} 554}
540 555
541/// Query process memory 556/// Query process memory
@@ -573,7 +588,7 @@ static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAdd
573 588
574/// Exits the current process 589/// Exits the current process
575static void ExitProcess() { 590static void ExitProcess() {
576 auto& current_process = Core::CurrentProcess(); 591 auto* current_process = Core::CurrentProcess();
577 592
578 LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID()); 593 LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
579 ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running, 594 ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
@@ -621,7 +636,7 @@ static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, V
621 auto& kernel = Core::System::GetInstance().Kernel(); 636 auto& kernel = Core::System::GetInstance().Kernel();
622 CASCADE_RESULT(SharedPtr<Thread> thread, 637 CASCADE_RESULT(SharedPtr<Thread> thread,
623 Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top, 638 Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top,
624 Core::CurrentProcess())); 639 *Core::CurrentProcess()));
625 const auto new_guest_handle = kernel.HandleTable().Create(thread); 640 const auto new_guest_handle = kernel.HandleTable().Create(thread);
626 if (new_guest_handle.Failed()) { 641 if (new_guest_handle.Failed()) {
627 return new_guest_handle.Code(); 642 return new_guest_handle.Code();
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 8e514cf9a..33aed8c23 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -194,7 +194,7 @@ static void ResetThreadContext(Core::ARM_Interface::ThreadContext& context, VAdd
194 194
195ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point, 195ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point,
196 u32 priority, u64 arg, s32 processor_id, 196 u32 priority, u64 arg, s32 processor_id,
197 VAddr stack_top, SharedPtr<Process> owner_process) { 197 VAddr stack_top, Process& owner_process) {
198 // Check if priority is in ranged. Lowest priority -> highest priority id. 198 // Check if priority is in ranged. Lowest priority -> highest priority id.
199 if (priority > THREADPRIO_LOWEST) { 199 if (priority > THREADPRIO_LOWEST) {
200 LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority); 200 LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
@@ -208,7 +208,7 @@ ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name
208 208
209 // TODO(yuriks): Other checks, returning 0xD9001BEA 209 // TODO(yuriks): Other checks, returning 0xD9001BEA
210 210
211 if (!Memory::IsValidVirtualAddress(*owner_process, entry_point)) { 211 if (!Memory::IsValidVirtualAddress(owner_process, entry_point)) {
212 LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point); 212 LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
213 // TODO (bunnei): Find the correct error code to use here 213 // TODO (bunnei): Find the correct error code to use here
214 return ResultCode(-1); 214 return ResultCode(-1);
@@ -232,7 +232,7 @@ ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name
232 thread->wait_handle = 0; 232 thread->wait_handle = 0;
233 thread->name = std::move(name); 233 thread->name = std::move(name);
234 thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap(); 234 thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap();
235 thread->owner_process = owner_process; 235 thread->owner_process = &owner_process;
236 thread->scheduler = Core::System::GetInstance().Scheduler(processor_id).get(); 236 thread->scheduler = Core::System::GetInstance().Scheduler(processor_id).get();
237 thread->scheduler->AddThread(thread, priority); 237 thread->scheduler->AddThread(thread, priority);
238 thread->tls_address = thread->owner_process->MarkNextAvailableTLSSlotAsUsed(*thread); 238 thread->tls_address = thread->owner_process->MarkNextAvailableTLSSlotAsUsed(*thread);
@@ -264,7 +264,7 @@ SharedPtr<Thread> SetupMainThread(KernelCore& kernel, VAddr entry_point, u32 pri
264 // Initialize new "main" thread 264 // Initialize new "main" thread
265 const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress(); 265 const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress();
266 auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0, THREADPROCESSORID_0, 266 auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0, THREADPROCESSORID_0,
267 stack_top, &owner_process); 267 stack_top, owner_process);
268 268
269 SharedPtr<Thread> thread = std::move(thread_res).Unwrap(); 269 SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
270 270
diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h
index c6ffbd28c..f4d7bd235 100644
--- a/src/core/hle/kernel/thread.h
+++ b/src/core/hle/kernel/thread.h
@@ -89,7 +89,7 @@ public:
89 static ResultVal<SharedPtr<Thread>> Create(KernelCore& kernel, std::string name, 89 static ResultVal<SharedPtr<Thread>> Create(KernelCore& kernel, std::string name,
90 VAddr entry_point, u32 priority, u64 arg, 90 VAddr entry_point, u32 priority, u64 arg,
91 s32 processor_id, VAddr stack_top, 91 s32 processor_id, VAddr stack_top,
92 SharedPtr<Process> owner_process); 92 Process& owner_process);
93 93
94 std::string GetName() const override { 94 std::string GetName() const override {
95 return name; 95 return name;
@@ -262,11 +262,11 @@ public:
262 return processor_id; 262 return processor_id;
263 } 263 }
264 264
265 SharedPtr<Process>& GetOwnerProcess() { 265 Process* GetOwnerProcess() {
266 return owner_process; 266 return owner_process;
267 } 267 }
268 268
269 const SharedPtr<Process>& GetOwnerProcess() const { 269 const Process* GetOwnerProcess() const {
270 return owner_process; 270 return owner_process;
271 } 271 }
272 272
@@ -386,7 +386,7 @@ private:
386 u64 tpidr_el0 = 0; ///< TPIDR_EL0 read/write system register. 386 u64 tpidr_el0 = 0; ///< TPIDR_EL0 read/write system register.
387 387
388 /// Process that owns this thread 388 /// Process that owns this thread
389 SharedPtr<Process> owner_process; 389 Process* owner_process;
390 390
391 /// Objects that the thread is waiting on, in the same order as they were 391 /// Objects that the thread is waiting on, in the same order as they were
392 /// passed to WaitSynchronization1/N. 392 /// passed to WaitSynchronization1/N.
diff --git a/src/core/loader/nsp.cpp b/src/core/loader/nsp.cpp
index 5534ce01c..13e57848d 100644
--- a/src/core/loader/nsp.cpp
+++ b/src/core/loader/nsp.cpp
@@ -35,7 +35,7 @@ AppLoader_NSP::AppLoader_NSP(FileSys::VirtualFile file)
35 return; 35 return;
36 36
37 std::tie(nacp_file, icon_file) = 37 std::tie(nacp_file, icon_file) =
38 FileSys::PatchManager(nsp->GetProgramTitleID()).ParseControlNCA(control_nca); 38 FileSys::PatchManager(nsp->GetProgramTitleID()).ParseControlNCA(*control_nca);
39} 39}
40 40
41AppLoader_NSP::~AppLoader_NSP() = default; 41AppLoader_NSP::~AppLoader_NSP() = default;
diff --git a/src/core/loader/nsp.h b/src/core/loader/nsp.h
index b006594a6..db91cd01e 100644
--- a/src/core/loader/nsp.h
+++ b/src/core/loader/nsp.h
@@ -49,7 +49,7 @@ private:
49 std::unique_ptr<AppLoader> secondary_loader; 49 std::unique_ptr<AppLoader> secondary_loader;
50 50
51 FileSys::VirtualFile icon_file; 51 FileSys::VirtualFile icon_file;
52 std::shared_ptr<FileSys::NACP> nacp_file; 52 std::unique_ptr<FileSys::NACP> nacp_file;
53 u64 title_id; 53 u64 title_id;
54}; 54};
55 55
diff --git a/src/core/loader/xci.cpp b/src/core/loader/xci.cpp
index ee5452eb9..7a619acb4 100644
--- a/src/core/loader/xci.cpp
+++ b/src/core/loader/xci.cpp
@@ -30,7 +30,7 @@ AppLoader_XCI::AppLoader_XCI(FileSys::VirtualFile file)
30 return; 30 return;
31 31
32 std::tie(nacp_file, icon_file) = 32 std::tie(nacp_file, icon_file) =
33 FileSys::PatchManager(xci->GetProgramTitleID()).ParseControlNCA(control_nca); 33 FileSys::PatchManager(xci->GetProgramTitleID()).ParseControlNCA(*control_nca);
34} 34}
35 35
36AppLoader_XCI::~AppLoader_XCI() = default; 36AppLoader_XCI::~AppLoader_XCI() = default;
diff --git a/src/core/loader/xci.h b/src/core/loader/xci.h
index 770ed1437..46f8dfc9e 100644
--- a/src/core/loader/xci.h
+++ b/src/core/loader/xci.h
@@ -49,7 +49,7 @@ private:
49 std::unique_ptr<AppLoader_NCA> nca_loader; 49 std::unique_ptr<AppLoader_NCA> nca_loader;
50 50
51 FileSys::VirtualFile icon_file; 51 FileSys::VirtualFile icon_file;
52 std::shared_ptr<FileSys::NACP> nacp_file; 52 std::unique_ptr<FileSys::NACP> nacp_file;
53}; 53};
54 54
55} // namespace Loader 55} // namespace Loader
diff --git a/src/core/telemetry_session.cpp b/src/core/telemetry_session.cpp
index f29fff1e7..7b04792b5 100644
--- a/src/core/telemetry_session.cpp
+++ b/src/core/telemetry_session.cpp
@@ -2,12 +2,16 @@
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 <array>
6
7#include <mbedtls/ctr_drbg.h>
8#include <mbedtls/entropy.h>
9
5#include "common/assert.h" 10#include "common/assert.h"
6#include "common/common_types.h" 11#include "common/common_types.h"
7#include "common/file_util.h" 12#include "common/file_util.h"
13#include "common/logging/log.h"
8 14
9#include <mbedtls/ctr_drbg.h>
10#include <mbedtls/entropy.h>
11#include "core/core.h" 15#include "core/core.h"
12#include "core/file_sys/control_metadata.h" 16#include "core/file_sys/control_metadata.h"
13#include "core/file_sys/patch_manager.h" 17#include "core/file_sys/patch_manager.h"
@@ -28,11 +32,11 @@ static u64 GenerateTelemetryId() {
28 mbedtls_entropy_context entropy; 32 mbedtls_entropy_context entropy;
29 mbedtls_entropy_init(&entropy); 33 mbedtls_entropy_init(&entropy);
30 mbedtls_ctr_drbg_context ctr_drbg; 34 mbedtls_ctr_drbg_context ctr_drbg;
31 std::string personalization = "yuzu Telemetry ID"; 35 constexpr std::array<char, 18> personalization{{"yuzu Telemetry ID"}};
32 36
33 mbedtls_ctr_drbg_init(&ctr_drbg); 37 mbedtls_ctr_drbg_init(&ctr_drbg);
34 ASSERT(mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, 38 ASSERT(mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
35 reinterpret_cast<const unsigned char*>(personalization.c_str()), 39 reinterpret_cast<const unsigned char*>(personalization.data()),
36 personalization.size()) == 0); 40 personalization.size()) == 0);
37 ASSERT(mbedtls_ctr_drbg_random(&ctr_drbg, reinterpret_cast<unsigned char*>(&telemetry_id), 41 ASSERT(mbedtls_ctr_drbg_random(&ctr_drbg, reinterpret_cast<unsigned char*>(&telemetry_id),
38 sizeof(u64)) == 0); 42 sizeof(u64)) == 0);
diff --git a/src/core/telemetry_session.h b/src/core/telemetry_session.h
index cec271df0..2a4845797 100644
--- a/src/core/telemetry_session.h
+++ b/src/core/telemetry_session.h
@@ -5,6 +5,7 @@
5#pragma once 5#pragma once
6 6
7#include <memory> 7#include <memory>
8#include <string>
8#include "common/telemetry.h" 9#include "common/telemetry.h"
9 10
10namespace Core { 11namespace Core {
@@ -30,8 +31,6 @@ public:
30 field_collection.AddField(type, name, std::move(value)); 31 field_collection.AddField(type, name, std::move(value));
31 } 32 }
32 33
33 static void FinalizeAsyncJob();
34
35private: 34private:
36 Telemetry::FieldCollection field_collection; ///< Tracks all added fields for the session 35 Telemetry::FieldCollection field_collection; ///< Tracks all added fields for the session
37 std::unique_ptr<Telemetry::VisitorInterface> backend; ///< Backend interface that logs fields 36 std::unique_ptr<Telemetry::VisitorInterface> backend; ///< Backend interface that logs fields
@@ -53,7 +52,6 @@ u64 RegenerateTelemetryId();
53 * Verifies the username and token. 52 * Verifies the username and token.
54 * @param username yuzu username to use for authentication. 53 * @param username yuzu username to use for authentication.
55 * @param token yuzu token to use for authentication. 54 * @param token yuzu token to use for authentication.
56 * @param func A function that gets exectued when the verification is finished
57 * @returns Future with bool indicating whether the verification succeeded 55 * @returns Future with bool indicating whether the verification succeeded
58 */ 56 */
59bool VerifyLogin(const std::string& username, const std::string& token); 57bool VerifyLogin(const std::string& username, const std::string& token);
diff --git a/src/tests/core/arm/arm_test_common.cpp b/src/tests/core/arm/arm_test_common.cpp
index c0a57e71f..37e15bad0 100644
--- a/src/tests/core/arm/arm_test_common.cpp
+++ b/src/tests/core/arm/arm_test_common.cpp
@@ -15,7 +15,8 @@ namespace ArmTests {
15TestEnvironment::TestEnvironment(bool mutable_memory_) 15TestEnvironment::TestEnvironment(bool mutable_memory_)
16 : mutable_memory(mutable_memory_), test_memory(std::make_shared<TestMemory>(this)) { 16 : mutable_memory(mutable_memory_), test_memory(std::make_shared<TestMemory>(this)) {
17 17
18 Core::CurrentProcess() = Kernel::Process::Create(kernel, ""); 18 auto process = Kernel::Process::Create(kernel, "");
19 kernel.MakeCurrentProcess(process.get());
19 page_table = &Core::CurrentProcess()->VMManager().page_table; 20 page_table = &Core::CurrentProcess()->VMManager().page_table;
20 21
21 std::fill(page_table->pointers.begin(), page_table->pointers.end(), nullptr); 22 std::fill(page_table->pointers.begin(), page_table->pointers.end(), nullptr);
diff --git a/src/video_core/engines/shader_bytecode.h b/src/video_core/engines/shader_bytecode.h
index b1f137b9c..550ab1148 100644
--- a/src/video_core/engines/shader_bytecode.h
+++ b/src/video_core/engines/shader_bytecode.h
@@ -314,6 +314,15 @@ enum class TextureMiscMode : u64 {
314 PTP, 314 PTP,
315}; 315};
316 316
317enum class IsberdMode : u64 {
318 None = 0,
319 Patch = 1,
320 Prim = 2,
321 Attr = 3,
322};
323
324enum class IsberdShift : u64 { None = 0, U16 = 1, B32 = 2 };
325
317enum class IpaInterpMode : u64 { 326enum class IpaInterpMode : u64 {
318 Linear = 0, 327 Linear = 0,
319 Perspective = 1, 328 Perspective = 1,
@@ -340,6 +349,87 @@ struct IpaMode {
340 } 349 }
341}; 350};
342 351
352enum class SystemVariable : u64 {
353 LaneId = 0x00,
354 VirtCfg = 0x02,
355 VirtId = 0x03,
356 Pm0 = 0x04,
357 Pm1 = 0x05,
358 Pm2 = 0x06,
359 Pm3 = 0x07,
360 Pm4 = 0x08,
361 Pm5 = 0x09,
362 Pm6 = 0x0a,
363 Pm7 = 0x0b,
364 OrderingTicket = 0x0f,
365 PrimType = 0x10,
366 InvocationId = 0x11,
367 Ydirection = 0x12,
368 ThreadKill = 0x13,
369 ShaderType = 0x14,
370 DirectBeWriteAddressLow = 0x15,
371 DirectBeWriteAddressHigh = 0x16,
372 DirectBeWriteEnabled = 0x17,
373 MachineId0 = 0x18,
374 MachineId1 = 0x19,
375 MachineId2 = 0x1a,
376 MachineId3 = 0x1b,
377 Affinity = 0x1c,
378 InvocationInfo = 0x1d,
379 WscaleFactorXY = 0x1e,
380 WscaleFactorZ = 0x1f,
381 Tid = 0x20,
382 TidX = 0x21,
383 TidY = 0x22,
384 TidZ = 0x23,
385 CtaParam = 0x24,
386 CtaIdX = 0x25,
387 CtaIdY = 0x26,
388 CtaIdZ = 0x27,
389 NtId = 0x28,
390 CirQueueIncrMinusOne = 0x29,
391 Nlatc = 0x2a,
392 SmSpaVersion = 0x2c,
393 MultiPassShaderInfo = 0x2d,
394 LwinHi = 0x2e,
395 SwinHi = 0x2f,
396 SwinLo = 0x30,
397 SwinSz = 0x31,
398 SmemSz = 0x32,
399 SmemBanks = 0x33,
400 LwinLo = 0x34,
401 LwinSz = 0x35,
402 LmemLosz = 0x36,
403 LmemHioff = 0x37,
404 EqMask = 0x38,
405 LtMask = 0x39,
406 LeMask = 0x3a,
407 GtMask = 0x3b,
408 GeMask = 0x3c,
409 RegAlloc = 0x3d,
410 CtxAddr = 0x3e, // .fmask = F_SM50
411 BarrierAlloc = 0x3e, // .fmask = F_SM60
412 GlobalErrorStatus = 0x40,
413 WarpErrorStatus = 0x42,
414 WarpErrorStatusClear = 0x43,
415 PmHi0 = 0x48,
416 PmHi1 = 0x49,
417 PmHi2 = 0x4a,
418 PmHi3 = 0x4b,
419 PmHi4 = 0x4c,
420 PmHi5 = 0x4d,
421 PmHi6 = 0x4e,
422 PmHi7 = 0x4f,
423 ClockLo = 0x50,
424 ClockHi = 0x51,
425 GlobalTimerLo = 0x52,
426 GlobalTimerHi = 0x53,
427 HwTaskId = 0x60,
428 CircularQueueEntryIndex = 0x61,
429 CircularQueueEntryAddressLow = 0x62,
430 CircularQueueEntryAddressHigh = 0x63,
431};
432
343union Instruction { 433union Instruction {
344 Instruction& operator=(const Instruction& instr) { 434 Instruction& operator=(const Instruction& instr) {
345 value = instr.value; 435 value = instr.value;
@@ -915,6 +1005,18 @@ union Instruction {
915 } bra; 1005 } bra;
916 1006
917 union { 1007 union {
1008 BitField<39, 1, u64> emit; // EmitVertex
1009 BitField<40, 1, u64> cut; // EndPrimitive
1010 } out;
1011
1012 union {
1013 BitField<31, 1, u64> skew;
1014 BitField<32, 1, u64> o;
1015 BitField<33, 2, IsberdMode> mode;
1016 BitField<47, 2, IsberdShift> shift;
1017 } isberd;
1018
1019 union {
918 BitField<20, 16, u64> imm20_16; 1020 BitField<20, 16, u64> imm20_16;
919 BitField<36, 1, u64> product_shift_left; 1021 BitField<36, 1, u64> product_shift_left;
920 BitField<37, 1, u64> merge_37; 1022 BitField<37, 1, u64> merge_37;
@@ -936,6 +1038,10 @@ union Instruction {
936 BitField<36, 5, u64> index; 1038 BitField<36, 5, u64> index;
937 } cbuf36; 1039 } cbuf36;
938 1040
1041 // Unsure about the size of this one.
1042 // It's always used with a gpr0, so any size should be fine.
1043 BitField<20, 8, SystemVariable> sys20;
1044
939 BitField<47, 1, u64> generates_cc; 1045 BitField<47, 1, u64> generates_cc;
940 BitField<61, 1, u64> is_b_imm; 1046 BitField<61, 1, u64> is_b_imm;
941 BitField<60, 1, u64> is_b_gpr; 1047 BitField<60, 1, u64> is_b_gpr;
@@ -975,6 +1081,8 @@ public:
975 TMML, // Texture Mip Map Level 1081 TMML, // Texture Mip Map Level
976 EXIT, 1082 EXIT,
977 IPA, 1083 IPA,
1084 OUT_R, // Emit vertex/primitive
1085 ISBERD,
978 FFMA_IMM, // Fused Multiply and Add 1086 FFMA_IMM, // Fused Multiply and Add
979 FFMA_CR, 1087 FFMA_CR,
980 FFMA_RC, 1088 FFMA_RC,
@@ -1034,6 +1142,7 @@ public:
1034 MOV_C, 1142 MOV_C,
1035 MOV_R, 1143 MOV_R,
1036 MOV_IMM, 1144 MOV_IMM,
1145 MOV_SYS,
1037 MOV32_IMM, 1146 MOV32_IMM,
1038 SHL_C, 1147 SHL_C,
1039 SHL_R, 1148 SHL_R,
@@ -1209,6 +1318,8 @@ private:
1209 INST("1101111101011---", Id::TMML, Type::Memory, "TMML"), 1318 INST("1101111101011---", Id::TMML, Type::Memory, "TMML"),
1210 INST("111000110000----", Id::EXIT, Type::Trivial, "EXIT"), 1319 INST("111000110000----", Id::EXIT, Type::Trivial, "EXIT"),
1211 INST("11100000--------", Id::IPA, Type::Trivial, "IPA"), 1320 INST("11100000--------", Id::IPA, Type::Trivial, "IPA"),
1321 INST("1111101111100---", Id::OUT_R, Type::Trivial, "OUT_R"),
1322 INST("1110111111010---", Id::ISBERD, Type::Trivial, "ISBERD"),
1212 INST("0011001-1-------", Id::FFMA_IMM, Type::Ffma, "FFMA_IMM"), 1323 INST("0011001-1-------", Id::FFMA_IMM, Type::Ffma, "FFMA_IMM"),
1213 INST("010010011-------", Id::FFMA_CR, Type::Ffma, "FFMA_CR"), 1324 INST("010010011-------", Id::FFMA_CR, Type::Ffma, "FFMA_CR"),
1214 INST("010100011-------", Id::FFMA_RC, Type::Ffma, "FFMA_RC"), 1325 INST("010100011-------", Id::FFMA_RC, Type::Ffma, "FFMA_RC"),
@@ -1255,6 +1366,7 @@ private:
1255 INST("0100110010011---", Id::MOV_C, Type::Arithmetic, "MOV_C"), 1366 INST("0100110010011---", Id::MOV_C, Type::Arithmetic, "MOV_C"),
1256 INST("0101110010011---", Id::MOV_R, Type::Arithmetic, "MOV_R"), 1367 INST("0101110010011---", Id::MOV_R, Type::Arithmetic, "MOV_R"),
1257 INST("0011100-10011---", Id::MOV_IMM, Type::Arithmetic, "MOV_IMM"), 1368 INST("0011100-10011---", Id::MOV_IMM, Type::Arithmetic, "MOV_IMM"),
1369 INST("1111000011001---", Id::MOV_SYS, Type::Trivial, "MOV_SYS"),
1258 INST("000000010000----", Id::MOV32_IMM, Type::ArithmeticImmediate, "MOV32_IMM"), 1370 INST("000000010000----", Id::MOV32_IMM, Type::ArithmeticImmediate, "MOV32_IMM"),
1259 INST("0100110001100---", Id::FMNMX_C, Type::Arithmetic, "FMNMX_C"), 1371 INST("0100110001100---", Id::FMNMX_C, Type::Arithmetic, "FMNMX_C"),
1260 INST("0101110001100---", Id::FMNMX_R, Type::Arithmetic, "FMNMX_R"), 1372 INST("0101110001100---", Id::FMNMX_R, Type::Arithmetic, "FMNMX_R"),
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index daae67121..84582c777 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -255,7 +255,7 @@ DrawParameters RasterizerOpenGL::SetupDraw() {
255 return params; 255 return params;
256} 256}
257 257
258void RasterizerOpenGL::SetupShaders() { 258void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
259 MICROPROFILE_SCOPE(OpenGL_Shader); 259 MICROPROFILE_SCOPE(OpenGL_Shader);
260 const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D(); 260 const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
261 261
@@ -270,6 +270,11 @@ void RasterizerOpenGL::SetupShaders() {
270 270
271 // Skip stages that are not enabled 271 // Skip stages that are not enabled
272 if (!gpu.regs.IsShaderConfigEnabled(index)) { 272 if (!gpu.regs.IsShaderConfigEnabled(index)) {
273 switch (program) {
274 case Maxwell::ShaderProgram::Geometry:
275 shader_program_manager->UseTrivialGeometryShader();
276 break;
277 }
273 continue; 278 continue;
274 } 279 }
275 280
@@ -288,11 +293,18 @@ void RasterizerOpenGL::SetupShaders() {
288 switch (program) { 293 switch (program) {
289 case Maxwell::ShaderProgram::VertexA: 294 case Maxwell::ShaderProgram::VertexA:
290 case Maxwell::ShaderProgram::VertexB: { 295 case Maxwell::ShaderProgram::VertexB: {
291 shader_program_manager->UseProgrammableVertexShader(shader->GetProgramHandle()); 296 shader_program_manager->UseProgrammableVertexShader(
297 shader->GetProgramHandle(primitive_mode));
298 break;
299 }
300 case Maxwell::ShaderProgram::Geometry: {
301 shader_program_manager->UseProgrammableGeometryShader(
302 shader->GetProgramHandle(primitive_mode));
292 break; 303 break;
293 } 304 }
294 case Maxwell::ShaderProgram::Fragment: { 305 case Maxwell::ShaderProgram::Fragment: {
295 shader_program_manager->UseProgrammableFragmentShader(shader->GetProgramHandle()); 306 shader_program_manager->UseProgrammableFragmentShader(
307 shader->GetProgramHandle(primitive_mode));
296 break; 308 break;
297 } 309 }
298 default: 310 default:
@@ -302,12 +314,13 @@ void RasterizerOpenGL::SetupShaders() {
302 } 314 }
303 315
304 // Configure the const buffers for this shader stage. 316 // Configure the const buffers for this shader stage.
305 current_constbuffer_bindpoint = SetupConstBuffers(static_cast<Maxwell::ShaderStage>(stage), 317 current_constbuffer_bindpoint =
306 shader, current_constbuffer_bindpoint); 318 SetupConstBuffers(static_cast<Maxwell::ShaderStage>(stage), shader, primitive_mode,
319 current_constbuffer_bindpoint);
307 320
308 // Configure the textures for this shader stage. 321 // Configure the textures for this shader stage.
309 current_texture_bindpoint = SetupTextures(static_cast<Maxwell::ShaderStage>(stage), shader, 322 current_texture_bindpoint = SetupTextures(static_cast<Maxwell::ShaderStage>(stage), shader,
310 current_texture_bindpoint); 323 primitive_mode, current_texture_bindpoint);
311 324
312 // When VertexA is enabled, we have dual vertex shaders 325 // When VertexA is enabled, we have dual vertex shaders
313 if (program == Maxwell::ShaderProgram::VertexA) { 326 if (program == Maxwell::ShaderProgram::VertexA) {
@@ -317,8 +330,6 @@ void RasterizerOpenGL::SetupShaders() {
317 } 330 }
318 331
319 state.Apply(); 332 state.Apply();
320
321 shader_program_manager->UseTrivialGeometryShader();
322} 333}
323 334
324std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const { 335std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
@@ -581,7 +592,7 @@ void RasterizerOpenGL::DrawArrays() {
581 592
582 SetupVertexArrays(); 593 SetupVertexArrays();
583 DrawParameters params = SetupDraw(); 594 DrawParameters params = SetupDraw();
584 SetupShaders(); 595 SetupShaders(params.primitive_mode);
585 596
586 buffer_cache.Unmap(); 597 buffer_cache.Unmap();
587 598
@@ -720,7 +731,7 @@ void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntr
720} 731}
721 732
722u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader, 733u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
723 u32 current_bindpoint) { 734 GLenum primitive_mode, u32 current_bindpoint) {
724 MICROPROFILE_SCOPE(OpenGL_UBO); 735 MICROPROFILE_SCOPE(OpenGL_UBO);
725 const auto& gpu = Core::System::GetInstance().GPU(); 736 const auto& gpu = Core::System::GetInstance().GPU();
726 const auto& maxwell3d = gpu.Maxwell3D(); 737 const auto& maxwell3d = gpu.Maxwell3D();
@@ -772,7 +783,7 @@ u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shad
772 buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment)); 783 buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
773 784
774 // Now configure the bindpoint of the buffer inside the shader 785 // Now configure the bindpoint of the buffer inside the shader
775 glUniformBlockBinding(shader->GetProgramHandle(), 786 glUniformBlockBinding(shader->GetProgramHandle(primitive_mode),
776 shader->GetProgramResourceIndex(used_buffer), 787 shader->GetProgramResourceIndex(used_buffer),
777 current_bindpoint + bindpoint); 788 current_bindpoint + bindpoint);
778 789
@@ -788,7 +799,8 @@ u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shad
788 return current_bindpoint + static_cast<u32>(entries.size()); 799 return current_bindpoint + static_cast<u32>(entries.size());
789} 800}
790 801
791u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader, u32 current_unit) { 802u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
803 GLenum primitive_mode, u32 current_unit) {
792 MICROPROFILE_SCOPE(OpenGL_Texture); 804 MICROPROFILE_SCOPE(OpenGL_Texture);
793 const auto& gpu = Core::System::GetInstance().GPU(); 805 const auto& gpu = Core::System::GetInstance().GPU();
794 const auto& maxwell3d = gpu.Maxwell3D(); 806 const auto& maxwell3d = gpu.Maxwell3D();
@@ -803,8 +815,8 @@ u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
803 815
804 // Bind the uniform to the sampler. 816 // Bind the uniform to the sampler.
805 817
806 glProgramUniform1i(shader->GetProgramHandle(), shader->GetUniformLocation(entry), 818 glProgramUniform1i(shader->GetProgramHandle(primitive_mode),
807 current_bindpoint); 819 shader->GetUniformLocation(entry), current_bindpoint);
808 820
809 const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset()); 821 const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
810 822
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index 2395e0a7a..b1f7ccc7e 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -120,7 +120,7 @@ private:
120 * @returns The next available bindpoint for use in the next shader stage. 120 * @returns The next available bindpoint for use in the next shader stage.
121 */ 121 */
122 u32 SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader, 122 u32 SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader,
123 u32 current_bindpoint); 123 GLenum primitive_mode, u32 current_bindpoint);
124 124
125 /* 125 /*
126 * Configures the current textures to use for the draw command. 126 * Configures the current textures to use for the draw command.
@@ -130,7 +130,7 @@ private:
130 * @returns The next available bindpoint for use in the next shader stage. 130 * @returns The next available bindpoint for use in the next shader stage.
131 */ 131 */
132 u32 SetupTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader, 132 u32 SetupTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader,
133 u32 current_unit); 133 GLenum primitive_mode, u32 current_unit);
134 134
135 /// Syncs the viewport to match the guest state 135 /// Syncs the viewport to match the guest state
136 void SyncViewport(); 136 void SyncViewport();
@@ -210,7 +210,7 @@ private:
210 210
211 DrawParameters SetupDraw(); 211 DrawParameters SetupDraw();
212 212
213 void SetupShaders(); 213 void SetupShaders(GLenum primitive_mode);
214 214
215 enum class AccelDraw { Disabled, Arrays, Indexed }; 215 enum class AccelDraw { Disabled, Arrays, Indexed };
216 AccelDraw accelerate_draw = AccelDraw::Disabled; 216 AccelDraw accelerate_draw = AccelDraw::Disabled;
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.cpp b/src/video_core/renderer_opengl/gl_shader_cache.cpp
index 7cd8f91e4..1a03a677f 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_cache.cpp
@@ -68,6 +68,10 @@ CachedShader::CachedShader(VAddr addr, Maxwell::ShaderProgram program_type)
68 program_result = GLShader::GenerateVertexShader(setup); 68 program_result = GLShader::GenerateVertexShader(setup);
69 gl_type = GL_VERTEX_SHADER; 69 gl_type = GL_VERTEX_SHADER;
70 break; 70 break;
71 case Maxwell::ShaderProgram::Geometry:
72 program_result = GLShader::GenerateGeometryShader(setup);
73 gl_type = GL_GEOMETRY_SHADER;
74 break;
71 case Maxwell::ShaderProgram::Fragment: 75 case Maxwell::ShaderProgram::Fragment:
72 program_result = GLShader::GenerateFragmentShader(setup); 76 program_result = GLShader::GenerateFragmentShader(setup);
73 gl_type = GL_FRAGMENT_SHADER; 77 gl_type = GL_FRAGMENT_SHADER;
@@ -80,11 +84,16 @@ CachedShader::CachedShader(VAddr addr, Maxwell::ShaderProgram program_type)
80 84
81 entries = program_result.second; 85 entries = program_result.second;
82 86
83 OGLShader shader; 87 if (program_type != Maxwell::ShaderProgram::Geometry) {
84 shader.Create(program_result.first.c_str(), gl_type); 88 OGLShader shader;
85 program.Create(true, shader.handle); 89 shader.Create(program_result.first.c_str(), gl_type);
86 SetShaderUniformBlockBindings(program.handle); 90 program.Create(true, shader.handle);
87 VideoCore::LabelGLObject(GL_PROGRAM, program.handle, addr); 91 SetShaderUniformBlockBindings(program.handle);
92 VideoCore::LabelGLObject(GL_PROGRAM, program.handle, addr);
93 } else {
94 // Store shader's code to lazily build it on draw
95 geometry_programs.code = program_result.first;
96 }
88} 97}
89 98
90GLuint CachedShader::GetProgramResourceIndex(const GLShader::ConstBufferEntry& buffer) { 99GLuint CachedShader::GetProgramResourceIndex(const GLShader::ConstBufferEntry& buffer) {
@@ -110,6 +119,21 @@ GLint CachedShader::GetUniformLocation(const GLShader::SamplerEntry& sampler) {
110 return search->second; 119 return search->second;
111} 120}
112 121
122GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program,
123 const std::string& glsl_topology,
124 const std::string& debug_name) {
125 if (target_program.handle != 0) {
126 return target_program.handle;
127 }
128 const std::string source{geometry_programs.code + "layout (" + glsl_topology + ") in;\n"};
129 OGLShader shader;
130 shader.Create(source.c_str(), GL_GEOMETRY_SHADER);
131 target_program.Create(true, shader.handle);
132 SetShaderUniformBlockBindings(target_program.handle);
133 VideoCore::LabelGLObject(GL_PROGRAM, target_program.handle, addr, debug_name);
134 return target_program.handle;
135};
136
113Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) { 137Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) {
114 const VAddr program_addr{GetShaderAddress(program)}; 138 const VAddr program_addr{GetShaderAddress(program)};
115 139
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.h b/src/video_core/renderer_opengl/gl_shader_cache.h
index 9bafe43a9..7bb287f56 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.h
+++ b/src/video_core/renderer_opengl/gl_shader_cache.h
@@ -7,6 +7,7 @@
7#include <map> 7#include <map>
8#include <memory> 8#include <memory>
9 9
10#include "common/assert.h"
10#include "common/common_types.h" 11#include "common/common_types.h"
11#include "video_core/rasterizer_cache.h" 12#include "video_core/rasterizer_cache.h"
12#include "video_core/renderer_opengl/gl_resource_manager.h" 13#include "video_core/renderer_opengl/gl_resource_manager.h"
@@ -38,8 +39,31 @@ public:
38 } 39 }
39 40
40 /// Gets the GL program handle for the shader 41 /// Gets the GL program handle for the shader
41 GLuint GetProgramHandle() const { 42 GLuint GetProgramHandle(GLenum primitive_mode) {
42 return program.handle; 43 if (program_type != Maxwell::ShaderProgram::Geometry) {
44 return program.handle;
45 }
46 switch (primitive_mode) {
47 case GL_POINTS:
48 return LazyGeometryProgram(geometry_programs.points, "points", "ShaderPoints");
49 case GL_LINES:
50 case GL_LINE_STRIP:
51 return LazyGeometryProgram(geometry_programs.lines, "lines", "ShaderLines");
52 case GL_LINES_ADJACENCY:
53 case GL_LINE_STRIP_ADJACENCY:
54 return LazyGeometryProgram(geometry_programs.lines_adjacency, "lines_adjacency",
55 "ShaderLinesAdjacency");
56 case GL_TRIANGLES:
57 case GL_TRIANGLE_STRIP:
58 case GL_TRIANGLE_FAN:
59 return LazyGeometryProgram(geometry_programs.triangles, "triangles", "ShaderTriangles");
60 case GL_TRIANGLES_ADJACENCY:
61 case GL_TRIANGLE_STRIP_ADJACENCY:
62 return LazyGeometryProgram(geometry_programs.triangles_adjacency, "triangles_adjacency",
63 "ShaderLines");
64 default:
65 UNREACHABLE_MSG("Unknown primitive mode.");
66 }
43 } 67 }
44 68
45 /// Gets the GL program resource location for the specified resource, caching as needed 69 /// Gets the GL program resource location for the specified resource, caching as needed
@@ -49,12 +73,30 @@ public:
49 GLint GetUniformLocation(const GLShader::SamplerEntry& sampler); 73 GLint GetUniformLocation(const GLShader::SamplerEntry& sampler);
50 74
51private: 75private:
76 /// Generates a geometry shader or returns one that already exists.
77 GLuint LazyGeometryProgram(OGLProgram& target_program, const std::string& glsl_topology,
78 const std::string& debug_name);
79
52 VAddr addr; 80 VAddr addr;
53 Maxwell::ShaderProgram program_type; 81 Maxwell::ShaderProgram program_type;
54 GLShader::ShaderSetup setup; 82 GLShader::ShaderSetup setup;
55 GLShader::ShaderEntries entries; 83 GLShader::ShaderEntries entries;
84
85 // Non-geometry program.
56 OGLProgram program; 86 OGLProgram program;
57 87
88 // Geometry programs. These are needed because GLSL needs an input topology but it's not
89 // declared by the hardware. Workaround this issue by generating a different shader per input
90 // topology class.
91 struct {
92 std::string code;
93 OGLProgram points;
94 OGLProgram lines;
95 OGLProgram lines_adjacency;
96 OGLProgram triangles;
97 OGLProgram triangles_adjacency;
98 } geometry_programs;
99
58 std::map<u32, GLuint> resource_cache; 100 std::map<u32, GLuint> resource_cache;
59 std::map<u32, GLint> uniform_cache; 101 std::map<u32, GLint> uniform_cache;
60}; 102};
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
index 7e57de78a..c82a0dcfa 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
@@ -7,6 +7,7 @@
7#include <string> 7#include <string>
8#include <string_view> 8#include <string_view>
9 9
10#include <boost/optional.hpp>
10#include <fmt/format.h> 11#include <fmt/format.h>
11 12
12#include "common/assert.h" 13#include "common/assert.h"
@@ -29,11 +30,32 @@ using Tegra::Shader::SubOp;
29constexpr u32 PROGRAM_END = MAX_PROGRAM_CODE_LENGTH; 30constexpr u32 PROGRAM_END = MAX_PROGRAM_CODE_LENGTH;
30constexpr u32 PROGRAM_HEADER_SIZE = sizeof(Tegra::Shader::Header); 31constexpr u32 PROGRAM_HEADER_SIZE = sizeof(Tegra::Shader::Header);
31 32
33enum : u32 { POSITION_VARYING_LOCATION = 0, GENERIC_VARYING_START_LOCATION = 1 };
34
35constexpr u32 MAX_GEOMETRY_BUFFERS = 6;
36constexpr u32 MAX_ATTRIBUTES = 0x100; // Size in vec4s, this value is untested
37
32class DecompileFail : public std::runtime_error { 38class DecompileFail : public std::runtime_error {
33public: 39public:
34 using std::runtime_error::runtime_error; 40 using std::runtime_error::runtime_error;
35}; 41};
36 42
43/// Translate topology
44static std::string GetTopologyName(Tegra::Shader::OutputTopology topology) {
45 switch (topology) {
46 case Tegra::Shader::OutputTopology::PointList:
47 return "points";
48 case Tegra::Shader::OutputTopology::LineStrip:
49 return "line_strip";
50 case Tegra::Shader::OutputTopology::TriangleStrip:
51 return "triangle_strip";
52 default:
53 LOG_CRITICAL(Render_OpenGL, "Unknown output topology {}", static_cast<u32>(topology));
54 UNREACHABLE();
55 return "points";
56 }
57}
58
37/// Describes the behaviour of code path of a given entry point and a return point. 59/// Describes the behaviour of code path of a given entry point and a return point.
38enum class ExitMethod { 60enum class ExitMethod {
39 Undetermined, ///< Internal value. Only occur when analyzing JMP loop. 61 Undetermined, ///< Internal value. Only occur when analyzing JMP loop.
@@ -253,8 +275,9 @@ enum class InternalFlag : u64 {
253class GLSLRegisterManager { 275class GLSLRegisterManager {
254public: 276public:
255 GLSLRegisterManager(ShaderWriter& shader, ShaderWriter& declarations, 277 GLSLRegisterManager(ShaderWriter& shader, ShaderWriter& declarations,
256 const Maxwell3D::Regs::ShaderStage& stage, const std::string& suffix) 278 const Maxwell3D::Regs::ShaderStage& stage, const std::string& suffix,
257 : shader{shader}, declarations{declarations}, stage{stage}, suffix{suffix} { 279 const Tegra::Shader::Header& header)
280 : shader{shader}, declarations{declarations}, stage{stage}, suffix{suffix}, header{header} {
258 BuildRegisterList(); 281 BuildRegisterList();
259 BuildInputList(); 282 BuildInputList();
260 } 283 }
@@ -358,11 +381,13 @@ public:
358 * @param reg The destination register to use. 381 * @param reg The destination register to use.
359 * @param elem The element to use for the operation. 382 * @param elem The element to use for the operation.
360 * @param attribute The input attribute to use as the source value. 383 * @param attribute The input attribute to use as the source value.
384 * @param vertex The register that decides which vertex to read from (used in GS).
361 */ 385 */
362 void SetRegisterToInputAttibute(const Register& reg, u64 elem, Attribute::Index attribute, 386 void SetRegisterToInputAttibute(const Register& reg, u64 elem, Attribute::Index attribute,
363 const Tegra::Shader::IpaMode& input_mode) { 387 const Tegra::Shader::IpaMode& input_mode,
388 boost::optional<Register> vertex = {}) {
364 const std::string dest = GetRegisterAsFloat(reg); 389 const std::string dest = GetRegisterAsFloat(reg);
365 const std::string src = GetInputAttribute(attribute, input_mode) + GetSwizzle(elem); 390 const std::string src = GetInputAttribute(attribute, input_mode, vertex) + GetSwizzle(elem);
366 shader.AddLine(dest + " = " + src + ';'); 391 shader.AddLine(dest + " = " + src + ';');
367 } 392 }
368 393
@@ -391,16 +416,29 @@ public:
391 * are stored as floats, so this may require conversion. 416 * are stored as floats, so this may require conversion.
392 * @param attribute The destination output attribute. 417 * @param attribute The destination output attribute.
393 * @param elem The element to use for the operation. 418 * @param elem The element to use for the operation.
394 * @param reg The register to use as the source value. 419 * @param val_reg The register to use as the source value.
420 * @param buf_reg The register that tells which buffer to write to (used in geometry shaders).
395 */ 421 */
396 void SetOutputAttributeToRegister(Attribute::Index attribute, u64 elem, const Register& reg) { 422 void SetOutputAttributeToRegister(Attribute::Index attribute, u64 elem, const Register& val_reg,
423 const Register& buf_reg) {
397 const std::string dest = GetOutputAttribute(attribute); 424 const std::string dest = GetOutputAttribute(attribute);
398 const std::string src = GetRegisterAsFloat(reg); 425 const std::string src = GetRegisterAsFloat(val_reg);
399 426
400 if (!dest.empty()) { 427 if (!dest.empty()) {
401 // Can happen with unknown/unimplemented output attributes, in which case we ignore the 428 // Can happen with unknown/unimplemented output attributes, in which case we ignore the
402 // instruction for now. 429 // instruction for now.
403 shader.AddLine(dest + GetSwizzle(elem) + " = " + src + ';'); 430 if (stage == Maxwell3D::Regs::ShaderStage::Geometry) {
431 // TODO(Rodrigo): nouveau sets some attributes after setting emitting a geometry
432 // shader. These instructions use a dirty register as buffer index. To avoid some
433 // drivers from complaining for the out of boundary writes, guard them.
434 const std::string buf_index{"min(" + GetRegisterAsInteger(buf_reg) + ", " +
435 std::to_string(MAX_GEOMETRY_BUFFERS - 1) + ')'};
436 shader.AddLine("amem[" + buf_index + "][" +
437 std::to_string(static_cast<u32>(attribute)) + ']' +
438 GetSwizzle(elem) + " = " + src + ';');
439 } else {
440 shader.AddLine(dest + GetSwizzle(elem) + " = " + src + ';');
441 }
404 } 442 }
405 } 443 }
406 444
@@ -441,41 +479,123 @@ public:
441 } 479 }
442 } 480 }
443 481
444 /// Add declarations for registers 482 /// Add declarations.
445 void GenerateDeclarations(const std::string& suffix) { 483 void GenerateDeclarations(const std::string& suffix) {
484 GenerateRegisters(suffix);
485 GenerateInternalFlags();
486 GenerateInputAttrs();
487 GenerateOutputAttrs();
488 GenerateConstBuffers();
489 GenerateSamplers();
490 GenerateGeometry();
491 }
492
493 /// Returns a list of constant buffer declarations.
494 std::vector<ConstBufferEntry> GetConstBuffersDeclarations() const {
495 std::vector<ConstBufferEntry> result;
496 std::copy_if(declr_const_buffers.begin(), declr_const_buffers.end(),
497 std::back_inserter(result), [](const auto& entry) { return entry.IsUsed(); });
498 return result;
499 }
500
501 /// Returns a list of samplers used in the shader.
502 const std::vector<SamplerEntry>& GetSamplers() const {
503 return used_samplers;
504 }
505
506 /// Returns the GLSL sampler used for the input shader sampler, and creates a new one if
507 /// necessary.
508 std::string AccessSampler(const Sampler& sampler, Tegra::Shader::TextureType type,
509 bool is_array, bool is_shadow) {
510 const auto offset = static_cast<std::size_t>(sampler.index.Value());
511
512 // If this sampler has already been used, return the existing mapping.
513 const auto itr =
514 std::find_if(used_samplers.begin(), used_samplers.end(),
515 [&](const SamplerEntry& entry) { return entry.GetOffset() == offset; });
516
517 if (itr != used_samplers.end()) {
518 ASSERT(itr->GetType() == type && itr->IsArray() == is_array &&
519 itr->IsShadow() == is_shadow);
520 return itr->GetName();
521 }
522
523 // Otherwise create a new mapping for this sampler
524 const std::size_t next_index = used_samplers.size();
525 const SamplerEntry entry{stage, offset, next_index, type, is_array, is_shadow};
526 used_samplers.emplace_back(entry);
527 return entry.GetName();
528 }
529
530private:
531 /// Generates declarations for registers.
532 void GenerateRegisters(const std::string& suffix) {
446 for (const auto& reg : regs) { 533 for (const auto& reg : regs) {
447 declarations.AddLine(GLSLRegister::GetTypeString() + ' ' + reg.GetPrefixString() + 534 declarations.AddLine(GLSLRegister::GetTypeString() + ' ' + reg.GetPrefixString() +
448 std::to_string(reg.GetIndex()) + '_' + suffix + " = 0;"); 535 std::to_string(reg.GetIndex()) + '_' + suffix + " = 0;");
449 } 536 }
450 declarations.AddNewLine(); 537 declarations.AddNewLine();
538 }
451 539
540 /// Generates declarations for internal flags.
541 void GenerateInternalFlags() {
452 for (u32 ii = 0; ii < static_cast<u64>(InternalFlag::Amount); ii++) { 542 for (u32 ii = 0; ii < static_cast<u64>(InternalFlag::Amount); ii++) {
453 const InternalFlag code = static_cast<InternalFlag>(ii); 543 const InternalFlag code = static_cast<InternalFlag>(ii);
454 declarations.AddLine("bool " + GetInternalFlag(code) + " = false;"); 544 declarations.AddLine("bool " + GetInternalFlag(code) + " = false;");
455 } 545 }
456 declarations.AddNewLine(); 546 declarations.AddNewLine();
547 }
548
549 /// Generates declarations for input attributes.
550 void GenerateInputAttrs() {
551 if (stage != Maxwell3D::Regs::ShaderStage::Vertex) {
552 const std::string attr =
553 stage == Maxwell3D::Regs::ShaderStage::Geometry ? "gs_position[]" : "position";
554 declarations.AddLine("layout (location = " + std::to_string(POSITION_VARYING_LOCATION) +
555 ") in vec4 " + attr + ';');
556 }
457 557
458 for (const auto element : declr_input_attribute) { 558 for (const auto element : declr_input_attribute) {
459 // TODO(bunnei): Use proper number of elements for these 559 // TODO(bunnei): Use proper number of elements for these
460 u32 idx = 560 u32 idx =
461 static_cast<u32>(element.first) - static_cast<u32>(Attribute::Index::Attribute_0); 561 static_cast<u32>(element.first) - static_cast<u32>(Attribute::Index::Attribute_0);
462 declarations.AddLine("layout(location = " + std::to_string(idx) + ")" + 562 if (stage != Maxwell3D::Regs::ShaderStage::Vertex) {
463 GetInputFlags(element.first) + "in vec4 " + 563 // If inputs are varyings, add an offset
464 GetInputAttribute(element.first, element.second) + ';'); 564 idx += GENERIC_VARYING_START_LOCATION;
565 }
566
567 std::string attr{GetInputAttribute(element.first, element.second)};
568 if (stage == Maxwell3D::Regs::ShaderStage::Geometry) {
569 attr = "gs_" + attr + "[]";
570 }
571 declarations.AddLine("layout (location = " + std::to_string(idx) + ") " +
572 GetInputFlags(element.first) + "in vec4 " + attr + ';');
465 } 573 }
574
466 declarations.AddNewLine(); 575 declarations.AddNewLine();
576 }
467 577
578 /// Generates declarations for output attributes.
579 void GenerateOutputAttrs() {
580 if (stage != Maxwell3D::Regs::ShaderStage::Fragment) {
581 declarations.AddLine("layout (location = " + std::to_string(POSITION_VARYING_LOCATION) +
582 ") out vec4 position;");
583 }
468 for (const auto& index : declr_output_attribute) { 584 for (const auto& index : declr_output_attribute) {
469 // TODO(bunnei): Use proper number of elements for these 585 // TODO(bunnei): Use proper number of elements for these
470 declarations.AddLine("layout(location = " + 586 const u32 idx = static_cast<u32>(index) -
471 std::to_string(static_cast<u32>(index) - 587 static_cast<u32>(Attribute::Index::Attribute_0) +
472 static_cast<u32>(Attribute::Index::Attribute_0)) + 588 GENERIC_VARYING_START_LOCATION;
473 ") out vec4 " + GetOutputAttribute(index) + ';'); 589 declarations.AddLine("layout (location = " + std::to_string(idx) + ") out vec4 " +
590 GetOutputAttribute(index) + ';');
474 } 591 }
475 declarations.AddNewLine(); 592 declarations.AddNewLine();
593 }
476 594
595 /// Generates declarations for constant buffers.
596 void GenerateConstBuffers() {
477 for (const auto& entry : GetConstBuffersDeclarations()) { 597 for (const auto& entry : GetConstBuffersDeclarations()) {
478 declarations.AddLine("layout(std140) uniform " + entry.GetName()); 598 declarations.AddLine("layout (std140) uniform " + entry.GetName());
479 declarations.AddLine('{'); 599 declarations.AddLine('{');
480 declarations.AddLine(" vec4 c" + std::to_string(entry.GetIndex()) + 600 declarations.AddLine(" vec4 c" + std::to_string(entry.GetIndex()) +
481 "[MAX_CONSTBUFFER_ELEMENTS];"); 601 "[MAX_CONSTBUFFER_ELEMENTS];");
@@ -483,7 +603,10 @@ public:
483 declarations.AddNewLine(); 603 declarations.AddNewLine();
484 } 604 }
485 declarations.AddNewLine(); 605 declarations.AddNewLine();
606 }
486 607
608 /// Generates declarations for samplers.
609 void GenerateSamplers() {
487 const auto& samplers = GetSamplers(); 610 const auto& samplers = GetSamplers();
488 for (const auto& sampler : samplers) { 611 for (const auto& sampler : samplers) {
489 declarations.AddLine("uniform " + sampler.GetTypeString() + ' ' + sampler.GetName() + 612 declarations.AddLine("uniform " + sampler.GetTypeString() + ' ' + sampler.GetName() +
@@ -492,44 +615,42 @@ public:
492 declarations.AddNewLine(); 615 declarations.AddNewLine();
493 } 616 }
494 617
495 /// Returns a list of constant buffer declarations 618 /// Generates declarations used for geometry shaders.
496 std::vector<ConstBufferEntry> GetConstBuffersDeclarations() const { 619 void GenerateGeometry() {
497 std::vector<ConstBufferEntry> result; 620 if (stage != Maxwell3D::Regs::ShaderStage::Geometry)
498 std::copy_if(declr_const_buffers.begin(), declr_const_buffers.end(), 621 return;
499 std::back_inserter(result), [](const auto& entry) { return entry.IsUsed(); });
500 return result;
501 }
502
503 /// Returns a list of samplers used in the shader
504 const std::vector<SamplerEntry>& GetSamplers() const {
505 return used_samplers;
506 }
507
508 /// Returns the GLSL sampler used for the input shader sampler, and creates a new one if
509 /// necessary.
510 std::string AccessSampler(const Sampler& sampler, Tegra::Shader::TextureType type,
511 bool is_array, bool is_shadow) {
512 const std::size_t offset = static_cast<std::size_t>(sampler.index.Value());
513 622
514 // If this sampler has already been used, return the existing mapping. 623 declarations.AddLine(
515 const auto itr = 624 "layout (" + GetTopologyName(header.common3.output_topology) +
516 std::find_if(used_samplers.begin(), used_samplers.end(), 625 ", max_vertices = " + std::to_string(header.common4.max_output_vertices) + ") out;");
517 [&](const SamplerEntry& entry) { return entry.GetOffset() == offset; }); 626 declarations.AddNewLine();
518 627
519 if (itr != used_samplers.end()) { 628 declarations.AddLine("vec4 amem[" + std::to_string(MAX_GEOMETRY_BUFFERS) + "][" +
520 ASSERT(itr->GetType() == type && itr->IsArray() == is_array && 629 std::to_string(MAX_ATTRIBUTES) + "];");
521 itr->IsShadow() == is_shadow); 630 declarations.AddNewLine();
522 return itr->GetName();
523 }
524 631
525 // Otherwise create a new mapping for this sampler 632 constexpr char buffer[] = "amem[output_buffer]";
526 const std::size_t next_index = used_samplers.size(); 633 declarations.AddLine("void emit_vertex(uint output_buffer) {");
527 const SamplerEntry entry{stage, offset, next_index, type, is_array, is_shadow}; 634 ++declarations.scope;
528 used_samplers.emplace_back(entry); 635 for (const auto element : declr_output_attribute) {
529 return entry.GetName(); 636 declarations.AddLine(GetOutputAttribute(element) + " = " + buffer + '[' +
637 std::to_string(static_cast<u32>(element)) + "];");
638 }
639
640 declarations.AddLine("position = " + std::string(buffer) + '[' +
641 std::to_string(static_cast<u32>(Attribute::Index::Position)) + "];");
642
643 // If a geometry shader is attached, it will always flip (it's the last stage before
644 // fragment). For more info about flipping, refer to gl_shader_gen.cpp.
645 declarations.AddLine("position.xy *= viewport_flip.xy;");
646 declarations.AddLine("gl_Position = position;");
647 declarations.AddLine("position.w = 1.0;");
648 declarations.AddLine("EmitVertex();");
649 --declarations.scope;
650 declarations.AddLine('}');
651 declarations.AddNewLine();
530 } 652 }
531 653
532private:
533 /// Generates code representing a temporary (GPR) register. 654 /// Generates code representing a temporary (GPR) register.
534 std::string GetRegister(const Register& reg, unsigned elem) { 655 std::string GetRegister(const Register& reg, unsigned elem) {
535 if (reg == Register::ZeroIndex) { 656 if (reg == Register::ZeroIndex) {
@@ -586,11 +707,19 @@ private:
586 707
587 /// Generates code representing an input attribute register. 708 /// Generates code representing an input attribute register.
588 std::string GetInputAttribute(Attribute::Index attribute, 709 std::string GetInputAttribute(Attribute::Index attribute,
589 const Tegra::Shader::IpaMode& input_mode) { 710 const Tegra::Shader::IpaMode& input_mode,
711 boost::optional<Register> vertex = {}) {
712 auto GeometryPass = [&](const std::string& name) {
713 if (stage == Maxwell3D::Regs::ShaderStage::Geometry && vertex) {
714 return "gs_" + name + '[' + GetRegisterAsInteger(vertex.value(), 0, false) + ']';
715 }
716 return name;
717 };
718
590 switch (attribute) { 719 switch (attribute) {
591 case Attribute::Index::Position: 720 case Attribute::Index::Position:
592 if (stage != Maxwell3D::Regs::ShaderStage::Fragment) { 721 if (stage != Maxwell3D::Regs::ShaderStage::Fragment) {
593 return "position"; 722 return GeometryPass("position");
594 } else { 723 } else {
595 return "vec4(gl_FragCoord.x, gl_FragCoord.y, gl_FragCoord.z, 1.0)"; 724 return "vec4(gl_FragCoord.x, gl_FragCoord.y, gl_FragCoord.z, 1.0)";
596 } 725 }
@@ -619,7 +748,7 @@ private:
619 UNREACHABLE(); 748 UNREACHABLE();
620 } 749 }
621 } 750 }
622 return "input_attribute_" + std::to_string(index); 751 return GeometryPass("input_attribute_" + std::to_string(index));
623 } 752 }
624 753
625 LOG_CRITICAL(HW_GPU, "Unhandled input attribute: {}", static_cast<u32>(attribute)); 754 LOG_CRITICAL(HW_GPU, "Unhandled input attribute: {}", static_cast<u32>(attribute));
@@ -672,7 +801,7 @@ private:
672 return out; 801 return out;
673 } 802 }
674 803
675 /// Generates code representing an output attribute register. 804 /// Generates code representing the declaration name of an output attribute register.
676 std::string GetOutputAttribute(Attribute::Index attribute) { 805 std::string GetOutputAttribute(Attribute::Index attribute) {
677 switch (attribute) { 806 switch (attribute) {
678 case Attribute::Index::Position: 807 case Attribute::Index::Position:
@@ -708,6 +837,7 @@ private:
708 std::vector<SamplerEntry> used_samplers; 837 std::vector<SamplerEntry> used_samplers;
709 const Maxwell3D::Regs::ShaderStage& stage; 838 const Maxwell3D::Regs::ShaderStage& stage;
710 const std::string& suffix; 839 const std::string& suffix;
840 const Tegra::Shader::Header& header;
711}; 841};
712 842
713class GLSLGenerator { 843class GLSLGenerator {
@@ -1103,8 +1233,8 @@ private:
1103 return offset + 1; 1233 return offset + 1;
1104 } 1234 }
1105 1235
1106 shader.AddLine("// " + std::to_string(offset) + ": " + opcode->GetName() + " (" + 1236 shader.AddLine(
1107 std::to_string(instr.value) + ')'); 1237 fmt::format("// {}: {} (0x{:016x})", offset, opcode->GetName(), instr.value));
1108 1238
1109 using Tegra::Shader::Pred; 1239 using Tegra::Shader::Pred;
1110 ASSERT_MSG(instr.pred.full_pred != Pred::NeverExecute, 1240 ASSERT_MSG(instr.pred.full_pred != Pred::NeverExecute,
@@ -1826,7 +1956,7 @@ private:
1826 const auto LoadNextElement = [&](u32 reg_offset) { 1956 const auto LoadNextElement = [&](u32 reg_offset) {
1827 regs.SetRegisterToInputAttibute(instr.gpr0.Value() + reg_offset, next_element, 1957 regs.SetRegisterToInputAttibute(instr.gpr0.Value() + reg_offset, next_element,
1828 static_cast<Attribute::Index>(next_index), 1958 static_cast<Attribute::Index>(next_index),
1829 input_mode); 1959 input_mode, instr.gpr39.Value());
1830 1960
1831 // Load the next attribute element into the following register. If the element 1961 // Load the next attribute element into the following register. If the element
1832 // to load goes beyond the vec4 size, load the first element of the next 1962 // to load goes beyond the vec4 size, load the first element of the next
@@ -1890,8 +2020,8 @@ private:
1890 2020
1891 const auto StoreNextElement = [&](u32 reg_offset) { 2021 const auto StoreNextElement = [&](u32 reg_offset) {
1892 regs.SetOutputAttributeToRegister(static_cast<Attribute::Index>(next_index), 2022 regs.SetOutputAttributeToRegister(static_cast<Attribute::Index>(next_index),
1893 next_element, 2023 next_element, instr.gpr0.Value() + reg_offset,
1894 instr.gpr0.Value() + reg_offset); 2024 instr.gpr39.Value());
1895 2025
1896 // Load the next attribute element into the following register. If the element 2026 // Load the next attribute element into the following register. If the element
1897 // to load goes beyond the vec4 size, load the first element of the next 2027 // to load goes beyond the vec4 size, load the first element of the next
@@ -2299,8 +2429,7 @@ private:
2299 ASSERT_MSG(!instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV), 2429 ASSERT_MSG(!instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
2300 "NDV is not implemented"); 2430 "NDV is not implemented");
2301 2431
2302 const std::string op_a = regs.GetRegisterAsFloat(instr.gpr8); 2432 const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
2303 const std::string op_b = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
2304 const bool is_array = instr.tmml.array != 0; 2433 const bool is_array = instr.tmml.array != 0;
2305 auto texture_type = instr.tmml.texture_type.Value(); 2434 auto texture_type = instr.tmml.texture_type.Value();
2306 const std::string sampler = 2435 const std::string sampler =
@@ -2311,13 +2440,11 @@ private:
2311 std::string coord; 2440 std::string coord;
2312 switch (texture_type) { 2441 switch (texture_type) {
2313 case Tegra::Shader::TextureType::Texture1D: { 2442 case Tegra::Shader::TextureType::Texture1D: {
2314 std::string x = regs.GetRegisterAsFloat(instr.gpr8);
2315 coord = "float coords = " + x + ';'; 2443 coord = "float coords = " + x + ';';
2316 break; 2444 break;
2317 } 2445 }
2318 case Tegra::Shader::TextureType::Texture2D: { 2446 case Tegra::Shader::TextureType::Texture2D: {
2319 std::string x = regs.GetRegisterAsFloat(instr.gpr8); 2447 const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
2320 std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
2321 coord = "vec2 coords = vec2(" + x + ", " + y + ");"; 2448 coord = "vec2 coords = vec2(" + x + ", " + y + ");";
2322 break; 2449 break;
2323 } 2450 }
@@ -2327,8 +2454,7 @@ private:
2327 UNREACHABLE(); 2454 UNREACHABLE();
2328 2455
2329 // Fallback to interpreting as a 2D texture for now 2456 // Fallback to interpreting as a 2D texture for now
2330 std::string x = regs.GetRegisterAsFloat(instr.gpr8); 2457 const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
2331 std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
2332 coord = "vec2 coords = vec2(" + x + ", " + y + ");"; 2458 coord = "vec2 coords = vec2(" + x + ", " + y + ");";
2333 texture_type = Tegra::Shader::TextureType::Texture2D; 2459 texture_type = Tegra::Shader::TextureType::Texture2D;
2334 } 2460 }
@@ -2738,6 +2864,52 @@ private:
2738 2864
2739 break; 2865 break;
2740 } 2866 }
2867 case OpCode::Id::OUT_R: {
2868 ASSERT(instr.gpr20.Value() == Register::ZeroIndex);
2869 ASSERT_MSG(stage == Maxwell3D::Regs::ShaderStage::Geometry,
2870 "OUT is expected to be used in a geometry shader.");
2871
2872 if (instr.out.emit) {
2873 // gpr0 is used to store the next address. Hardware returns a pointer but
2874 // we just return the next index with a cyclic cap.
2875 const std::string current{regs.GetRegisterAsInteger(instr.gpr8, 0, false)};
2876 const std::string next = "((" + current + " + 1" + ") % " +
2877 std::to_string(MAX_GEOMETRY_BUFFERS) + ')';
2878 shader.AddLine("emit_vertex(" + current + ");");
2879 regs.SetRegisterToInteger(instr.gpr0, false, 0, next, 1, 1);
2880 }
2881 if (instr.out.cut) {
2882 shader.AddLine("EndPrimitive();");
2883 }
2884
2885 break;
2886 }
2887 case OpCode::Id::MOV_SYS: {
2888 switch (instr.sys20) {
2889 case Tegra::Shader::SystemVariable::InvocationInfo: {
2890 LOG_WARNING(HW_GPU, "MOV_SYS instruction with InvocationInfo is incomplete");
2891 regs.SetRegisterToInteger(instr.gpr0, false, 0, "0u", 1, 1);
2892 break;
2893 }
2894 default: {
2895 LOG_CRITICAL(HW_GPU, "Unhandled system move: {}",
2896 static_cast<u32>(instr.sys20.Value()));
2897 UNREACHABLE();
2898 }
2899 }
2900 break;
2901 }
2902 case OpCode::Id::ISBERD: {
2903 ASSERT(instr.isberd.o == 0);
2904 ASSERT(instr.isberd.skew == 0);
2905 ASSERT(instr.isberd.shift == Tegra::Shader::IsberdShift::None);
2906 ASSERT(instr.isberd.mode == Tegra::Shader::IsberdMode::None);
2907 ASSERT_MSG(stage == Maxwell3D::Regs::ShaderStage::Geometry,
2908 "ISBERD is expected to be used in a geometry shader.");
2909 LOG_WARNING(HW_GPU, "ISBERD instruction is incomplete");
2910 regs.SetRegisterToFloat(instr.gpr0, 0, regs.GetRegisterAsFloat(instr.gpr8), 1, 1);
2911 break;
2912 }
2741 case OpCode::Id::BRA: { 2913 case OpCode::Id::BRA: {
2742 ASSERT_MSG(instr.bra.constant_buffer == 0, 2914 ASSERT_MSG(instr.bra.constant_buffer == 0,
2743 "BRA with constant buffers are not implemented"); 2915 "BRA with constant buffers are not implemented");
@@ -2911,7 +3083,7 @@ private:
2911 3083
2912 ShaderWriter shader; 3084 ShaderWriter shader;
2913 ShaderWriter declarations; 3085 ShaderWriter declarations;
2914 GLSLRegisterManager regs{shader, declarations, stage, suffix}; 3086 GLSLRegisterManager regs{shader, declarations, stage, suffix, header};
2915 3087
2916 // Declarations 3088 // Declarations
2917 std::set<std::string> declr_predicates; 3089 std::set<std::string> declr_predicates;
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp
index b0466c18f..1e5eb32df 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp
@@ -17,7 +17,18 @@ ProgramResult GenerateVertexShader(const ShaderSetup& setup) {
17 std::string out = "#version 430 core\n"; 17 std::string out = "#version 430 core\n";
18 out += "#extension GL_ARB_separate_shader_objects : enable\n\n"; 18 out += "#extension GL_ARB_separate_shader_objects : enable\n\n";
19 out += Decompiler::GetCommonDeclarations(); 19 out += Decompiler::GetCommonDeclarations();
20 out += "bool exec_vertex();\n"; 20
21 out += R"(
22out gl_PerVertex {
23 vec4 gl_Position;
24};
25
26layout(std140) uniform vs_config {
27 vec4 viewport_flip;
28 uvec4 instance_id;
29 uvec4 flip_stage;
30};
31)";
21 32
22 if (setup.IsDualProgram()) { 33 if (setup.IsDualProgram()) {
23 out += "bool exec_vertex_b();\n"; 34 out += "bool exec_vertex_b();\n";
@@ -28,18 +39,17 @@ ProgramResult GenerateVertexShader(const ShaderSetup& setup) {
28 Maxwell3D::Regs::ShaderStage::Vertex, "vertex") 39 Maxwell3D::Regs::ShaderStage::Vertex, "vertex")
29 .get_value_or({}); 40 .get_value_or({});
30 41
31 out += R"( 42 out += program.first;
32
33out gl_PerVertex {
34 vec4 gl_Position;
35};
36 43
37out vec4 position; 44 if (setup.IsDualProgram()) {
45 ProgramResult program_b =
46 Decompiler::DecompileProgram(setup.program.code_b, PROGRAM_OFFSET,
47 Maxwell3D::Regs::ShaderStage::Vertex, "vertex_b")
48 .get_value_or({});
49 out += program_b.first;
50 }
38 51
39layout (std140) uniform vs_config { 52 out += R"(
40 vec4 viewport_flip;
41 uvec4 instance_id;
42};
43 53
44void main() { 54void main() {
45 position = vec4(0.0, 0.0, 0.0, 0.0); 55 position = vec4(0.0, 0.0, 0.0, 0.0);
@@ -52,27 +62,52 @@ void main() {
52 62
53 out += R"( 63 out += R"(
54 64
55 // Viewport can be flipped, which is unsupported by glViewport 65 // Check if the flip stage is VertexB
56 position.xy *= viewport_flip.xy; 66 if (flip_stage[0] == 1) {
67 // Viewport can be flipped, which is unsupported by glViewport
68 position.xy *= viewport_flip.xy;
69 }
57 gl_Position = position; 70 gl_Position = position;
58 71
59 // TODO(bunnei): This is likely a hack, position.w should be interpolated as 1.0 72 // TODO(bunnei): This is likely a hack, position.w should be interpolated as 1.0
60 // For now, this is here to bring order in lieu of proper emulation 73 // For now, this is here to bring order in lieu of proper emulation
61 position.w = 1.0; 74 if (flip_stage[0] == 1) {
75 position.w = 1.0;
76 }
62} 77}
63 78
64)"; 79)";
65 80
66 out += program.first; 81 return {out, program.second};
82}
67 83
68 if (setup.IsDualProgram()) { 84ProgramResult GenerateGeometryShader(const ShaderSetup& setup) {
69 ProgramResult program_b = 85 std::string out = "#version 430 core\n";
70 Decompiler::DecompileProgram(setup.program.code_b, PROGRAM_OFFSET, 86 out += "#extension GL_ARB_separate_shader_objects : enable\n\n";
71 Maxwell3D::Regs::ShaderStage::Vertex, "vertex_b") 87 out += Decompiler::GetCommonDeclarations();
72 .get_value_or({}); 88 out += "bool exec_geometry();\n";
73 out += program_b.first; 89
74 } 90 ProgramResult program =
91 Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET,
92 Maxwell3D::Regs::ShaderStage::Geometry, "geometry")
93 .get_value_or({});
94 out += R"(
95out gl_PerVertex {
96 vec4 gl_Position;
97};
75 98
99layout (std140) uniform gs_config {
100 vec4 viewport_flip;
101 uvec4 instance_id;
102 uvec4 flip_stage;
103};
104
105void main() {
106 exec_geometry();
107}
108
109)";
110 out += program.first;
76 return {out, program.second}; 111 return {out, program.second};
77} 112}
78 113
@@ -87,7 +122,6 @@ ProgramResult GenerateFragmentShader(const ShaderSetup& setup) {
87 Maxwell3D::Regs::ShaderStage::Fragment, "fragment") 122 Maxwell3D::Regs::ShaderStage::Fragment, "fragment")
88 .get_value_or({}); 123 .get_value_or({});
89 out += R"( 124 out += R"(
90in vec4 position;
91layout(location = 0) out vec4 FragColor0; 125layout(location = 0) out vec4 FragColor0;
92layout(location = 1) out vec4 FragColor1; 126layout(location = 1) out vec4 FragColor1;
93layout(location = 2) out vec4 FragColor2; 127layout(location = 2) out vec4 FragColor2;
@@ -100,6 +134,7 @@ layout(location = 7) out vec4 FragColor7;
100layout (std140) uniform fs_config { 134layout (std140) uniform fs_config {
101 vec4 viewport_flip; 135 vec4 viewport_flip;
102 uvec4 instance_id; 136 uvec4 instance_id;
137 uvec4 flip_stage;
103}; 138};
104 139
105void main() { 140void main() {
@@ -110,5 +145,4 @@ void main() {
110 out += program.first; 145 out += program.first;
111 return {out, program.second}; 146 return {out, program.second};
112} 147}
113 148} // namespace OpenGL::GLShader \ No newline at end of file
114} // namespace OpenGL::GLShader
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.h b/src/video_core/renderer_opengl/gl_shader_gen.h
index e56f39e78..79596087a 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.h
+++ b/src/video_core/renderer_opengl/gl_shader_gen.h
@@ -196,6 +196,12 @@ private:
196ProgramResult GenerateVertexShader(const ShaderSetup& setup); 196ProgramResult GenerateVertexShader(const ShaderSetup& setup);
197 197
198/** 198/**
199 * Generates the GLSL geometry shader program source code for the given GS program
200 * @returns String of the shader source code
201 */
202ProgramResult GenerateGeometryShader(const ShaderSetup& setup);
203
204/**
199 * Generates the GLSL fragment shader program source code for the given FS program 205 * Generates the GLSL fragment shader program source code for the given FS program
200 * @returns String of the shader source code 206 * @returns String of the shader source code
201 */ 207 */
diff --git a/src/video_core/renderer_opengl/gl_shader_manager.cpp b/src/video_core/renderer_opengl/gl_shader_manager.cpp
index 022d32a86..010857ec6 100644
--- a/src/video_core/renderer_opengl/gl_shader_manager.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_manager.cpp
@@ -18,6 +18,14 @@ void MaxwellUniformData::SetFromRegs(const Maxwell3D::State::ShaderStageInfo& sh
18 18
19 // We only assign the instance to the first component of the vector, the rest is just padding. 19 // We only assign the instance to the first component of the vector, the rest is just padding.
20 instance_id[0] = state.current_instance; 20 instance_id[0] = state.current_instance;
21
22 // Assign in which stage the position has to be flipped
23 // (the last stage before the fragment shader).
24 if (gpu.regs.shader_config[static_cast<u32>(Maxwell3D::Regs::ShaderProgram::Geometry)].enable) {
25 flip_stage[0] = static_cast<u32>(Maxwell3D::Regs::ShaderProgram::Geometry);
26 } else {
27 flip_stage[0] = static_cast<u32>(Maxwell3D::Regs::ShaderProgram::VertexB);
28 }
21} 29}
22 30
23} // namespace OpenGL::GLShader 31} // namespace OpenGL::GLShader
diff --git a/src/video_core/renderer_opengl/gl_shader_manager.h b/src/video_core/renderer_opengl/gl_shader_manager.h
index 3de15ba9b..b3a191cf2 100644
--- a/src/video_core/renderer_opengl/gl_shader_manager.h
+++ b/src/video_core/renderer_opengl/gl_shader_manager.h
@@ -21,8 +21,9 @@ struct MaxwellUniformData {
21 void SetFromRegs(const Maxwell3D::State::ShaderStageInfo& shader_stage); 21 void SetFromRegs(const Maxwell3D::State::ShaderStageInfo& shader_stage);
22 alignas(16) GLvec4 viewport_flip; 22 alignas(16) GLvec4 viewport_flip;
23 alignas(16) GLuvec4 instance_id; 23 alignas(16) GLuvec4 instance_id;
24 alignas(16) GLuvec4 flip_stage;
24}; 25};
25static_assert(sizeof(MaxwellUniformData) == 32, "MaxwellUniformData structure size is incorrect"); 26static_assert(sizeof(MaxwellUniformData) == 48, "MaxwellUniformData structure size is incorrect");
26static_assert(sizeof(MaxwellUniformData) < 16384, 27static_assert(sizeof(MaxwellUniformData) < 16384,
27 "MaxwellUniformData structure must be less than 16kb as per the OpenGL spec"); 28 "MaxwellUniformData structure must be less than 16kb as per the OpenGL spec");
28 29
@@ -36,6 +37,10 @@ public:
36 vs = program; 37 vs = program;
37 } 38 }
38 39
40 void UseProgrammableGeometryShader(GLuint program) {
41 gs = program;
42 }
43
39 void UseProgrammableFragmentShader(GLuint program) { 44 void UseProgrammableFragmentShader(GLuint program) {
40 fs = program; 45 fs = program;
41 } 46 }
diff --git a/src/video_core/utils.h b/src/video_core/utils.h
index 681919ae3..237cc1307 100644
--- a/src/video_core/utils.h
+++ b/src/video_core/utils.h
@@ -169,16 +169,20 @@ static void LabelGLObject(GLenum identifier, GLuint handle, VAddr addr,
169 const std::string nice_addr = fmt::format("0x{:016x}", addr); 169 const std::string nice_addr = fmt::format("0x{:016x}", addr);
170 std::string object_label; 170 std::string object_label;
171 171
172 switch (identifier) { 172 if (extra_info.empty()) {
173 case GL_TEXTURE: 173 switch (identifier) {
174 object_label = extra_info + "@" + nice_addr; 174 case GL_TEXTURE:
175 break; 175 object_label = "Texture@" + nice_addr;
176 case GL_PROGRAM: 176 break;
177 object_label = "ShaderProgram@" + nice_addr; 177 case GL_PROGRAM:
178 break; 178 object_label = "Shader@" + nice_addr;
179 default: 179 break;
180 object_label = fmt::format("Object(0x{:x})@{}", identifier, nice_addr); 180 default:
181 break; 181 object_label = fmt::format("Object(0x{:x})@{}", identifier, nice_addr);
182 break;
183 }
184 } else {
185 object_label = extra_info + '@' + nice_addr;
182 } 186 }
183 glObjectLabel(identifier, handle, -1, static_cast<const GLchar*>(object_label.c_str())); 187 glObjectLabel(identifier, handle, -1, static_cast<const GLchar*>(object_label.c_str()));
184} 188}
diff --git a/src/yuzu/bootmanager.cpp b/src/yuzu/bootmanager.cpp
index 4e4c108ab..e8ab23326 100644
--- a/src/yuzu/bootmanager.cpp
+++ b/src/yuzu/bootmanager.cpp
@@ -110,6 +110,7 @@ GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread)
110 std::string window_title = fmt::format("yuzu {} | {}-{}", Common::g_build_name, 110 std::string window_title = fmt::format("yuzu {} | {}-{}", Common::g_build_name,
111 Common::g_scm_branch, Common::g_scm_desc); 111 Common::g_scm_branch, Common::g_scm_desc);
112 setWindowTitle(QString::fromStdString(window_title)); 112 setWindowTitle(QString::fromStdString(window_title));
113 setAttribute(Qt::WA_AcceptTouchEvents);
113 114
114 InputCommon::Init(); 115 InputCommon::Init();
115 InputCommon::StartJoystickEventHandler(); 116 InputCommon::StartJoystickEventHandler();
@@ -190,11 +191,17 @@ QByteArray GRenderWindow::saveGeometry() {
190 return geometry; 191 return geometry;
191} 192}
192 193
193qreal GRenderWindow::windowPixelRatio() { 194qreal GRenderWindow::windowPixelRatio() const {
194 // windowHandle() might not be accessible until the window is displayed to screen. 195 // windowHandle() might not be accessible until the window is displayed to screen.
195 return windowHandle() ? windowHandle()->screen()->devicePixelRatio() : 1.0f; 196 return windowHandle() ? windowHandle()->screen()->devicePixelRatio() : 1.0f;
196} 197}
197 198
199std::pair<unsigned, unsigned> GRenderWindow::ScaleTouch(const QPointF pos) const {
200 const qreal pixel_ratio = windowPixelRatio();
201 return {static_cast<unsigned>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
202 static_cast<unsigned>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
203}
204
198void GRenderWindow::closeEvent(QCloseEvent* event) { 205void GRenderWindow::closeEvent(QCloseEvent* event) {
199 emit Closed(); 206 emit Closed();
200 QWidget::closeEvent(event); 207 QWidget::closeEvent(event);
@@ -209,31 +216,81 @@ void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
209} 216}
210 217
211void GRenderWindow::mousePressEvent(QMouseEvent* event) { 218void GRenderWindow::mousePressEvent(QMouseEvent* event) {
219 if (event->source() == Qt::MouseEventSynthesizedBySystem)
220 return; // touch input is handled in TouchBeginEvent
221
212 auto pos = event->pos(); 222 auto pos = event->pos();
213 if (event->button() == Qt::LeftButton) { 223 if (event->button() == Qt::LeftButton) {
214 qreal pixelRatio = windowPixelRatio(); 224 const auto [x, y] = ScaleTouch(pos);
215 this->TouchPressed(static_cast<unsigned>(pos.x() * pixelRatio), 225 this->TouchPressed(x, y);
216 static_cast<unsigned>(pos.y() * pixelRatio));
217 } else if (event->button() == Qt::RightButton) { 226 } else if (event->button() == Qt::RightButton) {
218 InputCommon::GetMotionEmu()->BeginTilt(pos.x(), pos.y()); 227 InputCommon::GetMotionEmu()->BeginTilt(pos.x(), pos.y());
219 } 228 }
220} 229}
221 230
222void GRenderWindow::mouseMoveEvent(QMouseEvent* event) { 231void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
232 if (event->source() == Qt::MouseEventSynthesizedBySystem)
233 return; // touch input is handled in TouchUpdateEvent
234
223 auto pos = event->pos(); 235 auto pos = event->pos();
224 qreal pixelRatio = windowPixelRatio(); 236 const auto [x, y] = ScaleTouch(pos);
225 this->TouchMoved(std::max(static_cast<unsigned>(pos.x() * pixelRatio), 0u), 237 this->TouchMoved(x, y);
226 std::max(static_cast<unsigned>(pos.y() * pixelRatio), 0u));
227 InputCommon::GetMotionEmu()->Tilt(pos.x(), pos.y()); 238 InputCommon::GetMotionEmu()->Tilt(pos.x(), pos.y());
228} 239}
229 240
230void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) { 241void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
242 if (event->source() == Qt::MouseEventSynthesizedBySystem)
243 return; // touch input is handled in TouchEndEvent
244
231 if (event->button() == Qt::LeftButton) 245 if (event->button() == Qt::LeftButton)
232 this->TouchReleased(); 246 this->TouchReleased();
233 else if (event->button() == Qt::RightButton) 247 else if (event->button() == Qt::RightButton)
234 InputCommon::GetMotionEmu()->EndTilt(); 248 InputCommon::GetMotionEmu()->EndTilt();
235} 249}
236 250
251void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
252 // TouchBegin always has exactly one touch point, so take the .first()
253 const auto [x, y] = ScaleTouch(event->touchPoints().first().pos());
254 this->TouchPressed(x, y);
255}
256
257void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
258 QPointF pos;
259 int active_points = 0;
260
261 // average all active touch points
262 for (const auto tp : event->touchPoints()) {
263 if (tp.state() & (Qt::TouchPointPressed | Qt::TouchPointMoved | Qt::TouchPointStationary)) {
264 active_points++;
265 pos += tp.pos();
266 }
267 }
268
269 pos /= active_points;
270
271 const auto [x, y] = ScaleTouch(pos);
272 this->TouchMoved(x, y);
273}
274
275void GRenderWindow::TouchEndEvent() {
276 this->TouchReleased();
277}
278
279bool GRenderWindow::event(QEvent* event) {
280 if (event->type() == QEvent::TouchBegin) {
281 TouchBeginEvent(static_cast<QTouchEvent*>(event));
282 return true;
283 } else if (event->type() == QEvent::TouchUpdate) {
284 TouchUpdateEvent(static_cast<QTouchEvent*>(event));
285 return true;
286 } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
287 TouchEndEvent();
288 return true;
289 }
290
291 return QWidget::event(event);
292}
293
237void GRenderWindow::focusOutEvent(QFocusEvent* event) { 294void GRenderWindow::focusOutEvent(QFocusEvent* event) {
238 QWidget::focusOutEvent(event); 295 QWidget::focusOutEvent(event);
239 InputCommon::GetKeyboard()->ReleaseAllKeys(); 296 InputCommon::GetKeyboard()->ReleaseAllKeys();
diff --git a/src/yuzu/bootmanager.h b/src/yuzu/bootmanager.h
index f133bfadf..873985564 100644
--- a/src/yuzu/bootmanager.h
+++ b/src/yuzu/bootmanager.h
@@ -15,6 +15,7 @@
15 15
16class QKeyEvent; 16class QKeyEvent;
17class QScreen; 17class QScreen;
18class QTouchEvent;
18 19
19class GGLWidgetInternal; 20class GGLWidgetInternal;
20class GMainWindow; 21class GMainWindow;
@@ -119,7 +120,7 @@ public:
119 void restoreGeometry(const QByteArray& geometry); // overridden 120 void restoreGeometry(const QByteArray& geometry); // overridden
120 QByteArray saveGeometry(); // overridden 121 QByteArray saveGeometry(); // overridden
121 122
122 qreal windowPixelRatio(); 123 qreal windowPixelRatio() const;
123 124
124 void closeEvent(QCloseEvent* event) override; 125 void closeEvent(QCloseEvent* event) override;
125 126
@@ -130,6 +131,8 @@ public:
130 void mouseMoveEvent(QMouseEvent* event) override; 131 void mouseMoveEvent(QMouseEvent* event) override;
131 void mouseReleaseEvent(QMouseEvent* event) override; 132 void mouseReleaseEvent(QMouseEvent* event) override;
132 133
134 bool event(QEvent* event) override;
135
133 void focusOutEvent(QFocusEvent* event) override; 136 void focusOutEvent(QFocusEvent* event) override;
134 137
135 void OnClientAreaResized(unsigned width, unsigned height); 138 void OnClientAreaResized(unsigned width, unsigned height);
@@ -148,6 +151,11 @@ signals:
148 void Closed(); 151 void Closed();
149 152
150private: 153private:
154 std::pair<unsigned, unsigned> ScaleTouch(const QPointF pos) const;
155 void TouchBeginEvent(const QTouchEvent* event);
156 void TouchUpdateEvent(const QTouchEvent* event);
157 void TouchEndEvent();
158
151 void OnMinimalClientAreaChangeRequest( 159 void OnMinimalClientAreaChangeRequest(
152 const std::pair<unsigned, unsigned>& minimal_size) override; 160 const std::pair<unsigned, unsigned>& minimal_size) override;
153 161
diff --git a/src/yuzu/game_list_worker.cpp b/src/yuzu/game_list_worker.cpp
index d2b3de683..8f99a1c78 100644
--- a/src/yuzu/game_list_worker.cpp
+++ b/src/yuzu/game_list_worker.cpp
@@ -27,9 +27,8 @@
27#include "yuzu/ui_settings.h" 27#include "yuzu/ui_settings.h"
28 28
29namespace { 29namespace {
30void GetMetadataFromControlNCA(const FileSys::PatchManager& patch_manager, 30void GetMetadataFromControlNCA(const FileSys::PatchManager& patch_manager, const FileSys::NCA& nca,
31 const std::shared_ptr<FileSys::NCA>& nca, std::vector<u8>& icon, 31 std::vector<u8>& icon, std::string& name) {
32 std::string& name) {
33 auto [nacp, icon_file] = patch_manager.ParseControlNCA(nca); 32 auto [nacp, icon_file] = patch_manager.ParseControlNCA(nca);
34 if (icon_file != nullptr) 33 if (icon_file != nullptr)
35 icon = icon_file->ReadAllBytes(); 34 icon = icon_file->ReadAllBytes();
@@ -110,7 +109,7 @@ void GameListWorker::AddInstalledTitlesToGameList() {
110 const FileSys::PatchManager patch{program_id}; 109 const FileSys::PatchManager patch{program_id};
111 const auto& control = cache->GetEntry(game.title_id, FileSys::ContentRecordType::Control); 110 const auto& control = cache->GetEntry(game.title_id, FileSys::ContentRecordType::Control);
112 if (control != nullptr) 111 if (control != nullptr)
113 GetMetadataFromControlNCA(patch, control, icon, name); 112 GetMetadataFromControlNCA(patch, *control, icon, name);
114 113
115 auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id); 114 auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
116 115
@@ -197,8 +196,8 @@ void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, unsign
197 res2 == Loader::ResultStatus::Success) { 196 res2 == Loader::ResultStatus::Success) {
198 // Use from metadata pool. 197 // Use from metadata pool.
199 if (nca_control_map.find(program_id) != nca_control_map.end()) { 198 if (nca_control_map.find(program_id) != nca_control_map.end()) {
200 const auto nca = nca_control_map[program_id]; 199 const auto& nca = nca_control_map[program_id];
201 GetMetadataFromControlNCA(patch, nca, icon, name); 200 GetMetadataFromControlNCA(patch, *nca, icon, name);
202 } 201 }
203 } 202 }
204 203
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
index 155095095..a9ad92a80 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
@@ -40,6 +40,35 @@ void EmuWindow_SDL2::OnMouseButton(u32 button, u8 state, s32 x, s32 y) {
40 } 40 }
41} 41}
42 42
43std::pair<unsigned, unsigned> EmuWindow_SDL2::TouchToPixelPos(float touch_x, float touch_y) const {
44 int w, h;
45 SDL_GetWindowSize(render_window, &w, &h);
46
47 touch_x *= w;
48 touch_y *= h;
49
50 return {static_cast<unsigned>(std::max(std::round(touch_x), 0.0f)),
51 static_cast<unsigned>(std::max(std::round(touch_y), 0.0f))};
52}
53
54void EmuWindow_SDL2::OnFingerDown(float x, float y) {
55 // TODO(NeatNit): keep track of multitouch using the fingerID and a dictionary of some kind
56 // This isn't critical because the best we can do when we have that is to average them, like the
57 // 3DS does
58
59 const auto [px, py] = TouchToPixelPos(x, y);
60 TouchPressed(px, py);
61}
62
63void EmuWindow_SDL2::OnFingerMotion(float x, float y) {
64 const auto [px, py] = TouchToPixelPos(x, y);
65 TouchMoved(px, py);
66}
67
68void EmuWindow_SDL2::OnFingerUp() {
69 TouchReleased();
70}
71
43void EmuWindow_SDL2::OnKeyEvent(int key, u8 state) { 72void EmuWindow_SDL2::OnKeyEvent(int key, u8 state) {
44 if (state == SDL_PRESSED) { 73 if (state == SDL_PRESSED) {
45 InputCommon::GetKeyboard()->PressKey(key); 74 InputCommon::GetKeyboard()->PressKey(key);
@@ -219,11 +248,26 @@ void EmuWindow_SDL2::PollEvents() {
219 OnKeyEvent(static_cast<int>(event.key.keysym.scancode), event.key.state); 248 OnKeyEvent(static_cast<int>(event.key.keysym.scancode), event.key.state);
220 break; 249 break;
221 case SDL_MOUSEMOTION: 250 case SDL_MOUSEMOTION:
222 OnMouseMotion(event.motion.x, event.motion.y); 251 // ignore if it came from touch
252 if (event.button.which != SDL_TOUCH_MOUSEID)
253 OnMouseMotion(event.motion.x, event.motion.y);
223 break; 254 break;
224 case SDL_MOUSEBUTTONDOWN: 255 case SDL_MOUSEBUTTONDOWN:
225 case SDL_MOUSEBUTTONUP: 256 case SDL_MOUSEBUTTONUP:
226 OnMouseButton(event.button.button, event.button.state, event.button.x, event.button.y); 257 // ignore if it came from touch
258 if (event.button.which != SDL_TOUCH_MOUSEID) {
259 OnMouseButton(event.button.button, event.button.state, event.button.x,
260 event.button.y);
261 }
262 break;
263 case SDL_FINGERDOWN:
264 OnFingerDown(event.tfinger.x, event.tfinger.y);
265 break;
266 case SDL_FINGERMOTION:
267 OnFingerMotion(event.tfinger.x, event.tfinger.y);
268 break;
269 case SDL_FINGERUP:
270 OnFingerUp();
227 break; 271 break;
228 case SDL_QUIT: 272 case SDL_QUIT:
229 is_open = false; 273 is_open = false;
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2.h b/src/yuzu_cmd/emu_window/emu_window_sdl2.h
index d34902109..b0d4116cc 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2.h
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.h
@@ -40,6 +40,18 @@ private:
40 /// Called by PollEvents when a mouse button is pressed or released 40 /// Called by PollEvents when a mouse button is pressed or released
41 void OnMouseButton(u32 button, u8 state, s32 x, s32 y); 41 void OnMouseButton(u32 button, u8 state, s32 x, s32 y);
42 42
43 /// Translates pixel position (0..1) to pixel positions
44 std::pair<unsigned, unsigned> TouchToPixelPos(float touch_x, float touch_y) const;
45
46 /// Called by PollEvents when a finger starts touching the touchscreen
47 void OnFingerDown(float x, float y);
48
49 /// Called by PollEvents when a finger moves while touching the touchscreen
50 void OnFingerMotion(float x, float y);
51
52 /// Called by PollEvents when a finger stops touching the touchscreen
53 void OnFingerUp();
54
43 /// Called by PollEvents when any event that may cause the window to be resized occurs 55 /// Called by PollEvents when any event that may cause the window to be resized occurs
44 void OnResize(); 56 void OnResize();
45 57