summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-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.cpp6
-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/errors.h2
-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.cpp103
-rw-r--r--src/core/hle/kernel/thread.cpp13
-rw-r--r--src/core/hle/kernel/thread.h8
-rw-r--r--src/core/hle/service/audio/hwopus.cpp37
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp20
-rw-r--r--src/core/hle/service/nvdrv/devices/nvmap.cpp72
-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/tests/core/arm/arm_test_common.cpp3
-rw-r--r--src/video_core/engines/fermi_2d.h14
-rw-r--r--src/video_core/engines/maxwell_3d.h41
-rw-r--r--src/video_core/engines/shader_bytecode.h148
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp57
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h9
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.cpp35
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.h9
-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.cpp378
-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/textures/texture.h17
-rw-r--r--src/video_core/utils.h24
-rw-r--r--src/yuzu/game_list_worker.cpp11
38 files changed, 1030 insertions, 239 deletions
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 6c072d0a3..554eae9bc 100644
--- a/src/core/file_sys/ips_layer.cpp
+++ b/src/core/file_sys/ips_layer.cpp
@@ -107,12 +107,12 @@ VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
107 return nullptr; 107 return nullptr;
108 108
109 if (real_offset + rle_size > in_data.size()) 109 if (real_offset + rle_size > in_data.size())
110 rle_size = in_data.size() - real_offset; 110 rle_size = static_cast<u16>(in_data.size() - real_offset);
111 std::memset(in_data.data() + real_offset, data.get(), rle_size); 111 std::memset(in_data.data() + real_offset, data.get(), rle_size);
112 } else { // Standard Patch 112 } else { // Standard Patch
113 auto read = data_size; 113 auto read = data_size;
114 if (real_offset + read > in_data.size()) 114 if (real_offset + read > in_data.size())
115 read = in_data.size() - real_offset; 115 read = static_cast<u16>(in_data.size() - real_offset);
116 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)
117 return nullptr; 117 return nullptr;
118 offset += data_size; 118 offset += data_size;
@@ -265,7 +265,7 @@ void IPSwitchCompiler::Parse() {
265 if (patch_line.length() < 11) 265 if (patch_line.length() < 11)
266 break; 266 break;
267 auto offset = std::stoul(patch_line.substr(0, 8), nullptr, 16); 267 auto offset = std::stoul(patch_line.substr(0, 8), nullptr, 16);
268 offset += offset_shift; 268 offset += static_cast<unsigned long>(offset_shift);
269 269
270 std::vector<u8> replace; 270 std::vector<u8> replace;
271 // 9 - first char of replacement val 271 // 9 - first char of replacement val
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/errors.h b/src/core/hle/kernel/errors.h
index e5fa67ae8..885259618 100644
--- a/src/core/hle/kernel/errors.h
+++ b/src/core/hle/kernel/errors.h
@@ -22,6 +22,7 @@ enum {
22 HandleTableFull = 105, 22 HandleTableFull = 105,
23 InvalidMemoryState = 106, 23 InvalidMemoryState = 106,
24 InvalidMemoryPermissions = 108, 24 InvalidMemoryPermissions = 108,
25 InvalidMemoryRange = 110,
25 InvalidThreadPriority = 112, 26 InvalidThreadPriority = 112,
26 InvalidProcessorId = 113, 27 InvalidProcessorId = 113,
27 InvalidHandle = 114, 28 InvalidHandle = 114,
@@ -56,6 +57,7 @@ constexpr ResultCode ERR_INVALID_ADDRESS(ErrorModule::Kernel, ErrCodes::InvalidA
56constexpr ResultCode ERR_INVALID_ADDRESS_STATE(ErrorModule::Kernel, ErrCodes::InvalidMemoryState); 57constexpr ResultCode ERR_INVALID_ADDRESS_STATE(ErrorModule::Kernel, ErrCodes::InvalidMemoryState);
57constexpr ResultCode ERR_INVALID_MEMORY_PERMISSIONS(ErrorModule::Kernel, 58constexpr ResultCode ERR_INVALID_MEMORY_PERMISSIONS(ErrorModule::Kernel,
58 ErrCodes::InvalidMemoryPermissions); 59 ErrCodes::InvalidMemoryPermissions);
60constexpr ResultCode ERR_INVALID_MEMORY_RANGE(ErrorModule::Kernel, ErrCodes::InvalidMemoryRange);
59constexpr ResultCode ERR_INVALID_HANDLE(ErrorModule::Kernel, ErrCodes::InvalidHandle); 61constexpr ResultCode ERR_INVALID_HANDLE(ErrorModule::Kernel, ErrCodes::InvalidHandle);
60constexpr ResultCode ERR_INVALID_PROCESSOR_ID(ErrorModule::Kernel, ErrCodes::InvalidProcessorId); 62constexpr ResultCode ERR_INVALID_PROCESSOR_ID(ErrorModule::Kernel, ErrCodes::InvalidProcessorId);
61constexpr ResultCode ERR_INVALID_SIZE(ErrorModule::Kernel, ErrCodes::InvalidSize); 63constexpr ResultCode ERR_INVALID_SIZE(ErrorModule::Kernel, ErrCodes::InvalidSize);
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 e5dd43275..863ecfa74 100644
--- a/src/core/hle/kernel/svc.cpp
+++ b/src/core/hle/kernel/svc.cpp
@@ -39,6 +39,73 @@ namespace {
39constexpr bool Is4KBAligned(VAddr address) { 39constexpr bool Is4KBAligned(VAddr address) {
40 return (address & 0xFFF) == 0; 40 return (address & 0xFFF) == 0;
41} 41}
42
43// Checks if address + size is greater than the given address
44// This can return false if the size causes an overflow of a 64-bit type
45// or if the given size is zero.
46constexpr bool IsValidAddressRange(VAddr address, u64 size) {
47 return address + size > address;
48}
49
50// Checks if a given address range lies within a larger address range.
51constexpr bool IsInsideAddressRange(VAddr address, u64 size, VAddr address_range_begin,
52 VAddr address_range_end) {
53 const VAddr end_address = address + size - 1;
54 return address_range_begin <= address && end_address <= address_range_end - 1;
55}
56
57bool IsInsideAddressSpace(const VMManager& vm, VAddr address, u64 size) {
58 return IsInsideAddressRange(address, size, vm.GetAddressSpaceBaseAddress(),
59 vm.GetAddressSpaceEndAddress());
60}
61
62bool IsInsideNewMapRegion(const VMManager& vm, VAddr address, u64 size) {
63 return IsInsideAddressRange(address, size, vm.GetNewMapRegionBaseAddress(),
64 vm.GetNewMapRegionEndAddress());
65}
66
67// Helper function that performs the common sanity checks for svcMapMemory
68// and svcUnmapMemory. This is doable, as both functions perform their sanitizing
69// in the same order.
70ResultCode MapUnmapMemorySanityChecks(const VMManager& vm_manager, VAddr dst_addr, VAddr src_addr,
71 u64 size) {
72 if (!Is4KBAligned(dst_addr) || !Is4KBAligned(src_addr)) {
73 return ERR_INVALID_ADDRESS;
74 }
75
76 if (size == 0 || !Is4KBAligned(size)) {
77 return ERR_INVALID_SIZE;
78 }
79
80 if (!IsValidAddressRange(dst_addr, size)) {
81 return ERR_INVALID_ADDRESS_STATE;
82 }
83
84 if (!IsValidAddressRange(src_addr, size)) {
85 return ERR_INVALID_ADDRESS_STATE;
86 }
87
88 if (!IsInsideAddressSpace(vm_manager, src_addr, size)) {
89 return ERR_INVALID_ADDRESS_STATE;
90 }
91
92 if (!IsInsideNewMapRegion(vm_manager, dst_addr, size)) {
93 return ERR_INVALID_MEMORY_RANGE;
94 }
95
96 const VAddr dst_end_address = dst_addr + size;
97 if (dst_end_address > vm_manager.GetHeapRegionBaseAddress() &&
98 dst_addr < vm_manager.GetHeapRegionEndAddress()) {
99 return ERR_INVALID_MEMORY_RANGE;
100 }
101
102 if (dst_end_address > vm_manager.GetNewMapRegionBaseAddress() &&
103 dst_addr < vm_manager.GetMapRegionEndAddress()) {
104 return ERR_INVALID_MEMORY_RANGE;
105 }
106
107 return RESULT_SUCCESS;
108}
42} // Anonymous namespace 109} // Anonymous namespace
43 110
44/// Set the process heap to a given Size. It can both extend and shrink the heap. 111/// Set the process heap to a given Size. It can both extend and shrink the heap.
@@ -69,15 +136,15 @@ static ResultCode MapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
69 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr, 136 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
70 src_addr, size); 137 src_addr, size);
71 138
72 if (!Is4KBAligned(dst_addr) || !Is4KBAligned(src_addr)) { 139 auto* const current_process = Core::CurrentProcess();
73 return ERR_INVALID_ADDRESS; 140 const auto& vm_manager = current_process->VMManager();
74 }
75 141
76 if (size == 0 || !Is4KBAligned(size)) { 142 const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
77 return ERR_INVALID_SIZE; 143 if (result != RESULT_SUCCESS) {
144 return result;
78 } 145 }
79 146
80 return Core::CurrentProcess()->MirrorMemory(dst_addr, src_addr, size); 147 return current_process->MirrorMemory(dst_addr, src_addr, size);
81} 148}
82 149
83/// Unmaps a region that was previously mapped with svcMapMemory 150/// Unmaps a region that was previously mapped with svcMapMemory
@@ -85,15 +152,15 @@ static ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
85 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr, 152 LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
86 src_addr, size); 153 src_addr, size);
87 154
88 if (!Is4KBAligned(dst_addr) || !Is4KBAligned(src_addr)) { 155 auto* const current_process = Core::CurrentProcess();
89 return ERR_INVALID_ADDRESS; 156 const auto& vm_manager = current_process->VMManager();
90 }
91 157
92 if (size == 0 || !Is4KBAligned(size)) { 158 const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
93 return ERR_INVALID_SIZE; 159 if (result != RESULT_SUCCESS) {
160 return result;
94 } 161 }
95 162
96 return Core::CurrentProcess()->UnmapMemory(dst_addr, src_addr, size); 163 return current_process->UnmapMemory(dst_addr, src_addr, size);
97} 164}
98 165
99/// Connect to an OS service given the port name, returns the handle to the port to out 166/// Connect to an OS service given the port name, returns the handle to the port to out
@@ -341,7 +408,7 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
341 LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id, 408 LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
342 info_sub_id, handle); 409 info_sub_id, handle);
343 410
344 const auto& current_process = Core::CurrentProcess(); 411 const auto* current_process = Core::CurrentProcess();
345 const auto& vm_manager = current_process->VMManager(); 412 const auto& vm_manager = current_process->VMManager();
346 413
347 switch (static_cast<GetInfoType>(info_id)) { 414 switch (static_cast<GetInfoType>(info_id)) {
@@ -439,7 +506,7 @@ static ResultCode GetThreadContext(VAddr thread_context, Handle handle) {
439 return ERR_INVALID_HANDLE; 506 return ERR_INVALID_HANDLE;
440 } 507 }
441 508
442 const auto current_process = Core::CurrentProcess(); 509 const auto* current_process = Core::CurrentProcess();
443 if (thread->GetOwnerProcess() != current_process) { 510 if (thread->GetOwnerProcess() != current_process) {
444 return ERR_INVALID_HANDLE; 511 return ERR_INVALID_HANDLE;
445 } 512 }
@@ -531,7 +598,7 @@ static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 s
531 return ERR_INVALID_HANDLE; 598 return ERR_INVALID_HANDLE;
532 } 599 }
533 600
534 return shared_memory->Map(Core::CurrentProcess().get(), addr, permissions_type, 601 return shared_memory->Map(Core::CurrentProcess(), addr, permissions_type,
535 MemoryPermission::DontCare); 602 MemoryPermission::DontCare);
536} 603}
537 604
@@ -550,7 +617,7 @@ static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64
550 auto& kernel = Core::System::GetInstance().Kernel(); 617 auto& kernel = Core::System::GetInstance().Kernel();
551 auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle); 618 auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
552 619
553 return shared_memory->Unmap(Core::CurrentProcess().get(), addr); 620 return shared_memory->Unmap(Core::CurrentProcess(), addr);
554} 621}
555 622
556/// Query process memory 623/// Query process memory
@@ -588,7 +655,7 @@ static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAdd
588 655
589/// Exits the current process 656/// Exits the current process
590static void ExitProcess() { 657static void ExitProcess() {
591 auto& current_process = Core::CurrentProcess(); 658 auto* current_process = Core::CurrentProcess();
592 659
593 LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID()); 660 LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
594 ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running, 661 ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
@@ -636,7 +703,7 @@ static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, V
636 auto& kernel = Core::System::GetInstance().Kernel(); 703 auto& kernel = Core::System::GetInstance().Kernel();
637 CASCADE_RESULT(SharedPtr<Thread> thread, 704 CASCADE_RESULT(SharedPtr<Thread> thread,
638 Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top, 705 Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top,
639 Core::CurrentProcess())); 706 *Core::CurrentProcess()));
640 const auto new_guest_handle = kernel.HandleTable().Create(thread); 707 const auto new_guest_handle = kernel.HandleTable().Create(thread);
641 if (new_guest_handle.Failed()) { 708 if (new_guest_handle.Failed()) {
642 return new_guest_handle.Code(); 709 return new_guest_handle.Code();
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 8e514cf9a..352ce1725 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -183,18 +183,15 @@ void Thread::ResumeFromWait() {
183 */ 183 */
184static void ResetThreadContext(Core::ARM_Interface::ThreadContext& context, VAddr stack_top, 184static void ResetThreadContext(Core::ARM_Interface::ThreadContext& context, VAddr stack_top,
185 VAddr entry_point, u64 arg) { 185 VAddr entry_point, u64 arg) {
186 memset(&context, 0, sizeof(Core::ARM_Interface::ThreadContext)); 186 context = {};
187
188 context.cpu_registers[0] = arg; 187 context.cpu_registers[0] = arg;
189 context.pc = entry_point; 188 context.pc = entry_point;
190 context.sp = stack_top; 189 context.sp = stack_top;
191 context.pstate = 0;
192 context.fpcr = 0;
193} 190}
194 191
195ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point, 192ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point,
196 u32 priority, u64 arg, s32 processor_id, 193 u32 priority, u64 arg, s32 processor_id,
197 VAddr stack_top, SharedPtr<Process> owner_process) { 194 VAddr stack_top, Process& owner_process) {
198 // Check if priority is in ranged. Lowest priority -> highest priority id. 195 // Check if priority is in ranged. Lowest priority -> highest priority id.
199 if (priority > THREADPRIO_LOWEST) { 196 if (priority > THREADPRIO_LOWEST) {
200 LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority); 197 LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
@@ -208,7 +205,7 @@ ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name
208 205
209 // TODO(yuriks): Other checks, returning 0xD9001BEA 206 // TODO(yuriks): Other checks, returning 0xD9001BEA
210 207
211 if (!Memory::IsValidVirtualAddress(*owner_process, entry_point)) { 208 if (!Memory::IsValidVirtualAddress(owner_process, entry_point)) {
212 LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point); 209 LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
213 // TODO (bunnei): Find the correct error code to use here 210 // TODO (bunnei): Find the correct error code to use here
214 return ResultCode(-1); 211 return ResultCode(-1);
@@ -232,7 +229,7 @@ ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name
232 thread->wait_handle = 0; 229 thread->wait_handle = 0;
233 thread->name = std::move(name); 230 thread->name = std::move(name);
234 thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap(); 231 thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap();
235 thread->owner_process = owner_process; 232 thread->owner_process = &owner_process;
236 thread->scheduler = Core::System::GetInstance().Scheduler(processor_id).get(); 233 thread->scheduler = Core::System::GetInstance().Scheduler(processor_id).get();
237 thread->scheduler->AddThread(thread, priority); 234 thread->scheduler->AddThread(thread, priority);
238 thread->tls_address = thread->owner_process->MarkNextAvailableTLSSlotAsUsed(*thread); 235 thread->tls_address = thread->owner_process->MarkNextAvailableTLSSlotAsUsed(*thread);
@@ -264,7 +261,7 @@ SharedPtr<Thread> SetupMainThread(KernelCore& kernel, VAddr entry_point, u32 pri
264 // Initialize new "main" thread 261 // Initialize new "main" thread
265 const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress(); 262 const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress();
266 auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0, THREADPROCESSORID_0, 263 auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0, THREADPROCESSORID_0,
267 stack_top, &owner_process); 264 stack_top, owner_process);
268 265
269 SharedPtr<Thread> thread = std::move(thread_res).Unwrap(); 266 SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
270 267
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/hle/service/audio/hwopus.cpp b/src/core/hle/service/audio/hwopus.cpp
index fc6067e59..7168c6a10 100644
--- a/src/core/hle/service/audio/hwopus.cpp
+++ b/src/core/hle/service/audio/hwopus.cpp
@@ -2,8 +2,10 @@
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 <chrono>
5#include <cstring> 6#include <cstring>
6#include <memory> 7#include <memory>
8#include <optional>
7#include <vector> 9#include <vector>
8 10
9#include <opus.h> 11#include <opus.h>
@@ -33,7 +35,8 @@ public:
33 {1, nullptr, "SetContext"}, 35 {1, nullptr, "SetContext"},
34 {2, nullptr, "DecodeInterleavedForMultiStream"}, 36 {2, nullptr, "DecodeInterleavedForMultiStream"},
35 {3, nullptr, "SetContextForMultiStream"}, 37 {3, nullptr, "SetContextForMultiStream"},
36 {4, nullptr, "Unknown4"}, 38 {4, &IHardwareOpusDecoderManager::DecodeInterleavedWithPerformance,
39 "DecodeInterleavedWithPerformance"},
37 {5, nullptr, "Unknown5"}, 40 {5, nullptr, "Unknown5"},
38 {6, nullptr, "Unknown6"}, 41 {6, nullptr, "Unknown6"},
39 {7, nullptr, "Unknown7"}, 42 {7, nullptr, "Unknown7"},
@@ -59,8 +62,31 @@ private:
59 ctx.WriteBuffer(samples.data(), samples.size() * sizeof(s16)); 62 ctx.WriteBuffer(samples.data(), samples.size() * sizeof(s16));
60 } 63 }
61 64
62 bool Decoder_DecodeInterleaved(u32& consumed, u32& sample_count, const std::vector<u8>& input, 65 void DecodeInterleavedWithPerformance(Kernel::HLERequestContext& ctx) {
63 std::vector<opus_int16>& output) { 66 u32 consumed = 0;
67 u32 sample_count = 0;
68 u64 performance = 0;
69 std::vector<opus_int16> samples(ctx.GetWriteBufferSize() / sizeof(opus_int16));
70 if (!Decoder_DecodeInterleaved(consumed, sample_count, ctx.ReadBuffer(), samples,
71 performance)) {
72 IPC::ResponseBuilder rb{ctx, 2};
73 // TODO(ogniK): Use correct error code
74 rb.Push(ResultCode(-1));
75 return;
76 }
77 IPC::ResponseBuilder rb{ctx, 6};
78 rb.Push(RESULT_SUCCESS);
79 rb.Push<u32>(consumed);
80 rb.Push<u64>(performance);
81 rb.Push<u32>(sample_count);
82 ctx.WriteBuffer(samples.data(), samples.size() * sizeof(s16));
83 }
84
85 bool Decoder_DecodeInterleaved(
86 u32& consumed, u32& sample_count, const std::vector<u8>& input,
87 std::vector<opus_int16>& output,
88 std::optional<std::reference_wrapper<u64>> performance_time = std::nullopt) {
89 const auto start_time = std::chrono::high_resolution_clock::now();
64 std::size_t raw_output_sz = output.size() * sizeof(opus_int16); 90 std::size_t raw_output_sz = output.size() * sizeof(opus_int16);
65 if (sizeof(OpusHeader) > input.size()) 91 if (sizeof(OpusHeader) > input.size())
66 return false; 92 return false;
@@ -80,8 +106,13 @@ private:
80 (static_cast<int>(raw_output_sz / sizeof(s16) / channel_count)), 0); 106 (static_cast<int>(raw_output_sz / sizeof(s16) / channel_count)), 0);
81 if (out_sample_count < 0) 107 if (out_sample_count < 0)
82 return false; 108 return false;
109 const auto end_time = std::chrono::high_resolution_clock::now() - start_time;
83 sample_count = out_sample_count; 110 sample_count = out_sample_count;
84 consumed = static_cast<u32>(sizeof(OpusHeader) + hdr.sz); 111 consumed = static_cast<u32>(sizeof(OpusHeader) + hdr.sz);
112 if (performance_time.has_value()) {
113 performance_time->get() =
114 std::chrono::duration_cast<std::chrono::milliseconds>(end_time).count();
115 }
85 return true; 116 return true;
86 } 117 }
87 118
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp b/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp
index 7555bbe7d..c41ef7058 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp
@@ -15,6 +15,11 @@
15#include "video_core/renderer_base.h" 15#include "video_core/renderer_base.h"
16 16
17namespace Service::Nvidia::Devices { 17namespace Service::Nvidia::Devices {
18namespace NvErrCodes {
19enum {
20 InvalidNmapHandle = -22,
21};
22}
18 23
19nvhost_as_gpu::nvhost_as_gpu(std::shared_ptr<nvmap> nvmap_dev) : nvmap_dev(std::move(nvmap_dev)) {} 24nvhost_as_gpu::nvhost_as_gpu(std::shared_ptr<nvmap> nvmap_dev) : nvmap_dev(std::move(nvmap_dev)) {}
20nvhost_as_gpu::~nvhost_as_gpu() = default; 25nvhost_as_gpu::~nvhost_as_gpu() = default;
@@ -79,14 +84,16 @@ u32 nvhost_as_gpu::Remap(const std::vector<u8>& input, std::vector<u8>& output)
79 std::memcpy(entries.data(), input.data(), input.size()); 84 std::memcpy(entries.data(), input.data(), input.size());
80 85
81 auto& gpu = Core::System::GetInstance().GPU(); 86 auto& gpu = Core::System::GetInstance().GPU();
82
83 for (const auto& entry : entries) { 87 for (const auto& entry : entries) {
84 LOG_WARNING(Service_NVDRV, "remap entry, offset=0x{:X} handle=0x{:X} pages=0x{:X}", 88 LOG_WARNING(Service_NVDRV, "remap entry, offset=0x{:X} handle=0x{:X} pages=0x{:X}",
85 entry.offset, entry.nvmap_handle, entry.pages); 89 entry.offset, entry.nvmap_handle, entry.pages);
86 Tegra::GPUVAddr offset = static_cast<Tegra::GPUVAddr>(entry.offset) << 0x10; 90 Tegra::GPUVAddr offset = static_cast<Tegra::GPUVAddr>(entry.offset) << 0x10;
87
88 auto object = nvmap_dev->GetObject(entry.nvmap_handle); 91 auto object = nvmap_dev->GetObject(entry.nvmap_handle);
89 ASSERT(object); 92 if (!object) {
93 LOG_CRITICAL(Service_NVDRV, "nvmap {} is an invalid handle!", entry.nvmap_handle);
94 std::memcpy(output.data(), entries.data(), output.size());
95 return static_cast<u32>(NvErrCodes::InvalidNmapHandle);
96 }
90 97
91 ASSERT(object->status == nvmap::Object::Status::Allocated); 98 ASSERT(object->status == nvmap::Object::Status::Allocated);
92 99
@@ -167,10 +174,11 @@ u32 nvhost_as_gpu::UnmapBuffer(const std::vector<u8>& input, std::vector<u8>& ou
167 auto& system_instance = Core::System::GetInstance(); 174 auto& system_instance = Core::System::GetInstance();
168 175
169 // Remove this memory region from the rasterizer cache. 176 // Remove this memory region from the rasterizer cache.
170 system_instance.Renderer().Rasterizer().FlushAndInvalidateRegion(params.offset,
171 itr->second.size);
172
173 auto& gpu = system_instance.GPU(); 177 auto& gpu = system_instance.GPU();
178 auto cpu_addr = gpu.MemoryManager().GpuToCpuAddress(params.offset);
179 ASSERT(cpu_addr);
180 system_instance.Renderer().Rasterizer().FlushAndInvalidateRegion(*cpu_addr, itr->second.size);
181
174 params.offset = gpu.MemoryManager().UnmapBuffer(params.offset, itr->second.size); 182 params.offset = gpu.MemoryManager().UnmapBuffer(params.offset, itr->second.size);
175 183
176 buffer_mappings.erase(itr->second.offset); 184 buffer_mappings.erase(itr->second.offset);
diff --git a/src/core/hle/service/nvdrv/devices/nvmap.cpp b/src/core/hle/service/nvdrv/devices/nvmap.cpp
index a2287cc1b..43651d8a6 100644
--- a/src/core/hle/service/nvdrv/devices/nvmap.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvmap.cpp
@@ -11,6 +11,13 @@
11 11
12namespace Service::Nvidia::Devices { 12namespace Service::Nvidia::Devices {
13 13
14namespace NvErrCodes {
15enum {
16 OperationNotPermitted = -1,
17 InvalidValue = -22,
18};
19}
20
14nvmap::nvmap() = default; 21nvmap::nvmap() = default;
15nvmap::~nvmap() = default; 22nvmap::~nvmap() = default;
16 23
@@ -44,7 +51,11 @@ u32 nvmap::ioctl(Ioctl command, const std::vector<u8>& input, std::vector<u8>& o
44u32 nvmap::IocCreate(const std::vector<u8>& input, std::vector<u8>& output) { 51u32 nvmap::IocCreate(const std::vector<u8>& input, std::vector<u8>& output) {
45 IocCreateParams params; 52 IocCreateParams params;
46 std::memcpy(&params, input.data(), sizeof(params)); 53 std::memcpy(&params, input.data(), sizeof(params));
54 LOG_DEBUG(Service_NVDRV, "size=0x{:08X}", params.size);
47 55
56 if (!params.size) {
57 return static_cast<u32>(NvErrCodes::InvalidValue);
58 }
48 // Create a new nvmap object and obtain a handle to it. 59 // Create a new nvmap object and obtain a handle to it.
49 auto object = std::make_shared<Object>(); 60 auto object = std::make_shared<Object>();
50 object->id = next_id++; 61 object->id = next_id++;
@@ -55,8 +66,6 @@ u32 nvmap::IocCreate(const std::vector<u8>& input, std::vector<u8>& output) {
55 u32 handle = next_handle++; 66 u32 handle = next_handle++;
56 handles[handle] = std::move(object); 67 handles[handle] = std::move(object);
57 68
58 LOG_DEBUG(Service_NVDRV, "size=0x{:08X}", params.size);
59
60 params.handle = handle; 69 params.handle = handle;
61 70
62 std::memcpy(output.data(), &params, sizeof(params)); 71 std::memcpy(output.data(), &params, sizeof(params));
@@ -66,9 +75,29 @@ u32 nvmap::IocCreate(const std::vector<u8>& input, std::vector<u8>& output) {
66u32 nvmap::IocAlloc(const std::vector<u8>& input, std::vector<u8>& output) { 75u32 nvmap::IocAlloc(const std::vector<u8>& input, std::vector<u8>& output) {
67 IocAllocParams params; 76 IocAllocParams params;
68 std::memcpy(&params, input.data(), sizeof(params)); 77 std::memcpy(&params, input.data(), sizeof(params));
78 LOG_DEBUG(Service_NVDRV, "called, addr={:X}", params.addr);
79
80 if (!params.handle) {
81 return static_cast<u32>(NvErrCodes::InvalidValue);
82 }
83
84 if ((params.align - 1) & params.align) {
85 return static_cast<u32>(NvErrCodes::InvalidValue);
86 }
87
88 const u32 min_alignment = 0x1000;
89 if (params.align < min_alignment) {
90 params.align = min_alignment;
91 }
69 92
70 auto object = GetObject(params.handle); 93 auto object = GetObject(params.handle);
71 ASSERT(object); 94 if (!object) {
95 return static_cast<u32>(NvErrCodes::InvalidValue);
96 }
97
98 if (object->status == Object::Status::Allocated) {
99 return static_cast<u32>(NvErrCodes::OperationNotPermitted);
100 }
72 101
73 object->flags = params.flags; 102 object->flags = params.flags;
74 object->align = params.align; 103 object->align = params.align;
@@ -76,8 +105,6 @@ u32 nvmap::IocAlloc(const std::vector<u8>& input, std::vector<u8>& output) {
76 object->addr = params.addr; 105 object->addr = params.addr;
77 object->status = Object::Status::Allocated; 106 object->status = Object::Status::Allocated;
78 107
79 LOG_DEBUG(Service_NVDRV, "called, addr={:X}", params.addr);
80
81 std::memcpy(output.data(), &params, sizeof(params)); 108 std::memcpy(output.data(), &params, sizeof(params));
82 return 0; 109 return 0;
83} 110}
@@ -88,8 +115,14 @@ u32 nvmap::IocGetId(const std::vector<u8>& input, std::vector<u8>& output) {
88 115
89 LOG_WARNING(Service_NVDRV, "called"); 116 LOG_WARNING(Service_NVDRV, "called");
90 117
118 if (!params.handle) {
119 return static_cast<u32>(NvErrCodes::InvalidValue);
120 }
121
91 auto object = GetObject(params.handle); 122 auto object = GetObject(params.handle);
92 ASSERT(object); 123 if (!object) {
124 return static_cast<u32>(NvErrCodes::OperationNotPermitted);
125 }
93 126
94 params.id = object->id; 127 params.id = object->id;
95 128
@@ -105,7 +138,14 @@ u32 nvmap::IocFromId(const std::vector<u8>& input, std::vector<u8>& output) {
105 138
106 auto itr = std::find_if(handles.begin(), handles.end(), 139 auto itr = std::find_if(handles.begin(), handles.end(),
107 [&](const auto& entry) { return entry.second->id == params.id; }); 140 [&](const auto& entry) { return entry.second->id == params.id; });
108 ASSERT(itr != handles.end()); 141 if (itr == handles.end()) {
142 return static_cast<u32>(NvErrCodes::InvalidValue);
143 }
144
145 auto& object = itr->second;
146 if (object->status != Object::Status::Allocated) {
147 return static_cast<u32>(NvErrCodes::InvalidValue);
148 }
109 149
110 itr->second->refcount++; 150 itr->second->refcount++;
111 151
@@ -125,8 +165,13 @@ u32 nvmap::IocParam(const std::vector<u8>& input, std::vector<u8>& output) {
125 LOG_WARNING(Service_NVDRV, "(STUBBED) called type={}", params.param); 165 LOG_WARNING(Service_NVDRV, "(STUBBED) called type={}", params.param);
126 166
127 auto object = GetObject(params.handle); 167 auto object = GetObject(params.handle);
128 ASSERT(object); 168 if (!object) {
129 ASSERT(object->status == Object::Status::Allocated); 169 return static_cast<u32>(NvErrCodes::InvalidValue);
170 }
171
172 if (object->status != Object::Status::Allocated) {
173 return static_cast<u32>(NvErrCodes::OperationNotPermitted);
174 }
130 175
131 switch (static_cast<ParamTypes>(params.param)) { 176 switch (static_cast<ParamTypes>(params.param)) {
132 case ParamTypes::Size: 177 case ParamTypes::Size:
@@ -163,9 +208,12 @@ u32 nvmap::IocFree(const std::vector<u8>& input, std::vector<u8>& output) {
163 LOG_WARNING(Service_NVDRV, "(STUBBED) called"); 208 LOG_WARNING(Service_NVDRV, "(STUBBED) called");
164 209
165 auto itr = handles.find(params.handle); 210 auto itr = handles.find(params.handle);
166 ASSERT(itr != handles.end()); 211 if (itr == handles.end()) {
167 212 return static_cast<u32>(NvErrCodes::InvalidValue);
168 ASSERT(itr->second->refcount > 0); 213 }
214 if (!itr->second->refcount) {
215 return static_cast<u32>(NvErrCodes::InvalidValue);
216 }
169 217
170 itr->second->refcount--; 218 itr->second->refcount--;
171 219
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/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/fermi_2d.h b/src/video_core/engines/fermi_2d.h
index 81d15c62a..2a6e8bbbb 100644
--- a/src/video_core/engines/fermi_2d.h
+++ b/src/video_core/engines/fermi_2d.h
@@ -36,9 +36,9 @@ public:
36 RenderTargetFormat format; 36 RenderTargetFormat format;
37 BitField<0, 1, u32> linear; 37 BitField<0, 1, u32> linear;
38 union { 38 union {
39 BitField<0, 4, u32> block_depth; 39 BitField<0, 4, u32> block_width;
40 BitField<4, 4, u32> block_height; 40 BitField<4, 4, u32> block_height;
41 BitField<8, 4, u32> block_width; 41 BitField<8, 4, u32> block_depth;
42 }; 42 };
43 u32 depth; 43 u32 depth;
44 u32 layer; 44 u32 layer;
@@ -53,10 +53,20 @@ public:
53 address_low); 53 address_low);
54 } 54 }
55 55
56 u32 BlockWidth() const {
57 // The block width is stored in log2 format.
58 return 1 << block_width;
59 }
60
56 u32 BlockHeight() const { 61 u32 BlockHeight() const {
57 // The block height is stored in log2 format. 62 // The block height is stored in log2 format.
58 return 1 << block_height; 63 return 1 << block_height;
59 } 64 }
65
66 u32 BlockDepth() const {
67 // The block depth is stored in log2 format.
68 return 1 << block_depth;
69 }
60 }; 70 };
61 static_assert(sizeof(Surface) == 0x28, "Surface has incorrect size"); 71 static_assert(sizeof(Surface) == 0x28, "Surface has incorrect size");
62 72
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index 4290da33f..c8d1b6478 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -347,6 +347,16 @@ public:
347 DecrWrap = 8, 347 DecrWrap = 8,
348 }; 348 };
349 349
350 enum class MemoryLayout : u32 {
351 Linear = 0,
352 BlockLinear = 1,
353 };
354
355 enum class InvMemoryLayout : u32 {
356 BlockLinear = 0,
357 Linear = 1,
358 };
359
350 struct Cull { 360 struct Cull {
351 enum class FrontFace : u32 { 361 enum class FrontFace : u32 {
352 ClockWise = 0x0900, 362 ClockWise = 0x0900,
@@ -432,7 +442,12 @@ public:
432 u32 width; 442 u32 width;
433 u32 height; 443 u32 height;
434 Tegra::RenderTargetFormat format; 444 Tegra::RenderTargetFormat format;
435 u32 block_dimensions; 445 union {
446 BitField<0, 3, u32> block_width;
447 BitField<4, 3, u32> block_height;
448 BitField<8, 3, u32> block_depth;
449 BitField<12, 1, InvMemoryLayout> type;
450 } memory_layout;
436 u32 array_mode; 451 u32 array_mode;
437 u32 layer_stride; 452 u32 layer_stride;
438 u32 base_layer; 453 u32 base_layer;
@@ -532,7 +547,21 @@ public:
532 INSERT_PADDING_WORDS(0x3); 547 INSERT_PADDING_WORDS(0x3);
533 s32 clear_stencil; 548 s32 clear_stencil;
534 549
535 INSERT_PADDING_WORDS(0x6C); 550 INSERT_PADDING_WORDS(0x17);
551
552 struct {
553 u32 enable;
554 union {
555 BitField<0, 16, u32> min_x;
556 BitField<16, 16, u32> max_x;
557 };
558 union {
559 BitField<0, 16, u32> min_y;
560 BitField<16, 16, u32> max_y;
561 };
562 } scissor_test;
563
564 INSERT_PADDING_WORDS(0x52);
536 565
537 s32 stencil_back_func_ref; 566 s32 stencil_back_func_ref;
538 u32 stencil_back_mask; 567 u32 stencil_back_mask;
@@ -548,7 +577,12 @@ public:
548 u32 address_high; 577 u32 address_high;
549 u32 address_low; 578 u32 address_low;
550 Tegra::DepthFormat format; 579 Tegra::DepthFormat format;
551 u32 block_dimensions; 580 union {
581 BitField<0, 4, u32> block_width;
582 BitField<4, 4, u32> block_height;
583 BitField<8, 4, u32> block_depth;
584 BitField<20, 1, InvMemoryLayout> type;
585 } memory_layout;
552 u32 layer_stride; 586 u32 layer_stride;
553 587
554 GPUVAddr Address() const { 588 GPUVAddr Address() const {
@@ -1002,6 +1036,7 @@ ASSERT_REG_POSITION(vertex_buffer, 0x35D);
1002ASSERT_REG_POSITION(clear_color[0], 0x360); 1036ASSERT_REG_POSITION(clear_color[0], 0x360);
1003ASSERT_REG_POSITION(clear_depth, 0x364); 1037ASSERT_REG_POSITION(clear_depth, 0x364);
1004ASSERT_REG_POSITION(clear_stencil, 0x368); 1038ASSERT_REG_POSITION(clear_stencil, 0x368);
1039ASSERT_REG_POSITION(scissor_test, 0x380);
1005ASSERT_REG_POSITION(stencil_back_func_ref, 0x3D5); 1040ASSERT_REG_POSITION(stencil_back_func_ref, 0x3D5);
1006ASSERT_REG_POSITION(stencil_back_mask, 0x3D6); 1041ASSERT_REG_POSITION(stencil_back_mask, 0x3D6);
1007ASSERT_REG_POSITION(stencil_back_func_mask, 0x3D7); 1042ASSERT_REG_POSITION(stencil_back_func_mask, 0x3D7);
diff --git a/src/video_core/engines/shader_bytecode.h b/src/video_core/engines/shader_bytecode.h
index b1f137b9c..9a59b65b3 100644
--- a/src/video_core/engines/shader_bytecode.h
+++ b/src/video_core/engines/shader_bytecode.h
@@ -214,6 +214,18 @@ enum class IMinMaxExchange : u64 {
214 XHi = 3, 214 XHi = 3,
215}; 215};
216 216
217enum class VmadType : u64 {
218 Size16_Low = 0,
219 Size16_High = 1,
220 Size32 = 2,
221 Invalid = 3,
222};
223
224enum class VmadShr : u64 {
225 Shr7 = 1,
226 Shr15 = 2,
227};
228
217enum class XmadMode : u64 { 229enum class XmadMode : u64 {
218 None = 0, 230 None = 0,
219 CLo = 1, 231 CLo = 1,
@@ -314,6 +326,15 @@ enum class TextureMiscMode : u64 {
314 PTP, 326 PTP,
315}; 327};
316 328
329enum class IsberdMode : u64 {
330 None = 0,
331 Patch = 1,
332 Prim = 2,
333 Attr = 3,
334};
335
336enum class IsberdShift : u64 { None = 0, U16 = 1, B32 = 2 };
337
317enum class IpaInterpMode : u64 { 338enum class IpaInterpMode : u64 {
318 Linear = 0, 339 Linear = 0,
319 Perspective = 1, 340 Perspective = 1,
@@ -340,6 +361,87 @@ struct IpaMode {
340 } 361 }
341}; 362};
342 363
364enum class SystemVariable : u64 {
365 LaneId = 0x00,
366 VirtCfg = 0x02,
367 VirtId = 0x03,
368 Pm0 = 0x04,
369 Pm1 = 0x05,
370 Pm2 = 0x06,
371 Pm3 = 0x07,
372 Pm4 = 0x08,
373 Pm5 = 0x09,
374 Pm6 = 0x0a,
375 Pm7 = 0x0b,
376 OrderingTicket = 0x0f,
377 PrimType = 0x10,
378 InvocationId = 0x11,
379 Ydirection = 0x12,
380 ThreadKill = 0x13,
381 ShaderType = 0x14,
382 DirectBeWriteAddressLow = 0x15,
383 DirectBeWriteAddressHigh = 0x16,
384 DirectBeWriteEnabled = 0x17,
385 MachineId0 = 0x18,
386 MachineId1 = 0x19,
387 MachineId2 = 0x1a,
388 MachineId3 = 0x1b,
389 Affinity = 0x1c,
390 InvocationInfo = 0x1d,
391 WscaleFactorXY = 0x1e,
392 WscaleFactorZ = 0x1f,
393 Tid = 0x20,
394 TidX = 0x21,
395 TidY = 0x22,
396 TidZ = 0x23,
397 CtaParam = 0x24,
398 CtaIdX = 0x25,
399 CtaIdY = 0x26,
400 CtaIdZ = 0x27,
401 NtId = 0x28,
402 CirQueueIncrMinusOne = 0x29,
403 Nlatc = 0x2a,
404 SmSpaVersion = 0x2c,
405 MultiPassShaderInfo = 0x2d,
406 LwinHi = 0x2e,
407 SwinHi = 0x2f,
408 SwinLo = 0x30,
409 SwinSz = 0x31,
410 SmemSz = 0x32,
411 SmemBanks = 0x33,
412 LwinLo = 0x34,
413 LwinSz = 0x35,
414 LmemLosz = 0x36,
415 LmemHioff = 0x37,
416 EqMask = 0x38,
417 LtMask = 0x39,
418 LeMask = 0x3a,
419 GtMask = 0x3b,
420 GeMask = 0x3c,
421 RegAlloc = 0x3d,
422 CtxAddr = 0x3e, // .fmask = F_SM50
423 BarrierAlloc = 0x3e, // .fmask = F_SM60
424 GlobalErrorStatus = 0x40,
425 WarpErrorStatus = 0x42,
426 WarpErrorStatusClear = 0x43,
427 PmHi0 = 0x48,
428 PmHi1 = 0x49,
429 PmHi2 = 0x4a,
430 PmHi3 = 0x4b,
431 PmHi4 = 0x4c,
432 PmHi5 = 0x4d,
433 PmHi6 = 0x4e,
434 PmHi7 = 0x4f,
435 ClockLo = 0x50,
436 ClockHi = 0x51,
437 GlobalTimerLo = 0x52,
438 GlobalTimerHi = 0x53,
439 HwTaskId = 0x60,
440 CircularQueueEntryIndex = 0x61,
441 CircularQueueEntryAddressLow = 0x62,
442 CircularQueueEntryAddressHigh = 0x63,
443};
444
343union Instruction { 445union Instruction {
344 Instruction& operator=(const Instruction& instr) { 446 Instruction& operator=(const Instruction& instr) {
345 value = instr.value; 447 value = instr.value;
@@ -362,6 +464,7 @@ union Instruction {
362 BitField<48, 16, u64> opcode; 464 BitField<48, 16, u64> opcode;
363 465
364 union { 466 union {
467 BitField<20, 16, u64> imm20_16;
365 BitField<20, 19, u64> imm20_19; 468 BitField<20, 19, u64> imm20_19;
366 BitField<20, 32, s64> imm20_32; 469 BitField<20, 32, s64> imm20_32;
367 BitField<45, 1, u64> negate_b; 470 BitField<45, 1, u64> negate_b;
@@ -403,6 +506,10 @@ union Instruction {
403 } 506 }
404 } lop3; 507 } lop3;
405 508
509 u16 GetImm20_16() const {
510 return static_cast<u16>(imm20_16);
511 }
512
406 u32 GetImm20_19() const { 513 u32 GetImm20_19() const {
407 u32 imm{static_cast<u32>(imm20_19)}; 514 u32 imm{static_cast<u32>(imm20_19)};
408 imm <<= 12; 515 imm <<= 12;
@@ -915,6 +1022,35 @@ union Instruction {
915 } bra; 1022 } bra;
916 1023
917 union { 1024 union {
1025 BitField<39, 1, u64> emit; // EmitVertex
1026 BitField<40, 1, u64> cut; // EndPrimitive
1027 } out;
1028
1029 union {
1030 BitField<31, 1, u64> skew;
1031 BitField<32, 1, u64> o;
1032 BitField<33, 2, IsberdMode> mode;
1033 BitField<47, 2, IsberdShift> shift;
1034 } isberd;
1035
1036 union {
1037 BitField<48, 1, u64> signed_a;
1038 BitField<38, 1, u64> is_byte_chunk_a;
1039 BitField<36, 2, VmadType> type_a;
1040 BitField<36, 2, u64> byte_height_a;
1041
1042 BitField<49, 1, u64> signed_b;
1043 BitField<50, 1, u64> use_register_b;
1044 BitField<30, 1, u64> is_byte_chunk_b;
1045 BitField<28, 2, VmadType> type_b;
1046 BitField<28, 2, u64> byte_height_b;
1047
1048 BitField<51, 2, VmadShr> shr;
1049 BitField<55, 1, u64> saturate; // Saturates the result (a * b + c)
1050 BitField<47, 1, u64> cc;
1051 } vmad;
1052
1053 union {
918 BitField<20, 16, u64> imm20_16; 1054 BitField<20, 16, u64> imm20_16;
919 BitField<36, 1, u64> product_shift_left; 1055 BitField<36, 1, u64> product_shift_left;
920 BitField<37, 1, u64> merge_37; 1056 BitField<37, 1, u64> merge_37;
@@ -936,6 +1072,10 @@ union Instruction {
936 BitField<36, 5, u64> index; 1072 BitField<36, 5, u64> index;
937 } cbuf36; 1073 } cbuf36;
938 1074
1075 // Unsure about the size of this one.
1076 // It's always used with a gpr0, so any size should be fine.
1077 BitField<20, 8, SystemVariable> sys20;
1078
939 BitField<47, 1, u64> generates_cc; 1079 BitField<47, 1, u64> generates_cc;
940 BitField<61, 1, u64> is_b_imm; 1080 BitField<61, 1, u64> is_b_imm;
941 BitField<60, 1, u64> is_b_gpr; 1081 BitField<60, 1, u64> is_b_gpr;
@@ -975,6 +1115,9 @@ public:
975 TMML, // Texture Mip Map Level 1115 TMML, // Texture Mip Map Level
976 EXIT, 1116 EXIT,
977 IPA, 1117 IPA,
1118 OUT_R, // Emit vertex/primitive
1119 ISBERD,
1120 VMAD,
978 FFMA_IMM, // Fused Multiply and Add 1121 FFMA_IMM, // Fused Multiply and Add
979 FFMA_CR, 1122 FFMA_CR,
980 FFMA_RC, 1123 FFMA_RC,
@@ -1034,6 +1177,7 @@ public:
1034 MOV_C, 1177 MOV_C,
1035 MOV_R, 1178 MOV_R,
1036 MOV_IMM, 1179 MOV_IMM,
1180 MOV_SYS,
1037 MOV32_IMM, 1181 MOV32_IMM,
1038 SHL_C, 1182 SHL_C,
1039 SHL_R, 1183 SHL_R,
@@ -1209,6 +1353,9 @@ private:
1209 INST("1101111101011---", Id::TMML, Type::Memory, "TMML"), 1353 INST("1101111101011---", Id::TMML, Type::Memory, "TMML"),
1210 INST("111000110000----", Id::EXIT, Type::Trivial, "EXIT"), 1354 INST("111000110000----", Id::EXIT, Type::Trivial, "EXIT"),
1211 INST("11100000--------", Id::IPA, Type::Trivial, "IPA"), 1355 INST("11100000--------", Id::IPA, Type::Trivial, "IPA"),
1356 INST("1111101111100---", Id::OUT_R, Type::Trivial, "OUT_R"),
1357 INST("1110111111010---", Id::ISBERD, Type::Trivial, "ISBERD"),
1358 INST("01011111--------", Id::VMAD, Type::Trivial, "VMAD"),
1212 INST("0011001-1-------", Id::FFMA_IMM, Type::Ffma, "FFMA_IMM"), 1359 INST("0011001-1-------", Id::FFMA_IMM, Type::Ffma, "FFMA_IMM"),
1213 INST("010010011-------", Id::FFMA_CR, Type::Ffma, "FFMA_CR"), 1360 INST("010010011-------", Id::FFMA_CR, Type::Ffma, "FFMA_CR"),
1214 INST("010100011-------", Id::FFMA_RC, Type::Ffma, "FFMA_RC"), 1361 INST("010100011-------", Id::FFMA_RC, Type::Ffma, "FFMA_RC"),
@@ -1255,6 +1402,7 @@ private:
1255 INST("0100110010011---", Id::MOV_C, Type::Arithmetic, "MOV_C"), 1402 INST("0100110010011---", Id::MOV_C, Type::Arithmetic, "MOV_C"),
1256 INST("0101110010011---", Id::MOV_R, Type::Arithmetic, "MOV_R"), 1403 INST("0101110010011---", Id::MOV_R, Type::Arithmetic, "MOV_R"),
1257 INST("0011100-10011---", Id::MOV_IMM, Type::Arithmetic, "MOV_IMM"), 1404 INST("0011100-10011---", Id::MOV_IMM, Type::Arithmetic, "MOV_IMM"),
1405 INST("1111000011001---", Id::MOV_SYS, Type::Trivial, "MOV_SYS"),
1258 INST("000000010000----", Id::MOV32_IMM, Type::ArithmeticImmediate, "MOV32_IMM"), 1406 INST("000000010000----", Id::MOV32_IMM, Type::ArithmeticImmediate, "MOV32_IMM"),
1259 INST("0100110001100---", Id::FMNMX_C, Type::Arithmetic, "FMNMX_C"), 1407 INST("0100110001100---", Id::FMNMX_C, Type::Arithmetic, "FMNMX_C"),
1260 INST("0101110001100---", Id::FMNMX_R, Type::Arithmetic, "FMNMX_R"), 1408 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 209bdf181..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 {
@@ -541,6 +552,7 @@ void RasterizerOpenGL::DrawArrays() {
541 SyncLogicOpState(); 552 SyncLogicOpState();
542 SyncCullMode(); 553 SyncCullMode();
543 SyncAlphaTest(); 554 SyncAlphaTest();
555 SyncScissorTest();
544 SyncTransformFeedback(); 556 SyncTransformFeedback();
545 SyncPointState(); 557 SyncPointState();
546 558
@@ -580,7 +592,7 @@ void RasterizerOpenGL::DrawArrays() {
580 592
581 SetupVertexArrays(); 593 SetupVertexArrays();
582 DrawParameters params = SetupDraw(); 594 DrawParameters params = SetupDraw();
583 SetupShaders(); 595 SetupShaders(params.primitive_mode);
584 596
585 buffer_cache.Unmap(); 597 buffer_cache.Unmap();
586 598
@@ -719,7 +731,7 @@ void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntr
719} 731}
720 732
721u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader, 733u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
722 u32 current_bindpoint) { 734 GLenum primitive_mode, u32 current_bindpoint) {
723 MICROPROFILE_SCOPE(OpenGL_UBO); 735 MICROPROFILE_SCOPE(OpenGL_UBO);
724 const auto& gpu = Core::System::GetInstance().GPU(); 736 const auto& gpu = Core::System::GetInstance().GPU();
725 const auto& maxwell3d = gpu.Maxwell3D(); 737 const auto& maxwell3d = gpu.Maxwell3D();
@@ -771,7 +783,7 @@ u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shad
771 buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment)); 783 buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
772 784
773 // Now configure the bindpoint of the buffer inside the shader 785 // Now configure the bindpoint of the buffer inside the shader
774 glUniformBlockBinding(shader->GetProgramHandle(), 786 glUniformBlockBinding(shader->GetProgramHandle(primitive_mode),
775 shader->GetProgramResourceIndex(used_buffer), 787 shader->GetProgramResourceIndex(used_buffer),
776 current_bindpoint + bindpoint); 788 current_bindpoint + bindpoint);
777 789
@@ -787,7 +799,8 @@ u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shad
787 return current_bindpoint + static_cast<u32>(entries.size()); 799 return current_bindpoint + static_cast<u32>(entries.size());
788} 800}
789 801
790u32 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) {
791 MICROPROFILE_SCOPE(OpenGL_Texture); 804 MICROPROFILE_SCOPE(OpenGL_Texture);
792 const auto& gpu = Core::System::GetInstance().GPU(); 805 const auto& gpu = Core::System::GetInstance().GPU();
793 const auto& maxwell3d = gpu.Maxwell3D(); 806 const auto& maxwell3d = gpu.Maxwell3D();
@@ -802,8 +815,8 @@ u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
802 815
803 // Bind the uniform to the sampler. 816 // Bind the uniform to the sampler.
804 817
805 glProgramUniform1i(shader->GetProgramHandle(), shader->GetUniformLocation(entry), 818 glProgramUniform1i(shader->GetProgramHandle(primitive_mode),
806 current_bindpoint); 819 shader->GetUniformLocation(entry), current_bindpoint);
807 820
808 const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset()); 821 const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
809 822
@@ -972,6 +985,22 @@ void RasterizerOpenGL::SyncAlphaTest() {
972 } 985 }
973} 986}
974 987
988void RasterizerOpenGL::SyncScissorTest() {
989 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
990
991 state.scissor.enabled = (regs.scissor_test.enable != 0);
992 // TODO(Blinkhawk): Figure if the hardware supports scissor testing per viewport and how it's
993 // implemented.
994 if (regs.scissor_test.enable != 0) {
995 const u32 width = regs.scissor_test.max_x - regs.scissor_test.min_x;
996 const u32 height = regs.scissor_test.max_y - regs.scissor_test.min_y;
997 state.scissor.x = regs.scissor_test.min_x;
998 state.scissor.y = regs.scissor_test.min_y;
999 state.scissor.width = width;
1000 state.scissor.height = height;
1001 }
1002}
1003
975void RasterizerOpenGL::SyncTransformFeedback() { 1004void RasterizerOpenGL::SyncTransformFeedback() {
976 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs; 1005 const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
977 1006
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index 0dab2018b..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();
@@ -165,6 +165,9 @@ private:
165 /// Syncs the alpha test state to match the guest state 165 /// Syncs the alpha test state to match the guest state
166 void SyncAlphaTest(); 166 void SyncAlphaTest();
167 167
168 /// Syncs the scissor test state to match the guest state
169 void SyncScissorTest();
170
168 /// Syncs the transform feedback state to match the guest state 171 /// Syncs the transform feedback state to match the guest state
169 void SyncTransformFeedback(); 172 void SyncTransformFeedback();
170 173
@@ -207,7 +210,7 @@ private:
207 210
208 DrawParameters SetupDraw(); 211 DrawParameters SetupDraw();
209 212
210 void SetupShaders(); 213 void SetupShaders(GLenum primitive_mode);
211 214
212 enum class AccelDraw { Disabled, Arrays, Indexed }; 215 enum class AccelDraw { Disabled, Arrays, Indexed };
213 AccelDraw accelerate_draw = AccelDraw::Disabled; 216 AccelDraw accelerate_draw = AccelDraw::Disabled;
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
index 56ff83eff..65a220c41 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
@@ -45,7 +45,9 @@ static VAddr TryGetCpuAddr(Tegra::GPUVAddr gpu_addr) {
45 SurfaceParams params{}; 45 SurfaceParams params{};
46 params.addr = TryGetCpuAddr(config.tic.Address()); 46 params.addr = TryGetCpuAddr(config.tic.Address());
47 params.is_tiled = config.tic.IsTiled(); 47 params.is_tiled = config.tic.IsTiled();
48 params.block_width = params.is_tiled ? config.tic.BlockWidth() : 0,
48 params.block_height = params.is_tiled ? config.tic.BlockHeight() : 0, 49 params.block_height = params.is_tiled ? config.tic.BlockHeight() : 0,
50 params.block_depth = params.is_tiled ? config.tic.BlockDepth() : 0,
49 params.pixel_format = 51 params.pixel_format =
50 PixelFormatFromTextureFormat(config.tic.format, config.tic.r_type.Value()); 52 PixelFormatFromTextureFormat(config.tic.format, config.tic.r_type.Value());
51 params.component_type = ComponentTypeFromTexture(config.tic.r_type.Value()); 53 params.component_type = ComponentTypeFromTexture(config.tic.r_type.Value());
@@ -97,8 +99,11 @@ static VAddr TryGetCpuAddr(Tegra::GPUVAddr gpu_addr) {
97 const auto& config{Core::System::GetInstance().GPU().Maxwell3D().regs.rt[index]}; 99 const auto& config{Core::System::GetInstance().GPU().Maxwell3D().regs.rt[index]};
98 SurfaceParams params{}; 100 SurfaceParams params{};
99 params.addr = TryGetCpuAddr(config.Address()); 101 params.addr = TryGetCpuAddr(config.Address());
100 params.is_tiled = true; 102 params.is_tiled =
101 params.block_height = Tegra::Texture::TICEntry::DefaultBlockHeight; 103 config.memory_layout.type == Tegra::Engines::Maxwell3D::Regs::InvMemoryLayout::BlockLinear;
104 params.block_width = 1 << config.memory_layout.block_width;
105 params.block_height = 1 << config.memory_layout.block_height;
106 params.block_depth = 1 << config.memory_layout.block_depth;
102 params.pixel_format = PixelFormatFromRenderTargetFormat(config.format); 107 params.pixel_format = PixelFormatFromRenderTargetFormat(config.format);
103 params.component_type = ComponentTypeFromRenderTarget(config.format); 108 params.component_type = ComponentTypeFromRenderTarget(config.format);
104 params.type = GetFormatType(params.pixel_format); 109 params.type = GetFormatType(params.pixel_format);
@@ -120,13 +125,16 @@ static VAddr TryGetCpuAddr(Tegra::GPUVAddr gpu_addr) {
120 return params; 125 return params;
121} 126}
122 127
123/*static*/ SurfaceParams SurfaceParams::CreateForDepthBuffer(u32 zeta_width, u32 zeta_height, 128/*static*/ SurfaceParams SurfaceParams::CreateForDepthBuffer(
124 Tegra::GPUVAddr zeta_address, 129 u32 zeta_width, u32 zeta_height, Tegra::GPUVAddr zeta_address, Tegra::DepthFormat format,
125 Tegra::DepthFormat format) { 130 u32 block_width, u32 block_height, u32 block_depth,
131 Tegra::Engines::Maxwell3D::Regs::InvMemoryLayout type) {
126 SurfaceParams params{}; 132 SurfaceParams params{};
127 params.addr = TryGetCpuAddr(zeta_address); 133 params.addr = TryGetCpuAddr(zeta_address);
128 params.is_tiled = true; 134 params.is_tiled = type == Tegra::Engines::Maxwell3D::Regs::InvMemoryLayout::BlockLinear;
129 params.block_height = Tegra::Texture::TICEntry::DefaultBlockHeight; 135 params.block_width = 1 << std::min(block_width, 5U);
136 params.block_height = 1 << std::min(block_height, 5U);
137 params.block_depth = 1 << std::min(block_depth, 5U);
130 params.pixel_format = PixelFormatFromDepthFormat(format); 138 params.pixel_format = PixelFormatFromDepthFormat(format);
131 params.component_type = ComponentTypeFromDepthFormat(format); 139 params.component_type = ComponentTypeFromDepthFormat(format);
132 params.type = GetFormatType(params.pixel_format); 140 params.type = GetFormatType(params.pixel_format);
@@ -148,7 +156,9 @@ static VAddr TryGetCpuAddr(Tegra::GPUVAddr gpu_addr) {
148 SurfaceParams params{}; 156 SurfaceParams params{};
149 params.addr = TryGetCpuAddr(config.Address()); 157 params.addr = TryGetCpuAddr(config.Address());
150 params.is_tiled = !config.linear; 158 params.is_tiled = !config.linear;
151 params.block_height = params.is_tiled ? config.BlockHeight() : 0, 159 params.block_width = params.is_tiled ? std::min(config.BlockWidth(), 32U) : 0,
160 params.block_height = params.is_tiled ? std::min(config.BlockHeight(), 32U) : 0,
161 params.block_depth = params.is_tiled ? std::min(config.BlockDepth(), 32U) : 0,
152 params.pixel_format = PixelFormatFromRenderTargetFormat(config.format); 162 params.pixel_format = PixelFormatFromRenderTargetFormat(config.format);
153 params.component_type = ComponentTypeFromRenderTarget(config.format); 163 params.component_type = ComponentTypeFromRenderTarget(config.format);
154 params.type = GetFormatType(params.pixel_format); 164 params.type = GetFormatType(params.pixel_format);
@@ -818,6 +828,11 @@ void CachedSurface::LoadGLBuffer() {
818 if (params.is_tiled) { 828 if (params.is_tiled) {
819 gl_buffer.resize(total_size); 829 gl_buffer.resize(total_size);
820 830
831 ASSERT_MSG(params.block_width == 1, "Block width is defined as {} on texture type {}",
832 params.block_width, static_cast<u32>(params.target));
833 ASSERT_MSG(params.block_depth == 1, "Block depth is defined as {} on texture type {}",
834 params.block_depth, static_cast<u32>(params.target));
835
821 // TODO(bunnei): This only unswizzles and copies a 2D texture - we do not yet know how to do 836 // TODO(bunnei): This only unswizzles and copies a 2D texture - we do not yet know how to do
822 // this for 3D textures, etc. 837 // this for 3D textures, etc.
823 switch (params.target) { 838 switch (params.target) {
@@ -989,7 +1004,9 @@ Surface RasterizerCacheOpenGL::GetDepthBufferSurface(bool preserve_contents) {
989 } 1004 }
990 1005
991 SurfaceParams depth_params{SurfaceParams::CreateForDepthBuffer( 1006 SurfaceParams depth_params{SurfaceParams::CreateForDepthBuffer(
992 regs.zeta_width, regs.zeta_height, regs.zeta.Address(), regs.zeta.format)}; 1007 regs.zeta_width, regs.zeta_height, regs.zeta.Address(), regs.zeta.format,
1008 regs.zeta.memory_layout.block_width, regs.zeta.memory_layout.block_height,
1009 regs.zeta.memory_layout.block_depth, regs.zeta.memory_layout.type)};
993 1010
994 return GetSurface(depth_params, preserve_contents); 1011 return GetSurface(depth_params, preserve_contents);
995} 1012}
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.h b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
index 0b4940b3c..66d98ad4e 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
@@ -716,9 +716,10 @@ struct SurfaceParams {
716 static SurfaceParams CreateForFramebuffer(std::size_t index); 716 static SurfaceParams CreateForFramebuffer(std::size_t index);
717 717
718 /// Creates SurfaceParams for a depth buffer configuration 718 /// Creates SurfaceParams for a depth buffer configuration
719 static SurfaceParams CreateForDepthBuffer(u32 zeta_width, u32 zeta_height, 719 static SurfaceParams CreateForDepthBuffer(
720 Tegra::GPUVAddr zeta_address, 720 u32 zeta_width, u32 zeta_height, Tegra::GPUVAddr zeta_address, Tegra::DepthFormat format,
721 Tegra::DepthFormat format); 721 u32 block_width, u32 block_height, u32 block_depth,
722 Tegra::Engines::Maxwell3D::Regs::InvMemoryLayout type);
722 723
723 /// Creates SurfaceParams for a Fermi2D surface copy 724 /// Creates SurfaceParams for a Fermi2D surface copy
724 static SurfaceParams CreateForFermiCopySurface( 725 static SurfaceParams CreateForFermiCopySurface(
@@ -733,7 +734,9 @@ struct SurfaceParams {
733 734
734 VAddr addr; 735 VAddr addr;
735 bool is_tiled; 736 bool is_tiled;
737 u32 block_width;
736 u32 block_height; 738 u32 block_height;
739 u32 block_depth;
737 PixelFormat pixel_format; 740 PixelFormat pixel_format;
738 ComponentType component_type; 741 ComponentType component_type;
739 SurfaceType type; 742 SurfaceType type;
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 85c668ca1..8dfb49507 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
@@ -2734,6 +2864,52 @@ private:
2734 2864
2735 break; 2865 break;
2736 } 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 }
2737 case OpCode::Id::BRA: { 2913 case OpCode::Id::BRA: {
2738 ASSERT_MSG(instr.bra.constant_buffer == 0, 2914 ASSERT_MSG(instr.bra.constant_buffer == 0,
2739 "BRA with constant buffers are not implemented"); 2915 "BRA with constant buffers are not implemented");
@@ -2777,6 +2953,88 @@ private:
2777 LOG_WARNING(HW_GPU, "DEPBAR instruction is stubbed"); 2953 LOG_WARNING(HW_GPU, "DEPBAR instruction is stubbed");
2778 break; 2954 break;
2779 } 2955 }
2956 case OpCode::Id::VMAD: {
2957 const bool signed_a = instr.vmad.signed_a == 1;
2958 const bool signed_b = instr.vmad.signed_b == 1;
2959 const bool result_signed = signed_a || signed_b;
2960 boost::optional<std::string> forced_result;
2961
2962 auto Unpack = [&](const std::string& op, bool is_chunk, bool is_signed,
2963 Tegra::Shader::VmadType type, u64 byte_height) {
2964 const std::string value = [&]() {
2965 if (!is_chunk) {
2966 const auto offset = static_cast<u32>(byte_height * 8);
2967 return "((" + op + " >> " + std::to_string(offset) + ") & 0xff)";
2968 }
2969 const std::string zero = "0";
2970
2971 switch (type) {
2972 case Tegra::Shader::VmadType::Size16_Low:
2973 return '(' + op + " & 0xffff)";
2974 case Tegra::Shader::VmadType::Size16_High:
2975 return '(' + op + " >> 16)";
2976 case Tegra::Shader::VmadType::Size32:
2977 // TODO(Rodrigo): From my hardware tests it becomes a bit "mad" when
2978 // this type is used (1 * 1 + 0 == 0x5b800000). Until a better
2979 // explanation is found: assert.
2980 UNREACHABLE_MSG("Unimplemented");
2981 return zero;
2982 case Tegra::Shader::VmadType::Invalid:
2983 // Note(Rodrigo): This flag is invalid according to nvdisasm. From my
2984 // testing (even though it's invalid) this makes the whole instruction
2985 // assign zero to target register.
2986 forced_result = boost::make_optional(zero);
2987 return zero;
2988 default:
2989 UNREACHABLE();
2990 return zero;
2991 }
2992 }();
2993
2994 if (is_signed) {
2995 return "int(" + value + ')';
2996 }
2997 return value;
2998 };
2999
3000 const std::string op_a = Unpack(regs.GetRegisterAsInteger(instr.gpr8, 0, false),
3001 instr.vmad.is_byte_chunk_a != 0, signed_a,
3002 instr.vmad.type_a, instr.vmad.byte_height_a);
3003
3004 std::string op_b;
3005 if (instr.vmad.use_register_b) {
3006 op_b = Unpack(regs.GetRegisterAsInteger(instr.gpr20, 0, false),
3007 instr.vmad.is_byte_chunk_b != 0, signed_b, instr.vmad.type_b,
3008 instr.vmad.byte_height_b);
3009 } else {
3010 op_b = '(' +
3011 std::to_string(signed_b ? static_cast<s16>(instr.alu.GetImm20_16())
3012 : instr.alu.GetImm20_16()) +
3013 ')';
3014 }
3015
3016 const std::string op_c = regs.GetRegisterAsInteger(instr.gpr39, 0, result_signed);
3017
3018 std::string result;
3019 if (forced_result) {
3020 result = *forced_result;
3021 } else {
3022 result = '(' + op_a + " * " + op_b + " + " + op_c + ')';
3023
3024 switch (instr.vmad.shr) {
3025 case Tegra::Shader::VmadShr::Shr7:
3026 result = '(' + result + " >> 7)";
3027 break;
3028 case Tegra::Shader::VmadShr::Shr15:
3029 result = '(' + result + " >> 15)";
3030 break;
3031 }
3032 }
3033 regs.SetRegisterToInteger(instr.gpr0, result_signed, 1, result, 1, 1,
3034 instr.vmad.saturate == 1, 0, Register::Size::Word,
3035 instr.vmad.cc);
3036 break;
3037 }
2780 default: { 3038 default: {
2781 LOG_CRITICAL(HW_GPU, "Unhandled instruction: {}", opcode->GetName()); 3039 LOG_CRITICAL(HW_GPU, "Unhandled instruction: {}", opcode->GetName());
2782 UNREACHABLE(); 3040 UNREACHABLE();
@@ -2907,7 +3165,7 @@ private:
2907 3165
2908 ShaderWriter shader; 3166 ShaderWriter shader;
2909 ShaderWriter declarations; 3167 ShaderWriter declarations;
2910 GLSLRegisterManager regs{shader, declarations, stage, suffix}; 3168 GLSLRegisterManager regs{shader, declarations, stage, suffix, header};
2911 3169
2912 // Declarations 3170 // Declarations
2913 std::set<std::string> declr_predicates; 3171 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/textures/texture.h b/src/video_core/textures/texture.h
index 8f31d825a..58d17abcb 100644
--- a/src/video_core/textures/texture.h
+++ b/src/video_core/textures/texture.h
@@ -161,7 +161,9 @@ struct TICEntry {
161 BitField<21, 3, TICHeaderVersion> header_version; 161 BitField<21, 3, TICHeaderVersion> header_version;
162 }; 162 };
163 union { 163 union {
164 BitField<0, 3, u32> block_width;
164 BitField<3, 3, u32> block_height; 165 BitField<3, 3, u32> block_height;
166 BitField<6, 3, u32> block_depth;
165 167
166 // High 16 bits of the pitch value 168 // High 16 bits of the pitch value
167 BitField<0, 16, u32> pitch_high; 169 BitField<0, 16, u32> pitch_high;
@@ -202,13 +204,24 @@ struct TICEntry {
202 return depth_minus_1 + 1; 204 return depth_minus_1 + 1;
203 } 205 }
204 206
207 u32 BlockWidth() const {
208 ASSERT(IsTiled());
209 // The block height is stored in log2 format.
210 return 1 << block_width;
211 }
212
205 u32 BlockHeight() const { 213 u32 BlockHeight() const {
206 ASSERT(header_version == TICHeaderVersion::BlockLinear || 214 ASSERT(IsTiled());
207 header_version == TICHeaderVersion::BlockLinearColorKey);
208 // The block height is stored in log2 format. 215 // The block height is stored in log2 format.
209 return 1 << block_height; 216 return 1 << block_height;
210 } 217 }
211 218
219 u32 BlockDepth() const {
220 ASSERT(IsTiled());
221 // The block height is stored in log2 format.
222 return 1 << block_depth;
223 }
224
212 bool IsTiled() const { 225 bool IsTiled() const {
213 return header_version == TICHeaderVersion::BlockLinear || 226 return header_version == TICHeaderVersion::BlockLinear ||
214 header_version == TICHeaderVersion::BlockLinearColorKey; 227 header_version == TICHeaderVersion::BlockLinearColorKey;
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/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