diff --git a/CMakeLists.txt b/CMakeLists.txt index c6d073b..096269e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,6 +146,7 @@ if(SWITCH_PICO_SWITCH2_MOUSE_CAPTURE) SWITCH_PICO_SWITCH2_MOUSE_CAPTURE=1 SWITCH_PICO_SWITCH2_MOUSE_CAPTURE_NATIVE=$) endif() +set(SWITCH2_BRIDGE_WII_INPUT OFF) if(SWITCH_PICO_SWITCH2_USB_BRIDGE) if(NOT SWITCH_PICO_INPUT_BACKEND STREQUAL "BLUEPAD32" OR NOT SWITCH_PICO_ENABLE_BLE @@ -157,8 +158,19 @@ if(SWITCH_PICO_SWITCH2_USB_BRIDGE) if(SWITCH_PICO_WII_IR_MOUSE OR SWITCH_PICO_WII_IR_GYRO) message(FATAL_ERROR "Switch 2 USB bridge owns USB; Wii IR USB experiments cannot be combined") endif() + set(SWITCH2_BRIDGE_INPUT "JOYCON2" CACHE STRING "Native bridge source: JOYCON2 or WII") + set_property(CACHE SWITCH2_BRIDGE_INPUT PROPERTY STRINGS JOYCON2 WII) + if(SWITCH2_BRIDGE_INPUT STREQUAL "WII") + if(NOT SWITCH_PICO_ENABLE_CLASSIC) + message(FATAL_ERROR "Wii native bridge requires Bluetooth MIXED mode") + endif() + set(SWITCH2_BRIDGE_WII_INPUT ON) + add_compile_definitions(SWITCH2_BRIDGE_WII_INPUT=1 SWITCH_PICO_WII_IR=1) + elseif(NOT SWITCH2_BRIDGE_INPUT STREQUAL "JOYCON2") + message(FATAL_ERROR "SWITCH2_BRIDGE_INPUT must be JOYCON2 or WII") + endif() set(SWITCH2_BRIDGE_SOURCE_ADDRESS "" CACHE STRING - "Physical right Joy-Con 2 Bluetooth source address (xx:xx:xx:xx:xx:xx)") + "Physical Bluetooth controller source address (xx:xx:xx:xx:xx:xx)") string(TOLOWER "${SWITCH2_BRIDGE_SOURCE_ADDRESS}" bridge_source_address) string(LENGTH "${bridge_source_address}" bridge_source_address_length) if(NOT bridge_source_address_length EQUAL 17 @@ -335,16 +347,41 @@ if(SWITCH_PICO_SWITCH2_USB_BRIDGE) message(FATAL_ERROR "Switch 2 USB bridge requires the initialized probe with factory and user calibration captures") endif() target_sources(switch-pico PRIVATE + ${SWITCH2_USB_PROBE_DIR}/bootsel.cpp ${SWITCH2_USB_PROBE_DIR}/controller_input.cpp) + if(SWITCH2_BRIDGE_WII_INPUT) + set(LIBOGC_IR_PREP_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/tools/prepare_libogc_ir.py) + set(LIBOGC_IR_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/libogc_ir.c) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + ${LIBOGC_IR_PREP_SCRIPT} + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/UPSTREAM.json + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/ir.h + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/license_libogc.txt + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/libogc_license.txt + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/upstream/ir.c + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/upstream/ir.h + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/upstream/wiiuse.h + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/upstream/wiiuse_internal.h + ${CMAKE_CURRENT_LIST_DIR}/external/libogc_ir/upstream/definitions.h) + execute_process( + COMMAND ${Python3_EXECUTABLE} ${LIBOGC_IR_PREP_SCRIPT} --output ${LIBOGC_IR_GENERATED} + RESULT_VARIABLE LIBOGC_IR_PREP_RESULT) + if(NOT LIBOGC_IR_PREP_RESULT EQUAL 0) + message(FATAL_ERROR "Preparing the pinned libogc IR pipeline failed") + endif() + target_include_directories(switch-pico PRIVATE ${CMAKE_CURRENT_LIST_DIR}/external) + target_sources(switch-pico PRIVATE ${SWITCH2_USB_PROBE_DIR}/native_imu.cpp ${LIBOGC_IR_GENERATED}) + endif() target_compile_definitions(switch-pico PRIVATE SWITCH2_BRIDGE_SOURCE_ADDRESS_BYTES=${SWITCH2_BRIDGE_SOURCE_ADDRESS_BYTES}) else() target_sources(switch-pico PRIVATE ${SWITCH_PICO_SOURCE_DIR}/main.cpp) endif() -if(SWITCH_PICO_WII_IR_MOUSE OR SWITCH_PICO_WII_IR_GYRO) - target_sources(switch-pico PRIVATE - ${SWITCH_PICO_SOURCE_DIR}/input/wii_ir_pointer.cpp - ${SWITCH_PICO_SOURCE_DIR}/input/wii_ir_tracker.cpp) +if(SWITCH_PICO_WII_IR_MOUSE OR SWITCH_PICO_WII_IR_GYRO OR SWITCH2_BRIDGE_WII_INPUT) + target_sources(switch-pico PRIVATE ${SWITCH_PICO_SOURCE_DIR}/input/wii_ir_pointer.cpp) + if(NOT SWITCH2_BRIDGE_WII_INPUT) + target_sources(switch-pico PRIVATE ${SWITCH_PICO_SOURCE_DIR}/input/wii_ir_tracker.cpp) + endif() endif() if(SWITCH_PICO_WII_IR_MOUSE) target_sources(switch-pico PRIVATE diff --git a/README.md b/README.md index dfec285..52bc07b 100644 --- a/README.md +++ b/README.md @@ -479,6 +479,173 @@ The AIO firmware enables motion automatically for original Wii Remotes with an e Protocol references: [WiiBrew Wiimote](https://wiibrew.org/wiki/Wiimote), [MotionPlus registers/calibration](https://wiibrew.org/wiki/Wiimote/Extension_Controllers/Wii_Motion_Plus), [Dolphin MotionPlus calibration](https://github.com/dolphin-emu/dolphin/blob/master/Source/Core/Core/HW/WiimoteEmu/MotionPlus.cpp), and [SDL Wii sensor axes](https://github.com/libsdl-org/SDL/blob/main/src/joystick/hidapi/SDL_hidapi_wii.c). +### Experimental native Joy-Con 2 USB output + +`SWITCH_PICO_SWITCH2_USB_BRIDGE=ON` selects the separate USB protocol probe in +`tools/switch2_usb_probe`, not the ordinary four-Pro-controller AIO output. +`SWITCH2_BRIDGE_INPUT=JOYCON2` preserves complete packets from one selected right +Joy-Con 2; `SWITCH2_BRIDGE_INPUT=WII` generates native right-Joy-Con reports from +Wii input. Select the physical Bluetooth address with +`SWITCH2_BRIDGE_SOURCE_ADDRESS`. + +The Wii source requires Pico 2 W, the Bluepad32 backend, Bluetooth `MIXED` mode, +and the bridge's native capture prerequisites +(`SWITCH_PICO_SWITCH2_MOUSE_CAPTURE=ON` and +`SWITCH_PICO_SWITCH2_MOUSE_CAPTURE_NATIVE=ON`). It enables the Wii camera parser +without the mutually exclusive legacy `SWITCH_PICO_WII_IR_MOUSE` or +`SWITCH_PICO_WII_IR_GYRO` USB experiments. + +This research target also requires the probe's validated identity, firmware, +factory-memory and user-calibration inputs, a distinct virtual controller address, +`SWITCH2_PROBE_ACK_SETUP04=ON`, and `SWITCH2_PROBE_USB_INIT=ON`. The +`SWITCH2_PROBE_*_FILE` inputs are checked by `probe_build.cmake`; private captures, +pairing records and firmware backups are not bundled with the source. +Keep a known-good UF2 and use a separate build directory for experiments. + +- **Motion:** factory-calibrated Wii acceleration and MotionPlus gyro have + independent freshness counters. Keep the Remote still at startup for at least + 1.5 seconds and 64 fresh gyro samples to estimate residual bias. The encoder + integrates real gyro into an orientation quaternion, using fresh near-1g + acceleration to correct tilt drift, and emits the recovered 30-byte native + IMU format. Fresh full-bar observations gently correct relative heading + around world-up, following the sensor-fusion approach used by Dolphin. + The first optical observation anchors the current heading without a jump; + missing/inferred observations do not supply heading corrections. Translation + changes optical bearing too, so this is not an absolute world-yaw reference. + A fixed mounting transform makes a face-up Wii + correspond to the virtual right Joy-Con's rail-down mouse pose. Missing, + stale or uncalibrated sensors withhold IMU/mouse output rather than inventing it. +- **IR:** firmware 0.32 runs the actual libogc Wiiuse IR math pipeline from + [commit `a4064a8`](https://github.com/devkitPro/libogc/blob/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/wiiuse/ir.c), + not a separately implemented approximation. `tools/prepare_libogc_ir.py` + checks pinned source hashes and extracts seven unchanged functions and their + algorithm constants into a build-local C translation unit. The original + sources remain untouched under `external/libogc_ir/upstream/`. + Upstream owns bar selection, missing-dot recovery, smoothing, glitch counters + and bounded screen mapping. It runs once per new camera report, including + while USB output is disabled; its frame-count behavior is not replaced by + custom timing or association thresholds. + The separate native adapter supplies mirrored raw X, unchanged raw Y, and + gravity roll in degrees. It converts upstream smoothed `sx/sy` changes into + signed16 relative mouse reports with once-only consumption. A first native + baseline waits for an accepted upstream position rather than its initial + glitch-held origin; USB stalls, freshness loss and reconnects discard stale + native movement. Brief upstream missing/glitch holds produce no invented + movement. Relative output is not gated on upstream's bounded `ir.valid`, + because the adapter does not know the actual host cursor position. + Optical heading confidence excludes upstream-rejected glitches and inferred + endpoints. The native IMU encoder and heading observer remain project code; + they are not a verbatim Dolphin port. Legacy IR modes retain their old trackers. + Native USB still provides no absolute cursor-position feedback or automatic + synchronization; host sensitivity and initial cursor location still matter. +- **Controls:** stored profiles map ordinary controller buttons; IR does not + create left/right clicks or turn button 1 into a desktop-mouse clutch. + This is one virtual **right** Joy-Con, so left-only controls require profile + remapping if needed. A mapped right stick takes precedence; otherwise a + Nunchuk's mapped left stick supplies the single virtual stick using the + calibration advertised to the console. Configure profiles in normal AIO + firmware before using this probe. + After Bluetooth setup, press a mapped face button (A with the tested profile) + if the Switch has not assigned the controller. The button used to wake the + Wii may be consumed during setup; observed activation changes player LEDs + from mask 0 to 1. No automatic button press is injected. +- **Feedback/pairing:** built-in cue commands become bounded Wii on/off rumble + patterns, not HD frequency/audio emulation. USB completion follows Core 1 + driver dispatch. Holding BOOTSEL for two seconds opens pairing; this probe + never routes a long hold to clear pairings. +- **Qualification:** genuine Joy-Con passthrough mouse operation is confirmed + on Switch with firmware 0.24. Earlier Wii builds deliver accepted native mouse + and IMU reports, but pointing remained unreliable. Their custom tracker tests + did not establish equivalence to upstream. Firmware 0.32 replaces that native + tracker with the pinned upstream pipeline. Source identity and all seven + retained function bodies are verified; the actual C code has been replayed + on 495 recorded camera snapshots. All final 100 steady observations produced + valid smoothed full-bar output. That 10Hz, zero-roll replay does not establish + full-rate timing or improved console behavior; hardware qualification remains pending. + Firmware 0.33 adds a camera-only sensitivity-level-2 trial after an on/off + comparison retained one detection with the bar off. The upstream tracking + code is unchanged. Both default level 3 and selected level 2 have been + exercised through the real parser's complete camera-register setup; reduced + interference and usable range still require a hardware comparison. + **In progress; Wii pointing work is paused.** Firmware 0.33 was flashed and + verified with persistent storage unchanged, but the level-2 on/off comparison + has not been run. Erratic tracking, tracking loss and ineffective vertical + movement remain unresolved; this checkpoint is not a completed Wii pointer. + +Native Wii camera and viewport settings are build-time parameters, not stored profile changes: + +| CMake option | Default | Meaning | +| --- | ---: | --- | +| `SWITCH2_WII_IR_SENSITIVITY` | `3` | Standard camera preset `2` or `3`; lower sensitivity may reduce interference and range | +| `SWITCH2_WII_IR_VIEW_WIDTH` | `660` | Viewport width in camera pixels | +| `SWITCH2_WII_IR_VIEW_HEIGHT` | `370` | Viewport height in camera pixels | +| `SWITCH2_WII_IR_OFFSET_X` | `0` | Horizontal offset from the camera center | +| `SWITCH2_WII_IR_OFFSET_Y` | `-115` | Below-screen bar; use `115` for above-screen | +| `SWITCH2_WII_IR_SPAN_X` | `1920` | Native mouse counts across viewport width | +| `SWITCH2_WII_IR_SPAN_Y` | `1080` | Native mouse counts across viewport height | + +The 660 x 370 viewport and +/-115 vertical placement follow libogc's 16:9 +defaults; they are not a measurement of the attached camera or screen. Spans +are **mouse counts**, not guaranteed display pixels. The viewport must remain +inside the 1024 x 768 camera image. For example, configure the existing native +Wii build with `cmake -S . -B build-switch2-usb-wii -DSWITCH2_WII_IR_OFFSET_Y=-115`, +then build normally. Trace builds sample raw IR diagnostics at 10Hz; diagnostic +flag bits 3/4 additionally indicate viewport inclusion and full optical reference. +Offsets locate the nominal screen rectangle and its diagnostics; a constant +offset alone cannot recenter a relative host cursor. Viewport dimensions and +mouse-count spans determine movement scale, but absolute pointing remains unsynchronized. +For the lower-sensitivity trial, configure with +`cmake -S . -B build-switch2-usb-wii -DSWITCH2_WII_IR_SENSITIVITY=2`, then build. +The parser logs the selected level after camera setup completes. Other firmware +builds retain standard level 3 unless explicitly configured otherwise. + + +**Port provenance and licensing:** see `external/libogc_ir/UPSTREAM.json` and +`external/libogc_ir/NOTICE.txt`. The component retains its full GPLv3 license +and libogc-specific independent-module linking exception; independent project +code is not relicensed. Preserve component notices and corresponding source +when distributing the firmware. The only C-language compatibility adjustment +is an equivalent disabled debug macro accepting one-argument calls in strict +C11; algorithm bodies and constants are unchanged. Transport/report decoding +is provided by the existing Bluepad32 path, not copied Wiiuse I/O stubs. +Do not edit generated `build*/libogc_ir.c` or the pinned original files to tune +tracking. Changes to upstream require an explicit pin/manifest update; native +protocol adaptations belong in the separate adapter. + + +Both native bridge sources support the existing software **BOOTSEL reboot** +without erasing pairings, profiles or configuration. The standalone USB diagnostic +probe does not. Connect the bridge to a PC and disconnect any genuine USB right +Joy-Con 2 before running this from the repository: + +```sh +uv run python - <<'PY' +import usb.core +from switch_pico_bridge.config_manager import request_bootsel_reboot + +devices = list(usb.core.find(find_all=True, idVendor=0x057e, idProduct=0x2066)) +if len(devices) != 1: + raise SystemExit("Connect exactly one native bridge (057e:2066).") +request_bootsel_reboot(devices[0]) +print("Rebooting into USB BOOTSEL mode.") +PY +``` + +USB access requires permission to the matching `/dev/bus/usb` device. With +multiple bridges, select the intended PyUSB device by its `bus` and `address` +instead of sending to every matching device. The ordinary +`switch-pico-config reboot bootsel` CLI uses management discovery, which this +native USB identity deliberately does not expose; the direct helper above needs +no discovery request or interface claim. + +Only vendor-device OUT `0x40`, request `0x04`, value `0x5350`, index `1`, with the +existing validated 16-byte management envelope is accepted. The shared handler +validates and dispatches at the control status ACK, then the existing 50 ms guard +enters ROM USB boot mode. Invalid envelopes cannot schedule a reboot. Nintendo's +separate request `0x04`, value `0x0276`, index `0`, length `0` remains an ordinary +setup acknowledgement. No configuration writes or extra management capabilities +are enabled in native mode. + ### Switch 2 controller input The AIO firmware implements the proprietary BLE protocol for Nintendo `057E:2069` (Pro), `057E:2067` (left Joy-Con 2), and `057E:2066` (right Joy-Con 2). This is controller **input** support, distinct from the existing Switch 2 console-wake feature and from emulating a native Switch 2 USB controller. diff --git a/bluepad32_config/sdkconfig.h b/bluepad32_config/sdkconfig.h index 61d30dc..ed391c9 100644 --- a/bluepad32_config/sdkconfig.h +++ b/bluepad32_config/sdkconfig.h @@ -13,3 +13,11 @@ // 2 == Info #define CONFIG_BLUEPAD32_LOG_LEVEL 2 + +// Standard Wii camera presets; native diagnostic builds may select level 2. +#ifndef SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL +#define SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL 3 +#endif +#if SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL != 2 && SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL != 3 +#error "Wii IR sensitivity must be standard preset 2 or 3" +#endif diff --git a/external/libogc_ir/NOTICE.txt b/external/libogc_ir/NOTICE.txt new file mode 100644 index 0000000..27dcb3e --- /dev/null +++ b/external/libogc_ir/NOTICE.txt @@ -0,0 +1,76 @@ +libogc Wiiuse IR math component port + +Upstream: https://github.com/devkitPro/libogc +Pinned commit: a4064a86487c46d8ab76d4fdf99e8059a62c4fa2 +Modified for switch-pico on 2026-09-11. + +This directory is a source extraction from the Wiiuse component of libogc, +not an independent reimplementation and not a copy of ordinary Wiiuse from +another repository. Original sources in upstream/ are byte-for-byte copies +from the pin; UPSTREAM.json records their URLs, checksums and retained ranges. + +LICENSE AND ATTRIBUTION + +The full, unchanged wiiuse/license_libogc.txt from that libogc revision is +provided here as license_libogc.txt. It contains GNU GPL version 3 plus the +section 18 exception for linking with independent modules. The opening scope +restriction (libogc and its covered or combined works) is retained. This is a +modified port of that libogc component; we explicitly extend and retain the +section 18 linking exception for this version, including the portable header +and generated IR translation unit. This component is not offered under MIT. +The surrounding independent switch-pico project is not relicensed. + +Section 18 permits linking this library with independent modules under their +own licenses and distributing the executable under terms of your choice, +provided each independent module's license is satisfied. An independent +module is not derived from or based on this library. The exception does not +remove the GPL obligations for this component itself, including provision of +its corresponding source when distributing it in object-code form. The +original component, extraction script and portable header are supplied in +source form. Recipients should retain these notices and the full license. + +The original Wiiuse notice in upstream/wiiuse_internal.h credits Michael +Laforest, copyright 2006-2007, grants GPL version 3 or later, and disclaims +warranty. It is retained intact in that file, the portable header, and the +generated C. There is no copyright/license preamble in the pinned ir.c, +ir.h, definitions.h or gc/wiiuse/wiiuse.h; none has been invented for them. + +The root libogc notice is preserved verbatim as libogc_license.txt. It credits +Michael Wiedenbauer (shagkur) and Dave Murphy (WinterMute), copyright 2004-2009, +and grants permission subject to origin, altered-source marking and notice +retention restrictions. This root notice does not replace the Wiiuse-specific +GPL plus exception. There is no root LICENSE file at the pinned revision; +UPSTREAM.json records the failed LICENSE URL and the actual pinned root file. + +EXACT PORTABILITY CHANGES + +1. Keep upstream/ir.c untouched. tools/prepare_libogc_ir.py selects the exact + declared byte-preserving line ranges rather than rewriting any algorithm. + No function body, algorithm constant, comparison, arithmetic expression or + math-library call in the retained functions is changed. +2. Omit transport, report decoding, device setup and platform includes. No + unused transport function is compiled, and no fake Wiiuse I/O implementation + is supplied. The caller supplies decoded dots and orientation. +3. Supply a narrow C/C++ header instead of the Bluetooth/GEKKO headers. Keep + the original ubyte, orient_t, ir_dot_t, fdot_t, sb_t, aspect_t, ir_position_t + and ir_t declarations verbatim; supply the platform primitive f32 as float. + Copy the original anonymous IR state enum and original aspect-size macros + into this header. Add a unique include guard, C linkage and declarations + for the two already-external functions find_sensorbar/apply_ir_smoothing. + Retain the original calc_yaw/interpret_ir_data declarations. +4. Generated C starts with #include "libogc_ir/ir.h", includes standard math.h, + and copies the original PI/angle conversion macros. The original disabled + WIIUSE_DEBUG(fmt, ...) definition is retained, then redefined as + WIIUSE_DEBUG(...) with the same empty expansion. This makes one-argument + debug calls valid strict C11 without enabling logging, changing call sites, + suppressing compiler warnings, or modifying algorithm bodies/constants. +5. Add dated modification/license comments, blank separators and #line + directives around unchanged source sections. File names in those directives + are repository-relative, so output is independent of the build directory. + The extraction has no runtime dependency on Python or the filesystem. + +The native relative-output adapter is separate from these upstream math +functions. It handles camera coordinate conventions, gravity units, camera +sequence consumption, configurable relative scale and USB delta baselines. +Those adaptations are not changes to the algorithm in this directory and do +not provide absolute host cursor synchronization. diff --git a/external/libogc_ir/UPSTREAM.json b/external/libogc_ir/UPSTREAM.json new file mode 100644 index 0000000..3da9ab1 --- /dev/null +++ b/external/libogc_ir/UPSTREAM.json @@ -0,0 +1,326 @@ +{ + "format_version": 1, + "repository": "https://github.com/devkitPro/libogc", + "commit": "a4064a86487c46d8ab76d4fdf99e8059a62c4fa2", + "modified_date": "2026-09-11", + "ir_git_blob_sha1": "d9659f5da575861f574d3d0480887955ef8f8faf", + "sources": { + "wiiuse/ir.c": { + "url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/wiiuse/ir.c", + "local_path": "upstream/ir.c", + "sha256": "12b3a21bcbe92fa2ae3ba262ff4bff94f385978062b7f33f65956e11ec4c2ff2", + "git_blob_sha1": "d9659f5da575861f574d3d0480887955ef8f8faf", + "bytes": 23568, + "lines": 834 + }, + "gc/wiiuse/wiiuse.h": { + "url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/gc/wiiuse/wiiuse.h", + "local_path": "upstream/wiiuse.h", + "sha256": "21f890f417d3504999175692860f8994038c9127936f872d63405f2824e2c8d5", + "git_blob_sha1": "7be2a7d9e9cc4b506516b73a659b52feb59d507b", + "bytes": 22507, + "lines": 748 + }, + "wiiuse/wiiuse_internal.h": { + "url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/wiiuse/wiiuse_internal.h", + "local_path": "upstream/wiiuse_internal.h", + "sha256": "ea2485eb06e4423b7f1ddd584e4c1157aeb0cf79212c74c2bb93bef1afa7be3e", + "git_blob_sha1": "ade44da594289d79c4c9769f1f871198df09144e", + "bytes": 8678, + "lines": 277 + }, + "wiiuse/definitions.h": { + "url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/wiiuse/definitions.h", + "local_path": "upstream/definitions.h", + "sha256": "a625020c657d2369ea99e2044aa4298ba92e3bfb9d7a5801eb4b2ca0ff20bb90", + "git_blob_sha1": "04dc5be6d8437ac4e3ab9f923610246ab1f8b95e", + "bytes": 1680, + "lines": 55 + }, + "wiiuse/ir.h": { + "url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/wiiuse/ir.h", + "local_path": "upstream/ir.h", + "sha256": "4fd4009c1b4c81d8b121f233693bd4248d567ce641d19f2fb2bcd60a85f9f9e1", + "git_blob_sha1": "f90cfc89c53167bb494a090024fd0698c0f0cbdd", + "bytes": 413, + "lines": 22 + }, + "wiiuse/license_libogc.txt": { + "url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/wiiuse/license_libogc.txt", + "local_path": "license_libogc.txt", + "sha256": "6bbd4837fe3fd232883e27c606cce94f17aa4fd23a9f981c68149e4ec4c7cae1", + "git_blob_sha1": "a149fce1ce2915d22fc30eda8e691607d21335b4", + "bytes": 33495, + "lines": 641 + }, + "libogc_license.txt": { + "url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/libogc_license.txt", + "local_path": "libogc_license.txt", + "sha256": "8be3bc1cad868fae35498ce049c60b4263e57184a7d23df99ea1f7ba2d338a2f", + "git_blob_sha1": "a3dfd0581becdeaea787614ec3ed6b75287164b3", + "bytes": 942, + "lines": 20 + } + }, + "root_license_lookup": { + "requested_url": "https://raw.githubusercontent.com/devkitPro/libogc/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2/LICENSE", + "status": "HTTP 404: no LICENSE entry in the pinned root tree", + "tree_url": "https://api.github.com/repos/devkitPro/libogc/git/trees/a4064a86487c46d8ab76d4fdf99e8059a62c4fa2", + "actual_source": "libogc_license.txt" + }, + "license": { + "component_license": "GNU GPL version 3 with libogc section 18 independent-module linking exception", + "upstream_internal_header_notice": "Michael Laforest, Copyright 2006-2007; GNU GPL version 3 or (at your option) any later version; no warranty", + "exception_extended_to_this_modified_component": true, + "full_component_license": "license_libogc.txt", + "full_root_notice": "libogc_license.txt", + "modification_notice": "NOTICE.txt", + "project_relicensed": false, + "inputs": "Only this pinned devkitPro/libogc component; no ordinary Wiiuse GPL-only repository inputs" + }, + "extraction": { + "line_numbering": "1-based inclusive; bytes split with keepends=True, no newline or whitespace normalization", + "c_sections": [ + { + "source": "wiiuse/wiiuse_internal.h", + "first_line": 1, + "last_line": 27, + "first_line_text": "/*", + "last_line_text": " */", + "sha256": "e78f559543e0d48e5f54d5316c55c98520e583ff16f0b9fecd2bb65efc3a97e9", + "purpose": "Wiiuse copyright, GPLv3-or-later and warranty notice" + }, + { + "source": "wiiuse/definitions.h", + "first_line": 6, + "last_line": 6, + "first_line_text": "#define WIIMOTE_PI\t\t\t3.14159265f", + "last_line_text": "#define WIIMOTE_PI\t\t\t3.14159265f", + "sha256": "3c8132e59374a2aa64f38839677a5eda20286d0488f4b989ff2d60a00d15a501", + "purpose": "WIIMOTE_PI" + }, + { + "source": "wiiuse/definitions.h", + "first_line": 31, + "last_line": 31, + "first_line_text": "\t#define WIIUSE_DEBUG(fmt, ...)", + "last_line_text": "\t#define WIIUSE_DEBUG(fmt, ...)", + "sha256": "3eb11daa6ec4902683edfbebb54fdad73cf2f4c3933f69dbc9b247f579206283", + "purpose": "upstream disabled WIIUSE_DEBUG definition" + }, + { + "source": "wiiuse/definitions.h", + "first_line": 44, + "last_line": 46, + "first_line_text": "/* Convert between radians and degrees */", + "last_line_text": "#define DEGREE_TO_RAD(d)\t(d * (WIIMOTE_PI / 180.0f))", + "sha256": "87d7ef0bdfb09bc9f8be97e6938bb3cd0cd48836114aa398e6152fffb05c5739", + "purpose": "RAD_TO_DEGREE, DEGREE_TO_RAD" + }, + { + "source": "wiiuse/ir.c", + "first_line": 15, + "last_line": 16, + "first_line_text": "static int ir_correct_for_bounds(float* x, float* y, enum aspect_t aspect, int offset_x, int offset_y);", + "last_line_text": "static void ir_convert_to_vres(float* x, float* y, enum aspect_t aspect, unsigned int vx, unsigned int vy);", + "sha256": "c20c25c89c31d8bddd6a885163d9c91e351e71c218731efb54af55a5edaec2e7", + "purpose": "original private helper prototypes" + }, + { + "source": "wiiuse/ir.c", + "first_line": 55, + "last_line": 144, + "first_line_text": "static void rotate_dots(struct fdot_t* in, struct fdot_t *out, int count, float ang) {", + "last_line_text": "}", + "sha256": "cd6b24d0cb478cdc61270a45a7410a614ac6678c821a91e1ad9cac9d3809fac2", + "purpose": "rotate_dots, ir_correct_for_bounds, ir_convert_to_vres" + }, + { + "source": "wiiuse/ir.c", + "first_line": 438, + "last_line": 833, + "first_line_text": "// half-height of the IR sensor if half-width is 1", + "last_line_text": "}", + "sha256": "2e8465a163a1d35a1781136d1078d3532b75995cb07cedfb96e9759daca5e7c2", + "purpose": "all sensorbar, smoothing and interpretation constants; find_sensorbar, apply_ir_smoothing, interpret_ir_data, calc_yaw" + } + ], + "header_sections": [ + { + "source": "wiiuse/wiiuse_internal.h", + "first_line": 1, + "last_line": 27, + "first_line_text": "/*", + "last_line_text": " */", + "sha256": "e78f559543e0d48e5f54d5316c55c98520e583ff16f0b9fecd2bb65efc3a97e9", + "purpose": "Wiiuse copyright, GPLv3-or-later and warranty notice" + }, + { + "source": "gc/wiiuse/wiiuse.h", + "first_line": 187, + "last_line": 187, + "first_line_text": "typedef unsigned char ubyte;", + "last_line_text": "typedef unsigned char ubyte;", + "sha256": "584753f151dc6fdb69bac85ef521ebe77f0c01de4e2801dc26f292bb24d0d305", + "purpose": "ubyte primitive" + }, + { + "source": "gc/wiiuse/wiiuse.h", + "first_line": 108, + "last_line": 112, + "first_line_text": "/* IR correction types */", + "last_line_text": "} ir_position_t;", + "sha256": "495c0b4599ec31e4189f2ccedf640a76dc71868cc238ba339fc137cd5863514a", + "purpose": "ir_position_t" + }, + { + "source": "gc/wiiuse/wiiuse.h", + "first_line": 297, + "last_line": 310, + "first_line_text": "/**", + "last_line_text": "} orient_t;", + "sha256": "073eab21f91deb1eb460d80c85e8e9f4de7d0340715ca86113a76d0e56d5c79b", + "purpose": "orient_t" + }, + { + "source": "gc/wiiuse/wiiuse.h", + "first_line": 336, + "last_line": 405, + "first_line_text": "/**", + "last_line_text": "} ir_t;", + "sha256": "d1f7c5c93665b760c86bf1e3591a7b8c88cf82b4ad79a2ecfcf8af31d7d14474", + "purpose": "ir_dot_t, fdot_t, sb_t, aspect_t, ir_t" + }, + { + "source": "wiiuse/ir.c", + "first_line": 431, + "last_line": 436, + "first_line_text": "enum {", + "last_line_text": "};", + "sha256": "672444f503b33a4bcd7e52c99ac9ca938f2410b99969ff6008d6e54b074cfe74", + "purpose": "IR_STATE_DEAD, IR_STATE_GOOD, IR_STATE_SINGLE, IR_STATE_LOST enum" + }, + { + "source": "wiiuse/wiiuse_internal.h", + "first_line": 154, + "last_line": 158, + "first_line_text": "/* aspect ratio */", + "last_line_text": "#define WM_ASPECT_4_3_Y\t\t420", + "sha256": "8a6b6501b9b4e8645b3201c03fa6c114e5e557cac64d7659a0ce7358cbb4f8fc", + "purpose": "original viewport dimensions" + }, + { + "source": "wiiuse/ir.h", + "first_line": 15, + "last_line": 16, + "first_line_text": "float calc_yaw(struct ir_t* ir);", + "last_line_text": "void interpret_ir_data(struct ir_t* ir, struct orient_t *orient);", + "sha256": "1b6d1fa3431f094bd6f25e1c9d9bbba3f4fd73183581cfb6685902b43e067dd9", + "purpose": "calc_yaw and interpret_ir_data prototypes" + } + ], + "retained_functions": [ + { + "name": "rotate_dots", + "source": "wiiuse/ir.c", + "first_line": 55, + "last_line": 79, + "sha256": "b7f1437819b636ec237b451c38bfeb1aff1819b0994c608ce40cb448bcd08991" + }, + { + "name": "ir_correct_for_bounds", + "source": "wiiuse/ir.c", + "first_line": 95, + "last_line": 122, + "sha256": "f303a51195d05355d3e699fa9a6e72f08c6ed1db6a57c95c0cc295b5475c6c68" + }, + { + "name": "ir_convert_to_vres", + "source": "wiiuse/ir.c", + "first_line": 128, + "last_line": 144, + "sha256": "69a457776dadbec16cf6b71213943751814992d1f4b56c9bd96ad5473ea6797e" + }, + { + "name": "find_sensorbar", + "source": "wiiuse/ir.c", + "first_line": 488, + "last_line": 719, + "sha256": "e0cb1843e92043a86705dd19bcbb248d4fb977fd8e3a4f2a215e9532d2ebfba9" + }, + { + "name": "apply_ir_smoothing", + "source": "wiiuse/ir.c", + "first_line": 730, + "last_line": 751, + "sha256": "9ab2e0cef3167f5a1b156c32b0972766d704e69d12a1b492e14870034d7f84f6" + }, + { + "name": "interpret_ir_data", + "source": "wiiuse/ir.c", + "first_line": 766, + "last_line": 819, + "sha256": "05c9ec6b4da39697dfd3c2fba20b99822bff64db57dc4df4fec0cb55bd6e758a" + }, + { + "name": "calc_yaw", + "source": "wiiuse/ir.c", + "first_line": 826, + "last_line": 833, + "sha256": "fc6d1a163837cf6dda45db67c2c4cc9de9a263aed53a987a8d0d03bc4c073d48" + } + ], + "omitted_ir_c_ranges": [ + { + "first_line": 1, + "last_line": 14, + "reason": "platform/transport includes replaced by portable header and math.h" + }, + { + "first_line": 18, + "last_line": 53, + "reason": "get_ir_sens device sensitivity helper" + }, + { + "first_line": 146, + "last_line": 429, + "reason": "device mode/enable/configuration/sensitivity and basic/extended Bluetooth report decoding" + } + ], + "debug": "Original disabled macro is retained, then equivalently redefined as WIIUSE_DEBUG(...) for strict C11 calls with only a format argument; logging remains disabled" + }, + "portable_header": { + "path": "ir.h", + "sha256": "73bb59ab64183b943e206687883095723a39fd8a5d160dc32a6e8526f6ca1b7b", + "local_additions": [ + "dated provenance/license comment", + "SWITCH_PICO_LIBOGC_IR_H include guard", + "typedef float f32;", + "extern C wrapper for the four public functions", + "find_sensorbar and apply_ir_smoothing declarations matching upstream definitions" + ] + }, + "generated_c": { + "first_line": "#include \"libogc_ir/ir.h\"", + "standard_include": "#include ", + "local_additions": [ + "dated provenance/license comment", + "blank separators", + "repository-relative #line directives before unchanged C sections", + "equivalent disabled WIIUSE_DEBUG(...) macro replaces GNU empty variadic-tail syntax for strict C11" + ], + "body_and_constant_rewrites": [], + "io_stubs": [], + "compile_language": "C11", + "include_root": "external/", + "math_library": "link the platform math library when required" + }, + "helper": { + "path": "tools/prepare_libogc_ir.py", + "cli": "python tools/prepare_libogc_ir.py --output build/libogc_ir.c", + "python_api": "prepare(output: pathlib.Path) -> pathlib.Path", + "dependencies": "Python standard library only; vendored local inputs; no network or Git needed", + "writes": "Requested output only, and only when generated bytes differ" + }, + "adaptation_boundary": "The native relative-output adapter supplies decoded dots and orientation, consumes each camera sequence once, maps unbounded smoothed coordinates into relative USB scale and manages output baselines. No such behavior is inserted into these upstream algorithm bodies." +} diff --git a/external/libogc_ir/ir.h b/external/libogc_ir/ir.h new file mode 100644 index 0000000..54c9bd6 --- /dev/null +++ b/external/libogc_ir/ir.h @@ -0,0 +1,162 @@ +/* + * Portable extraction of the libogc Wiiuse IR component, modified 2026-09-11. + * Original declarations are copied verbatim from the pinned libogc sources. + * This component remains under the GNU GPL with the libogc section 18 linking + * exception, explicitly extended to this modified version. See + * license_libogc.txt, libogc_license.txt, NOTICE.txt and UPSTREAM.json beside + * this header. The surrounding independent project is not relicensed. + * The original Wiiuse notice below is from upstream/wiiuse_internal.h. + */ +/* + * wiiuse + * + * Written By: + * Michael Laforest < para > + * Email: < thepara (--AT--) g m a i l [--DOT--] com > + * + * Copyright 2006-2007 + * + * This file is part of wiiuse. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * $Header: /lvm/shared/ds/ds/cvs/devkitpro-cvsbackup/libogc/wiiuse/wiiuse_internal.h,v 1.8 2008-12-10 16:16:40 shagkur Exp $ + * + */ + +#ifndef SWITCH_PICO_LIBOGC_IR_H +#define SWITCH_PICO_LIBOGC_IR_H + +typedef unsigned char ubyte; +typedef float f32; + +/* IR correction types */ +typedef enum ir_position_t { + WIIUSE_IR_ABOVE, + WIIUSE_IR_BELOW +} ir_position_t; + +/** + * @struct orient_t + * @brief Orientation struct. + * + * Yaw, pitch, and roll range from -180 to 180 degrees. + */ +typedef struct orient_t { + float roll; /**< roll, this may be smoothed if enabled */ + float pitch; /**< pitch, this may be smoothed if enabled */ + float yaw; + + float a_roll; /**< absolute roll, unsmoothed */ + float a_pitch; /**< absolute pitch, unsmoothed */ +} orient_t; + +/** + * @struct ir_dot_t + * @brief A single IR source. + */ +typedef struct ir_dot_t { + ubyte visible; /**< if the IR source is visible */ + + short rx; /**< raw X coordinate (0-1023) */ + short ry; /**< raw Y coordinate (0-767) */ + + ubyte size; /**< size of the IR dot (0-15) */ +} ir_dot_t; + + +typedef struct fdot_t { + float x,y; +} fdot_t; + +typedef struct sb_t { + fdot_t dots[2]; + fdot_t acc_dots[2]; + fdot_t rot_dots[2]; + float angle; + float off_angle; + float score; +} sb_t; + +/** + * @enum aspect_t + * @brief Screen aspect ratio. + */ +typedef enum aspect_t { + WIIUSE_ASPECT_4_3, + WIIUSE_ASPECT_16_9 +} aspect_t; + + +/** + * @struct ir_t + * @brief IR struct. Hold all data related to the IR tracking. + */ +typedef struct ir_t { + struct ir_dot_t dot[4]; /**< IR dots */ + ubyte num_dots; /**< number of dots at this time */ + + int state; /**< keeps track of the IR state */ + + int raw_valid; /**< is the raw position valid? */ + sb_t sensorbar; /**< sensor bar, detected or guessed */ + float ax; /**< raw X coordinate */ + float ay; /**< raw Y coordinate */ + float distance; /**< pixel width of the sensor bar */ + float z; /**< calculated distance in meters */ + float angle; /**< angle of the wiimote to the sensor bar*/ + + int smooth_valid; /**< is the smoothed position valid? */ + float sx; /**< smoothed X coordinate */ + float sy; /**< smoothed Y coordinate */ + float error_cnt; /**< error count, for smoothing algorithm*/ + float glitch_cnt; /**< glitch count, same */ + + int valid; /**< is the bounded position valid? */ + float x; /**< bounded X coordinate */ + float y; /**< bounded Y coordinate */ + enum aspect_t aspect; /**< aspect ratio of the screen */ + enum ir_position_t pos; /**< IR sensor bar position */ + unsigned int vres[2]; /**< IR virtual screen resolution */ + int offset[2]; /**< IR XY correction offset */ + +} ir_t; + +enum { + IR_STATE_DEAD = 0, + IR_STATE_GOOD, + IR_STATE_SINGLE, + IR_STATE_LOST, +}; + +/* aspect ratio */ +#define WM_ASPECT_16_9_X 660 +#define WM_ASPECT_16_9_Y 370 +#define WM_ASPECT_4_3_X 560 +#define WM_ASPECT_4_3_Y 420 + +#ifdef __cplusplus +extern "C" { +#endif + +float calc_yaw(struct ir_t* ir); +void interpret_ir_data(struct ir_t* ir, struct orient_t *orient); +void find_sensorbar(struct ir_t* ir, struct orient_t *orient); +void apply_ir_smoothing(struct ir_t *ir); + +#ifdef __cplusplus +} +#endif + +#endif /* SWITCH_PICO_LIBOGC_IR_H */ diff --git a/external/libogc_ir/libogc_license.txt b/external/libogc_ir/libogc_license.txt new file mode 100644 index 0000000..a3dfd05 --- /dev/null +++ b/external/libogc_ir/libogc_license.txt @@ -0,0 +1,20 @@ + Copyright (C) 2004 - 2009 + Michael Wiedenbauer (shagkur) + Dave Murphy (WinterMute) + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any + damages arising from the use of this software. + + Permission is granted to anyone to use this software for any + purpose, including commercial applications, and to alter it and + redistribute it freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. + 3. This notice may not be removed or altered from any source + distribution. diff --git a/external/libogc_ir/license_libogc.txt b/external/libogc_ir/license_libogc.txt new file mode 100644 index 0000000..a149fce --- /dev/null +++ b/external/libogc_ir/license_libogc.txt @@ -0,0 +1,641 @@ +This license is valid ONLY for libogc and what this license +defines as a "covered work" or a "combined work" with libogc. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an officialder +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + 18. Exceptions + + Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole combination. + + As a special exception, the copyright holders of this library give +you permission to link this library with independent modules to produce +an executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from or +based on this library. If you modify this library, you may extend this +exception to your version of the library, but you are not obligated to +do so. If you do not wish to do so, delete this exception statement from +your version. + diff --git a/external/libogc_ir/upstream/definitions.h b/external/libogc_ir/upstream/definitions.h new file mode 100644 index 0000000..04dc5be --- /dev/null +++ b/external/libogc_ir/upstream/definitions.h @@ -0,0 +1,55 @@ +#ifndef __DEFINITIONS_H__ +#define __DEFINITIONS_H__ + +#include "os.h" + +#define WIIMOTE_PI 3.14159265f + +//#define WITH_WIIUSE_DEBUG + +/* Error output macros */ +#define WIIUSE_ERROR(fmt, ...) fprintf(stderr, "[ERROR] " fmt "\n", ##__VA_ARGS__) + +/* Warning output macros */ +#define WIIUSE_WARNING(fmt, ...) fprintf(stderr, "[WARNING] " fmt "\n", ##__VA_ARGS__) + +/* Information output macros */ +#define WIIUSE_INFO(fmt, ...) fprintf(stderr, "[INFO] " fmt "\n", ##__VA_ARGS__) + +#ifdef WITH_WIIUSE_DEBUG + #ifdef WIN32 + #define WIIUSE_DEBUG(fmt, ...) do { \ + char* file = __FILE__; \ + int i = strlen(file) - 1; \ + for (; i && (file[i] != '\\'); --i); \ + fprintf(stderr, "[DEBUG] %s:%i: " fmt "\n", file+i+1, __LINE__, ##__VA_ARGS__); \ + } while (0) + #else + #define WIIUSE_DEBUG(fmt, ...) fprintf(stderr, "[DEBUG] " __FILE__ ":%i: " fmt "\n", __LINE__, ##__VA_ARGS__) + #endif +#else + #define WIIUSE_DEBUG(fmt, ...) +#endif + +#if 1 +#define WII_DEBUG(fmt, ...) do { \ + printf("[WDEBUG] " __FILE__ ":%i: " fmt "\n", __LINE__, ##__VA_ARGS__); \ + usleep(3000000); \ + } while (0) +#else + #define WII_DEBUG(fmt, ...) +#endif + + +/* Convert between radians and degrees */ +#define RAD_TO_DEGREE(r) ((r * 180.0f) / WIIMOTE_PI) +#define DEGREE_TO_RAD(d) (d * (WIIMOTE_PI / 180.0f)) + +/* Convert to big endian */ +#define BIG_ENDIAN_LONG(i) (htonl(i)) +#define BIG_ENDIAN_SHORT(i) (htons(i)) + +#define absf(x) ((x >= 0) ? (x) : (x * -1.0f)) +#define diff_f(x, y) ((x >= y) ? (absf(x - y)) : (absf(y - x))) + +#endif diff --git a/external/libogc_ir/upstream/ir.c b/external/libogc_ir/upstream/ir.c new file mode 100644 index 0000000..d9659f5 --- /dev/null +++ b/external/libogc_ir/upstream/ir.c @@ -0,0 +1,834 @@ +#include +#include +#include + +#ifndef WIN32 + #include +#endif +#ifdef GEKKO + #include +#endif +#include "definitions.h" +#include "wiiuse_internal.h" +#include "ir.h" + +static int ir_correct_for_bounds(float* x, float* y, enum aspect_t aspect, int offset_x, int offset_y); +static void ir_convert_to_vres(float* x, float* y, enum aspect_t aspect, unsigned int vx, unsigned int vy); + +/** + * @brief Get the IR sensitivity settings. + * + * @param wm Pointer to a wiimote_t structure. + * @param block1 [out] Pointer to where block1 will be set. + * @param block2 [out] Pointer to where block2 will be set. + * + * @return Returns the sensitivity level. + */ +static int get_ir_sens(struct wiimote_t* wm, char** block1, char** block2) { + if (WIIMOTE_IS_SET(wm, WIIMOTE_STATE_IR_SENS_LVL1)) { + *block1 = WM_IR_BLOCK1_LEVEL1; + *block2 = WM_IR_BLOCK2_LEVEL1; + return 1; + } else if (WIIMOTE_IS_SET(wm, WIIMOTE_STATE_IR_SENS_LVL2)) { + *block1 = WM_IR_BLOCK1_LEVEL2; + *block2 = WM_IR_BLOCK2_LEVEL2; + return 2; + } else if (WIIMOTE_IS_SET(wm, WIIMOTE_STATE_IR_SENS_LVL3)) { + *block1 = WM_IR_BLOCK1_LEVEL3; + *block2 = WM_IR_BLOCK2_LEVEL3; + return 3; + } else if (WIIMOTE_IS_SET(wm, WIIMOTE_STATE_IR_SENS_LVL4)) { + *block1 = WM_IR_BLOCK1_LEVEL4; + *block2 = WM_IR_BLOCK2_LEVEL4; + return 4; + } else if (WIIMOTE_IS_SET(wm, WIIMOTE_STATE_IR_SENS_LVL5)) { + *block1 = WM_IR_BLOCK1_LEVEL5; + *block2 = WM_IR_BLOCK2_LEVEL5; + return 5; + } + + *block1 = NULL; + *block2 = NULL; + return 0; +} + +static void rotate_dots(struct fdot_t* in, struct fdot_t *out, int count, float ang) { + float s, c; + int i; + + if (ang == 0) { + for (i = 0; i < count; ++i) { + out[i].x = in[i].x; + out[i].y = in[i].y; + } + return; + } + + s = sin(DEGREE_TO_RAD(ang)); + c = cos(DEGREE_TO_RAD(ang)); + + /* + * [ cos(theta) -sin(theta) ][ ir->rx ] + * [ sin(theta) cos(theta) ][ ir->ry ] + */ + + for (i = 0; i < count; ++i) { + out[i].x = (c * in[i].x) + (-s * in[i].y); + out[i].y = (s * in[i].x) + (c * in[i].y); + } +} + +/** + * @brief Correct for the IR bounding box. + * + * @param x [out] The current X, it will be updated if valid. + * @param y [out] The current Y, it will be updated if valid. + * @param aspect Aspect ratio of the screen. + * @param offset_x The X offset of the bounding box. + * @param offset_y The Y offset of the bounding box. + * + * @return Returns 1 if the point is valid and was updated. + * + * Nintendo was smart with this bit. They sacrifice a little + * precision for a big increase in usability. + */ +static int ir_correct_for_bounds(float* x, float* y, enum aspect_t aspect, int offset_x, int offset_y) { + float x0, y0; + int xs, ys; + + if (aspect == WIIUSE_ASPECT_16_9) { + xs = WM_ASPECT_16_9_X; + ys = WM_ASPECT_16_9_Y; + } else { + xs = WM_ASPECT_4_3_X; + ys = WM_ASPECT_4_3_Y; + } + + x0 = ((1024 - xs) / 2) + offset_x; + y0 = ((768 - ys) / 2) + offset_y; + + if ((*x >= x0) + && (*x <= (x0 + xs)) + && (*y >= y0) + && (*y <= (y0 + ys))) + { + *x -= offset_x; + *y -= offset_y; + + return 1; + } + + return 0; +} + + +/** + * @brief Interpolate the point to the user defined virtual screen resolution. + */ +static void ir_convert_to_vres(float* x, float* y, enum aspect_t aspect, unsigned int vx, unsigned int vy) { + int xs, ys; + + if (aspect == WIIUSE_ASPECT_16_9) { + xs = WM_ASPECT_16_9_X; + ys = WM_ASPECT_16_9_Y; + } else { + xs = WM_ASPECT_4_3_X; + ys = WM_ASPECT_4_3_Y; + } + + *x -= ((1024-xs)/2); + *y -= ((768-ys)/2); + + *x = (*x / (float)xs) * vx; + *y = (*y / (float)ys) * vy; +} + +void wiiuse_set_ir_mode(struct wiimote_t *wm) +{ + ubyte buf = 0x00; + + if(!wm) return; + if(!WIIMOTE_IS_SET(wm,WIIMOTE_STATE_IR)) return; + + if(WIIMOTE_IS_SET(wm,WIIMOTE_STATE_EXP)) buf = WM_IR_TYPE_BASIC; + else buf = WM_IR_TYPE_EXTENDED; + wiiuse_write_data(wm,WM_REG_IR_MODENUM, &buf, 1, NULL); +} + +void wiiuse_set_ir(struct wiimote_t *wm,int status) +{ + ubyte buf = 0x00; + int ir_level = 0; + char* block1 = NULL; + char* block2 = NULL; + + if(!wm) return; + + /* + * Wait for the handshake to finish first. + * When it handshake finishes and sees that + * IR is enabled, it will call this function + * again to actually enable IR. + */ + if(!WIIMOTE_IS_SET(wm,WIIMOTE_STATE_HANDSHAKE_COMPLETE)) { + WIIUSE_DEBUG("Tried to enable IR, will wait until handshake finishes.\n"); + if(status) + WIIMOTE_ENABLE_STATE(wm, WIIMOTE_STATE_IR_INIT); + else + WIIMOTE_DISABLE_STATE(wm, WIIMOTE_STATE_IR_INIT); + return; + } + + /* + * Check to make sure a sensitivity setting is selected. + */ + ir_level = get_ir_sens(wm, &block1, &block2); + if (!ir_level) { + WIIUSE_ERROR("No IR sensitivity setting selected."); + return; + } + + if (status) { + /* if already enabled then stop */ + if (WIIMOTE_IS_SET(wm, WIIMOTE_STATE_IR) || WIIMOTE_IS_SET(wm, WIIMOTE_STATE_WIIU_PRO)) { + wiiuse_status(wm,NULL); + return; + } + } else { + /* if already disabled then stop */ + if (!WIIMOTE_IS_SET(wm, WIIMOTE_STATE_IR)) { + wiiuse_status(wm,NULL); + return; + } + } + + buf = (status ? 0x04 : 0x00); + wiiuse_sendcmd(wm,WM_CMD_IR,&buf,1,NULL); + wiiuse_sendcmd(wm,WM_CMD_IR_2,&buf,1,NULL); + + if (!status) { + WIIUSE_DEBUG("Disabled IR cameras for wiimote id %i.", wm->unid); + wiiuse_status(wm,NULL); + return; + } + + /* enable IR, set sensitivity */ + buf = 0x08; + wiiuse_write_data(wm,WM_REG_IR,&buf,1,NULL); + + wiiuse_write_data(wm, WM_REG_IR_BLOCK1, (ubyte*)block1, 9, NULL); + wiiuse_write_data(wm, WM_REG_IR_BLOCK2, (ubyte*)block2, 2, NULL); + + if(WIIMOTE_IS_SET(wm,WIIMOTE_STATE_EXP)) buf = WM_IR_TYPE_BASIC; + else buf = WM_IR_TYPE_EXTENDED; + wiiuse_write_data(wm,WM_REG_IR_MODENUM, &buf, 1, NULL); + + wiiuse_status(wm,NULL); + return; +} + +/** + * @brief Set the virtual screen resolution for IR tracking. + * + * @param wm Pointer to a wiimote_t structure. + * @param status 1 to enable, 0 to disable. + */ +void wiiuse_set_ir_vres(struct wiimote_t* wm, unsigned int x, unsigned int y) { + if (!wm) return; + + wm->ir.vres[0] = (x-1); + wm->ir.vres[1] = (y-1); +} + +/** + * @brief Set the XY position for the IR cursor. + * + * @param wm Pointer to a wiimote_t structure. + */ +void wiiuse_set_ir_position(struct wiimote_t* wm, enum ir_position_t pos) { + if (!wm) return; + + wm->ir.pos = pos; + + switch (pos) { + + case WIIUSE_IR_ABOVE: + wm->ir.offset[0] = 0; + + if (wm->ir.aspect == WIIUSE_ASPECT_16_9) + wm->ir.offset[1] = WM_ASPECT_16_9_Y/2 - 70; + else if (wm->ir.aspect == WIIUSE_ASPECT_4_3) + wm->ir.offset[1] = WM_ASPECT_4_3_Y/2 - 100; + + return; + + case WIIUSE_IR_BELOW: + wm->ir.offset[0] = 0; + + if (wm->ir.aspect == WIIUSE_ASPECT_16_9) + wm->ir.offset[1] = -WM_ASPECT_16_9_Y/2 + 70; + else if (wm->ir.aspect == WIIUSE_ASPECT_4_3) + wm->ir.offset[1] = -WM_ASPECT_4_3_Y/2 + 100; + + return; + + default: + return; + }; +} + +/** + * @brief Set the aspect ratio of the TV/monitor. + * + * @param wm Pointer to a wiimote_t structure. + * @param aspect Either WIIUSE_ASPECT_16_9 or WIIUSE_ASPECT_4_3 + */ +void wiiuse_set_aspect_ratio(struct wiimote_t* wm, enum aspect_t aspect) { + if (!wm) return; + + wm->ir.aspect = aspect; + + if (aspect == WIIUSE_ASPECT_4_3) { + wm->ir.vres[0] = WM_ASPECT_4_3_X; + wm->ir.vres[1] = WM_ASPECT_4_3_Y; + } else { + wm->ir.vres[0] = WM_ASPECT_16_9_X; + wm->ir.vres[1] = WM_ASPECT_16_9_Y; + } + + /* reset the position offsets */ + wiiuse_set_ir_position(wm, wm->ir.pos); +} + + +/** + * @brief Set the IR sensitivity. + * + * @param wm Pointer to a wiimote_t structure. + * @param level 1-5, same as Wii system sensitivity setting. + * + * If the level is < 1, then level will be set to 1. + * If the level is > 5, then level will be set to 5. + */ +void wiiuse_set_ir_sensitivity(struct wiimote_t* wm, int level) { + char* block1 = NULL; + char* block2 = NULL; + + if (!wm) return; + + if (level > 5) level = 5; + if (level < 1) level = 1; + + WIIMOTE_DISABLE_STATE(wm, (WIIMOTE_STATE_IR_SENS_LVL1 | + WIIMOTE_STATE_IR_SENS_LVL2 | + WIIMOTE_STATE_IR_SENS_LVL3 | + WIIMOTE_STATE_IR_SENS_LVL4 | + WIIMOTE_STATE_IR_SENS_LVL5)); + + switch (level) { + case 1: + WIIMOTE_ENABLE_STATE(wm, WIIMOTE_STATE_IR_SENS_LVL1); + break; + case 2: + WIIMOTE_ENABLE_STATE(wm, WIIMOTE_STATE_IR_SENS_LVL2); + break; + case 3: + WIIMOTE_ENABLE_STATE(wm, WIIMOTE_STATE_IR_SENS_LVL3); + break; + case 4: + WIIMOTE_ENABLE_STATE(wm, WIIMOTE_STATE_IR_SENS_LVL4); + break; + case 5: + WIIMOTE_ENABLE_STATE(wm, WIIMOTE_STATE_IR_SENS_LVL5); + break; + default: + return; + } + + if(!WIIMOTE_IS_SET(wm,WIIMOTE_STATE_IR)) return; + + /* set the new sensitivity */ + get_ir_sens(wm, &block1, &block2); + + wiiuse_write_data(wm, WM_REG_IR_BLOCK1, (ubyte*)block1, 9,NULL); + wiiuse_write_data(wm, WM_REG_IR_BLOCK2, (ubyte*)block2, 2,NULL); + + WIIUSE_DEBUG("Set IR sensitivity to level %i (unid %i)", level, wm->unid); +} + + +/** + * @brief Calculate the data from the IR spots. Basic IR mode. + * + * @param wm Pointer to a wiimote_t structure. + * @param data Data returned by the wiimote for the IR spots. + */ +void calculate_basic_ir(struct wiimote_t* wm, ubyte* data) { + struct ir_dot_t* dot = wm->ir.dot; + int i; + + dot[0].rx = 1023 - (data[0] | ((data[2] & 0x30) << 4)); + dot[0].ry = data[1] | ((data[2] & 0xC0) << 2); + + dot[1].rx = 1023 - (data[3] | ((data[2] & 0x03) << 8)); + dot[1].ry = data[4] | ((data[2] & 0x0C) << 6); + + dot[2].rx = 1023 - (data[5] | ((data[7] & 0x30) << 4)); + dot[2].ry = data[6] | ((data[7] & 0xC0) << 2); + + dot[3].rx = 1023 - (data[8] | ((data[7] & 0x03) << 8)); + dot[3].ry = data[9] | ((data[7] & 0x0C) << 6); + + /* set each IR spot to visible if spot is in range */ + for (i = 0; i < 4; ++i) { + dot[i].rx = BIG_ENDIAN_SHORT(dot[i].rx); + dot[i].ry = BIG_ENDIAN_SHORT(dot[i].ry); + + if (dot[i].ry == 1023) + dot[i].visible = 0; + else { + dot[i].visible = 1; + dot[i].size = 0; /* since we don't know the size, set it as 0 */ + } + } +#ifndef GEKKO + interpret_ir_data(&wm->ir,&wm->orient,WIIMOTE_IS_SET(wm, WIIMOTE_STATE_ACC)); +#endif +} + +/** + * @brief Calculate the data from the IR spots. Extended IR mode. + * + * @param wm Pointer to a wiimote_t structure. + * @param data Data returned by the wiimote for the IR spots. + */ +void calculate_extended_ir(struct wiimote_t* wm, ubyte* data) { + struct ir_dot_t* dot = wm->ir.dot; + int i; + + for (i = 0; i < 4; ++i) { + dot[i].rx = 1023 - (data[3*i] | ((data[(3*i)+2] & 0x30) << 4)); + dot[i].ry = data[(3*i)+1] | ((data[(3*i)+2] & 0xC0) << 2); + + dot[i].size = data[(3*i)+2]; + + dot[i].rx = BIG_ENDIAN_SHORT(dot[i].rx); + dot[i].ry = BIG_ENDIAN_SHORT(dot[i].ry); + + dot[i].size = dot[i].size&0x0f; + + /* if in range set to visible */ + if (dot[i].ry == 1023) + dot[i].visible = 0; + else + dot[i].visible = 1; + } +#ifndef GEKKO + interpret_ir_data(&wm->ir,&wm->orient,WIIMOTE_IS_SET(wm, WIIMOTE_STATE_ACC)); +#endif +} + +enum { + IR_STATE_DEAD = 0, + IR_STATE_GOOD, + IR_STATE_SINGLE, + IR_STATE_LOST, +}; + +// half-height of the IR sensor if half-width is 1 +#define HEIGHT (384.0f / 512.0f) +// maximum sensor bar slope (tan(35 degrees)) +#define MAX_SB_SLOPE 0.7f +// minimum sensor bar width in view, relative to half of the IR sensor area +#define MIN_SB_WIDTH 0.1f +// reject "sensor bars" that happen to have a dot towards the middle +#define SB_MIDDOT_REJECT 0.05f + +// physical dimensions +// cm center to center of emitters +#define SB_WIDTH 19.5f +// half-width in cm of emitters +#define SB_DOT_WIDTH 2.25f +// half-height in cm of emitters (with some tolerance) +#define SB_DOT_HEIGHT 1.0f + +#define SB_DOT_WIDTH_RATIO (SB_DOT_WIDTH / SB_WIDTH) +#define SB_DOT_HEIGHT_RATIO (SB_DOT_HEIGHT / SB_WIDTH) + +// dots further out than these coords are allowed to not be picked up +// otherwise assume something's wrong +//#define SB_OFF_SCREEN_X 0.8f +//#define SB_OFF_SCREEN_Y (0.8f * HEIGHT) + +// disable, may be doing more harm than good due to sensor pickup glitches +#define SB_OFF_SCREEN_X 0.0f +#define SB_OFF_SCREEN_Y 0.0f + +// if a point is closer than this to one of the previous SB points +// when it reappears, consider it the same instead of trying to guess +// which one of the two it is +#define SB_SINGLE_NOGUESS_DISTANCE (100.0 * 100.0) + +// width of the sensor bar in pixels at one meter from the Wiimote +#define SB_Z_COEFFICIENT 256.0f + +// distance in meters from the center of the FOV to the left or right edge, +// when the wiimote is at one meter +#define WIIMOTE_FOV_COEFFICIENT 0.39f + +#define SQUARED(x) ((x)*(x)) +#define WMAX(x,y) ((x>y)?(x):(y)) +#define WMIN(x,y) ((xroll); + + /* count visible dots and populate dots structure */ + /* dots[] is in -1..1 units for width */ + ir->num_dots = 0; + for (i = 0; i < 4; i++) { + if (ir->dot[i].visible) { + dots[ir->num_dots].x = (ir->dot[i].rx - 512.0f) / 512.0f; + dots[ir->num_dots].y = (ir->dot[i].ry - 384.0f) / 512.0f; + WIIUSE_DEBUG("IR: dot %d at (%d,%d) (%.03f,%.03f)\n",ir->num_dots,ir->dot[i].rx,ir->dot[i].ry,dots[ir->num_dots].x,dots[ir->num_dots].y); + ir->num_dots++; + } + } + + WIIUSE_DEBUG("IR: found %d dots\n",ir->num_dots); + + // nothing to track + if(ir->num_dots == 0) { + if(ir->state != IR_STATE_DEAD) + ir->state = IR_STATE_LOST; + ir->ax = 0; + ir->ay = 0; + ir->distance = 0.0f; + ir->raw_valid = 0; + return; + } + + /* ==== Find the Sensor Bar ==== */ + + // first rotate according to accelerometer orientation + rotate_dots(dots, acc_dots, ir->num_dots, orient->roll); + if(ir->num_dots > 1) { + WIIUSE_DEBUG("IR: locating sensor bar candidates\n"); + + // iterate through all dot pairs + for(first=0; first < (ir->num_dots-1); first++) { + for(second=(first+1); second < ir->num_dots; second++) { + WIIUSE_DEBUG("IR: trying dots %d and %d\n",first,second); + // order the dots leftmost first into cand + // storing both the raw dots and the accel-rotated dots + if(acc_dots[first].x > acc_dots[second].x) { + cand.dots[0] = dots[second]; + cand.dots[1] = dots[first]; + cand.acc_dots[0] = acc_dots[second]; + cand.acc_dots[1] = acc_dots[first]; + } else { + cand.dots[0] = dots[first]; + cand.dots[1] = dots[second]; + cand.acc_dots[0] = acc_dots[first]; + cand.acc_dots[1] = acc_dots[second]; + } + difference.x = cand.acc_dots[1].x - cand.acc_dots[0].x; + difference.y = cand.acc_dots[1].y - cand.acc_dots[0].y; + + // check angle + if(fabsf(difference.y / difference.x) > MAX_SB_SLOPE) + continue; + WIIUSE_DEBUG("IR: passed angle check\n"); + // rotate to the true sensor bar angle + cand.off_angle = -RAD_TO_DEGREE(atan2(difference.y, difference.x)); + cand.angle = cand.off_angle + orient->roll; + rotate_dots(cand.dots, cand.rot_dots, 2, cand.angle); + WIIUSE_DEBUG("IR: off_angle: %.02f, angle: %.02f\n", cand.off_angle, cand.angle); + // recalculate x distance - y should be zero now, so ignore it + difference.x = cand.rot_dots[1].x - cand.rot_dots[0].x; + + // check distance + if(difference.x < MIN_SB_WIDTH) + continue; + // middle dot check. If there's another source somewhere in the + // middle of this candidate, then this can't be a sensor bar + + for(i=0; inum_dots; i++) { + float wadj, hadj; + struct fdot_t tdot; + if(i==first || i==second) continue; + hadj = SB_DOT_HEIGHT_RATIO * difference.x; + wadj = SB_DOT_WIDTH_RATIO * difference.x; + rotate_dots(&dots[i], &tdot, 1, cand.angle); + if( ((cand.rot_dots[0].x + wadj) < tdot.x) && + ((cand.rot_dots[1].x - wadj) > tdot.x) && + ((cand.rot_dots[0].y + hadj) > tdot.y) && + ((cand.rot_dots[0].y - hadj) < tdot.y)) + break; + } + // failed middle dot check + if(i < ir->num_dots) continue; + WIIUSE_DEBUG("IR: passed middle dot check\n"); + + cand.score = 1 / (cand.rot_dots[1].x - cand.rot_dots[0].x); + + // we have a candidate, store it + WIIUSE_DEBUG("IR: new candidate %d\n",num_candidates); + candidates[num_candidates++] = cand; + } + } + } + + if(num_candidates == 0) { + int closest = -1; + int closest_to = 0; + float best = 999.0f; + float d; + float dx[2]; + struct sb_t sbx[2]; + // no sensor bar candidates, try to work with a lone dot + WIIUSE_DEBUG("IR: no candidates\n"); + switch(ir->state) { + case IR_STATE_DEAD: + WIIUSE_DEBUG("IR: we're dead\n"); + // we've never seen a sensor bar before, so we're screwed + ir->ax = 0.0f; + ir->ay = 0.0f; + ir->distance = 0.0f; + ir->raw_valid = 0; + return; + case IR_STATE_GOOD: + case IR_STATE_SINGLE: + case IR_STATE_LOST: + WIIUSE_DEBUG("IR: trying to keep track of single dot\n"); + // try to find the dot closest to the previous sensor bar position + for(i=0; inum_dots; i++) { + WIIUSE_DEBUG("IR: checking dot %d (%.02f, %.02f)\n",i, acc_dots[i].x,acc_dots[i].y); + for(j=0; j<2; j++) { + WIIUSE_DEBUG(" to dot %d (%.02f, %.02f)\n",j, ir->sensorbar.acc_dots[j].x,ir->sensorbar.acc_dots[j].y); + d = SQUARED(acc_dots[i].x - ir->sensorbar.acc_dots[j].x); + d += SQUARED(acc_dots[i].y - ir->sensorbar.acc_dots[j].y); + if(d < best) { + best = d; + closest_to = j; + closest = i; + } + } + } + WIIUSE_DEBUG("IR: closest dot is %d to %d\n",closest,closest_to); + if(ir->state != IR_STATE_LOST || best < SB_SINGLE_NOGUESS_DISTANCE) { + // now work out where the other dot would be, in the acc frame + sb.acc_dots[closest_to] = acc_dots[closest]; + sb.acc_dots[closest_to^1].x = ir->sensorbar.acc_dots[closest_to^1].x - ir->sensorbar.acc_dots[closest_to].x + acc_dots[closest].x; + sb.acc_dots[closest_to^1].y = ir->sensorbar.acc_dots[closest_to^1].y - ir->sensorbar.acc_dots[closest_to].y + acc_dots[closest].y; + // get the raw frame + rotate_dots(sb.acc_dots, sb.dots, 2, -orient->roll); + if((fabsf(sb.dots[closest_to^1].x) < SB_OFF_SCREEN_X) && (fabsf(sb.dots[closest_to^1].y) < SB_OFF_SCREEN_Y)) { + // this dot should be visible but isn't, since the candidate section failed. + // fall through and try to pick out the sensor bar without previous information + WIIUSE_DEBUG("IR: dot falls on screen, falling through\n"); + } else { + // calculate the rotated dots frame + // angle tends to drift, so recalculate + sb.off_angle = -RAD_TO_DEGREE(atan2(sb.acc_dots[1].y - sb.acc_dots[0].y, sb.acc_dots[1].x - sb.acc_dots[0].x)); + sb.angle = ir->sensorbar.off_angle + orient->roll; + rotate_dots(sb.acc_dots, sb.rot_dots, 2, ir->sensorbar.off_angle); + WIIUSE_DEBUG("IR: kept track of single dot\n"); + break; + } + } else { + WIIUSE_DEBUG("IR: lost the dot and new one is too far away\n"); + } + // try to find the dot closest to the sensor edge + WIIUSE_DEBUG("IR: trying to find best dot\n"); + for(i=0; inum_dots; i++) { + d = WMIN(1.0f - fabsf(dots[i].x), HEIGHT - fabsf(dots[i].y)); + if(d < best) { + best = d; + closest = i; + } + } + WIIUSE_DEBUG("IR: best dot: %d\n",closest); + // now try it as both places in the sensor bar + // and pick the one that places the other dot furthest off-screen + for(i=0; i<2; i++) { + sbx[i].acc_dots[i] = acc_dots[closest]; + sbx[i].acc_dots[i^1].x = ir->sensorbar.acc_dots[i^1].x - ir->sensorbar.acc_dots[i].x + acc_dots[closest].x; + sbx[i].acc_dots[i^1].y = ir->sensorbar.acc_dots[i^1].y - ir->sensorbar.acc_dots[i].y + acc_dots[closest].y; + rotate_dots(sbx[i].acc_dots, sbx[i].dots, 2, -orient->roll); + dx[i] = WMAX(fabsf(sbx[i].dots[i^1].x),fabsf(sbx[i].dots[i^1].y / HEIGHT)); + } + if(dx[0] > dx[1]) { + WIIUSE_DEBUG("IR: dot is LEFT: %.02f > %.02f\n",dx[0],dx[1]); + sb = sbx[0]; + } else { + WIIUSE_DEBUG("IR: dot is RIGHT: %.02f < %.02f\n",dx[0],dx[1]); + sb = sbx[1]; + } + // angle tends to drift, so recalculate + sb.off_angle = -RAD_TO_DEGREE(atan2(sb.acc_dots[1].y - sb.acc_dots[0].y, sb.acc_dots[1].x - sb.acc_dots[0].x)); + sb.angle = ir->sensorbar.off_angle + orient->roll; + rotate_dots(sb.acc_dots, sb.rot_dots, 2, ir->sensorbar.off_angle); + WIIUSE_DEBUG("IR: found new dot to track\n"); + break; + } + sb.score = 0; + ir->state = IR_STATE_SINGLE; + } else { + int bestidx = 0; + float best = 0.0f; + WIIUSE_DEBUG("IR: finding best candidate\n"); + // look for the best candidate + // for now, the formula is simple: pick the one with the smallest distance + for(i=0; i best) { + bestidx = i; + best = candidates[i].score; + } + } + WIIUSE_DEBUG("IR: best candidate: %d\n",bestidx); + sb = candidates[bestidx]; + ir->state = IR_STATE_GOOD; + } + + ir->raw_valid = 1; + ir->ax = ((sb.rot_dots[0].x + sb.rot_dots[1].x) / 2) * 512.0 + 512.0; + ir->ay = ((sb.rot_dots[0].y + sb.rot_dots[1].y) / 2) * 512.0 + 384.0; + ir->sensorbar = sb; + ir->distance = (sb.rot_dots[1].x - sb.rot_dots[0].x) * 512.0; + +} + +#define SMOOTH_IR_RADIUS 8.0f +#define SMOOTH_IR_SPEED 0.25f +#define SMOOTH_IR_DEADZONE 2.5f + +/** + * @brief Smooth the IR pointer position + * + * @param ir Pointer to an ir_t structure. + */ +void apply_ir_smoothing(struct ir_t *ir) { + f32 dx, dy, d, theta; + + WIIUSE_DEBUG("Smooth: OK (%.02f, %.02f) LAST (%.02f, %.02f) ", ir->ax, ir->ay, ir->sx, ir->sy); + dx = ir->ax - ir->sx; + dy = ir->ay - ir->sy; + d = sqrtf(dx*dx + dy*dy); + if (d > SMOOTH_IR_DEADZONE) { + if (d < SMOOTH_IR_RADIUS) { + WIIUSE_DEBUG("INSIDE\n"); + ir->sx += dx * SMOOTH_IR_SPEED; + ir->sy += dy * SMOOTH_IR_SPEED; + } else { + WIIUSE_DEBUG("OUTSIDE\n"); + theta = atan2f(dy, dx); + ir->sx = ir->ax - cosf(theta) * SMOOTH_IR_RADIUS; + ir->sy = ir->ay - sinf(theta) * SMOOTH_IR_RADIUS; + } + } else { + WIIUSE_DEBUG("DEADZONE\n"); + } +} + +// max number of errors before cooked data drops out +#define ERROR_MAX_COUNT 8 +// max number of glitches before cooked data updates +#define GLITCH_MAX_COUNT 5 +// squared delta over which we consider something a glitch +#define GLITCH_DIST (150.0f * 150.0f) + +/** + * @brief Interpret IR data into more user friendly variables. + * + * @param ir Pointer to an ir_t structure. + * @param orient Pointer to an orient_t structure. + */ +void interpret_ir_data(struct ir_t* ir, struct orient_t *orient) { + + float x,y; + float d; + + find_sensorbar(ir, orient); + + if(ir->raw_valid) { + ir->angle = ir->sensorbar.angle; + ir->z = SB_Z_COEFFICIENT / ir->distance; + orient->yaw = calc_yaw(ir); + if(ir->error_cnt >= ERROR_MAX_COUNT) { + ir->sx = ir->ax; + ir->sy = ir->ay; + ir->glitch_cnt = 0; + } else { + d = SQUARED(ir->ax - ir->sx) + SQUARED(ir->ay - ir->sy); + if(d > GLITCH_DIST) { + if(ir->glitch_cnt > GLITCH_MAX_COUNT) { + apply_ir_smoothing(ir); + ir->glitch_cnt = 0; + } else { + ir->glitch_cnt++; + } + } else { + ir->glitch_cnt = 0; + apply_ir_smoothing(ir); + } + } + ir->smooth_valid = 1; + ir->error_cnt = 0; + } else { + if(ir->error_cnt >= ERROR_MAX_COUNT) { + ir->smooth_valid = 0; + } else { + ir->smooth_valid = 1; + ir->error_cnt++; + } + } + if(ir->smooth_valid) { + x = ir->sx; + y = ir->sy; + if (ir_correct_for_bounds(&x, &y, ir->aspect, ir->offset[0], ir->offset[1])) { + ir_convert_to_vres(&x, &y, ir->aspect, ir->vres[0], ir->vres[1]); + ir->x = x; + ir->y = y; + ir->valid = 1; + } else { + ir->valid = 0; + } + } else { + ir->valid = 0; + } +} + +/** + * @brief Calculate yaw given the IR data. + * + * @param ir IR data structure. + */ +float calc_yaw(struct ir_t* ir) { + float x; + + x = ir->ax - 512; + x *= WIIMOTE_FOV_COEFFICIENT / 512.0; + + return RAD_TO_DEGREE( atanf(x) ); +} + diff --git a/external/libogc_ir/upstream/ir.h b/external/libogc_ir/upstream/ir.h new file mode 100644 index 0000000..f90cfc8 --- /dev/null +++ b/external/libogc_ir/upstream/ir.h @@ -0,0 +1,22 @@ +#ifndef __IR_H__ +#define __IR_H__ + +#include "wiiuse_internal.h" + +#define WII_VRES_X 560 +#define WII_VRES_Y 340 + +#ifdef __cplusplus +extern "C" { +#endif + +void calculate_basic_ir(struct wiimote_t* wm, ubyte* data); +void calculate_extended_ir(struct wiimote_t* wm, ubyte* data); +float calc_yaw(struct ir_t* ir); +void interpret_ir_data(struct ir_t* ir, struct orient_t *orient); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/external/libogc_ir/upstream/wiiuse.h b/external/libogc_ir/upstream/wiiuse.h new file mode 100644 index 0000000..7be2a7d --- /dev/null +++ b/external/libogc_ir/upstream/wiiuse.h @@ -0,0 +1,748 @@ +#ifndef __WIIUSE_H__ +#define __WIIUSE_H__ + +#if defined(_WIN32) + /* windows */ + #include +#elif defined(GEKKO) + /* wii */ + #include +#elif defined(__linux__) + /* nix */ + #include +#endif + +#ifdef WIIUSE_INTERNAL_H_INCLUDED + #define WCONST +#else + #define WCONST const +#endif + +/* led bit masks */ +#define WIIMOTE_LED_NONE 0x00 +#define WIIMOTE_LED_1 0x10 +#define WIIMOTE_LED_2 0x20 +#define WIIMOTE_LED_3 0x40 +#define WIIMOTE_LED_4 0x80 + +/* button codes */ +#define WIIMOTE_BUTTON_TWO 0x0001 +#define WIIMOTE_BUTTON_ONE 0x0002 +#define WIIMOTE_BUTTON_B 0x0004 +#define WIIMOTE_BUTTON_A 0x0008 +#define WIIMOTE_BUTTON_MINUS 0x0010 +#define WIIMOTE_BUTTON_ZACCEL_BIT6 0x0020 +#define WIIMOTE_BUTTON_ZACCEL_BIT7 0x0040 +#define WIIMOTE_BUTTON_HOME 0x0080 +#define WIIMOTE_BUTTON_LEFT 0x0100 +#define WIIMOTE_BUTTON_RIGHT 0x0200 +#define WIIMOTE_BUTTON_DOWN 0x0400 +#define WIIMOTE_BUTTON_UP 0x0800 +#define WIIMOTE_BUTTON_PLUS 0x1000 +#define WIIMOTE_BUTTON_ZACCEL_BIT4 0x2000 +#define WIIMOTE_BUTTON_ZACCEL_BIT5 0x4000 +#define WIIMOTE_BUTTON_UNKNOWN 0x8000 +#define WIIMOTE_BUTTON_ALL 0x1F9F + +/* nunchul button codes */ +#define NUNCHUK_BUTTON_Z 0x01 +#define NUNCHUK_BUTTON_C 0x02 +#define NUNCHUK_BUTTON_ALL 0x03 + +/* classic controller button codes */ +#define CLASSIC_CTRL_BUTTON_UP 0x0001 +#define CLASSIC_CTRL_BUTTON_LEFT 0x0002 +#define CLASSIC_CTRL_BUTTON_ZR 0x0004 +#define CLASSIC_CTRL_BUTTON_X 0x0008 +#define CLASSIC_CTRL_BUTTON_A 0x0010 +#define CLASSIC_CTRL_BUTTON_Y 0x0020 +#define CLASSIC_CTRL_BUTTON_B 0x0040 +#define CLASSIC_CTRL_BUTTON_ZL 0x0080 +#define CLASSIC_CTRL_BUTTON_FULL_R 0x0200 +#define CLASSIC_CTRL_BUTTON_PLUS 0x0400 +#define CLASSIC_CTRL_BUTTON_HOME 0x0800 +#define CLASSIC_CTRL_BUTTON_MINUS 0x1000 +#define CLASSIC_CTRL_BUTTON_FULL_L 0x2000 +#define CLASSIC_CTRL_BUTTON_DOWN 0x4000 +#define CLASSIC_CTRL_BUTTON_RIGHT 0x8000 +#define CLASSIC_CTRL_BUTTON_ALL 0xFEFF + +/* guitar hero 3 button codes */ +#define GUITAR_HERO_3_BUTTON_STRUM_UP 0x0001 +#define GUITAR_HERO_3_BUTTON_YELLOW 0x0008 +#define GUITAR_HERO_3_BUTTON_GREEN 0x0010 +#define GUITAR_HERO_3_BUTTON_BLUE 0x0020 +#define GUITAR_HERO_3_BUTTON_RED 0x0040 +#define GUITAR_HERO_3_BUTTON_ORANGE 0x0080 +#define GUITAR_HERO_3_BUTTON_PLUS 0x0400 +#define GUITAR_HERO_3_BUTTON_MINUS 0x1000 +#define GUITAR_HERO_3_BUTTON_STRUM_DOWN 0x4000 +#define GUITAR_HERO_3_BUTTON_ALL 0xFEFF + +/* guitar hero world tour touch bar codes */ +#define GUITAR_HERO_3_TOUCH_AVAILABLE 0x1000 +#define GUITAR_HERO_3_TOUCH_GREEN 0x1001 +#define GUITAR_HERO_3_TOUCH_RED 0x1002 +#define GUITAR_HERO_3_TOUCH_YELLOW 0x1004 +#define GUITAR_HERO_3_TOUCH_BLUE 0x1008 +#define GUITAR_HERO_3_TOUCH_ORANGE 0x1010 + +/* wiimote option flags */ +#define WIIUSE_SMOOTHING 0x01 +#define WIIUSE_CONTINUOUS 0x02 +#define WIIUSE_ACCEL_THRESH 0x04 +#define WIIUSE_IR_THRESH 0x08 +#define WIIUSE_JS_THRESH 0x10 +#define WIIUSE_INIT_FLAGS WIIUSE_SMOOTHING + +#define WIIUSE_ORIENT_PRECISION 100.0f + +/* expansion codes */ +#define EXP_NONE 0 +#define EXP_NUNCHUK 1 +#define EXP_CLASSIC 2 +#define EXP_GUITAR_HERO_3 3 +#define EXP_WII_BOARD 4 +#define EXP_MOTION_PLUS 5 + +/* IR correction types */ +typedef enum ir_position_t { + WIIUSE_IR_ABOVE, + WIIUSE_IR_BELOW +} ir_position_t; + +/** + * @brief Check if a button is pressed. + * @param dev Pointer to a wiimote_t or expansion structure. + * @param button The button you are interested in. + * @return 1 if the button is pressed, 0 if not. + */ +#define IS_PRESSED(dev, button) ((dev->btns & button) == button) + +/** + * @brief Check if a button is being held. + * @param dev Pointer to a wiimote_t or expansion structure. + * @param button The button you are interested in. + * @return 1 if the button is held, 0 if not. + */ +#define IS_HELD(dev, button) ((dev->btns_held & button) == button) + +/** + * @brief Check if a button is released on this event. \n\n + * This does not mean the button is not pressed, it means \n + * this button was just now released. + * @param dev Pointer to a wiimote_t or expansion structure. + * @param button The button you are interested in. + * @return 1 if the button is released, 0 if not. + * + */ +#define IS_RELEASED(dev, button) ((dev->btns_released & button) == button) + +/** + * @brief Check if a button has just been pressed this event. + * @param dev Pointer to a wiimote_t or expansion structure. + * @param button The button you are interested in. + * @return 1 if the button is pressed, 0 if not. + */ +#define IS_JUST_PRESSED(dev, button) (IS_PRESSED(dev, button) && !IS_HELD(dev, button)) + +/** + * @brief Return the IR sensitivity level. + * @param wm Pointer to a wiimote_t structure. + * @param lvl [out] Pointer to an int that will hold the level setting. + * If no level is set 'lvl' will be set to 0. + */ +#define WIIUSE_GET_IR_SENSITIVITY(dev, lvl) \ + do { \ + if ((wm->state & 0x01000) == 0x01000) *lvl = 1; \ + else if ((wm->state & 0x02000) == 0x02000) *lvl = 2; \ + else if ((wm->state & 0x04000) == 0x04000) *lvl = 3; \ + else if ((wm->state & 0x08000) == 0x08000) *lvl = 4; \ + else if ((wm->state & 0x10000) == 0x10000) *lvl = 5; \ + else *lvl = 0; \ + } while (0) + +#define WIIUSE_USING_ACC(wm) ((wm->state & 0x00100) == 0x00100) +#define WIIUSE_USING_EXP(wm) ((wm->state & 0x00200) == 0x00200) +#define WIIUSE_USING_IR(wm) ((wm->state & 0x00400) == 0x00400) +#define WIIUSE_USING_SPEAKER(wm) ((wm->state & 0x00800) == 0x00800) + +#define WIIUSE_IS_LED_SET(wm, num) ((wm->leds & WIIMOTE_LED_##num) == WIIMOTE_LED_##num) + +/* + * Largest known payload is 21 bytes. + * Add 2 for the prefix and round up to a power of 2. + */ +#define MAX_PAYLOAD 32 + +/* + * This is left over from an old hack, but it may actually + * be a useful feature to keep so it wasn't removed. + */ +#ifdef WIN32 + #define WIIMOTE_DEFAULT_TIMEOUT 100 + #define WIIMOTE_EXP_TIMEOUT 100 +#endif + +typedef unsigned char ubyte; +typedef char sbyte; +typedef unsigned short uword; +typedef short sword; +typedef unsigned int uint; +typedef char sint; + + +struct wiimote_t; +struct vec3b_t; +struct orient_t; +struct gforce_t; + +#ifdef GEKKO + typedef void (*wii_event_cb)(struct wiimote_t*, s32 event); +#endif + +/** + * @brief Callback that handles a read event. + * + * @param wm Pointer to a wiimote_t structure. + * @param data Pointer to the filled data block. + * @param len Length in bytes of the data block. + * + * @see wiiuse_init() + * + * A registered function of this type is called automatically by the wiiuse + * library when the wiimote has returned the full data requested by a previous + * call to wiiuse_read_data(). + */ +typedef void (*wiiuse_data_cb)(struct wiimote_t* wm, ubyte* data, unsigned short len); + +typedef enum data_req_s +{ + REQ_READY = 0, + REQ_SENT, + REQ_DONE +} data_req_s; + +/** + * @struct data_req_t + * @brief Data read request structure. + */ +struct data_req_t { + lwp_node node; + ubyte data[48]; /**< buffer where read data is written */ + unsigned int len; + data_req_s state; /**< set to 1 if not using callback and needs to be cleaned up */ + wiiuse_data_cb cb; /**< read data callback */ + struct data_req_t *next; +}; + +typedef void (*cmd_blk_cb)(struct wiimote_t *wm,ubyte *data,uword len); + +typedef enum cmd_blk_s +{ + CMD_READY = 0, + CMD_SENT, + CMD_DONE +} cmd_blk_s; + +struct cmd_blk_t +{ + lwp_node node; + + ubyte data[48]; + uint len; + + cmd_blk_s state; + cmd_blk_cb cb; + + struct cmd_blk_t *next; +}; + + +/** + * @struct vec2b_t + * @brief Unsigned x,y byte vector. + */ +typedef struct vec2b_t { + ubyte x, y; +} vec2b_t; + + +/** +* @struct vec3b_t +* @brief Unsigned x,y,z byte vector. +*/ +typedef struct vec3b_t { + ubyte x, y, z; +} vec3b_t; + +/** +* @struct vec3b_t +* @brief Unsigned x,y,z byte vector. +*/ +typedef struct vec3w_t { + uword x, y, z; +} vec3w_t; + + +/** + * @struct vec3f_t + * @brief Signed x,y,z float struct. + */ +typedef struct vec3f_t { + float x, y, z; +} vec3f_t; + + +/** + * @struct orient_t + * @brief Orientation struct. + * + * Yaw, pitch, and roll range from -180 to 180 degrees. + */ +typedef struct orient_t { + float roll; /**< roll, this may be smoothed if enabled */ + float pitch; /**< pitch, this may be smoothed if enabled */ + float yaw; + + float a_roll; /**< absolute roll, unsmoothed */ + float a_pitch; /**< absolute pitch, unsmoothed */ +} orient_t; + + +/** + * @struct gforce_t + * @brief Gravity force struct. + */ +typedef struct gforce_t { + float x, y, z; +} gforce_t; + + +/** + * @struct accel_t + * @brief Accelerometer struct. For any device with an accelerometer. + */ +typedef struct accel_t { + struct vec3w_t cal_zero; /**< zero calibration */ + struct vec3w_t cal_g; /**< 1g difference around 0cal */ + + float st_roll; /**< last smoothed roll value */ + float st_pitch; /**< last smoothed roll pitch */ + float st_alpha; /**< alpha value for smoothing [0-1] */ +} accel_t; + + +/** + * @struct ir_dot_t + * @brief A single IR source. + */ +typedef struct ir_dot_t { + ubyte visible; /**< if the IR source is visible */ + + short rx; /**< raw X coordinate (0-1023) */ + short ry; /**< raw Y coordinate (0-767) */ + + ubyte size; /**< size of the IR dot (0-15) */ +} ir_dot_t; + + +typedef struct fdot_t { + float x,y; +} fdot_t; + +typedef struct sb_t { + fdot_t dots[2]; + fdot_t acc_dots[2]; + fdot_t rot_dots[2]; + float angle; + float off_angle; + float score; +} sb_t; + +/** + * @enum aspect_t + * @brief Screen aspect ratio. + */ +typedef enum aspect_t { + WIIUSE_ASPECT_4_3, + WIIUSE_ASPECT_16_9 +} aspect_t; + + +/** + * @struct ir_t + * @brief IR struct. Hold all data related to the IR tracking. + */ +typedef struct ir_t { + struct ir_dot_t dot[4]; /**< IR dots */ + ubyte num_dots; /**< number of dots at this time */ + + int state; /**< keeps track of the IR state */ + + int raw_valid; /**< is the raw position valid? */ + sb_t sensorbar; /**< sensor bar, detected or guessed */ + float ax; /**< raw X coordinate */ + float ay; /**< raw Y coordinate */ + float distance; /**< pixel width of the sensor bar */ + float z; /**< calculated distance in meters */ + float angle; /**< angle of the wiimote to the sensor bar*/ + + int smooth_valid; /**< is the smoothed position valid? */ + float sx; /**< smoothed X coordinate */ + float sy; /**< smoothed Y coordinate */ + float error_cnt; /**< error count, for smoothing algorithm*/ + float glitch_cnt; /**< glitch count, same */ + + int valid; /**< is the bounded position valid? */ + float x; /**< bounded X coordinate */ + float y; /**< bounded Y coordinate */ + enum aspect_t aspect; /**< aspect ratio of the screen */ + enum ir_position_t pos; /**< IR sensor bar position */ + unsigned int vres[2]; /**< IR virtual screen resolution */ + int offset[2]; /**< IR XY correction offset */ + +} ir_t; + + +/** + * @struct joystick_t + * @brief Joystick calibration structure. + * + * The angle \a ang is relative to the positive y-axis into quadrant I + * and ranges from 0 to 360 degrees. So if the joystick is held straight + * upwards then angle is 0 degrees. If it is held to the right it is 90, + * down is 180, and left is 270. + * + * The magnitude \a mag is the distance from the center to where the + * joystick is being held. The magnitude ranges from 0 to 1. + * If the joystick is only slightly tilted from the center the magnitude + * will be low, but if it is closer to the outter edge the value will + * be higher. + */ +typedef struct joystick_t { + struct vec2b_t max; /**< maximum joystick values */ + struct vec2b_t min; /**< minimum joystick values */ + struct vec2b_t center; /**< center joystick values */ + struct vec2b_t pos; /**< raw position values */ + + float ang; /**< angle the joystick is being held */ + float mag; /**< magnitude of the joystick (range 0-1) */ +} joystick_t; + + +/** + * @struct nunchuk_t + * @brief Nunchuk expansion device. + */ +typedef struct nunchuk_t { + struct accel_t accel_calib; /**< nunchuk accelerometer calibration */ + struct joystick_t js; /**< joystick calibration */ + + int* flags; /**< options flag (points to wiimote_t.flags) */ + + ubyte btns; /**< what buttons have just been pressed */ + ubyte btns_last; /**< what buttons have just been pressed */ + ubyte btns_held; /**< what buttons are being held down */ + ubyte btns_released; /**< what buttons were just released this */ + + struct vec3w_t accel; /**< current raw acceleration data */ + struct orient_t orient; /**< current orientation on each axis */ + struct gforce_t gforce; /**< current gravity forces on each axis */ +} nunchuk_t; + + +/** + * @struct classic_ctrl_t + * @brief Classic controller expansion device. + */ +typedef struct classic_ctrl_t { + short btns; /**< what buttons have just been pressed */ + short btns_last; /**< what buttons have just been pressed */ + short btns_held; /**< what buttons are being held down */ + short btns_released; /**< what buttons were just released this */ + + ubyte rs_raw; + ubyte ls_raw; + + float r_shoulder; /**< right shoulder button (range 0-1) */ + float l_shoulder; /**< left shoulder button (range 0-1) */ + + struct joystick_t ljs; /**< left joystick calibration */ + struct joystick_t rjs; /**< right joystick calibration */ + ubyte type; /**< original, pro, wiiu pro */ +} classic_ctrl_t; + + +/** + * @struct guitar_hero_3_t + * @brief Guitar Hero 3 expansion device. + */ +typedef struct guitar_hero_3_t { + short btns; /**< what buttons have just been pressed */ + short btns_last; /**< what buttons have just been pressed */ + short btns_held; /**< what buttons are being held down */ + short btns_released; /**< what buttons were just released this */ + + ubyte wb_raw; + float whammy_bar; /**< whammy bar (range 0-1) */ + + ubyte tb_raw; + int touch_bar; /**< touch bar */ + + struct joystick_t js; /**< joystick calibration */ +} guitar_hero_3_t; + +/** + * @struct wii_board_t + * @brief Wii Balance Board expansion device. + */ +typedef struct wii_board_t { + float tl; /* Interpolated */ + float tr; + float bl; + float br; /* End interp */ + short rtl; /* RAW */ + short rtr; + short rbl; + short rbr; /* /RAW */ + short ctl[3]; /* Calibration */ + short ctr[3]; + short cbl[3]; + short cbr[3]; /* /Calibration */ + float x; + float y; +} wii_board_t; + +typedef struct motion_plus_t +{ + short rx, ry, rz; + ubyte status; + ubyte ext; +} motion_plus_t; + +/** + * @struct expansion_t + * @brief Generic expansion device plugged into wiimote. + */ +typedef struct expansion_t { + int type; /**< type of expansion attached */ + + union { + struct nunchuk_t nunchuk; + struct classic_ctrl_t classic; + struct guitar_hero_3_t gh3; + struct wii_board_t wb; + struct motion_plus_t mp; + }; +} expansion_t; + + +/** + * @enum win32_bt_stack_t + * @brief Available bluetooth stacks for Windows. + */ +typedef enum win_bt_stack_t { + WIIUSE_STACK_UNKNOWN, + WIIUSE_STACK_MS, + WIIUSE_STACK_BLUESOLEIL +} win_bt_stack_t; + + +/** + * @struct wiimote_state_t + * @brief Significant data from the previous event. + */ +typedef struct wiimote_state_t { + unsigned short btns; + + struct ir_t ir; + struct vec3w_t accel; + struct expansion_t exp; +} wiimote_state_t; + + +/** + * @enum WIIUSE_EVENT_TYPE + * @brief Events that wiiuse can generate from a poll. + */ +typedef enum WIIUSE_EVENT_TYPE { + WIIUSE_NONE = 0, + WIIUSE_EVENT, + WIIUSE_STATUS, + WIIUSE_CONNECT, + WIIUSE_DISCONNECT, + WIIUSE_UNEXPECTED_DISCONNECT, + WIIUSE_READ_DATA, + WIIUSE_ACK, + WIIUSE_NUNCHUK_INSERTED, + WIIUSE_NUNCHUK_REMOVED, + WIIUSE_CLASSIC_CTRL_INSERTED, + WIIUSE_CLASSIC_CTRL_REMOVED, + WIIUSE_GUITAR_HERO_3_CTRL_INSERTED, + WIIUSE_GUITAR_HERO_3_CTRL_REMOVED, + WIIUSE_WII_BOARD_INSERTED, + WIIUSE_WII_BOARD_REMOVED, + WIIUSE_MOTION_PLUS_ACTIVATED, + WIIUSE_MOTION_PLUS_REMOVED +} WIIUSE_EVENT_TYPE; + +/** + * @struct wiimote_t + * @brief Wiimote structure. + */ +typedef struct wiimote_t { + WCONST int unid; /**< user specified id */ + + #if defined(_WIN32) + WCONST HANDLE dev_handle; /**< HID handle */ + WCONST OVERLAPPED hid_overlap; /**< overlap handle */ + WCONST enum win_bt_stack_t stack; /**< type of bluetooth stack to use */ + WCONST int timeout; /**< read timeout */ + WCONST ubyte normal_timeout; /**< normal timeout */ + WCONST ubyte exp_timeout; /**< timeout for expansion handshake */ + #elif defined(GEKKO) + WCONST lwp_queue cmdq; + WCONST struct bd_addr bdaddr; /**< bt address */ + WCONST char bdaddr_str[18]; /**< readable bt address */ + WCONST struct bte_pcb *sock; /**< output socket */ + WCONST wii_event_cb event_cb; /**< event callback */ + #elif defined(unix) + WCONST bdaddr_t bdaddr; /**< bt address */ + WCONST char bdaddr_str[18]; /**< readable bt address */ + WCONST int out_sock; /**< output socket */ + WCONST int in_sock; /**< input socket */ + #endif + + WCONST int state; /**< various state flags */ + WCONST ubyte leds; /**< currently lit leds */ +#ifdef GEKKO + WCONST ubyte battery_level; /**< battery level */ +#else + WCONST float battery_level; /**< battery level */ +#endif + + WCONST int flags; /**< options flag */ + + WCONST ubyte handshake_state; /**< the state of the connection handshake */ + WCONST ubyte expansion_state; /**< the state of the expansion handshake */ + + WCONST struct data_req_t* data_req; /**< list of data read requests */ + + WCONST struct cmd_blk_t *cmd_head; + WCONST struct cmd_blk_t *cmd_tail; + + WCONST struct accel_t accel_calib; /**< wiimote accelerometer calibration */ + WCONST struct expansion_t exp; /**< wiimote expansion device */ + + WCONST struct vec3w_t accel; /**< current raw acceleration data */ + WCONST struct orient_t orient; /**< current orientation on each axis */ + WCONST struct gforce_t gforce; /**< current gravity forces on each axis */ + + WCONST struct ir_t ir; /**< IR data */ + + WCONST unsigned short btns; /**< what buttons are down */ + WCONST unsigned short btns_last; /**< what buttons were down before */ + WCONST unsigned short btns_held; /**< what buttons are and were held down */ + WCONST unsigned short btns_released; /**< what buttons were just released */ + + WCONST struct wiimote_state_t lstate; /**< last saved state */ + + WCONST WIIUSE_EVENT_TYPE event; /**< type of event that occured */ + WCONST ubyte event_buf[MAX_PAYLOAD]; /**< event buffer */ + + WCONST ubyte motion_plus_id[6]; +} wiimote; + +#if defined(GEKKO) +/** + * @struct wiimote_listen_t + * @brief Wiimote listen structure. + */ +typedef struct wiimote_listen_t { + WCONST struct bd_addr bdaddr; + WCONST struct bte_pcb *sock; + WCONST struct wiimote_t *(*assign_cb)(struct bd_addr *bdaddr); + WCONST struct wiimote_t *wm; +} wiimote_listen; +#endif + +/***************************************** + * + * Include API specific stuff + * + *****************************************/ + +#ifdef _WIN32 + #define WIIUSE_EXPORT_DECL __declspec(dllexport) + #define WIIUSE_IMPORT_DECL __declspec(dllimport) +#else + #define WIIUSE_EXPORT_DECL + #define WIIUSE_IMPORT_DECL +#endif + +#ifdef WIIUSE_COMPILE_LIB + #define WIIUSE_EXPORT WIIUSE_EXPORT_DECL +#else + #define WIIUSE_EXPORT WIIUSE_IMPORT_DECL +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* wiiuse.c */ +WIIUSE_EXPORT extern const char* wiiuse_version(); + +#ifndef GEKKO +WIIUSE_EXPORT extern struct wiimote_t** wiiuse_init(int wiimotes); +#else +WIIUSE_EXPORT extern int wiiuse_register(struct wiimote_listen_t *wml, struct bd_addr *bdaddr, struct wiimote_t *(*assign_cb)(struct bd_addr *bdaddr)); +WIIUSE_EXPORT extern struct wiimote_t** wiiuse_init(int wiimotes, wii_event_cb event_cb); +WIIUSE_EXPORT extern void wiiuse_sensorbar_enable(int enable); +#endif + +WIIUSE_EXPORT extern void wiiuse_disconnected(struct wiimote_t* wm); +WIIUSE_EXPORT extern void wiiuse_cleanup(struct wiimote_t** wm, int wiimotes); +WIIUSE_EXPORT extern void wiiuse_rumble(struct wiimote_t* wm, int status); +WIIUSE_EXPORT extern void wiiuse_toggle_rumble(struct wiimote_t* wm); +WIIUSE_EXPORT extern void wiiuse_set_leds(struct wiimote_t* wm, int leds,cmd_blk_cb cb); +WIIUSE_EXPORT extern void wiiuse_motion_sensing(struct wiimote_t* wm, int status); +WIIUSE_EXPORT extern int wiiuse_read_data(struct wiimote_t* wm, ubyte* buffer, unsigned int offset, unsigned short len, cmd_blk_cb cb); +WIIUSE_EXPORT extern int wiiuse_write_data(struct wiimote_t *wm,unsigned int addr,ubyte *data,ubyte len,cmd_blk_cb cb); +WIIUSE_EXPORT extern void wiiuse_status(struct wiimote_t *wm,cmd_blk_cb cb); +WIIUSE_EXPORT extern struct wiimote_t* wiiuse_get_by_id(struct wiimote_t** wm, int wiimotes, int unid); +WIIUSE_EXPORT extern int wiiuse_set_flags(struct wiimote_t* wm, int enable, int disable); +WIIUSE_EXPORT extern float wiiuse_set_smooth_alpha(struct wiimote_t* wm, float alpha); +WIIUSE_EXPORT extern void wiiuse_set_bluetooth_stack(struct wiimote_t** wm, int wiimotes, enum win_bt_stack_t type); +WIIUSE_EXPORT extern void wiiuse_resync(struct wiimote_t* wm); +WIIUSE_EXPORT extern void wiiuse_set_timeout(struct wiimote_t** wm, int wiimotes, ubyte normal_timeout, ubyte exp_timeout); +WIIUSE_EXPORT extern int wiiuse_write_streamdata(struct wiimote_t *wm,ubyte *data,ubyte len,cmd_blk_cb cb); + +/* connect.c */ +WIIUSE_EXPORT extern int wiiuse_find(struct wiimote_t** wm, int max_wiimotes, int timeout); +WIIUSE_EXPORT extern int wiiuse_connect(struct wiimote_t** wm, int wiimotes); +WIIUSE_EXPORT extern void wiiuse_disconnect(struct wiimote_t* wm); + +/* events.c */ +WIIUSE_EXPORT extern int wiiuse_poll(struct wiimote_t** wm, int wiimotes); + +/* ir.c */ +WIIUSE_EXPORT extern void wiiuse_set_ir_mode(struct wiimote_t *wm); +WIIUSE_EXPORT extern void wiiuse_set_ir(struct wiimote_t* wm, int status); +WIIUSE_EXPORT extern void wiiuse_set_ir_vres(struct wiimote_t* wm, unsigned int x, unsigned int y); +WIIUSE_EXPORT extern void wiiuse_set_ir_position(struct wiimote_t* wm, enum ir_position_t pos); +WIIUSE_EXPORT extern void wiiuse_set_aspect_ratio(struct wiimote_t* wm, enum aspect_t aspect); +WIIUSE_EXPORT extern void wiiuse_set_ir_sensitivity(struct wiimote_t* wm, int level); + +/* motion_plus.c */ +WIIUSE_EXPORT extern void wiiuse_set_motion_plus(struct wiimote_t *wm, int status); + +/* speaker.c */ +WIIUSE_EXPORT extern void wiiuse_set_speaker(struct wiimote_t *wm, int status); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/external/libogc_ir/upstream/wiiuse_internal.h b/external/libogc_ir/upstream/wiiuse_internal.h new file mode 100644 index 0000000..ade44da --- /dev/null +++ b/external/libogc_ir/upstream/wiiuse_internal.h @@ -0,0 +1,277 @@ +/* + * wiiuse + * + * Written By: + * Michael Laforest < para > + * Email: < thepara (--AT--) g m a i l [--DOT--] com > + * + * Copyright 2006-2007 + * + * This file is part of wiiuse. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * $Header: /lvm/shared/ds/ds/cvs/devkitpro-cvsbackup/libogc/wiiuse/wiiuse_internal.h,v 1.8 2008-12-10 16:16:40 shagkur Exp $ + * + */ + +/** + * @file + * @brief General internal wiiuse stuff. + * + * Since Wiiuse is a library, wiiuse.h is a duplicate + * of the API header. + * + * The code that would normally go in that file, but + * which is not needed by third party developers, + * is put here. + * + * So wiiuse_internal.h is included by other files + * internally, wiiuse.h is included only here. + */ + +#ifndef WIIUSE_INTERNAL_H_INCLUDED +#define WIIUSE_INTERNAL_H_INCLUDED + +#if defined(__linux__) + #include /* htons() */ + #include +#endif + +#include "definitions.h" + +/* wiiuse version */ +#define WIIUSE_VERSION "0.12" + +/******************** + * + * Wiimote internal codes + * + ********************/ + +/* Communication channels */ +#define WM_OUTPUT_CHANNEL 0x11 +#define WM_INPUT_CHANNEL 0x13 + +#define WM_SET_REPORT 0x50 +#define WM_DATA 0xA0 + +/* commands */ +#define WM_CMD_RUMBLE 0x10 +#define WM_CMD_LED 0x11 +#define WM_CMD_REPORT_TYPE 0x12 +#define WM_CMD_IR 0x13 +#define WM_CMD_SPEAKER_ENABLE 0x14 +#define WM_CMD_CTRL_STATUS 0x15 +#define WM_CMD_WRITE_DATA 0x16 +#define WM_CMD_READ_DATA 0x17 +#define WM_CMD_STREAM_DATA 0x18 +#define WM_CMD_SPEAKER_MUTE 0x19 +#define WM_CMD_IR_2 0x1A + +/* input report ids */ +#define WM_RPT_CTRL_STATUS 0x20 +#define WM_RPT_READ 0x21 +#define WM_RPT_ACK 0x22 +#define WM_RPT_BTN 0x30 +#define WM_RPT_BTN_ACC 0x31 +#define WM_RPT_BTN_ACC_IR 0x33 +#define WM_RPT_BTN_EXP 0x34 +#define WM_RPT_BTN_ACC_EXP 0x35 +#define WM_RPT_BTN_IR_EXP 0x36 +#define WM_RPT_BTN_ACC_IR_EXP 0x37 + +#define WM_BT_INPUT 0x01 +#define WM_BT_OUTPUT 0x02 + +/* Identify the wiimote device by its class */ +#define WM_DEV_CLASS_0 0x04 +#define WM_DEV_CLASS_1 0x25 +#define WM_DEV_CLASS_2 0x00 +#define WM_VENDOR_ID 0x057E +#define WM_PRODUCT_ID 0x0306 + +/* controller status stuff */ +#define WM_MAX_BATTERY_CODE 0xC8 + +/* offsets in wiimote memory */ +#define WM_MEM_OFFSET_CALIBRATION 0x16 +#define WM_EXP_MEM_BASE 0x04A40000 +#define WM_EXP_MEM_ENABLE1 0x04A400F0 +#define WM_EXP_MEM_ENABLE2 0x04A400FB +#define WM_EXP_MEM_KEY 0x04A40040 +#define WM_EXP_MEM_CALIBR 0x04A40020 +#define WM_EXP_MOTION_PLUS_ENABLE 0x04A600FE +#define WM_EXP_ID 0x04A400FA + +#define WM_REG_IR 0x04B00030 +#define WM_REG_IR_BLOCK1 0x04B00000 +#define WM_REG_IR_BLOCK2 0x04B0001A +#define WM_REG_IR_MODENUM 0x04B00033 + +#define WM_REG_SPEAKER_REG1 0x04A20001 +#define WM_REG_SPEAKER_REG2 0x04A20008 +#define WM_REG_SPEAKER_REG3 0x04A20009 +#define WM_REG_SPEAKER_BLOCK 0x04A20001 + +/* ir block data */ +#define WM_IR_BLOCK1_LEVEL1 "\x02\x00\x00\x71\x01\x00\x64\x00\xfe" +#define WM_IR_BLOCK2_LEVEL1 "\xfd\x05" +#define WM_IR_BLOCK1_LEVEL2 "\x02\x00\x00\x71\x01\x00\x96\x00\xb4" +#define WM_IR_BLOCK2_LEVEL2 "\xb3\x04" +#define WM_IR_BLOCK1_LEVEL3 "\x02\x00\x00\x71\x01\x00\xaa\x00\x64" +#define WM_IR_BLOCK2_LEVEL3 "\x63\x03" +#define WM_IR_BLOCK1_LEVEL4 "\x02\x00\x00\x71\x01\x00\xc8\x00\x36" +#define WM_IR_BLOCK2_LEVEL4 "\x35\x03" +#define WM_IR_BLOCK1_LEVEL5 "\x07\x00\x00\x71\x01\x00\x72\x00\x20" +#define WM_IR_BLOCK2_LEVEL5 "\x1f\x03" + +#define WM_IR_TYPE_BASIC 0x01 +#define WM_IR_TYPE_EXTENDED 0x03 +#define WM_IR_TYPE_FULL 0x05 + +/* controller status flags for the first message byte */ +/* bit 1 is unknown */ +#define WM_CTRL_STATUS_BYTE1_ATTACHMENT 0x02 +#define WM_CTRL_STATUS_BYTE1_SPEAKER_ENABLED 0x04 +#define WM_CTRL_STATUS_BYTE1_IR_ENABLED 0x08 +#define WM_CTRL_STATUS_BYTE1_LED_1 0x10 +#define WM_CTRL_STATUS_BYTE1_LED_2 0x20 +#define WM_CTRL_STATUS_BYTE1_LED_3 0x40 +#define WM_CTRL_STATUS_BYTE1_LED_4 0x80 + +/* aspect ratio */ +#define WM_ASPECT_16_9_X 660 +#define WM_ASPECT_16_9_Y 370 +#define WM_ASPECT_4_3_X 560 +#define WM_ASPECT_4_3_Y 420 + + +/** + * Expansion stuff + */ + +/* encrypted expansion id codes (located at 0x04A400FC) */ +#define EXP_ID_CODE_NUNCHUK 0xa4200000 +#define EXP_ID_CODE_CLASSIC_CONTROLLER 0xa4200101 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_NYKOWING 0x90908f00 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_NYKOWING2 0x9e9f9c00 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_NYKOWING3 0x908f8f00 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_GENERIC 0xa5a2a300 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_GENERIC2 0x98999900 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_GENERIC3 0xa0a1a000 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_GENERIC4 0x8d8d8e00 +#define EXP_ID_CODE_CLASSIC_CONTROLLER_GENERIC5 0x93949400 +#define EXP_ID_CODE_CLASSIC_WIIU_PRO 0xa4200120 +#define EXP_ID_CODE_GUITAR 0xa4200103 +#define EXP_ID_CODE_WIIBOARD 0xa4200402 +#define EXP_ID_CODE_MOTION_PLUS 0xa4200405 + +#define EXP_HANDSHAKE_LEN 224 + +/******************** + * + * End Wiimote internal codes + * + ********************/ + +/* wiimote state flags - (some duplicated in wiiuse.h)*/ +#define WIIMOTE_STATE_DEV_FOUND 0x00001 +//#define WIIMOTE_STATE_DEV_REGISTER 0x00002 +#define WIIMOTE_STATE_HANDSHAKE 0x00004 /* actual connection exists but no handshake yet */ +#define WIIMOTE_STATE_HANDSHAKE_COMPLETE 0x00008 /* actual connection exists but no handshake yet */ +#define WIIMOTE_STATE_CONNECTED 0x00010 +#define WIIMOTE_STATE_EXP_HANDSHAKE 0x00020 /* actual connection exists but no handshake yet */ +#define WIIMOTE_STATE_EXP_FAILED 0x00040 /* actual connection exists but no handshake yet */ +#define WIIMOTE_STATE_RUMBLE 0x00080 +#define WIIMOTE_STATE_ACC 0x00100 +#define WIIMOTE_STATE_EXP 0x00200 +#define WIIMOTE_STATE_IR 0x00400 +#define WIIMOTE_STATE_SPEAKER 0x00800 +#define WIIMOTE_STATE_IR_SENS_LVL1 0x01000 +#define WIIMOTE_STATE_IR_SENS_LVL2 0x02000 +#define WIIMOTE_STATE_IR_SENS_LVL3 0x04000 +#define WIIMOTE_STATE_IR_SENS_LVL4 0x08000 +#define WIIMOTE_STATE_IR_SENS_LVL5 0x10000 +#define WIIMOTE_STATE_IR_INIT 0x20000 +#define WIIMOTE_STATE_SPEAKER_INIT 0x40000 +#define WIIMOTE_STATE_WIIU_PRO 0x80000 + +#define WIIMOTE_INIT_STATES (WIIMOTE_STATE_IR_SENS_LVL3) + +/* macro to manage states */ +#define WIIMOTE_IS_SET(wm, s) ((wm->state & (s)) == (s)) +#define WIIMOTE_ENABLE_STATE(wm, s) (wm->state |= (s)) +#define WIIMOTE_DISABLE_STATE(wm, s) (wm->state &= ~(s)) +#define WIIMOTE_TOGGLE_STATE(wm, s) ((wm->state & (s)) ? WIIMOTE_DISABLE_STATE(wm, s) : WIIMOTE_ENABLE_STATE(wm, s)) + +#define WIIMOTE_IS_FLAG_SET(wm, s) ((wm->flags & (s)) == (s)) +#define WIIMOTE_ENABLE_FLAG(wm, s) (wm->flags |= (s)) +#define WIIMOTE_DISABLE_FLAG(wm, s) (wm->flags &= ~(s)) +#define WIIMOTE_TOGGLE_FLAG(wm, s) ((wm->flags & (s)) ? WIIMOTE_DISABLE_FLAG(wm, s) : WIIMOTE_ENABLE_FLAG(wm, s)) + +#define NUNCHUK_IS_FLAG_SET(wm, s) ((*(wm->flags) & (s)) == (s)) + +/* misc macros */ +#define WIIMOTE_ID(wm) (wm->unid) +#define WIIMOTE_IS_CONNECTED(wm) (WIIMOTE_IS_SET(wm, WIIMOTE_STATE_CONNECTED)) + +/* + * Smooth tilt calculations are computed with the + * exponential moving average formula: + * St = St_last + (alpha * (tilt - St_last)) + * alpha is between 0 and 1 + */ +#define WIIUSE_DEFAULT_SMOOTH_ALPHA 0.3f + +#define SMOOTH_ROLL 0x01 +#define SMOOTH_PITCH 0x02 + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct op_t +{ + ubyte cmd; + union { + struct { + uint addr; + uword size; + } readdata; + struct { + uint addr; + ubyte size; + ubyte data[16]; + } writedata; + ubyte __data[MAX_PAYLOAD]; + }; + + void *buffer; + int wait; +} __attribute__((packed)); + +/* not part of the api */ +void wiiuse_init_cmd_queue(struct wiimote_t *wm); +void wiiuse_send_next_command(struct wiimote_t *wm); +int wiiuse_set_report_type(struct wiimote_t* wm,cmd_blk_cb cb); +int wiiuse_sendcmd(struct wiimote_t *wm,ubyte report_type,ubyte *msg,int len,cmd_blk_cb cb); + +#ifdef __cplusplus +} +#endif + +#endif /* WIIUSE_INTERNAL_H_INCLUDED */ diff --git a/patches/bluepad32-sdl3-imu.patch b/patches/bluepad32-sdl3-imu.patch index 7287292..db7f137 100644 --- a/patches/bluepad32-sdl3-imu.patch +++ b/patches/bluepad32-sdl3-imu.patch @@ -1262,13 +1262,19 @@ diff --git a/src/components/bluepad32/include/parser/uni_hid_parser_wii.h b/src/ @@ -8,1 +8,2 @@ +#include #include -@@ -46,3 +47,11 @@ +@@ -46,3 +47,17 @@ void uni_hid_parser_wii_request_report_type(struct uni_hid_device_s* d, wii_report_type_t report_type); + +// Calibrated physical acceleration, independent of gyro/IR output selection. +// Sequence advances only on a fresh accelerometer report, never status/acks. +bool uni_hid_parser_wii_accel_snapshot(struct uni_hid_device_s* d, + int32_t accel[3], uint32_t* sequence); ++// Independent calibrated MotionPlus stream; status/ACK/Nunchuk never advance it. ++bool uni_hid_parser_wii_gyro_snapshot(struct uni_hid_device_s* d, ++ int32_t gyro[3], uint32_t* sequence); ++void uni_hid_parser_wii_teardown(struct uni_hid_device_s* d); ++// The void rumble hook ignores commands during topology setup. ++bool uni_hid_parser_wii_rumble_ready(struct uni_hid_device_s* d); +// Independent Nunchuk stream; never includes interleaved MotionPlus samples. +bool uni_hid_parser_wii_nunchuk_accel_snapshot(struct uni_hid_device_s* d, + int32_t accel[3], uint32_t* sequence); @@ -1346,7 +1352,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen wii_mode_t mode; /* horizontal, accel, vertical, rumble, etc.. */ enum wii_devtype dev_type; enum wii_exttype ext_type; -@@ -159,6 +167,36 @@ +@@ -159,6 +167,39 @@ uint16_t rumble_duration_ms; balance_board_calibration_t balance_board_calibration; @@ -1354,13 +1360,15 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen + uint16_t read_address; + uint8_t read_size; + uint8_t report_type; -+ bool motion_setup_done; -+ bool accel_calibrated; -+ bool mp_calibrated; -+ bool mp_active; -+ bool ready; -+ bool ext_connected; -+ bool topology_pending; ++ // Keep all independent validity flags within the fixed 256-byte instance. ++ bool motion_setup_done : 1; ++ bool accel_calibrated : 1; ++ bool mp_calibrated : 1; ++ bool mp_active : 1; ++ bool ready : 1; ++ bool ext_connected : 1; ++ bool topology_pending : 1; ++ bool gyro_valid : 1; + uint8_t ext_retries; + uint16_t accel_zero[3]; + uint16_t accel_span[3]; @@ -1369,6 +1377,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen + int32_t accel[3]; + uint32_t accel_sequence; + int32_t gyro[3]; ++ uint32_t gyro_sequence; + int16_t nunchuk_x; + int16_t nunchuk_y; + uint16_t nunchuk_buttons; @@ -1383,7 +1392,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen // Debug only int debug_fd; // File descriptor where dump is saved -@@ -177,7 +215,6 @@ +@@ -177,7 +218,6 @@ static void process_drm_kae(uni_hid_device_t* d, const uint8_t* report, uint16_t len); static void process_drm_kee(uni_hid_device_t* d, const uint8_t* report, uint16_t len); static void process_drm_e(uni_hid_device_t* d, const uint8_t* report, uint16_t len); @@ -1391,7 +1400,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen static udraw_tablet_t process_udraw_tablet(const uint8_t* e, uint16_t len); static balance_board_t process_balance_board(uni_hid_device_t* d, const uint8_t* e, uint16_t len); -@@ -196,6 +233,43 @@ +@@ -196,6 +236,43 @@ static void on_wii_set_rumble_on(btstack_timer_source_t* ts); static void on_wii_set_rumble_off(btstack_timer_source_t* ts); static void wii_play_dual_rumble_now(struct uni_hid_device_s* d, uint16_t duration_ms); @@ -1435,7 +1444,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen // Constants static const char* wii_devtype_names[] = { -@@ -217,124 +291,447 @@ +@@ -217,124 +294,450 @@ // process_ functions @@ -1487,6 +1496,8 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen + // A400F0 unmaps an active MP and exposes its downstream extension. + // Do not decode in-flight extension bytes until the new topology is ready. + ins->mp_active = false; ++ ins->gyro_valid = false; ++ ins->mp_calibrated = false; + wii_fsm_ext_init(d); +} + @@ -1509,6 +1520,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen +static void wii_confirm_topology(uni_hid_device_t* d) { + wii_instance_t* ins = get_wii_instance(d); + if (!ins->mp_active) { ++ ins->gyro_valid = false; + memset(ins->gyro, 0, sizeof(ins->gyro)); + memset(d->controller.gamepad.gyro, 0, sizeof(d->controller.gamepad.gyro)); + } @@ -1571,7 +1583,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen +static void wii_ir_complete(uni_hid_device_t* d, wii_ir_t* ir) { + ir->initialized = !ir->failed; + if (ir->initialized) -+ logi("Wii: IR camera ready, mode %u\n", ir->mode); ++ logi("Wii: IR camera ready, mode %u sensitivity %u\n", ir->mode, SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL); + wii_instance_t* ins = get_wii_instance(d); + // A physical extension can change while the camera owns the write FSM. + // Reconcile after the last ACK, without competing memory transactions. @@ -1618,10 +1630,10 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen + }; + uni_hid_device_send_intr_report(d, report, sizeof(report)); + } else { -+ // WiiBrew sensitivity level 3. Write every byte separately, with at ++ // Standard Wii sensitivity preset. Write every byte separately, with at + // least 50 ms after each ACK, including both camera-enable commands. -+ static const uint8_t sensitivity1[] = {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64}; -+ static const uint8_t sensitivity2[] = {0x63, 0x03}; ++ static const uint8_t sensitivity1[] = {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL == 2 ? 0x96 : 0xaa, 0x00, SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL == 2 ? 0xb4 : 0x64}; ++ static const uint8_t sensitivity2[] = {SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL == 2 ? 0xb3 : 0x63, SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL == 2 ? 0x04 : 0x03}; + uint32_t address = 0xb00030; + uint8_t value = 0x08; + if (ir->step >= WII_IR_SENSITIVITY1 && ir->step < WII_IR_SENSITIVITY2) { @@ -1993,7 +2005,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } static void process_req_data_read_calibration_data(uni_hid_device_t* d, const uint8_t* report, uint16_t len) { -@@ -444,17 +841,90 @@ +@@ -444,17 +847,90 @@ // Defined here: http://wiibrew.org/wiki/Wiimote#0x21:_Read_Memory_Data static void process_req_data(uni_hid_device_t* d, const uint8_t* report, uint16_t len) { @@ -2091,7 +2103,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen case WII_FSM_BALANCE_BOARD_DID_READ_CALIBRATION: process_req_data_read_calibration_data(d, report, len); break; -@@ -465,7 +935,6 @@ +@@ -465,7 +941,6 @@ process_req_data_dump_eeprom(d, report, len); break; default: @@ -2099,7 +2111,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen break; } } -@@ -473,29 +942,44 @@ +@@ -473,29 +948,44 @@ // Defined here: // http://wiibrew.org/wiki/Wiimote#0x22:_Acknowledge_output_report.2C_return_function_result static void process_req_return(uni_hid_device_t* d, const uint8_t* report, uint16_t len) { @@ -2167,7 +2179,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } } -@@ -514,15 +998,26 @@ +@@ -514,15 +1004,26 @@ const uint8_t* data = &report[1]; wii_instance_t* ins = get_wii_instance(d); @@ -2203,7 +2215,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } // Process misc buttons ctl->gamepad.misc_buttons |= (data[1] & 0x80) ? MISC_BUTTON_SYSTEM : 0; // Button "home" -@@ -563,46 +1058,144 @@ +@@ -563,46 +1064,160 @@ // Used for WiiMote in Accelerometer Mode. Defined here: // http://wiibrew.org/wiki/Wiimote#0x31:_Core_Buttons_and_Accelerometer static void process_drm_ka(uni_hid_device_t* d, const uint8_t* report, uint16_t len) { @@ -2279,6 +2291,19 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen + return true; +} + ++bool uni_hid_parser_wii_gyro_snapshot(uni_hid_device_t* d, ++ int32_t gyro[3], uint32_t* sequence) { ++ if (!d || !gyro || !sequence || d->report_parser.setup != uni_hid_parser_wii_setup) ++ return false; ++ wii_instance_t* ins = get_wii_instance(d); ++ if (!ins->mp_active || !ins->mp_calibrated || !ins->gyro_valid) ++ return false; ++ for (int i = 0; i < 3; ++i) ++ gyro[i] = ins->gyro[i]; ++ *sequence = ins->gyro_sequence; ++ return true; ++} ++ +bool uni_hid_parser_wii_nunchuk_accel_snapshot(uni_hid_device_t* d, + int32_t accel[3], uint32_t* sequence) { + if (!d || !accel || !sequence || d->report_parser.setup != uni_hid_parser_wii_setup) @@ -2381,6 +2406,9 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen + ins->gyro[0] = wii_calibrate_gyro(ins, 2, pitch, e[3] & 1); + ins->gyro[1] = -wii_calibrate_gyro(ins, 0, yaw, e[3] & 2); + ins->gyro[2] = wii_calibrate_gyro(ins, 1, roll, e[4] & 2); ++ if (++ins->gyro_sequence == 0) ++ ++ins->gyro_sequence; ++ ins->gyro_valid = true; + for (int i = 0; i < 3; i++) + d->controller.gamepad.gyro[i] = ins->gyro[i]; + if (ins->topology_pending && ins->state == WII_FSM_LED_UPDATED) @@ -2388,7 +2416,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } // Used in WiiMote + Nunchuk Mode -@@ -617,31 +1210,17 @@ +@@ -617,31 +1232,17 @@ } wii_instance_t* ins = get_wii_instance(d); @@ -2428,7 +2456,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen // Better if uDraw reports its own "type", but for the moment // it gets reported and the 2nd half of a gamepad. -@@ -668,59 +1247,59 @@ +@@ -668,59 +1269,59 @@ ctl->gamepad.buttons |= n.button_lower ? BUTTON_Y : 0; } @@ -2536,7 +2564,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen static udraw_tablet_t process_udraw_tablet(const uint8_t* e, uint16_t len) { // uDraw Tablet format here: -@@ -1002,52 +1581,18 @@ +@@ -1002,52 +1603,18 @@ logi("fsm: req_status\n"); wii_instance_t* ins = get_wii_instance(d); ins->state = WII_FSM_DID_REQ_STATUS; @@ -2594,7 +2622,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } static void wii_fsm_ext_read_register(uni_hid_device_t* d) { -@@ -1055,8 +1600,7 @@ +@@ -1055,8 +1622,7 @@ wii_instance_t* ins = get_wii_instance(d); ins->state = WII_FSM_EXT_DID_READ_REGISTER; @@ -2604,7 +2632,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen uint16_t bytes_to_read = 6; wii_read_mem(d, WII_READ_FROM_REGISTERS, offset, bytes_to_read); } -@@ -1066,8 +1610,7 @@ +@@ -1066,8 +1632,7 @@ wii_instance_t* ins = get_wii_instance(d); ins->state = WII_FSM_BALANCE_BOARD_DID_READ_CALIBRATION; @@ -2614,7 +2642,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen uint16_t bytes_to_read = 16; wii_read_mem(d, WII_READ_FROM_REGISTERS, offset, bytes_to_read); } -@@ -1077,8 +1620,7 @@ +@@ -1077,8 +1642,7 @@ wii_instance_t* ins = get_wii_instance(d); ins->state = WII_FSM_BALANCE_BOARD_DID_READ_CALIBRATION2; @@ -2624,7 +2652,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen uint16_t bytes_to_read = 8; wii_read_mem(d, WII_READ_FROM_REGISTERS, offset, bytes_to_read); } -@@ -1086,6 +1628,10 @@ +@@ -1086,6 +1650,10 @@ static void wii_fsm_assign_device(uni_hid_device_t* d) { logi("fsm: assign_device\n"); wii_instance_t* ins = get_wii_instance(d); @@ -2635,7 +2663,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen uint8_t dev = ins->dev_type; switch (dev) { case WII_DEVTYPE_UNK: -@@ -1100,18 +1646,8 @@ +@@ -1100,18 +1668,8 @@ } uint8_t report_type = 0xff; if (ins->ext_type == WII_EXT_NUNCHUK) { @@ -2656,7 +2684,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } else if (ins->ext_type == WII_EXT_CLASSIC_CONTROLLER) { logi("Wii: requesting E (Classic Controller)\n"); d->controller_subtype = CONTROLLER_SUBTYPE_WII_CLASSIC; -@@ -1125,21 +1661,17 @@ +@@ -1125,21 +1683,17 @@ d->controller_subtype = CONTROLLER_SUBTYPE_WIIMOTE_UDRAW_TABLET; report_type = WII_REPORT_TYPE_KE; } else { @@ -2688,7 +2716,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen uni_hid_parser_wii_request_report_type(d, report_type); break; } -@@ -1164,7 +1696,10 @@ +@@ -1164,7 +1718,10 @@ ins->state = WII_FSM_LED_UPDATED; wii_process_fsm(d); @@ -2700,7 +2728,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } static void wii_fsm_dump_eeprom(struct uni_hid_device_s* d) { -@@ -1218,7 +1753,15 @@ +@@ -1218,7 +1775,15 @@ // Do nothing break; case WII_FSM_DEV_GUESSED: @@ -2717,7 +2745,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen break; case WII_FSM_BALANCE_BOARD_READ_CALIBRATION: wii_fsm_balance_board_read_calibration(d); -@@ -1234,6 +1777,19 @@ +@@ -1234,6 +1799,19 @@ wii_fsm_update_led(d); break; case WII_FSM_LED_UPDATED: @@ -2737,7 +2765,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen break; default: loge("Wii: wii_process_fsm() unexpected state: %d\n", ins->state); -@@ -1249,10 +1805,10 @@ +@@ -1249,10 +1827,10 @@ ins->mode = WII_MODE_HORIZONTAL; ins->state = WII_FSM_SETUP; @@ -2752,9 +2780,35 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen // Dump EEPROM #if ENABLE_EEPROM_DUMP -@@ -1267,13 +1823,18 @@ +@@ -1267,13 +1845,44 @@ } ++void uni_hid_parser_wii_teardown(uni_hid_device_t* d) { ++ if (!d || d->report_parser.setup != uni_hid_parser_wii_setup) ++ return; ++ wii_instance_t* ins = get_wii_instance(d); ++ ins->gyro_valid = false; ++ ins->mp_active = false; ++ ins->mp_calibrated = false; ++ memset(ins->gyro, 0, sizeof(ins->gyro)); ++ memset(d->controller.gamepad.gyro, 0, sizeof(d->controller.gamepad.gyro)); ++ btstack_run_loop_remove_timer(&ins->rumble_timer_delayed_start); ++ btstack_run_loop_remove_timer(&ins->rumble_timer_duration); ++ ins->rumble_state = WII_STATE_RUMBLE_DISABLED; ++ ins->ready = false; ++#if SWITCH_PICO_WII_IR ++ wii_ir_invalidate(d); ++#endif ++} ++ ++bool uni_hid_parser_wii_rumble_ready(uni_hid_device_t* d) { ++ if (!d || d->report_parser.setup != uni_hid_parser_wii_setup) ++ return false; ++ wii_instance_t* ins = get_wii_instance(d); ++ return d->conn.connected && d->conn.interrupt_cid != 0 && ++ ins->ready && ins->state >= WII_FSM_LED_UPDATED; ++} ++ void uni_hid_parser_wii_init_report(uni_hid_device_t* d) { - // Reset old state. Each report contains a full-state. + wii_instance_t* ins = get_wii_instance(d); @@ -2773,7 +2827,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen return; switch (report[0]) { case WIIPROTO_REQ_STATUS: -@@ -1291,6 +1852,14 @@ +@@ -1291,6 +1900,14 @@ case WII_REPORT_TYPE_KAE: process_drm_kae(d, report, len); break; @@ -2788,7 +2842,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen case WII_REPORT_TYPE_KEE: process_drm_kee(d, report, len); break; -@@ -1307,6 +1876,9 @@ +@@ -1307,6 +1924,9 @@ logi("Wii parser: unknown report type: 0x%02x\n", report[0]); printf_hexdump(report, len); } @@ -2798,7 +2852,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen } void uni_hid_parser_wii_set_player_leds(uni_hid_device_t* d, uint8_t leds) { -@@ -1371,29 +1943,25 @@ +@@ -1371,29 +1991,25 @@ void uni_hid_parser_wii_set_mode(uni_hid_device_t* d, wii_mode_t mode) { wii_instance_t* ins = get_wii_instance(d); @@ -2843,7 +2897,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen uni_hid_device_send_intr_report(d, report, sizeof(report)); } -@@ -1480,10 +2048,13 @@ +@@ -1480,10 +2096,13 @@ static void wii_read_mem(uni_hid_device_t* d, wii_read_type_t t, uint32_t offset, uint16_t size) { logi("****** read_mem: offset=0x%04x, size=%d from=%d\n", offset, size, t); @@ -2858,7 +2912,7 @@ diff --git a/src/components/bluepad32/parser/uni_hid_parser_wii.c b/src/componen (offset & 0xff0000) >> 16, (offset & 0xff00) >> 8, (offset & 0xff), // Offset (size & 0xff00) >> 8, (size & 0xff), // Size in bytes // clang-format on -@@ -1491,6 +2062,15 @@ +@@ -1491,6 +2110,15 @@ uni_hid_device_send_intr_report(d, report, sizeof(report)); } @@ -2885,7 +2939,7 @@ diff --git a/src/components/bluepad32/uni_hid_device.c b/src/components/bluepad3 #include "parser/uni_hid_parser_wii.h" #include "parser/uni_hid_parser_xboxone.h" #include "platform/uni_platform.h" -@@ -447,6 +448,11 @@ +@@ -447,6 +448,13 @@ return; } @@ -2893,11 +2947,13 @@ diff --git a/src/components/bluepad32/uni_hid_device.c b/src/components/bluepad3 + uni_hid_parser_switch_teardown(d); + if (uni_hid_parser_switch2_is_ble_device(d)) + uni_hid_parser_switch2_teardown(d); ++ if (d->report_parser.setup == uni_hid_parser_wii_setup) ++ uni_hid_parser_wii_teardown(d); + // Disconnect child first if (d->child) uni_hid_device_disconnect(d->child); -@@ -465,9 +471,9 @@ +@@ -465,9 +473,9 @@ // Cleanup if (!uni_hid_device_is_virtual_device(d)) { type = gap_get_connection_type(d->conn.handle); @@ -2909,7 +2965,7 @@ diff --git a/src/components/bluepad32/uni_hid_device.c b/src/components/bluepad3 uni_bt_bredr_disconnect(d); else loge("uni_hid_device_disconnect: Unknown GAP connection type: %d\n", type); -@@ -490,6 +496,11 @@ +@@ -490,6 +498,13 @@ loge("uni_hid_device_delete: invalid hid device: NULL\n"); return; } @@ -2917,11 +2973,13 @@ diff --git a/src/components/bluepad32/uni_hid_device.c b/src/components/bluepad3 + uni_hid_parser_switch_teardown(d); + if (uni_hid_parser_switch2_is_ble_device(d)) + uni_hid_parser_switch2_teardown(d); ++ if (d->report_parser.setup == uni_hid_parser_wii_setup) ++ uni_hid_parser_wii_teardown(d); + // Delete child first if (d->child) -@@ -655,6 +666,7 @@ +@@ -655,6 +670,7 @@ d->report_parser.setup = uni_hid_parser_psmove_setup; d->report_parser.init_report = uni_hid_parser_psmove_init_report; d->report_parser.parse_input_report = uni_hid_parser_psmove_parse_input_report; @@ -2929,7 +2987,7 @@ diff --git a/src/components/bluepad32/uni_hid_device.c b/src/components/bluepad3 d->report_parser.set_lightbar_color = uni_hid_parser_psmove_set_lightbar_color; d->report_parser.play_dual_rumble = uni_hid_parser_psmove_play_dual_rumble; logi("Device detected as PS Move: 0x%02x\n", type); -@@ -718,6 +730,15 @@ +@@ -718,6 +734,15 @@ d->report_parser.device_dump = uni_hid_parser_switch_device_dump; logi("Device detected as Nintendo Switch Pro controller: 0x%02x\n", type); break; @@ -2945,7 +3003,7 @@ diff --git a/src/components/bluepad32/uni_hid_device.c b/src/components/bluepad3 case CONTROLLER_TYPE_SteamController: d->report_parser.setup = uni_hid_parser_steam_setup; d->report_parser.init_report = uni_hid_parser_steam_init_report; -@@ -809,7 +830,11 @@ +@@ -809,7 +834,11 @@ return; } diff --git a/src/firmware/input/bluepad32_input_backend.cpp b/src/firmware/input/bluepad32_input_backend.cpp index 722cd5a..407a86a 100644 --- a/src/firmware/input/bluepad32_input_backend.cpp +++ b/src/firmware/input/bluepad32_input_backend.cpp @@ -18,6 +18,7 @@ #include "configuration/configuration_service.h" #include "profile/profile_service.h" #include +#include #include #include @@ -193,6 +194,54 @@ struct WiiAimSource { }; #endif +#ifdef SWITCH2_BRIDGE_WII_INPUT +struct WiiMotionIngress { + uint32_t received_us = 0; + uint32_t accel_sequence = 0; + uint32_t gyro_sequence = 0; + uint32_t nunchuk_sequence = 0; + uint32_t accel_received_us = 0; + uint32_t gyro_received_us = 0; + int32_t accel_q13[3]{}; + int32_t gyro_q10[3]{}; + bool accel_valid = false; + bool gyro_valid = false; +}; + +struct WiiCue { + uint64_t token = 0; + uint32_t connection_generation = 0; + uint32_t requested_ms = 0; + uint32_t started_ms = 0; + uint8_t slot = 0xff; + uint8_t sample_id = 0; + uint8_t dispatched_phase = 0xff; + int result = -1; + bool consumed = false; + bool active = false; + bool stop_pending = false; + bool in_flight = false; +}; + +// Wii has a fixed-strength ERM motor: "soft"/"strong" are approximated only +// through pulse length, not invented HD frequencies or amplitude control. +struct WiiCuePattern { + uint16_t phases_ms[7]; // Alternating on/gap, starting and ending on. + uint8_t count; +}; +constexpr WiiCuePattern kWiiCuePatterns[8] = { + {{0}, 0}, + {{1000}, 1}, + {{100, 180, 100, 180, 100, 180, 100}, 7}, + {{25, 90, 25}, 3}, + {{100, 140, 100}, 3}, + {{70, 120, 70}, 3}, + {{60}, 1}, + {{120}, 1}, +}; +constexpr uint32_t kWiiCueDeadlineMs = 2000; +#endif + // Security Manager identity events arrive before Bluepad32 publishes a ready @@ -227,6 +276,9 @@ struct BackendSlot { bool active; bool wii_orientation_pending; WiiOrientationRequest pending_wii_orientation; +#ifdef SWITCH2_BRIDGE_WII_INPUT + WiiMotionIngress wii_motion; +#endif #ifdef SWITCH_PICO_WII_IR_GYRO WiiAimSource wii_aim; #endif @@ -265,6 +317,50 @@ uint32_t g_next_clear_pairings_request_token = 1; bool g_pairing_snapshot_requested = false; bool g_initialized = false; bool g_started = false; +#ifdef SWITCH2_BRIDGE_WII_INPUT +bool g_wii_source_selected = false; +uint8_t g_wii_source_address[6]{}; +Bluepad32WiiBridgeSnapshot g_wii_snapshot{}; +WiiCue g_wii_cue{}; +uint64_t g_next_wii_cue_token = 1; + +// All native Wii state shares the backend lock. Only Core 1 dereferences a +// parser or dispatches transport; Core 0 sees a copied, published snapshot. +bool is_selected_wii(const BackendSlot& slot) { + return g_wii_source_selected && slot.active && slot.device != nullptr && + slot.companion == nullptr && + slot.device->controller_type == CONTROLLER_TYPE_WiiController && + memcmp(slot.device->conn.btaddr, g_wii_source_address, 6) == 0; +} + +void retire_wii_motion(WiiMotionIngress& motion) { + // Keep the observed counters across logical epochs: a cached parser sample + // must not acquire a new receipt timestamp after orientation/reselection. + const uint32_t accel_sequence = motion.accel_sequence; + const uint32_t gyro_sequence = motion.gyro_sequence; + const uint32_t nunchuk_sequence = motion.nunchuk_sequence; + motion = {}; + motion.accel_sequence = accel_sequence; + motion.gyro_sequence = gyro_sequence; + motion.nunchuk_sequence = nunchuk_sequence; +} + +void cancel_wii_cue_locked() { + g_wii_cue.stop_pending = g_wii_cue.stop_pending || + g_wii_cue.active || g_wii_cue.in_flight; + g_wii_cue.active = false; + g_wii_cue.result = -1; +} + +void retire_wii_slot(uint8_t slot_index) { + if (g_wii_snapshot.slot == slot_index) g_wii_snapshot = {}; + if (g_wii_cue.slot == slot_index) { + // The connection is gone or its owner is being reset on Core 1. + // Never send a deferred stop into a replacement generation. + g_wii_cue = {}; + } +} +#endif // These fields are only read or written by Core 1 / BTstack. btstack_timer_source_t g_rumble_timer{}; @@ -1081,6 +1177,30 @@ bool lighting_target_is_current( return current; } +Bluepad32ControllerLayout controller_layout(const BackendSlot& slot) { + if (!slot.active || slot.device == nullptr) + return Bluepad32ControllerLayout::kUnspecified; + const int side = joycon_side(slot.device); + if (side != 0) { + return slot.companion != nullptr + ? Bluepad32ControllerLayout::kJoyCon2MergedPair + : side < 0 ? Bluepad32ControllerLayout::kJoyCon2LeftSolo + : Bluepad32ControllerLayout::kJoyCon2RightSolo; + } + switch (slot.device->controller_subtype) { + case CONTROLLER_SUBTYPE_WIIMOTE_HORIZONTAL: + case CONTROLLER_SUBTYPE_WIIMOTE_ACCEL: + return Bluepad32ControllerLayout::kWiiHorizontal; + case CONTROLLER_SUBTYPE_WIIMOTE_VERTICAL: + return Bluepad32ControllerLayout::kWiiVertical; + case CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK: + case CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK_ACCEL: + return Bluepad32ControllerLayout::kWiiNunchuk; + default: + return Bluepad32ControllerLayout::kUnspecified; + } +} + ConnectionStatus compute_connection_status() { @@ -1127,6 +1247,28 @@ void publish_device_state(uint8_t slot, uni_hid_device_t* device, } #endif ++target.state_generation; +#ifdef SWITCH2_BRIDGE_WII_INPUT + if (is_selected_wii(target)) { + const WiiMotionIngress& motion = target.wii_motion; + g_wii_snapshot.slot = slot; + g_wii_snapshot.controller = { + target.active, target.connection_generation, target.identity, + target.pre_hotkey_button_mask, target.state, + target.accelerometer, target.nunchuk_accelerometer}; + g_wii_snapshot.layout = controller_layout(target); + g_wii_snapshot.state_generation = target.state_generation; + g_wii_snapshot.received_us = motion.received_us; + g_wii_snapshot.battery = device->controller.battery; + g_wii_snapshot.accel_valid = motion.accel_valid; + g_wii_snapshot.gyro_valid = motion.gyro_valid; + g_wii_snapshot.accel_sequence = motion.accel_sequence; + g_wii_snapshot.gyro_sequence = motion.gyro_sequence; + g_wii_snapshot.accel_received_us = motion.accel_received_us; + g_wii_snapshot.gyro_received_us = motion.gyro_received_us; + memcpy(g_wii_snapshot.accel_q13, motion.accel_q13, sizeof(motion.accel_q13)); + memcpy(g_wii_snapshot.gyro_q10, motion.gyro_q10, sizeof(motion.gyro_q10)); + } +#endif g_macro_capture.observe(slot, target.connection_generation, time_us_32(), target.state); } @@ -1139,6 +1281,10 @@ void publish_all_neutral() { wii_ir_pointer_reset(); #endif for (BackendSlot& slot : g_slots) { +#ifdef SWITCH2_BRIDGE_WII_INPUT + retire_wii_slot(static_cast(&slot - g_slots)); + retire_wii_motion(slot.wii_motion); +#endif clear_switch2_ingress(slot); reset_switch2_outputs(slot); slot.state = make_neutral_state(); @@ -1671,6 +1817,10 @@ void reset_slot_hotkeys(BackendSlot& slot) { slot.connection_generation, time_us_32()); slot.wii_orientation_pending = false; slot.pending_wii_orientation = {}; +#ifdef SWITCH2_BRIDGE_WII_INPUT + retire_wii_slot(static_cast(&slot - g_slots)); + retire_wii_motion(slot.wii_motion); +#endif #ifdef SWITCH_PICO_WII_IR_GYRO slot.wii_aim = {}; #endif @@ -2245,6 +2395,134 @@ void dispatch_rumble(uni_hid_device_t* device, uint16_t duration_ms, device->report_parser.play_dual_rumble(device, 0, duration_ms, weak, strong); } +#ifdef SWITCH2_BRIDGE_WII_INPUT +struct WiiCueDispatch { + uni_hid_device_t* device = nullptr; + uint64_t token = 0; + uint32_t connection_generation = 0; + uint8_t slot = 0xff; + uint8_t phase = 0; + uint16_t duration_ms = 0; + bool cancellation_stop = false; +}; + +bool wii_cue_target_current() { + return g_wii_cue.slot < kSlotCount && + is_selected_wii(g_slots[g_wii_cue.slot]) && + g_slots[g_wii_cue.slot].connection_generation == + g_wii_cue.connection_generation; +} + +void restore_wii_host_rumble(BackendSlot& slot) { + if (slot.retained_host_rumble_valid) { + slot.pending_rumble = slot.retained_host_rumble; + slot.rumble_pending = true; + } +} + +// Called under the backend lock, after profile/local arbitration. A waiting +// cue yields to local feedback; a playing cue is canceled rather than replayed +// after an interruption. A finite driver timer bounds even a stalled poller. +bool prepare_wii_cue(uint8_t slot_index, uint32_t now_ms, + bool local_active, bool local_dispatch, + WiiCueDispatch* output) { + WiiCue& cue = g_wii_cue; + if (cue.slot != slot_index) return false; + BackendSlot& slot = g_slots[slot_index]; + if (!wii_cue_target_current() || + slot.device->report_parser.play_dual_rumble == nullptr) { + cue = {}; + return false; + } + if ((cue.result == 0 && + static_cast(now_ms - cue.requested_ms) >= kWiiCueDeadlineMs) || + (cue.active && + static_cast(now_ms - cue.started_ms) >= kWiiCueDeadlineMs)) { + cancel_wii_cue_locked(); + } + if (local_active || local_dispatch) { + if (cue.active) cancel_wii_cue_locked(); + // A local rumble command replaces our finite pulse; a later stop must + // not cut that higher-priority feedback short. + if (local_dispatch) cue.stop_pending = false; + return cue.result == 0 || cue.active || cue.stop_pending; + } + if (cue.in_flight) return true; + if (cue.result != 0 && !cue.active && !cue.stop_pending) return false; + uint8_t phase = 0; + uint16_t duration_ms = 0; + if (!cue.stop_pending && cue.sample_id != 0) { + const WiiCuePattern& pattern = kWiiCuePatterns[cue.sample_id]; + uint32_t elapsed = cue.active ? now_ms - cue.started_ms : 0; + while (phase < pattern.count && elapsed >= pattern.phases_ms[phase]) { + elapsed -= pattern.phases_ms[phase++]; + } + if (phase == pattern.count) { + cue.active = false; + restore_wii_host_rumble(slot); + return false; + } + // The driver's duration timer supplies the gaps. Skip missed phases, + // never replay a burst of old pulses to catch up after a scheduling gap. + if ((phase & 1u) != 0 || phase == cue.dispatched_phase) return true; + duration_ms = static_cast(pattern.phases_ms[phase] - elapsed); + } + *output = {slot.device, cue.token, cue.connection_generation, + slot_index, phase, duration_ms, cue.stop_pending}; + cue.in_flight = true; + return true; +} + +void dispatch_wii_cue(const WiiCueDispatch& command) { + if (command.device == nullptr) return; + critical_section_enter_blocking(&g_state_lock); + const bool current = g_wii_cue.token == command.token && + g_wii_cue.in_flight && wii_cue_target_current() && + g_slots[command.slot].device == command.device && + (command.cancellation_stop ? g_wii_cue.stop_pending + : g_wii_cue.result != -1); + critical_section_exit(&g_state_lock); + // Lifecycle/parser callbacks are serialized on Core 1. The readiness check + // excludes the Wii void hook's early-return path during topology setup. + const bool dispatched = current && + command.device->report_parser.play_dual_rumble != nullptr && + uni_hid_parser_wii_rumble_ready(command.device); + if (dispatched) { + __atomic_add_fetch(&g_rumble_dispatches, 1, __ATOMIC_RELAXED); + command.device->report_parser.play_dual_rumble( + command.device, 0, command.duration_ms, UINT8_MAX, UINT8_MAX); + } + critical_section_enter_blocking(&g_state_lock); + WiiCue& cue = g_wii_cue; + if (cue.token == command.token && cue.connection_generation == command.connection_generation) { + cue.in_flight = false; + if (!wii_cue_target_current()) { + cue = {}; + } else if (command.cancellation_stop) { + if (dispatched) { + cue.stop_pending = false; + restore_wii_host_rumble(g_slots[command.slot]); + } + } else if (cue.result != -1 && dispatched) { + const uint32_t now_ms = btstack_run_loop_get_time_ms(); + if (cue.result == 0 && now_ms - cue.requested_ms >= kWiiCueDeadlineMs) { + cue.stop_pending = command.duration_ms != 0; + cancel_wii_cue_locked(); + } else { + if (cue.result == 0) { + cue.started_ms = now_ms; + cue.result = 1; // Driver dispatch, not an application ACK. + } + cue.active = cue.sample_id != 0; + cue.dispatched_phase = command.phase; + if (!cue.active) restore_wii_host_rumble(g_slots[command.slot]); + } + } + } + critical_section_exit(&g_state_lock); +} +#endif + // Core 1 only. The mailbox carries values, never a parser pointer supplied by // Core 0. Revalidate after lifecycle/topology work and before touching the parser. void process_wii_orientation(uint8_t slot_index) { @@ -2398,6 +2676,9 @@ void process_rumble_timer(btstack_timer_source_t* timer) { bool profile_rumble_dispatch = false; bool feedback_dispatch = false; bool host_dispatch = false; +#ifdef SWITCH2_BRIDGE_WII_INPUT + WiiCueDispatch wii_cue_dispatch{}; +#endif critical_section_enter_blocking(&g_state_lock); BackendSlot& slot = g_slots[slot_index]; @@ -2527,8 +2808,16 @@ void process_rumble_timer(btstack_timer_source_t* timer) { slot.profile_feedback.active || static_cast( now_ms - slot.feedback_until_ms) < 0; +#ifdef SWITCH2_BRIDGE_WII_INPUT + const bool wii_cue_owns_rumble = prepare_wii_cue( + slot_index, now_ms, local_feedback_active, + profile_rumble_dispatch || feedback_dispatch, &wii_cue_dispatch); +#endif if (!profile_rumble_dispatch && !feedback_dispatch && !local_feedback_active && slot.rumble_pending +#ifdef SWITCH2_BRIDGE_WII_INPUT + && !wii_cue_owns_rumble +#endif #ifdef SWITCH_PICO_HAPTICS_EXPERIMENT && !(xinput_host_mode && haptics_experiment_gameplay_owns(slot.device)) @@ -2602,6 +2891,9 @@ void process_rumble_timer(btstack_timer_source_t* timer) { dispatch_host_rumble(target, envelope.duration_ms, envelope.rumble); } } +#ifdef SWITCH2_BRIDGE_WII_INPUT + dispatch_wii_cue(wii_cue_dispatch); +#endif } update_status_led(); @@ -3277,22 +3569,16 @@ void platform_on_controller_data(uni_hid_device_t* device, } #ifdef SWITCH_PICO_WII_IR uni_wii_ir_snapshot_t infrared{}; - const bool have_infrared = uni_hid_parser_wii_ir_snapshot(device, &infrared); + const bool have_infrared = +#ifdef SWITCH2_BRIDGE_WII_INPUT + is_selected_wii(slot) && slot.device == device && +#endif + uni_hid_parser_wii_ir_snapshot(device, &infrared); #ifdef SWITCH_PICO_WII_IR_GYRO observe_wii_aim_chord( slot, device, controller->gamepad, have_infrared ? &infrared : nullptr, time_us_32()); #endif - if (have_infrared) { - const bool nunchuk_c = - (device->controller_subtype == CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK || - device->controller_subtype == CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK_ACCEL) && - (controller->gamepad.buttons & BUTTON_X) != 0; - wii_ir_pointer_observe(static_cast(slot_index), - slot.connection_generation, infrared.sequence, - infrared.buttons, infrared.x, infrared.y, - infrared.valid_mask, nunchuk_c); - } #endif const uint8_t extras = uni_hid_parser_switch2_extra_buttons(device); if (slot.companion == device) { @@ -3307,26 +3593,91 @@ void platform_on_controller_data(uni_hid_device_t* device, if (device->controller_type == CONTROLLER_TYPE_WiiController) { int32_t acceleration[3]; uint32_t sequence; +#ifdef SWITCH2_BRIDGE_WII_INPUT + WiiMotionIngress& motion = slot.wii_motion; + motion.received_us = time_us_32(); +#endif if (!uni_hid_parser_wii_accel_snapshot(device, acceleration, &sequence)) { slot.accelerometer = {}; - } else if (!slot.accelerometer.valid || sequence != slot.accelerometer.sequence) { +#ifdef SWITCH2_BRIDGE_WII_INPUT + motion.accel_valid = false; +#endif + } else if ( +#ifdef SWITCH2_BRIDGE_WII_INPUT + sequence != motion.accel_sequence +#else + !slot.accelerometer.valid || sequence != slot.accelerometer.sequence +#endif + ) { slot.accelerometer = { convert_accel(-static_cast(acceleration[2])), convert_accel(-static_cast(acceleration[0])), convert_accel(acceleration[1]), sequence, btstack_run_loop_get_time_ms(), true}; } +#ifdef SWITCH2_BRIDGE_WII_INPUT + if (slot.accelerometer.valid && sequence != motion.accel_sequence) { + motion.accel_sequence = sequence; + motion.accel_received_us = motion.received_us; + motion.accel_valid = true; + memcpy(motion.accel_q13, acceleration, sizeof(motion.accel_q13)); + } + int32_t gyro[3]; + if (!uni_hid_parser_wii_gyro_snapshot(device, gyro, &sequence)) { + motion.gyro_valid = false; + } else if (sequence != motion.gyro_sequence) { + motion.gyro_sequence = sequence; + motion.gyro_received_us = motion.received_us; + motion.gyro_valid = true; + memcpy(motion.gyro_q10, gyro, sizeof(motion.gyro_q10)); + } +#endif if (!uni_hid_parser_wii_nunchuk_accel_snapshot(device, acceleration, &sequence)) { slot.nunchuk_accelerometer = {}; - } else if (!slot.nunchuk_accelerometer.valid || - sequence != slot.nunchuk_accelerometer.sequence) { + } else if ( +#ifdef SWITCH2_BRIDGE_WII_INPUT + sequence != motion.nunchuk_sequence +#else + !slot.nunchuk_accelerometer.valid || + sequence != slot.nunchuk_accelerometer.sequence +#endif + ) { slot.nunchuk_accelerometer = { convert_accel(-static_cast(acceleration[2])), convert_accel(-static_cast(acceleration[0])), convert_accel(acceleration[1]), sequence, btstack_run_loop_get_time_ms(), true}; +#ifdef SWITCH2_BRIDGE_WII_INPUT + motion.nunchuk_sequence = sequence; +#endif } } +#ifdef SWITCH_PICO_WII_IR + if (have_infrared) { + const bool nunchuk_c = + (device->controller_subtype == CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK || + device->controller_subtype == CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK_ACCEL) && + (controller->gamepad.buttons & BUTTON_X) != 0; + float gravity_roll = 0.0f; + bool gravity_valid = false; +#if SWITCH2_BRIDGE_WII_INPUT + const WiiMotionIngress& motion = slot.wii_motion; + if (motion.accel_valid && time_us_32() - motion.accel_received_us < 150000) { + const float x = static_cast(motion.accel_q13[0]) / 8192.0f; + const float y = static_cast(motion.accel_q13[1]) / 8192.0f; + const float z = static_cast(motion.accel_q13[2]) / 8192.0f; + const float magnitude = x * x + y * y + z * z; + gravity_valid = magnitude >= 0.85f * 0.85f && magnitude <= 1.15f * 1.15f && + x * x + y * y >= 0.25f; + if (gravity_valid) gravity_roll = atan2f(-x, y); + } +#endif + wii_ir_pointer_observe(static_cast(slot_index), + slot.connection_generation, infrared.sequence, + infrared.buttons, infrared.x, infrared.y, + infrared.valid_mask, nunchuk_c, gravity_roll, gravity_valid); + } +#endif const uni_gamepad_t gamepad = logical_gamepad(slot); uni_hid_device_t* owner = slot.device; const bool fresh_motion = @@ -3720,6 +4071,95 @@ void bluepad32_input_backend_snapshot(uint8_t slot_index, g_last_snapshot_generation[slot_index] = state_generation; } +#ifdef SWITCH2_BRIDGE_WII_INPUT +void bluepad32_input_backend_select_wii_source(const uint8_t address[6]) { + // Selection is configuration, not a live Core 0 parser mutation. + if (!g_initialized || g_started) return; + critical_section_enter_blocking(&g_state_lock); + g_wii_source_selected = address != nullptr; + if (address != nullptr) memcpy(g_wii_source_address, address, 6); + else memset(g_wii_source_address, 0, sizeof(g_wii_source_address)); + g_wii_snapshot = {}; + g_wii_cue = {}; + for (BackendSlot& slot : g_slots) retire_wii_motion(slot.wii_motion); +#ifdef SWITCH_PICO_WII_IR + // Lock order: backend exclusive, then pointer striped. + wii_ir_pointer_reset(); +#endif + critical_section_exit(&g_state_lock); +} + +void bluepad32_input_backend_wii_snapshot(Bluepad32WiiBridgeSnapshot* output) { + if (output == nullptr) return; + *output = {}; + if (!g_initialized) return; + critical_section_enter_blocking(&g_state_lock); + const uint8_t slot = g_wii_snapshot.slot; + if (slot < kSlotCount && is_selected_wii(g_slots[slot]) && + g_slots[slot].connection_generation == + g_wii_snapshot.controller.connection_generation) { + *output = g_wii_snapshot; + } + critical_section_exit(&g_state_lock); +} + +bool bluepad32_input_backend_wii_sample_request(uint8_t sample_id, uint64_t* token) { + if (token == nullptr) return false; + *token = 0; + if (!g_initialized || sample_id >= 8) return false; + critical_section_enter_blocking(&g_state_lock); + bool accepted = false; + // Do not overwrite a command already being dispatched. Sample zero can + // replace a queued/running pattern; ordinary cues serialize until it ends. + if (g_next_wii_cue_token != 0 && !g_wii_cue.in_flight && + (sample_id == 0 || (g_wii_cue.result != 0 && + !g_wii_cue.active && !g_wii_cue.stop_pending))) { + for (uint8_t slot_index = 0; slot_index < kSlotCount; ++slot_index) { + const BackendSlot& slot = g_slots[slot_index]; + if (!is_selected_wii(slot) || + slot.device->report_parser.play_dual_rumble == nullptr) continue; + g_wii_cue = {}; + g_wii_cue.token = g_next_wii_cue_token++; + g_wii_cue.slot = slot_index; + g_wii_cue.connection_generation = slot.connection_generation; + g_wii_cue.sample_id = sample_id; + g_wii_cue.requested_ms = btstack_run_loop_get_time_ms(); + g_wii_cue.result = 0; + *token = g_wii_cue.token; + accepted = true; + break; + } + } + critical_section_exit(&g_state_lock); + return accepted; +} + +int bluepad32_input_backend_wii_sample_result(uint64_t token) { + if (!g_initialized || token == 0) return -1; + critical_section_enter_blocking(&g_state_lock); + int result = -1; + if (g_wii_cue.token == token && !g_wii_cue.consumed) { + if (!wii_cue_target_current() || + g_slots[g_wii_cue.slot].device->report_parser.play_dual_rumble == nullptr || + (g_wii_cue.result == 0 && + btstack_run_loop_get_time_ms() - g_wii_cue.requested_ms >= kWiiCueDeadlineMs)) { + cancel_wii_cue_locked(); + } + result = g_wii_cue.result; + if (result != 0) g_wii_cue.consumed = true; + } + critical_section_exit(&g_state_lock); + return result; +} + +void bluepad32_input_backend_wii_sample_cancel() { + if (!g_initialized) return; + critical_section_enter_blocking(&g_state_lock); + cancel_wii_cue_locked(); + critical_section_exit(&g_state_lock); +} +#endif + void bluepad32_input_backend_playtest_snapshot( uint8_t slot_index, Bluepad32PlaytestSnapshot* out) { if (out == nullptr) { @@ -3745,35 +4185,7 @@ void bluepad32_input_backend_playtest_snapshot( (slot.device->report_parser.set_lightbar_color != nullptr ? 2u : 0u) | (slot.device->report_parser.set_player_leds != nullptr ? 4u : 0u) | (slot.state.motion_sample_count != 0 ? 8u : 0u); - if (slot.active) { - const int side = joycon_side(slot.device); - if (side != 0) { - out->controller_layout = slot.companion != nullptr - ? Bluepad32ControllerLayout::kJoyCon2MergedPair - : side < 0 - ? Bluepad32ControllerLayout::kJoyCon2LeftSolo - : Bluepad32ControllerLayout::kJoyCon2RightSolo; - } else { - switch (slot.device->controller_subtype) { - case CONTROLLER_SUBTYPE_WIIMOTE_HORIZONTAL: - case CONTROLLER_SUBTYPE_WIIMOTE_ACCEL: - out->controller_layout = - Bluepad32ControllerLayout::kWiiHorizontal; - break; - case CONTROLLER_SUBTYPE_WIIMOTE_VERTICAL: - out->controller_layout = - Bluepad32ControllerLayout::kWiiVertical; - break; - case CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK: - case CONTROLLER_SUBTYPE_WIIMOTE_NUNCHUK_ACCEL: - out->controller_layout = - Bluepad32ControllerLayout::kWiiNunchuk; - break; - default: - break; - } - } - } + out->controller_layout = controller_layout(slot); } critical_section_exit(&g_state_lock); } diff --git a/src/firmware/input/bluepad32_input_backend.h b/src/firmware/input/bluepad32_input_backend.h index 1a63ceb..aeec139 100644 --- a/src/firmware/input/bluepad32_input_backend.h +++ b/src/firmware/input/bluepad32_input_backend.h @@ -78,6 +78,36 @@ enum class Bluepad32ControllerLayout : uint8_t { kWiiVertical = 7, }; +#ifdef SWITCH2_BRIDGE_WII_INPUT +// Calibrated SDL axes, before legacy Switch int16 conversion and motion gating. +// Both sensor sequences and receipt times are independent of controller reports. +struct Bluepad32WiiBridgeSnapshot { + uint8_t slot = 0xff; + Bluepad32SlotSnapshot controller{}; + Bluepad32ControllerLayout layout = Bluepad32ControllerLayout::kUnspecified; + uint32_t state_generation = 0; + uint32_t received_us = 0; + uint8_t battery = 0; + bool accel_valid = false; + bool gyro_valid = false; + uint32_t accel_sequence = 0; + uint32_t gyro_sequence = 0; + uint32_t accel_received_us = 0; + uint32_t gyro_received_us = 0; + int32_t accel_q13[3]{}; + int32_t gyro_q10[3]{}; +}; + +// Core 0, after init and before start. Reselection retires source-local work. +void bluepad32_input_backend_select_wii_source(const uint8_t address[6]); +void bluepad32_input_backend_wii_snapshot(Bluepad32WiiBridgeSnapshot* output); +// Bounded ERM approximations, not HD haptics. Completion means Core 1 driver +// dispatch, never a Wii application ACK. Tokens are unique for this boot. +bool bluepad32_input_backend_wii_sample_request(uint8_t sample_id, uint64_t* token); +int bluepad32_input_backend_wii_sample_result(uint64_t token); +void bluepad32_input_backend_wii_sample_cancel(); +#endif + // Side-effect-free raw input snapshot for management telemetry. Unlike the // report-path snapshot, reading this does not consume motion samples. struct Bluepad32PlaytestSnapshot { diff --git a/src/firmware/input/wii_ir_pointer.cpp b/src/firmware/input/wii_ir_pointer.cpp index 8e8c517..1839d41 100644 --- a/src/firmware/input/wii_ir_pointer.cpp +++ b/src/firmware/input/wii_ir_pointer.cpp @@ -1,5 +1,9 @@ #include "input/wii_ir_pointer.h" +#if SWITCH2_BRIDGE_WII_INPUT +#include "libogc_ir/ir.h" +#else #include "input/wii_ir_tracker.h" +#endif #include #include @@ -13,10 +17,29 @@ constexpr int32_t kMaximumPendingQ8 = 4096 * 256; #endif constexpr uint16_t kButtonA = 0x0008; constexpr uint16_t kButtonB = 0x0004; +#if !SWITCH2_BRIDGE_WII_INPUT +constexpr bool kResetModelOnDelivery = true; constexpr uint16_t kButtonOne = 0x0002; constexpr WiiIrCameraModel kCamera{}; -#ifdef SWITCH_PICO_WII_IR_GYRO +#endif +#if SWITCH2_BRIDGE_WII_INPUT || defined(SWITCH_PICO_WII_IR_GYRO) constexpr float kDegreesPerRadian = 57.295779513f; +#endif +#if SWITCH2_BRIDGE_WII_INPUT +constexpr bool kResetModelOnDelivery = false; +ir_t g_ir{}; +orient_t g_orientation{}; +float g_screen_width = 660.0f; +float g_screen_height = 370.0f; +float g_screen_offset_x = 0.0f; +float g_screen_offset_y = -115.0f; +float g_screen_span_x = 1920.0f; +float g_screen_span_y = 1080.0f; +bool g_optical_valid; +bool g_in_viewport; +float g_optical_yaw; +uint32_t g_optical_sequence, g_optical_received_us; +#elif defined(SWITCH_PICO_WII_IR_GYRO) WiiIrTracker g_tracker{kCamera, true}; #else WiiIrTracker g_tracker{kCamera}; @@ -37,9 +60,14 @@ uint8_t g_valid_mask; uint8_t g_buttons; uint8_t g_sent_buttons; bool g_have_sample; +bool g_output_enabled = true; bool g_tracking; bool g_clutch; +#if SWITCH2_BRIDGE_WII_INPUT +int64_t g_filtered_x_q8, g_filtered_y_q8; +#else int32_t g_filtered_x_q8, g_filtered_y_q8; +#endif int32_t g_pending_x_q8, g_pending_y_q8; #ifdef SWITCH_PICO_WII_IR_GYRO @@ -68,7 +96,21 @@ int32_t clamp(int32_t value, int32_t limit) { } void stop_tracking(bool reset_model = true) { +#if SWITCH2_BRIDGE_WII_INPUT + if (reset_model) { + // Match upstream's zero-initialized history. Only connection/reset + // replaces it; delivery and USB readiness gates discard deltas only. + g_ir = {}; + g_ir.aspect = WIIUSE_ASPECT_16_9; + g_ir.pos = WIIUSE_IR_BELOW; + g_ir.vres[0] = WM_ASPECT_16_9_X; + g_ir.vres[1] = WM_ASPECT_16_9_Y; + g_ir.offset[1] = -WM_ASPECT_16_9_Y / 2 + 70; + g_orientation = {}; + } +#else if (reset_model) g_tracker.reset(); +#endif bool pending = g_pending_x_q8 || g_pending_y_q8; #ifdef SWITCH_PICO_WII_IR_GYRO pending = pending || g_fraction_x || g_fraction_y; @@ -80,6 +122,10 @@ void stop_tracking(bool reset_model = true) { ++g_rebaselines; } g_tracking = false; +#if SWITCH2_BRIDGE_WII_INPUT + g_optical_valid = false; + g_in_viewport = false; +#endif g_pending_x_q8 = 0; g_pending_y_q8 = 0; } @@ -128,7 +174,7 @@ void expire(uint32_t now) { // before this lock was acquired. A small negative age is not a timeout. if (g_have_sample && static_cast(now - g_received_us) >= static_cast(kStaleUs)) { - stop_tracking(); + stop_tracking(kResetModelOnDelivery); g_buttons = 0; // Losing IR must not silently select physical gyro. Keep the chosen // source and emit zero until a fresh tracking baseline is available. @@ -169,6 +215,9 @@ void pointer_diagnostics(uint8_t* data, uint32_t now) { data[2] = g_valid_mask; data[3] = (g_tracking ? 1 : 0) | (g_clutch ? 2 : 0) | (g_have_sample && now - g_received_us < kStaleUs ? 4 : 0); +#if SWITCH2_BRIDGE_WII_INPUT + data[3] |= (g_in_viewport ? 8 : 0) | (g_optical_valid ? 16 : 0); +#endif put32(data + 4, g_sequence); put32(data + 8, g_samples); put32(data + 12, g_sent); @@ -201,6 +250,7 @@ void wii_ir_pointer_reset() { ++g_generation; g_buttons = 0; g_owner = 0xff; + g_connection_generation = 0; // Force an explicit release after reset if the host saw a held button. g_have_sample = false; g_valid_mask = 0; @@ -212,6 +262,30 @@ void wii_ir_pointer_reset() { critical_section_exit(&g_lock); } +#if SWITCH2_BRIDGE_WII_INPUT +bool wii_ir_pointer_configure_screen(float width, float height, float offset_x, + float offset_y, float span_x, float span_y) { + if (!g_initialized || !isfinite(width) || !isfinite(height) || + !isfinite(offset_x) || !isfinite(offset_y) || + !isfinite(span_x) || !isfinite(span_y) || + width < 1 || width > 1024 || height < 1 || height > 768 || + fabsf(offset_x) > (1024.0f - width) * 0.5f || + fabsf(offset_y) > (768.0f - height) * 0.5f || + span_x <= 0 || span_x > 32767 || span_y <= 0 || span_y > 32767) return false; + critical_section_enter_blocking(&g_lock); + stop_tracking(false); + g_screen_width = width; + g_screen_height = height; + g_screen_offset_x = offset_x; + g_screen_offset_y = offset_y; + g_screen_span_x = span_x; + g_screen_span_y = span_y; + ++g_generation; + critical_section_exit(&g_lock); + return true; +} +#endif + void wii_ir_pointer_disconnect(uint8_t slot) { if (!g_initialized) return; critical_section_enter_blocking(&g_lock); @@ -219,6 +293,7 @@ void wii_ir_pointer_disconnect(uint8_t slot) { stop_tracking(); ++g_generation; g_owner = 0xff; + g_connection_generation = 0; g_buttons = 0; g_have_sample = false; g_valid_mask = 0; @@ -234,7 +309,8 @@ void wii_ir_pointer_disconnect(uint8_t slot) { void wii_ir_pointer_observe(uint8_t slot, uint32_t connection_generation, uint32_t sequence, uint16_t buttons, const uint16_t x[4], const uint16_t y[4], - uint8_t valid_mask, bool nunchuk_c) { + uint8_t valid_mask, bool nunchuk_c, + float gravity_roll_radians, bool gravity_valid) { if (!g_initialized) return; const uint32_t now = time_us_32(); critical_section_enter_blocking(&g_lock); @@ -259,6 +335,25 @@ void wii_ir_pointer_observe(uint8_t slot, uint32_t connection_generation, g_raw_buttons = buttons; g_valid_mask = valid_mask & 0x0f; g_buttons = ((buttons & kButtonA) ? 1 : 0) | ((buttons & kButtonB) ? 2 : 0); +#if SWITCH2_BRIDGE_WII_INPUT + // Controller profiles own all native buttons, including the legacy + // desktop clutch. The pointer button bytes remain diagnostic telemetry; + // the native consumer never overlays them onto the controller profile. + g_clutch = false; + (void)nunchuk_c; + for (unsigned i = 0; i < 4; ++i) { + g_ir.dot[i].rx = 1023 - x[i]; + g_ir.dot[i].ry = y[i]; + g_ir.dot[i].visible = (g_valid_mask & (1u << i)) != 0; + } + // The producer supplies the bar angle in raw camera pixels. Upstream + // expects degrees after X mirroring; retain its last gravity reference + // when acceleration cannot provide a new one. + if (gravity_valid && isfinite(gravity_roll_radians)) { + g_orientation.roll = gravity_roll_radians * kDegreesPerRadian; + } + interpret_ir_data(&g_ir, &g_orientation); +#else g_clutch = (buttons & kButtonOne) != 0; #ifdef SWITCH_PICO_WII_IR_GYRO // C + 1 is the reposition chord. Keep 1 + 2 motionless while the @@ -266,18 +361,41 @@ void wii_ir_pointer_observe(uint8_t slot, uint32_t connection_generation, g_clutch = g_clutch && (nunchuk_c || (buttons & 0x0001) != 0); #else (void)nunchuk_c; +#endif #endif - bool usable = !g_clutch; + bool usable = g_output_enabled && !g_clutch; #ifdef SWITCH_PICO_WII_IR_GYRO usable = usable && (!g_infrared || g_motion_enabled); #endif if (!usable) { - stop_tracking(); + stop_tracking(kResetModelOnDelivery); critical_section_exit(&g_lock); return; } - const WiiIrTrackingResult tracked = g_tracker.update(x, y, g_valid_mask, now); +#if SWITCH2_BRIDGE_WII_INPUT + if (!g_ir.smooth_valid || + (!g_tracking && (!g_ir.raw_valid || g_ir.glitch_cnt != 0))) { + // A new relative baseline needs an accepted upstream position, not + // the zero-origin/cached position held during upstream glitch grace. + // Do not change that grace, its counters, or the sensor-bar history. + stop_tracking(false); + critical_section_exit(&g_lock); + return; + } + const float screen_x = (g_ir.sx - 512.0f - g_screen_offset_x) / + g_screen_width + 0.5f; + const float screen_y = (g_ir.sy - 384.0f - g_screen_offset_y) / + g_screen_height + 0.5f; + // A relative host cursor need not be at our viewport edge. Never gate + // unbounded smoothed positions on upstream's bounded ir.valid field. + const int64_t px = llroundf(screen_x * g_screen_span_x * 256.0f); + // Shared mouse Y remains negative; the native serializer flips it once. + const int64_t py = llroundf(-screen_y * g_screen_span_y * 256.0f); + const bool rebased = !g_tracking; +#else + const WiiIrTrackingResult tracked = g_tracker.update( + x, y, g_valid_mask, now, gravity_roll_radians, gravity_valid); if (!tracked.tracked) { // Discard output, but retain bounded association history so a brief // occlusion does not make another reflection become the reference. @@ -299,15 +417,26 @@ void wii_ir_pointer_observe(uint8_t slot, uint32_t connection_generation, const int32_t px = static_cast(lroundf(tracked.yaw_radians * kCamera.fx * 512.0f)); const int32_t py = static_cast(lroundf(tracked.pitch_radians * kCamera.fy * 512.0f)); #endif - if (!g_tracking || tracked.rebased) { + const bool rebased = tracked.rebased; +#endif + if (!g_tracking || rebased) { stop_tracking(false); g_tracking = true; g_filtered_x_q8 = px; g_filtered_y_q8 = py; ++g_rebaselines; } else { +#if SWITCH2_BRIDGE_WII_INPUT + const int64_t wide_dx = px - g_filtered_x_q8; + const int64_t wide_dy = py - g_filtered_y_q8; + const int32_t dx = static_cast(wide_dx < -kMaximumPendingQ8 ? -kMaximumPendingQ8 : + wide_dx > kMaximumPendingQ8 ? kMaximumPendingQ8 : wide_dx); + const int32_t dy = static_cast(wide_dy < -kMaximumPendingQ8 ? -kMaximumPendingQ8 : + wide_dy > kMaximumPendingQ8 ? kMaximumPendingQ8 : wide_dy); +#else const int32_t dx = px - g_filtered_x_q8; const int32_t dy = py - g_filtered_y_q8; +#endif g_filtered_x_q8 = px; g_filtered_y_q8 = py; #ifdef SWITCH_PICO_WII_IR_GYRO @@ -324,18 +453,45 @@ void wii_ir_pointer_observe(uint8_t slot, uint32_t connection_generation, g_pending_y_q8 = clamp(g_pending_y_q8 + dy, kMaximumPendingQ8); #endif } +#if SWITCH2_BRIDGE_WII_INPUT + // Propagate upstream glitch rejection to the independent heading observer: + // a held pointer must not silently accept that rejected raw geometry as yaw. + g_optical_valid = g_ir.raw_valid && g_ir.state == IR_STATE_GOOD && + g_ir.smooth_valid && g_ir.glitch_cnt == 0; + g_in_viewport = screen_x >= 0 && screen_x <= 1 && screen_y >= 0 && screen_y <= 1; + // interpret_ir_data already computes calc_yaw from the raw bar center. + g_optical_yaw = g_orientation.yaw / kDegreesPerRadian; + g_optical_sequence = sequence; + g_optical_received_us = now; +#endif critical_section_exit(&g_lock); } -bool wii_ir_mouse_peek(WiiIrMouseReport* report) { - if (!g_initialized || report == nullptr) return false; +bool wii_ir_mouse_peek(WiiIrMouseReport* report, int16_t maximum_delta) { + if (report == nullptr) return false; + if (!g_initialized) { + *report = {}; + report->owner = 0xff; + return false; + } critical_section_enter_blocking(&g_lock); expire(time_us_32()); - report->dx = static_cast(clamp(g_pending_x_q8 / 256, 127)); - report->dy = static_cast(clamp(g_pending_y_q8 / 256, 127)); + const int32_t limit = maximum_delta > 0 ? maximum_delta : 0; + report->dx = static_cast(clamp(g_pending_x_q8 / 256, limit)); + report->dy = static_cast(clamp(g_pending_y_q8 / 256, limit)); report->buttons = g_buttons; report->generation = g_generation; - const bool pending = report->dx || report->dy || g_buttons != g_sent_buttons; + report->tracking = g_tracking; + report->owner = g_owner; + report->connection_generation = g_connection_generation; +#if SWITCH2_BRIDGE_WII_INPUT + report->optical_valid = g_tracking && g_optical_valid; + report->optical_yaw_radians = g_optical_yaw; + report->optical_sequence = g_optical_sequence; + report->optical_received_us = g_optical_received_us; +#endif + const bool pending = g_output_enabled && + (report->dx || report->dy || g_buttons != g_sent_buttons); critical_section_exit(&g_lock); return pending; } @@ -343,7 +499,10 @@ bool wii_ir_mouse_peek(WiiIrMouseReport* report) { void wii_ir_mouse_commit(const WiiIrMouseReport& report) { if (!g_initialized) return; critical_section_enter_blocking(&g_lock); - if (report.generation == g_generation) { + expire(time_us_32()); + if (g_output_enabled && report.generation == g_generation && + report.owner == g_owner && + report.connection_generation == g_connection_generation) { g_pending_x_q8 -= static_cast(report.dx) * 256; g_pending_y_q8 -= static_cast(report.dy) * 256; } @@ -353,6 +512,17 @@ void wii_ir_mouse_commit(const WiiIrMouseReport& report) { critical_section_exit(&g_lock); } +void wii_ir_mouse_set_output_enabled(bool enabled) { + if (!g_initialized) return; + critical_section_enter_blocking(&g_lock); + if (g_output_enabled != enabled) { + stop_tracking(kResetModelOnDelivery); + ++g_generation; + g_output_enabled = enabled; + } + critical_section_exit(&g_lock); +} + size_t wii_ir_pointer_diagnostics(uint8_t* buffer, size_t capacity) { if (!g_initialized || buffer == nullptr) return 0; uint8_t data[WII_IR_MOUSE_DIAGNOSTIC_SIZE]{}; diff --git a/src/firmware/input/wii_ir_pointer.h b/src/firmware/input/wii_ir_pointer.h index 2738aea..a0a8257 100644 --- a/src/firmware/input/wii_ir_pointer.h +++ b/src/firmware/input/wii_ir_pointer.h @@ -5,29 +5,59 @@ #include "core/controller_state.h" struct WiiIrMouseReport { - int8_t dx; - int8_t dy; + int16_t dx; + int16_t dy; uint8_t buttons; uint32_t generation; + bool tracking; + uint8_t owner; + uint32_t connection_generation; +#if SWITCH2_BRIDGE_WII_INPUT + // Full-pair upstream heading, excluding raw geometry still held as a glitch. + bool optical_valid; + float optical_yaw_radians; + uint32_t optical_sequence; + uint32_t optical_received_us; +#endif }; // Core 0 initializes before starting Bluetooth. The producer runs on Core 1; // USB peeks/commits on Core 0, preserving movement until a successful send. void wii_ir_pointer_init(); void wii_ir_pointer_reset(); -bool wii_ir_mouse_peek(WiiIrMouseReport* report); +// Metadata is populated even without pending output. Nonpositive limits +// suppress movement; the default retains the legacy signed 8-bit HID range. +bool wii_ir_mouse_peek(WiiIrMouseReport* report, int16_t maximum_delta = 127); void wii_ir_mouse_commit(const WiiIrMouseReport& report); +// Enabled by default. Transitions discard pending motion and its baseline, +// retaining owner and diagnostics. Native Wii keeps upstream camera history; +// legacy modes reset association. Repeated calls preserve live tracking. +// Reset/disconnect preserve this gate. +void wii_ir_mouse_set_output_enabled(bool enabled); constexpr size_t WII_IR_MOUSE_DIAGNOSTIC_SIZE = 48; size_t wii_ir_pointer_diagnostics(uint8_t* buffer, size_t capacity); +#if SWITCH2_BRIDGE_WII_INPUT +// Configure before starting Core 1. The viewport is in camera pixels; spans +// are native mouse counts across it, not a claim about console cursor pixels. +// Upstream sx/sy remain unclipped; this rectangle controls relative scale and +// diagnostic viewport membership, not absolute host cursor synchronization. +bool wii_ir_pointer_configure_screen(float width, float height, float offset_x, + float offset_y, float span_x, float span_y); +#endif + // The first Wii source owns the experimental pointer until disconnected. void wii_ir_pointer_disconnect(uint8_t slot); // nunchuk_c is the unmapped physical C state, false without a Nunchuk. +// Native Wii: one call per actual camera sequence, raw unmirrored dot X/Y. +// Gravity roll is the raw bar angle in radians; invalid gravity retains the +// last valid upstream roll. Controller profile buttons never become clicks. void wii_ir_pointer_observe(uint8_t slot, uint32_t connection_generation, uint32_t sequence, uint16_t buttons, const uint16_t x[4], const uint16_t y[4], - uint8_t valid_mask, bool nunchuk_c); + uint8_t valid_mask, bool nunchuk_c, + float gravity_roll_radians = 0.0f, bool gravity_valid = false); #ifdef SWITCH_PICO_WII_IR_GYRO struct WiiIrGyroReport { diff --git a/src/firmware/input/wii_ir_tracker.h b/src/firmware/input/wii_ir_tracker.h index 7f6c2f0..d20b3e8 100644 --- a/src/firmware/input/wii_ir_tracker.h +++ b/src/firmware/input/wii_ir_tracker.h @@ -15,7 +15,7 @@ struct WiiIrTrackingResult { bool tracked = false; bool rebased = false; bool inferred = false; - // Matched spots: relative mode may use one to four, not just a bar pair. + // Supporting spots used for the tracked measurement. uint8_t pair_mask = 0; float yaw_radians = 0; float pitch_radians = 0; diff --git a/tests/bluepad32_backend_lifecycle_test.cpp b/tests/bluepad32_backend_lifecycle_test.cpp index 665f6e2..701069a 100644 --- a/tests/bluepad32_backend_lifecycle_test.cpp +++ b/tests/bluepad32_backend_lifecycle_test.cpp @@ -40,6 +40,10 @@ struct WiiAccelFixture { }; WiiAccelFixture remote_accel_fixture; WiiAccelFixture nunchuk_accel_fixture; +#ifdef SWITCH2_BRIDGE_WII_INPUT +WiiAccelFixture gyro_fixture; +bool wii_rumble_ready = true; +#endif bool wii_accel_fixture_snapshot(const WiiAccelFixture& fixture, uni_hid_device_t* controller, @@ -749,6 +753,17 @@ extern "C" bool uni_hid_parser_wii_nunchuk_accel_snapshot( return wii_accel_fixture_snapshot(nunchuk_accel_fixture, controller, acceleration, sequence); } +#ifdef SWITCH2_BRIDGE_WII_INPUT +extern "C" bool uni_hid_parser_wii_gyro_snapshot( + uni_hid_device_t* controller, int32_t gyro[3], uint32_t* sequence) { + return wii_accel_fixture_snapshot(gyro_fixture, controller, gyro, sequence); +} +extern "C" bool uni_hid_parser_wii_rumble_ready(uni_hid_device_t*) { + require(state_lock_depth == 0, "Wii dispatch readiness must be checked on Core 1 outside the state lock"); + return wii_rumble_ready; +} +#endif + #ifdef SWITCH_PICO_HAPTICS_EXPERIMENT namespace { std::vector native_timers; @@ -5605,6 +5620,186 @@ void dispatch_wii_requests() { wii_dispatch_active = false; } +#ifdef SWITCH2_BRIDGE_WII_INPUT +void test_wii_bridge_sensors() { + auto selected = wii_device(1); + auto other = wii_device(0); + bluepad32_input_backend_init(); + bluepad32_input_backend_select_wii_source(selected.conn.btaddr); + start_pairing_backend(); + require(platform_on_device_ready(&other) == UNI_ERROR_SUCCESS, "unselected Wii must remain available normally"); + uni_controller_t input{}; + input.klass = UNI_CONTROLLER_CLASS_GAMEPAD; + input.gamepad.buttons = BUTTON_A; + remote_accel_fixture = {&other, {8193, -42, 91}, 7, true}; + gyro_fixture = {&other, {123456, -45678, 91011}, 11, true}; + platform_on_controller_data(&other, &input); + Bluepad32WiiBridgeSnapshot snapshot{}; + bluepad32_input_backend_wii_snapshot(&snapshot); + require(!snapshot.controller.active && snapshot.slot == 0xff, + "an unrelated Wii cannot claim the selected native source"); + selected.controller_type = CONTROLLER_TYPE_UnknownController; + require(platform_on_device_ready(&selected) == UNI_ERROR_SUCCESS, "non-Wii address match must connect normally"); + platform_on_controller_data(&selected, &input); + bluepad32_input_backend_wii_snapshot(&snapshot); + require(!snapshot.controller.active, "matching address alone must not identify a Wii"); + platform_on_device_disconnected(&selected); + auto replacement = wii_device(1); + require(platform_on_device_ready(&replacement) == UNI_ERROR_SUCCESS, "selected physical Wii must become ready"); + const uint32_t generation = slot_snapshot(1).connection_generation; + if (kDefaultMotionEnabled) { + require(bluepad32_input_backend_toggle_motion(1, generation), "legacy motion toggle must be independent"); + } + remote_accel_fixture = {&replacement, {8193, -42, 91}, 7, true}; + gyro_fixture = {&replacement, {123456, -45678, 91011}, 11, true}; + now_ms = 100; + platform_on_controller_data(&replacement, &input); + bluepad32_input_backend_wii_snapshot(&snapshot); + require(snapshot.controller.active && snapshot.slot == 1 && + snapshot.controller.state.button_south && + snapshot.controller.state.motion_sample_count == 0 && + snapshot.accel_valid && snapshot.gyro_valid && + snapshot.accel_q13[0] == 8193 && snapshot.gyro_q10[0] == 123456, + "native raw precision and ordinary buttons must survive legacy motion disable"); + require(snapshot.accel_received_us == 100000 && snapshot.gyro_received_us == 100000, + "both first genuine sensor samples need ingress timestamps"); + now_ms = 250; + ++remote_accel_fixture.sequence; + platform_on_controller_data(&replacement, &input); + now_ms = 300; // Status/ACK callback has no new sensor sequence. + platform_on_controller_data(&replacement, &input); + bluepad32_input_backend_report_sent(1); + bluepad32_input_backend_wii_snapshot(&snapshot); + require(snapshot.received_us == 300000 && snapshot.accel_received_us == 250000 && + snapshot.gyro_received_us == 100000 && snapshot.gyro_sequence == 11, + "accel interleaves, status and USB consumption cannot rejuvenate gyro"); + require(bluepad32_input_backend_set_wii_orientation( + snapshot.controller.identity, generation, true), "orientation change must queue"); + dispatch_wii_requests(); + platform_on_controller_data(&replacement, &input); + bluepad32_input_backend_wii_snapshot(&snapshot); + require(snapshot.controller.connection_generation != generation && + !snapshot.accel_valid && !snapshot.gyro_valid && + !snapshot.controller.accelerometer.valid, + "a logical epoch must not republish cached parser samples as fresh"); + ++remote_accel_fixture.sequence; + ++gyro_fixture.sequence; + now_ms = 320; + platform_on_controller_data(&replacement, &input); + bluepad32_input_backend_wii_snapshot(&snapshot); + require(snapshot.accel_valid && snapshot.gyro_valid && snapshot.gyro_received_us == 320000, + "distinct samples must recover the new logical epoch"); + platform_on_device_disconnected(&replacement); + bluepad32_input_backend_wii_snapshot(&snapshot); + require(!snapshot.controller.active && !snapshot.accel_valid && !snapshot.gyro_valid && + snapshot.slot == 0xff, "disconnect must retire source identity and samples together"); +} + +void (*during_wii_rumble)() = nullptr; +void observe_wii_rumble(uni_hid_device_t* target, uint16_t delay, + uint16_t duration, uint8_t weak, uint8_t strong) { + require(state_lock_depth == 0, "Wii transport must run without the backend lock"); + play_rumble(target, delay, duration, weak, strong); + if (during_wii_rumble != nullptr) during_wii_rumble(); +} + +void test_wii_bridge_cues() { + auto selected = wii_device(1); + selected.report_parser.play_dual_rumble = observe_wii_rumble; + auto other = wii_device(0); + bluepad32_input_backend_init(); + bluepad32_input_backend_select_wii_source(selected.conn.btaddr); + start_pairing_backend(); + require(platform_on_device_ready(&other) == UNI_ERROR_SUCCESS && + platform_on_device_ready(&selected) == UNI_ERROR_SUCCESS, "cue fixtures must connect"); + uint64_t token = 0; + require(bluepad32_input_backend_wii_sample_request(3, &token) && + bluepad32_input_backend_wii_sample_result(token) == 0 && + selected.rumble_calls == 0, "Core 0 queue acceptance is not cue completion"); + process_rumble_timer(&g_rumble_timer); + require(bluepad32_input_backend_wii_sample_result(token) == 1 && + bluepad32_input_backend_wii_sample_result(token) == -1 && + selected.rumble_calls == 1 && selected.last_rumble_duration_ms == 25, + "double-click completion must be consumable once after its first driver dispatch"); + now_ms = 60; + process_rumble_timer(&g_rumble_timer); + require(selected.rumble_calls == 1, "double-click gap must not vibrate"); + now_ms = 115; + process_rumble_timer(&g_rumble_timer); + require(selected.rumble_calls == 2 && selected.last_rumble_duration_ms == 25 && + other.rumble_calls == 0, "double-click must dispatch exactly its second selected-Wii pulse"); + now_ms = 2000; + process_rumble_timer(&g_rumble_timer); + uint64_t newer; + require(bluepad32_input_backend_wii_sample_request(1, &newer) && newer != token, + "finite patterns must release the cue ledger without reusing tokens"); + process_rumble_timer(&g_rumble_timer); + require(selected.last_rumble_duration_ms == 1000, "buzz must have a finite one-second driver timer"); + require(bluepad32_input_backend_wii_sample_request(0, &token), "stop must replace a running pattern"); + process_rumble_timer(&g_rumble_timer); + require(selected.last_rumble_duration_ms == 0 && + bluepad32_input_backend_wii_sample_result(token) == 1 && + bluepad32_input_backend_wii_sample_result(newer) == -1, + "stop must retire the old ledger and complete only after dispatch"); + const int stopped_calls = selected.rumble_calls; + now_ms += 3000; + process_rumble_timer(&g_rumble_timer); + require(selected.rumble_calls == stopped_calls, "stopped patterns must never replay"); +} + +void test_wii_bridge_cue_races() { + auto selected = wii_device(0); + selected.report_parser.play_dual_rumble = observe_wii_rumble; + bluepad32_input_backend_init(); + bluepad32_input_backend_select_wii_source(selected.conn.btaddr); + start_pairing_backend(); + require(platform_on_device_ready(&selected) == UNI_ERROR_SUCCESS, "selected Wii must connect"); + const auto connection = slot_snapshot(0); + bluepad32_input_backend_queue_profile_feedback( + 0, connection.connection_generation, 1, ControllerProfileConfirmationPolicy::kRumble); + uint64_t token; + require(bluepad32_input_backend_wii_sample_request(3, &token), "cue must wait behind profile feedback"); + process_rumble_timer(&g_rumble_timer); + require(selected.last_rumble_duration_ms == 75 && + bluepad32_input_backend_wii_sample_result(token) == 0, + "profile confirmation has priority and cannot count as cue dispatch"); + now_ms = 150; + during_wii_rumble = [] { bluepad32_input_backend_wii_sample_cancel(); }; + process_rumble_timer(&g_rumble_timer); + during_wii_rumble = nullptr; + require(bluepad32_input_backend_wii_sample_result(token) == -1, + "cancellation during driver dispatch must defeat its late completion"); + process_rumble_timer(&g_rumble_timer); + require(selected.last_rumble_duration_ms == 0, "canceled in-flight cue must receive a finite stop"); + wii_rumble_ready = false; + require(bluepad32_input_backend_wii_sample_request(1, &token), "topology setup may defer cue dispatch"); + const int calls = selected.rumble_calls; + process_rumble_timer(&g_rumble_timer); + require(bluepad32_input_backend_wii_sample_result(token) == 0 && selected.rumble_calls == calls, + "a Wii void-hook early return must not masquerade as dispatch"); + now_ms += 2000; + require(bluepad32_input_backend_wii_sample_result(token) == -1, "undispatched cue deadline must expire"); + wii_rumble_ready = true; + process_rumble_timer(&g_rumble_timer); + require(selected.rumble_calls == calls, "expired cue must not dispatch when setup finally completes"); + uint64_t replacement_token; + require(bluepad32_input_backend_wii_sample_request(2, &replacement_token) && replacement_token != token, + "expiration must permit a uniquely identified new request"); + during_wii_rumble = [] { platform_on_device_disconnected(g_slots[0].device); }; + process_rumble_timer(&g_rumble_timer); + during_wii_rumble = nullptr; + auto replacement = wii_device(0); + require(platform_on_device_ready(&replacement) == UNI_ERROR_SUCCESS, "replacement must connect"); + process_rumble_timer(&g_rumble_timer); + require(bluepad32_input_backend_wii_sample_result(replacement_token) == -1 && + replacement.rumble_calls == 0, + "late driver completion must never cross a physical generation"); + replacement.report_parser.play_dual_rumble = nullptr; + require(!bluepad32_input_backend_wii_sample_request(1, &token), + "a missing Wii rumble driver cannot accept a cue"); +} +#endif + void test_wii_orientation() { start_pairing_backend(); initialize_runtime_profile_storage(); @@ -6021,6 +6216,20 @@ void test_transport_background_scan() { int main(int argc, char** argv) { require(argc == 2, "scenario argument required"); const std::string scenario = argv[1]; +#ifdef SWITCH2_BRIDGE_WII_INPUT + if (scenario == "wii-bridge-sensors") { + test_wii_bridge_sensors(); + return 0; + } + if (scenario == "wii-bridge-cues") { + test_wii_bridge_cues(); + return 0; + } + if (scenario == "wii-bridge-cue-races") { + test_wii_bridge_cue_races(); + return 0; + } +#endif if (scenario == "transport-policy") { test_transport_mode_policy(); return 0; diff --git a/tests/bluepad32_native_stubs/parser/uni_hid_parser_wii.h b/tests/bluepad32_native_stubs/parser/uni_hid_parser_wii.h index 59dd916..2515320 100644 --- a/tests/bluepad32_native_stubs/parser/uni_hid_parser_wii.h +++ b/tests/bluepad32_native_stubs/parser/uni_hid_parser_wii.h @@ -15,6 +15,11 @@ typedef enum wii_flags { void uni_hid_parser_wii_set_mode(uni_hid_device_t* device, wii_mode_t mode); bool uni_hid_parser_wii_accel_snapshot( uni_hid_device_t*, int32_t[3], uint32_t*); +#ifdef SWITCH2_BRIDGE_WII_INPUT +bool uni_hid_parser_wii_gyro_snapshot( + uni_hid_device_t*, int32_t[3], uint32_t*); +bool uni_hid_parser_wii_rumble_ready(uni_hid_device_t*); +#endif bool uni_hid_parser_wii_nunchuk_accel_snapshot( uni_hid_device_t*, int32_t[3], uint32_t*); diff --git a/tests/switch2_native_imu_test.cpp b/tests/switch2_native_imu_test.cpp new file mode 100644 index 0000000..f0df928 --- /dev/null +++ b/tests/switch2_native_imu_test.cpp @@ -0,0 +1,821 @@ +#include "native_imu.h" + +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +using Vector = std::array; +using Quaternion = std::array; + +void expect(bool okay, const char* message) { + if (!okay) { + std::cerr << message << '\n'; + ++failures; + } +} + +// Deliberately decode bit-by-bit rather than mirroring the encoder's word +// boundaries. Double precision here is an independent host-side reference. +uint32_t bits(const uint8_t* bytes, unsigned start, unsigned width) { + uint32_t result = 0; + for (unsigned i = 0; i < width; ++i) { + result |= static_cast((bytes[(start + i) / 8] >> ((start + i) % 8)) & 1) << i; + } + return result; +} + +int64_t signed_bits(const uint8_t* bytes, unsigned start, unsigned width) { + const uint32_t value = bits(bytes, start, width); + return value & (UINT32_C(1) << (width - 1)) ? static_cast(value) - (INT64_C(1) << width) : value; +} + +struct Decoded { + Quaternion q{}; + Vector acceleration{}; + std::array acceleration_raw{}; + uint32_t counter = 0; + uint32_t elapsed = 0; + int64_t temperature = 0; +}; + +Decoded decode(const uint8_t* bytes) { + Decoded result; + expect(bytes[3] == 0x0c, "wire block must use the recovered one-sample format"); + result.counter = bits(bytes, 0, 12); + result.elapsed = bits(bytes, 12, 12); + result.temperature = signed_bits(bytes, 224, 16); + const unsigned largest = bits(bytes, 32, 3); + expect(largest < 4, "wire quaternion tag must identify an actual component"); + if (largest >= 4) return result; + Vector ratios{}; + double length_squared = 1.0; + for (unsigned i = 0; i < 3; ++i) { + ratios[i] = bits(bytes, 35 + 31 * i, 31) / 1073741824.0 - 1.0; + length_squared += ratios[i] * ratios[i]; + result.acceleration_raw[i] = signed_bits(bytes, 128 + 32 * i, 32); + result.acceleration[i] = result.acceleration_raw[i] / 268435456.0; + } + result.q[largest] = 1.0 / std::sqrt(length_squared); + for (unsigned i = 0; i < 3; ++i) result.q[(largest + i + 1) & 3] = ratios[i] * result.q[largest]; + return result; +} + +Vector rotate(const Quaternion& q, const Vector& v) { + const Vector cross{q[2] * v[2] - q[3] * v[1], q[3] * v[0] - q[1] * v[2], q[1] * v[1] - q[2] * v[0]}; + return {v[0] + 2.0 * (q[0] * cross[0] + q[2] * cross[2] - q[3] * cross[1]), + v[1] + 2.0 * (q[0] * cross[1] + q[3] * cross[0] - q[1] * cross[2]), + v[2] + 2.0 * (q[0] * cross[2] + q[1] * cross[1] - q[2] * cross[0])}; +} + +bool close(const Vector& a, const Vector& b, double tolerance = 0.00002) { + for (unsigned i = 0; i < 3; ++i) { + if (!std::isfinite(a[i]) || std::abs(a[i] - b[i]) > tolerance) return false; + } + return true; +} + +Quaternion normalized(const float input[4]) { + double squared = 0.0; + for (unsigned i = 0; i < 4; ++i) squared += static_cast(input[i]) * input[i]; + Quaternion result{}; + for (unsigned i = 0; i < 4; ++i) result[i] = input[i] / std::sqrt(squared); + return result; +} + +double camera_heading(const ProbeNativeMotion& motion) { + const Vector forward = rotate(normalized(motion.quaternion()), {0.0, 1.0, 0.0}); + return std::atan2(forward[1], forward[0]); +} + +double heading_change(const ProbeNativeMotion& motion, double initial_heading) { + return std::remainder(camera_heading(motion) - initial_heading, 2.0 * std::acos(-1.0)); +} + +void check_encoded_orientation(const float q[4], const float accel[3]) { + std::array guarded{}; + guarded.front() = 0x53; + guarded.back() = 0x79; + expect(probe_native_imu_pack(q, accel, 0xabc, 0xdef, -12345, guarded.data() + 1), "finite nonzero orientation must encode"); + expect(guarded.front() == 0x53 && guarded.back() == 0x79, "encoder must write exactly thirty bytes"); + const auto decoded = decode(guarded.data() + 1); + expect(decoded.counter == 0xabc && decoded.elapsed == 0xdef && decoded.temperature == -12345, + "wire counters and signed temperature must decode independently"); + for (unsigned axis = 0; axis < 3; ++axis) { + Vector basis{}; + basis[axis] = 1.0; + expect(close(rotate(decoded.q, basis), rotate(normalized(q), basis)), + "wire orientation must preserve physical rotation for every largest-component choice"); + } + expect(close(decoded.acceleration, {accel[0], accel[1], accel[2]}, 0.0000001), + "wire acceleration must preserve signed Q28 g units"); +} + +void codec_wire_edges() { + const float accel[3]{1.25f, -2.5f, 0.0625f}; + const float orientations[][4]{{4.0f, -1.0f, 2.0f, -3.0f}, {-0.5f, -3.0f, 0.25f, 1.0f}, + {1.0f, -2.0f, 4.0f, -0.5f}, {-1.0f, 0.5f, -2.0f, -4.0f}, + {1.0f, -1.0f, 1.0f, 1.0f}}; + for (const auto& q : orientations) check_encoded_orientation(q, accel); + const float large = std::numeric_limits::max(); + const float tiny = std::numeric_limits::denorm_min(); + const float large_q[4]{large, -large, large, -large}; + const float tiny_q[4]{tiny, -tiny, tiny, -tiny}; + check_encoded_orientation(large_q, accel); + check_encoded_orientation(tiny_q, accel); + + uint8_t bytes[30]{}; + const float identity[4]{1.0f, 0.0f, 0.0f, 0.0f}; + const float saturated[3]{large, -large, -8.0f}; + expect(probe_native_imu_pack(identity, saturated, 0, 4095, -32768, bytes), "finite out-of-range acceleration must saturate"); + const auto limits = decode(bytes); + expect(limits.acceleration_raw == std::array{INT32_MAX, INT32_MIN, INT32_MIN}, + "positive saturation must never wrap to negative acceleration"); + expect(limits.counter == 0 && limits.elapsed == 4095 && limits.temperature == -32768, + "wire signed and unsigned field boundaries must survive encoding"); + const float ties[3]{0.5f / 268435456.0f, 1.5f / 268435456.0f, -2.5f / 268435456.0f}; + const float fine_q[4]{1.0f, 5.5f / 1073741824.0f, -5.5f / 1073741824.0f, 0.0f}; + expect(probe_native_imu_pack(fine_q, ties, 0, 0, 0, bytes), "sub-count finite inputs must encode"); + expect(decode(bytes).acceleration_raw == std::array{0, 2, -2}, "Q28 halfway values use nearest-even rounding"); + expect(bits(bytes, 35, 31) == UINT32_C(0x40000006) && bits(bytes, 66, 31) == UINT32_C(0x3ffffffa), + "adding the ratio midpoint must not erase low quaternion bits"); +} + +void codec_rejects_invalid_inputs() { + float q[4]{1.0f, 0.0f, 0.0f, 0.0f}; + float accel[3]{0.0f, 0.0f, 1.0f}; + std::array output; + output.fill(0xa5); + const auto unchanged = output; + const float invalid[]{std::numeric_limits::quiet_NaN(), std::numeric_limits::infinity(), + -std::numeric_limits::infinity()}; + for (float value : invalid) { + q[2] = value; + expect(!probe_native_imu_pack(q, accel, 1, 1, 0, output.data()), "nonfinite quaternion must be rejected"); + q[2] = 0.0f; + accel[1] = value; + expect(!probe_native_imu_pack(q, accel, 1, 1, 0, output.data()), "nonfinite acceleration must be rejected, not saturated"); + accel[1] = 0.0f; + } + q[0] = 0.0f; + expect(!probe_native_imu_pack(q, accel, 1, 1, 0, output.data()), "zero quaternion cannot identify a real orientation"); + q[0] = 1.0f; + expect(!probe_native_imu_pack(q, accel, 4096, 1, 0, output.data()), "counter overflow must fail rather than overwrite elapsed bits"); + expect(!probe_native_imu_pack(q, accel, 1, 4096, 0, output.data()), "elapsed overflow must fail rather than overwrite format bits"); + expect(output == unchanged, "failed encoding must leave the caller's pending packet unchanged"); +} + +struct Rig { + ProbeNativeMotion motion; + ProbeNativeMotionSample sample{}; + uint32_t now; + uint32_t generation = 1; + static constexpr float residual[3]{0.4f, -0.3f, 0.2f}; + + explicit Rig(uint32_t start = 0) : now(start) { + sample.accel_valid = sample.gyro_valid = true; + sample.accel_g[2] = 1.0f; + rest(); + } + void rest() { + for (unsigned i = 0; i < 3; ++i) sample.gyro_dps[i] = residual[i]; + } + void fresh(uint32_t elapsed = 25000, bool accel = true, bool gyro = true) { + now += elapsed; + if (accel) { + ++sample.accel_sequence; + sample.accel_us = now; + } + if (gyro) { + ++sample.gyro_sequence; + sample.gyro_us = now; + } + motion.update(now, generation, sample); + } + void settle() { + for (unsigned i = 0; i < 65; ++i) fresh(); + expect(motion.ready(), "fresh stationary sensors must finish residual bias calibration"); + } + Decoded packet() { + uint8_t bytes[30]{}; + expect(motion.ready(), "only calibrated fresh motion may be packed for the consumer"); + expect(probe_native_imu_pack(motion.quaternion(), motion.acceleration(), 0, 0, 0, bytes), "live motion must be encodable"); + return decode(bytes); + } +}; + +void startup_needs_count_and_stillness() { + Rig fast; + fast.fresh(0); + for (unsigned i = 0; i < 63; ++i) fast.fresh(1000); + expect(!fast.motion.ready(), "sixty-four packets alone cannot replace 1.5 seconds of stillness"); + for (unsigned i = 0; i < 56; ++i) fast.fresh(); + expect(!fast.motion.ready(), "calibration must not finish before the stillness duration"); + fast.fresh(37000); + expect(fast.motion.ready(), "a stationary window may finish at exactly 1.5 seconds"); + + Rig slow; + slow.fresh(0); + for (unsigned i = 0; i < 62; ++i) slow.fresh(30000); + expect(!slow.motion.ready(), "elapsed stillness cannot replace sixty-four distinct gyro samples"); + slow.fresh(30000); + expect(slow.motion.ready(), "the sixty-fourth stationary sample can finish calibration"); + expect(close({slow.motion.bias()[0], slow.motion.bias()[1], slow.motion.bias()[2]}, + {Rig::residual[0], Rig::residual[1], Rig::residual[2]}, 0.000001), + "calibration must learn the selected sensor's residual bias"); +} + +void quantized_wii_bias_calibrates_and_integrates() { + Rig rig; + constexpr float device_bias[3]{-13.0625f, 12.4375f, -13.125f}; + constexpr int noise_q10[8]{-576, 192, -320, 576, -192, 320, -64, 64}; + const Vector gravity{8352.0 / 8192.0, 290.0 / 8192.0, -298.0 / 8192.0}; + // Deterministic Wii-scale Q13 steps and Q10 noise, with accel and gyro + // arriving independently at 200 / 100 Hz. Neither noise nor bias is motion. + for (unsigned i = 0; i < 320 && !rig.motion.ready(); ++i) { + rig.sample.accel_g[0] = (8352 + (i & 1 ? 80 : -80)) / 8192.0f; + rig.sample.accel_g[1] = (290 + (i & 2 ? 40 : -40)) / 8192.0f; + rig.sample.accel_g[2] = (-298 + (i & 4 ? 43 : -43)) / 8192.0f; + if (i % 2 == 0) { + for (unsigned axis = 0; axis < 3; ++axis) { + rig.sample.gyro_dps[axis] = device_bias[axis] + noise_q10[(i / 2 + axis * 3) % 8] / 1024.0f; + } + } + rig.fresh(5000, true, i % 2 == 0); + } + expect(rig.motion.ready(), "quantized stationary Wii sensors with a large own-device bias must calibrate"); + expect(close({rig.motion.bias()[0], rig.motion.bias()[1], rig.motion.bias()[2]}, + {device_bias[0], device_bias[1], device_bias[2]}, 0.01), + "stationary variation must average into the measured bias, not a nominal or donor zero"); + const Quaternion reference = rig.packet().q; + const double gravity_length = std::sqrt(gravity[0] * gravity[0] + gravity[1] * gravity[1] + gravity[2] * gravity[2]); + expect(close(rotate(reference, gravity), {0.0, 0.0, gravity_length}, 0.0002), + "quantized gravity must establish the physical reference without rescaling acceleration"); + for (unsigned axis = 0; axis < 3; ++axis) { + rig.sample.gyro_dps[axis] = device_bias[axis]; + rig.sample.accel_g[axis] = static_cast(gravity[axis]); + } + rig.fresh(0); + for (unsigned i = 0; i < 100; ++i) rig.fresh(10000); + expect(close(rotate(rig.packet().q, {1.0, 0.0, 0.0}), rotate(reference, {1.0, 0.0, 0.0}), 0.001), + "learned large residual bias must not become stationary orientation drift"); + rig.sample.gyro_dps[2] += 90.0f; + rig.fresh(0); + for (unsigned i = 1; i <= 100; ++i) { + const double angle = i * std::acos(-1.0) / 200.0; + rig.sample.accel_g[0] = static_cast(std::cos(angle) * gravity[0] + std::sin(angle) * gravity[1]); + rig.sample.accel_g[1] = static_cast(-std::sin(angle) * gravity[0] + std::cos(angle) * gravity[1]); + rig.fresh(10000); + } + expect(close(rotate(rig.packet().q, {1.0, 0.0, 0.0}), rotate(reference, {0.0, 1.0, 0.0}), 0.001), + "one second of body rotation must subtract the measured Wii bias before integration"); +} + +void measured_gravity_sets_reference() { + const float poses[][3]{{1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, -1.0f}, + {0.000001f, 0.000002f, -1.0f}, {0.3f, 0.4f, 0.8660254f}}; + for (const auto& pose : poses) { + Rig rig; + for (unsigned i = 0; i < 3; ++i) rig.sample.accel_g[i] = pose[i]; + rig.settle(); + const auto decoded = rig.packet(); + expect(close(rotate(decoded.q, decoded.acceleration), {0.0, 0.0, 1.0}), + "measured gravity, including anti-parallel gravity, must align with reference +Z"); + expect(close(decoded.acceleration, {pose[0], pose[1], pose[2]}, 0.0000001), + "reference initialization must not replace the real body acceleration"); + } +} + +void bias_corrected_body_rotation_reaches_wire() { + Rig rig; + rig.sample.accel_g[0] = 1.0f; + rig.sample.accel_g[2] = 0.0f; + rig.settle(); + for (unsigned i = 0; i < 100; ++i) rig.fresh(10000); + expect(close(rotate(rig.packet().q, {1.0, 0.0, 0.0}), {0.0, 0.0, 1.0}), + "stationary residual bias must not rotate the initialized orientation"); + rig.sample.gyro_dps[2] += 90.0f; + rig.fresh(0); + for (unsigned i = 1; i <= 100; ++i) { + const double angle = i * std::acos(-1.0) / 200.0; + rig.sample.accel_g[0] = static_cast(std::cos(angle)); + rig.sample.accel_g[1] = static_cast(-std::sin(angle)); + rig.fresh(10000); + } + const auto turned = rig.packet(); + expect(close(rotate(turned.q, {1.0, 0.0, 0.0}), {0.0, 1.0, 0.0}) && + close(rotate(turned.q, {0.0, 1.0, 0.0}), {0.0, 0.0, -1.0}) && + close(rotate(turned.q, {0.0, 0.0, 1.0}), {-1.0, 0.0, 0.0}), + "one second of corrected body-Z rotation must compose after the nonidentity gravity alignment"); + rig.sample.accel_g[0] = 1.6f; + rig.sample.accel_g[1] = -0.3f; + rig.sample.accel_g[2] = 0.8f; + rig.fresh(0); + expect(close(rig.packet().acceleration, {1.6, -0.3, 0.8}, 0.0000001), "ready packets must retain real dynamic acceleration"); + expect(close({rig.motion.bias()[0], rig.motion.bias()[1], rig.motion.bias()[2]}, + {Rig::residual[0], Rig::residual[1], Rig::residual[2]}, 0.000001), + "motion after calibration must not relearn or chase the gyro bias"); +} + +void elapsed_time_not_packet_count_controls_rotation() { + for (uint32_t interval : {5000u, 25000u}) { + Rig rig; + rig.settle(); + rig.sample.gyro_dps[2] += 120.0f; + rig.fresh(0); + for (uint32_t elapsed = interval; elapsed <= 1000000; elapsed += interval) { + rig.fresh(interval, true, elapsed % 100000 == 0); + } + expect(close(rotate(rig.packet().q, {1.0, 0.0, 0.0}), {-0.5, std::sqrt(0.75), 0.0}), + "a fresh held gyro rate must integrate elapsed time regardless of polling cadence"); + } + Rig split; + split.settle(); + split.sample.gyro_dps[2] += 90.0f; + ++split.sample.gyro_sequence; + split.sample.gyro_us = split.now + 10000; + split.fresh(40000, true, false); + const double angle = 2.7 * std::acos(-1.0) / 180.0; + expect(close(rotate(split.packet().q, {1.0, 0.0, 0.0}), {std::cos(angle), std::sin(angle), 0.0}), + "a rate arriving inside an update interval must only affect time after its receipt"); +} + +void moving_startup_does_not_calibrate() { + for (unsigned movement = 0; movement < 4; ++movement) { + Rig rig; + for (unsigned i = 0; i < 100; ++i) { + rig.rest(); + rig.sample.accel_g[0] = 0.0f; + rig.sample.accel_g[1] = 0.0f; + rig.sample.accel_g[2] = 1.0f; + if (movement == 0) { + // A real slow body-X turn changes gravity even with a constant + // gyro reading. Its per-packet tilt is smaller than Wii noise. + const float angle = static_cast(i) * 0.025f * 2.0f * static_cast(std::acos(-1.0) / 180.0); + rig.sample.gyro_dps[0] += 2.0f; + rig.sample.accel_g[1] = std::sin(angle); + rig.sample.accel_g[2] = std::cos(angle); + } + if (movement == 1) rig.sample.accel_g[2] = 0.5f; + if (movement == 2) rig.sample.accel_g[0] = i & 1 ? 0.04f : -0.04f; + if (movement == 3) rig.sample.gyro_dps[0] = i & 1 ? 1.0f : -1.0f; + rig.fresh(); + } + expect(!rig.motion.ready(), "moving startup cannot be mistaken for a stationary calibration window"); + rig.rest(); + rig.sample.accel_g[0] = 0.0f; + rig.sample.accel_g[1] = 0.0f; + rig.sample.accel_g[2] = 1.0f; + for (unsigned i = 0; i < 128; ++i) rig.fresh(); + expect(rig.motion.ready(), "a new stationary window must recover after changing motion ends"); + } + Rig contaminated; + for (unsigned i = 0; i < 40; ++i) contaminated.fresh(); + contaminated.sample.gyro_dps[0] = 4.0f; + contaminated.fresh(); + contaminated.rest(); + for (unsigned i = 0; i < 40; ++i) contaminated.fresh(); + expect(!contaminated.motion.ready(), "a gyro impulse must discard, not pool, the partial bias window"); + for (unsigned i = 0; i < 24; ++i) contaminated.fresh(); + expect(contaminated.motion.ready(), "an uncontaminated replacement window must eventually calibrate"); + + Rig interleaved; + for (unsigned i = 0; i < 55; ++i) interleaved.fresh(); + interleaved.sample.accel_g[0] = 0.1f; + interleaved.fresh(5000, true, false); + interleaved.sample.accel_g[0] = 0.0f; + interleaved.fresh(5000, true, false); + for (unsigned i = 0; i < 20; ++i) interleaved.fresh(); + expect(!interleaved.motion.ready(), "acceleration-only movement must reset the gyro calibration window too"); + interleaved.settle(); +} + +void duplicate_sequences_and_interleaved_recovery() { + Rig rig; + rig.fresh(0); + for (unsigned i = 0; i < 400; ++i) { + // A caller cannot renew sensor lifetime by relabelling receipt time + // while leaving the actual parser sequence unchanged. + rig.sample.accel_us = rig.sample.gyro_us = rig.now + 5000; + rig.fresh(5000, false, false); + } + expect(!rig.motion.ready(), "duplicate samples cannot establish calibrated sensor readiness"); + for (unsigned i = 0; i < 128; ++i) rig.fresh(25000, i % 2 == 0, i % 2 != 0); + expect(rig.motion.ready(), "fresh independently interleaved sensors must recover after a stale reset"); + rig.sample.gyro_dps[2] += 100.0f; + rig.fresh(10000, false, false); + expect(close(rotate(rig.packet().q, {1.0, 0.0, 0.0}), {1.0, 0.0, 0.0}), + "mutating a duplicate sequence must not inject a new angular rate"); +} + +void lifecycle_invalidates_bias_and_orientation() { + for (unsigned fault = 0; fault < 7; ++fault) { + Rig rig; + rig.settle(); + if (fault == 0) rig.sample.accel_valid = false; + if (fault == 1) rig.sample.gyro_valid = false; + if (fault == 2) rig.sample.accel_g[0] = std::numeric_limits::quiet_NaN(); + if (fault == 3) rig.sample.gyro_dps[0] = std::numeric_limits::infinity(); + if (fault == 4) ++rig.generation; + if (fault == 5) rig.motion.reset(); + rig.fresh(fault == 6 ? 50001 : 1000); + expect(!rig.motion.ready(), "lifecycle or invalid sensor input must fail closed immediately"); + rig.sample.accel_valid = rig.sample.gyro_valid = true; + rig.sample.accel_g[0] = rig.sample.accel_g[1] = 0.0f; + rig.sample.accel_g[2] = -1.0f; + rig.sample.gyro_dps[0] = -0.25f; + rig.sample.gyro_dps[1] = 0.1f; + rig.sample.gyro_dps[2] = -0.35f; + rig.settle(); + expect(close({rig.motion.bias()[0], rig.motion.bias()[1], rig.motion.bias()[2]}, {-0.25, 0.1, -0.35}, 0.000001), + "recovery must calibrate a new bias instead of borrowing the previous connection's bias"); + expect(close(rotate(rig.packet().q, {0.0, 0.0, -1.0}), {0.0, 0.0, 1.0}), + "recovery must align the new physical pose instead of replaying old orientation"); + } +} + +void stale_boundaries_and_hidden_gaps() { + for (bool stale_gyro : {false, true}) { + Rig rig; + rig.settle(); + rig.fresh(50000, stale_gyro, !stale_gyro); + rig.fresh(50000, stale_gyro, !stale_gyro); + rig.fresh(49999, stale_gyro, !stale_gyro); + expect(rig.motion.ready(), "a held sensor remains usable strictly below the 150ms age limit"); + rig.fresh(1, stale_gyro, !stale_gyro); + expect(!rig.motion.ready(), "either sensor reaching the 150ms limit must invalidate motion"); + rig.settle(); + } + Rig hidden; + hidden.settle(); + hidden.sample.gyro_dps[2] += 90.0f; + hidden.fresh(0); + hidden.fresh(50000, false, false); + hidden.fresh(50000, false, false); + expect(hidden.motion.ready(), "a 50ms update gap is still within the integration limit"); + hidden.fresh(50000); + expect(hidden.motion.ready(), "a replacement exactly at expiry must preserve the continuously covered interval"); + hidden.fresh(50000, false, false); + hidden.fresh(50000, false, false); + hidden.fresh(49999, false, false); + hidden.fresh(2); + expect(!hidden.motion.ready(), "fresh replacements cannot hide an intervening stale sample interval"); + hidden.rest(); + hidden.settle(); + expect(close(rotate(hidden.packet().q, {1.0, 0.0, 0.0}), {1.0, 0.0, 0.0}), + "stale angular displacement must not replay after recalibration"); +} + +void clocks_sequences_and_connections_wrap() { + Rig rig(UINT32_MAX - 2200000u); + rig.sample.accel_sequence = rig.sample.gyro_sequence = UINT32_MAX - 30u; + rig.settle(); + rig.sample.gyro_dps[2] += 90.0f; + rig.fresh(0); + for (unsigned i = 0; i < 80; ++i) rig.fresh(12500); + expect(close(rotate(rig.packet().q, {1.0, 0.0, 0.0}), {0.0, 1.0, 0.0}), + "microsecond rollover must preserve one second of physical angular displacement"); + ++rig.generation; + rig.sample.accel_sequence = rig.sample.gyro_sequence = 0; + rig.rest(); + rig.fresh(0); + expect(!rig.motion.ready(), "a new connection cannot inherit readiness even if it reuses sample identities"); + rig.settle(); + expect(close(rotate(rig.packet().q, {1.0, 0.0, 0.0}), {1.0, 0.0, 0.0}), + "a new connection must establish its own reference orientation"); + + Rig calibration_wrap(UINT32_MAX - 750000u); + calibration_wrap.settle(); + expect(calibration_wrap.motion.ready(), "the stationary window must span microsecond rollover safely"); +} + +void fresh_gravity_bounds_warm_gyro_tilt_drift() { + Rig normal, fast; + for (Rig* rig : {&normal, &fast}) { + rig->sample.accel_g[0] = 1.0f; + rig->sample.accel_g[2] = 0.0f; + rig->settle(); + // The console trace drifted roughly 0.6 degrees/s after startup. + rig->sample.gyro_dps[1] += 0.6f; + rig->fresh(0); + } + double maximum_tilt = 0.0; + for (unsigned millisecond = 1; millisecond <= 60000; ++millisecond) { + fast.fresh(1000, millisecond % 10 == 0, millisecond % 10 == 0); + if (millisecond % 10 == 0) normal.fresh(10000); + if (millisecond % 1000 == 0) { + const Vector gravity = rotate(normal.packet().q, {1.0, 0.0, 0.0}); + const double tilt = std::atan2(std::hypot(gravity[0], gravity[1]), gravity[2]); + if (tilt > maximum_tilt) maximum_tilt = tilt; + } + } + expect(maximum_tilt < std::acos(-1.0) / 180.0, + "fresh stationary gravity must keep warming gyro tilt drift below one degree"); + expect(close(rotate(normal.packet().q, {1.0, 0.0, 0.0}), + rotate(fast.packet().q, {1.0, 0.0, 0.0}), 0.0002), + "duplicate accelerometer polling must not strengthen gravity correction"); +} + +void dynamic_acceleration_does_not_steer_orientation() { + Rig rig; + rig.settle(); + rig.sample.gyro_dps[2] += 60.0f; + rig.sample.accel_g[0] = 2.0f; + rig.fresh(0); + for (unsigned i = 0; i < 100; ++i) rig.fresh(10000); + const auto packet = rig.packet(); + expect(close(rotate(packet.q, {1.0, 0.0, 0.0}), {0.5, std::sqrt(0.75), 0.0}), + "non-gravity acceleration must not steer gyro orientation"); + expect(close(packet.acceleration, {2.0, 0.0, 1.0}), + "gravity correction must not replace the consumer's dynamic acceleration"); +} + +void optical_heading_bounds_drift_without_polling_gain() { + Rig slow, frequent, gyro_only; + for (Rig* rig : {&slow, &frequent, &gyro_only}) { + rig->settle(); + rig->sample.gyro_dps[2] += 0.6f; + rig->fresh(0); + } + const double initial = camera_heading(slow.motion); + slow.motion.observe_optical_heading(slow.now, 1, 0, slow.now, 0.2f, true); + frequent.motion.observe_optical_heading(frequent.now, 1, 0, frequent.now, 0.2f, true); + double maximum_drift = 0.0; + for (uint32_t step = 1; step <= 6000; ++step) { + slow.fresh(10000); + frequent.fresh(10000); + gyro_only.fresh(10000); + // The same physical reference at 10Hz and 50Hz, with extra polling of + // duplicate 50Hz reports, must give essentially the same drift bound. + if (step % 10 == 0) { + slow.motion.observe_optical_heading(slow.now, 1, step / 10, slow.now, 0.2f, true); + } + frequent.motion.observe_optical_heading(frequent.now, 1, step / 2, + frequent.now, 0.2f, true); + if (step % 10 == 0) { + const double drift = std::abs(heading_change(slow.motion, initial)); + if (drift > maximum_drift) maximum_drift = drift; + } + } + expect(maximum_drift < 1.3 * std::acos(-1.0) / 180.0, + "stable optical bearing must bound a minute of warming gyro yaw drift"); + expect(std::abs(heading_change(slow.motion, camera_heading(frequent.motion))) < 0.0002, + "optical correction strength must follow sample time, not sample or polling count"); + expect(std::abs(heading_change(gyro_only.motion, initial) - 36.0 * std::acos(-1.0) / 180.0) < 0.0002, + "without optical observations gravity must leave yaw gyro-derived"); +} + +void optical_anchor_preserves_pose_and_corrects_only_world_yaw() { + Rig rig; + rig.sample.accel_g[0] = 0.3f; + rig.sample.accel_g[1] = 0.4f; + rig.sample.accel_g[2] = std::sqrt(0.75f); + rig.settle(); + // Establish arbitrary nonzero world yaw while preserving this physical tilt. + for (unsigned i = 0; i < 3; ++i) rig.sample.gyro_dps[i] += 60.0f * rig.sample.accel_g[i]; + rig.fresh(0); + for (unsigned i = 0; i < 20; ++i) rig.fresh(25000); + rig.rest(); + rig.fresh(0); + const Quaternion initial = normalized(rig.motion.quaternion()); + const double initial_heading = camera_heading(rig.motion); + rig.motion.observe_optical_heading(rig.now, 1, 1, rig.now, 0.45f, true); + expect(normalized(rig.motion.quaternion()) == initial, + "the first optical sample must preserve arbitrary existing yaw and tilt exactly"); + rig.sample.accel_g[0] = 1.8f; + rig.sample.accel_g[1] = -0.2f; + rig.sample.accel_g[2] = 0.6f; + rig.fresh(0); + for (uint32_t step = 1; step <= 400; ++step) { + rig.fresh(25000); + if (step % 4 == 0) { + rig.motion.observe_optical_heading(rig.now, 1, step / 4 + 1, rig.now, 0.8f, true); + } + } + expect(std::abs(heading_change(rig.motion, initial_heading) + 0.35) < 0.004, + "increasing aim-right optical yaw must converge to negative world yaw, not reanchor away motion"); + const Quaternion corrected = normalized(rig.motion.quaternion()); + for (unsigned axis = 0; axis < 3; ++axis) { + Vector basis{}; + basis[axis] = 1.0; + expect(std::abs(rotate(initial, basis)[2] - rotate(corrected, basis)[2]) < 0.000002, + "optical correction must preserve every body axis's gravity-aligned tilt"); + } + expect(close(rig.packet().acceleration, {1.8, -0.2, 0.6}, 0.0000001), + "optical correction must retain real dynamic acceleration in the native packet"); + expect(close({rig.motion.bias()[0], rig.motion.bias()[1], rig.motion.bias()[2]}, + {Rig::residual[0], Rig::residual[1], Rig::residual[2]}, 0.000001), + "optical correction must not modify the calibrated raw gyro bias"); +} + +void optical_duplicates_and_hidden_intervals_do_not_gain_weight() { + Rig rig; + rig.settle(); + const double initial_heading = camera_heading(rig.motion); + uint32_t sequence = 10; + rig.motion.observe_optical_heading(rig.now, 1, sequence, rig.now, 0.0f, true); + rig.sample.gyro_dps[2] += 30.0f; + rig.fresh(0); + for (unsigned i = 0; i < 40; ++i) { + rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, 0.0f, false); + } + rig.rest(); + rig.fresh(0); + expect(std::abs(heading_change(rig.motion, initial_heading) - std::acos(-1.0) / 6.0) < 0.00002, + "hidden or inferred optical reports must not invent a heading correction"); + const double hidden_heading = camera_heading(rig.motion); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, 0.0f, true); + expect(std::abs(heading_change(rig.motion, hidden_heading)) < 0.000001, + "reacquisition must not spend correction weight accumulated while hidden"); + for (unsigned i = 0; i < 4; ++i) rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, 0.0f, true); + expect(heading_change(rig.motion, hidden_heading) < -0.02, + "continuous reacquisition must correct toward the retained original relative anchor"); + const double corrected_heading = camera_heading(rig.motion); + for (unsigned i = 0; i < 200; ++i) { + rig.fresh(1000); + // A changed value and a newly labelled timestamp are still one packet. + rig.motion.observe_optical_heading(rig.now, 1, sequence, rig.now, -1.0f, true); + } + expect(std::abs(heading_change(rig.motion, corrected_heading)) < 0.000001, + "duplicate optical sequence identities cannot strengthen correction or inject changed bearings"); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, 0.0f, true); + expect(std::abs(heading_change(rig.motion, corrected_heading)) < 0.000001, + "duplicate timestamps cannot keep optical validity alive across a stale interval"); +} + +void optical_rejects_bad_samples_and_clock_order() { + Rig rig; + rig.settle(); + rig.motion.observe_optical_heading(rig.now, 1, 1, rig.now, 0.0f, true); + uint32_t sequence = 1; + const double initial_heading = camera_heading(rig.motion); + // Each rejected identity must remain rejected if its fields are rewritten. + for (unsigned fault = 0; fault < 4; ++fault) { + for (unsigned i = 0; i < 4; ++i) rig.fresh(25000); + const float bearing = fault == 0 ? std::numeric_limits::quiet_NaN() : 1.0f; + const uint32_t timestamp = fault == 1 ? rig.now - 150000u : + fault == 2 ? rig.now + 1u : rig.now; + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, timestamp, bearing, fault != 3); + for (unsigned i = 0; i < 4; ++i) { + rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, 1, sequence, rig.now, 1.0f, true); + } + expect(std::abs(heading_change(rig.motion, initial_heading)) < 0.000001, + "nonfinite, stale, future or unavailable optical identities cannot later be relabelled valid"); + } + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, 0.0f, true); + const uint32_t last_timestamp = rig.now; + rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, last_timestamp - 1u, 1.0f, true); + rig.motion.observe_optical_heading(rig.now, 1, sequence - 1u, rig.now, 1.0f, true); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, last_timestamp, 1.0f, true); + expect(std::abs(heading_change(rig.motion, initial_heading)) < 0.000001, + "backwards clocks, out-of-order sequences and zero-time samples must not correct heading"); + // A subsequent ordered sample still contributes its own sensor-time + // interval after the rejected observations. + rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now - 1u, 1.0f, true); + expect(heading_change(rig.motion, initial_heading) < -0.02, + "a later fresh unique optical sample must still correct after rejected clock order"); +} + +void optical_generation_and_motion_lifecycle_reanchor() { + for (unsigned transition = 0; transition < 4; ++transition) { + Rig rig; + rig.settle(); + rig.motion.observe_optical_heading(rig.now, UINT32_MAX, 100, rig.now, 0.0f, true); + for (unsigned i = 0; i < 4; ++i) rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, UINT32_MAX, 101, rig.now, 1.0f, true); + expect(heading_change(rig.motion, std::acos(-1.0) / 2.0) < -0.04, + "the old optical reference must be active before lifecycle replacement"); + uint32_t optical_generation = UINT32_MAX; + uint32_t sequence = 102; + if (transition == 0) { + optical_generation = 0; + sequence = 0; + } else { + if (transition == 1) { + rig.sample.gyro_valid = false; + rig.fresh(0); + rig.sample.gyro_valid = true; + } + if (transition == 2) rig.motion.reset(); + if (transition == 3) ++rig.generation; + rig.settle(); + } + const Quaternion before = normalized(rig.motion.quaternion()); + const double heading = camera_heading(rig.motion); + rig.motion.observe_optical_heading(rig.now, optical_generation, sequence, rig.now, -0.8f, true); + expect(normalized(rig.motion.quaternion()) == before, + "optical generation, motion invalidation, reset and reconnect must anchor without an initial jump"); + for (unsigned i = 0; i < 40; ++i) { + rig.fresh(25000); + if (i % 4 == 3) { + rig.motion.observe_optical_heading(rig.now, optical_generation, ++sequence, rig.now, -0.8f, true); + } + } + expect(std::abs(heading_change(rig.motion, heading)) < 0.000002, + "a replaced optical reference must not pull toward the preceding lifecycle's bearing"); + } +} + +void optical_angles_and_sample_clocks_wrap() { + Rig rig(UINT32_MAX - 1750000u); + rig.settle(); + const float pi = std::acos(-1.0f); + const float initial_bearing = pi - 0.02f; + const double initial_heading = camera_heading(rig.motion); + uint32_t sequence = UINT32_MAX - 1u; + rig.motion.observe_optical_heading(rig.now, 1, sequence, rig.now, initial_bearing, true); + // Matching physical yaw and optical motion cross both wrap boundaries. + rig.sample.gyro_dps[2] -= 30.0f; + rig.fresh(0); + for (unsigned step = 1; step <= 20; ++step) { + rig.fresh(25000); + if (step % 4 == 0) { + const float bearing = std::remainder(initial_bearing + step * 0.025f * pi / 6.0f, 2.0f * pi); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, bearing, true); + } + } + expect(std::abs(heading_change(rig.motion, initial_heading) + std::acos(-1.0) / 12.0) < 0.00002, + "optical angle, sequence and microsecond wrap must preserve intentional yaw direction without a jump"); + rig.rest(); + rig.fresh(0); + const float final_bearing = std::remainder(initial_bearing + pi / 12.0f + 0.1f, 2.0f * pi); + for (unsigned step = 1; step <= 400; ++step) { + rig.fresh(25000); + if (step % 4 == 0) { + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, final_bearing, true); + } + } + expect(std::abs(heading_change(rig.motion, initial_heading) + std::acos(-1.0) / 12.0 + 0.1) < 0.001, + "wrapped optical observations must continue correcting toward the original relative anchor"); +} + +void optical_vertical_forward_defers_the_anchor() { + Rig rig; + rig.sample.accel_g[1] = 1.0f; + rig.sample.accel_g[2] = 0.0f; + rig.settle(); + const Quaternion vertical = normalized(rig.motion.quaternion()); + uint32_t sequence = 0; + for (unsigned i = 0; i < 20; ++i) { + rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, i * 0.1f, true); + } + expect(close(rotate(normalized(rig.motion.quaternion()), {1.0, 0.0, 0.0}), + rotate(vertical, {1.0, 0.0, 0.0})), + "near-vertical camera forward must reject ill-conditioned optical yaw"); + // Tilt smoothly away from vertical with matching physical gravity. + rig.sample.gyro_dps[0] -= 90.0f; + rig.fresh(0); + for (unsigned i = 1; i <= 40; ++i) { + const float angle = i * std::acos(-1.0f) / 80.0f; + rig.sample.accel_g[1] = std::cos(angle); + rig.sample.accel_g[2] = std::sin(angle); + rig.fresh(25000); + } + rig.rest(); + rig.fresh(0); + const Quaternion horizontal = normalized(rig.motion.quaternion()); + const double heading = camera_heading(rig.motion); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, -0.6f, true); + expect(normalized(rig.motion.quaternion()) == horizontal, + "the first well-conditioned optical observation must establish the anchor without jumping"); + for (unsigned i = 0; i < 4; ++i) rig.fresh(25000); + rig.motion.observe_optical_heading(rig.now, 1, ++sequence, rig.now, -0.3f, true); + expect(heading_change(rig.motion, heading) < -0.01, + "heading correction must recover after the forward projection leaves vertical"); +} + +} // namespace + +int main() { + codec_wire_edges(); + codec_rejects_invalid_inputs(); + startup_needs_count_and_stillness(); + quantized_wii_bias_calibrates_and_integrates(); + measured_gravity_sets_reference(); + bias_corrected_body_rotation_reaches_wire(); + elapsed_time_not_packet_count_controls_rotation(); + moving_startup_does_not_calibrate(); + duplicate_sequences_and_interleaved_recovery(); + lifecycle_invalidates_bias_and_orientation(); + stale_boundaries_and_hidden_gaps(); + clocks_sequences_and_connections_wrap(); + fresh_gravity_bounds_warm_gyro_tilt_drift(); + dynamic_acceleration_does_not_steer_orientation(); + optical_heading_bounds_drift_without_polling_gain(); + optical_anchor_preserves_pose_and_corrects_only_world_yaw(); + optical_duplicates_and_hidden_intervals_do_not_gain_weight(); + optical_rejects_bad_samples_and_clock_order(); + optical_generation_and_motion_lifecycle_reanchor(); + optical_angles_and_sample_clocks_wrap(); + optical_vertical_forward_defers_the_anchor(); + return failures ? 1 : 0; +} diff --git a/tests/switch2_wii_bridge_test.cpp b/tests/switch2_wii_bridge_test.cpp new file mode 100644 index 0000000..6ae3f60 --- /dev/null +++ b/tests/switch2_wii_bridge_test.cpp @@ -0,0 +1,263 @@ +#include +#include +#include +#include +#include + +#include "controller_input.h" +#include "input/bluepad32_input_backend.h" +#include "input/wii_ir_pointer.h" +#include "platform/pico/bootsel_pairing_button.h" +#include "platform/pico/system_clock.h" +#include "profile/controller_profile_runtime.h" +#include "pico/stdlib.h" + +static uint64_t now_us; +static uint32_t stage; +static Bluepad32WiiBridgeSnapshot source; +static bool swap_faces = true; +static bool publish_during_snapshot; +static uint32_t ir_sequence; +static uint32_t sensor_sequence; +static uint32_t last_sensor_us; +static uint16_t raw_ir_buttons; +static uint16_t ir_x[4] = {420, 620, 0, 0}; +static uint16_t ir_y[4] = {384, 384, 0, 0}; +static uint8_t ir_mask = 3; +static probe_controller_input controls; +static uint8_t packet[63]; +static const int32_t bias_q10[3] = {1024, -2048, 512}; + +uint32_t time_us_32() { return static_cast(now_us); } +absolute_time_t get_absolute_time() { return now_us; } +uint32_t to_ms_since_boot(absolute_time_t time) { return static_cast(time / 1000); } +absolute_time_t make_timeout_time_ms(uint32_t ms) { return now_us + 1000ull * ms; } +bool time_reached(absolute_time_t deadline) { return now_us >= deadline; } +void sleep_ms(uint32_t ms) { now_us += 1000ull * ms; } +void system_clock_initialize() {} +extern "C" int probe_debug_printf(const char*, ...) { return 0; } +BootselPairingButtonEvent bootsel_pairing_button_task() { return BootselPairingButtonEvent::kNone; } + +void bluepad32_input_backend_init() { stage = 1; wii_ir_pointer_init(); } +void bluepad32_input_backend_start() { stage = 2; } +void bluepad32_input_backend_diagnostics(Bluepad32BackendDiagnostics* out) { *out = {}; out->initialization_stage = stage; } +void bluepad32_input_backend_open_pairing_window() {} +void bluepad32_input_backend_select_wii_source(const uint8_t[6]) { wii_ir_pointer_reset(); } +void bluepad32_input_backend_wii_snapshot(Bluepad32WiiBridgeSnapshot* out) { + if (publish_during_snapshot) { + // Model Core1 publishing after Core0 entered the snapshot call. + now_us += 300; + source.accel_sequence = source.gyro_sequence = ++sensor_sequence; + source.received_us = source.accel_received_us = source.gyro_received_us = time_us_32(); + } + *out = source; +} +bool bluepad32_input_backend_set_wii_orientation(const ControllerIdentity&, uint32_t, bool) { return false; } +void bluepad32_input_backend_report_sent(uint8_t) {} +bool bluepad32_input_backend_wii_sample_request(uint8_t, uint64_t*) { return false; } +int bluepad32_input_backend_wii_sample_result(uint64_t) { return -1; } +void bluepad32_input_backend_wii_sample_cancel() {} +void bluepad32_input_backend_queue_profile_feedback(uint8_t, uint32_t, uint8_t, ControllerProfileConfirmationPolicy) {} +void controller_profile_runtime_reset() {} +bool controller_profile_runtime_take_initial_profile_indication(uint8_t, ControllerProfileRuntimeProfileChangeEvent*) { return false; } +bool controller_profile_runtime_take_profile_change(uint8_t, ControllerProfileRuntimeProfileChangeEvent*) { return false; } +ControllerProfileTransformResult controller_profile_runtime_transform( + uint8_t, const Bluepad32SlotSnapshot& input, uint32_t, AdapterUsbMode) { + ControllerProfileTransformResult result{}; + result.state = input.state; + if (swap_faces) { + result.state.button_south = input.state.button_east; + result.state.button_east = input.state.button_south; + } + return result; +} + +static void put_pair(uint8_t* out, uint16_t x, uint16_t y) { + out[0] = static_cast(x); + out[1] = static_cast((x >> 8) | (y << 4)); + out[2] = static_cast(y >> 4); +} +static uint16_t stick_x(const uint8_t* p) { return p[5] | ((p[6] & 15u) << 8); } +static uint16_t stick_y(const uint8_t* p) { return (p[6] >> 4) | (p[7] << 4); } +static int32_t signed32(const uint8_t* p) { + const uint32_t raw = p[0] | (uint32_t(p[1]) << 8) | (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); + return raw <= INT32_MAX ? static_cast(raw) : -1 - static_cast(UINT32_MAX - raw); +} +static uint32_t get_bits(const uint8_t* p, unsigned start, unsigned count) { + uint32_t result = 0; + for (unsigned i = 0; i < count; ++i) result |= uint32_t((p[(start+i)/8] >> ((start+i)%8)) & 1) << i; + return result; +} +static void decode_quaternion(const uint8_t* p, double out[4]) { + const uint8_t* imu = p + 16; + const unsigned index = get_bits(imu, 32, 3); + assert(index < 4); + double ratios[3], norm = 1; + for (unsigned i = 0; i < 3; ++i) { + ratios[i] = get_bits(imu, 35 + 31*i, 31) / 1073741824.0 - 1; + norm += ratios[i] * ratios[i]; + } + out[index] = 1 / sqrt(norm); + for (unsigned i = 0; i < 3; ++i) out[(index+i+1)&3] = ratios[i] * out[index]; +} +static void publish(bool gyro_fresh = true) { + source.received_us = time_us_32(); + ++source.state_generation; + if (time_us_32() - last_sensor_us >= 10000) { + last_sensor_us = time_us_32(); + ++sensor_sequence; + source.accel_sequence = sensor_sequence; + source.accel_received_us = time_us_32(); + if (gyro_fresh) { + source.gyro_sequence = sensor_sequence; + source.gyro_received_us = time_us_32(); + } + } + wii_ir_pointer_observe(source.slot, source.controller.connection_generation, + ++ir_sequence, raw_ir_buttons, ir_x, ir_y, ir_mask, false, 0.0f, true); +} +static uint32_t poll(bool commit = true, bool gyro_fresh = true) { + now_us += 4000; + publish(gyro_fresh); + probe_controller_input_poll(to_ms_since_boot(now_us), &controls); + const uint32_t token = probe_controller_input_peek_native_report(to_ms_since_boot(now_us), packet); + if (commit && token) assert(probe_controller_input_commit_native_report(token)); + return token; +} + +int main() { + probe_controller_input_init(); + assert(probe_controller_input_start()); + uint8_t calibration[9]; + put_pair(calibration, 2000, 2100); + put_pair(calibration+3, 1500, 1400); + put_pair(calibration+6, 1600, 1700); + probe_controller_input_set_stick_calibration(calibration); + probe_controller_input_set_native_features(0x37); + probe_controller_input_set_native_stream(true); + source.slot = 0; + source.controller.active = true; + source.controller.connection_generation = 7; + source.layout = Bluepad32ControllerLayout::kWiiNunchuk; + source.controller.state.button_south = true; // Profile maps this to native A. + source.accel_valid = source.gyro_valid = true; + source.accel_q13[1] = 8192; // SDL up -> virtual native rail-down +X. + memcpy(source.gyro_q10, bias_q10, sizeof(bias_q10)); + for (unsigned i = 0; i < 450; ++i) assert(poll()); + assert(controls.active && packet[15] == 30 && packet[19] == 0x0c); + assert(signed32(packet+32) == (1 << 28)); + assert(signed32(packet+36) == 0 && signed32(packet+40) == 0); + assert(packet[2] == 2 && packet[3] == 0 && packet[13] == 20); + assert(stick_x(packet) == 2000 && stick_y(packet) == 2100); + double initial[4]; decode_quaternion(packet, initial); + + raw_ir_buttons = 0x000c; // Physical A+B in pointer telemetry are not click overlays. + for (unsigned i = 0; i < 8; ++i) assert(poll()); + assert(packet[2] == 2 && (packet[2] & 0x30) == 0); + source.controller.state.left_stick_x = INT16_MAX; + source.controller.state.left_stick_y = INT16_MIN; + assert(poll()); + assert(stick_x(packet) == 3500 && stick_y(packet) == 3500); + source.controller.state.left_stick_x = source.controller.state.left_stick_y = 0; + + // Native IR displacement must survive failed submission, then be consumed once. + raw_ir_buttons = 0x0002; // A mapped game button must not clutch native IR movement. + bool horizontal_motion = false; + int32_t horizontal_total = 0, horizontal_cross_axis = 0; + for (unsigned i = 0; i < 24; ++i) { + ir_x[0] += 2; ir_x[1] += 2; + assert(poll()); + horizontal_motion = horizontal_motion || packet[9] != 0 || packet[10] != 0; + const uint16_t x = packet[9] | (uint16_t(packet[10]) << 8); + const uint16_t y = packet[11] | (uint16_t(packet[12]) << 8); + horizontal_total += x <= INT16_MAX ? int32_t(x) : int32_t(x) - 65536; + horizontal_cross_axis += y <= INT16_MAX ? int32_t(y) : int32_t(y) - 65536; + } + assert(horizontal_motion); + assert(horizontal_total < 0); + assert(horizontal_cross_axis * 4 > horizontal_total && horizontal_cross_axis * 4 < -horizontal_total); + ir_x[0] += 8; ir_x[1] += 8; + const uint32_t ticket = poll(false); + uint8_t retry[63]; + assert(ticket && probe_controller_input_peek_native_report(to_ms_since_boot(now_us), retry) == ticket); + assert(memcmp(packet, retry, sizeof(packet)) == 0); + assert(probe_controller_input_commit_native_report(ticket)); + assert(!probe_controller_input_commit_native_report(ticket)); + + // Tilting the Wii up moves camera spots down. Native Joy-Con Y must + // reverse the desktop-pointer convention without changing consumption. + for (unsigned i = 0; i < 80; ++i) assert(poll()); + int32_t vertical_totals[2]{}; + for (unsigned direction = 0; direction < 2; ++direction) { + for (unsigned i = 0; i < 104; ++i) { + if (i < 24) { + ir_y[0] += direction == 0 ? 2 : -2; + ir_y[1] += direction == 0 ? 2 : -2; + } + assert(poll()); + const uint16_t y = packet[11] | (uint16_t(packet[12]) << 8); + vertical_totals[direction] += y <= INT16_MAX ? int32_t(y) : int32_t(y) - 65536; + WiiIrMouseReport pending{}; + (void)wii_ir_mouse_peek(&pending, INT16_MAX); + assert(pending.dx == 0 && pending.dy == 0); + } + } + assert(vertical_totals[0] > 0 && vertical_totals[1] < 0); + // Upstream radial smoothing has a positional dead zone, so returning the + // camera to its origin need not return the filtered pointer exactly there. + // Per-report checks above instead defend once-only native consumption. + + // A visible, stationary bar must anchor native heading against residual drift. + for (unsigned i = 0; i < 3000; ++i) assert(poll()); + decode_quaternion(packet, initial); + source.gyro_q10[1] = bias_q10[1] + 614; // ~0.6dps warming drift about vertical. + for (unsigned i = 0; i < 5000; ++i) assert(poll()); + double optically_held[4]; decode_quaternion(packet, optically_held); + double heading_dot = 0; + for (unsigned i = 0; i < 4; ++i) heading_dot += initial[i] * optically_held[i]; + assert(fabs(heading_dot) > cos(2.0 * acos(-1.0) / 360.0)); + memcpy(source.gyro_q10, bias_q10, sizeof(bias_q10)); + + // Gyro-only motion remains available while the sensor bar is out of view. + ir_mask = 0; + for (unsigned i = 0; i < 20; ++i) assert(poll()); + decode_quaternion(packet, initial); + for (unsigned i = 0; i < 250; ++i) assert(poll()); + double after_bias[4]; decode_quaternion(packet, after_bias); + double dot = 0; for (unsigned i=0;i<4;++i) dot += initial[i]*after_bias[i]; + assert(fabs(dot) > .99999); + // SDL yaw -> native mouse-frame +X; one second at90dps rotates90 degrees. + source.gyro_q10[1] = bias_q10[1] + 90 * 1024; + for (unsigned i = 0; i < 250; ++i) assert(poll()); + double turned[4]; decode_quaternion(packet, turned); + dot = 0; for (unsigned i=0;i<4;++i) dot += initial[i]*turned[i]; + assert(fabs(fabs(dot) - sqrt(.5)) < .015); + memcpy(source.gyro_q10, bias_q10, sizeof(bias_q10)); + + ir_mask = 0; + assert(poll()); + assert(packet[9] == 0 && packet[10] == 0 && packet[11] == 0 && packet[12] == 0 && packet[13] == 0xff); + ir_x[0] = 500; ir_x[1] = 700; ir_mask = 3; + assert(poll()); + assert(packet[9] == 0 && packet[10] == 0 && packet[11] == 0 && packet[12] == 0); + + // Fresh controller/accelerometer traffic cannot rejuvenate stale MotionPlus. + for (unsigned i = 0; i < 42; ++i) assert(poll(true, false)); + assert(controls.active && packet[15] == 0 && packet[13] == 0xff); + const uint32_t obsolete = poll(false, false); + ++source.controller.connection_generation; + assert(poll(false)); + assert(!probe_controller_input_commit_native_report(obsolete)); + probe_controller_input_set_native_stream(false); + assert(probe_controller_input_peek_native_report(to_ms_since_boot(now_us), retry) == 0); + probe_controller_input_set_native_stream(true); + publish_during_snapshot = true; + for (unsigned i = 0; i < 450; ++i) assert(poll()); + assert(packet[15] == 30); + source.controller.active = false; + now_us += 4000; + probe_controller_input_poll(to_ms_since_boot(now_us), &controls); + assert(!controls.active); + assert(probe_controller_input_peek_native_report(to_ms_since_boot(now_us), retry) == 0); + return 0; +} diff --git a/tests/test_bluepad32_backend_lifecycle_native.py b/tests/test_bluepad32_backend_lifecycle_native.py index 76f211d..b267712 100644 --- a/tests/test_bluepad32_backend_lifecycle_native.py +++ b/tests/test_bluepad32_backend_lifecycle_native.py @@ -10,14 +10,15 @@ def test_bluepad32_backend_lifecycle_native(tmp_path: Path) -> None: compiler = shutil.which("c++") or shutil.which("g++") assert compiler is not None, "a host C++ compiler is required" - for bluetooth_mode, native, short_packets in ( - ("mixed", False, False), - ("mixed", True, False), - ("mixed", True, True), - ("ble", False, False), - ("classic", False, False), + for bluetooth_mode, native, short_packets, wii_bridge in ( + ("mixed", False, False, False), + ("mixed", True, False, False), + ("mixed", True, True, False), + ("ble", False, False, False), + ("classic", False, False, False), + ("mixed", False, False, True), ): - suffix = "_native32" if short_packets else "_native64" if native else "" + suffix = "_wii_bridge" if wii_bridge else "_native32" if short_packets else "_native64" if native else "" executable = ( tmp_path / f"bluepad32_backend_lifecycle_test_{bluetooth_mode}{suffix}" ) @@ -33,6 +34,8 @@ def test_bluepad32_backend_lifecycle_native(tmp_path: Path) -> None: f"-DSWITCH_PICO_ENABLE_BLE={int(bluetooth_mode != 'classic')}", f"-DSWITCH_PICO_ENABLE_CLASSIC={int(bluetooth_mode != 'ble')}", ] + if wii_bridge: + command.append("-DSWITCH2_BRIDGE_WII_INPUT=1") if native: command.extend( [ @@ -112,6 +115,10 @@ def test_bluepad32_backend_lifecycle_native(tmp_path: Path) -> None: ] ) subprocess.run(command, check=True, cwd=root) + if wii_bridge: + for scenario in ("wii-bridge-sensors", "wii-bridge-cues", "wii-bridge-cue-races"): + subprocess.run([str(executable), scenario], check=True, cwd=root) + continue subprocess.run([str(executable), "transport-policy"], check=True, cwd=root) if bluetooth_mode != "classic": subprocess.run( diff --git a/tests/test_switch2_native_imu.py b/tests/test_switch2_native_imu.py new file mode 100644 index 0000000..f406656 --- /dev/null +++ b/tests/test_switch2_native_imu.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + + +def test_switch2_native_imu(tmp_path: Path) -> None: + root = Path(__file__).resolve().parents[1] + compiler = shutil.which("c++") or shutil.which("g++") + assert compiler is not None, "a host C++ compiler is required" + + executable = tmp_path / "switch2_native_imu_test" + subprocess.run( + [ + compiler, + "-std=c++17", + "-Wall", + "-Wextra", + "-Werror", + "-pedantic", + f"-I{root / 'tools' / 'switch2_usb_probe'}", + str(root / "tests" / "switch2_native_imu_test.cpp"), + str(root / "tools" / "switch2_usb_probe" / "native_imu.cpp"), + "-o", + str(executable), + ], + check=True, + cwd=root, + ) + subprocess.run([str(executable)], check=True, cwd=root) diff --git a/tests/test_switch2_wii_bridge_native.py b/tests/test_switch2_wii_bridge_native.py new file mode 100644 index 0000000..634ae81 --- /dev/null +++ b/tests/test_switch2_wii_bridge_native.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + +from prepare_libogc_ir import prepare + + +def test_wii_native_bridge_sensor_pointer_and_profile_contract(tmp_path: Path) -> None: + root = Path(__file__).resolve().parents[1] + compiler = shutil.which("c++") or shutil.which("g++") + assert compiler is not None, "a host C++ compiler is required" + c_compiler = shutil.which("cc") + assert c_compiler is not None, "a host C compiler is required" + generated = prepare(tmp_path / "libogc_ir.c") + ir_object = tmp_path / "libogc_ir.o" + subprocess.run( + [ + c_compiler, + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-pedantic", + f"-I{root / 'external'}", + "-c", + str(generated), + "-o", + str(ir_object), + ], + check=True, + cwd=root, + ) + executable = tmp_path / "switch2_wii_bridge_test" + subprocess.run( + [ + compiler, + "-std=c++17", + "-Wall", + "-Wextra", + "-Werror", + "-pedantic", + "-pthread", + "-DSWITCH_PICO_SWITCH2_USB_BRIDGE=1", + "-DSWITCH2_BRIDGE_WII_INPUT=1", + "-DSWITCH_PICO_BLUEPAD32=1", + "-DSWITCH_PICO_ENABLE_BLE=1", + "-DSWITCH_PICO_ENABLE_CLASSIC=1", + "-DSWITCH_PICO_SWITCH2_MOUSE_CAPTURE=1", + "-DSWITCH_PICO_SWITCH2_MOUSE_CAPTURE_NATIVE=1", + "-DSWITCH_PICO_WII_IR=1", + "-DSWITCH2_BRIDGE_SOURCE_ADDRESS_BYTES=0x02,0,0,0,0,1", + f"-I{root / 'tests' / 'switch2_mouse_bridge_native_stubs'}", + f"-I{root / 'tests' / 'wii_ir_aiming_native_stubs'}", + f"-I{root / 'tools' / 'switch2_usb_probe'}", + f"-I{root / 'src' / 'firmware'}", + f"-I{root / 'bluepad32_config'}", + f"-I{root / 'external'}", + str(root / "tests" / "switch2_wii_bridge_test.cpp"), + str(root / "tools" / "switch2_usb_probe" / "controller_input.cpp"), + str(root / "tools" / "switch2_usb_probe" / "native_imu.cpp"), + str(root / "src" / "firmware" / "input" / "wii_ir_pointer.cpp"), + str(ir_object), + "-o", + str(executable), + ], + check=True, + cwd=root, + ) + subprocess.run([str(executable)], check=True, cwd=root) diff --git a/tests/test_wii_ir_pointer_native.py b/tests/test_wii_ir_pointer_native.py new file mode 100644 index 0000000..9cdc140 --- /dev/null +++ b/tests/test_wii_ir_pointer_native.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + +from prepare_libogc_ir import prepare + + +@pytest.mark.parametrize( + "native_bridge", [False, True], ids=["legacy-mouse", "native-wii"] +) +def test_wii_ir_pointer_output_contract(tmp_path: Path, native_bridge: bool) -> None: + root = Path(__file__).resolve().parents[1] + compiler = shutil.which("c++") or shutil.which("g++") + assert compiler is not None, "a host C++ compiler is required" + executable = tmp_path / "wii_ir_pointer_test" + defines = ["-DSWITCH_PICO_WII_IR=1"] + defines.append( + "-DSWITCH2_BRIDGE_WII_INPUT=1" + if native_bridge + else "-DSWITCH_PICO_WII_IR_MOUSE=1" + ) + if native_bridge: + c_compiler = shutil.which("cc") + assert c_compiler is not None, "a host C compiler is required" + generated = prepare(tmp_path / "libogc_ir.c") + ir_object = tmp_path / "libogc_ir.o" + subprocess.run( + [ + c_compiler, + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-pedantic", + f"-I{root / 'external'}", + "-c", + str(generated), + "-o", + str(ir_object), + ], + check=True, + cwd=root, + ) + ir_sources = [str(ir_object)] + else: + ir_sources = [str(root / "src" / "firmware" / "input" / "wii_ir_tracker.cpp")] + subprocess.run( + [ + compiler, + "-std=c++17", + "-Wall", + "-Wextra", + "-Werror", + "-pedantic", + *defines, + f"-I{root / 'tests' / 'wii_ir_aiming_native_stubs'}", + f"-I{root / 'src' / 'firmware'}", + f"-I{root / 'external'}", + str(root / "tests" / "wii_ir_pointer_test.cpp"), + str(root / "src" / "firmware" / "input" / "wii_ir_pointer.cpp"), + *ir_sources, + "-o", + str(executable), + ], + check=True, + cwd=root, + ) + subprocess.run([str(executable)], check=True, cwd=root) diff --git a/tests/wii_ir_pointer_test.cpp b/tests/wii_ir_pointer_test.cpp new file mode 100644 index 0000000..f070092 --- /dev/null +++ b/tests/wii_ir_pointer_test.cpp @@ -0,0 +1,489 @@ +#include "input/wii_ir_pointer.h" + +#include +#include +#include +#include + +static uint32_t clock_us; +uint32_t time_us_32() { return clock_us; } + +namespace { +int failures; + +void expect(bool okay, const char* message) { + if (!okay) { std::cerr << message << '\n'; ++failures; } +} + +void observe(uint8_t slot, uint32_t connection_generation, uint32_t sequence, + int dx, int dy, uint16_t buttons = 0, uint8_t mask = 3, + bool nunchuk_c = false) { + clock_us += 5000; + const uint16_t x[4] = {static_cast(400 + dx), static_cast(624 + dx), 0, 0}; + const uint16_t y[4] = {static_cast(384 + dy), static_cast(384 + dy), 0, 0}; + wii_ir_pointer_observe(slot, connection_generation, sequence, buttons, x, y, mask, nunchuk_c, + 0.0f, false); +} + +struct Rig { + uint8_t slot = 2; + uint32_t connection_generation = 41; + uint32_t sequence = 0; + int horizontal = 0; + int vertical = 0; + + Rig() { + wii_ir_pointer_init(); + wii_ir_pointer_reset(); +#if SWITCH2_BRIDGE_WII_INPUT + expect(wii_ir_pointer_configure_screen(660, 370, 0, 0, 1320, 740), + "explicit native viewport and count spans must be configurable"); +#endif + wii_ir_mouse_set_output_enabled(true); + clock_us = 100000; +#if SWITCH2_BRIDGE_WII_INPUT + // Prime the real upstream startup/glitch/smoothing history, then + // consume its finite startup tail before comparing relative motion. + settle(0, 0); +#endif + WiiIrMouseReport release{}; + if (wii_ir_mouse_peek(&release)) wii_ir_mouse_commit(release); + input(0, 0); + input(0, 0); + } + + void input(int dx, int dy, uint16_t buttons = 0, uint8_t mask = 3, + bool nunchuk_c = false) { + horizontal = dx; + vertical = dy; + observe(slot, connection_generation, ++sequence, dx, dy, buttons, mask, nunchuk_c); + } + + void baseline(int dx, int dy) { +#if SWITCH2_BRIDGE_WII_INPUT + for (unsigned i = 0; i < 16; ++i) { + input(dx, dy); + if (peek().tracking) return; + } + expect(false, "fresh stationary full-pair reports must establish a native baseline"); +#else + input(dx, dy); + input(dx, dy); +#endif + } + + void settle(int dx, int dy, uint16_t buttons = 0) { + for (int i = 0; i < 80; ++i) input(dx, dy, buttons); + } + + void move_to(int dx, int dy) { + const int from_x = horizontal; + const int from_y = vertical; + for (int i = 1; i <= 20; ++i) { + input(from_x + (dx - from_x) * i / 20, from_y + (dy - from_y) * i / 20); + } + settle(dx, dy); + } + + WiiIrMouseReport peek() { + WiiIrMouseReport report{}; + wii_ir_mouse_peek(&report, 32767); + return report; + } +}; + +void native_movement_and_legacy_limits_conserve_output() { + Rig rig; + rig.move_to(100, -100); + const auto native = rig.peek(); + expect(native.dx < -127 && native.dy > 127, + "large two-axis motion must remain signed and exceed the legacy 8-bit range"); + const auto retry = rig.peek(); + expect(retry.dx == native.dx && retry.dy == native.dy && retry.generation == native.generation, + "peeking an unsubmitted native report must not consume movement"); + + WiiIrMouseReport legacy{}; + expect(wii_ir_mouse_peek(&legacy) && legacy.dx == -127 && legacy.dy == 127, + "legacy callers must retain the signed 8-bit HID movement limits"); + WiiIrMouseReport bounded{}; + expect(wii_ir_mouse_peek(&bounded, 31) && bounded.dx == -31 && bounded.dy == 31, + "both signed axes must obey the caller's movement bound"); + expect(!wii_ir_mouse_peek(&bounded, 0) && bounded.dx == 0 && bounded.dy == 0 && bounded.tracking, + "a zero movement allowance must leave tracking live without consuming displacement"); + + wii_ir_mouse_commit(legacy); + const auto remainder = rig.peek(); + expect(remainder.dx == native.dx - legacy.dx && remainder.dy == native.dy - legacy.dy, + "committing a bounded legacy report must leave its full native remainder"); + wii_ir_mouse_commit(remainder); + expect(!wii_ir_mouse_peek(&bounded, 32767) && bounded.dx == 0 && bounded.dy == 0 && bounded.tracking, + "committed movement must not be sent again and idle tracking must remain visible"); +} + +void prepared_report_preserves_newer_observations() { + Rig rig; + rig.move_to(80, -80); + const auto prepared = rig.peek(); + rig.move_to(120, -120); + const auto accumulated = rig.peek(); + expect(accumulated.dx < prepared.dx && accumulated.dy > prepared.dy, + "fresh observations must continue accumulating while a USB report waits"); + wii_ir_mouse_commit(prepared); + const auto remaining = rig.peek(); + expect(remaining.dx == accumulated.dx - prepared.dx && remaining.dy == accumulated.dy - prepared.dy, + "a successful cached report must consume only its own displacement, not newer samples"); +} + +void disabled_output_rebaselines_without_losing_owner() { + Rig rig; + rig.move_to(100, -100); + const auto old = rig.peek(); + wii_ir_mouse_set_output_enabled(false); + WiiIrMouseReport disabled{}; + expect(!wii_ir_mouse_peek(&disabled, 32767) && disabled.dx == 0 && disabled.dy == 0 && !disabled.tracking, + "disabling output must immediately discard pending movement and tracking"); + expect(disabled.owner == rig.slot && disabled.connection_generation == rig.connection_generation && + disabled.generation != old.generation, + "gating must invalidate prepared reports without relinquishing the selected owner"); + + rig.settle(-150, 100, 0x000c); + expect(!wii_ir_mouse_peek(&disabled, 32767) && disabled.dx == 0 && disabled.dy == 0 && disabled.buttons == 3, + "disabled camera observations must retain legacy button diagnostics but never queue output"); + uint8_t diagnostics[WII_IR_MOUSE_DIAGNOSTIC_SIZE]{}; + wii_ir_pointer_diagnostics(diagnostics, sizeof(diagnostics)); + expect(diagnostics[2] == 3 && diagnostics[32] == 0x0c && diagnostics[34] == 3, + "disabled output must continue reporting observed spots and physical buttons in diagnostics"); + + wii_ir_mouse_set_output_enabled(true); + const auto reopened = rig.peek(); + expect(reopened.dx == 0 && reopened.dy == 0 && !reopened.tracking && + reopened.owner == rig.slot && reopened.generation != disabled.generation, + "reopening output must await a fresh camera baseline without replaying disabled movement"); + rig.baseline(-150, 100); + const auto baseline = rig.peek(); + expect(baseline.tracking && baseline.dx == 0 && baseline.dy == 0, + "fresh observations after reopening must establish a motionless baseline"); + + rig.move_to(-120, 70); + const auto resumed = rig.peek(); + expect(resumed.dx < 0 && resumed.dx > -127 && resumed.dy > 0 && resumed.dy < 127, + "reopened output must contain the small new motion, not the larger disabled repositioning"); + wii_ir_mouse_commit(old); + const auto after_late_commit = rig.peek(); + expect(after_late_commit.dx == resumed.dx && after_late_commit.dy == resumed.dy, + "a late commit from before disabling must not consume newly acquired movement"); + + wii_ir_mouse_set_output_enabled(false); + wii_ir_pointer_reset(); + rig.slot = 4; + rig.connection_generation = 99; + rig.settle(0, 0); + expect(!wii_ir_mouse_peek(&disabled, 32767) && !disabled.tracking && disabled.owner == 4 && + disabled.connection_generation == 99 && disabled.dx == 0 && disabled.dy == 0, + "reset and source reselection must not silently reopen a disabled output gate"); +} + +void repeated_enable_preserves_live_tracking() { + Rig rig; + rig.move_to(50, -50); + const auto before = rig.peek(); + wii_ir_mouse_set_output_enabled(true); + const auto unchanged = rig.peek(); + expect(unchanged.tracking && unchanged.generation == before.generation && + unchanged.dx == before.dx && unchanged.dy == before.dy, + "repeated enable must neither reset live tracking nor discard pending displacement"); + for (int i = 1; i <= 20; ++i) { + wii_ir_mouse_set_output_enabled(true); + rig.input(50 + i, -50 - i); + } + const auto moved = rig.peek(); + expect(moved.tracking && moved.generation == before.generation && moved.dx < before.dx && moved.dy > before.dy, + "a continuously asserted readiness gate must allow subsequent camera motion"); +} + +void duplicate_samples_cannot_refresh_stale_tracking() { + Rig rig; + rig.move_to(80, -80); + const auto prepared = rig.peek(); + for (int i = 0; i < 29; ++i) { + observe(rig.slot, rig.connection_generation, rig.sequence, -100, 100, 0x000c); + } + const auto fresh = rig.peek(); + expect(fresh.tracking && fresh.dx == prepared.dx && fresh.dy == prepared.dy && fresh.buttons == 0, + "duplicate sequences must not update camera movement, buttons, or the freshness deadline"); + observe(rig.slot, rig.connection_generation, rig.sequence, -100, 100, 0x000c); + WiiIrMouseReport stale{}; + expect(!wii_ir_mouse_peek(&stale, 32767) && !stale.tracking && stale.dx == 0 && stale.dy == 0, + "tracking and queued movement must expire at 150ms despite duplicate observations"); + expect(stale.owner == rig.slot && stale.connection_generation == rig.connection_generation && + stale.generation != prepared.generation, + "stale tracking must invalidate prepared movement without forgetting the connected owner"); + rig.baseline(-100, 100); + const auto reacquired = rig.peek(); + expect(reacquired.tracking && reacquired.dx == 0 && reacquired.dy == 0, + "reacquisition after stale tracking must not include the stale interval"); + rig.move_to(-70, 70); + const auto current = rig.peek(); + wii_ir_mouse_commit(prepared); + const auto after = rig.peek(); + expect(after.dx == current.dx && after.dy == current.dy, + "an expired report cannot consume movement from a fresh tracking generation"); +} + +void owner_generation_and_tracking_loss_invalidate_reports() { + Rig rig; + WiiIrMouseReport idle{}; + expect(!wii_ir_mouse_peek(&idle, 32767) && idle.tracking && idle.owner == rig.slot && + idle.connection_generation == rig.connection_generation, + "a stationary source must expose tracking and connection identity even without pending output"); + rig.move_to(80, -80); + const auto old = rig.peek(); + observe(7, 900, 1, -100, 100, 0x000c); + wii_ir_pointer_disconnect(7); + const auto owned = rig.peek(); + expect(owned.owner == rig.slot && owned.connection_generation == rig.connection_generation && + owned.dx == old.dx && owned.dy == old.dy && owned.buttons == 0, + "an unrelated source or disconnect must not steal ownership or alter movement"); + + ++rig.connection_generation; + rig.sequence = 0; + rig.baseline(-100, 100); + const auto reconnected = rig.peek(); + expect(reconnected.tracking && reconnected.dx == 0 && reconnected.dy == 0 && + reconnected.connection_generation == rig.connection_generation && reconnected.generation != old.generation, + "reusing a slot with a new connection generation must discard the old association and backlog"); + rig.move_to(-70, 70); + const auto current = rig.peek(); + wii_ir_mouse_commit(old); + const auto after = rig.peek(); + expect(after.dx == current.dx && after.dy == current.dy, + "a previous connection's report cannot consume current movement"); + +#if SWITCH2_BRIDGE_WII_INPUT + // Upstream holds eight missing reports; only the ninth is true loss. + for (unsigned i = 0; i < 8; ++i) rig.input(-70, 70, 0, 0); +#endif + rig.input(-70, 70, 0, 0); + expect(!wii_ir_mouse_peek(&idle, 32767) && !idle.tracking && idle.dx == 0 && idle.dy == 0, + "true camera tracking loss must drop unsent movement"); + wii_ir_pointer_disconnect(rig.slot); + expect(!wii_ir_mouse_peek(&idle, 32767) && !idle.tracking && idle.owner == 0xff && idle.connection_generation == 0, + "disconnect must clear tracking and connection identity even without pending movement"); +} + +void legacy_buttons_and_clutch_remain_independent_of_movement() { + Rig rig; + rig.input(0, 0, 0x000c); + WiiIrMouseReport buttons{}; + expect(wii_ir_mouse_peek(&buttons) && buttons.buttons == 3 && buttons.dx == 0 && buttons.dy == 0, + "legacy mouse buttons must remain observable independently of camera movement"); + wii_ir_mouse_commit(buttons); + expect(!wii_ir_mouse_peek(&buttons), "committing stationary legacy buttons must clear their pending change"); +#if SWITCH2_BRIDGE_WII_INPUT + for (int i = 1; i <= 20; ++i) rig.input(i, -i, 0x0003, 3, true); + const auto held = rig.peek(); + expect(held.tracking && held.dx < 0 && held.dy > 0 && held.buttons == 0, + "native controller buttons and Nunchuk C must not activate either legacy clutch chord"); +#else + rig.input(20, -20, 0x0002); + expect(wii_ir_mouse_peek(&buttons) && buttons.buttons == 0 && !buttons.tracking && buttons.dx == 0 && buttons.dy == 0, + "the legacy 1-button clutch must suppress movement while still releasing buttons"); + wii_ir_mouse_commit(buttons); + rig.settle(100, -100, 0x0002); + rig.input(100, -100); + rig.input(100, -100); + expect(!wii_ir_mouse_peek(&buttons) && buttons.tracking && buttons.dx == 0 && buttons.dy == 0, + "releasing the legacy clutch must rebaseline rather than replay repositioning"); + rig.move_to(120, -120); + const auto moved = rig.peek(); + expect(moved.dx < 0 && moved.dy > 0, "movement must resume normally after the legacy clutch is released"); +#endif +} + +#if SWITCH2_BRIDGE_WII_INPUT +void native_cold_baseline_and_unique_camera_reports() { + Rig rig; + wii_ir_pointer_reset(); + const uint16_t x[4] = {300, 524, 0, 0}; + const uint16_t y[4] = {384, 384, 0, 0}; + clock_us += 5000; + wii_ir_pointer_observe(rig.slot, rig.connection_generation, ++rig.sequence, + 0, x, y, 3, false, 0.0f, true); + for (unsigned i = 0; i < 64; ++i) { + wii_ir_pointer_observe(rig.slot, rig.connection_generation, rig.sequence, + 0, x, y, 3, false, 0.0f, true); + const auto held = rig.peek(); + expect(!held.tracking && held.dx == 0 && held.dy == 0, + "polls and duplicate sequences must not advance upstream's initial glitch hold"); + } + rig.baseline(-100, 0); + const auto first = rig.peek(); + expect(first.tracking && first.dx == 0 && first.dy == 0 && first.optical_valid, + "first accepted upstream position must become a motionless relative baseline"); + expect(first.optical_sequence == rig.sequence && first.optical_received_us == clock_us && + std::fabs(first.optical_yaw_radians - std::atan(99.0f * 0.39f / 512.0f)) < 0.00001f, + "optical heading must use mirrored raw X with upstream calc_yaw in radians"); + uint8_t diagnostics[WII_IR_MOUSE_DIAGNOSTIC_SIZE]{}; + expect(wii_ir_pointer_diagnostics(diagnostics, sizeof(diagnostics)) == 48 && + diagnostics[16] == 0x2c && diagnostics[17] == 0x01 && + diagnostics[18] == 0x80 && diagnostics[19] == 0x01 && + (diagnostics[3] & 0x19) == 0x19, + "raw48 diagnostics must retain original unmirrored pixels and upstream tracking flags"); +} + +void native_glitch_hold_excludes_optical_heading() { + Rig rig; + const auto before = rig.peek(); + for (unsigned frame = 0; frame < 6; ++frame) { + rig.input(250, 0); + const auto held = rig.peek(); + expect(held.tracking && !held.optical_valid && held.dx == 0 && held.dy == 0 && + held.generation == before.generation, + "upstream glitch-held raw geometry must not move the pointer or feed optical heading"); + } + rig.input(250, 0); + const auto accepted = rig.peek(); + expect(accepted.tracking && accepted.optical_valid && accepted.dx < 0 && + accepted.generation == before.generation, + "upstream accepting a persistent glitch must restore heading confidence without a custom rebase"); +} + +void native_missing_report_grace_and_true_loss() { + Rig rig; + rig.input(20, -20); // Leave an upstream smoothing tail when the dots vanish. + const auto settled = rig.peek(); + wii_ir_mouse_commit(settled); + for (unsigned missing = 1; missing <= 8; ++missing) { + rig.input(20, -20, 0, 0); + const auto held = rig.peek(); + expect(held.tracking && !held.optical_valid && held.dx == 0 && held.dy == 0 && + held.generation == settled.generation, + "upstream's eight missing-frame grace must hold position without movement or rebasing"); + // Core0 polling cannot age the frame-count error policy. + for (unsigned poll = 0; poll < 16; ++poll) { + const auto polled = rig.peek(); + expect(polled.tracking && polled.dx == 0 && polled.dy == 0, + "USB peeks must neither age missing-frame grace nor synthesize movement"); + } + } + rig.input(20, -20, 0, 0); + const auto lost = rig.peek(); + expect(!lost.tracking && !lost.optical_valid && lost.dx == 0 && lost.dy == 0 && + lost.generation != settled.generation, + "ninth missing camera report must expose upstream's real loss and invalidate pending generations"); + rig.input(-100, 100); + const auto acquired = rig.peek(); + expect(acquired.tracking && acquired.optical_valid && acquired.dx == 0 && acquired.dy == 0, + "upstream loss recovery must rebaseline rather than bridge the absent camera interval"); + rig.move_to(-70, 70); + expect(rig.peek().dx < 0 && rig.peek().dy > 0, + "real movement must resume after loss recovery"); +} + +void native_single_end_does_not_supply_full_optical_heading() { + Rig rig; + int vertical = 0; + for (int i = 1; i <= 80; ++i) { + rig.input(0, i, 0, 1); + const auto report = rig.peek(); + expect(report.tracking && !report.optical_valid, + "upstream single-end continuation must not claim a full-pair optical heading"); + vertical += report.dy; + wii_ir_mouse_commit(report); + } + expect(vertical < -140, + "continuous single-end observations must retain upstream's relative movement"); + rig.input(0, 80); + expect(rig.peek().optical_valid, + "a full pair returning must restore the native optical observer metadata"); +} + +void native_roll_convention_and_invalid_gravity_retention() { + Rig rig; + wii_ir_pointer_reset(); + // A raw +90-degree bar becomes horizontal only after mirrored camera X + // and upstream's +90-degree rotation. Raw X travel becomes corrected Y. + int horizontal = 0, vertical = 0; + for (unsigned i = 0; i < 100; ++i) { + const uint16_t x[4] = {static_cast(512 + (i > 30 ? 30 : 0)), + static_cast(512 + (i > 30 ? 30 : 0)), 0, 0}; + const uint16_t y[4] = {272, 496, 0, 0}; + clock_us += 5000; + wii_ir_pointer_observe(rig.slot, rig.connection_generation, ++rig.sequence, + 0, x, y, 3, false, + i == 0 ? 1.57079632679f : std::numeric_limits::quiet_NaN(), + (i % 2) == 0); + const auto report = rig.peek(); + if (i > 30) { + expect(report.tracking && report.optical_valid, + "invalid new gravity must retain the last valid roll for upstream full-pair tracking"); + horizontal += report.dx; + vertical += report.dy; + } + wii_ir_mouse_commit(report); + } + expect(vertical > 0 && vertical > 2 * std::abs(horizontal), + "raw +90-degree roll must map travel predominantly to shared positive Y despite smoothing history"); +} +void native_relative_motion_is_not_clipped_to_viewport() { + Rig rig; + wii_ir_pointer_reset(); + for (int i = 0; i < 80; ++i) { + rig.input(0, 220); + wii_ir_mouse_commit(rig.peek()); + } + int vertical = 0; + bool tracked = true; + for (int i = 1; i <= 110; ++i) { + rig.input(0, 220 + (i < 30 ? i : 30)); + const auto report = rig.peek(); + tracked = tracked && report.tracking; + vertical += report.dy; + wii_ir_mouse_commit(report); + } + expect(tracked && vertical < -40 && vertical > -80, + "visible vertical motion outside the viewport must still reach a relative mouse"); + + expect(wii_ir_pointer_configure_screen(1, 1, 0, 0, 32767, 32767), + "the narrowest supported viewport and largest count spans must be accepted"); + for (int i = 0; i < 80; ++i) { + rig.input(300, 0); + wii_ir_mouse_commit(rig.peek()); + } + int horizontal = 0; + bool bounded = true; + for (int i = 0; i < 24; ++i) { + rig.input(290, 0); + const auto report = rig.peek(); + bounded = bounded && report.dx >= 0 && report.dx <= 4096 && + report.dy >= -4096 && report.dy <= 4096; + horizontal += report.dx; + wii_ir_mouse_commit(report); + } + expect(bounded && horizontal > 0, + "wide off-viewport coordinates must not overflow or reverse bounded relative movement"); +} + +#endif + +} // namespace + +int main() { + native_movement_and_legacy_limits_conserve_output(); + prepared_report_preserves_newer_observations(); + disabled_output_rebaselines_without_losing_owner(); + repeated_enable_preserves_live_tracking(); + duplicate_samples_cannot_refresh_stale_tracking(); + owner_generation_and_tracking_loss_invalidate_reports(); + legacy_buttons_and_clutch_remain_independent_of_movement(); +#if SWITCH2_BRIDGE_WII_INPUT + native_cold_baseline_and_unique_camera_reports(); + native_glitch_hold_excludes_optical_heading(); + native_missing_report_grace_and_true_loss(); + native_single_end_does_not_supply_full_optical_heading(); + native_roll_convention_and_invalid_gravity_retention(); + native_relative_motion_is_not_clipped_to_viewport(); +#endif + if (failures) return 1; + std::cout << "IR pointer output contract passed\n"; +} diff --git a/tests/wii_parser_native_test.c b/tests/wii_parser_native_test.c index b782c48..4d99a85 100644 --- a/tests/wii_parser_native_test.c +++ b/tests/wii_parser_native_test.c @@ -66,6 +66,13 @@ bool uni_hid_device_set_ready_complete(uni_hid_device_t* d) { void uni_log(const char* fmt, ...) { (void)fmt; } void printf_hexdump(const void* data, int len) { (void)data; (void)len; } +// This parser fixture does not schedule rumble. Teardown still asks BTstack +// to remove both timers; neither is present in the fixture's empty timer list. +bool btstack_run_loop_remove_timer(btstack_timer_source_t* timer) { + assert(timer != NULL); + return false; +} + static void put_be16(uint8_t* output, uint16_t value) { output[0] = value >> 8; output[1] = value; @@ -509,6 +516,88 @@ static void accelerometer_snapshot_requires_fresh_calibrated_reports(void) { assert(!uni_hid_parser_wii_accel_snapshot(&f.device, acceleration, &sequence)); } +static void gyro_snapshot_advances_only_on_calibrated_motionplus_packets(void) { + reset_fixture(0x0330, true, EXT_NUNCHUK); + connect_device(); + int32_t gyro[3]; + uint32_t sequence; + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + send_nunchuk_controls(true); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + send_motion(7760, 8200, 7560, false, true, false); + assert(uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + expect_vector(gyro, 360 * 1024, -120 * 1024, 40 * 1024); + const uint32_t first = sequence; + send_nunchuk_controls(true); + send_ack(0x16, 0); + send_status(true); + finish_setup(); + uint8_t short_report[11] = {0x35}; + feed(short_report, sizeof(short_report)); + assert(uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + assert(sequence == first); + expect_vector(gyro, 360 * 1024, -120 * 1024, 40 * 1024); + send_motion(7760, 8200, 7560, false, true, false); + assert(uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + assert(sequence != first); // Equal values do not mean a duplicate packet. + + reset_fixture(0x0330, true, EXT_NONE); + f.mp_calibration[30] ^= 1; + connect_device(); + send_motion(7760, 8200, 7560, false, true, false); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + assert(uni_hid_parser_wii_accel_snapshot(&f.device, gyro, &sequence)); +} + +static void gyro_snapshot_invalidates_on_topology_and_teardown(void) { + reset_fixture(0x0306, true, EXT_NONE); + connect_device(); + send_motion(7760, 8200, 7560, false, true, false); + int32_t gyro[3]; + uint32_t sequence; + assert(uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + const uint32_t first = sequence; + assert(uni_hid_parser_wii_rumble_ready(&f.device)); + f.extension = EXT_NUNCHUK; + send_motion(7760, 8200, 7560, false, true, false); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + assert(!uni_hid_parser_wii_rumble_ready(&f.device)); + finish_setup(); + assert(uni_hid_parser_wii_rumble_ready(&f.device)); + send_nunchuk_controls(true); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + send_motion(7760, 8200, 7560, false, true, false); + assert(uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + assert(sequence > first); // Topology setup cannot reuse a pre-hotplug ID. + + f.extension = EXT_NONE; + f.motionplus = false; + f.mp_active = false; + send_status(false); + finish_setup(); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + send_core_and_accel(); + assert(uni_hid_parser_wii_accel_snapshot(&f.device, gyro, &sequence)); + f.motionplus = true; + send_status(true); + finish_setup(); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + send_motion(7760, 8200, 7560, false, true, false); + // The first gyro packet resolves the active MP's downstream topology, + // which the attachment status bit alone cannot distinguish. + finish_setup(); + send_motion(7760, 8200, 7560, false, true, false); + assert(uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + assert(sequence > first); + uni_hid_parser_wii_teardown(&f.device); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); + assert(!uni_hid_parser_wii_rumble_ready(&f.device)); + f.ready_count = 0; // A new parser connection gets its own ready notification. + uni_hid_parser_wii_setup(&f.device); + finish_setup(); + assert(!uni_hid_parser_wii_gyro_snapshot(&f.device, gyro, &sequence)); +} + static void setup_read_and_write_errors_leave_buttons_ready(void) { reset_fixture(0x0330, true, EXT_NONE); f.fail_read_address = 0xa60030; @@ -1112,6 +1201,8 @@ static void run_case(const char* name, void (*test)(void)) { int main(void) { run_case("fresh calibrated accelerometer snapshots without MotionPlus", accelerometer_snapshot_requires_fresh_calibrated_reports); + run_case("independent fresh calibrated MotionPlus gyro snapshots", gyro_snapshot_advances_only_on_calibrated_motionplus_packets); + run_case("gyro validity through hotplug, replacement and teardown", gyro_snapshot_invalidates_on_topology_and_teardown); run_case("plain Nunchuk independent packed acceleration", plain_nunchuk_accel_uses_own_packed_factory_points); run_case("MotionPlus Nunchuk acceleration bitpacking and freshness", passthrough_nunchuk_accel_bitpacking_and_freshness); run_case("Nunchuk accelerometer calibration independent of stick and Remote", nunchuk_accel_calibration_is_independent_of_stick_and_remote); diff --git a/tools/prepare_libogc_ir.py b/tools/prepare_libogc_ir.py new file mode 100755 index 0000000..0db6a53 --- /dev/null +++ b/tools/prepare_libogc_ir.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Extract the pinned libogc Wiiuse IR math into a build-local C source file.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from pathlib import Path + +UPSTREAM_COMMIT = "a4064a86487c46d8ab76d4fdf99e8059a62c4fa2" +IR_GIT_BLOB = "d9659f5da575861f574d3d0480887955ef8f8faf" +COMPONENT = Path(__file__).resolve().parents[1] / "external" / "libogc_ir" + + +class PreparationError(RuntimeError): + pass + + +def _check_sha256(data: bytes, expected: str, label: str) -> None: + actual = hashlib.sha256(data).hexdigest() + if actual != expected: + raise PreparationError( + f"{label}: SHA-256 mismatch: expected {expected}, got {actual}" + ) + + +def _section(data: bytes, section: dict) -> bytes: + first, last = section["first_line"], section["last_line"] + lines = data.splitlines(keepends=True) + label = f"{section['source']}:{first}-{last}" + if not 1 <= first <= last <= len(lines): + raise PreparationError(f"{label}: extraction range is outside the source") + selected = lines[first - 1 : last] + if ( + selected[0].decode("utf-8").rstrip("\r\n") != section["first_line_text"] + or selected[-1].decode("utf-8").rstrip("\r\n") != section["last_line_text"] + ): + raise PreparationError(f"{label}: extraction boundary marker mismatch") + content = b"".join(selected) + _check_sha256(content, section["sha256"], label) + return content + + +def prepare(output: Path) -> Path: + """Write unchanged upstream math sections; preserve mtime when bytes match. + + Input hashes, extraction boundaries and header fidelity are strict build + prerequisites. This does not fetch sources, invoke Git, rewrite C, or + compile anything. The generated component retains the libogc GPL plus its + section 18 linking exception; see external/libogc_ir/NOTICE.txt. + """ + output = Path(output).resolve() + if output.is_relative_to(COMPONENT): + raise PreparationError( + "output must be outside the vendored libogc IR component" + ) + + manifest = json.loads((COMPONENT / "UPSTREAM.json").read_bytes()) + if manifest["format_version"] != 1 or manifest["commit"] != UPSTREAM_COMMIT: + raise PreparationError("unsupported libogc IR manifest version or source pin") + if manifest["ir_git_blob_sha1"] != IR_GIT_BLOB: + raise PreparationError("unexpected pinned ir.c Git blob") + + sources = {} + for name, record in manifest["sources"].items(): + data = (COMPONENT / record["local_path"]).read_bytes() + _check_sha256(data, record["sha256"], name) + blob = hashlib.sha1(b"blob " + str(len(data)).encode("ascii") + b"\0" + data) + if blob.hexdigest() != record["git_blob_sha1"]: + raise PreparationError(f"{name}: Git blob checksum mismatch") + if len(data) != record["bytes"] or len(data.splitlines()) != record["lines"]: + raise PreparationError(f"{name}: source size or line count mismatch") + sources[name] = data + ir_source = sources["wiiuse/ir.c"] + ir_blob = hashlib.sha1( + b"blob " + str(len(ir_source)).encode("ascii") + b"\0" + ir_source + ).hexdigest() + if ir_blob != IR_GIT_BLOB: + raise PreparationError("ir.c differs from the pinned upstream Git blob") + + header = manifest["portable_header"] + _check_sha256((COMPONENT / header["path"]).read_bytes(), header["sha256"], "ir.h") + for section in manifest["extraction"]["header_sections"]: + _section(sources[section["source"]], section) + + chunks = [ + b'#include "libogc_ir/ir.h"\n#include \n\n', + ( + "/*\n" + " * Generated libogc Wiiuse IR math extraction; modified 2026-09-11.\n" + f" * Upstream commit: {UPSTREAM_COMMIT}\n" + " * Function bodies and algorithm constants below are unchanged.\n" + " * Only platform isolation, declarations and provenance are adapted.\n" + " * GNU GPL with the libogc section 18 linking exception, explicitly\n" + " * retained and extended to this modified component. See\n" + " * external/libogc_ir/license_libogc.txt, libogc_license.txt,\n" + " * NOTICE.txt and UPSTREAM.json. The original Wiiuse notice follows.\n" + " */\n" + ).encode(), + ] + for section in manifest["extraction"]["c_sections"]: + source = section["source"] + local_path = manifest["sources"][source]["local_path"] + chunks.append( + f'\n#line {section["first_line"]} "external/libogc_ir/{local_path}"\n'.encode() + ) + chunks.append(_section(sources[source], section)) + if source == "wiiuse/definitions.h" and section["first_line"] == 31: + # Upstream uses the GNU empty-tail form DEBUG(fmt, ...). A purely + # variadic disabled macro has identical expansion and is valid C11. + chunks.append( + b"\n/* C11 portability only: logging stays disabled. */\n" + b"#undef WIIUSE_DEBUG\n#define WIIUSE_DEBUG(...)\n" + ) + generated = b"".join(chunks) + + if not output.exists() or output.read_bytes() != generated: + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(generated) + return output + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + try: + prepare(args.output) + except (PreparationError, OSError, ValueError, KeyError, TypeError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/switch2_native_imu.py b/tools/switch2_native_imu.py new file mode 100755 index 0000000..c098457 --- /dev/null +++ b/tools/switch2_native_imu.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python3 +"""Offline candidate codec for native Joy-Con 2 (R) IMU blocks. + +No device access or firmware writes. Accepts exported native_hex packet JSON, +unfragmented decrypted BLE PCAPng (ATT handle 0x000e), or --block HEX. + +Recovered from native captures, not copied from original-Switch report 0x30. +The quaternion is ratio-coded: select the largest component, make it positive, +and store the next three components in cyclic order divided by that component. +Labelled right-Joy-Con captures support wire order (w, x, y, z), with +X toward +the outer edge away from the rail, +Y toward R/ZR, and +Z out of the button face. +Positive gyro rotation follows the right-hand rule about those body axes. +Acceleration units are a g-scale candidate supported by gravity magnitudes. +For observed packed tag 3, labelled turns support gyro degrees/second = +raw * 500 / 2**(width - 1), correcting the initial 512-degree-range hypothesis. +Subsample timing and cross-device tick units remain unconfirmed. The trailing +temperature-like word is raw, not degrees; format 0x0f has no such word. + +Reference for native report boundaries: +https://github.com/ndeadly/switch2_controller_research/blob/master/hid_reports.md +""" + +from __future__ import annotations + +import argparse +import json +import math +import struct +import sys +from collections import Counter +from collections.abc import Iterable, Iterator +from pathlib import Path +from typing import TypedDict + + +class AccelerationVector(TypedDict): + bit_offset: int + width: int + fraction_bits_candidate: int + raw: list[int] + g_candidate: list[float] + + +class RotationTriplet(TypedDict): + bit_offset: int + width: int + dps_per_count_candidate: float + raw: list[int] + dps_candidate: list[float] + interpretation: str + + +class DecodedBlock(TypedDict): + format: int + length: int + counter_ticks: int + elapsed_ticks: int + range_tag: int | None + largest_component: int + quaternion_width: int + quaternion_ratios: list[float] + quaternion_wire: list[float] + accelerations: list[AccelerationVector] + rotation_triplets: list[RotationTriplet] + temperature_raw_candidate: int | None + + +class InputRecord(TypedDict, total=False): + native_hex: str + block: str + t_us: int | None + stream: str + + +# Quaternion width; alternating acceleration / rotation triplet widths. +# All offsets are LSB-first within the IMU block, not the containing HID report. +LAYOUTS = { + 0: (31, (32,)), + 1: (23, (22, 22, 22)), + 2: (21, (14, 13, 13, 14, 14)), + 3: (21, (14, 16, 13, 16, 14)), +} + + +def bits(word: int, start: int, width: int) -> int: + return (word >> start) & ((1 << width) - 1) + + +def signed(word: int, start: int, width: int) -> int: + value = bits(word, start, width) + return value - (1 << width) if value & (1 << (width - 1)) else value + + +def quaternion_from_ratios(index: int, ratios: list[float]) -> list[float]: + largest = 1.0 / math.sqrt(1.0 + sum(value * value for value in ratios)) + result = [0.0] * 4 + result[index] = largest + for i, ratio in enumerate(ratios): + result[(index + i + 1) & 3] = ratio * largest + return result + + +def decode_block(block: bytes) -> DecodedBlock: + if len(block) not in (30, 40): + raise ValueError(f"expected 30 or 40 IMU bytes, received {len(block)}") + if block[3] not in (0x0C, 0x0D, 0x0E, 0x0F): + raise ValueError(f"unsupported internal format byte 0x{block[3]:02x}") + variant = block[3] & 3 + if len(block) != (30 if variant == 0 else 40): + raise ValueError("internal format does not match declared IMU length") + word = int.from_bytes(block, "little") + quaternion_width, widths = LAYOUTS[variant] + range_tag = None if variant == 0 else bits(word, 32, 2) + if range_tag not in (None, 3): + raise ValueError(f"unobserved packed range tag {range_tag}; scale unresolved") + index_start = 32 if variant == 0 else 34 + index_tag = bits(word, index_start, 3) + if index_tag > 3: + raise ValueError(f"unobserved quaternion index tag {index_tag}") + position = index_start + 3 + ratio_codes = [bits(word, position + i * quaternion_width, quaternion_width) + for i in range(3)] + ratios = [value / (1 << (quaternion_width - 1)) - 1.0 for value in ratio_codes] + position += 3 * quaternion_width + accelerations: list[AccelerationVector] = [] + rotation_triplets: list[RotationTriplet] = [] + for vector_index, width in enumerate(widths): + values = [signed(word, position + i * width, width) for i in range(3)] + if vector_index % 2 == 0: + fraction_bits = 28 if variant == 0 else width - 2 + accelerations.append({ + "bit_offset": position, + "width": width, + "fraction_bits_candidate": fraction_bits, + "raw": values, + "g_candidate": [value / (1 << fraction_bits) for value in values], + }) + else: + dps_per_count = 500.0 / (1 << (width - 1)) + rotation_triplets.append({ + "bit_offset": position, + "width": width, + "dps_per_count_candidate": dps_per_count, + "raw": values, + "dps_candidate": [value * dps_per_count for value in values], + "interpretation": "body-local angular velocity candidate", + }) + position += 3 * width + if variant == 3: + assert position == 319 + if bits(word, 319, 1): + raise ValueError("unobserved nonzero format-0x0f terminal bit") + temperature = None + else: + assert position == len(block) * 8 - 16 + temperature = signed(word, position, 16) + return { + "format": block[3], + "length": len(block), + "counter_ticks": bits(word, 0, 12), + "elapsed_ticks": bits(word, 12, 12), + "range_tag": range_tag, + "largest_component": index_tag, + "quaternion_width": quaternion_width, + "quaternion_ratios": ratios, + "quaternion_wire": quaternion_from_ratios(index_tag, ratios), + "accelerations": accelerations, + "rotation_triplets": rotation_triplets, + "temperature_raw_candidate": temperature, + } + + +def put_bits(word: int, start: int, width: int, value: int, *, is_signed: bool = False) -> int: + minimum = -(1 << (width - 1)) if is_signed else 0 + maximum = (1 << (width - int(is_signed))) - 1 + if not minimum <= value <= maximum: + raise ValueError(f"value {value} does not fit {'signed ' if is_signed else ''}{width} bits") + return word | ((value & ((1 << width) - 1)) << start) + + +def pack_quaternion(word: int, start: int, width: int, + quaternion: list[float], index: int) -> int: + if len(quaternion) != 4 or not all(math.isfinite(v) for v in quaternion): + raise ValueError("quaternion must contain four finite components") + if index not in range(4) or quaternion[index] == 0: + raise ValueError("selected quaternion component must be nonzero") + word = put_bits(word, start, 3, index) + start += 3 + for i in range(3): + ratio = quaternion[(index + i + 1) & 3] / quaternion[index] + if abs(ratio) > 1.000000001: + raise ValueError("selected quaternion component is not largest") + # +1 is the top quantization boundary; do not wrap it into -1. + code = min((1 << width) - 1, + max(0, round((ratio + 1.0) * (1 << (width - 1))))) + word = put_bits(word, start + i * width, width, code) + return word + + +def encode_mode0(counter_ticks: int, elapsed_ticks: int, + quaternion_wire: list[float], acceleration_g: list[float], + temperature_raw: int, *, largest_component: int | None = None) -> bytes: + """Encode the recovered one-sample layout; not yet a console-qualified encoder. + + Physical axis mapping and temperature conversion are caller responsibilities. + This deliberately takes real orientation/acceleration, not canned motion data. + """ + if len(quaternion_wire) != 4: + raise ValueError("quaternion must have four components") + if largest_component is None: + largest_component = max(range(4), key=lambda i: abs(quaternion_wire[i])) + if len(acceleration_g) != 3 or not all(math.isfinite(v) for v in acceleration_g): + raise ValueError("acceleration must contain three finite components") + word = put_bits(0, 0, 12, counter_ticks) + word = put_bits(word, 12, 12, elapsed_ticks) + word = put_bits(word, 24, 8, 0x0C) + word = pack_quaternion(word, 32, 31, quaternion_wire, largest_component) + for i, value in enumerate(acceleration_g): + word = put_bits(word, 128 + 32 * i, 32, round(value * (1 << 28)), is_signed=True) + word = put_bits(word, 224, 16, temperature_raw, is_signed=True) + return word.to_bytes(30, "little") + + +def repack_decoded(decoded: DecodedBlock) -> bytes: + """Rebuild fields independently; do not copy original bytes or ratio codes. + + Rebuild gyro fields from candidate degree-per-second values as well. + """ + variant = decoded["format"] & 3 + quaternion_width, widths = LAYOUTS[variant] + word = put_bits(0, 0, 12, decoded["counter_ticks"]) + word = put_bits(word, 12, 12, decoded["elapsed_ticks"]) + word = put_bits(word, 24, 8, decoded["format"]) + start = 32 + if variant: + range_tag = decoded["range_tag"] + if range_tag is None: + raise ValueError("packed frame requires a range tag") + word = put_bits(word, start, 2, range_tag) + start += 2 + word = pack_quaternion(word, start, quaternion_width, + decoded["quaternion_wire"], decoded["largest_component"]) + position = start + 3 + 3 * quaternion_width + accel_index = rotation_index = 0 + for vector_index, width in enumerate(widths): + if vector_index % 2 == 0: + fraction_bits = 28 if variant == 0 else width - 2 + values = [round(v * (1 << fraction_bits)) + for v in decoded["accelerations"][accel_index]["g_candidate"]] + accel_index += 1 + else: + counts_per_dps = (1 << (width - 1)) / 500.0 + values = [round(v * counts_per_dps) + for v in decoded["rotation_triplets"][rotation_index]["dps_candidate"]] + rotation_index += 1 + for i, value in enumerate(values): + word = put_bits(word, position + i * width, width, value, is_signed=True) + position += 3 * width + if variant != 3: + temperature = decoded["temperature_raw_candidate"] + if temperature is None: + raise ValueError("this format requires the trailing temperature-like word") + word = put_bits(word, position, 16, temperature, is_signed=True) + return word.to_bytes(decoded["length"], "little") + + +def pcap_native_records(path: Path) -> Iterator[InputRecord]: + """Read complete decrypted native-right notifications, not BLE reassembly.""" + data = path.read_bytes() + position = 0 + endian = "<" + interfaces: list[tuple[int, int, int]] = [] + while position + 12 <= len(data): + if data[position:position + 4] == b"\x0a\x0d\x0d\x0a": + magic = data[position + 8:position + 12] + if magic not in (b"\x4d\x3c\x2b\x1a", b"\x1a\x2b\x3c\x4d"): + raise ValueError("invalid PCAPng byte-order magic") + endian = "<" if magic[0] == 0x4D else ">" + interfaces = [] + kind, size = struct.unpack_from(endian + "II", data, position) + if (size < 12 or size % 4 or position + size > len(data) or + struct.unpack_from(endian + "I", data, position + size - 4)[0] != size): + raise ValueError(f"invalid PCAPng block at {position}") + if kind == 1: + if size < 20: + raise ValueError("truncated interface description") + link_type = struct.unpack_from(endian + "H", data, position + 8)[0] + resolution, offset_seconds = 1_000_000, 0 + option = position + 16 + while option + 4 <= position + size - 4: + code, length = struct.unpack_from(endian + "HH", data, option) + option += 4 + if option + length > position + size - 4: + raise ValueError("truncated interface option") + value = data[option:option + length] + if code == 9 and length == 1: + resolution = (2 if value[0] & 128 else 10) ** (value[0] & 127) + elif code == 14 and length == 8: + offset_seconds = struct.unpack(endian + "q", value)[0] + option += (length + 3) & ~3 + if code == 0: + break + interfaces.append((link_type, resolution, offset_seconds)) + elif kind == 6: + if size < 32: + raise ValueError("truncated enhanced packet block") + interface, high, low, captured, _ = struct.unpack_from(endian + "IIIII", data, position + 8) + if interface >= len(interfaces) or captured > size - 32: + raise ValueError("invalid enhanced packet metadata") + link_type, resolution, offset_seconds = interfaces[interface] + packet = data[position + 28:position + 28 + captured] + ll_start = {256: 10, 251: 0}.get(link_type) + if ll_start is not None and len(packet) >= ll_start + 6: + ll_payload = ll_start + 6 + # LLID=2: complete first L2CAP fragment. This reader does not + # reconstruct fragmented or encrypted notifications. + if (packet[ll_start + 4] & 3 == 2 and packet[ll_start + 5] == 70 and + packet[ll_payload:ll_payload + 7] == b"\x42\x00\x04\x00\x1b\x0e\x00" and + len(packet) >= ll_payload + 70): + timestamp = (((high << 32) | low) * 1_000_000 // resolution + + offset_seconds * 1_000_000) + yield {"t_us": timestamp, + "stream": f"{interface}:{packet[ll_start:ll_start + 4].hex()}", + "native_hex": packet[ll_payload + 7:ll_payload + 70].hex()} + position += size + if position != len(data): + raise ValueError("trailing incomplete PCAPng block") + + +def records(path: Path) -> Iterator[InputRecord]: + if path.suffix.lower() == ".pcapng": + yield from pcap_native_records(path) + else: + data = json.loads(path.read_text()) + yield from data["packets"] if isinstance(data, dict) else data + + +def native_block(record: InputRecord) -> bytes: + native_hex = record.get("native_hex") + if native_hex is None: + raise ValueError("input record requires native_hex") + packet = bytes.fromhex(native_hex) + if len(packet) == 64 and packet[0] == 8: + packet = packet[1:] + if len(packet) != 63: + raise ValueError("expected 63 native08 payload bytes, optionally prefixed by report ID") + length = packet[15] + if length not in (0, 30, 40): + raise ValueError(f"unrecognized native08 IMU length {length}") + return packet[16:16 + length] + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("inputs", nargs="*", type=Path) + parser.add_argument("--block", help="decode one 30/40-byte IMU block in hexadecimal") + parser.add_argument("--summary", action="store_true", help="aggregate instead of JSON-lines output") + parser.add_argument("--verify-roundtrip", action="store_true", help="re-encode all fields and compare bytes") + args = parser.parse_args() + if bool(args.block) == bool(args.inputs): + parser.error("provide input files or --block, but not both") + counts: Counter[str] = Counter() + norms: list[float] = [] + decoded_count = 0 + empty_count = 0 + mismatch_count = 0 + timing_gaps = 0 + previous: dict[tuple[str, str], int] = {} + streams: list[tuple[str, Iterable[InputRecord]]] = [("hex", [{"block": args.block}])] if args.block else [ + (str(path), records(path)) for path in args.inputs] + try: + for source, source_records in streams: + for record in source_records: + block = bytes.fromhex(record["block"]) if "block" in record else native_block(record) + if not block: + empty_count += 1 + continue + decoded = decode_block(block) + decoded_count += 1 + counts[f"0x{decoded['format']:02x}"] += 1 + for acceleration in decoded["accelerations"]: + norms.append(math.sqrt(sum(v * v for v in acceleration["g_candidate"]))) + key = (source, record.get("stream", "default")) + if key in previous: + delta = (decoded["counter_ticks"] - previous[key]) & 0xFFF + if delta != decoded["elapsed_ticks"]: + timing_gaps += 1 + previous[key] = decoded["counter_ticks"] + if args.verify_roundtrip: + rebuilt = repack_decoded(decoded) + if decoded["format"] == 0x0C: + temperature = decoded["temperature_raw_candidate"] + if temperature is None: + raise ValueError("mode0 requires the trailing temperature-like word") + rebuilt_mode0 = encode_mode0( + decoded["counter_ticks"], decoded["elapsed_ticks"], + decoded["quaternion_wire"], decoded["accelerations"][0]["g_candidate"], + temperature, + largest_component=decoded["largest_component"]) + if rebuilt_mode0 != block: + raise ValueError("mode0 semantic encoder round trip failed") + mismatch_count += rebuilt != block + if not args.summary: + print(json.dumps({"source": source, "t_us": record.get("t_us"), **decoded})) + if decoded_count == 0: + raise ValueError("no supported native IMU blocks found") + if args.summary: + norms.sort() + print(json.dumps({ + "decoded_blocks": decoded_count, + "empty_blocks": empty_count, + "formats": dict(sorted(counts.items())), + "acceleration_vectors": len(norms), + "acceleration_norm_g_candidate": { + name: norms[round((len(norms) - 1) * fraction)] + for name, fraction in (("min", 0), ("p10", .1), ("median", .5), ("p90", .9), ("max", 1)) + }, + "counter_interval_mismatches": timing_gaps, + "roundtrip_mismatches": mismatch_count if args.verify_roundtrip else None, + "limitations": ["axis and gyro-scale qualification limited to labelled right-Joy-Con captures", + "subsample timing and cross-device tick units unconfirmed", + "temperature conversion unconfirmed", + "encoder not yet console-qualified"], + }, indent=2)) + except (ValueError, KeyError, TypeError, OSError, struct.error) as error: + print(f"decode error: {error}", file=sys.stderr) + return 1 + return int(mismatch_count != 0) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/switch2_usb_probe/bootsel.cpp b/tools/switch2_usb_probe/bootsel.cpp new file mode 100644 index 0000000..ef5a972 --- /dev/null +++ b/tools/switch2_usb_probe/bootsel.cpp @@ -0,0 +1,35 @@ +#include "bootsel.h" + +#include "adapter/adapter_mode_controller.h" +#include "usb/usb_configuration_management.h" + +namespace { +bool bootsel_accepted; +} + +bool probe_bootsel_vendor_control(uint8_t rhport, uint8_t stage, + const tusb_control_request_t* request) { + using namespace UsbConfigurationManagement; + if (request == nullptr || request->bmRequestType != 0x40 || + request->bRequest != static_cast(Operation::kBootselReboot) || + request->wValue != kRequestValue || request->wIndex != kRequestIndex || + request->wLength != kRequestHeaderSize) { + return false; + } + // The shared handler receives the envelope at SETUP and validates and + // dispatches it only at ACK, after the host's control transfer completes. + const bool accepted = + usb_configuration_management_vendor_control(rhport, stage, request); + if (accepted && stage == CONTROL_STAGE_ACK) { + bootsel_accepted = true; + } + return accepted; +} + +void probe_bootsel_task(uint32_t now_ms) { + // The native bridge does not initialize ordinary adapter-mode selection. + // A successful BOOTSEL dispatch guarantees the task takes its reboot path. + if (bootsel_accepted) { + adapter_mode_controller_task(now_ms); + } +} diff --git a/tools/switch2_usb_probe/bootsel.h b/tools/switch2_usb_probe/bootsel.h new file mode 100644 index 0000000..f40faa6 --- /dev/null +++ b/tools/switch2_usb_probe/bootsel.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +#include "tusb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Core 0: expose only the existing private BOOTSEL command, not configuration. +bool probe_bootsel_vendor_control(uint8_t rhport, uint8_t stage, + const tusb_control_request_t* request); +// Core 0: service the existing reboot delay only after a validated status ACK. +void probe_bootsel_task(uint32_t now_ms); + +#ifdef __cplusplus +} +#endif diff --git a/tools/switch2_usb_probe/controller_input.cpp b/tools/switch2_usb_probe/controller_input.cpp index cbae87d..189079d 100644 --- a/tools/switch2_usb_probe/controller_input.cpp +++ b/tools/switch2_usb_probe/controller_input.cpp @@ -8,6 +8,13 @@ #include "platform/pico/system_clock.h" #include "profile/controller_profile_runtime.h" #include "pico/stdlib.h" +#if SWITCH2_BRIDGE_WII_INPUT +#include +#include "input/wii_ir_pointer.h" +#include "native_imu.h" +#include "pico/time.h" +extern "C" int probe_debug_printf(const char* format, ...); +#endif #if !SWITCH_PICO_SWITCH2_USB_BRIDGE || !SWITCH_PICO_BLUEPAD32 || \ !SWITCH_PICO_ENABLE_BLE || !SWITCH_PICO_SWITCH2_MOUSE_CAPTURE || \ @@ -27,7 +34,323 @@ bool g_initialized; bool g_start_attempted; bool g_flash_ready; probe_controller_input g_input; +#if !SWITCH2_BRIDGE_WII_INPUT uint32_t g_received_ms; +#endif +#if SWITCH2_BRIDGE_WII_INPUT +#ifndef SWITCH2_WII_IR_SCREEN_CONFIG +#define SWITCH2_WII_IR_SCREEN_CONFIG 660, 370, 0, -115, 1920, 1080 +#endif +constexpr float kIrScreenConfig[] = {SWITCH2_WII_IR_SCREEN_CONFIG}; +static_assert(sizeof(kIrScreenConfig) / sizeof(kIrScreenConfig[0]) == 6); +bool g_screen_configured; +constexpr uint32_t kSensorDeadlineUs = 150000; +constexpr uint32_t kOutputDeadlineUs = 100000; +Bluepad32WiiBridgeSnapshot g_wii; +ProbeNativeMotion g_motion; +bool g_wii_active; +bool g_native_stream; +uint8_t g_native_features; +uint32_t g_wii_generation; +uint32_t g_orientation_requested_generation; +int g_sensor_status = -1; +uint16_t g_stick_center[2]{2048, 2048}; +uint16_t g_stick_positive[2]{2047, 2047}; +uint16_t g_stick_negative[2]{2048, 2048}; +uint8_t g_power_info = 0x24; // Nominal battery until source status; no USB-power flag. +uint8_t g_report_counter; +uint32_t g_report_serial; +uint32_t g_pending_serial; +uint32_t g_pending_us; +uint32_t g_pending_generation; +uint32_t g_pending_ticks; +uint8_t g_pending_report[63]; +WiiIrMouseReport g_pending_pointer{}; +bool g_pending_motion_ready; +bool g_clock_started; +uint32_t g_clock_us; +uint32_t g_clock_ticks; +uint32_t g_clock_fraction; +bool g_have_committed_ticks; +uint32_t g_committed_ticks; +bool g_have_submission; +uint32_t g_submitted_us; +uint32_t g_output_open_us; +#ifdef SWITCH2_PROBE_TRACE_NATIVE_INPUT +uint32_t g_last_ir_trace_us; +#endif + +void unpack_stick_pair(const uint8_t* data, uint16_t values[2]) { + values[0] = data[0] | (static_cast(data[1] & 15) << 8); + values[1] = (data[1] >> 4) | (static_cast(data[2]) << 4); +} + +uint16_t calibrated_stick_axis(int16_t value, unsigned axis, bool invert) { + const int32_t input = value; + const bool input_positive = input >= 0; + const bool output_positive = input_positive != invert; + const int32_t magnitude = input_positive ? input : -input; + const int32_t denominator = input_positive ? INT16_MAX : 32768; + const int32_t travel = output_positive ? g_stick_positive[axis] : g_stick_negative[axis]; + const int32_t displacement = (magnitude * travel + denominator / 2) / denominator; + return static_cast(g_stick_center[axis] + + (output_positive ? displacement : -displacement)); +} + +void pack_wii_controls(const ControllerProfileTransformResult& mapped) { + const ControllerState& state = mapped.state; + g_input.buttons[0] = static_cast( + (state.button_south ? 0x01 : 0) | (state.button_east ? 0x02 : 0) | + (state.button_west ? 0x04 : 0) | (state.button_north ? 0x08 : 0) | + (state.button_right_shoulder ? 0x10 : 0) | + (state.right_trigger != 0 && + state.right_trigger >= mapped.right_trigger_digital_threshold ? 0x20 : 0) | + (state.button_start ? 0x40 : 0) | (state.button_right_stick ? 0x80 : 0)); + g_input.buttons[1] = static_cast( + (state.button_system ? 0x01 : 0) | ((state.extra_buttons & 1) ? 0x10 : 0) | + ((state.extra_buttons & (1u << 5)) ? 0x80 : 0) | + ((state.extra_buttons & (1u << 6)) ? 0x40 : 0)); + // One virtual right stick: honor a mapped right stick first, otherwise the + // Nunchuk stick. Left-only buttons are not repurposed as mouse clicks. + int16_t x = state.right_stick_x; + int16_t y = state.right_stick_y; + if (x == 0 && y == 0 && g_wii.layout == Bluepad32ControllerLayout::kWiiNunchuk) { + x = state.left_stick_x; + y = state.left_stick_y; + } + const uint16_t sx = calibrated_stick_axis(x, 0, false); + const uint16_t sy = calibrated_stick_axis(y, 1, true); + g_input.stick[0] = static_cast(sx); + g_input.stick[1] = static_cast((sx >> 8) | (sy << 4)); + g_input.stick[2] = static_cast(sy >> 4); +} + +void advance_wii_clock(uint32_t now_us) { + if (!g_clock_started) { + g_clock_started = true; + g_clock_us = now_us; + return; + } + const uint64_t scaled = static_cast(now_us - g_clock_us) * 960u + + g_clock_fraction; + g_clock_us = now_us; + g_clock_ticks += static_cast(scaled / 1000000u); + g_clock_fraction = static_cast(scaled % 1000000u); +} + +bool wii_sensors_fresh(uint32_t now_us) { + return g_wii.accel_valid && g_wii.gyro_valid && + static_cast(now_us - g_wii.accel_received_us) < + static_cast(kSensorDeadlineUs) && + static_cast(now_us - g_wii.gyro_received_us) < + static_cast(kSensorDeadlineUs); +} + +#ifdef SWITCH2_PROBE_TRACE_NATIVE_INPUT +void trace_wii_ir(uint32_t now_us, bool output_enabled) { + // Ten snapshots/second keep camera diagnostics well below UART capacity. + if (now_us - g_last_ir_trace_us < 100000) return; + g_last_ir_trace_us = now_us; + uint8_t data[WII_IR_MOUSE_DIAGNOSTIC_SIZE]; + if (wii_ir_pointer_diagnostics(data, sizeof(data)) != sizeof(data)) return; + static constexpr char hex[] = "0123456789abcdef"; + char encoded[sizeof(data) * 2 + 1]; + for (size_t i = 0; i < sizeof(data); ++i) { + encoded[2 * i] = hex[data[i] >> 4]; + encoded[2 * i + 1] = hex[data[i] & 15]; + } + encoded[sizeof(encoded) - 1] = 0; + // State bits: calibrated IMU, native stream, effective IR output gate. + const unsigned state = static_cast(g_motion.ready()) | + (static_cast(g_native_stream) << 1) | + (static_cast(output_enabled) << 2); + probe_debug_printf("[PROBE %lu] WII_IR_DIAGNOSTIC state=%u len=%u: %s\n", + static_cast(to_ms_since_boot(get_absolute_time())), state, + static_cast(sizeof(data)), encoded); +} +#endif + +void update_wii_ir_gate(uint32_t now_us) { + const uint32_t last_progress = g_have_submission ? g_submitted_us : g_output_open_us; + const bool output_fresh = static_cast(now_us - last_progress) < + static_cast(kOutputDeadlineUs); + const bool enabled = g_native_stream && g_wii_active && + g_motion.ready() && wii_sensors_fresh(now_us) && output_fresh && + (g_native_features & 0x10); + wii_ir_mouse_set_output_enabled(enabled); +#ifdef SWITCH2_PROBE_TRACE_NATIVE_INPUT + trace_wii_ir(now_us, enabled); +#endif +} + +void discard_wii_output() { + g_pending_serial = 0; + g_have_committed_ticks = false; + g_have_submission = false; + g_output_open_us = time_us_32(); + wii_ir_mouse_set_output_enabled(false); +} + +void lose_wii_source() { + if (g_wii_active) { + g_motion.reset(); + discard_wii_output(); + g_sensor_status = -1; + } + g_wii_active = false; + g_input = {}; +} + +void poll_wii_source(uint32_t now_ms) { + bluepad32_input_backend_wii_snapshot(&g_wii); + // Read the clock after the coherent snapshot so Core1 receipt timestamps + // cannot appear to be in the future to the motion integrator. + const uint32_t now_us = time_us_32(); + advance_wii_clock(now_us); + if (!g_wii.controller.active || g_wii.slot >= BLUEPAD32_INPUT_BACKEND_SLOT_COUNT || + static_cast(now_us - g_wii.received_us) >= + static_cast(kInputDeadlineMs * 1000u)) { + lose_wii_source(); + g_orientation_requested_generation = 0; + return; + } + if (g_wii.layout == Bluepad32ControllerLayout::kWiiHorizontal) { + if (g_orientation_requested_generation != g_wii.controller.connection_generation && + bluepad32_input_backend_set_wii_orientation(g_wii.controller.identity, + g_wii.controller.connection_generation, true)) { + g_orientation_requested_generation = g_wii.controller.connection_generation; + } + lose_wii_source(); + return; // Never emit a transient sideways mapping while Core1 switches. + } + if (!g_wii_active || g_wii_generation != g_wii.controller.connection_generation) { + discard_wii_output(); + g_motion.reset(); + g_wii_generation = g_wii.controller.connection_generation; + g_sensor_status = -1; +#ifdef SWITCH2_PROBE_TRACE_NATIVE_INPUT + g_last_ir_trace_us = now_us; +#endif + g_power_info = 0x24; + probe_debug_printf("[PROBE] Wii source active in slot %u; keep still for native motion calibration\n", + g_wii.slot); + } + g_wii_active = true; + g_input.active = true; + g_input.serial = g_wii.state_generation; + g_input.native_status = static_cast(0x30 | ((g_native_features & 0x20) ? 8 : 0)); + const ControllerProfileTransformResult mapped = controller_profile_runtime_transform( + g_wii.slot, g_wii.controller, now_ms, AdapterUsbMode::kSwitch); + pack_wii_controls(mapped); + ControllerProfileRuntimeProfileChangeEvent feedback{}; + if (controller_profile_runtime_take_initial_profile_indication(g_wii.slot, &feedback) || + controller_profile_runtime_take_profile_change(g_wii.slot, &feedback)) { + bluepad32_input_backend_queue_profile_feedback(g_wii.slot, + feedback.connection_generation, feedback.active_profile_number, feedback.policy); + } + if (g_wii.battery != 0) { + const unsigned level = (static_cast(g_wii.battery) * 9u + 127u) / 255u; + g_power_info = static_cast(level << 2); + } + ProbeNativeMotionSample motion{}; + motion.accel_valid = g_wii.accel_valid; + motion.gyro_valid = g_wii.gyro_valid; + motion.accel_sequence = g_wii.accel_sequence; + motion.gyro_sequence = g_wii.gyro_sequence; + motion.accel_us = g_wii.accel_received_us; + motion.gyro_us = g_wii.gyro_received_us; + // SDL -> physical right frame [X,-Z,Y], then a +90-degree mouse mounting + // rotation about forward Y. A face-up Wii becomes rail-down native +X gravity. + motion.accel_g[0] = static_cast(g_wii.accel_q13[1]) / 8192.0f; + motion.accel_g[1] = -static_cast(g_wii.accel_q13[2]) / 8192.0f; + motion.accel_g[2] = -static_cast(g_wii.accel_q13[0]) / 8192.0f; + motion.gyro_dps[0] = static_cast(g_wii.gyro_q10[1]) / 1024.0f; + motion.gyro_dps[1] = -static_cast(g_wii.gyro_q10[2]) / 1024.0f; + motion.gyro_dps[2] = -static_cast(g_wii.gyro_q10[0]) / 1024.0f; + g_motion.update(now_us, g_wii_generation, motion); + WiiIrMouseReport optical{}; + (void)wii_ir_mouse_peek(&optical, 0); + // Core 1 may publish during the peek. Read the clock after the snapshot. + g_motion.observe_optical_heading(time_us_32(), optical.generation, + optical.optical_sequence, optical.optical_received_us, optical.optical_yaw_radians, + optical.tracking && optical.optical_valid && optical.owner == g_wii.slot && + optical.connection_generation == g_wii_generation); + const int sensor_status = !wii_sensors_fresh(now_us) ? 0 : g_motion.ready() ? 2 : 1; + if (sensor_status != g_sensor_status) { + g_sensor_status = sensor_status; + if (sensor_status == 2) { + const float* bias = g_motion.bias(); + probe_debug_printf("[PROBE] Wii native IMU ready; bias_mdeg_s=%ld,%ld,%ld\n", + lroundf(bias[0] * 1000), lroundf(bias[1] * 1000), + lroundf(bias[2] * 1000)); + } else { + probe_debug_printf("[PROBE] Wii native IMU %s\n", sensor_status ? + "calibrating: keep still" : "waiting for fresh calibrated accelerometer/MotionPlus"); + } + } + update_wii_ir_gate(now_us); +} + +uint32_t prepare_wii_report(uint8_t report[63]) { + if (!report || !g_native_stream || !g_wii_active) return 0; + const uint32_t now_us = time_us_32(); + if (static_cast(now_us - g_wii.received_us) >= + static_cast(kInputDeadlineMs * 1000u)) return 0; + advance_wii_clock(now_us); + update_wii_ir_gate(now_us); + WiiIrMouseReport pointer{}; + (void)wii_ir_mouse_peek(&pointer, INT16_MAX); + const bool motion_ready = g_motion.ready() && wii_sensors_fresh(now_us); + if (g_pending_serial && + (g_pending_generation != g_wii_generation || + g_pending_pointer.generation != pointer.generation || + g_pending_motion_ready != motion_ready || + static_cast(now_us - g_pending_us) >= static_cast(kOutputDeadlineUs))) { + g_pending_serial = 0; + } + if (g_pending_serial) { + memcpy(report, g_pending_report, sizeof(g_pending_report)); + return g_pending_serial; + } + if (g_report_serial == UINT32_MAX) return 0; // Never reuse a submission token. + memset(g_pending_report, 0, sizeof(g_pending_report)); + g_pending_report[0] = g_report_counter; + g_pending_report[1] = g_power_info; + memcpy(g_pending_report + 2, g_input.buttons, sizeof(g_input.buttons)); + g_pending_report[4] = 7; + memcpy(g_pending_report + 5, g_input.stick, sizeof(g_input.stick)); + g_pending_report[8] = g_input.native_status; + g_pending_report[13] = 0xff; // Observed no-surface value. + g_pending_ticks = g_clock_ticks; + const uint32_t elapsed = g_have_committed_ticks ? g_pending_ticks - g_committed_ticks : 1; + const uint16_t wire_elapsed = static_cast(elapsed <= 0xfff ? elapsed : 1); + const bool have_motion = g_motion.ready() && wii_sensors_fresh(now_us) && + probe_native_imu_pack(g_motion.quaternion(), g_motion.acceleration(), + static_cast(g_pending_ticks & 0xfff), wire_elapsed, 0, + g_pending_report + 16); + if (have_motion) g_pending_report[15] = 30; + if (have_motion && pointer.tracking && pointer.owner == g_wii.slot && + pointer.connection_generation == g_wii_generation) { + const uint16_t dx = static_cast(pointer.dx); + // Native Joy-Con Y is opposite to the shared desktop-pointer convention. + // Keep the original pointer delta for commit/consumption below. + const uint16_t dy = static_cast(-pointer.dy); + g_pending_report[9] = static_cast(dx); + g_pending_report[10] = static_cast(dx >> 8); + g_pending_report[11] = static_cast(dy); + g_pending_report[12] = static_cast(dy >> 8); + g_pending_report[13] = 20; // Observed contact-range value for virtual IR tracking. + } + // IR buttons are deliberately NOT mapped to desktop/native click buttons. + g_pending_pointer = pointer; + g_pending_motion_ready = have_motion; + g_pending_generation = g_wii_generation; + g_pending_us = now_us; + g_pending_serial = ++g_report_serial; + memcpy(report, g_pending_report, sizeof(g_pending_report)); + return g_pending_serial; +} +#endif } // namespace extern "C" void probe_controller_input_clock_init(void) { @@ -36,11 +359,19 @@ extern "C" void probe_controller_input_clock_init(void) { extern "C" void probe_controller_input_init(void) { if (g_initialized) return; +#if SWITCH2_BRIDGE_WII_INPUT + bluepad32_input_backend_init(); + bluepad32_input_backend_select_wii_source(kSourceAddress); + g_screen_configured = wii_ir_pointer_configure_screen( + kIrScreenConfig[0], kIrScreenConfig[1], kIrScreenConfig[2], + kIrScreenConfig[3], kIrScreenConfig[4], kIrScreenConfig[5]); + if (!g_screen_configured) probe_debug_printf("[PROBE] Invalid native IR viewport configuration\n"); + wii_ir_mouse_set_output_enabled(false); +#else switch2_mouse_capture_init(); switch2_mouse_capture_select_input(kSourceAddress); - // Prepare the existing storage services without initializing legacy USB. - // Core 1 loads their persisted state during the normal backend startup. bluepad32_input_backend_init(); +#endif controller_profile_runtime_reset(); g_initialized = true; } @@ -48,6 +379,9 @@ extern "C" void probe_controller_input_init(void) { extern "C" bool probe_controller_input_start(void) { if (!g_initialized) probe_controller_input_init(); if (g_start_attempted) return g_flash_ready; +#if SWITCH2_BRIDGE_WII_INPUT + if (!g_screen_configured) return false; +#endif g_start_attempted = true; bluepad32_input_backend_start(); const absolute_time_t deadline = make_timeout_time_ms(kFlashCoordinationTimeoutMs); @@ -75,19 +409,61 @@ extern "C" bool probe_controller_input_pairing_task(void) { return true; } +#if SWITCH2_BRIDGE_WII_INPUT +extern "C" void probe_controller_input_set_stick_calibration(const uint8_t calibration[9]) { + if (!calibration) return; + unpack_stick_pair(calibration, g_stick_center); + unpack_stick_pair(calibration + 3, g_stick_positive); + unpack_stick_pair(calibration + 6, g_stick_negative); + g_pending_serial = 0; +} + +extern "C" void probe_controller_input_set_native_features(uint8_t features) { + if (g_native_features == features) return; + g_native_features = features; + g_pending_serial = 0; + update_wii_ir_gate(time_us_32()); +} +#endif + extern "C" void probe_controller_input_set_native_stream(bool enabled) { +#if SWITCH2_BRIDGE_WII_INPUT + enabled = enabled && g_flash_ready; + if (g_native_stream != enabled || !enabled) discard_wii_output(); + g_native_stream = enabled; + update_wii_ir_gate(time_us_32()); +#else switch2_mouse_capture_set_native_stream(g_flash_ready && enabled); +#endif } extern "C" uint32_t probe_controller_input_peek_native_report( uint32_t now_ms, uint8_t report[63]) { if (!g_flash_ready) return 0; +#if SWITCH2_BRIDGE_WII_INPUT + (void)now_ms; + return prepare_wii_report(report); +#else return switch2_mouse_capture_peek_native_report(now_ms, report); +#endif } extern "C" bool probe_controller_input_commit_native_report(uint32_t serial) { if (!g_flash_ready) return false; +#if SWITCH2_BRIDGE_WII_INPUT + if (!g_native_stream || !serial || serial != g_pending_serial || + g_pending_generation != g_wii_generation || !g_wii_active) return false; + wii_ir_mouse_commit(g_pending_pointer); + g_pending_serial = 0; + g_committed_ticks = g_pending_ticks; + g_have_committed_ticks = true; + g_have_submission = true; + g_submitted_us = time_us_32(); + ++g_report_counter; + return true; +#else return switch2_mouse_capture_commit_native_report(serial); +#endif } extern "C" bool probe_controller_input_play_sample(uint8_t sample_id, uint64_t* token) { @@ -95,17 +471,30 @@ extern "C" bool probe_controller_input_play_sample(uint8_t sample_id, uint64_t* if (token != nullptr) *token = 0; return false; } +#if SWITCH2_BRIDGE_WII_INPUT + return bluepad32_input_backend_wii_sample_request(sample_id, token); +#else return switch2_mouse_capture_request_sample( sample_id, to_ms_since_boot(get_absolute_time()), token); +#endif } extern "C" int probe_controller_input_sample_result(uint64_t token, uint32_t now_ms) { if (!g_flash_ready) return -1; +#if SWITCH2_BRIDGE_WII_INPUT + (void)now_ms; + return bluepad32_input_backend_wii_sample_result(token); +#else return switch2_mouse_capture_sample_result(token, now_ms); +#endif } extern "C" void probe_controller_input_cancel_sample(void) { +#if SWITCH2_BRIDGE_WII_INPUT + bluepad32_input_backend_wii_sample_cancel(); +#else switch2_mouse_capture_cancel_sample(); +#endif } extern "C" void probe_controller_input_poll(uint32_t now_ms, @@ -115,13 +504,14 @@ extern "C" void probe_controller_input_poll(uint32_t now_ms, *out = {}; return; } +#if SWITCH2_BRIDGE_WII_INPUT + poll_wii_source(now_ms); +#else Switch2MouseCaptureInput sample; if (switch2_mouse_capture_latest_input(g_input.serial, &sample)) { g_input.serial = sample.serial; g_input.active = sample.active; g_received_ms = sample.received_ms; - // Preserve physical byte meaning: never route through the generic - // solo Joy-Con rotation/mapping. Teardown fields are already zeroed. memcpy(g_input.buttons, sample.buttons, sizeof(g_input.buttons)); memcpy(g_input.stick, sample.stick, sizeof(g_input.stick)); g_input.native_status = sample.native_status; @@ -130,11 +520,8 @@ extern "C" void probe_controller_input_poll(uint32_t now_ms, g_input.mouse_total_y = sample.mouse_total_y; g_input.mouse_surface = sample.mouse_surface; } - // The producer can be a millisecond ahead of the caller's pre-poll clock. - // Signed elapsed time tolerates that race and ordinary uint32_t rollover. - // Expiration latches inactive until a newer capture serial arrives. - if (g_input.active && - static_cast(now_ms - g_received_ms) >= + // A producer timestamp can be slightly ahead of this pre-poll clock. + if (g_input.active && static_cast(now_ms - g_received_ms) >= static_cast(kInputDeadlineMs)) { g_input.active = false; memset(g_input.buttons, 0, sizeof(g_input.buttons)); @@ -145,5 +532,6 @@ extern "C" void probe_controller_input_poll(uint32_t now_ms, g_input.mouse_total_y = 0; g_input.mouse_surface = 0; } +#endif *out = g_input; } diff --git a/tools/switch2_usb_probe/controller_input.h b/tools/switch2_usb_probe/controller_input.h index 689fbb0..ae344f0 100644 --- a/tools/switch2_usb_probe/controller_input.h +++ b/tools/switch2_usb_probe/controller_input.h @@ -36,30 +36,34 @@ bool probe_controller_input_start(void); // True means a Bluetooth pairing-window request was queued. Long holds NEVER // clear pairings in this bridge, and this does not inject USB controller input. bool probe_controller_input_pairing_task(void); -// Core 0 native 08 relay: disabled until explicitly enabled after flash-ready -// startup. Disable clears queued data, repeated enable preserves it. Resets -// must disable the stream; this never changes Bluetooth bonds or pairing. -// Only subsequent selected-source packets enter the separate 32-entry FIFO. -// Overflow drops queued history and retains only the arriving packet. +#if SWITCH2_BRIDGE_WII_INPUT +// Main supplies the same validated calibration record advertised to the host. +void probe_controller_input_set_stick_calibration(const uint8_t calibration[9]); +// Native feature changes are output barriers, not Bluetooth/IMU resets. +void probe_controller_input_set_native_features(uint8_t features); +#endif +// Core0 native08 output. Disable discards queued/prepared data; repeated enable +// preserves it. Joy-Con mode relays its bounded FIFO; Wii mode synthesizes from +// fresh calibrated sensors and the selected IR pointer. No pairing changes. void probe_controller_input_set_native_stream(bool enabled); -// Copy a full opaque 63-byte payload (without report ID), oldest first. Returns -// its never-reused boot-lifetime serial; 0 leaves report untouched. Latest source -// or head >=500 ms old discards the FIFO; now_ms is the Pico boot-ms clock. -// Nondestructive until successful HID submission followed by commit. +// Copy one63-byte payload without report ID. Returns a boot-unique token, or0 +// without changing output. Nondestructive until successful HID submission and +// commit. now_ms uses the Pico boot-ms clock; unavailable/stale input is rejected. uint32_t probe_controller_input_peek_native_report(uint32_t now_ms, uint8_t report[63]); // Remove only the exact current head once. A stale/replaced token cannot pop a // new stream's packet. Before flash-ready startup peek/commit return 0/false. bool probe_controller_input_commit_native_report(uint32_t serial); // Built-in vibration samples only; raw HD-rumble output is not forwarded. -// A nonzero token means queued, not acknowledged. Result: 0 pending, 1 real -// source ACK, -1 failed/stale. Reset cancels the request, never stored pairing. +// A nonzero token means queued, not completed. Result:0 pending,1 completion, +// -1 failed/stale. Joy-Con completion is its application ACK; Wii completion is +// actual bounded rumble-driver dispatch (not an HD-waveform fidelity claim). +// Reset cancels the request, never stored pairing. bool probe_controller_input_play_sample(uint8_t sample_id, uint64_t* token); int probe_controller_input_sample_result(uint64_t token, uint32_t now_ms); void probe_controller_input_cancel_sample(void); -// Core 0 at 250 Hz; now_ms uses the Pico boot-millisecond clock. Only fresh -// native 08 buttons/stick and cumulative mouse totals are exposed. Inactive -// fields are zero except serial; the USB protocol must supply its calibrated -// stick center rather than forwarding inactive stick bytes. +// Core0 at250Hz; now_ms uses Pico boot milliseconds. Supplies current mapped +// controls for diagnostic reports; the native sender owns motion consumption. +// Inactive controls are zero except serial; USB supplies its calibrated center. void probe_controller_input_poll(uint32_t now_ms, probe_controller_input* out); #ifdef __cplusplus diff --git a/tools/switch2_usb_probe/main.c b/tools/switch2_usb_probe/main.c index 390d122..6727aaa 100644 --- a/tools/switch2_usb_probe/main.c +++ b/tools/switch2_usb_probe/main.c @@ -9,6 +9,7 @@ #include #ifdef SWITCH_PICO_SWITCH2_USB_BRIDGE +#include "bootsel.h" #include "controller_input.h" #else #include "platform/pico/bootsel_button_sample.h" @@ -63,6 +64,9 @@ static uint32_t last_hid_complete_ms; static bool hid_completion_seen; static uint32_t mouse_delivered_reports, mouse_logged_reports; static int64_t mouse_delivered_x, mouse_delivered_y; +#ifdef SWITCH2_PROBE_TRACE_NATIVE_INPUT +static uint32_t last_native_trace_ms; +#endif #endif #ifndef SWITCH_PICO_SWITCH2_USB_BRIDGE static probe_button_state button_test; @@ -214,8 +218,13 @@ static void reset_protocol(void) { protocol.play_sample = probe_controller_input_play_sample; #endif #ifdef SWITCH2_PROBE_MEMORY - if (!probe_memory_right_stick_center(protocol.right_stick_center)) + uint8_t stick_calibration[9]; + if (!probe_memory_right_stick_calibration(stick_calibration)) panic("Invalid captured Joy-Con stick calibration"); + memcpy(protocol.right_stick_center, stick_calibration, sizeof(protocol.right_stick_center)); +#if SWITCH2_BRIDGE_WII_INPUT + probe_controller_input_set_stick_calibration(stick_calibration); +#endif protocol.read_memory = probe_memory_read; #endif uint8_t pairing[PROBE_PAIRING_BLOB_SIZE]; @@ -230,12 +239,18 @@ static void reset_protocol(void) { command_expected = 8; last_input_ms = 0; #ifdef SWITCH_PICO_SWITCH2_USB_BRIDGE +#if SWITCH2_BRIDGE_WII_INPUT + probe_controller_input_set_native_features(0); +#endif last_controller_poll_ms = 0; last_delivered_buttons = 0; probe_controller_input_set_native_stream(false); native_stream_ready = false; last_hid_complete_ms = 0; hid_completion_seen = false; +#ifdef SWITCH2_PROBE_TRACE_NATIVE_INPUT + last_native_trace_ms = 0; +#endif #endif #ifndef SWITCH_PICO_SWITCH2_USB_BRIDGE (void)probe_button_update(&button_test, -1, false); @@ -267,12 +282,15 @@ static void complete_command(void) { previous_features != protocol.enabled_features) { probe_controller_input_set_native_stream(false); native_stream_ready = false; +#if SWITCH2_BRIDGE_WII_INPUT + probe_controller_input_set_native_features(protocol.enabled_features); +#endif } #endif reply->length = (uint8_t)length; ++reply_count; if (reply->deferred_token) { - probe_debug_printf("[PROBE] Sample %u awaiting source ACK token=%" PRIu64 "\n", + probe_debug_printf("[PROBE] Sample %u awaiting source completion token=%" PRIu64 "\n", command_frame[8], reply->deferred_token); } else { log_packet("BULK_REPLY_QUEUED", 0, 0, reply->data, reply->length); @@ -364,11 +382,23 @@ static void controller_input_task(uint32_t now) { } static void gate_native_report(uint8_t input[PROBE_INPUT_SIZE]) { +#if SWITCH2_BRIDGE_WII_INPUT + // Generated status follows virtual feature state, not a donor snapshot. + input[8] = (uint8_t)(0x30 | ((protocol.enabled_features & 0x20) ? 8 : 0)); +#endif if (!(protocol.enabled_features & 1)) memset(input + 2, 0, 2); if (!(protocol.enabled_features & 2)) memcpy(input + 5, protocol.right_stick_center, sizeof(protocol.right_stick_center)); if (!(protocol.enabled_features & 0x10)) memset(input + 9, 0, 5); +#ifdef SWITCH2_PROBE_OMIT_NATIVE_IMU + // Deliberate A/B fault injection: leave every other field and feature bit intact. + memset(input + 15, 0, 41); +#elif defined(SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD) + if (!(protocol.enabled_features & 4)) input[15] = 0; + memset(input + 16, 0, 40); // Otherwise preserve the genuine length byte. +#else if (!(protocol.enabled_features & 4)) memset(input + 15, 0, 41); +#endif } #endif @@ -381,8 +411,13 @@ static void protocol_task(uint32_t now) { if (!ready) { const int result = probe_controller_input_sample_result(reply->deferred_token, now); if (result > 0) { +#if SWITCH2_BRIDGE_WII_INPUT + probe_debug_printf("[PROBE] Wii cue dispatched token=%" PRIu64 "\n", + reply->deferred_token); +#else probe_debug_printf("[PROBE] Source sample ACK token=%" PRIu64 "\n", reply->deferred_token); +#endif reply->deferred_token = 0; ready = true; log_packet("BULK_REPLY_QUEUED", 0, 0, reply->data, reply->length); @@ -468,6 +503,13 @@ void tud_hid_report_complete_cb(uint8_t instance, const uint8_t* report, uint16_ if (report[0] == 0x08) { const int32_t dx = signed_mouse_delta(report + 10); const int32_t dy = signed_mouse_delta(report + 12); +#ifdef SWITCH2_PROBE_TRACE_NATIVE_INPUT + if ((uint32_t)(last_hid_complete_ms - last_native_trace_ms) >= 1000) { + last_native_trace_ms = last_hid_complete_ms; + // Observe the completed transfer, not a proposed or ungated report. + log_packet("NATIVE_INPUT_DELIVERED", instance, report[0], report, length); + } +#endif if (dx || dy) { ++mouse_delivered_reports; mouse_delivered_x += dx; @@ -529,6 +571,10 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request) { if (stage == CONTROL_STAGE_SETUP) log_packet("VENDOR_CONTROL", rhport, 0, (const uint8_t*)request, sizeof(*request)); +#ifdef SWITCH_PICO_SWITCH2_USB_BRIDGE + if (probe_bootsel_vendor_control(rhport, stage, request)) + return true; +#endif #ifdef SWITCH2_PROBE_IDENTITY_REPLY if (request->bmRequestType == 0xc0 && request->bRequest == 0x03 && request->wValue == 0 && request->wIndex == 0) { @@ -611,9 +657,18 @@ int main(void) { #else probe_debug_printf("\n[PROBE] Joy-Con 2 (R) USB enumeration recorder\n"); #endif +#ifdef SWITCH2_PROBE_OMIT_NATIVE_IMU + probe_debug_printf("[PROBE] ACTIVATION_TEST=no-imu: native08 bytes 15..55 omitted; features, power, status, counters and cadence unchanged\n"); +#elif defined(SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD) + probe_debug_printf("[PROBE] ACTIVATION_TEST=zero-imu-payload: native08 bytes 16..55 zeroed; length, features and all other fields unchanged\n"); +#endif #ifdef SWITCH_PICO_SWITCH2_USB_BRIDGE probe_controller_input_init(); +#if SWITCH2_BRIDGE_WII_INPUT + probe_debug_printf("[PROBE] UART0 GP0=TX, 115200 8N1; selected Wii IR/MotionPlus source enabled\n"); +#else probe_debug_printf("[PROBE] UART0 GP0=TX, 115200 8N1; selected right Joy-Con Bluetooth source enabled\n"); +#endif #else probe_debug_printf("[PROBE] UART0 GP0=TX, 115200 8N1; Bluetooth disabled\n"); #endif @@ -633,7 +688,12 @@ int main(void) { probe_debug_printf("[PROBE] Own virtual pairing storage offset=%08" PRIx32 "\n", probe_storage_offset()); #ifdef SWITCH_PICO_SWITCH2_USB_BRIDGE +#if SWITCH2_BRIDGE_WII_INPUT + probe_debug_printf("[PROBE] Wii IR drives native mouse movement; buttons retain profile mapping; keep Wii still for MotionPlus calibration\n"); + probe_debug_printf("[PROBE] Hold BOOTSEL2s for pairing; Wii cue feedback uses bounded ERM patterns, not HD audio waveforms\n"); +#else probe_debug_printf("[PROBE] Live right Joy-Con buttons/stick/native mouse; hold BOOTSEL 2s for Bluetooth pairing (never clears pairings)\n"); +#endif #else probe_debug_printf("[PROBE] Manual input test: hold BOOTSEL for SL+SR, release for neutral; no controller forwarding\n"); #endif @@ -650,6 +710,9 @@ int main(void) { tud_task(); drain_log(); const uint32_t now = to_ms_since_boot(get_absolute_time()); +#ifdef SWITCH_PICO_SWITCH2_USB_BRIDGE + probe_bootsel_task(now); +#endif #ifdef SWITCH2_PROBE_USB_INIT #ifdef SWITCH_PICO_SWITCH2_USB_BRIDGE if (probe_controller_input_pairing_task()) diff --git a/tools/switch2_usb_probe/memory.c b/tools/switch2_usb_probe/memory.c index 4a1794b..9c82609 100644 --- a/tools/switch2_usb_probe/memory.c +++ b/tools/switch2_usb_probe/memory.c @@ -43,7 +43,7 @@ static bool valid_calibration(const uint8_t* data) { return true; } -bool probe_memory_right_stick_center(uint8_t output[3]) { +bool probe_memory_right_stick_calibration(uint8_t output[9]) { if (!output) return false; // A solo Joy-Con uses the primary calibration record, even for the right // controller. User magic precedes its 9-byte record; factory has no magic. @@ -52,6 +52,6 @@ bool probe_memory_right_stick_center(uint8_t output[3]) { if (user[0] == 0xb2 && user[1] == 0xa1 && valid_calibration(user + 2)) selected = user + 2; if (!valid_calibration(selected)) return false; - memcpy(output, selected, 3); + memcpy(output, selected, 9); return true; } diff --git a/tools/switch2_usb_probe/memory.h b/tools/switch2_usb_probe/memory.h index f2d5882..2bc4327 100644 --- a/tools/switch2_usb_probe/memory.h +++ b/tools/switch2_usb_probe/memory.h @@ -4,4 +4,5 @@ #include bool probe_memory_read(uint32_t address, uint8_t* output, size_t length); -bool probe_memory_right_stick_center(uint8_t output[3]); +// Packed center, positive travel, negative travel (two12-bit axes each). +bool probe_memory_right_stick_calibration(uint8_t output[9]); diff --git a/tools/switch2_usb_probe/native_imu.cpp b/tools/switch2_usb_probe/native_imu.cpp new file mode 100644 index 0000000..d88886b --- /dev/null +++ b/tools/switch2_usb_probe/native_imu.cpp @@ -0,0 +1,440 @@ +#include "native_imu.h" + +#include +#include + +namespace { +constexpr uint32_t kFreshUs = 150000; +constexpr uint32_t kMaximumUpdateGapUs = 50000; +constexpr uint32_t kCalibrationUs = 1500000; +constexpr uint32_t kCalibrationSamples = 64; +constexpr uint32_t kVariationSamples = 16; +// The stationary Wii trace has 0.383 dps / 0.010 g vector RMS variation; +// quantized sample-to-sample steps reach 0.806 dps / 0.030 g. Judge variance +// over distinct samples, with roughly twice that measured noise allowance. +constexpr float kGyroRmsDps = 0.75f; +constexpr float kAccelRmsG = 0.025f; +// One degree between averaged gravity directions, independent of g scale. +constexpr float kGravityDirectionCosSquared = 0.9996954135f; +constexpr float kGravityTimeConstantUs = 1000000.0f; +constexpr float kRadiansPerDegree = 0.017453292519943295f; +constexpr float kTwoPi = 6.2831853071795864769f; +// A two-second complementary heading correction, driven by distinct optical +// sample times rather than polling frequency. Reuse the 150ms sensor lifetime. +constexpr float kOpticalTimeConstantUs = 2000000.0f; +// Reject camera-forward directions within about 14.5 degrees of world vertical. +constexpr float kMinimumOpticalHorizontalSquared = 0.25f * 0.25f; + +bool finite_vector(const float* values, unsigned count) { + for (unsigned i = 0; i < count; ++i) { + if (!std::isfinite(values[i])) return false; + } + return true; +} + +float squared_norm(const float values[3]) { + return values[0] * values[0] + values[1] * values[1] + values[2] * values[2]; +} + +bool accumulate_stationary(const float sample[3], uint32_t count, float mean[3], + float& variation, float rms_limit) { + if (count == 1) { + for (unsigned i = 0; i < 3; ++i) mean[i] = sample[i]; + variation = 0.0f; + return true; + } + // Welford's sum of squared vector deviations avoids subtracting the large + // uncalibrated bias from a sum of squares. No samples or heap state retained. + const float weight = 1.0f / static_cast(count); + float deviation_squared = 0.0f; + for (unsigned i = 0; i < 3; ++i) { + const float delta = sample[i] - mean[i]; + deviation_squared += delta * delta; + mean[i] += delta * weight; + variation += delta * (sample[i] - mean[i]); + } + const float variance_limit = rms_limit * rms_limit; + // A four-RMS excursion discards impulses immediately instead of letting a + // long quiet prefix dilute them. Ordinary quantization is judged by RMS. + return std::isfinite(deviation_squared) && std::isfinite(variation) && + deviation_squared < 16.0f * variance_limit && + (count < kVariationSamples || variation < static_cast(count - 1) * variance_limit); +} + +// Match the reference codec's nearest-even rounding without double arithmetic +// or a dependency on the process floating-point rounding mode. Callers ensure +// the input and its rounded result fit int32_t. +int32_t round_even(float value) { + int32_t integral = static_cast(value); + const float remainder = value - static_cast(integral); + if (remainder > 0.5f || (remainder == 0.5f && (integral & 1))) ++integral; + if (remainder < -0.5f || (remainder == -0.5f && (integral & 1))) --integral; + return integral; +} + +uint32_t ratio_code(float ratio) { + // Add the midpoint as an integer: (ratio + 1.0f) would first discard low + // ratio bits. The +1 endpoint is 2^31, outside the unsigned 31-bit field. + const int32_t offset = round_even(ratio * 1073741824.0f); + const uint32_t code = static_cast(offset) + UINT32_C(0x40000000); + return code > UINT32_C(0x7fffffff) ? UINT32_C(0x7fffffff) : code; +} + +int32_t acceleration_code(float acceleration) { + if (acceleration >= 8.0f) return INT32_MAX; + if (acceleration <= -8.0f) return INT32_MIN; + return round_even(acceleration * 268435456.0f); +} + +void put_u32(uint8_t* output, uint32_t value) { + output[0] = static_cast(value); + output[1] = static_cast(value >> 8); + output[2] = static_cast(value >> 16); + output[3] = static_cast(value >> 24); +} +} // namespace + +extern "C" bool probe_native_imu_pack(const float quaternion_wxyz[4], const float accel_g[3], + uint16_t counter_ticks, uint16_t elapsed_ticks, + int16_t temperature_raw, uint8_t output[30]) { + if (!quaternion_wxyz || !accel_g || !output || counter_ticks > 0x0fff || + elapsed_ticks > 0x0fff || !finite_vector(quaternion_wxyz, 4) || !finite_vector(accel_g, 3)) { + return false; + } + unsigned largest = 0; + for (unsigned i = 1; i < 4; ++i) { + if (std::fabs(quaternion_wxyz[i]) > std::fabs(quaternion_wxyz[largest])) largest = i; + } + if (quaternion_wxyz[largest] == 0.0f) return false; + + uint32_t ratios[3]; + for (unsigned i = 0; i < 3; ++i) { + ratios[i] = ratio_code(quaternion_wxyz[(largest + i + 1) & 3] / quaternion_wxyz[largest]); + } + output[0] = static_cast(counter_ticks); + output[1] = static_cast((counter_ticks >> 8) | (elapsed_ticks << 4)); + output[2] = static_cast(elapsed_ticks >> 4); + output[3] = 0x0c; + put_u32(output + 4, largest | (ratios[0] << 3)); + put_u32(output + 8, (ratios[0] >> 29) | (ratios[1] << 2)); + put_u32(output + 12, (ratios[1] >> 30) | (ratios[2] << 1)); + for (unsigned i = 0; i < 3; ++i) { + put_u32(output + 16 + i * 4, static_cast(acceleration_code(accel_g[i]))); + } + const uint16_t temperature = static_cast(temperature_raw); + output[28] = static_cast(temperature); + output[29] = static_cast(temperature >> 8); + return true; +} + +void ProbeNativeMotion::reset() { + *this = ProbeNativeMotion{}; +} + +void ProbeNativeMotion::clear_candidate() { + candidate_ = false; + gyro_count_ = 0; + accel_count_ = 0; +} + +void ProbeNativeMotion::invalidate() { + ready_ = false; + have_accel_ = false; + have_gyro_ = false; + have_optical_reference_ = false; + have_optical_sample_ = false; + clear_candidate(); + quaternion_[0] = 1.0f; + for (unsigned i = 0; i < 3; ++i) { + quaternion_[i + 1] = 0.0f; + acceleration_[i] = 0.0f; + gyro_dps_[i] = 0.0f; + bias_[i] = 0.0f; + } + // Keep the last observed identities until a connection change or explicit + // reset. Restoring availability cannot turn the same packet into new data. +} + +bool ProbeNativeMotion::initialize_orientation() { + const float norm = std::sqrt(squared_norm(mean_accel_)); + if (!std::isfinite(norm) || norm <= 0.0f) return false; + const float x = mean_accel_[0] / norm; + const float y = mean_accel_[1] / norm; + const float z = mean_accel_[2] / norm; + const float horizontal = std::sqrt(x * x + y * y); + quaternion_[3] = 0.0f; + if (horizontal > 0.0f) { + // atan2 remains well conditioned near -Z, unlike normalizing [1+z,y,-x,0]. + const float half_angle = 0.5f * std::atan2(horizontal, z); + const float sine = std::sin(half_angle); + quaternion_[0] = std::cos(half_angle); + quaternion_[1] = (y / horizontal) * sine; + quaternion_[2] = (-x / horizontal) * sine; + } else { + quaternion_[0] = z >= 0.0f ? 1.0f : 0.0f; + quaternion_[1] = z >= 0.0f ? 0.0f : 1.0f; + quaternion_[2] = 0.0f; + } + return true; +} + +bool ProbeNativeMotion::integrate(const float gyro_dps[3], uint32_t elapsed_us) { + if (elapsed_us == 0) return true; + const float x = gyro_dps[0] - bias_[0]; + const float y = gyro_dps[1] - bias_[1]; + const float z = gyro_dps[2] - bias_[2]; + const float norm_squared = x * x + y * y + z * z; + if (!std::isfinite(norm_squared)) return false; + if (norm_squared == 0.0f) return true; + const float norm = std::sqrt(norm_squared); + const float half_angle = norm * (static_cast(elapsed_us) * (0.5e-6f * kRadiansPerDegree)); + const float sine_scale = std::sin(half_angle) / norm; + const float dw = std::cos(half_angle); + const float dx = x * sine_scale; + const float dy = y * sine_scale; + const float dz = z * sine_scale; + const float w = quaternion_[0]; + const float qx = quaternion_[1]; + const float qy = quaternion_[2]; + const float qz = quaternion_[3]; + // Body-local rates multiply on the right of the body-to-reference rotation. + quaternion_[0] = w * dw - qx * dx - qy * dy - qz * dz; + quaternion_[1] = w * dx + qx * dw + qy * dz - qz * dy; + quaternion_[2] = w * dy - qx * dz + qy * dw + qz * dx; + quaternion_[3] = w * dz + qx * dy - qy * dx + qz * dw; + return normalize_orientation(); +} + +bool ProbeNativeMotion::normalize_orientation() { + const float length_squared = quaternion_[0] * quaternion_[0] + quaternion_[1] * quaternion_[1] + + quaternion_[2] * quaternion_[2] + quaternion_[3] * quaternion_[3]; + if (!std::isfinite(length_squared) || length_squared <= 0.0f) return false; + const float reciprocal_length = 1.0f / std::sqrt(length_squared); + for (float& component : quaternion_) component *= reciprocal_length; + return true; +} + +bool ProbeNativeMotion::correct_gravity(uint32_t elapsed_us) { + if (elapsed_us == 0) return true; + const float norm_squared = squared_norm(acceleration_); + // Do not treat obvious dynamic acceleration as a gravity observation. + // The real acceleration remains unchanged in the outgoing report. + if (norm_squared < 0.9f * 0.9f || norm_squared > 1.1f * 1.1f) return true; + const float reciprocal_norm = 1.0f / std::sqrt(norm_squared); + const float ax = acceleration_[0] * reciprocal_norm; + const float ay = acceleration_[1] * reciprocal_norm; + const float az = acceleration_[2] * reciprocal_norm; + const float w = quaternion_[0], x = quaternion_[1], y = quaternion_[2], z = quaternion_[3]; + const float tx = 2.0f * (y * az - z * ay); + const float ty = 2.0f * (z * ax - x * az); + const float tz = 2.0f * (x * ay - y * ax); + const float gx = ax + w * tx + y * tz - z * ty; + const float gy = ay + w * ty + z * tx - x * tz; + const float gz = az + w * tz + x * ty - y * tx; + const float horizontal = std::sqrt(gx * gx + gy * gy); + if (horizontal == 0.0f && gz >= 0.0f) return true; + // Complementary tilt correction in reference space. Its rotation axis has + // no reference-Z component: do not invent a yaw observation from gravity. + // Sensor elapsed time, not Core 0 polling, controls the filter strength. + const float alpha = static_cast(elapsed_us) / + (kGravityTimeConstantUs + static_cast(elapsed_us)); + const float half_angle = 0.5f * alpha * std::atan2(horizontal, gz); + const float sine = std::sin(half_angle); + const float cw = std::cos(half_angle); + const float cx = horizontal > 0.0f ? (gy / horizontal) * sine : sine; + const float cy = horizontal > 0.0f ? (-gx / horizontal) * sine : 0.0f; + quaternion_[0] = cw * w - cx * x - cy * y; + quaternion_[1] = cw * x + cx * w + cy * z; + quaternion_[2] = cw * y - cx * z + cy * w; + quaternion_[3] = cw * z + cx * y - cy * x; + return normalize_orientation(); +} + +void ProbeNativeMotion::observe_optical_heading(uint32_t now_us, uint32_t reference_generation, + uint32_t sequence, uint32_t sample_us, + float yaw_radians, bool valid) { + if (!ready_) return; + if (!have_optical_generation_ || reference_generation != optical_generation_) { + have_optical_generation_ = true; + optical_generation_ = reference_generation; + seen_optical_sequence_ = false; + have_optical_reference_ = false; + have_optical_sample_ = false; + } + if (!valid || (have_optical_sample_ && now_us - optical_sample_us_ >= kFreshUs)) { + // Retain the relative anchor while hidden, but never accumulate filter + // weight for the interval without observations. + have_optical_sample_ = false; + } + const uint32_t sequence_delta = sequence - optical_sequence_; + if (seen_optical_sequence_ && (sequence_delta == 0 || sequence_delta >= 0x80000000u)) return; + seen_optical_sequence_ = true; + optical_sequence_ = sequence; + if (!valid || !std::isfinite(yaw_radians) || now_us - sample_us >= kFreshUs) { + have_optical_sample_ = false; + return; + } + // Reject backwards timestamps while both observations could still be + // fresh. Unsigned differences admit normal microsecond-clock rollover. + if (have_optical_reference_ && now_us - optical_sample_us_ < kFreshUs && + sample_us - optical_sample_us_ >= 0x80000000u) return; + const float w = quaternion_[0], x = quaternion_[1], y = quaternion_[2], z = quaternion_[3]; + // Native body Y is camera forward. Its world XY projection supplies heading; + // near vertical, yaw is ill-conditioned and must not become an observation. + const float forward_x = 2.0f * (x * y - w * z); + const float forward_y = 1.0f - 2.0f * (x * x + z * z); + if (forward_x * forward_x + forward_y * forward_y < kMinimumOpticalHorizontalSquared) { + have_optical_sample_ = false; + return; + } + const uint32_t elapsed_us = have_optical_sample_ ? sample_us - optical_sample_us_ : 0; + optical_sample_us_ = sample_us; + have_optical_sample_ = true; + const float heading = std::atan2(forward_y, forward_x); + const float bearing = std::remainder(yaw_radians, kTwoPi); + if (!have_optical_reference_) { + optical_reference_radians_ = std::remainder(heading + bearing, kTwoPi); + have_optical_reference_ = true; + return; + } + if (elapsed_us == 0 || elapsed_us >= kFreshUs) return; + // Optical direction complements gyro heading; concept reference: + // https://github.com/dolphin-emu/dolphin/blob/master/Source/Core/InputCommon/ControllerInterface/Wiimote/WiimoteController.cpp + // Independently use a relative yaw anchor and elapsed-time gain, not its + // per-frame full-vector correction. Translation also changes bar bearing; + // bar placement/pitch can bias it, so this is not absolute world heading. + // Positive optical aim-right is a negative world-Z heading change. + const float error = std::remainder(optical_reference_radians_ - bearing - heading, kTwoPi); + const float alpha = static_cast(elapsed_us) / + (kOpticalTimeConstantUs + static_cast(elapsed_us)); + const float half_angle = 0.5f * alpha * error; + const float cw = std::cos(half_angle), cz = std::sin(half_angle); + // Left multiplication about reference-world Z preserves gravity-aligned + // tilt, and neither the measured acceleration nor learned gyro bias changes. + quaternion_[0] = cw * w - cz * z; + quaternion_[1] = cw * x - cz * y; + quaternion_[2] = cw * y + cz * x; + quaternion_[3] = cw * z + cz * w; + if (!normalize_orientation()) invalidate(); +} + +void ProbeNativeMotion::update(uint32_t now_us, uint32_t connection_generation, + const ProbeNativeMotionSample& sample) { + if (!have_generation_ || connection_generation != connection_generation_) { + reset(); + have_generation_ = true; + connection_generation_ = connection_generation; + } + const uint32_t elapsed_us = have_update_ ? now_us - update_us_ : 0; + update_us_ = now_us; + have_update_ = true; + if (elapsed_us > kMaximumUpdateGapUs) invalidate(); + if (!sample.accel_valid || !sample.gyro_valid || + !finite_vector(sample.accel_g, 3) || !finite_vector(sample.gyro_dps, 3)) { + invalidate(); + return; + } + + const bool new_accel = !seen_accel_sequence_ || sample.accel_sequence != accel_sequence_; + const bool new_gyro = !seen_gyro_sequence_ || sample.gyro_sequence != gyro_sequence_; + // A fresh replacement cannot conceal a stale interval between observations. + // Unsigned differences also reject timestamps that move backwards. + if ((have_accel_ && new_accel && sample.accel_us - accel_us_ > kFreshUs) || + (have_gyro_ && new_gyro && sample.gyro_us - gyro_us_ > kFreshUs)) { + invalidate(); + } + const bool was_ready = ready_; + const uint32_t accel_elapsed_us = was_ready && new_accel ? sample.accel_us - accel_us_ : 0; + float previous_gyro[3]; + if (was_ready && new_gyro) { + for (unsigned i = 0; i < 3; ++i) previous_gyro[i] = gyro_dps_[i]; + } + if (new_accel) { + seen_accel_sequence_ = true; + accel_sequence_ = sample.accel_sequence; + accel_us_ = sample.accel_us; + have_accel_ = true; + for (unsigned i = 0; i < 3; ++i) acceleration_[i] = sample.accel_g[i]; + } + if (new_gyro) { + seen_gyro_sequence_ = true; + gyro_sequence_ = sample.gyro_sequence; + gyro_us_ = sample.gyro_us; + have_gyro_ = true; + for (unsigned i = 0; i < 3; ++i) gyro_dps_[i] = sample.gyro_dps[i]; + } + if ((have_accel_ && now_us - accel_us_ >= kFreshUs) || (have_gyro_ && now_us - gyro_us_ >= kFreshUs)) { + invalidate(); + return; + } + // Wii acceleration and gyro arrive on independent packets. Keep a fresh + // first half while waiting for the other sensor after invalidation. + if (!have_accel_ || !have_gyro_) return; + if (was_ready) { + // Zero-order hold uses actual receipt times, independent of update/USB + // cadence. Split only when a new rate arrived inside this update span. + const uint32_t rate_age_us = now_us - gyro_us_; + if (new_gyro && rate_age_us < elapsed_us) { + if (!integrate(previous_gyro, elapsed_us - rate_age_us) || !integrate(gyro_dps_, rate_age_us)) { + invalidate(); + } + } else if (!integrate(gyro_dps_, elapsed_us)) { + invalidate(); + } + if (ready_ && new_accel && !correct_gravity(accel_elapsed_us)) invalidate(); + return; + } + + const float acceleration_norm_squared = squared_norm(acceleration_); + if (acceleration_norm_squared < 0.85f * 0.85f || + acceleration_norm_squared > 1.15f * 1.15f) { + clear_candidate(); + return; + } + if (!candidate_) { + if (!new_gyro) return; + candidate_ = true; + candidate_us_ = gyro_us_; + gyro_count_ = 0; + accel_count_ = 0; + } + if (new_accel || accel_count_ == 0) { + if (!accumulate_stationary(acceleration_, ++accel_count_, mean_accel_, + accel_variation_, kAccelRmsG)) { + clear_candidate(); + return; + } + if (accel_count_ == kVariationSamples) { + for (unsigned i = 0; i < 3; ++i) gravity_reference_[i] = mean_accel_[i]; + } else if (accel_count_ > kVariationSamples) { + // Anchor the averaged direction rather than the previous packet: + // slow tilt must not be accepted as a series of small noisy steps. + float dot = 0.0f; + for (unsigned i = 0; i < 3; ++i) dot += gravity_reference_[i] * mean_accel_[i]; + if (dot <= 0.0f || dot * dot < squared_norm(gravity_reference_) * + squared_norm(mean_accel_) * kGravityDirectionCosSquared) { + clear_candidate(); + return; + } + } + } + if (!new_gyro) return; + // An absolute angular-rate limit cannot distinguish motion from the bias + // being estimated. Changing rates, acceleration and gravity direction can; + // perfectly steady rotation about gravity still requires the user to rest. + if (!accumulate_stationary(gyro_dps_, ++gyro_count_, mean_gyro_, + gyro_variation_, kGyroRmsDps)) { + clear_candidate(); + return; + } + if (gyro_count_ >= kCalibrationSamples && accel_count_ >= kVariationSamples && + gyro_us_ - candidate_us_ >= kCalibrationUs) { + if (!initialize_orientation()) { + clear_candidate(); + return; + } + for (unsigned i = 0; i < 3; ++i) bias_[i] = mean_gyro_[i]; + ready_ = true; + clear_candidate(); + } +} diff --git a/tools/switch2_usb_probe/native_imu.h b/tools/switch2_usb_probe/native_imu.h new file mode 100644 index 0000000..46ee596 --- /dev/null +++ b/tools/switch2_usb_probe/native_imu.h @@ -0,0 +1,99 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Encode one native mode-0 IMU block. Inputs use the native-right body frame; +// quaternion wxyz rotates body vectors into the reference frame. Quaternion +// scale/sign do not matter. Finite acceleration saturates at signed Q28 limits. +// Invalid inputs leave output untouched; counter and elapsed must fit 12 bits. +bool probe_native_imu_pack(const float quaternion_wxyz[4], const float accel_g[3], + uint16_t counter_ticks, uint16_t elapsed_ticks, + int16_t temperature_raw, uint8_t output[30]); + +#ifdef __cplusplus +} + +struct ProbeNativeMotionSample { + bool accel_valid = false; + bool gyro_valid = false; + uint32_t accel_sequence = 0; + uint32_t gyro_sequence = 0; + uint32_t accel_us = 0; + uint32_t gyro_us = 0; + float accel_g[3]{}; + float gyro_dps[3]{}; +}; + +// Core 0 only. Call update even when sensors are unavailable, and consult ready +// before using the orientation. Sequence identities, not polling, admit samples; +// repeated sequences cannot refresh timestamps or contribute to calibration. +// Startup requires the user to rest the controller: constant rotation about +// gravity is indistinguishable from an unknown gyro bias without another sensor. +// Fresh near-1g acceleration corrects tilt drift after startup. Heading remains +// gyro-derived unless a reliable optical heading observation is supplied. +class ProbeNativeMotion { +public: + void reset(); + void update(uint32_t now_us, uint32_t connection_generation, + const ProbeNativeMotionSample& sample); + // Call after update, using a full observed sensor-bar pair (never inferred). + // Positive optical yaw means aim-right, the negative reference-world turn. + // The first sample in each optical generation anchors the current heading; + // it supplies neither absolute world yaw nor an absolute console cursor. + void observe_optical_heading(uint32_t now_us, uint32_t reference_generation, + uint32_t sequence, uint32_t sample_us, + float yaw_radians, bool valid); + bool ready() const { return ready_; } + const float* quaternion() const { return quaternion_; } + const float* acceleration() const { return acceleration_; } + const float* bias() const { return bias_; } + +private: + void invalidate(); + void clear_candidate(); + bool initialize_orientation(); + bool integrate(const float gyro_dps[3], uint32_t elapsed_us); + bool correct_gravity(uint32_t elapsed_us); + bool normalize_orientation(); + + bool have_generation_ = false; + bool have_update_ = false; + bool seen_accel_sequence_ = false; + bool seen_gyro_sequence_ = false; + bool have_accel_ = false; + bool have_gyro_ = false; + bool candidate_ = false; + bool ready_ = false; + bool have_optical_generation_ = false; + bool seen_optical_sequence_ = false; + bool have_optical_reference_ = false; + bool have_optical_sample_ = false; + uint32_t connection_generation_ = 0; + uint32_t update_us_ = 0; + uint32_t accel_sequence_ = 0; + uint32_t gyro_sequence_ = 0; + uint32_t accel_us_ = 0; + uint32_t gyro_us_ = 0; + uint32_t candidate_us_ = 0; + uint32_t gyro_count_ = 0; + uint32_t accel_count_ = 0; + uint32_t optical_generation_ = 0; + uint32_t optical_sequence_ = 0; + uint32_t optical_sample_us_ = 0; + float optical_reference_radians_ = 0.0f; + float gyro_variation_ = 0.0f; + float accel_variation_ = 0.0f; + float quaternion_[4]{1.0f, 0.0f, 0.0f, 0.0f}; + float acceleration_[3]{}; + float gyro_dps_[3]{}; + float bias_[3]{}; + float mean_gyro_[3]{}; + float mean_accel_[3]{}; + float gravity_reference_[3]{}; +}; +#endif diff --git a/tools/switch2_usb_probe/probe_build.cmake b/tools/switch2_usb_probe/probe_build.cmake index 47b7358..66bae3d 100644 --- a/tools/switch2_usb_probe/probe_build.cmake +++ b/tools/switch2_usb_probe/probe_build.cmake @@ -18,6 +18,68 @@ function(switch2_usb_probe_configure target) ${PICO_SDK_PATH}/lib/btstack/platform/embedded) target_compile_definitions(${target} PRIVATE CFG_TUSB_CONFIG_FILE="${SWITCH2_USB_PROBE_DIR}/tusb_config.h") + option(SWITCH2_PROBE_TRACE_NATIVE_INPUT + "Trace one completed native USB input report per second without changing its contents" OFF) + if(SWITCH2_PROBE_TRACE_NATIVE_INPUT) + if(NOT SWITCH_PICO_SWITCH2_USB_BRIDGE) + message(FATAL_ERROR "Native input tracing requires the Bluetooth USB bridge") + endif() + target_compile_definitions(${target} PRIVATE SWITCH2_PROBE_TRACE_NATIVE_INPUT=1) + endif() + if(SWITCH2_BRIDGE_WII_INPUT) + set(SWITCH2_WII_IR_SENSITIVITY 3 CACHE STRING "Standard Wii camera sensitivity preset: 2 or 3") + set_property(CACHE SWITCH2_WII_IR_SENSITIVITY PROPERTY STRINGS 2 3) + if(NOT "${SWITCH2_WII_IR_SENSITIVITY}" MATCHES "^[23]$") + message(FATAL_ERROR "SWITCH2_WII_IR_SENSITIVITY must be standard preset 2 or 3") + endif() + target_compile_definitions(bluepad32 PRIVATE + SWITCH_PICO_WII_IR_SENSITIVITY_LEVEL=${SWITCH2_WII_IR_SENSITIVITY}) + set(SWITCH2_WII_IR_VIEW_WIDTH 660 CACHE STRING "Native Wii IR viewport width in camera pixels") + set(SWITCH2_WII_IR_VIEW_HEIGHT 370 CACHE STRING "Native Wii IR viewport height in camera pixels") + set(SWITCH2_WII_IR_OFFSET_X 0 CACHE STRING "Native Wii IR viewport horizontal camera offset") + set(SWITCH2_WII_IR_OFFSET_Y -115 CACHE STRING "Native Wii IR viewport vertical offset: -115 below, +115 above") + set(SWITCH2_WII_IR_SPAN_X 1920 CACHE STRING "Native mouse counts across the IR viewport width") + set(SWITCH2_WII_IR_SPAN_Y 1080 CACHE STRING "Native mouse counts across the IR viewport height") + foreach(field VIEW_WIDTH VIEW_HEIGHT OFFSET_X OFFSET_Y SPAN_X SPAN_Y) + if(NOT "${SWITCH2_WII_IR_${field}}" MATCHES "^-?[0-9]+$") + message(FATAL_ERROR "SWITCH2_WII_IR_${field} must be an integer") + endif() + endforeach() + math(EXPR offset_x_twice "2 * ${SWITCH2_WII_IR_OFFSET_X}") + math(EXPR offset_y_twice "2 * ${SWITCH2_WII_IR_OFFSET_Y}") + math(EXPR room_x "1024 - ${SWITCH2_WII_IR_VIEW_WIDTH}") + math(EXPR room_y "768 - ${SWITCH2_WII_IR_VIEW_HEIGHT}") + if(SWITCH2_WII_IR_VIEW_WIDTH LESS 1 OR SWITCH2_WII_IR_VIEW_WIDTH GREATER 1024 OR + SWITCH2_WII_IR_VIEW_HEIGHT LESS 1 OR SWITCH2_WII_IR_VIEW_HEIGHT GREATER 768 OR + offset_x_twice LESS -${room_x} OR offset_x_twice GREATER ${room_x} OR + offset_y_twice LESS -${room_y} OR offset_y_twice GREATER ${room_y} OR + SWITCH2_WII_IR_SPAN_X LESS 1 OR SWITCH2_WII_IR_SPAN_X GREATER 32767 OR + SWITCH2_WII_IR_SPAN_Y LESS 1 OR SWITCH2_WII_IR_SPAN_Y GREATER 32767) + message(FATAL_ERROR "Native IR viewport must lie inside the camera; mouse spans must be 1..32767") + endif() + target_compile_definitions(${target} PRIVATE + SWITCH2_WII_IR_SCREEN_CONFIG=${SWITCH2_WII_IR_VIEW_WIDTH},${SWITCH2_WII_IR_VIEW_HEIGHT},${SWITCH2_WII_IR_OFFSET_X},${SWITCH2_WII_IR_OFFSET_Y},${SWITCH2_WII_IR_SPAN_X},${SWITCH2_WII_IR_SPAN_Y}) + endif() + option(SWITCH2_PROBE_OMIT_NATIVE_IMU + "Activation experiment: omit only native IMU bytes while retaining advertised features" OFF) + option(SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD + "Activation experiment: zero native IMU payload while preserving its length" OFF) + if(SWITCH2_PROBE_OMIT_NATIVE_IMU AND SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD) + message(FATAL_ERROR "Select only one IMU activation experiment") + endif() + if(SWITCH2_PROBE_OMIT_NATIVE_IMU OR SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD) + if(NOT SWITCH_PICO_SWITCH2_USB_BRIDGE) + message(FATAL_ERROR "Native IMU activation experiments require the Bluetooth USB bridge") + endif() + if(SWITCH2_BRIDGE_WII_INPUT) + message(FATAL_ERROR "Disable IMU ablation experiments for the Wii source bridge") + endif() + endif() + if(SWITCH2_PROBE_OMIT_NATIVE_IMU) + target_compile_definitions(${target} PRIVATE SWITCH2_PROBE_OMIT_NATIVE_IMU=1) + elseif(SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD) + target_compile_definitions(${target} PRIVATE SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD=1) + endif() set(SWITCH2_PROBE_IDENTITY_FILE "" CACHE FILEPATH "64-byte Joy-Con 2 (R) factory-format identity block") if(SWITCH2_PROBE_IDENTITY_FILE) @@ -130,10 +192,30 @@ function(switch2_usb_probe_configure target) hardware_flash pico_flash pico_mbedtls_crypto pico_mbedtls_headers tinyusb_device) pico_enable_stdio_usb(${target} 0) pico_enable_stdio_uart(${target} 1) - if(SWITCH_PICO_SWITCH2_USB_BRIDGE) + if(SWITCH2_BRIDGE_WII_INPUT) + pico_set_program_name(${target} "Switch 2 Wii IR and native motion bridge") + elseif(SWITCH_PICO_SWITCH2_USB_BRIDGE) pico_set_program_name(${target} "Switch 2 right Joy-Con Bluetooth bridge") else() pico_set_program_name(${target} "Switch 2 USB initialization capture") endif() - pico_set_program_version(${target} "0.24") + if(SWITCH2_PROBE_OMIT_NATIVE_IMU) + pico_set_program_version(${target} "0.24-no-imu") + elseif(SWITCH2_PROBE_ZERO_NATIVE_IMU_PAYLOAD) + pico_set_program_version(${target} "0.24-zero-imu-payload") + elseif(SWITCH2_BRIDGE_WII_INPUT) + if(SWITCH2_PROBE_TRACE_NATIVE_INPUT) + pico_set_program_version(${target} "0.33-wii-trace") + else() + pico_set_program_version(${target} "0.33-wii") + endif() + elseif(SWITCH_PICO_SWITCH2_USB_BRIDGE) + if(SWITCH2_PROBE_TRACE_NATIVE_INPUT) + pico_set_program_version(${target} "0.25-trace") + else() + pico_set_program_version(${target} "0.25") + endif() + else() + pico_set_program_version(${target} "0.24") + endif() endfunction()