summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt1
-rw-r--r--src/citra/citra.cpp3
-rw-r--r--src/citra/config.cpp6
-rw-r--r--src/citra_qt/CMakeLists.txt2
-rw-r--r--src/citra_qt/bootmanager.cpp3
-rw-r--r--src/citra_qt/configuration/config.cpp6
-rw-r--r--src/citra_qt/configuration/configure_debug.ui7
-rw-r--r--src/common/logging/backend.cpp1
-rw-r--r--src/common/logging/log.h1
-rw-r--r--src/common/logging/text_formatter.cpp1
-rw-r--r--src/core/CMakeLists.txt2
-rw-r--r--src/core/hle/function_wrappers.h38
-rw-r--r--src/core/hle/kernel/client_session.cpp10
-rw-r--r--src/core/hle/kernel/client_session.h4
-rw-r--r--src/core/hle/kernel/errors.h5
-rw-r--r--src/core/hle/kernel/hle_ipc.cpp19
-rw-r--r--src/core/hle/kernel/server_port.cpp12
-rw-r--r--src/core/hle/kernel/server_port.h11
-rw-r--r--src/core/hle/kernel/server_session.cpp22
-rw-r--r--src/core/hle/kernel/server_session.h14
-rw-r--r--src/core/hle/service/nwm/nwm_uds.cpp77
-rw-r--r--src/core/hle/service/nwm/uds_data.cpp278
-rw-r--r--src/core/hle/service/nwm/uds_data.h78
-rw-r--r--src/core/hle/svc.cpp156
-rw-r--r--src/core/hw/aes/key.h2
-rw-r--r--src/core/hw/gpu.cpp41
-rw-r--r--src/core/hw/gpu.h2
-rw-r--r--src/network/CMakeLists.txt16
-rw-r--r--src/network/network.cpp50
-rw-r--r--src/network/network.h25
-rw-r--r--src/network/room.cpp60
-rw-r--r--src/network/room.h60
-rw-r--r--src/network/room_member.cpp74
-rw-r--r--src/network/room_member.h65
-rw-r--r--src/tests/core/hle/kernel/hle_ipc.cpp25
-rw-r--r--src/video_core/pica_state.h8
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp29
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h3
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.cpp10
-rw-r--r--src/video_core/renderer_opengl/gl_state.cpp10
-rw-r--r--src/video_core/renderer_opengl/gl_state.h2
-rw-r--r--src/video_core/swrasterizer/rasterizer.cpp3
42 files changed, 1142 insertions, 100 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index a45439481..655bd83aa 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -5,6 +5,7 @@ add_subdirectory(common)
5add_subdirectory(core) 5add_subdirectory(core)
6add_subdirectory(video_core) 6add_subdirectory(video_core)
7add_subdirectory(audio_core) 7add_subdirectory(audio_core)
8add_subdirectory(network)
8add_subdirectory(input_common) 9add_subdirectory(input_common)
9add_subdirectory(tests) 10add_subdirectory(tests)
10if (ENABLE_SDL2) 11if (ENABLE_SDL2)
diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp
index dd357ff72..14574e56c 100644
--- a/src/citra/citra.cpp
+++ b/src/citra/citra.cpp
@@ -18,7 +18,10 @@
18#endif 18#endif
19 19
20#ifdef _WIN32 20#ifdef _WIN32
21// windows.h needs to be included before shellapi.h
21#include <windows.h> 22#include <windows.h>
23
24#include <shellapi.h>
22#endif 25#endif
23 26
24#include "citra/config.h" 27#include "citra/config.h"
diff --git a/src/citra/config.cpp b/src/citra/config.cpp
index f08b4069c..957d8dc86 100644
--- a/src/citra/config.cpp
+++ b/src/citra/config.cpp
@@ -88,9 +88,9 @@ void Config::ReadValues() {
88 Settings::values.toggle_framelimit = 88 Settings::values.toggle_framelimit =
89 sdl2_config->GetBoolean("Renderer", "toggle_framelimit", true); 89 sdl2_config->GetBoolean("Renderer", "toggle_framelimit", true);
90 90
91 Settings::values.bg_red = (float)sdl2_config->GetReal("Renderer", "bg_red", 1.0); 91 Settings::values.bg_red = (float)sdl2_config->GetReal("Renderer", "bg_red", 0.0);
92 Settings::values.bg_green = (float)sdl2_config->GetReal("Renderer", "bg_green", 1.0); 92 Settings::values.bg_green = (float)sdl2_config->GetReal("Renderer", "bg_green", 0.0);
93 Settings::values.bg_blue = (float)sdl2_config->GetReal("Renderer", "bg_blue", 1.0); 93 Settings::values.bg_blue = (float)sdl2_config->GetReal("Renderer", "bg_blue", 0.0);
94 94
95 // Layout 95 // Layout
96 Settings::values.layout_option = 96 Settings::values.layout_option =
diff --git a/src/citra_qt/CMakeLists.txt b/src/citra_qt/CMakeLists.txt
index 4841cbf05..9572d3e28 100644
--- a/src/citra_qt/CMakeLists.txt
+++ b/src/citra_qt/CMakeLists.txt
@@ -91,7 +91,7 @@ if (APPLE)
91else() 91else()
92 add_executable(citra-qt ${SRCS} ${HEADERS} ${UI_HDRS}) 92 add_executable(citra-qt ${SRCS} ${HEADERS} ${UI_HDRS})
93endif() 93endif()
94target_link_libraries(citra-qt PRIVATE audio_core common core input_common video_core) 94target_link_libraries(citra-qt PRIVATE audio_core common core input_common network video_core)
95target_link_libraries(citra-qt PRIVATE Boost::boost glad nihstro-headers Qt5::OpenGL Qt5::Widgets) 95target_link_libraries(citra-qt PRIVATE Boost::boost glad nihstro-headers Qt5::OpenGL Qt5::Widgets)
96target_link_libraries(citra-qt PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads) 96target_link_libraries(citra-qt PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads)
97 97
diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp
index a8a4aed8b..30554890f 100644
--- a/src/citra_qt/bootmanager.cpp
+++ b/src/citra_qt/bootmanager.cpp
@@ -17,6 +17,7 @@
17#include "core/settings.h" 17#include "core/settings.h"
18#include "input_common/keyboard.h" 18#include "input_common/keyboard.h"
19#include "input_common/main.h" 19#include "input_common/main.h"
20#include "network/network.h"
20 21
21EmuThread::EmuThread(GRenderWindow* render_window) 22EmuThread::EmuThread(GRenderWindow* render_window)
22 : exec_step(false), running(false), stop_run(false), render_window(render_window) {} 23 : exec_step(false), running(false), stop_run(false), render_window(render_window) {}
@@ -110,10 +111,12 @@ GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread)
110 setWindowTitle(QString::fromStdString(window_title)); 111 setWindowTitle(QString::fromStdString(window_title));
111 112
112 InputCommon::Init(); 113 InputCommon::Init();
114 Network::Init();
113} 115}
114 116
115GRenderWindow::~GRenderWindow() { 117GRenderWindow::~GRenderWindow() {
116 InputCommon::Shutdown(); 118 InputCommon::Shutdown();
119 Network::Shutdown();
117} 120}
118 121
119void GRenderWindow::moveContext() { 122void GRenderWindow::moveContext() {
diff --git a/src/citra_qt/configuration/config.cpp b/src/citra_qt/configuration/config.cpp
index 2b99447ec..64ffc9152 100644
--- a/src/citra_qt/configuration/config.cpp
+++ b/src/citra_qt/configuration/config.cpp
@@ -70,9 +70,9 @@ void Config::ReadValues() {
70 Settings::values.use_vsync = qt_config->value("use_vsync", false).toBool(); 70 Settings::values.use_vsync = qt_config->value("use_vsync", false).toBool();
71 Settings::values.toggle_framelimit = qt_config->value("toggle_framelimit", true).toBool(); 71 Settings::values.toggle_framelimit = qt_config->value("toggle_framelimit", true).toBool();
72 72
73 Settings::values.bg_red = qt_config->value("bg_red", 1.0).toFloat(); 73 Settings::values.bg_red = qt_config->value("bg_red", 0.0).toFloat();
74 Settings::values.bg_green = qt_config->value("bg_green", 1.0).toFloat(); 74 Settings::values.bg_green = qt_config->value("bg_green", 0.0).toFloat();
75 Settings::values.bg_blue = qt_config->value("bg_blue", 1.0).toFloat(); 75 Settings::values.bg_blue = qt_config->value("bg_blue", 0.0).toFloat();
76 qt_config->endGroup(); 76 qt_config->endGroup();
77 77
78 qt_config->beginGroup("Layout"); 78 qt_config->beginGroup("Layout");
diff --git a/src/citra_qt/configuration/configure_debug.ui b/src/citra_qt/configuration/configure_debug.ui
index bbbb0e3f4..96638ebdb 100644
--- a/src/citra_qt/configuration/configure_debug.ui
+++ b/src/citra_qt/configuration/configure_debug.ui
@@ -23,6 +23,13 @@
23 </property> 23 </property>
24 <layout class="QVBoxLayout" name="verticalLayout_2"> 24 <layout class="QVBoxLayout" name="verticalLayout_2">
25 <item> 25 <item>
26 <widget class="QLabel">
27 <property name="text">
28 <string>The GDB Stub only works correctly when the CPU JIT is off.</string>
29 </property>
30 </widget>
31 </item>
32 <item>
26 <layout class="QHBoxLayout" name="horizontalLayout_3"> 33 <layout class="QHBoxLayout" name="horizontalLayout_3">
27 <item> 34 <item>
28 <widget class="QCheckBox" name="toggle_gdbstub"> 35 <widget class="QCheckBox" name="toggle_gdbstub">
diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp
index 42f6a9918..0e4b85a76 100644
--- a/src/common/logging/backend.cpp
+++ b/src/common/logging/backend.cpp
@@ -72,6 +72,7 @@ namespace Log {
72 SUB(Audio, DSP) \ 72 SUB(Audio, DSP) \
73 SUB(Audio, Sink) \ 73 SUB(Audio, Sink) \
74 CLS(Input) \ 74 CLS(Input) \
75 CLS(Network) \
75 CLS(Loader) 76 CLS(Loader)
76 77
77// GetClassName is a macro defined by Windows.h, grrr... 78// GetClassName is a macro defined by Windows.h, grrr...
diff --git a/src/common/logging/log.h b/src/common/logging/log.h
index 1b905f66c..8f13b80b3 100644
--- a/src/common/logging/log.h
+++ b/src/common/logging/log.h
@@ -90,6 +90,7 @@ enum class Class : ClassType {
90 Audio_Sink, ///< Emulator audio output backend 90 Audio_Sink, ///< Emulator audio output backend
91 Loader, ///< ROM loader 91 Loader, ///< ROM loader
92 Input, ///< Input emulation 92 Input, ///< Input emulation
93 Network, ///< Network emulation
93 Count ///< Total number of logging classes 94 Count ///< Total number of logging classes
94}; 95};
95 96
diff --git a/src/common/logging/text_formatter.cpp b/src/common/logging/text_formatter.cpp
index 9d423766f..f71e748d1 100644
--- a/src/common/logging/text_formatter.cpp
+++ b/src/common/logging/text_formatter.cpp
@@ -6,7 +6,6 @@
6#include <cstdio> 6#include <cstdio>
7 7
8#ifdef _WIN32 8#ifdef _WIN32
9#define WIN32_LEAN_AND_MEAN
10#include <windows.h> 9#include <windows.h>
11#endif 10#endif
12 11
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index b16a89990..ea09819e5 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -144,6 +144,7 @@ set(SRCS
144 hle/service/nwm/nwm_tst.cpp 144 hle/service/nwm/nwm_tst.cpp
145 hle/service/nwm/nwm_uds.cpp 145 hle/service/nwm/nwm_uds.cpp
146 hle/service/nwm/uds_beacon.cpp 146 hle/service/nwm/uds_beacon.cpp
147 hle/service/nwm/uds_data.cpp
147 hle/service/pm_app.cpp 148 hle/service/pm_app.cpp
148 hle/service/ptm/ptm.cpp 149 hle/service/ptm/ptm.cpp
149 hle/service/ptm/ptm_gets.cpp 150 hle/service/ptm/ptm_gets.cpp
@@ -341,6 +342,7 @@ set(HEADERS
341 hle/service/nwm/nwm_tst.h 342 hle/service/nwm/nwm_tst.h
342 hle/service/nwm/nwm_uds.h 343 hle/service/nwm/nwm_uds.h
343 hle/service/nwm/uds_beacon.h 344 hle/service/nwm/uds_beacon.h
345 hle/service/nwm/uds_data.h
344 hle/service/pm_app.h 346 hle/service/pm_app.h
345 hle/service/ptm/ptm.h 347 hle/service/ptm/ptm.h
346 hle/service/ptm/ptm_gets.h 348 hle/service/ptm/ptm_gets.h
diff --git a/src/core/hle/function_wrappers.h b/src/core/hle/function_wrappers.h
index 18b6e7017..5e6002f4e 100644
--- a/src/core/hle/function_wrappers.h
+++ b/src/core/hle/function_wrappers.h
@@ -16,9 +16,6 @@ namespace HLE {
16 16
17#define PARAM(n) Core::CPU().GetReg(n) 17#define PARAM(n) Core::CPU().GetReg(n)
18 18
19/// An invalid result code that is meant to be overwritten when a thread resumes from waiting
20static const ResultCode RESULT_INVALID(0xDEADC0DE);
21
22/** 19/**
23 * HLE a function return from the current ARM11 userland process 20 * HLE a function return from the current ARM11 userland process
24 * @param res Result to return 21 * @param res Result to return
@@ -68,10 +65,18 @@ void Wrap() {
68 (PARAM(3) != 0), (((s64)PARAM(4) << 32) | PARAM(0))) 65 (PARAM(3) != 0), (((s64)PARAM(4) << 32) | PARAM(0)))
69 .raw; 66 .raw;
70 67
71 if (retval != RESULT_INVALID.raw) { 68 Core::CPU().SetReg(1, (u32)param_1);
72 Core::CPU().SetReg(1, (u32)param_1); 69 FuncReturn(retval);
73 FuncReturn(retval); 70}
74 } 71
72template <ResultCode func(s32*, u32*, s32, u32)>
73void Wrap() {
74 s32 param_1 = 0;
75 u32 retval =
76 func(&param_1, (Kernel::Handle*)Memory::GetPointer(PARAM(1)), (s32)PARAM(2), PARAM(3)).raw;
77
78 Core::CPU().SetReg(1, (u32)param_1);
79 FuncReturn(retval);
75} 80}
76 81
77template <ResultCode func(u32, u32, u32, u32, s64)> 82template <ResultCode func(u32, u32, u32, u32, s64)>
@@ -92,9 +97,7 @@ template <ResultCode func(u32, s64)>
92void Wrap() { 97void Wrap() {
93 s32 retval = func(PARAM(0), (((s64)PARAM(3) << 32) | PARAM(2))).raw; 98 s32 retval = func(PARAM(0), (((s64)PARAM(3) << 32) | PARAM(2))).raw;
94 99
95 if (retval != RESULT_INVALID.raw) { 100 FuncReturn(retval);
96 FuncReturn(retval);
97 }
98} 101}
99 102
100template <ResultCode func(MemoryInfo*, PageInfo*, u32)> 103template <ResultCode func(MemoryInfo*, PageInfo*, u32)>
@@ -226,9 +229,18 @@ void Wrap() {
226 u32 retval = func(&param_1, &param_2, 229 u32 retval = func(&param_1, &param_2,
227 reinterpret_cast<const char*>(Memory::GetPointer(PARAM(2))), PARAM(3)) 230 reinterpret_cast<const char*>(Memory::GetPointer(PARAM(2))), PARAM(3))
228 .raw; 231 .raw;
229 // The first out parameter is moved into R2 and the second is moved into R1. 232 Core::CPU().SetReg(1, param_1);
230 Core::CPU().SetReg(1, param_2); 233 Core::CPU().SetReg(2, param_2);
231 Core::CPU().SetReg(2, param_1); 234 FuncReturn(retval);
235}
236
237template <ResultCode func(Kernel::Handle*, Kernel::Handle*)>
238void Wrap() {
239 Kernel::Handle param_1 = 0;
240 Kernel::Handle param_2 = 0;
241 u32 retval = func(&param_1, &param_2).raw;
242 Core::CPU().SetReg(1, param_1);
243 Core::CPU().SetReg(2, param_2);
232 FuncReturn(retval); 244 FuncReturn(retval);
233} 245}
234 246
diff --git a/src/core/hle/kernel/client_session.cpp b/src/core/hle/kernel/client_session.cpp
index fef97af1f..646a5cc64 100644
--- a/src/core/hle/kernel/client_session.cpp
+++ b/src/core/hle/kernel/client_session.cpp
@@ -9,6 +9,7 @@
9#include "core/hle/kernel/hle_ipc.h" 9#include "core/hle/kernel/hle_ipc.h"
10#include "core/hle/kernel/server_session.h" 10#include "core/hle/kernel/server_session.h"
11#include "core/hle/kernel/session.h" 11#include "core/hle/kernel/session.h"
12#include "core/hle/kernel/thread.h"
12 13
13namespace Kernel { 14namespace Kernel {
14 15
@@ -27,19 +28,24 @@ ClientSession::~ClientSession() {
27 28
28 // TODO(Subv): Force a wake up of all the ServerSession's waiting threads and set 29 // TODO(Subv): Force a wake up of all the ServerSession's waiting threads and set
29 // their WaitSynchronization result to 0xC920181A. 30 // their WaitSynchronization result to 0xC920181A.
31
32 // Clean up the list of client threads with pending requests, they are unneeded now that the
33 // client endpoint is closed.
34 server->pending_requesting_threads.clear();
35 server->currently_handling = nullptr;
30 } 36 }
31 37
32 parent->client = nullptr; 38 parent->client = nullptr;
33} 39}
34 40
35ResultCode ClientSession::SendSyncRequest() { 41ResultCode ClientSession::SendSyncRequest(SharedPtr<Thread> thread) {
36 // Keep ServerSession alive until we're done working with it. 42 // Keep ServerSession alive until we're done working with it.
37 SharedPtr<ServerSession> server = parent->server; 43 SharedPtr<ServerSession> server = parent->server;
38 if (server == nullptr) 44 if (server == nullptr)
39 return ERR_SESSION_CLOSED_BY_REMOTE; 45 return ERR_SESSION_CLOSED_BY_REMOTE;
40 46
41 // Signal the server session that new data is available 47 // Signal the server session that new data is available
42 return server->HandleSyncRequest(); 48 return server->HandleSyncRequest(std::move(thread));
43} 49}
44 50
45} // namespace 51} // namespace
diff --git a/src/core/hle/kernel/client_session.h b/src/core/hle/kernel/client_session.h
index 2de379c09..daf521529 100644
--- a/src/core/hle/kernel/client_session.h
+++ b/src/core/hle/kernel/client_session.h
@@ -14,6 +14,7 @@ namespace Kernel {
14 14
15class ServerSession; 15class ServerSession;
16class Session; 16class Session;
17class Thread;
17 18
18class ClientSession final : public Object { 19class ClientSession final : public Object {
19public: 20public:
@@ -34,9 +35,10 @@ public:
34 35
35 /** 36 /**
36 * Sends an SyncRequest from the current emulated thread. 37 * Sends an SyncRequest from the current emulated thread.
38 * @param thread Thread that initiated the request.
37 * @return ResultCode of the operation. 39 * @return ResultCode of the operation.
38 */ 40 */
39 ResultCode SendSyncRequest(); 41 ResultCode SendSyncRequest(SharedPtr<Thread> thread);
40 42
41 std::string name; ///< Name of client port (optional) 43 std::string name; ///< Name of client port (optional)
42 44
diff --git a/src/core/hle/kernel/errors.h b/src/core/hle/kernel/errors.h
index b3b60e7df..64aa61460 100644
--- a/src/core/hle/kernel/errors.h
+++ b/src/core/hle/kernel/errors.h
@@ -13,6 +13,7 @@ enum {
13 OutOfHandles = 19, 13 OutOfHandles = 19,
14 SessionClosedByRemote = 26, 14 SessionClosedByRemote = 26,
15 PortNameTooLong = 30, 15 PortNameTooLong = 30,
16 NoPendingSessions = 35,
16 WrongPermission = 46, 17 WrongPermission = 46,
17 InvalidBufferDescriptor = 48, 18 InvalidBufferDescriptor = 48,
18 MaxConnectionsReached = 52, 19 MaxConnectionsReached = 52,
@@ -94,5 +95,9 @@ constexpr ResultCode ERR_OUT_OF_RANGE_KERNEL(ErrorDescription::OutOfRange, Error
94 ErrorLevel::Permanent); // 0xD8E007FD 95 ErrorLevel::Permanent); // 0xD8E007FD
95constexpr ResultCode RESULT_TIMEOUT(ErrorDescription::Timeout, ErrorModule::OS, 96constexpr ResultCode RESULT_TIMEOUT(ErrorDescription::Timeout, ErrorModule::OS,
96 ErrorSummary::StatusChanged, ErrorLevel::Info); 97 ErrorSummary::StatusChanged, ErrorLevel::Info);
98/// Returned when Accept() is called on a port with no sessions to be accepted.
99constexpr ResultCode ERR_NO_PENDING_SESSIONS(ErrCodes::NoPendingSessions, ErrorModule::OS,
100 ErrorSummary::WouldBlock,
101 ErrorLevel::Permanent); // 0xD8401823
97 102
98} // namespace Kernel 103} // namespace Kernel
diff --git a/src/core/hle/kernel/hle_ipc.cpp b/src/core/hle/kernel/hle_ipc.cpp
index 1cac1d0c9..5ebe2eca4 100644
--- a/src/core/hle/kernel/hle_ipc.cpp
+++ b/src/core/hle/kernel/hle_ipc.cpp
@@ -67,10 +67,13 @@ ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const u32_le* sr
67 ASSERT(i + num_handles <= command_size); // TODO(yuriks): Return error 67 ASSERT(i + num_handles <= command_size); // TODO(yuriks): Return error
68 for (u32 j = 0; j < num_handles; ++j) { 68 for (u32 j = 0; j < num_handles; ++j) {
69 Handle handle = src_cmdbuf[i]; 69 Handle handle = src_cmdbuf[i];
70 SharedPtr<Object> object = src_table.GetGeneric(handle); 70 SharedPtr<Object> object = nullptr;
71 ASSERT(object != nullptr); // TODO(yuriks): Return error 71 if (handle != 0) {
72 if (descriptor == IPC::DescriptorType::MoveHandle) { 72 object = src_table.GetGeneric(handle);
73 src_table.Close(handle); 73 ASSERT(object != nullptr); // TODO(yuriks): Return error
74 if (descriptor == IPC::DescriptorType::MoveHandle) {
75 src_table.Close(handle);
76 }
74 } 77 }
75 78
76 cmd_buf[i++] = AddOutgoingHandle(std::move(object)); 79 cmd_buf[i++] = AddOutgoingHandle(std::move(object));
@@ -112,9 +115,11 @@ ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(u32_le* dst_cmdbuf, P
112 ASSERT(i + num_handles <= command_size); 115 ASSERT(i + num_handles <= command_size);
113 for (u32 j = 0; j < num_handles; ++j) { 116 for (u32 j = 0; j < num_handles; ++j) {
114 SharedPtr<Object> object = GetIncomingHandle(cmd_buf[i]); 117 SharedPtr<Object> object = GetIncomingHandle(cmd_buf[i]);
115 118 Handle handle = 0;
116 // TODO(yuriks): Figure out the proper error handling for if this fails 119 if (object != nullptr) {
117 Handle handle = dst_table.Create(object).Unwrap(); 120 // TODO(yuriks): Figure out the proper error handling for if this fails
121 handle = dst_table.Create(object).Unwrap();
122 }
118 dst_cmdbuf[i++] = handle; 123 dst_cmdbuf[i++] = handle;
119 } 124 }
120 break; 125 break;
diff --git a/src/core/hle/kernel/server_port.cpp b/src/core/hle/kernel/server_port.cpp
index 4d20c39a1..49a9cdfa3 100644
--- a/src/core/hle/kernel/server_port.cpp
+++ b/src/core/hle/kernel/server_port.cpp
@@ -5,8 +5,10 @@
5#include <tuple> 5#include <tuple>
6#include "common/assert.h" 6#include "common/assert.h"
7#include "core/hle/kernel/client_port.h" 7#include "core/hle/kernel/client_port.h"
8#include "core/hle/kernel/errors.h"
8#include "core/hle/kernel/kernel.h" 9#include "core/hle/kernel/kernel.h"
9#include "core/hle/kernel/server_port.h" 10#include "core/hle/kernel/server_port.h"
11#include "core/hle/kernel/server_session.h"
10#include "core/hle/kernel/thread.h" 12#include "core/hle/kernel/thread.h"
11 13
12namespace Kernel { 14namespace Kernel {
@@ -14,6 +16,16 @@ namespace Kernel {
14ServerPort::ServerPort() {} 16ServerPort::ServerPort() {}
15ServerPort::~ServerPort() {} 17ServerPort::~ServerPort() {}
16 18
19ResultVal<SharedPtr<ServerSession>> ServerPort::Accept() {
20 if (pending_sessions.empty()) {
21 return ERR_NO_PENDING_SESSIONS;
22 }
23
24 auto session = std::move(pending_sessions.back());
25 pending_sessions.pop_back();
26 return MakeResult(std::move(session));
27}
28
17bool ServerPort::ShouldWait(Thread* thread) const { 29bool ServerPort::ShouldWait(Thread* thread) const {
18 // If there are no pending sessions, we wait until a new one is added. 30 // If there are no pending sessions, we wait until a new one is added.
19 return pending_sessions.size() == 0; 31 return pending_sessions.size() == 0;
diff --git a/src/core/hle/kernel/server_port.h b/src/core/hle/kernel/server_port.h
index f1419cd46..6fe7c7f2f 100644
--- a/src/core/hle/kernel/server_port.h
+++ b/src/core/hle/kernel/server_port.h
@@ -14,6 +14,7 @@
14namespace Kernel { 14namespace Kernel {
15 15
16class ClientPort; 16class ClientPort;
17class ServerSession;
17class SessionRequestHandler; 18class SessionRequestHandler;
18 19
19class ServerPort final : public WaitObject { 20class ServerPort final : public WaitObject {
@@ -41,6 +42,12 @@ public:
41 } 42 }
42 43
43 /** 44 /**
45 * Accepts a pending incoming connection on this port. If there are no pending sessions, will
46 * return ERR_NO_PENDING_SESSIONS.
47 */
48 ResultVal<SharedPtr<ServerSession>> Accept();
49
50 /**
44 * Sets the HLE handler template for the port. ServerSessions crated by connecting to this port 51 * Sets the HLE handler template for the port. ServerSessions crated by connecting to this port
45 * will inherit a reference to this handler. 52 * will inherit a reference to this handler.
46 */ 53 */
@@ -50,8 +57,8 @@ public:
50 57
51 std::string name; ///< Name of port (optional) 58 std::string name; ///< Name of port (optional)
52 59
53 std::vector<SharedPtr<WaitObject>> 60 /// ServerSessions waiting to be accepted by the port
54 pending_sessions; ///< ServerSessions waiting to be accepted by the port 61 std::vector<SharedPtr<ServerSession>> pending_sessions;
55 62
56 /// This session's HLE request handler template (optional) 63 /// This session's HLE request handler template (optional)
57 /// ServerSessions created from this port inherit a reference to this handler. 64 /// ServerSessions created from this port inherit a reference to this handler.
diff --git a/src/core/hle/kernel/server_session.cpp b/src/core/hle/kernel/server_session.cpp
index d197137c3..337896abf 100644
--- a/src/core/hle/kernel/server_session.cpp
+++ b/src/core/hle/kernel/server_session.cpp
@@ -32,22 +32,29 @@ ResultVal<SharedPtr<ServerSession>> ServerSession::Create(std::string name) {
32 SharedPtr<ServerSession> server_session(new ServerSession); 32 SharedPtr<ServerSession> server_session(new ServerSession);
33 33
34 server_session->name = std::move(name); 34 server_session->name = std::move(name);
35 server_session->signaled = false;
36 server_session->parent = nullptr; 35 server_session->parent = nullptr;
37 36
38 return MakeResult(std::move(server_session)); 37 return MakeResult(std::move(server_session));
39} 38}
40 39
41bool ServerSession::ShouldWait(Thread* thread) const { 40bool ServerSession::ShouldWait(Thread* thread) const {
42 return !signaled; 41 // Closed sessions should never wait, an error will be returned from svcReplyAndReceive.
42 if (parent->client == nullptr)
43 return false;
44 // Wait if we have no pending requests, or if we're currently handling a request.
45 return pending_requesting_threads.empty() || currently_handling != nullptr;
43} 46}
44 47
45void ServerSession::Acquire(Thread* thread) { 48void ServerSession::Acquire(Thread* thread) {
46 ASSERT_MSG(!ShouldWait(thread), "object unavailable!"); 49 ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
47 signaled = false; 50 // We are now handling a request, pop it from the stack.
51 // TODO(Subv): What happens if the client endpoint is closed before any requests are made?
52 ASSERT(!pending_requesting_threads.empty());
53 currently_handling = pending_requesting_threads.back();
54 pending_requesting_threads.pop_back();
48} 55}
49 56
50ResultCode ServerSession::HandleSyncRequest() { 57ResultCode ServerSession::HandleSyncRequest(SharedPtr<Thread> thread) {
51 // The ServerSession received a sync request, this means that there's new data available 58 // The ServerSession received a sync request, this means that there's new data available
52 // from its ClientSession, so wake up any threads that may be waiting on a svcReplyAndReceive or 59 // from its ClientSession, so wake up any threads that may be waiting on a svcReplyAndReceive or
53 // similar. 60 // similar.
@@ -60,11 +67,14 @@ ResultCode ServerSession::HandleSyncRequest() {
60 return result; 67 return result;
61 hle_handler->HandleSyncRequest(SharedPtr<ServerSession>(this)); 68 hle_handler->HandleSyncRequest(SharedPtr<ServerSession>(this));
62 // TODO(Subv): Translate the response command buffer. 69 // TODO(Subv): Translate the response command buffer.
70 } else {
71 // Add the thread to the list of threads that have issued a sync request with this
72 // server.
73 pending_requesting_threads.push_back(std::move(thread));
63 } 74 }
64 75
65 // If this ServerSession does not have an HLE implementation, just wake up the threads waiting 76 // If this ServerSession does not have an HLE implementation, just wake up the threads waiting
66 // on it. 77 // on it.
67 signaled = true;
68 WakeupAllWaitingThreads(); 78 WakeupAllWaitingThreads();
69 return RESULT_SUCCESS; 79 return RESULT_SUCCESS;
70} 80}
@@ -90,4 +100,4 @@ ResultCode TranslateHLERequest(ServerSession* server_session) {
90 // TODO(Subv): Implement this function once multiple concurrent processes are supported. 100 // TODO(Subv): Implement this function once multiple concurrent processes are supported.
91 return RESULT_SUCCESS; 101 return RESULT_SUCCESS;
92} 102}
93} 103} // namespace Kernel
diff --git a/src/core/hle/kernel/server_session.h b/src/core/hle/kernel/server_session.h
index 5365605da..f4360ddf3 100644
--- a/src/core/hle/kernel/server_session.h
+++ b/src/core/hle/kernel/server_session.h
@@ -67,20 +67,30 @@ public:
67 67
68 /** 68 /**
69 * Handle a sync request from the emulated application. 69 * Handle a sync request from the emulated application.
70 * @param thread Thread that initiated the request.
70 * @returns ResultCode from the operation. 71 * @returns ResultCode from the operation.
71 */ 72 */
72 ResultCode HandleSyncRequest(); 73 ResultCode HandleSyncRequest(SharedPtr<Thread> thread);
73 74
74 bool ShouldWait(Thread* thread) const override; 75 bool ShouldWait(Thread* thread) const override;
75 76
76 void Acquire(Thread* thread) override; 77 void Acquire(Thread* thread) override;
77 78
78 std::string name; ///< The name of this session (optional) 79 std::string name; ///< The name of this session (optional)
79 bool signaled; ///< Whether there's new data available to this ServerSession
80 std::shared_ptr<Session> parent; ///< The parent session, which links to the client endpoint. 80 std::shared_ptr<Session> parent; ///< The parent session, which links to the client endpoint.
81 std::shared_ptr<SessionRequestHandler> 81 std::shared_ptr<SessionRequestHandler>
82 hle_handler; ///< This session's HLE request handler (optional) 82 hle_handler; ///< This session's HLE request handler (optional)
83 83
84 /// List of threads that are pending a response after a sync request. This list is processed in
85 /// a LIFO manner, thus, the last request will be dispatched first.
86 /// TODO(Subv): Verify if this is indeed processed in LIFO using a hardware test.
87 std::vector<SharedPtr<Thread>> pending_requesting_threads;
88
89 /// Thread whose request is currently being handled. A request is considered "handled" when a
90 /// response is sent via svcReplyAndReceive.
91 /// TODO(Subv): Find a better name for this.
92 SharedPtr<Thread> currently_handling;
93
84private: 94private:
85 ServerSession(); 95 ServerSession();
86 ~ServerSession() override; 96 ~ServerSession() override;
diff --git a/src/core/hle/service/nwm/nwm_uds.cpp b/src/core/hle/service/nwm/nwm_uds.cpp
index a7149c9e8..6dbdff044 100644
--- a/src/core/hle/service/nwm/nwm_uds.cpp
+++ b/src/core/hle/service/nwm/nwm_uds.cpp
@@ -15,6 +15,7 @@
15#include "core/hle/result.h" 15#include "core/hle/result.h"
16#include "core/hle/service/nwm/nwm_uds.h" 16#include "core/hle/service/nwm/nwm_uds.h"
17#include "core/hle/service/nwm/uds_beacon.h" 17#include "core/hle/service/nwm/uds_beacon.h"
18#include "core/hle/service/nwm/uds_data.h"
18#include "core/memory.h" 19#include "core/memory.h"
19 20
20namespace Service { 21namespace Service {
@@ -373,6 +374,80 @@ static void DestroyNetwork(Interface* self) {
373} 374}
374 375
375/** 376/**
377 * NWM_UDS::SendTo service function.
378 * Sends a data frame to the UDS network we're connected to.
379 * Inputs:
380 * 0 : Command header.
381 * 1 : Unknown.
382 * 2 : u16 Destination network node id.
383 * 3 : u8 Data channel.
384 * 4 : Buffer size >> 2
385 * 5 : Data size
386 * 6 : Flags
387 * 7 : Input buffer descriptor
388 * 8 : Input buffer address
389 * Outputs:
390 * 0 : Return header
391 * 1 : Result of function, 0 on success, otherwise error code
392 */
393static void SendTo(Interface* self) {
394 IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x17, 6, 2);
395
396 rp.Skip(1, false);
397 u16 dest_node_id = rp.Pop<u16>();
398 u8 data_channel = rp.Pop<u8>();
399 rp.Skip(1, false);
400 u32 data_size = rp.Pop<u32>();
401 u32 flags = rp.Pop<u32>();
402
403 size_t desc_size;
404 const VAddr input_address = rp.PopStaticBuffer(&desc_size, false);
405 ASSERT(desc_size == data_size);
406
407 IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
408
409 if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsClient) &&
410 connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
411 rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS,
412 ErrorSummary::InvalidState, ErrorLevel::Status));
413 return;
414 }
415
416 if (dest_node_id == connection_status.network_node_id) {
417 rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::UDS,
418 ErrorSummary::WrongArgument, ErrorLevel::Status));
419 return;
420 }
421
422 // TODO(Subv): Do something with the flags.
423
424 constexpr size_t MaxSize = 0x5C6;
425 if (data_size > MaxSize) {
426 rb.Push(ResultCode(ErrorDescription::TooLarge, ErrorModule::UDS,
427 ErrorSummary::WrongArgument, ErrorLevel::Usage));
428 return;
429 }
430
431 std::vector<u8> data(data_size);
432 Memory::ReadBlock(input_address, data.data(), data.size());
433
434 // TODO(Subv): Increment the sequence number after each sent packet.
435 u16 sequence_number = 0;
436 std::vector<u8> data_payload = GenerateDataPayload(
437 data, data_channel, dest_node_id, connection_status.network_node_id, sequence_number);
438
439 // TODO(Subv): Retrieve the MAC address of the dest_node_id and our own to encrypt
440 // and encapsulate the payload.
441
442 // TODO(Subv): Send the frame.
443
444 rb.Push(RESULT_SUCCESS);
445
446 LOG_WARNING(Service_NWM, "(STUB) called dest_node_id=%u size=%u flags=%u channel=%u",
447 static_cast<u32>(dest_node_id), data_size, flags, static_cast<u32>(data_channel));
448}
449
450/**
376 * NWM_UDS::GetChannel service function. 451 * NWM_UDS::GetChannel service function.
377 * Returns the WiFi channel in which the network we're connected to is transmitting. 452 * Returns the WiFi channel in which the network we're connected to is transmitting.
378 * Inputs: 453 * Inputs:
@@ -600,7 +675,7 @@ const Interface::FunctionInfo FunctionTable[] = {
600 {0x00130040, nullptr, "Unbind"}, 675 {0x00130040, nullptr, "Unbind"},
601 {0x001400C0, nullptr, "PullPacket"}, 676 {0x001400C0, nullptr, "PullPacket"},
602 {0x00150080, nullptr, "SetMaxSendDelay"}, 677 {0x00150080, nullptr, "SetMaxSendDelay"},
603 {0x00170182, nullptr, "SendTo"}, 678 {0x00170182, SendTo, "SendTo"},
604 {0x001A0000, GetChannel, "GetChannel"}, 679 {0x001A0000, GetChannel, "GetChannel"},
605 {0x001B0302, InitializeWithVersion, "InitializeWithVersion"}, 680 {0x001B0302, InitializeWithVersion, "InitializeWithVersion"},
606 {0x001D0044, BeginHostingNetwork, "BeginHostingNetwork"}, 681 {0x001D0044, BeginHostingNetwork, "BeginHostingNetwork"},
diff --git a/src/core/hle/service/nwm/uds_data.cpp b/src/core/hle/service/nwm/uds_data.cpp
new file mode 100644
index 000000000..8c6742dba
--- /dev/null
+++ b/src/core/hle/service/nwm/uds_data.cpp
@@ -0,0 +1,278 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <cstring>
6#include <cryptopp/aes.h>
7#include <cryptopp/ccm.h>
8#include <cryptopp/filters.h>
9#include <cryptopp/md5.h>
10#include <cryptopp/modes.h>
11#include "core/hle/service/nwm/nwm_uds.h"
12#include "core/hle/service/nwm/uds_data.h"
13#include "core/hw/aes/key.h"
14
15namespace Service {
16namespace NWM {
17
18using MacAddress = std::array<u8, 6>;
19
20/*
21 * Generates a SNAP-enabled 802.2 LLC header for the specified protocol.
22 * @returns a buffer with the bytes of the generated header.
23 */
24static std::vector<u8> GenerateLLCHeader(EtherType protocol) {
25 LLCHeader header{};
26 header.protocol = static_cast<u16>(protocol);
27
28 std::vector<u8> buffer(sizeof(header));
29 memcpy(buffer.data(), &header, sizeof(header));
30
31 return buffer;
32}
33
34/*
35 * Generates a Nintendo UDS SecureData header with the specified parameters.
36 * @returns a buffer with the bytes of the generated header.
37 */
38static std::vector<u8> GenerateSecureDataHeader(u16 data_size, u8 channel, u16 dest_node_id,
39 u16 src_node_id, u16 sequence_number) {
40 SecureDataHeader header{};
41 header.protocol_size = data_size + sizeof(SecureDataHeader);
42 // Note: This size includes everything except the first 4 bytes of the structure,
43 // reinforcing the hypotheses that the first 4 bytes are actually the header of
44 // another container protocol.
45 header.securedata_size = data_size + sizeof(SecureDataHeader) - 4;
46 // Frames sent by the emulated application are never UDS management frames
47 header.is_management = 0;
48 header.data_channel = channel;
49 header.sequence_number = sequence_number;
50 header.dest_node_id = dest_node_id;
51 header.src_node_id = src_node_id;
52
53 std::vector<u8> buffer(sizeof(header));
54 memcpy(buffer.data(), &header, sizeof(header));
55
56 return buffer;
57}
58
59/*
60 * Calculates the CTR used for the AES-CTR process that calculates
61 * the CCMP crypto key for data frames.
62 * @returns The CTR used for data frames crypto key generation.
63 */
64static std::array<u8, CryptoPP::MD5::DIGESTSIZE> GetDataCryptoCTR(const NetworkInfo& network_info) {
65 DataFrameCryptoCTR data{};
66
67 data.host_mac = network_info.host_mac_address;
68 data.wlan_comm_id = network_info.wlan_comm_id;
69 data.id = network_info.id;
70 data.network_id = network_info.network_id;
71
72 std::array<u8, CryptoPP::MD5::DIGESTSIZE> hash;
73 CryptoPP::MD5().CalculateDigest(hash.data(), reinterpret_cast<u8*>(&data), sizeof(data));
74
75 return hash;
76}
77
78/*
79 * Generates the key used for encrypting the 802.11 data frames generated by UDS.
80 * @returns The key used for data frames crypto.
81 */
82static std::array<u8, CryptoPP::AES::BLOCKSIZE> GenerateDataCCMPKey(
83 const std::vector<u8>& passphrase, const NetworkInfo& network_info) {
84 // Calculate the MD5 hash of the input passphrase.
85 std::array<u8, CryptoPP::MD5::DIGESTSIZE> passphrase_hash;
86 CryptoPP::MD5().CalculateDigest(passphrase_hash.data(), passphrase.data(), passphrase.size());
87
88 std::array<u8, CryptoPP::AES::BLOCKSIZE> ccmp_key;
89
90 // The CCMP key is the result of encrypting the MD5 hash of the passphrase with AES-CTR using
91 // keyslot 0x2D.
92 using CryptoPP::AES;
93 std::array<u8, CryptoPP::MD5::DIGESTSIZE> counter = GetDataCryptoCTR(network_info);
94 std::array<u8, AES::BLOCKSIZE> key = HW::AES::GetNormalKey(HW::AES::KeySlotID::UDSDataKey);
95 CryptoPP::CTR_Mode<AES>::Encryption aes;
96 aes.SetKeyWithIV(key.data(), AES::BLOCKSIZE, counter.data());
97 aes.ProcessData(ccmp_key.data(), passphrase_hash.data(), passphrase_hash.size());
98
99 return ccmp_key;
100}
101
102/*
103 * Generates the Additional Authenticated Data (AAD) for an UDS 802.11 encrypted data frame.
104 * @returns a buffer with the bytes of the AAD.
105 */
106static std::vector<u8> GenerateCCMPAAD(const MacAddress& sender, const MacAddress& receiver,
107 const MacAddress& bssid, u16 frame_control) {
108 // Reference: IEEE 802.11-2007
109
110 // 8.3.3.3.2 Construct AAD (22-30 bytes)
111 // The AAD is constructed from the MPDU header. The AAD does not include the header Duration
112 // field, because the Duration field value can change due to normal IEEE 802.11 operation (e.g.,
113 // a rate change during retransmission). For similar reasons, several subfields in the Frame
114 // Control field are masked to 0.
115 struct {
116 u16_be FC; // MPDU Frame Control field
117 MacAddress A1;
118 MacAddress A2;
119 MacAddress A3;
120 u16_be SC; // MPDU Sequence Control field
121 } aad_struct{};
122
123 constexpr u16 AADFrameControlMask = 0x8FC7;
124 aad_struct.FC = frame_control & AADFrameControlMask;
125 aad_struct.SC = 0;
126
127 bool to_ds = (frame_control & (1 << 0)) != 0;
128 bool from_ds = (frame_control & (1 << 1)) != 0;
129 // In the 802.11 standard, ToDS = 1 and FromDS = 1 is a valid configuration,
130 // however, the 3DS doesn't seem to transmit frames with such combination.
131 ASSERT_MSG(to_ds != from_ds, "Invalid combination");
132
133 // The meaning of the address fields depends on the ToDS and FromDS fields.
134 if (from_ds) {
135 aad_struct.A1 = receiver;
136 aad_struct.A2 = bssid;
137 aad_struct.A3 = sender;
138 }
139
140 if (to_ds) {
141 aad_struct.A1 = bssid;
142 aad_struct.A2 = sender;
143 aad_struct.A3 = receiver;
144 }
145
146 std::vector<u8> aad(sizeof(aad_struct));
147 std::memcpy(aad.data(), &aad_struct, sizeof(aad_struct));
148
149 return aad;
150}
151
152/*
153 * Decrypts the payload of an encrypted 802.11 data frame using the specified key.
154 * @returns The decrypted payload.
155 */
156static std::vector<u8> DecryptDataFrame(const std::vector<u8>& encrypted_payload,
157 const std::array<u8, CryptoPP::AES::BLOCKSIZE>& ccmp_key,
158 const MacAddress& sender, const MacAddress& receiver,
159 const MacAddress& bssid, u16 sequence_number,
160 u16 frame_control) {
161
162 // Reference: IEEE 802.11-2007
163
164 std::vector<u8> aad = GenerateCCMPAAD(sender, receiver, bssid, frame_control);
165
166 std::vector<u8> packet_number{0,
167 0,
168 0,
169 0,
170 static_cast<u8>((sequence_number >> 8) & 0xFF),
171 static_cast<u8>(sequence_number & 0xFF)};
172
173 // 8.3.3.3.3 Construct CCM nonce (13 bytes)
174 std::vector<u8> nonce;
175 nonce.push_back(0); // priority
176 nonce.insert(nonce.end(), sender.begin(), sender.end()); // Address 2
177 nonce.insert(nonce.end(), packet_number.begin(), packet_number.end()); // PN
178
179 try {
180 CryptoPP::CCM<CryptoPP::AES, 8>::Decryption d;
181 d.SetKeyWithIV(ccmp_key.data(), ccmp_key.size(), nonce.data(), nonce.size());
182 d.SpecifyDataLengths(aad.size(), encrypted_payload.size() - 8, 0);
183
184 CryptoPP::AuthenticatedDecryptionFilter df(
185 d, nullptr, CryptoPP::AuthenticatedDecryptionFilter::MAC_AT_END |
186 CryptoPP::AuthenticatedDecryptionFilter::THROW_EXCEPTION);
187 // put aad
188 df.ChannelPut(CryptoPP::AAD_CHANNEL, aad.data(), aad.size());
189
190 // put cipher with mac
191 df.ChannelPut(CryptoPP::DEFAULT_CHANNEL, encrypted_payload.data(),
192 encrypted_payload.size() - 8);
193 df.ChannelPut(CryptoPP::DEFAULT_CHANNEL,
194 encrypted_payload.data() + encrypted_payload.size() - 8, 8);
195
196 df.ChannelMessageEnd(CryptoPP::AAD_CHANNEL);
197 df.ChannelMessageEnd(CryptoPP::DEFAULT_CHANNEL);
198 df.SetRetrievalChannel(CryptoPP::DEFAULT_CHANNEL);
199
200 int size = df.MaxRetrievable();
201
202 std::vector<u8> pdata(size);
203 df.Get(pdata.data(), size);
204 return pdata;
205 } catch (CryptoPP::Exception&) {
206 LOG_ERROR(Service_NWM, "failed to decrypt");
207 }
208
209 return {};
210}
211
212/*
213 * Encrypts the payload of an 802.11 data frame using the specified key.
214 * @returns The encrypted payload.
215 */
216static std::vector<u8> EncryptDataFrame(const std::vector<u8>& payload,
217 const std::array<u8, CryptoPP::AES::BLOCKSIZE>& ccmp_key,
218 const MacAddress& sender, const MacAddress& receiver,
219 const MacAddress& bssid, u16 sequence_number,
220 u16 frame_control) {
221 // Reference: IEEE 802.11-2007
222
223 std::vector<u8> aad = GenerateCCMPAAD(sender, receiver, bssid, frame_control);
224
225 std::vector<u8> packet_number{0,
226 0,
227 0,
228 0,
229 static_cast<u8>((sequence_number >> 8) & 0xFF),
230 static_cast<u8>(sequence_number & 0xFF)};
231
232 // 8.3.3.3.3 Construct CCM nonce (13 bytes)
233 std::vector<u8> nonce;
234 nonce.push_back(0); // priority
235 nonce.insert(nonce.end(), sender.begin(), sender.end()); // Address 2
236 nonce.insert(nonce.end(), packet_number.begin(), packet_number.end()); // PN
237
238 try {
239 CryptoPP::CCM<CryptoPP::AES, 8>::Encryption d;
240 d.SetKeyWithIV(ccmp_key.data(), ccmp_key.size(), nonce.data(), nonce.size());
241 d.SpecifyDataLengths(aad.size(), payload.size(), 0);
242
243 CryptoPP::AuthenticatedEncryptionFilter df(d);
244 // put aad
245 df.ChannelPut(CryptoPP::AAD_CHANNEL, aad.data(), aad.size());
246 df.ChannelMessageEnd(CryptoPP::AAD_CHANNEL);
247
248 // put plaintext
249 df.ChannelPut(CryptoPP::DEFAULT_CHANNEL, payload.data(), payload.size());
250 df.ChannelMessageEnd(CryptoPP::DEFAULT_CHANNEL);
251
252 df.SetRetrievalChannel(CryptoPP::DEFAULT_CHANNEL);
253
254 int size = df.MaxRetrievable();
255
256 std::vector<u8> cipher(size);
257 df.Get(cipher.data(), size);
258 return cipher;
259 } catch (CryptoPP::Exception&) {
260 LOG_ERROR(Service_NWM, "failed to encrypt");
261 }
262
263 return {};
264}
265
266std::vector<u8> GenerateDataPayload(const std::vector<u8>& data, u8 channel, u16 dest_node,
267 u16 src_node, u16 sequence_number) {
268 std::vector<u8> buffer = GenerateLLCHeader(EtherType::SecureData);
269 std::vector<u8> securedata_header =
270 GenerateSecureDataHeader(data.size(), channel, dest_node, src_node, sequence_number);
271
272 buffer.insert(buffer.end(), securedata_header.begin(), securedata_header.end());
273 buffer.insert(buffer.end(), data.begin(), data.end());
274 return buffer;
275}
276
277} // namespace NWM
278} // namespace Service
diff --git a/src/core/hle/service/nwm/uds_data.h b/src/core/hle/service/nwm/uds_data.h
new file mode 100644
index 000000000..a23520a41
--- /dev/null
+++ b/src/core/hle/service/nwm/uds_data.h
@@ -0,0 +1,78 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <vector>
9#include "common/common_types.h"
10#include "common/swap.h"
11#include "core/hle/service/service.h"
12
13namespace Service {
14namespace NWM {
15
16enum class SAP : u8 { SNAPExtensionUsed = 0xAA };
17
18enum class PDUControl : u8 { UnnumberedInformation = 3 };
19
20enum class EtherType : u16 { SecureData = 0x876D, EAPoL = 0x888E };
21
22/*
23 * 802.2 header, UDS packets always use SNAP for these headers,
24 * which means the dsap and ssap are always SNAPExtensionUsed (0xAA)
25 * and the OUI is always 0.
26 */
27struct LLCHeader {
28 u8 dsap = static_cast<u8>(SAP::SNAPExtensionUsed);
29 u8 ssap = static_cast<u8>(SAP::SNAPExtensionUsed);
30 u8 control = static_cast<u8>(PDUControl::UnnumberedInformation);
31 std::array<u8, 3> OUI = {};
32 u16_be protocol;
33};
34
35static_assert(sizeof(LLCHeader) == 8, "LLCHeader has the wrong size");
36
37/*
38 * Nintendo SecureData header, every UDS packet contains one,
39 * it is used to store metadata about the transmission such as
40 * the source and destination network node ids.
41 */
42struct SecureDataHeader {
43 // TODO(Subv): It is likely that the first 4 bytes of this header are
44 // actually part of another container protocol.
45 u16_be protocol_size;
46 INSERT_PADDING_BYTES(2);
47 u16_be securedata_size;
48 u8 is_management;
49 u8 data_channel;
50 u16_be sequence_number;
51 u16_be dest_node_id;
52 u16_be src_node_id;
53};
54
55static_assert(sizeof(SecureDataHeader) == 14, "SecureDataHeader has the wrong size");
56
57/*
58 * The raw bytes of this structure are the CTR used in the encryption (AES-CTR)
59 * process used to generate the CCMP key for data frame encryption.
60 */
61struct DataFrameCryptoCTR {
62 u32_le wlan_comm_id;
63 u32_le network_id;
64 std::array<u8, 6> host_mac;
65 u16_le id;
66};
67
68static_assert(sizeof(DataFrameCryptoCTR) == 16, "DataFrameCryptoCTR has the wrong size");
69
70/**
71 * Generates an unencrypted 802.11 data payload.
72 * @returns The generated frame payload.
73 */
74std::vector<u8> GenerateDataPayload(const std::vector<u8>& data, u8 channel, u16 dest_node,
75 u16 src_node, u16 sequence_number);
76
77} // namespace NWM
78} // namespace Service
diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp
index e68b9f16a..e4b803046 100644
--- a/src/core/hle/svc.cpp
+++ b/src/core/hle/svc.cpp
@@ -25,6 +25,7 @@
25#include "core/hle/kernel/semaphore.h" 25#include "core/hle/kernel/semaphore.h"
26#include "core/hle/kernel/server_port.h" 26#include "core/hle/kernel/server_port.h"
27#include "core/hle/kernel/server_session.h" 27#include "core/hle/kernel/server_session.h"
28#include "core/hle/kernel/session.h"
28#include "core/hle/kernel/shared_memory.h" 29#include "core/hle/kernel/shared_memory.h"
29#include "core/hle/kernel/thread.h" 30#include "core/hle/kernel/thread.h"
30#include "core/hle/kernel/timer.h" 31#include "core/hle/kernel/timer.h"
@@ -36,8 +37,9 @@
36//////////////////////////////////////////////////////////////////////////////////////////////////// 37////////////////////////////////////////////////////////////////////////////////////////////////////
37// Namespace SVC 38// Namespace SVC
38 39
39using Kernel::SharedPtr;
40using Kernel::ERR_INVALID_HANDLE; 40using Kernel::ERR_INVALID_HANDLE;
41using Kernel::Handle;
42using Kernel::SharedPtr;
41 43
42namespace SVC { 44namespace SVC {
43 45
@@ -236,7 +238,7 @@ static ResultCode SendSyncRequest(Kernel::Handle handle) {
236 238
237 // TODO(Subv): svcSendSyncRequest should put the caller thread to sleep while the server 239 // TODO(Subv): svcSendSyncRequest should put the caller thread to sleep while the server
238 // responds and cause a reschedule. 240 // responds and cause a reschedule.
239 return session->SendSyncRequest(); 241 return session->SendSyncRequest(Kernel::GetCurrentThread());
240} 242}
241 243
242/// Close a handle 244/// Close a handle
@@ -397,6 +399,112 @@ static ResultCode WaitSynchronizationN(s32* out, Kernel::Handle* handles, s32 ha
397 } 399 }
398} 400}
399 401
402/// In a single operation, sends a IPC reply and waits for a new request.
403static ResultCode ReplyAndReceive(s32* index, Kernel::Handle* handles, s32 handle_count,
404 Kernel::Handle reply_target) {
405 // 'handles' has to be a valid pointer even if 'handle_count' is 0.
406 if (handles == nullptr)
407 return Kernel::ERR_INVALID_POINTER;
408
409 // Check if 'handle_count' is invalid
410 if (handle_count < 0)
411 return Kernel::ERR_OUT_OF_RANGE;
412
413 using ObjectPtr = SharedPtr<Kernel::WaitObject>;
414 std::vector<ObjectPtr> objects(handle_count);
415
416 for (int i = 0; i < handle_count; ++i) {
417 auto object = Kernel::g_handle_table.Get<Kernel::WaitObject>(handles[i]);
418 if (object == nullptr)
419 return ERR_INVALID_HANDLE;
420 objects[i] = object;
421 }
422
423 // We are also sending a command reply.
424 // Do not send a reply if the command id in the command buffer is 0xFFFF.
425 u32* cmd_buff = Kernel::GetCommandBuffer();
426 IPC::Header header{cmd_buff[0]};
427 if (reply_target != 0 && header.command_id != 0xFFFF) {
428 auto session = Kernel::g_handle_table.Get<Kernel::ServerSession>(reply_target);
429 if (session == nullptr)
430 return ERR_INVALID_HANDLE;
431
432 auto request_thread = std::move(session->currently_handling);
433
434 // Mark the request as "handled".
435 session->currently_handling = nullptr;
436
437 // Error out if there's no request thread or the session was closed.
438 // TODO(Subv): Is the same error code (ClosedByRemote) returned for both of these cases?
439 if (request_thread == nullptr || session->parent->client == nullptr) {
440 *index = -1;
441 return Kernel::ERR_SESSION_CLOSED_BY_REMOTE;
442 }
443
444 // TODO(Subv): Perform IPC translation from the current thread to request_thread.
445
446 // Note: The scheduler is not invoked here.
447 request_thread->ResumeFromWait();
448 }
449
450 if (handle_count == 0) {
451 *index = 0;
452 // The kernel uses this value as a placeholder for the real error, and returns it when we
453 // pass no handles and do not perform any reply.
454 if (reply_target == 0 || header.command_id == 0xFFFF)
455 return ResultCode(0xE7E3FFFF);
456
457 return RESULT_SUCCESS;
458 }
459
460 auto thread = Kernel::GetCurrentThread();
461
462 // Find the first object that is acquirable in the provided list of objects
463 auto itr = std::find_if(objects.begin(), objects.end(), [thread](const ObjectPtr& object) {
464 return !object->ShouldWait(thread);
465 });
466
467 if (itr != objects.end()) {
468 // We found a ready object, acquire it and set the result value
469 Kernel::WaitObject* object = itr->get();
470 object->Acquire(thread);
471 *index = std::distance(objects.begin(), itr);
472
473 if (object->GetHandleType() == Kernel::HandleType::ServerSession) {
474 auto server_session = static_cast<Kernel::ServerSession*>(object);
475 if (server_session->parent->client == nullptr)
476 return Kernel::ERR_SESSION_CLOSED_BY_REMOTE;
477
478 // TODO(Subv): Perform IPC translation from the ServerSession to the current thread.
479 }
480 return RESULT_SUCCESS;
481 }
482
483 // No objects were ready to be acquired, prepare to suspend the thread.
484
485 // TODO(Subv): Perform IPC translation upon wakeup.
486
487 // Put the thread to sleep
488 thread->status = THREADSTATUS_WAIT_SYNCH_ANY;
489
490 // Add the thread to each of the objects' waiting threads.
491 for (size_t i = 0; i < objects.size(); ++i) {
492 Kernel::WaitObject* object = objects[i].get();
493 object->AddWaitingThread(thread);
494 }
495
496 thread->wait_objects = std::move(objects);
497
498 Core::System::GetInstance().PrepareReschedule();
499
500 // Note: The output of this SVC will be set to RESULT_SUCCESS if the thread resumes due to a
501 // signal in one of its wait objects, or to 0xC8A01836 if there was a translation error.
502 // By default the index is set to -1.
503 thread->wait_set_output = true;
504 *index = -1;
505 return RESULT_SUCCESS;
506}
507
400/// Create an address arbiter (to allocate access to shared resources) 508/// Create an address arbiter (to allocate access to shared resources)
401static ResultCode CreateAddressArbiter(Kernel::Handle* out_handle) { 509static ResultCode CreateAddressArbiter(Kernel::Handle* out_handle) {
402 using Kernel::AddressArbiter; 510 using Kernel::AddressArbiter;
@@ -933,7 +1041,6 @@ static ResultCode CreatePort(Kernel::Handle* server_port, Kernel::Handle* client
933 1041
934 using Kernel::ServerPort; 1042 using Kernel::ServerPort;
935 using Kernel::ClientPort; 1043 using Kernel::ClientPort;
936 using Kernel::SharedPtr;
937 1044
938 auto ports = ServerPort::CreatePortPair(max_sessions); 1045 auto ports = ServerPort::CreatePortPair(max_sessions);
939 CASCADE_RESULT(*client_port, Kernel::g_handle_table.Create( 1046 CASCADE_RESULT(*client_port, Kernel::g_handle_table.Create(
@@ -947,6 +1054,41 @@ static ResultCode CreatePort(Kernel::Handle* server_port, Kernel::Handle* client
947 return RESULT_SUCCESS; 1054 return RESULT_SUCCESS;
948} 1055}
949 1056
1057static ResultCode CreateSessionToPort(Handle* out_client_session, Handle client_port_handle) {
1058 using Kernel::ClientPort;
1059 SharedPtr<ClientPort> client_port = Kernel::g_handle_table.Get<ClientPort>(client_port_handle);
1060 if (client_port == nullptr)
1061 return ERR_INVALID_HANDLE;
1062
1063 CASCADE_RESULT(auto session, client_port->Connect());
1064 CASCADE_RESULT(*out_client_session, Kernel::g_handle_table.Create(std::move(session)));
1065 return RESULT_SUCCESS;
1066}
1067
1068static ResultCode CreateSession(Handle* server_session, Handle* client_session) {
1069 auto sessions = Kernel::ServerSession::CreateSessionPair();
1070
1071 auto& server = std::get<SharedPtr<Kernel::ServerSession>>(sessions);
1072 CASCADE_RESULT(*server_session, Kernel::g_handle_table.Create(std::move(server)));
1073
1074 auto& client = std::get<SharedPtr<Kernel::ClientSession>>(sessions);
1075 CASCADE_RESULT(*client_session, Kernel::g_handle_table.Create(std::move(client)));
1076
1077 LOG_TRACE(Kernel_SVC, "called");
1078 return RESULT_SUCCESS;
1079}
1080
1081static ResultCode AcceptSession(Handle* out_server_session, Handle server_port_handle) {
1082 using Kernel::ServerPort;
1083 SharedPtr<ServerPort> server_port = Kernel::g_handle_table.Get<ServerPort>(server_port_handle);
1084 if (server_port == nullptr)
1085 return ERR_INVALID_HANDLE;
1086
1087 CASCADE_RESULT(auto session, server_port->Accept());
1088 CASCADE_RESULT(*out_server_session, Kernel::g_handle_table.Create(std::move(session)));
1089 return RESULT_SUCCESS;
1090}
1091
950static ResultCode GetSystemInfo(s64* out, u32 type, s32 param) { 1092static ResultCode GetSystemInfo(s64* out, u32 type, s32 param) {
951 using Kernel::MemoryRegion; 1093 using Kernel::MemoryRegion;
952 1094
@@ -1121,14 +1263,14 @@ static const FunctionDef SVC_Table[] = {
1121 {0x45, nullptr, "Unknown"}, 1263 {0x45, nullptr, "Unknown"},
1122 {0x46, nullptr, "Unknown"}, 1264 {0x46, nullptr, "Unknown"},
1123 {0x47, HLE::Wrap<CreatePort>, "CreatePort"}, 1265 {0x47, HLE::Wrap<CreatePort>, "CreatePort"},
1124 {0x48, nullptr, "CreateSessionToPort"}, 1266 {0x48, HLE::Wrap<CreateSessionToPort>, "CreateSessionToPort"},
1125 {0x49, nullptr, "CreateSession"}, 1267 {0x49, HLE::Wrap<CreateSession>, "CreateSession"},
1126 {0x4A, nullptr, "AcceptSession"}, 1268 {0x4A, HLE::Wrap<AcceptSession>, "AcceptSession"},
1127 {0x4B, nullptr, "ReplyAndReceive1"}, 1269 {0x4B, nullptr, "ReplyAndReceive1"},
1128 {0x4C, nullptr, "ReplyAndReceive2"}, 1270 {0x4C, nullptr, "ReplyAndReceive2"},
1129 {0x4D, nullptr, "ReplyAndReceive3"}, 1271 {0x4D, nullptr, "ReplyAndReceive3"},
1130 {0x4E, nullptr, "ReplyAndReceive4"}, 1272 {0x4E, nullptr, "ReplyAndReceive4"},
1131 {0x4F, nullptr, "ReplyAndReceive"}, 1273 {0x4F, HLE::Wrap<ReplyAndReceive>, "ReplyAndReceive"},
1132 {0x50, nullptr, "BindInterrupt"}, 1274 {0x50, nullptr, "BindInterrupt"},
1133 {0x51, nullptr, "UnbindInterrupt"}, 1275 {0x51, nullptr, "UnbindInterrupt"},
1134 {0x52, nullptr, "InvalidateProcessDataCache"}, 1276 {0x52, nullptr, "InvalidateProcessDataCache"},
diff --git a/src/core/hw/aes/key.h b/src/core/hw/aes/key.h
index b01d04f13..c9f1342f4 100644
--- a/src/core/hw/aes/key.h
+++ b/src/core/hw/aes/key.h
@@ -12,6 +12,8 @@ namespace HW {
12namespace AES { 12namespace AES {
13 13
14enum KeySlotID : size_t { 14enum KeySlotID : size_t {
15 // AES Keyslot used to generate the UDS data frame CCMP key.
16 UDSDataKey = 0x2D,
15 APTWrap = 0x31, 17 APTWrap = 0x31,
16 18
17 MaxKeySlotID = 0x40, 19 MaxKeySlotID = 0x40,
diff --git a/src/core/hw/gpu.cpp b/src/core/hw/gpu.cpp
index 42809c731..6838e449c 100644
--- a/src/core/hw/gpu.cpp
+++ b/src/core/hw/gpu.cpp
@@ -5,6 +5,7 @@
5#include <cstring> 5#include <cstring>
6#include <numeric> 6#include <numeric>
7#include <type_traits> 7#include <type_traits>
8#include "common/alignment.h"
8#include "common/color.h" 9#include "common/color.h"
9#include "common/common_types.h" 10#include "common/common_types.h"
10#include "common/logging/log.h" 11#include "common/logging/log.h"
@@ -313,7 +314,7 @@ static void TextureCopy(const Regs::DisplayTransferConfig& config) {
313 const PAddr src_addr = config.GetPhysicalInputAddress(); 314 const PAddr src_addr = config.GetPhysicalInputAddress();
314 const PAddr dst_addr = config.GetPhysicalOutputAddress(); 315 const PAddr dst_addr = config.GetPhysicalOutputAddress();
315 316
316 // TODO: do hwtest with these cases 317 // TODO: do hwtest with invalid addresses
317 if (!Memory::IsValidPhysicalAddress(src_addr)) { 318 if (!Memory::IsValidPhysicalAddress(src_addr)) {
318 LOG_CRITICAL(HW_GPU, "invalid input address 0x%08X", src_addr); 319 LOG_CRITICAL(HW_GPU, "invalid input address 0x%08X", src_addr);
319 return; 320 return;
@@ -324,31 +325,36 @@ static void TextureCopy(const Regs::DisplayTransferConfig& config) {
324 return; 325 return;
325 } 326 }
326 327
327 if (config.texture_copy.input_width == 0) { 328 if (VideoCore::g_renderer->Rasterizer()->AccelerateTextureCopy(config))
328 LOG_CRITICAL(HW_GPU, "zero input width");
329 return; 329 return;
330 }
331 330
332 if (config.texture_copy.output_width == 0) { 331 u8* src_pointer = Memory::GetPhysicalPointer(src_addr);
333 LOG_CRITICAL(HW_GPU, "zero output width"); 332 u8* dst_pointer = Memory::GetPhysicalPointer(dst_addr);
333
334 u32 remaining_size = Common::AlignDown(config.texture_copy.size, 16);
335
336 if (remaining_size == 0) {
337 LOG_CRITICAL(HW_GPU, "zero size. Real hardware freezes on this.");
334 return; 338 return;
335 } 339 }
336 340
337 if (config.texture_copy.size == 0) { 341 u32 input_gap = config.texture_copy.input_gap * 16;
338 LOG_CRITICAL(HW_GPU, "zero size"); 342 u32 output_gap = config.texture_copy.output_gap * 16;
343
344 // Zero gap means contiguous input/output even if width = 0. To avoid infinite loop below, width
345 // is assigned with the total size if gap = 0.
346 u32 input_width = input_gap == 0 ? remaining_size : config.texture_copy.input_width * 16;
347 u32 output_width = output_gap == 0 ? remaining_size : config.texture_copy.output_width * 16;
348
349 if (input_width == 0) {
350 LOG_CRITICAL(HW_GPU, "zero input width. Real hardware freezes on this.");
339 return; 351 return;
340 } 352 }
341 353
342 if (VideoCore::g_renderer->Rasterizer()->AccelerateTextureCopy(config)) 354 if (output_width == 0) {
355 LOG_CRITICAL(HW_GPU, "zero output width. Real hardware freezes on this.");
343 return; 356 return;
344 357 }
345 u8* src_pointer = Memory::GetPhysicalPointer(src_addr);
346 u8* dst_pointer = Memory::GetPhysicalPointer(dst_addr);
347
348 u32 input_width = config.texture_copy.input_width * 16;
349 u32 input_gap = config.texture_copy.input_gap * 16;
350 u32 output_width = config.texture_copy.output_width * 16;
351 u32 output_gap = config.texture_copy.output_gap * 16;
352 358
353 size_t contiguous_input_size = 359 size_t contiguous_input_size =
354 config.texture_copy.size / input_width * (input_width + input_gap); 360 config.texture_copy.size / input_width * (input_width + input_gap);
@@ -360,7 +366,6 @@ static void TextureCopy(const Regs::DisplayTransferConfig& config) {
360 Memory::RasterizerFlushAndInvalidateRegion(config.GetPhysicalOutputAddress(), 366 Memory::RasterizerFlushAndInvalidateRegion(config.GetPhysicalOutputAddress(),
361 static_cast<u32>(contiguous_output_size)); 367 static_cast<u32>(contiguous_output_size));
362 368
363 u32 remaining_size = config.texture_copy.size;
364 u32 remaining_input = input_width; 369 u32 remaining_input = input_width;
365 u32 remaining_output = output_width; 370 u32 remaining_output = output_width;
366 while (remaining_size > 0) { 371 while (remaining_size > 0) {
diff --git a/src/core/hw/gpu.h b/src/core/hw/gpu.h
index bdd997b2a..21b127fee 100644
--- a/src/core/hw/gpu.h
+++ b/src/core/hw/gpu.h
@@ -225,7 +225,7 @@ struct Regs {
225 INSERT_PADDING_WORDS(0x1); 225 INSERT_PADDING_WORDS(0x1);
226 226
227 struct { 227 struct {
228 u32 size; 228 u32 size; // The lower 4 bits are ignored
229 229
230 union { 230 union {
231 u32 input_size; 231 u32 input_size;
diff --git a/src/network/CMakeLists.txt b/src/network/CMakeLists.txt
new file mode 100644
index 000000000..aeabe430e
--- /dev/null
+++ b/src/network/CMakeLists.txt
@@ -0,0 +1,16 @@
1set(SRCS
2 network.cpp
3 room.cpp
4 room_member.cpp
5 )
6
7set(HEADERS
8 network.h
9 room.h
10 room_member.h
11 )
12
13create_directory_groups(${SRCS} ${HEADERS})
14
15add_library(network STATIC ${SRCS} ${HEADERS})
16target_link_libraries(network PRIVATE common enet)
diff --git a/src/network/network.cpp b/src/network/network.cpp
new file mode 100644
index 000000000..51b5d6a9f
--- /dev/null
+++ b/src/network/network.cpp
@@ -0,0 +1,50 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/assert.h"
6#include "common/logging/log.h"
7#include "enet/enet.h"
8#include "network/network.h"
9
10namespace Network {
11
12static std::shared_ptr<RoomMember> g_room_member; ///< RoomMember (Client) for network games
13static std::shared_ptr<Room> g_room; ///< Room (Server) for network games
14// TODO(B3N30): Put these globals into a networking class
15
16bool Init() {
17 if (enet_initialize() != 0) {
18 LOG_ERROR(Network, "Error initalizing ENet");
19 return false;
20 }
21 g_room = std::make_shared<Room>();
22 g_room_member = std::make_shared<RoomMember>();
23 LOG_DEBUG(Network, "initialized OK");
24 return true;
25}
26
27std::weak_ptr<Room> GetRoom() {
28 return g_room;
29}
30
31std::weak_ptr<RoomMember> GetRoomMember() {
32 return g_room_member;
33}
34
35void Shutdown() {
36 if (g_room_member) {
37 if (g_room_member->IsConnected())
38 g_room_member->Leave();
39 g_room_member.reset();
40 }
41 if (g_room) {
42 if (g_room->GetState() == Room::State::Open)
43 g_room->Destroy();
44 g_room.reset();
45 }
46 enet_deinitialize();
47 LOG_DEBUG(Network, "shutdown OK");
48}
49
50} // namespace Network
diff --git a/src/network/network.h b/src/network/network.h
new file mode 100644
index 000000000..6d002d693
--- /dev/null
+++ b/src/network/network.h
@@ -0,0 +1,25 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <memory>
8#include "network/room.h"
9#include "network/room_member.h"
10
11namespace Network {
12
13/// Initializes and registers the network device, the room, and the room member.
14bool Init();
15
16/// Returns a pointer to the room handle
17std::weak_ptr<Room> GetRoom();
18
19/// Returns a pointer to the room member handle
20std::weak_ptr<RoomMember> GetRoomMember();
21
22/// Unregisters the network device, the room, and the room member and shut them down.
23void Shutdown();
24
25} // namespace Network
diff --git a/src/network/room.cpp b/src/network/room.cpp
new file mode 100644
index 000000000..48de2f5cb
--- /dev/null
+++ b/src/network/room.cpp
@@ -0,0 +1,60 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "enet/enet.h"
6#include "network/room.h"
7
8namespace Network {
9
10/// Maximum number of concurrent connections allowed to this room.
11static constexpr u32 MaxConcurrentConnections = 10;
12
13class Room::RoomImpl {
14public:
15 ENetHost* server = nullptr; ///< Network interface.
16
17 std::atomic<State> state{State::Closed}; ///< Current state of the room.
18 RoomInformation room_information; ///< Information about this room.
19};
20
21Room::Room() : room_impl{std::make_unique<RoomImpl>()} {}
22
23Room::~Room() = default;
24
25void Room::Create(const std::string& name, const std::string& server_address, u16 server_port) {
26 ENetAddress address;
27 address.host = ENET_HOST_ANY;
28 enet_address_set_host(&address, server_address.c_str());
29 address.port = server_port;
30
31 room_impl->server = enet_host_create(&address, MaxConcurrentConnections, NumChannels, 0, 0);
32 // TODO(B3N30): Allow specifying the maximum number of concurrent connections.
33 room_impl->state = State::Open;
34
35 room_impl->room_information.name = name;
36 room_impl->room_information.member_slots = MaxConcurrentConnections;
37
38 // TODO(B3N30): Start the receiving thread
39}
40
41Room::State Room::GetState() const {
42 return room_impl->state;
43}
44
45const RoomInformation& Room::GetRoomInformation() const {
46 return room_impl->room_information;
47}
48
49void Room::Destroy() {
50 room_impl->state = State::Closed;
51 // TODO(B3n30): Join the receiving thread
52
53 if (room_impl->server) {
54 enet_host_destroy(room_impl->server);
55 }
56 room_impl->room_information = {};
57 room_impl->server = nullptr;
58}
59
60} // namespace Network
diff --git a/src/network/room.h b/src/network/room.h
new file mode 100644
index 000000000..70c64d5f1
--- /dev/null
+++ b/src/network/room.h
@@ -0,0 +1,60 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <atomic>
8#include <memory>
9#include <string>
10#include "common/common_types.h"
11
12namespace Network {
13
14constexpr u16 DefaultRoomPort = 1234;
15constexpr size_t NumChannels = 1; // Number of channels used for the connection
16
17struct RoomInformation {
18 std::string name; ///< Name of the server
19 u32 member_slots; ///< Maximum number of members in this room
20};
21
22/// This is what a server [person creating a server] would use.
23class Room final {
24public:
25 enum class State : u8 {
26 Open, ///< The room is open and ready to accept connections.
27 Closed, ///< The room is not opened and can not accept connections.
28 };
29
30 Room();
31 ~Room();
32
33 /**
34 * Gets the current state of the room.
35 */
36 State GetState() const;
37
38 /**
39 * Gets the room information of the room.
40 */
41 const RoomInformation& GetRoomInformation() const;
42
43 /**
44 * Creates the socket for this room. Will bind to default address if
45 * server is empty string.
46 */
47 void Create(const std::string& name, const std::string& server = "",
48 u16 server_port = DefaultRoomPort);
49
50 /**
51 * Destroys the socket
52 */
53 void Destroy();
54
55private:
56 class RoomImpl;
57 std::unique_ptr<RoomImpl> room_impl;
58};
59
60} // namespace Network
diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp
new file mode 100644
index 000000000..c87f009f4
--- /dev/null
+++ b/src/network/room_member.cpp
@@ -0,0 +1,74 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/assert.h"
6#include "enet/enet.h"
7#include "network/room_member.h"
8
9namespace Network {
10
11constexpr u32 ConnectionTimeoutMs = 5000;
12
13class RoomMember::RoomMemberImpl {
14public:
15 ENetHost* client = nullptr; ///< ENet network interface.
16 ENetPeer* server = nullptr; ///< The server peer the client is connected to
17
18 std::atomic<State> state{State::Idle}; ///< Current state of the RoomMember.
19
20 std::string nickname; ///< The nickname of this member.
21};
22
23RoomMember::RoomMember() : room_member_impl{std::make_unique<RoomMemberImpl>()} {
24 room_member_impl->client = enet_host_create(nullptr, 1, NumChannels, 0, 0);
25 ASSERT_MSG(room_member_impl->client != nullptr, "Could not create client");
26}
27
28RoomMember::~RoomMember() {
29 ASSERT_MSG(!IsConnected(), "RoomMember is being destroyed while connected");
30 enet_host_destroy(room_member_impl->client);
31}
32
33RoomMember::State RoomMember::GetState() const {
34 return room_member_impl->state;
35}
36
37void RoomMember::Join(const std::string& nick, const char* server_addr, u16 server_port,
38 u16 client_port) {
39 ENetAddress address{};
40 enet_address_set_host(&address, server_addr);
41 address.port = server_port;
42
43 room_member_impl->server =
44 enet_host_connect(room_member_impl->client, &address, NumChannels, 0);
45
46 if (!room_member_impl->server) {
47 room_member_impl->state = State::Error;
48 return;
49 }
50
51 ENetEvent event{};
52 int net = enet_host_service(room_member_impl->client, &event, ConnectionTimeoutMs);
53 if (net > 0 && event.type == ENET_EVENT_TYPE_CONNECT) {
54 room_member_impl->nickname = nick;
55 room_member_impl->state = State::Joining;
56 // TODO(B3N30): Send a join request with the nickname to the server
57 // TODO(B3N30): Start the receive thread
58 } else {
59 room_member_impl->state = State::CouldNotConnect;
60 }
61}
62
63bool RoomMember::IsConnected() const {
64 return room_member_impl->state == State::Joining || room_member_impl->state == State::Joined;
65}
66
67void RoomMember::Leave() {
68 enet_peer_disconnect(room_member_impl->server, 0);
69 room_member_impl->state = State::Idle;
70 // TODO(B3N30): Close the receive thread
71 enet_peer_reset(room_member_impl->server);
72}
73
74} // namespace Network
diff --git a/src/network/room_member.h b/src/network/room_member.h
new file mode 100644
index 000000000..177622b69
--- /dev/null
+++ b/src/network/room_member.h
@@ -0,0 +1,65 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <atomic>
8#include <memory>
9#include <string>
10#include "common/common_types.h"
11#include "network/room.h"
12
13namespace Network {
14
15/**
16 * This is what a client [person joining a server] would use.
17 * It also has to be used if you host a game yourself (You'd create both, a Room and a
18 * RoomMembership for yourself)
19 */
20class RoomMember final {
21public:
22 enum class State : u8 {
23 Idle, ///< Default state
24 Error, ///< Some error [permissions to network device missing or something]
25 Joining, ///< The client is attempting to join a room.
26 Joined, ///< The client is connected to the room and is ready to send/receive packets.
27 LostConnection, ///< Connection closed
28
29 // Reasons why connection was rejected
30 NameCollision, ///< Somebody is already using this name
31 MacCollision, ///< Somebody is already using that mac-address
32 CouldNotConnect ///< The room is not responding to a connection attempt
33 };
34
35 RoomMember();
36 ~RoomMember();
37
38 /**
39 * Returns the status of our connection to the room.
40 */
41 State GetState() const;
42
43 /**
44 * Returns whether we're connected to a server or not.
45 */
46 bool IsConnected() const;
47
48 /**
49 * Attempts to join a room at the specified address and port, using the specified nickname.
50 * This may fail if the username is already taken.
51 */
52 void Join(const std::string& nickname, const char* server_addr = "127.0.0.1",
53 const u16 serverPort = DefaultRoomPort, const u16 clientPort = 0);
54
55 /**
56 * Leaves the current room.
57 */
58 void Leave();
59
60private:
61 class RoomMemberImpl;
62 std::unique_ptr<RoomMemberImpl> room_member_impl;
63};
64
65} // namespace Network
diff --git a/src/tests/core/hle/kernel/hle_ipc.cpp b/src/tests/core/hle/kernel/hle_ipc.cpp
index e07a28c5b..52336d027 100644
--- a/src/tests/core/hle/kernel/hle_ipc.cpp
+++ b/src/tests/core/hle/kernel/hle_ipc.cpp
@@ -18,7 +18,7 @@ static SharedPtr<Object> MakeObject() {
18 return Event::Create(ResetType::OneShot); 18 return Event::Create(ResetType::OneShot);
19} 19}
20 20
21TEST_CASE("HLERequestContext::PopoulateFromIncomingCommandBuffer", "[core][kernel]") { 21TEST_CASE("HLERequestContext::PopulateFromIncomingCommandBuffer", "[core][kernel]") {
22 auto session = std::get<SharedPtr<ServerSession>>(ServerSession::CreateSessionPair()); 22 auto session = std::get<SharedPtr<ServerSession>>(ServerSession::CreateSessionPair());
23 HLERequestContext context(std::move(session)); 23 HLERequestContext context(std::move(session));
24 24
@@ -94,6 +94,18 @@ TEST_CASE("HLERequestContext::PopoulateFromIncomingCommandBuffer", "[core][kerne
94 REQUIRE(context.GetIncomingHandle(output[5]) == c); 94 REQUIRE(context.GetIncomingHandle(output[5]) == c);
95 } 95 }
96 96
97 SECTION("translates null handles") {
98 const u32_le input[]{
99 IPC::MakeHeader(0, 0, 2), IPC::MoveHandleDesc(1), 0,
100 };
101
102 auto result = context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
103
104 REQUIRE(result == RESULT_SUCCESS);
105 auto* output = context.CommandBuffer();
106 REQUIRE(context.GetIncomingHandle(output[2]) == nullptr);
107 }
108
97 SECTION("translates CallingPid descriptors") { 109 SECTION("translates CallingPid descriptors") {
98 const u32_le input[]{ 110 const u32_le input[]{
99 IPC::MakeHeader(0, 0, 2), IPC::CallingPidDesc(), 0x98989898, 111 IPC::MakeHeader(0, 0, 2), IPC::CallingPidDesc(), 0x98989898,
@@ -171,6 +183,17 @@ TEST_CASE("HLERequestContext::WriteToOutgoingCommandBuffer", "[core][kernel]") {
171 REQUIRE(handle_table.GetGeneric(output[4]) == b); 183 REQUIRE(handle_table.GetGeneric(output[4]) == b);
172 } 184 }
173 185
186 SECTION("translates null handles") {
187 input[0] = IPC::MakeHeader(0, 0, 2);
188 input[1] = IPC::MoveHandleDesc(1);
189 input[2] = context.AddOutgoingHandle(nullptr);
190
191 auto result = context.WriteToOutgoingCommandBuffer(output, *process, handle_table);
192
193 REQUIRE(result == RESULT_SUCCESS);
194 REQUIRE(output[2] == 0);
195 }
196
174 SECTION("translates multi-handle descriptors") { 197 SECTION("translates multi-handle descriptors") {
175 auto a = MakeObject(); 198 auto a = MakeObject();
176 auto b = MakeObject(); 199 auto b = MakeObject();
diff --git a/src/video_core/pica_state.h b/src/video_core/pica_state.h
index 3b00df0b3..2d23d34e6 100644
--- a/src/video_core/pica_state.h
+++ b/src/video_core/pica_state.h
@@ -111,6 +111,14 @@ struct State {
111 111
112 BitField<0, 13, s32> difference; // 1.1.11 fixed point 112 BitField<0, 13, s32> difference; // 1.1.11 fixed point
113 BitField<13, 11, u32> value; // 0.0.11 fixed point 113 BitField<13, 11, u32> value; // 0.0.11 fixed point
114
115 float ToFloat() const {
116 return static_cast<float>(value) / 2047.0f;
117 }
118
119 float DiffToFloat() const {
120 return static_cast<float>(difference) / 2047.0f;
121 }
114 }; 122 };
115 123
116 std::array<LutEntry, 128> lut; 124 std::array<LutEntry, 128> lut;
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index 8b7991c04..ff3f69ba3 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -94,10 +94,10 @@ RasterizerOpenGL::RasterizerOpenGL() : shader_dirty(true) {
94 framebuffer.Create(); 94 framebuffer.Create();
95 95
96 // Allocate and bind lighting lut textures 96 // Allocate and bind lighting lut textures
97 lighting_lut_buffer.Create(); 97 lighting_lut.Create();
98 state.lighting_lut.texture_buffer = lighting_lut.handle; 98 state.lighting_lut.texture_buffer = lighting_lut.handle;
99 state.Apply(); 99 state.Apply();
100 lighting_lut.Create(); 100 lighting_lut_buffer.Create();
101 glBindBuffer(GL_TEXTURE_BUFFER, lighting_lut_buffer.handle); 101 glBindBuffer(GL_TEXTURE_BUFFER, lighting_lut_buffer.handle);
102 glBufferData(GL_TEXTURE_BUFFER, 102 glBufferData(GL_TEXTURE_BUFFER,
103 sizeof(GLfloat) * 2 * 256 * Pica::LightingRegs::NumLightingSampler, nullptr, 103 sizeof(GLfloat) * 2 * 256 * Pica::LightingRegs::NumLightingSampler, nullptr,
@@ -106,16 +106,14 @@ RasterizerOpenGL::RasterizerOpenGL() : shader_dirty(true) {
106 glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, lighting_lut_buffer.handle); 106 glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, lighting_lut_buffer.handle);
107 107
108 // Setup the LUT for the fog 108 // Setup the LUT for the fog
109 { 109 fog_lut.Create();
110 fog_lut.Create(); 110 state.fog_lut.texture_buffer = fog_lut.handle;
111 state.fog_lut.texture_1d = fog_lut.handle;
112 }
113 state.Apply(); 111 state.Apply();
114 112 fog_lut_buffer.Create();
113 glBindBuffer(GL_TEXTURE_BUFFER, fog_lut_buffer.handle);
114 glBufferData(GL_TEXTURE_BUFFER, sizeof(GLfloat) * 2 * 128, nullptr, GL_DYNAMIC_DRAW);
115 glActiveTexture(TextureUnits::FogLUT.Enum()); 115 glActiveTexture(TextureUnits::FogLUT.Enum());
116 glTexImage1D(GL_TEXTURE_1D, 0, GL_R32UI, 128, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, nullptr); 116 glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, fog_lut_buffer.handle);
117 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
118 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
119 117
120 // Setup the noise LUT for proctex 118 // Setup the noise LUT for proctex
121 proctex_noise_lut.Create(); 119 proctex_noise_lut.Create();
@@ -1356,16 +1354,17 @@ void RasterizerOpenGL::SyncFogColor() {
1356} 1354}
1357 1355
1358void RasterizerOpenGL::SyncFogLUT() { 1356void RasterizerOpenGL::SyncFogLUT() {
1359 std::array<GLuint, 128> new_data; 1357 std::array<GLvec2, 128> new_data;
1360 1358
1361 std::transform(Pica::g_state.fog.lut.begin(), Pica::g_state.fog.lut.end(), new_data.begin(), 1359 std::transform(Pica::g_state.fog.lut.begin(), Pica::g_state.fog.lut.end(), new_data.begin(),
1362 [](const auto& entry) { return entry.raw; }); 1360 [](const auto& entry) {
1361 return GLvec2{entry.ToFloat(), entry.DiffToFloat()};
1362 });
1363 1363
1364 if (new_data != fog_lut_data) { 1364 if (new_data != fog_lut_data) {
1365 fog_lut_data = new_data; 1365 fog_lut_data = new_data;
1366 glActiveTexture(TextureUnits::FogLUT.Enum()); 1366 glBindBuffer(GL_TEXTURE_BUFFER, fog_lut_buffer.handle);
1367 glTexSubImage1D(GL_TEXTURE_1D, 0, 0, 128, GL_RED_INTEGER, GL_UNSIGNED_INT, 1367 glBufferSubData(GL_TEXTURE_BUFFER, 0, new_data.size() * sizeof(GLvec2), new_data.data());
1368 fog_lut_data.data());
1369 } 1368 }
1370} 1369}
1371 1370
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index 79acd4230..a433c1d4a 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -283,8 +283,9 @@ private:
283 OGLTexture lighting_lut; 283 OGLTexture lighting_lut;
284 std::array<std::array<GLvec2, 256>, Pica::LightingRegs::NumLightingSampler> lighting_lut_data{}; 284 std::array<std::array<GLvec2, 256>, Pica::LightingRegs::NumLightingSampler> lighting_lut_data{};
285 285
286 OGLBuffer fog_lut_buffer;
286 OGLTexture fog_lut; 287 OGLTexture fog_lut;
287 std::array<GLuint, 128> fog_lut_data{}; 288 std::array<GLvec2, 128> fog_lut_data{};
288 289
289 OGLTexture proctex_noise_lut; 290 OGLTexture proctex_noise_lut;
290 std::array<GLvec2, 128> proctex_noise_lut_data{}; 291 std::array<GLvec2, 128> proctex_noise_lut_data{};
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp
index 0c7c4dd5c..c93b108fb 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp
@@ -1052,7 +1052,7 @@ layout (std140) uniform shader_data {
1052 1052
1053uniform sampler2D tex[3]; 1053uniform sampler2D tex[3];
1054uniform samplerBuffer lighting_lut; 1054uniform samplerBuffer lighting_lut;
1055uniform usampler1D fog_lut; 1055uniform samplerBuffer fog_lut;
1056uniform sampler1D proctex_noise_lut; 1056uniform sampler1D proctex_noise_lut;
1057uniform sampler1D proctex_color_map; 1057uniform sampler1D proctex_color_map;
1058uniform sampler1D proctex_alpha_map; 1058uniform sampler1D proctex_alpha_map;
@@ -1145,12 +1145,8 @@ vec4 secondary_fragment_color = vec4(0.0);
1145 // Generate clamped fog factor from LUT for given fog index 1145 // Generate clamped fog factor from LUT for given fog index
1146 out += "float fog_i = clamp(floor(fog_index), 0.0, 127.0);\n"; 1146 out += "float fog_i = clamp(floor(fog_index), 0.0, 127.0);\n";
1147 out += "float fog_f = fog_index - fog_i;\n"; 1147 out += "float fog_f = fog_index - fog_i;\n";
1148 out += "uint fog_lut_entry = texelFetch(fog_lut, int(fog_i), 0).r;\n"; 1148 out += "vec2 fog_lut_entry = texelFetch(fog_lut, int(fog_i)).rg;\n";
1149 out += "float fog_lut_entry_difference = float(int((fog_lut_entry & 0x1FFFU) << 19U) >> " 1149 out += "float fog_factor = fog_lut_entry.r + fog_lut_entry.g * fog_f;\n";
1150 "19);\n"; // Extract signed difference
1151 out += "float fog_lut_entry_value = float((fog_lut_entry >> 13U) & 0x7FFU);\n";
1152 out += "float fog_factor = (fog_lut_entry_value + fog_lut_entry_difference * fog_f) / "
1153 "2047.0;\n";
1154 out += "fog_factor = clamp(fog_factor, 0.0, 1.0);\n"; 1150 out += "fog_factor = clamp(fog_factor, 0.0, 1.0);\n";
1155 1151
1156 // Blend the fog 1152 // Blend the fog
diff --git a/src/video_core/renderer_opengl/gl_state.cpp b/src/video_core/renderer_opengl/gl_state.cpp
index 14e63115c..eface2dea 100644
--- a/src/video_core/renderer_opengl/gl_state.cpp
+++ b/src/video_core/renderer_opengl/gl_state.cpp
@@ -54,7 +54,7 @@ OpenGLState::OpenGLState() {
54 54
55 lighting_lut.texture_buffer = 0; 55 lighting_lut.texture_buffer = 0;
56 56
57 fog_lut.texture_1d = 0; 57 fog_lut.texture_buffer = 0;
58 58
59 proctex_lut.texture_1d = 0; 59 proctex_lut.texture_1d = 0;
60 proctex_diff_lut.texture_1d = 0; 60 proctex_diff_lut.texture_1d = 0;
@@ -198,9 +198,9 @@ void OpenGLState::Apply() const {
198 } 198 }
199 199
200 // Fog LUT 200 // Fog LUT
201 if (fog_lut.texture_1d != cur_state.fog_lut.texture_1d) { 201 if (fog_lut.texture_buffer != cur_state.fog_lut.texture_buffer) {
202 glActiveTexture(TextureUnits::FogLUT.Enum()); 202 glActiveTexture(TextureUnits::FogLUT.Enum());
203 glBindTexture(GL_TEXTURE_1D, fog_lut.texture_1d); 203 glBindTexture(GL_TEXTURE_BUFFER, fog_lut.texture_buffer);
204 } 204 }
205 205
206 // ProcTex Noise LUT 206 // ProcTex Noise LUT
@@ -272,8 +272,8 @@ void OpenGLState::ResetTexture(GLuint handle) {
272 } 272 }
273 if (cur_state.lighting_lut.texture_buffer == handle) 273 if (cur_state.lighting_lut.texture_buffer == handle)
274 cur_state.lighting_lut.texture_buffer = 0; 274 cur_state.lighting_lut.texture_buffer = 0;
275 if (cur_state.fog_lut.texture_1d == handle) 275 if (cur_state.fog_lut.texture_buffer == handle)
276 cur_state.fog_lut.texture_1d = 0; 276 cur_state.fog_lut.texture_buffer = 0;
277 if (cur_state.proctex_noise_lut.texture_1d == handle) 277 if (cur_state.proctex_noise_lut.texture_1d == handle)
278 cur_state.proctex_noise_lut.texture_1d = 0; 278 cur_state.proctex_noise_lut.texture_1d = 0;
279 if (cur_state.proctex_color_map.texture_1d == handle) 279 if (cur_state.proctex_color_map.texture_1d == handle)
diff --git a/src/video_core/renderer_opengl/gl_state.h b/src/video_core/renderer_opengl/gl_state.h
index bb0218708..1efcf0811 100644
--- a/src/video_core/renderer_opengl/gl_state.h
+++ b/src/video_core/renderer_opengl/gl_state.h
@@ -91,7 +91,7 @@ public:
91 } lighting_lut; 91 } lighting_lut;
92 92
93 struct { 93 struct {
94 GLuint texture_1d; // GL_TEXTURE_BINDING_1D 94 GLuint texture_buffer; // GL_TEXTURE_BINDING_BUFFER
95 } fog_lut; 95 } fog_lut;
96 96
97 struct { 97 struct {
diff --git a/src/video_core/swrasterizer/rasterizer.cpp b/src/video_core/swrasterizer/rasterizer.cpp
index cd7b6c39d..512e81c08 100644
--- a/src/video_core/swrasterizer/rasterizer.cpp
+++ b/src/video_core/swrasterizer/rasterizer.cpp
@@ -584,8 +584,7 @@ static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Ve
584 float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f); 584 float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
585 float fog_f = fog_index - fog_i; 585 float fog_f = fog_index - fog_i;
586 const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)]; 586 const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
587 float fog_factor = (fog_lut_entry.value + fog_lut_entry.difference * fog_f) / 587 float fog_factor = fog_lut_entry.ToFloat() + fog_lut_entry.DiffToFloat() * fog_f;
588 2047.0f; // This is signed fixed point 1.11
589 fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f); 588 fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
590 589
591 // Blend the fog 590 // Blend the fog