Merge pull request #767 from wheremyfoodat/cpp

Initial support for CirclePad Pro/New 3DS controls
This commit is contained in:
wheremyfoodat 2025-07-03 03:39:12 +03:00 committed by GitHub
commit 2e148ae997
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 872 additions and 252 deletions

View file

@ -81,6 +81,7 @@ struct EmulatorConfig {
bool sdCardInserted = true;
bool sdWriteProtected = false;
bool circlePadProEnabled = true;
bool usePortableBuild = false;
bool audioEnabled = audioEnabledDefault;

View file

@ -2,8 +2,9 @@
#include "result_cfg.hpp"
#include "result_common.hpp"
#include "result_kernel.hpp"
#include "result_os.hpp"
#include "result_fnd.hpp"
#include "result_fs.hpp"
#include "result_gsp.hpp"
#include "result_gsp.hpp"
#include "result_ir.hpp"
#include "result_kernel.hpp"
#include "result_os.hpp"

View file

@ -0,0 +1,8 @@
#pragma once
#include "result_common.hpp"
DEFINE_HORIZON_RESULT_MODULE(Result::IR, IR);
namespace Result::IR {
DEFINE_HORIZON_RESULT(NoDeviceConnected, 13, InvalidState, Status);
};

View file

@ -12,7 +12,8 @@ struct Scheduler {
UpdateTimers = 1, // Update kernel timer objects
RunDSP = 2, // Make the emulated DSP run for one audio frame
SignalY2R = 3, // Signal that a Y2R conversion has finished
Panic = 4, // Dummy event that is always pending and should never be triggered (Timestamp = UINT64_MAX)
UpdateIR = 4, // Update an IR device (For now, just the CirclePad Pro/N3DS controls)
Panic = 5, // Dummy event that is always pending and should never be triggered (Timestamp = UINT64_MAX)
TotalNumberOfEvents // How many event types do we have in total?
};
static constexpr usize totalNumberOfEvents = static_cast<usize>(EventType::TotalNumberOfEvents);

View file

@ -27,6 +27,12 @@ namespace HID::Keys {
GPIO0Inv = 1 << 12, // Inverted value of GPIO bit 0
GPIO14Inv = 1 << 13, // Inverted value of GPIO bit 14
// CirclePad Pro buttons. We store them in the HID service for ease, even though they're only used by the IR service
// Whenever the HID service writes to shared memory, we remember to mask them out
ZL = 1 << 14,
ZR = 1 << 15,
CirclePadProButtons = ZL | ZR,
CirclePadRight = 1 << 28, // X >= 41
CirclePadLeft = 1 << 29, // X <= -41
CirclePadUp = 1 << 30, // Y >= 41
@ -58,6 +64,9 @@ class HIDService {
s16 roll, pitch, yaw; // Gyroscope state
s16 accelX, accelY, accelZ; // Accelerometer state
// New 3DS/CirclePad Pro C-stick state
s16 cStickX, cStickY;
bool accelerometerEnabled;
bool eventsInitialized;
bool gyroEnabled;
@ -113,7 +122,7 @@ class HIDService {
// Turn bits 28 and 29 off in the new button state, which indicate whether the circlepad is steering left or right
// Then, set them according to the new value of x
newButtons &= ~0x3000'0000;
newButtons &= ~(HID::Keys::CirclePadLeft | HID::Keys::CirclePadRight);
if (x >= 41) // Pressing right
newButtons |= 1 << 28;
else if (x <= -41) // Pressing left
@ -125,13 +134,19 @@ class HIDService {
// Turn bits 30 and 31 off in the new button state, which indicate whether the circlepad is steering up or down
// Then, set them according to the new value of y
newButtons &= ~0xC000'0000;
newButtons &= ~(HID::Keys::CirclePadUp | HID::Keys::CirclePadDown);
if (y >= 41) // Pressing up
newButtons |= 1 << 30;
else if (y <= -41) // Pressing down
newButtons |= 1 << 31;
}
void setCStickX(s16 x) { cStickX = x; }
void setCStickY(s16 y) { cStickY = y; }
s16 getCStickX() { return cStickX; }
s16 getCStickY() { return cStickY; }
void setRoll(s16 value) { roll = value; }
void setPitch(s16 value) { pitch = value; }
void setYaw(s16 value) { yaw = value; }
@ -157,9 +172,6 @@ class HIDService {
touchScreenPressed = true;
}
void releaseTouchScreen() {
touchScreenPressed = false;
}
void releaseTouchScreen() { touchScreenPressed = false; }
bool isTouchScreenPressed() { return touchScreenPressed; }
};

View file

@ -0,0 +1,53 @@
#pragma once
#include "bitfield.hpp"
#include "services/ir/ir_device.hpp"
#include "services/ir/ir_types.hpp"
namespace IR {
class CirclePadPro : public IR::Device {
public:
struct ButtonState {
static constexpr int C_STICK_CENTER = 0x800;
union {
BitField<0, 8, u32> header;
BitField<8, 12, u32> x;
BitField<20, 12, u32> y;
} cStick;
union {
BitField<0, 5, u8> batteryLevel;
BitField<5, 1, u8> zlNotPressed;
BitField<6, 1, u8> zrNotPressed;
BitField<7, 1, u8> rNotPressed;
} buttons;
u8 unknown;
ButtonState() {
// Response header for button state reads
cStick.header = static_cast<u8>(CPPResponseID::PollButtons);
cStick.x = static_cast<u32>(CirclePadPro::ButtonState::C_STICK_CENTER);
cStick.y = static_cast<u32>(CirclePadPro::ButtonState::C_STICK_CENTER);
// Fully charged
buttons.batteryLevel = 0x1F;
buttons.zrNotPressed = 1;
buttons.zlNotPressed = 1;
buttons.rNotPressed = 1;
unknown = 0;
}
};
static_assert(sizeof(ButtonState) == 6, "Circlepad Pro button state has wrong size");
virtual void connect() override;
virtual void disconnect() override;
virtual void receivePayload(Payload payload) override;
CirclePadPro(SendCallback sendCallback, Scheduler& scheduler) : IR::Device(sendCallback, scheduler) {}
ButtonState state;
// The current polling period in cycles, configured via the ConfigurePolling command
s64 period = Scheduler::nsToCycles(16000);
};
} // namespace IR

View file

@ -0,0 +1,25 @@
#pragma once
#include <functional>
#include <span>
#include "helpers.hpp"
#include "scheduler.hpp"
namespace IR {
class Device {
public:
using Payload = std::span<const u8>;
protected:
using SendCallback = std::function<void(Payload)>; // Callback for sending data from IR device->3DS
Scheduler& scheduler;
SendCallback sendCallback;
public:
virtual void connect() = 0;
virtual void disconnect() = 0;
virtual void receivePayload(Payload payload) = 0;
Device(SendCallback sendCallback, Scheduler& scheduler) : sendCallback(sendCallback), scheduler(scheduler) {}
};
} // namespace IR

View file

@ -0,0 +1,132 @@
#pragma once
#include <array>
#include "bitfield.hpp"
#include "helpers.hpp"
#include "memory.hpp"
#include "swap.hpp"
// Type definitions for the IR service
// Based off https://github.com/azahar-emu/azahar/blob/de7b457ee466e432047c4ee8d37fca9eae7e031e/src/core/hle/service/ir/ir_user.cpp#L88
namespace IR {
class Buffer {
public:
Buffer(Memory& memory, u32 sharedMemBaseVaddr, u32 infoOffset, u32 bufferOffset, u32 maxPackets, u32 bufferSize)
: memory(memory), sharedMemBaseVaddr(sharedMemBaseVaddr), infoOffset(infoOffset), bufferOffset(bufferOffset), maxPackets(maxPackets),
maxDataSize(bufferSize - sizeof(PacketInfo) * maxPackets) {
updateBufferInfo();
}
u8* getPointer(u32 offset) { return (u8*)memory.getReadPointer(sharedMemBaseVaddr + offset); }
bool put(std::span<const u8> packet) {
if (info.packetCount == maxPackets) {
return false;
}
u32 offset;
// finds free space offset in data buffer
if (info.packetCount == 0) {
offset = 0;
if (packet.size() > maxDataSize) {
return false;
}
} else {
const u32 lastIndex = (info.endIndex + maxPackets - 1) % maxPackets;
const PacketInfo first = getPacketInfo(info.beginIndex);
const PacketInfo last = getPacketInfo(lastIndex);
offset = (last.offset + last.size) % maxDataSize;
const u32 freeSpace = (first.offset + maxDataSize - offset) % maxDataSize;
if (packet.size() > freeSpace) {
return false;
}
}
// Writes packet info
PacketInfo packet_info{offset, static_cast<u32>(packet.size())};
setPacketInfo(info.endIndex, packet_info);
// Writes packet data
for (std::size_t i = 0; i < packet.size(); ++i) {
*getDataBufferPointer((offset + i) % maxDataSize) = packet[i];
}
// Updates buffer info
info.endIndex++;
info.endIndex %= maxPackets;
info.packetCount++;
updateBufferInfo();
return true;
}
bool release(u32 count) {
if (info.packetCount < count) {
return false;
}
info.packetCount -= count;
info.beginIndex += count;
info.beginIndex %= maxPackets;
updateBufferInfo();
return true;
}
u32 getPacketCount() { return info.packetCount; }
private:
struct BufferInfo {
u32_le beginIndex;
u32_le endIndex;
u32_le packetCount;
u32_le unknown;
};
static_assert(sizeof(BufferInfo) == 16, "IR::BufferInfo has wrong size!");
struct PacketInfo {
u32_le offset;
u32_le size;
};
static_assert(sizeof(PacketInfo) == 8, "IR::PacketInfo has wrong size!");
u8* getPacketInfoPointer(u32 index) { return getPointer(bufferOffset + sizeof(PacketInfo) * index); }
void setPacketInfo(u32 index, const PacketInfo& packet_info) { std::memcpy(getPacketInfoPointer(index), &packet_info, sizeof(PacketInfo)); }
PacketInfo getPacketInfo(u32 index) {
PacketInfo packet_info;
std::memcpy(&packet_info, getPacketInfoPointer(index), sizeof(PacketInfo));
return packet_info;
}
u8* getDataBufferPointer(u32 offset) { return getPointer(bufferOffset + sizeof(PacketInfo) * maxPackets + offset); }
void updateBufferInfo() {
if (infoOffset) {
std::memcpy(getPointer(infoOffset), &info, sizeof(info));
}
}
BufferInfo info{0, 0, 0, 0};
Memory& memory;
u32 sharedMemBaseVaddr;
u32 infoOffset;
u32 bufferOffset;
u32 maxPackets;
u32 maxDataSize;
};
namespace CPPResponseID {
enum : u8 {
PollButtons = 0x10, // This response contains the current Circlepad Pro button/stick state
ReadCalibrationData = 0x11, // Responding to a ReadCalibrationData request
};
}
namespace CPPRequestID {
enum : u8 {
ConfigurePolling = 1, // Configures if & how often to poll the Circlepad Pro button/stick state
ReadCalibrationData = 2, // Reads the Circlepad Pro calibration data
};
}
} // namespace IR

View file

@ -1,16 +1,22 @@
#pragma once
#include <memory>
#include <optional>
#include <span>
#include "config.hpp"
#include "helpers.hpp"
#include "kernel_types.hpp"
#include "logger.hpp"
#include "memory.hpp"
#include "result/result.hpp"
#include "services/hid.hpp"
#include "services/ir/circlepad_pro.hpp"
// Circular dependencies in this project? Never
class Kernel;
class IRUserService {
using Payload = IR::Device::Payload;
using Handle = HorizonHandle;
enum class DeviceID : u8 {
@ -20,23 +26,34 @@ class IRUserService {
Handle handle = KernelHandles::IR_USER;
Memory& mem;
Kernel& kernel;
// The IR service has a reference to the HID service as that's where the frontends store CirclePad Pro button state in
HIDService& hid;
const EmulatorConfig& config;
MAKE_LOG_FUNCTION(log, irUserLogger)
// Service commands
void clearReceiveBuffer(u32 messagePointer);
void clearSendBuffer(u32 messagePointer);
void disconnect(u32 messagePointer);
void finalizeIrnop(u32 messagePointer);
void getConnectionStatusEvent(u32 messagePointer);
void getReceiveEvent(u32 messagePointer);
void getSendEvent(u32 messagePointer);
void initializeIrnopShared(u32 messagePointer);
void requireConnection(u32 messagePointer);
void sendIrnop(u32 messagePointer);
void releaseReceivedData(u32 messagePointer);
using IREvent = std::optional<Handle>;
IREvent connectionStatusEvent = std::nullopt;
IREvent receiveEvent = std::nullopt;
IREvent sendEvent = std::nullopt;
IR::CirclePadPro cpp;
std::optional<MemoryBlock> sharedMemory = std::nullopt;
std::unique_ptr<IR::Buffer> receiveBuffer;
bool connectedDevice = false;
// Header of the IR shared memory containing various bits of info
@ -56,8 +73,19 @@ class IRUserService {
};
static_assert(sizeof(SharedMemoryStatus) == 16);
// The IR service uses CRC8 with generator polynomial = 0x07 for verifying packets received from IR devices
static u8 crc8(std::span<const u8> data);
// IR devices call this to send a device->console payload
void sendPayload(Payload payload);
public:
IRUserService(Memory& mem, Kernel& kernel) : mem(mem), kernel(kernel) {}
IRUserService(Memory& mem, HIDService& hid, const EmulatorConfig& config, Kernel& kernel);
void setCStickX(s16 value) { cpp.state.cStick.x = value; }
void setCStickY(s16 value) { cpp.state.cStick.y = value; }
void reset();
void handleSyncRequest(u32 messagePointer);
void updateCirclePadPro();
};

View file

@ -23,7 +23,7 @@
#include "services/gsp_lcd.hpp"
#include "services/hid.hpp"
#include "services/http.hpp"
#include "services/ir_user.hpp"
#include "services/ir/ir_user.hpp"
#include "services/ldr_ro.hpp"
#include "services/mcu/mcu_hwc.hpp"
#include "services/mic.hpp"
@ -115,4 +115,5 @@ class ServiceManager {
NFCService& getNFC() { return nfc; }
DSPService& getDSP() { return dsp; }
Y2RService& getY2R() { return y2r; }
IRUserService& getIRUser() { return ir_user; }
};