diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.cpp index 6bddd0252b..56d6ffd21f 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.cpp @@ -13,6 +13,7 @@ #include #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" +#include "Controllers/MgbaLink/MgbaLink_SharedLink.h" #include "CommonFramework/ImageTypes/ImageRGB32_Qt.h" #include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" @@ -221,17 +222,21 @@ void VideoSource_MgbaLink::poll_loop(){ } void VideoSource_MgbaLink::run_connection(Logger& logger, const std::string& host, uint16_t port){ - Connection connection(logger, GlobalThreadPools::unlimited_realtime(), host, port); + // Shared: a controller for the same address sends its commands on it. + std::shared_ptr connection = std::make_shared( + logger, GlobalThreadPools::unlimited_realtime(), host, port + ); { std::lock_guard lg(m_lock); if (m_stopping){ return; } - m_connection = &connection; + m_connection = connection.get(); } try{ - connection.open(); - poll_connected(logger, connection); + connection->open(); + LinkRegistry::Publication publication = link_registry().publish(m_address, connection); + poll_connected(logger, *connection); }catch (...){ std::lock_guard lg(m_lock); m_connection = nullptr; diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.h index a167ec857c..d0e1318402 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.h @@ -98,9 +98,10 @@ class VideoSourceDescriptor_MgbaLink : public VideoSourceDescriptor{ // drops it when the connection is lost, so a dead bridge shows no video. // // The bridge holds one client at a time, so this source takes its only -// slot. A controller for the same mGBA (slice 2: KEYS, GRANT) must not open -// a second connection: it has to share this one (Connection serializes -// commands from several threads). +// slot. While open, the connection is published in MgbaLink::link_registry() +// under the source's address; the mGBA controller for the same address +// sends KEYS and GRANT on it (Connection serializes commands from several +// threads). class VideoSource_MgbaLink : public VideoSource{ public: VideoSource_MgbaLink(Logger& logger, std::string address); diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index c6bbb619ab..ce76218576 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -25,6 +25,7 @@ #include "CommonFramework/Windows/LabChannel_Tests.h" #include "CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink_Tests.h" #include "Controllers/MgbaLink/MgbaLink_Keys_Tests.h" +#include "Controllers/MgbaLink/MgbaLink_KeySender_Tests.h" #include "Controllers/MgbaLink/MgbaLink_Tests.h" #include "NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_KeyMap_Tests.h" #include "CommonFramework/Windows/LabSnapshot_Tests.h" @@ -77,6 +78,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ add_tests_LabChannel(ret); MgbaLink::add_tests(ret); MgbaLink::add_key_tests(ret); + MgbaLink::add_key_sender_tests(ret); NintendoSwitch::add_tests_MgbaLinkKeyMap(ret); add_tests_VideoSource_MgbaLink(ret); add_tests_LabSnapshot(ret); diff --git a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp index edb904f191..e95aca7c6e 100644 --- a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp +++ b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp @@ -10,6 +10,7 @@ #include #include "Common/Qt/NoWheelComboBox.h" #include "CommonFramework/Panels/ConsoleSettingsStretch.h" +#include "CommonFramework/StaticGlobals.h" #include "Controllers/ControllerTypeStrings.h" #include "ControllerSelectorWidget.h" @@ -22,6 +23,23 @@ namespace PokemonAutomation{ template class RegisterUiStateQtWidget; +namespace{ + +// The interfaces the dropdown offers; mGBA Link only in Developer mode. +std::vector supported_interfaces(){ + std::vector interfaces{ + ControllerInterface::SerialPABotBase2, + ControllerInterface::TcpSysbotBase, +// ControllerInterface::UsbSysbotBase, + }; + if (STATIC_GLOBALS.DEVELOPER_MODE){ + interfaces.emplace_back(ControllerInterface::MgbaLink); + } + return interfaces; +} + +} // namespace + @@ -81,12 +99,7 @@ ControllerSelectorWidget::ControllerSelectorWidget( m_dropdowns->addWidget(m_interface_dropdown); - // Add all the supported interfaces. - { - m_interface_list.emplace_back(ControllerInterface::SerialPABotBase2); - m_interface_list.emplace_back(ControllerInterface::TcpSysbotBase); -// m_interface_list.emplace_back(ControllerInterface::UsbSysbotBase); - } + m_interface_list = supported_interfaces(); for (ControllerInterface item : m_interface_list){ diff --git a/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp b/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp index bbdddf11be..e59ff7eed8 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp +++ b/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp @@ -16,6 +16,7 @@ const EnumStringMap CONTROLLER_INTERFACE_STRINGS{ {ControllerInterface::SerialPABotBase2, "Serial: PABotBase2"}, {ControllerInterface::TcpSysbotBase, "TCP: sys-botbase"}, // {ControllerInterface::UsbSysbotBase, "USB: sys-botbase"}, + {ControllerInterface::MgbaLink, "TCP: mGBA Link"}, }; const EnumStringMap CONTROLLER_TYPE_STRINGS{ diff --git a/SerialPrograms/Source/Controllers/ControllerTypes.h b/SerialPrograms/Source/Controllers/ControllerTypes.h index 8a03518c01..c8a71a0018 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypes.h +++ b/SerialPrograms/Source/Controllers/ControllerTypes.h @@ -17,6 +17,7 @@ enum class ControllerInterface{ SerialPABotBase2, TcpSysbotBase, // UsbSysbotBase, + MgbaLink, // Developer mode only (fork lab tooling). }; enum class ControllerPerformanceClass{ diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.cpp b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.cpp new file mode 100644 index 0000000000..0c42810c65 --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.cpp @@ -0,0 +1,230 @@ +/* MgbaLink Key Sender + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "MgbaLink_KeySender.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + +namespace{ + +// How long a wait sleeps before it looks at its Cancellable again. +constexpr std::chrono::milliseconds CANCEL_POLL_PERIOD(50); + +// A release lasts one frame: frames_for_duration() of anything under +// 1.5 frames. +constexpr std::chrono::milliseconds ONE_FRAME(17); + +} // namespace + + +KeySender::KeySender( + Logger& logger, + ThreadPool& thread_pool, + LinkRegistry& registry, + std::string address, + std::chrono::milliseconds grant_period +) + : m_logger(logger) + , m_thread_pool(thread_pool) + , m_registry(registry) + , m_address(std::move(address)) + , m_grant_period(grant_period) +{} +KeySender::~KeySender(){ + std::lock_guard lg(m_lock); + m_pacer.reset(); + // With the connection closed, the bridge has released keys and grant. + if (!m_attachment || m_attachment->connection.expired()){ + return; + } + try{ + if (m_attachment->held_mask.value_or(0) != 0){ + restart_schedule(*m_attachment); + push_now(*m_attachment, 0, ONE_FRAME); + } + connection(*m_attachment)->command(std::format("GRANT {}", RUN_ON_GRANT)); + }catch (Exception& e){ + m_logger.log("MgbaLink: could not release mGBA: " + e.message(), COLOR_ORANGE); + } +} + +bool KeySender::is_ready() const{ + return m_registry.find(m_address).has_value(); +} + +KeySender::Attachment& KeySender::attach(){ + std::optional link = m_registry.find(m_address); + if (!link){ + throw ConnectionException(&m_logger, std::format( + "MgbaLink: no connection to {}. Select \"mGBA ({})\" as the video source.", + m_address, m_address + )); + } + if (m_attachment && m_attachment->serial == link->serial){ + if (m_pacer && !m_pacer->running()){ + throw ConnectionException(&m_logger, "MgbaLink: the connection to mGBA was lost."); + } + return *m_attachment; + } + + // A new connection (first use, or the video source reconnected). + m_pacer.reset(); + m_attachment.reset(); + m_input_log = InputLog(); + + // "GRANT 0" holds the emulator where it is and says which frame that + // is: the anchor. The pacer releases it from there. + WallClock now = current_time(); + std::string reply = link->connection->command("GRANT 0"); + std::optional frame = parse_ok_frame_reply(reply); + if (!frame){ + throw ConnectionException(&m_logger, "MgbaLink: unexpected GRANT reply: " + reply); + } + FrameClock clock(now, *frame); + m_attachment.emplace(Attachment{ + .serial = link->serial, + .connection = link->connection, + .clock = clock, + .schedule = KeySchedule(clock), + }); + m_pacer.emplace(m_logger, m_thread_pool, link->connection, clock, m_grant_period); + m_logger.log(std::format("MgbaLink: controller on {} anchored at frame {}.", m_address, *frame)); + return *m_attachment; +} + +std::shared_ptr KeySender::connection(const Attachment& attachment){ + std::shared_ptr locked = attachment.connection.lock(); + if (!locked){ + throw ConnectionException(&m_logger, "MgbaLink: the connection to mGBA was closed."); + } + return locked; +} + +void KeySender::restart_schedule(Attachment& attachment){ + // Commands already sent stay queued in the bridge, and the last one + // queued for a frame wins: start after the last one sent. + uint64_t next = attachment.last_sent_frame + ? *attachment.last_sent_frame + 1 + : attachment.clock.anchor_frame(); + attachment.schedule = KeySchedule(FrameClock(attachment.clock.timestamp(next), next)); + attachment.held_mask.reset(); +} + +void KeySender::push_now(Attachment& attachment, uint16_t mask, WallDuration duration){ + std::optional command = attachment.schedule.push(current_time(), mask, duration); + if (duration > WallDuration::zero()){ + attachment.held_mask = mask; + } + if (command){ + send(attachment, *command); + } +} + +void KeySender::send(Attachment& attachment, const KeysCommand& command){ + uint64_t late = connection(attachment)->keys(command.frame, command.mask); + m_input_log.record(command, late); + attachment.last_sent_frame = std::max(attachment.last_sent_frame.value_or(0), command.frame + late); + if (late != 0){ + m_logger.log( + std::format("MgbaLink: KEYS for frame {} landed {} frame(s) late.", command.frame, late), + COLOR_ORANGE + ); + } +} + +bool KeySender::wait_for_frame( + std::unique_lock& lg, Cancellable* cancellable, uint64_t frame, uint64_t epoch +){ + while (true){ + if (cancellable != nullptr){ + cancellable->throw_if_cancelled(); + } + if (m_epoch != epoch || !m_attachment){ + return false; + } + WallClock now = current_time(); + WallClock target = m_attachment->clock.timestamp(frame); + if (now >= target){ + return true; + } + WallDuration remaining = target - now; + m_cv.wait_for(lg, std::min(remaining, CANCEL_POLL_PERIOD)); + } +} + +void KeySender::push(Cancellable* cancellable, uint16_t mask, WallDuration duration){ + std::unique_lock lg(m_lock); + uint64_t epoch = m_epoch; + Attachment* attachment = &attach(); + + uint64_t start = attachment->schedule.end_frame(); + if (start > SEND_AHEAD_FRAMES){ + if (!wait_for_frame(lg, cancellable, start - SEND_AHEAD_FRAMES, epoch)){ + return; + } + // The connection may have changed while waiting. + attachment = &attach(); + } + if (m_replace_pending){ + m_replace_pending = false; + restart_schedule(*attachment); + } + push_now(*attachment, mask, duration); +} + +void KeySender::wait_for_all(Cancellable* cancellable){ + bool holding = false; + { + std::lock_guard lg(m_lock); + holding = m_attachment && m_attachment->held_mask.value_or(0) != 0; + } + if (holding){ + push(cancellable, 0, ONE_FRAME); + } + std::unique_lock lg(m_lock); + if (!m_attachment){ + return; + } + wait_for_frame(lg, cancellable, m_attachment->schedule.end_frame(), m_epoch); +} + +void KeySender::cancel(){ + std::lock_guard lg(m_lock); + m_epoch++; + m_replace_pending = false; + m_cv.notify_all(); + if (!m_attachment){ + return; + } + restart_schedule(*m_attachment); + try{ + push_now(*m_attachment, 0, ONE_FRAME); + }catch (ConnectionException&){ + // Logged by the exception. With the connection gone, the bridge + // has released the keys itself. + } +} + +void KeySender::replace_on_next(){ + std::lock_guard lg(m_lock); + m_epoch++; + m_replace_pending = true; + m_cv.notify_all(); +} + +std::string KeySender::input_log_text() const{ + std::lock_guard lg(m_lock); + return m_input_log.to_text(); +} + + +} // namespace MgbaLink +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.h b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.h new file mode 100644 index 0000000000..610568a848 --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.h @@ -0,0 +1,135 @@ +/* MgbaLink Key Sender + * + * From: https://github.com/PokemonAutomation/ + * + * The controller side of one mGBA instance: it takes the connection the + * video source published for the same "host:port" (the bridge holds one + * client), anchors a frame clock with "GRANT 0" (which also holds the + * emulator until the pacer grants), runs the pacer, and turns key states + * held for durations into "KEYS" commands on frames. Every command it sends + * goes into the input log at the frame it landed on. + * + * The bridge cannot take back a queued KEYS, so a state is sent only when + * it starts at most SEND_AHEAD_FRAMES after app time: push() blocks until + * then. A cancel then drops what is not sent yet and releases the keys at + * the first frame no sent command can override. + * + * Qt-free. Thread-safe: push() and wait_for_all() come from the issuing + * thread, cancel() and replace_on_next() from any thread. + * + */ + +#ifndef PokemonAutomation_Controllers_MgbaLink_KeySender_H +#define PokemonAutomation_Controllers_MgbaLink_KeySender_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/ConditionVariable.h" +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Concurrency/ThreadPool.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "MgbaLink_Keys.h" +#include "MgbaLink_Pacer.h" +#include "MgbaLink_Protocol.h" +#include "MgbaLink_SharedLink.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + + +// Sends one controller's key states to the mGBA published under an address. +class KeySender{ +public: + // Three frames past the pacer's lead (84 ms): a KEYS sent this early + // reaches the bridge before the emulator may run its frame, even if + // the sending thread wakes a frame or two late. It is also how long a + // cancelled state can still play. + static constexpr uint64_t SEND_AHEAD_FRAMES = KeySchedule::LEAD_FRAMES + 3; + + // Granted when the sender stops, so mGBA runs on instead of stalling + // at the last grant. Never reached. + static constexpr uint64_t RUN_ON_GRANT = (uint64_t)1 << 62; + + KeySender( + Logger& logger, + ThreadPool& thread_pool, + LinkRegistry& registry, + std::string address, + std::chrono::milliseconds grant_period = Pacer::DEFAULT_PERIOD + ); + + // Stops the pacer, releases held keys and lets mGBA run on (best effort). + ~KeySender(); + + // A connection is published for the address. + bool is_ready() const; + + // Holds GBA keys "mask" for "duration" after what is already scheduled. + // Blocks until that start is at most SEND_AHEAD_FRAMES ahead of app + // time; returns without sending if cancel() or replace_on_next() comes + // first. Throws ConnectionException if no connection is published or + // it is lost, OperationCancelledException if "cancellable" is cancelled. + void push(Cancellable* cancellable, uint16_t mask, WallDuration duration); + + // Releases the keys after the last state, then returns once app time + // reaches the end of the schedule. + void wait_for_all(Cancellable* cancellable); + + // Drops what is not sent yet and releases the keys. + void cancel(); + + // Drops what is not sent yet; the next push() starts as soon as it can + // and the keys it holds replace the current ones. + void replace_on_next(); + + // " " per change since the clock was anchored. + std::string input_log_text() const; + +private: + // The connection stays the video source's: the sender holds it only + // for the length of a command. + struct Attachment{ + uint64_t serial = 0; + std::weak_ptr connection; + FrameClock clock; + KeySchedule schedule; + std::optional held_mask = std::nullopt; + std::optional last_sent_frame = std::nullopt; + }; + + Attachment& attach(); + std::shared_ptr connection(const Attachment& attachment); + void restart_schedule(Attachment& attachment); + void push_now(Attachment& attachment, uint16_t mask, WallDuration duration); + void send(Attachment& attachment, const KeysCommand& command); + // Waits until app time reaches "frame" (in "lg"). False if a cancel + // came first. + bool wait_for_frame(std::unique_lock& lg, Cancellable* cancellable, uint64_t frame, uint64_t epoch); + +private: + Logger& m_logger; + ThreadPool& m_thread_pool; + LinkRegistry& m_registry; + const std::string m_address; + const std::chrono::milliseconds m_grant_period; + + mutable Mutex m_lock; + ConditionVariable m_cv; + // Bumped by cancel() and replace_on_next(): a waiting push() drops its state. + uint64_t m_epoch = 0; + bool m_replace_pending = false; + std::optional m_attachment; + InputLog m_input_log; + // Declared after the attachment: destroyed first, so it stops granting + // before the connection is released. + std::optional m_pacer; +}; + + +} // namespace MgbaLink +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.cpp b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.cpp new file mode 100644 index 0000000000..5bf0db625b --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.cpp @@ -0,0 +1,586 @@ +/* MgbaLink Key Sender Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/ConditionVariable.h" +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" +#ifdef _WIN32 +#include "Common/Cpp/Sockets/ServerSocket_WinSocket.h" +#else +#include "Common/Cpp/Sockets/ServerSocket_POSIX.h" +#endif +#include "MgbaLink_Connection.h" +#include "MgbaLink_KeySender.h" +#include "MgbaLink_KeySender_Tests.h" +#include "MgbaLink_Pacer.h" +#include "MgbaLink_SharedLink.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + +namespace{ + +#ifdef _WIN32 +using FakeServerSocket = ServerSocket_WinSocket; +#else +using FakeServerSocket = ServerSocket_POSIX; +#endif + +using std::chrono::milliseconds; + +// The fake emulator is always about to run this frame. +constexpr uint64_t BRIDGE_FRAME = 120; + + +std::string join_lines(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += text.empty() ? "<" : ", <"; + text += line; + text += ">"; + } + return text; +} + +// The number after " ", if "line" is that. +std::optional number_after(std::string_view line, std::string_view prefix){ + if (!line.starts_with(prefix)){ + return std::nullopt; + } + std::string_view rest = line.substr(prefix.size()); + uint64_t value = 0; + std::from_chars_result result = std::from_chars(rest.data(), rest.data() + rest.size(), value); + if (result.ec != std::errc() || rest.empty()){ + return std::nullopt; + } + return value; +} + + + +// A bridge stand-in that answers every command the controller side sends. +class FakeBridge : public AbstractServerSocket::Listener{ +public: + explicit FakeBridge(ThreadPool& thread_pool) + : m_server(thread_pool) + { + m_server.add_listener(*this); + } + ~FakeBridge(){ + m_server.remove_listener(*this); + } + + // Listens on a random port in 40000..59999; nullopt if 8 tries fail. + std::optional start(){ + std::mt19937 rng{std::random_device{}()}; + for (int attempt = 0; attempt < 8; attempt++){ + uint16_t port = (uint16_t)(40000 + rng() % 20000); + { + std::lock_guard lg(m_lock); + m_listen_error.reset(); + } + m_server.start("127.0.0.1", port); + std::unique_lock lg(m_lock); + m_cv.wait_for(lg, std::chrono::seconds(10), [this]{ return m_listen_error.has_value(); }); + if (m_listen_error && m_listen_error->empty()){ + return port; + } + } + return std::nullopt; + } + + // Waits up to 5 s for "line"; then returns every command seen. + std::vector commands_until(std::string_view line){ + std::unique_lock lg(m_lock); + m_cv.wait_for(lg, std::chrono::seconds(5), [&]{ + return !m_commands.empty() && m_commands.back() == line; + }); + return m_commands; + } + +private: + virtual void on_listen_finished(const std::string& error_message) override{ + std::lock_guard lg(m_lock); + m_listen_error = error_message; + m_cv.notify_all(); + } + virtual void on_receive_data(const void* data, size_t bytes) override{ + std::vector lines = m_splitter.push(std::string_view(static_cast(data), bytes)); + for (const std::string& line : lines){ + { + std::lock_guard lg(m_lock); + m_commands.emplace_back(line); + m_cv.notify_all(); + } + std::string reply = reply_for(line); + m_server.send(reply.data(), reply.size()); + if (line == "BYE"){ + m_server.close_connection(); + } + } + } + + static std::string reply_for(std::string_view line){ + if (line == "HELLO 1"){ + return "OK 1 BPRE bridge-0.1 paced\n"; + } + if (line.starts_with("GRANT ")){ + return std::format("OK {}\n", BRIDGE_FRAME); + } + if (line.starts_with("KEYS ")){ + return "OK\n"; + } + if (line == "BYE"){ + return "OK BYE\n"; + } + return std::format("ERR unknown {}\n", line.substr(0, line.find(' '))); + } + +private: + FakeServerSocket m_server; + LineSplitter m_splitter; + Mutex m_lock; + ConditionVariable m_cv; + std::optional m_listen_error; + std::vector m_commands; +}; + +// The registry: which connection a lookup finds after publications start +// and end. Connections are numbered by publish order, from 0. +enum class RegistryStep{ + PUBLISH_FIRST, + PUBLISH_SECOND, + END_FIRST, + END_SECOND, +}; +struct RegistryInput{ + std::vector steps; +}; +struct RegistryExpectation{ + // The connection found at the end, by number; nullopt = none. + std::optional found; +}; +struct RegistryCase{ + std::string name; + RegistryInput input; + RegistryExpectation expectation; +}; + +class Test_Registry : public UnitTest{ +public: + Test_Registry(RegistryCase test_case) + : UnitTest(std::format("Controllers::MgbaLink - link registry - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + ThreadPool& thread_pool = GlobalThreadPools::unlimited_normal(); + std::shared_ptr connections[2] = { + std::make_shared(logger, thread_pool, "127.0.0.1", 47801), + std::make_shared(logger, thread_pool, "127.0.0.1", 47801), + }; + LinkRegistry registry; + LinkRegistry::Publication publications[2]; + for (RegistryStep step : m_case.input.steps){ + switch (step){ + case RegistryStep::PUBLISH_FIRST: + publications[0] = registry.publish("127.0.0.1:47801", connections[0]); + break; + case RegistryStep::PUBLISH_SECOND: + publications[1] = registry.publish("127.0.0.1:47801", connections[1]); + break; + case RegistryStep::END_FIRST: + publications[0] = LinkRegistry::Publication(); + break; + case RegistryStep::END_SECOND: + publications[1] = LinkRegistry::Publication(); + break; + } + } + std::optional link = registry.find("127.0.0.1:47801"); + std::optional found; + if (link){ + found = link->connection == connections[0] ? 0 : 1; + } + if (found != m_case.expectation.found){ + auto text = [](std::optional x){ + return x ? std::format("connection {}", *x) : std::string("none"); + }; + return std::format("found {}, expected {}", text(found), text(m_case.expectation.found)); + } + if (registry.find("127.0.0.1:47802")){ + return "found a connection under another address"; + } + return true; + } + +private: + RegistryCase m_case; +}; + + +void add_registry_tests(UnitTestDatabase& database){ + const RegistryCase REGISTRY_CASES[] = { + { + .name = "nothing published", + .input = {{}}, + .expectation = {std::nullopt}, + }, + { + .name = "published", + .input = {{RegistryStep::PUBLISH_FIRST}}, + .expectation = {0}, + }, + { + .name = "publication ended", + .input = {{RegistryStep::PUBLISH_FIRST, RegistryStep::END_FIRST}}, + .expectation = {std::nullopt}, + }, + { + // A reconnect publishes before the old publication ends. + .name = "a newer publication outlives the older one", + .input = {{RegistryStep::PUBLISH_FIRST, RegistryStep::PUBLISH_SECOND, RegistryStep::END_FIRST}}, + .expectation = {1}, + }, + { + .name = "the newer publication ended", + .input = {{RegistryStep::PUBLISH_FIRST, RegistryStep::PUBLISH_SECOND, RegistryStep::END_SECOND}}, + .expectation = {std::nullopt}, + }, + }; + for (const RegistryCase& test_case : REGISTRY_CASES){ + database.add(test_case); + } +} + + + +// Runs "body" against a fake bridge with a connection to it published +// under its address in "registry". Returns every command the bridge saw, +// BYE last; nullopt if no port was free. +template +std::optional> with_fake_link(Logger& logger, Body&& body){ + ThreadPool& thread_pool = GlobalThreadPools::unlimited_normal(); + FakeBridge bridge(thread_pool); + std::optional port = bridge.start(); + if (!port){ + return std::nullopt; + } + { + LinkRegistry registry; + std::string address = std::format("127.0.0.1:{}", *port); + std::shared_ptr connection = std::make_shared(logger, thread_pool, "127.0.0.1", *port); + connection->open(); + LinkRegistry::Publication publication = registry.publish(address, connection); + body(thread_pool, registry, address, connection); + } + return bridge.commands_until("BYE"); +} + + + +// The pacer: GRANTs that follow app time, two frames ahead. +struct PacerInput{ + milliseconds run_time{}; +}; +struct PacerExpectation{ + uint64_t first_grant = 0; + size_t min_grants = 0; +}; +struct PacerCase{ + std::string name; + PacerInput input; + PacerExpectation expectation; +}; + +class Test_Pacer : public UnitTest{ +public: + Test_Pacer(PacerCase test_case) + : UnitTest(std::format("Controllers::MgbaLink - pacer - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + WallClock start; + WallClock stop; + std::optional> commands = with_fake_link( + logger, + [&](ThreadPool& thread_pool, LinkRegistry&, const std::string&, std::shared_ptr connection){ + start = current_time(); + { + Pacer pacer(logger, thread_pool, connection, FrameClock(start, BRIDGE_FRAME)); + std::this_thread::sleep_for(m_case.input.run_time); + } + stop = current_time(); + } + ); + if (!commands){ + return UnitTestResult(UnitTestResult::SKIPPED, "No free port for the fake bridge."); + } + std::vector grants; + for (const std::string& line : *commands){ + if (std::optional grant = number_after(line, "GRANT ")){ + grants.emplace_back(*grant); + } + } + if (grants.size() < m_case.expectation.min_grants){ + return std::format("{} GRANT(s), expected at least {}: {}", grants.size(), m_case.expectation.min_grants, join_lines(*commands)); + } + if (grants.front() != m_case.expectation.first_grant){ + return std::format("first GRANT {}, expected {}", grants.front(), m_case.expectation.first_grant); + } + for (size_t i = 1; i < grants.size(); i++){ + if (grants[i] <= grants[i - 1]){ + return std::format("GRANTs not increasing: {}", join_lines(*commands)); + } + } + uint64_t latest = grant_frame(FrameClock(start, BRIDGE_FRAME), stop, KeySchedule::LEAD_FRAMES); + if (grants.back() > latest){ + return std::format("last GRANT {} is past {}, the grant at the time the pacer stopped", grants.back(), latest); + } + return true; + } + +private: + PacerCase m_case; +}; + + +void add_pacer_tests(UnitTestDatabase& database){ + const PacerCase PACER_CASES[] = { + { + // About 12 frames in 200 ms; one GRANT per new frame, so at + // least half of them even on a loaded machine. + .name = "grants follow app time", + .input = {milliseconds(200)}, + .expectation = {.first_grant = BRIDGE_FRAME + 2, .min_grants = 6}, + }, + }; + for (const PacerCase& test_case : PACER_CASES){ + database.add(test_case); + } +} + + + +// The key sender: what reaches the bridge for a sequence of pushes. +enum class SenderStep{ + PUSH, + WAIT_FOR_ALL, + CANCEL, +}; +struct SenderAction{ + SenderStep step = SenderStep::PUSH; + uint16_t mask = 0; + milliseconds duration{}; +}; +struct SenderInput{ + bool published = true; + std::vector actions; +}; +struct SenderExpectation{ + // "KEYS + ", the anchoring + // "GRANT 0" and the closing run-on grant, in order; or "no connection". + std::vector commands; + // The run lasts no longer than this (a cancel cuts a long hold). + milliseconds max_run_time{}; +}; +struct SenderCase{ + std::string name; + SenderInput input; + SenderExpectation expectation; +}; + +SenderAction push(uint16_t mask, int ms){ + return SenderAction{SenderStep::PUSH, mask, milliseconds(ms)}; +} +SenderAction wait_for_all(){ + return SenderAction{SenderStep::WAIT_FOR_ALL, 0, milliseconds(0)}; +} +SenderAction cancel(){ + return SenderAction{SenderStep::CANCEL, 0, milliseconds(0)}; +} + +void run_actions(KeySender& sender, const std::vector& actions){ + for (const SenderAction& action : actions){ + switch (action.step){ + case SenderStep::PUSH: + sender.push(nullptr, action.mask, action.duration); + break; + case SenderStep::WAIT_FOR_ALL: + sender.wait_for_all(nullptr); + break; + case SenderStep::CANCEL: + sender.cancel(); + break; + } + } +} + +// Keeps KEYS (frames relative to the first one), "GRANT 0" and the +// run-on grant; drops the pacer's grants and the session lines. Also +// returns the first KEYS frame. +std::vector relative_keys(const std::vector& commands, std::optional& first_frame){ + std::vector kept; + const std::string run_on = std::format("GRANT {}", KeySender::RUN_ON_GRANT); + for (const std::string& line : commands){ + if (line == "GRANT 0" || line == run_on){ + kept.emplace_back(line == run_on ? "GRANT run-on" : line); + continue; + } + std::optional frame = number_after(line, "KEYS "); + if (!frame){ + continue; + } + if (!first_frame){ + first_frame = frame; + } + std::string_view mask = std::string_view(line).substr(line.rfind(' ') + 1); + kept.emplace_back(std::format("KEYS +{} {}", *frame - *first_frame, mask)); + } + return kept; +} + +class Test_Sender : public UnitTest{ +public: + Test_Sender(SenderCase test_case) + : UnitTest(std::format("Controllers::MgbaLink - key sender - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + WallClock start = current_time(); + std::vector results; + std::optional> commands = with_fake_link( + logger, + [&](ThreadPool& thread_pool, LinkRegistry& registry, const std::string& address, std::shared_ptr){ + LinkRegistry other; + KeySender sender(logger, thread_pool, m_case.input.published ? registry : other, address); + try{ + run_actions(sender, m_case.input.actions); + }catch (ConnectionException&){ + results.emplace_back("no connection"); + } + } + ); + milliseconds run_time = std::chrono::duration_cast(current_time() - start); + if (!commands){ + return UnitTestResult(UnitTestResult::SKIPPED, "No free port for the fake bridge."); + } + std::optional first_frame; + std::vector kept = relative_keys(*commands, first_frame); + results.insert(results.end(), kept.begin(), kept.end()); + if (results != m_case.expectation.commands){ + return std::format("the bridge saw {}, expected {}", join_lines(results), join_lines(m_case.expectation.commands)); + } + // Anchored at BRIDGE_FRAME, the first state starts two frames + // later (three on a slow machine). + if (first_frame && (*first_frame < BRIDGE_FRAME + 2 || *first_frame > BRIDGE_FRAME + 4)){ + return std::format("first KEYS on frame {}, expected {}..{}", *first_frame, BRIDGE_FRAME + 2, BRIDGE_FRAME + 4); + } + if (run_time > m_case.expectation.max_run_time){ + return std::format("took {} ms, expected at most {} ms", run_time.count(), m_case.expectation.max_run_time.count()); + } + return true; + } + +private: + SenderCase m_case; +}; + + +void add_sender_tests(UnitTestDatabase& database){ + const SenderCase SENDER_CASES[] = { + { + .name = "press and release", + .input = {.actions = {push(GBA_KEY_A, 80), push(GBA_KEY_NONE, 80), wait_for_all()}}, + .expectation = { + .commands = {"GRANT 0", "KEYS +0 1", "KEYS +5 0", "GRANT run-on"}, + .max_run_time = milliseconds(2000), + }, + }, + { + .name = "wait for all releases a held key", + .input = {.actions = {push(GBA_KEY_START, 80), wait_for_all()}}, + .expectation = { + .commands = {"GRANT 0", "KEYS +0 8", "KEYS +5 0", "GRANT run-on"}, + .max_run_time = milliseconds(2000), + }, + }, + { + // 50 ms is 2.99 frames; ends are placed from app time, so two + // holds of A take 6 frames, not 3 + 3 rounded separately. + .name = "same keys are one command", + .input = {.actions = {push(GBA_KEY_A, 50), push(GBA_KEY_A, 50), push(GBA_KEY_NONE, 50), wait_for_all()}}, + .expectation = { + .commands = {"GRANT 0", "KEYS +0 1", "KEYS +6 0", "GRANT run-on"}, + .max_run_time = milliseconds(2000), + }, + }, + { + // Up is held from frame +10 on, two states after A. Ends are + // placed from app time: 3 x 80 ms is 14.33 frames, so Up is + // released on +14, not on 3 x 5 = +15. + .name = "a later state waits for its turn", + .input = {.actions = {push(GBA_KEY_A, 80), push(GBA_KEY_NONE, 80), push(GBA_KEY_UP, 80), wait_for_all()}}, + .expectation = { + .commands = {"GRANT 0", "KEYS +0 1", "KEYS +5 0", "KEYS +10 64", "KEYS +14 0", "GRANT run-on"}, + .max_run_time = milliseconds(2000), + }, + }, + }; + for (const SenderCase& test_case : SENDER_CASES){ + database.add(test_case); + } +} + +void add_sender_cancel_tests(UnitTestDatabase& database){ + const SenderCase SENDER_CASES[] = { + { + // A 3 s hold, cancelled at once: released one frame later. + .name = "cancel releases at once", + .input = {.actions = {push(GBA_KEY_B, 3000), cancel(), wait_for_all()}}, + .expectation = { + .commands = {"GRANT 0", "KEYS +0 2", "KEYS +1 0", "GRANT run-on"}, + .max_run_time = milliseconds(1500), + }, + }, + { + .name = "no connection published", + .input = {.published = false, .actions = {push(GBA_KEY_A, 80)}}, + .expectation = { + .commands = {"no connection"}, + .max_run_time = milliseconds(2000), + }, + }, + }; + for (const SenderCase& test_case : SENDER_CASES){ + database.add(test_case); + } +} + +} // namespace + + +void add_key_sender_tests(UnitTestDatabase& database){ + add_registry_tests(database); + add_pacer_tests(database); + add_sender_tests(database); + add_sender_cancel_tests(database); +} + + +} // namespace MgbaLink +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.h b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.h new file mode 100644 index 0000000000..6905960d58 --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.h @@ -0,0 +1,23 @@ +/* MgbaLink Key Sender Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_MgbaLink_KeySender_Tests_H +#define PokemonAutomation_Controllers_MgbaLink_KeySender_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + + +// The shared link registry, and the pacer and key sender against a fake +// bridge on 127.0.0.1. +void add_key_sender_tests(UnitTestDatabase& database); + + +} // namespace MgbaLink +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_Pacer.cpp b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_Pacer.cpp new file mode 100644 index 0000000000..cf86f7386e --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_Pacer.cpp @@ -0,0 +1,77 @@ +/* MgbaLink Pacer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "MgbaLink_Keys.h" +#include "MgbaLink_Pacer.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + + +Pacer::Pacer( + Logger& logger, + ThreadPool& thread_pool, + std::weak_ptr connection, + FrameClock clock, + std::chrono::milliseconds period +) + : m_logger(logger) + , m_connection(std::move(connection)) + , m_clock(clock) + , m_period(period) +{ + m_task = thread_pool.dispatch_now_blocking([this]{ run(); }); +} +Pacer::~Pacer(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + } + m_cv.notify_all(); + m_task.wait_and_ignore_exceptions(); +} +bool Pacer::running() const{ + std::lock_guard lg(m_lock); + return !m_stopping && !m_failed; +} + +void Pacer::run(){ + std::optional last_grant; + while (true){ + uint64_t grant = grant_frame(m_clock, current_time(), KeySchedule::LEAD_FRAMES); + if (grant != last_grant){ + std::optional error; + if (std::shared_ptr connection = m_connection.lock()){ + try{ + connection->command(std::format("GRANT {}", grant)); + }catch (ConnectionException& e){ + error = e.message(); + } + }else{ + error = "the connection was closed."; + } + if (error){ + m_logger.log("MgbaLink: pacer stopped: " + *error, COLOR_RED); + std::lock_guard lg(m_lock); + m_failed = true; + return; + } + last_grant = grant; + } + std::unique_lock lg(m_lock); + if (m_cv.wait_for(lg, m_period, [this]{ return m_stopping; })){ + return; + } + } +} + + +} // namespace MgbaLink +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_Pacer.h b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_Pacer.h new file mode 100644 index 0000000000..557ca8fcdb --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_Pacer.h @@ -0,0 +1,78 @@ +/* MgbaLink Pacer + * + * From: https://github.com/PokemonAutomation/ + * + * Paced lockstep (design: docs/design/Lab-mGBA-Console.md, section 2): the + * app owns the clock and mGBA follows it. About every 8 ms the pacer sends + * "GRANT F0 + floor((now - t0) * 59.7275 / 1000) + 2", so the emulator runs + * at most two frames ahead of app time and stalls when the app does. The + * bridge ignores GRANT in free mode. + * + * Runs on a thread pool task; Qt-free. + * + */ + +#ifndef PokemonAutomation_Controllers_MgbaLink_Pacer_H +#define PokemonAutomation_Controllers_MgbaLink_Pacer_H + +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/AsyncTask.h" +#include "Common/Cpp/Concurrency/ConditionVariable.h" +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Concurrency/ThreadPool.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "MgbaLink_Connection.h" +#include "MgbaLink_Protocol.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + + +// Grants frames to the bridge from app time until destroyed. +class Pacer{ +public: + static constexpr std::chrono::milliseconds DEFAULT_PERIOD{8}; + + // Starts granting at once. "clock" is the anchor the controller + // schedules its KEYS against. The pacer does not keep "connection" + // open: it stops once its owner (the video source) closes it. + Pacer( + Logger& logger, + ThreadPool& thread_pool, + std::weak_ptr connection, + FrameClock clock, + std::chrono::milliseconds period = DEFAULT_PERIOD + ); + + // Stops granting. The last grant stays with the bridge: the emulator + // stalls there until someone grants again (or closes the connection). + ~Pacer(); + + // False once a GRANT failed or the connection was closed; the pacer + // then stops. + bool running() const; + +private: + void run(); + +private: + Logger& m_logger; + const std::weak_ptr m_connection; + const FrameClock m_clock; + const std::chrono::milliseconds m_period; + + mutable Mutex m_lock; + ConditionVariable m_cv; + bool m_stopping = false; + bool m_failed = false; + + AsyncTask m_task; +}; + + +} // namespace MgbaLink +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_SharedLink.cpp b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_SharedLink.cpp new file mode 100644 index 0000000000..474a4f16c7 --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_SharedLink.cpp @@ -0,0 +1,72 @@ +/* MgbaLink Shared Link + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "MgbaLink_SharedLink.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + + +LinkRegistry::Publication::Publication(Publication&& x) noexcept + : m_registry(x.m_registry) + , m_address(std::move(x.m_address)) + , m_serial(x.m_serial) +{ + x.m_registry = nullptr; +} +LinkRegistry::Publication& LinkRegistry::Publication::operator=(Publication&& x) noexcept{ + if (this != &x){ + reset(); + m_registry = x.m_registry; + m_address = std::move(x.m_address); + m_serial = x.m_serial; + x.m_registry = nullptr; + } + return *this; +} +LinkRegistry::Publication::~Publication(){ + reset(); +} +void LinkRegistry::Publication::reset() noexcept{ + if (m_registry != nullptr){ + m_registry->unpublish(m_address, m_serial); + m_registry = nullptr; + } +} + + +LinkRegistry::Publication LinkRegistry::publish(std::string address, std::shared_ptr connection){ + std::lock_guard lg(m_lock); + uint64_t serial = ++m_last_serial; + m_links[address] = Link{std::move(connection), serial}; + return Publication(*this, std::move(address), serial); +} +std::optional LinkRegistry::find(std::string_view address) const{ + std::lock_guard lg(m_lock); + auto iter = m_links.find(address); + if (iter == m_links.end()){ + return std::nullopt; + } + return iter->second; +} +void LinkRegistry::unpublish(const std::string& address, uint64_t serial) noexcept{ + std::lock_guard lg(m_lock); + auto iter = m_links.find(address); + // A later publish under the same address replaced this one: keep it. + if (iter != m_links.end() && iter->second.serial == serial){ + m_links.erase(iter); + } +} + + +LinkRegistry& link_registry(){ + static LinkRegistry registry; + return registry; +} + + +} // namespace MgbaLink +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_SharedLink.h b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_SharedLink.h new file mode 100644 index 0000000000..e431ab484f --- /dev/null +++ b/SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_SharedLink.h @@ -0,0 +1,84 @@ +/* MgbaLink Shared Link + * + * From: https://github.com/PokemonAutomation/ + * + * The bridge in mGBA holds one client at a time, so the video source and + * the controller of one console slot share one Connection. The video + * source opens it (and reopens it after a loss) and publishes it here under + * its "host:port"; the controller looks it up under the same text. + * + * Qt-free. + * + */ + +#ifndef PokemonAutomation_Controllers_MgbaLink_SharedLink_H +#define PokemonAutomation_Controllers_MgbaLink_SharedLink_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/Mutex.h" +#include "MgbaLink_Connection.h" + +namespace PokemonAutomation{ +namespace MgbaLink{ + + +// Open connections by address. Thread-safe. +class LinkRegistry{ +public: + // An open connection and which one it is: every publish gets a new + // serial, so a user can tell a reconnect from the link it already uses. + struct Link{ + std::shared_ptr connection; + uint64_t serial = 0; + }; + + // Keeps a connection listed until it is destroyed. + class Publication{ + public: + Publication() = default; + Publication(Publication&& x) noexcept; + Publication& operator=(Publication&& x) noexcept; + Publication(const Publication&) = delete; + Publication& operator=(const Publication&) = delete; + ~Publication(); + + private: + friend class LinkRegistry; + Publication(LinkRegistry& registry, std::string address, uint64_t serial) + : m_registry(®istry) + , m_address(std::move(address)) + , m_serial(serial) + {} + void reset() noexcept; + + LinkRegistry* m_registry = nullptr; + std::string m_address; + uint64_t m_serial = 0; + }; + + // Lists "connection" under "address", replacing what was listed there. + [[nodiscard]] Publication publish(std::string address, std::shared_ptr connection); + + // The connection listed under "address", if any. + std::optional find(std::string_view address) const; + +private: + void unpublish(const std::string& address, uint64_t serial) noexcept; + + mutable Mutex m_lock; + uint64_t m_last_serial = 0; + std::map> m_links; +}; + +// The registry the app's video sources and controllers share. +LinkRegistry& link_registry(); + + +} // namespace MgbaLink +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.cpp new file mode 100644 index 0000000000..2d80b49803 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.cpp @@ -0,0 +1,73 @@ +/* Nintendo Switch Controller Descriptor (mGBA over MgbaLink) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.h" +#include "NintendoSwitch_MgbaLink_Descriptor.h" +#include "NintendoSwitch_MgbaLink_ProController.h" + +namespace PokemonAutomation{ + +template class InterfaceType_t; + +namespace NintendoSwitch{ + + +ControllerDescriptor_MgbaLink::ControllerDescriptor_MgbaLink() + : ControllerDescriptor_MgbaLink(std::string(VideoSourceDescriptor_MgbaLink::DEFAULT_ADDRESS)) +{} +ControllerDescriptor_MgbaLink::ControllerDescriptor_MgbaLink(std::string address) + : UiState(INTERFACE_NAME) + , m_address(std::move(address)) +{} + +bool ControllerDescriptor_MgbaLink::operator==(const ControllerDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_address == static_cast(x).m_address; +} +std::string ControllerDescriptor_MgbaLink::display_name() const{ + return "mGBA (" + m_address + ")"; +} + +JsonValue ControllerDescriptor_MgbaLink::to_json() const{ + return m_address; +} +void ControllerDescriptor_MgbaLink::load_json(const JsonValue& json){ + const std::string* address = json.to_string(); + if (address != nullptr && parse_mgba_address(*address)){ + m_address = *address; + } +} + +std::unique_ptr ControllerDescriptor_MgbaLink::open_connection(Logger&) const{ + return std::make_unique(m_address); +} +std::unique_ptr ControllerDescriptor_MgbaLink::make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType +) const{ + const std::string& address = static_cast(connection).address(); + return std::make_unique(logger, address); +} + + +ControllerConnection_MgbaLink::ControllerConnection_MgbaLink(std::string address) + : m_address(std::move(address)) +{ + m_controller_list.emplace_back(ControllerType::NintendoSwitch_WiredController); + m_current_controller = ControllerType::NintendoSwitch_WiredController; + set_status_line0("mGBA Link: " + m_address, COLOR_BLUE); + set_status_line1("Sends keys on the mGBA video source's connection to " + m_address + "."); + declare_ready(); +} + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.h b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.h new file mode 100644 index 0000000000..0d4e275282 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.h @@ -0,0 +1,72 @@ +/* Nintendo Switch Controller Descriptor (mGBA over MgbaLink) + * + * From: https://github.com/PokemonAutomation/ + * + * The "TCP: mGBA Link" controller entry: an mGBA instance by "host:port". + * It opens no socket of its own; the controller sends on the connection + * the mGBA video source with the same address opened. Developer mode only + * (fork lab tooling). + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MgbaLink_Descriptor_H +#define PokemonAutomation_NintendoSwitch_MgbaLink_Descriptor_H + +#include +#include "Controllers/ControllerConnection.h" +#include "Controllers/ControllerDescriptor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// Selects an mGBA instance by "host:port" (saved in the profile). +class ControllerDescriptor_MgbaLink : public UiState{ +public: + static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::MgbaLink; + +public: + // The mGBA video source's default address. + ControllerDescriptor_MgbaLink(); + explicit ControllerDescriptor_MgbaLink(std::string address); + + const std::string& address() const{ + return m_address; + } + + virtual bool operator==(const ControllerDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual JsonValue to_json() const override; + virtual void load_json(const JsonValue& json) override; + + virtual std::unique_ptr open_connection(Logger& logger) const override; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const override; + +private: + std::string m_address; +}; + + +// Ready at once: whether mGBA is reachable shows in the controller's +// is_ready(), which follows the video source's connection. +class ControllerConnection_MgbaLink : public ControllerConnection{ +public: + explicit ControllerConnection_MgbaLink(std::string address); + + const std::string& address() const{ + return m_address; + } + +private: + const std::string m_address; +}; + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.cpp new file mode 100644 index 0000000000..dd684821e9 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.cpp @@ -0,0 +1,86 @@ +/* Nintendo Switch Pro Controller (mGBA over MgbaLink) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/Tools/GlobalThreadPools.h" +#include "Controllers/MgbaLink/MgbaLink_SharedLink.h" +#include "NintendoSwitch_MgbaLink_KeyMap.h" +#include "NintendoSwitch_MgbaLink_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +ProController_MgbaLink::ProController_MgbaLink(Logger& logger, std::string address) + : ProController(logger) + , ControllerWithScheduler(logger, logging_throttler()) + , m_sender(logger, GlobalThreadPools::unlimited_realtime(), MgbaLink::link_registry(), std::move(address)) +{} +ProController_MgbaLink::~ProController_MgbaLink() = default; + + +void ProController_MgbaLink::cancel_all_commands(){ + std::lock_guard lg(m_state_lock); + m_scheduler.clear_on_next(); + m_sender.cancel(); + m_logger.log("cancel_all_commands(): keys released.", COLOR_DARKGREEN); +} +void ProController_MgbaLink::replace_on_next_command(){ + std::lock_guard lg(m_state_lock); + m_scheduler.clear_on_next(); + m_sender.replace_on_next(); + m_logger.log("replace_on_next_command()", COLOR_DARKGREEN); +} +void ProController_MgbaLink::wait_for_all(Cancellable* cancellable){ + SuperscalarScheduler::Schedule schedule; + std::lock_guard lg0(m_issue_lock); + { + std::lock_guard lg1(m_state_lock); + m_scheduler.issue_wait_for_all(schedule); + } + execute_schedule(cancellable, schedule); + m_sender.wait_for_all(cancellable); +} + + +void ProController_MgbaLink::execute_state( + Cancellable* cancellable, + const SuperscalarScheduler::ScheduleEntry& entry +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + SwitchControllerState controller_state; + for (auto& item : entry.state){ + static_cast(*item).apply(controller_state); + } + GbaKeysFromSwitch keys = gba_keys_from_switch(controller_state); + log_unmapped_once(keys.unmapped, keys.right_stick_moved); + + m_sender.push(cancellable, keys.keys, entry.duration); +} + +void ProController_MgbaLink::log_unmapped_once(Button unmapped, bool right_stick_moved){ + Button new_buttons = unmapped & (Button)~(ButtonFlagType)m_logged_unmapped; + if (new_buttons != BUTTON_NONE){ + m_logged_unmapped |= new_buttons; + m_logger.log( + "MgbaLink: no GBA key for " + button_to_string(new_buttons) + "; ignored (logged once).", + COLOR_ORANGE + ); + } + if (right_stick_moved && !m_logged_right_stick){ + m_logged_right_stick = true; + m_logger.log("MgbaLink: no GBA key for the right stick; ignored (logged once).", COLOR_ORANGE); + } +} + + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.h new file mode 100644 index 0000000000..e8ca067e37 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.h @@ -0,0 +1,243 @@ +/* Nintendo Switch Pro Controller (mGBA over MgbaLink) + * + * From: https://github.com/PokemonAutomation/ + * + * Drives an mGBA instance as if it were a Switch: programs keep + * ProControllerContext and milliseconds; each scheduled controller state + * becomes GBA keys (NintendoSwitch_MgbaLink_KeyMap.h) held for whole + * frames, sent as "KEYS" on the connection the mGBA video source for the + * same address opened (MgbaLink::KeySender). While the controller is in + * use, mGBA runs paced by the app's clock. Buttons with no GBA key are + * logged once and do nothing. Developer mode only (fork lab tooling). + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MgbaLink_ProController_H +#define PokemonAutomation_NintendoSwitch_MgbaLink_ProController_H + +#include +#include "Controllers/ControllerTypes.h" +#include "Controllers/MgbaLink/MgbaLink_KeySender.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// A Pro Controller that plays its states as GBA keys on an mGBA instance. +class ProController_MgbaLink final : + public ProController, + public ControllerWithScheduler +{ +public: + using ContextType = ProControllerContext; + + // "address" is the "host:port" the mGBA video source uses. + ProController_MgbaLink(Logger& logger, std::string address); + ~ProController_MgbaLink(); + + + // The ProController interface. Callers reach it through ProController + // (the program's context), so the overrides stay out of this class's + // own public surface. +private: + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SerialPABotBase_Wired; + } + // One GBA frame: a state shorter than that still lasts a frame. + virtual Milliseconds ticksize() const override{ + return Milliseconds(17); + } + virtual Milliseconds cooldown() const override{ + return Milliseconds(17); + } + // Paced: every state lands on the frame it was scheduled for. + virtual Milliseconds timing_variation() const override{ + return Milliseconds::zero(); + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +private: + virtual void cancel_all_commands() override; + virtual void replace_on_next_command() override; + virtual bool cancel_all_and_wait(Milliseconds timeout) override{ + // The release is sent before cancel_all_commands() returns. + cancel_all_commands(); + return true; + } + + virtual void wait_for_all(Cancellable* cancellable) override; + + +private: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + const JoystickPosition& position + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, position); + } + virtual void issue_right_joystick( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + const JoystickPosition& position + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, position); + } + + virtual void issue_gyro_accel_x( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + Cancellable* cancellable, + bool enable_logging, + Milliseconds duration, + Button button, + DpadPosition dpad, + const JoystickPosition& left_joystick, + const JoystickPosition& right_joystick + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + enable_logging, + duration, + button, + dpad, + left_joystick, + right_joystick + ); + } + + +private: + // High speed RPCs. + + virtual void issue_mash_button( + Cancellable* cancellable, + Milliseconds duration, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button, delay, hold, cooldown); + } + virtual void issue_mash_button( + Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +private: + virtual Logger& logger() override{ + return m_logger; + } + virtual bool is_ready() const override{ + return m_sender.is_ready(); + } + + +private: + virtual void execute_state( + Cancellable* cancellable, + const SuperscalarScheduler::ScheduleEntry& entry + ) override; + + void log_unmapped_once(Button unmapped, bool right_stick_moved); + + +private: + MgbaLink::KeySender m_sender; + + // What was already reported as having no GBA key. Only the issuing + // thread (execute_state) touches these. + Button m_logged_unmapped = BUTTON_NONE; + bool m_logged_right_stick = false; +}; + + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.cpp new file mode 100644 index 0000000000..360b860b2c --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.cpp @@ -0,0 +1,64 @@ +/* Nintendo Switch Controller Selector (mGBA over MgbaLink) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink.h" +#include "NintendoSwitch_MgbaLink_SelectorWidget.h" + +namespace PokemonAutomation{ + +template class RegisterUiStateQtWidget; + +namespace NintendoSwitch{ + + +ControllerSelectorWidget_MgbaLink::ControllerSelectorWidget_MgbaLink( + ControllerSelectorWidget& parent, + const ControllerDescriptor* current +) + : QLineEdit(&parent) +{ + QSizePolicy policy; + policy.setHorizontalStretch(3); + this->setSizePolicy(policy); + this->setPlaceholderText(QString::fromUtf8( + VideoSourceDescriptor_MgbaLink::DEFAULT_ADDRESS.data(), + (qsizetype)VideoSourceDescriptor_MgbaLink::DEFAULT_ADDRESS.size() + )); + + if (current == nullptr || current->interface_type != ControllerInterface::MgbaLink){ + std::shared_ptr descriptor = + parent.session().option().get_descriptor_from_cache(ControllerInterface::MgbaLink); + if (!descriptor){ + descriptor = std::make_shared(); + } + parent.session().set_device(descriptor); + } + + std::shared_ptr active = parent.session().descriptor(); + this->setText(QString::fromStdString(static_cast(*active).address())); + + connect( + this, &QLineEdit::editingFinished, + &parent, [this, &parent](){ + std::string address = this->text().toStdString(); + if (!parse_mgba_address(address)){ + // Only 127.0.0.1: or localhost:, as the video source. + return; + } + std::shared_ptr selected = + std::make_shared(std::move(address)); + std::shared_ptr current = parent.session().descriptor(); + if (*current == *selected){ + return; + } + parent.session().set_device(std::move(selected)); + } + ); +} + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.h b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.h new file mode 100644 index 0000000000..ad6b671152 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.h @@ -0,0 +1,50 @@ +/* Nintendo Switch Controller Selector (mGBA over MgbaLink) + * + * From: https://github.com/PokemonAutomation/ + * + * The address box of the "TCP: mGBA Link" controller entry. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MgbaLink_SelectorWidget_H +#define PokemonAutomation_NintendoSwitch_MgbaLink_SelectorWidget_H + +#include +#include "Common/Qt/UiStateQtWidget.h" +#include "Controllers/ControllerDescriptor.h" +#include "Controllers/ControllerSelectorWidget.h" +#include "NintendoSwitch_MgbaLink_Descriptor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// Edits the address; ignores text that is not 127.0.0.1: or +// localhost:. +class ControllerSelectorWidget_MgbaLink + : public QLineEdit + , public UiComponentQtWidget +{ +public: + using ParentState = const ControllerDescriptor_MgbaLink; + + ControllerSelectorWidget_MgbaLink( + QWidget& parent, + const ParentState& current + ) + : ControllerSelectorWidget_MgbaLink(static_cast(parent), ¤t) + {} + ControllerSelectorWidget_MgbaLink( + ControllerSelectorWidget& parent, + const ControllerDescriptor* current + ); + + virtual QWidget& widget() override{ + return *this; + } +}; + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index fce49ccc5c..f0e8d93a5a 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -286,8 +286,16 @@ file(GLOB CORE_LIBRARY_SOURCES Source/Controllers/MgbaLink/MgbaLink_Keys.h Source/Controllers/MgbaLink/MgbaLink_Keys_Tests.cpp Source/Controllers/MgbaLink/MgbaLink_Keys_Tests.h + Source/Controllers/MgbaLink/MgbaLink_KeySender.cpp + Source/Controllers/MgbaLink/MgbaLink_KeySender.h + Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.cpp + Source/Controllers/MgbaLink/MgbaLink_KeySender_Tests.h + Source/Controllers/MgbaLink/MgbaLink_Pacer.cpp + Source/Controllers/MgbaLink/MgbaLink_Pacer.h Source/Controllers/MgbaLink/MgbaLink_Protocol.cpp Source/Controllers/MgbaLink/MgbaLink_Protocol.h + Source/Controllers/MgbaLink/MgbaLink_SharedLink.cpp + Source/Controllers/MgbaLink/MgbaLink_SharedLink.h Source/Controllers/MgbaLink/MgbaLink_Tests.cpp Source/Controllers/MgbaLink/MgbaLink_Tests.h Source/Controllers/NullController.cpp @@ -330,6 +338,8 @@ file(GLOB CORE_LIBRARY_SOURCES Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_KeyMap.h Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_KeyMap_Tests.cpp Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_KeyMap_Tests.h + Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.cpp + Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_ProController.h Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.cpp Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp @@ -1352,6 +1362,10 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h Source/NintendoSwitch/Controllers/Joycon/NintendoSwitch_JoyconTable.cpp Source/NintendoSwitch/Controllers/Joycon/NintendoSwitch_JoyconTable.h + Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.cpp + Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_Descriptor.h + Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.cpp + Source/NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_SelectorWidget.h Source/NintendoSwitch/Controllers/Procon/NintendoSwitch_ProControllerTable.cpp Source/NintendoSwitch/Controllers/Procon/NintendoSwitch_ProControllerTable.h Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h