diff --git a/client/core/src/armor.rs b/client/core/src/armor.rs index 71af317..ee09266 100644 --- a/client/core/src/armor.rs +++ b/client/core/src/armor.rs @@ -200,6 +200,7 @@ pub struct ArmorHealthStore { sink: Mutex>, assignments: Mutex>, match_sink: Mutex>, + mirror_sink: Mutex>>, match_result_sink: Mutex>, damage_participants: Mutex>, reset: Mutex>, @@ -219,6 +220,7 @@ impl ArmorHealthStore { sink: Mutex::new(None), assignments: Mutex::new(Vec::new()), match_sink: Mutex::new(None), + mirror_sink: Mutex::new(None), match_result_sink: Mutex::new(None), damage_participants: Mutex::new(HashSet::new()), reset: Mutex::new(None), @@ -278,6 +280,17 @@ impl ArmorHealthStore { /// 处理一条上报。测试从这里喂字节。 pub fn datagram(&self, bytes: &[u8], from: SocketAddr) { + if let Some(packet) = protocol::CameraMirror::decode(bytes) { + if let Some(sink) = self + .mirror_sink + .lock() + .expect("mirror sink poisoned") + .clone() + { + sink(packet); + } + return; + } let SocketAddr::V4(addr) = from else { return; }; @@ -418,6 +431,9 @@ impl ArmorHealthStore { pub fn set_match_sink(&self, sink: MatchSink) { *self.match_sink.lock().expect("match sink poisoned") = Some(sink); } + pub fn set_mirror_sink(&self, sink: Arc) { + *self.mirror_sink.lock().expect("mirror sink poisoned") = Some(sink); + } pub fn set_match_result_sink(&self, sink: MatchResultSink) { *self .match_result_sink diff --git a/client/core/src/camera_mirror.rs b/client/core/src/camera_mirror.rs new file mode 100644 index 0000000..4ca4e0a --- /dev/null +++ b/client/core/src/camera_mirror.rs @@ -0,0 +1,80 @@ +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CameraOrientation { + pub revision: u64, + pub origin: u64, + pub mirror: bool, + pub mirror_vertical: bool, +} +pub type CameraMirrors = BTreeMap; +impl CameraOrientation { + pub fn packet(&self, camera_id: u32) -> protocol::CameraMirror { + protocol::CameraMirror { + camera_id, + revision: self.revision, + origin: self.origin, + mirror: self.mirror, + mirror_vertical: self.mirror_vertical, + } + } +} +pub fn merge(entries: &mut CameraMirrors, packet: protocol::CameraMirror) -> bool { + if packet.encode().is_none() + || entries + .get(&packet.camera_id.to_string()) + .is_some_and(|old| (old.revision, old.origin) >= (packet.revision, packet.origin)) + { + return false; + } + entries.insert( + packet.camera_id.to_string(), + CameraOrientation { + revision: packet.revision, + origin: packet.origin, + mirror: packet.mirror, + mirror_vertical: packet.mirror_vertical, + }, + ); + true +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn concurrent_writes_converge_without_echo_or_cross_camera_changes() { + let a = protocol::CameraMirror { + camera_id: 7, + revision: 2, + origin: 8, + mirror: true, + mirror_vertical: false, + }; + let b = protocol::CameraMirror { + origin: 9, + mirror: false, + mirror_vertical: true, + ..a + }; + let mut left = CameraMirrors::new(); + let mut right = CameraMirrors::new(); + merge(&mut left, a); + merge(&mut left, b); + merge(&mut right, b); + assert!(!merge(&mut right, a)); + assert_eq!(left, right); + assert!(!merge(&mut left, b)); + merge(&mut left, protocol::CameraMirror { camera_id: 9, ..a }); + assert_eq!(left.len(), 2); + let mut config = crate::Config::default(); + config.camera_mirrors = left; + assert_eq!( + crate::Config::parse(&toml::to_string(&config).unwrap()) + .unwrap() + .camera_mirrors, + config.camera_mirrors + ); + } +} diff --git a/client/core/src/config.rs b/client/core/src/config.rs index e5f51fe..a77fce0 100644 --- a/client/core/src/config.rs +++ b/client/core/src/config.rs @@ -440,6 +440,7 @@ pub struct Config { pub mirror: bool, /// 上下镜像,与左右镜像独立;旧配置默认关闭。 pub mirror_vertical: bool, + pub camera_mirrors: crate::camera_mirror::CameraMirrors, /// 密码的 Argon2id PHC 字符串。`None` = 还没设过。 /// /// 只对用户端有意义([`Role::needs_password`])。 @@ -466,6 +467,7 @@ impl Default for Config { armor_id: None, mirror: true, mirror_vertical: false, + camera_mirrors: Default::default(), password: None, hud: HudConfig::default(), referee: RefereeConfig::default(), diff --git a/client/core/src/lib.rs b/client/core/src/lib.rs index 9eafd81..f514e90 100644 --- a/client/core/src/lib.rs +++ b/client/core/src/lib.rs @@ -29,6 +29,7 @@ pub mod armor; pub mod armor_reset; pub mod config; +pub mod camera_mirror; pub mod match_clock; pub mod operator; pub mod password; diff --git a/client/core/src/snapshot.rs b/client/core/src/snapshot.rs index b989f04..7ca0c20 100644 --- a/client/core/src/snapshot.rs +++ b/client/core/src/snapshot.rs @@ -385,6 +385,7 @@ pub struct SlotsDto { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Snapshot { + pub camera_mirrors: crate::camera_mirror::CameraMirrors, pub operator_control: crate::operator::OperatorView, pub match_clock: crate::match_clock::MatchView, pub role: Role, diff --git a/client/core/tests/mirror_sync.rs b/client/core/tests/mirror_sync.rs new file mode 100644 index 0000000..19bb79f --- /dev/null +++ b/client/core/tests/mirror_sync.rs @@ -0,0 +1,22 @@ +use cam_core::{armor::ArmorHealthStore, camera_mirror::{merge, CameraMirrors}}; +use std::{net::UdpSocket, sync::{Arc,Mutex}, time::Duration}; +#[test] +fn bidirectional_udp_mirrors_remain_camera_scoped_and_ignore_stale_echoes() { + let left=ArmorHealthStore::new();let right=ArmorHealthStore::new(); + let a=Arc::new(Mutex::new(CameraMirrors::new()));let b=Arc::new(Mutex::new(CameraMirrors::new())); + let copy=a.clone();left.set_mirror_sink(Arc::new(move|p|{merge(&mut copy.lock().unwrap(),p);})); + let copy=b.clone();right.set_mirror_sink(Arc::new(move|p|{merge(&mut copy.lock().unwrap(),p);})); + let tx=UdpSocket::bind("127.0.0.1:0").unwrap();let rx=UdpSocket::bind("127.0.0.1:0").unwrap(); + rx.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); + let transfer=|packet:protocol::CameraMirror,store:&ArmorHealthStore|{ + tx.send_to(&packet.encode().unwrap(),rx.local_addr().unwrap()).unwrap();let mut buf=[0;128];let(n,from)=rx.recv_from(&mut buf).unwrap();store.datagram(&buf[..n],from); + }; + let first=protocol::CameraMirror{camera_id:17,revision:1,origin:3,mirror:true,mirror_vertical:true}; + transfer(first,&right); + let second=protocol::CameraMirror{revision:2,origin:4,mirror:false,..first}; + transfer(second,&left);transfer(second,&right);transfer(first,&left); + assert_eq!(*a.lock().unwrap(),*b.lock().unwrap());assert!(!a.lock().unwrap()["17"].mirror); + transfer(protocol::CameraMirror{camera_id:18,..first},&right); + assert_eq!(a.lock().unwrap().len(),1);assert_eq!(b.lock().unwrap().len(),2); + assert!(left.boards().is_empty());assert!(right.boards().is_empty()); +} diff --git a/client/package.json b/client/package.json index 9858a6d..4e963da 100644 --- a/client/package.json +++ b/client/package.json @@ -1,7 +1,7 @@ { "name": "rmic-2026", "private": true, - "version": "0.5.0", + "version": "0.6.0", "type": "module", "description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)", "scripts": { diff --git a/client/src-tauri/src/commands.rs b/client/src-tauri/src/commands.rs index 9413adc..f5fcdff 100644 --- a/client/src-tauri/src/commands.rs +++ b/client/src-tauri/src/commands.rs @@ -234,9 +234,7 @@ pub fn set_role( /// 左右镜像。摄像头装反了才需要,不是判罚相关的东西,所以不设密码。 #[tauri::command] pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result { - state - .update_config(move |config| config.mirror = mirror) - .map_err(|err| format!("{err}"))?; + state.set_camera_mirror(None, Some(mirror), None)?; Ok(ConfigView::from(&state.config())) } @@ -244,13 +242,21 @@ pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result /// 上下镜像,独立保存,不改动左右镜像。 #[tauri::command] pub fn set_mirror_vertical(mirror_vertical: bool, state: Shared<'_>) -> Result { - state - .update_config(move |config| config.mirror_vertical = mirror_vertical) - .map_err(|err| format!("{err}"))?; + state.set_camera_mirror(None, None, Some(mirror_vertical))?; Ok(ConfigView::from(&state.config())) } +#[tauri::command] +pub fn set_camera_mirror( + camera: u32, + mirror: bool, + mirror_vertical: bool, + state: Shared<'_>, +) -> Result<(), String> { + state.set_camera_mirror(Some(camera), Some(mirror), Some(mirror_vertical)) +} + /// 保存 HUD 设置(血条、瞄准器、网格、命中反馈)。 #[tauri::command] pub fn save_hud(hud: HudConfig, state: Shared<'_>) -> Result { diff --git a/client/src-tauri/src/main.rs b/client/src-tauri/src/main.rs index c8e8b62..2477c01 100644 --- a/client/src-tauri/src/main.rs +++ b/client/src-tauri/src/main.rs @@ -344,6 +344,7 @@ fn run() -> Result<(), Box> { commands::set_team, commands::set_role, commands::set_mirror, + commands::set_camera_mirror, commands::set_mirror_vertical, commands::save_hud, commands::set_team_name, diff --git a/client/src-tauri/src/state.rs b/client/src-tauri/src/state.rs index aba9b57..07cb4c7 100644 --- a/client/src-tauri/src/state.rs +++ b/client/src-tauri/src/state.rs @@ -60,6 +60,8 @@ pub struct AppState { match_socket: Option, match_error: Mutex>, match_changed: tokio::sync::Notify, + mirror_inbox: Mutex, + mirror_origin: u64, operator: Mutex, operator_socket: Option, operator_focused: AtomicBool, @@ -90,6 +92,125 @@ pub struct AppState { } impl AppState { + fn mirror_targets(&self) -> Vec { + let config = self.config(); + if config.role == Role::Team { + config.camera_id.into_iter().collect() + } else { + self.slots + .lock() + .expect("slots poisoned") + .slots() + .into_iter() + .flatten() + .collect() + } + } + + pub fn set_camera_mirror( + &self, + camera: Option, + horizontal: Option, + vertical: Option, + ) -> Result<(), String> { + let targets = self.mirror_targets(); + let ids = match camera { + Some(id) if targets.contains(&id) => vec![id], + Some(_) => return Err("只能修改已绑定或当前槽位的图传板".into()), + None => targets, + }; + let mut config = self.config.lock().expect("config poisoned"); + let revision = config + .camera_mirrors + .values() + .map(|v| v.revision) + .max() + .unwrap_or(0) + .checked_add(1) + .ok_or("镜像修订号已用尽")?; + for id in ids { + let old = config.camera_mirrors.get(&id.to_string()); + let packet = protocol::CameraMirror { + camera_id: id, + revision, + origin: self.mirror_origin, + mirror: horizontal.unwrap_or(old.map_or(config.mirror, |v| v.mirror)), + mirror_vertical: vertical + .unwrap_or(old.map_or(config.mirror_vertical, |v| v.mirror_vertical)), + }; + cam_core::camera_mirror::merge(&mut config.camera_mirrors, packet); + } + if camera.is_none() || config.role == Role::Team { + if let Some(v) = horizontal { + config.mirror = v; + } + if let Some(v) = vertical { + config.mirror_vertical = v; + } + } + config + .save(&self.config_path) + .map_err(|e| format!("镜像已在本次运行生效,但保存失败:{e}"))?; + drop(config); + self.tick_mirrors(); + self.push_snapshot(); + Ok(()) + } + + fn tick_mirrors(&self) { + let targets = self.mirror_targets(); + let inbox = std::mem::take(&mut *self.mirror_inbox.lock().expect("mirror inbox poisoned")); + let mut config = self.config.lock().expect("config poisoned"); + let mut changed = false; + for (id, value) in inbox { + if let Ok(id) = id.parse::() { + if targets.contains(&id) { + changed |= cam_core::camera_mirror::merge( + &mut config.camera_mirrors, + value.packet(id), + ); + } + } + } + if config.role == Role::Team { + if let Some(value) = config + .camera_id + .and_then(|id| config.camera_mirrors.get(&id.to_string())) + .cloned() + { + config.mirror = value.mirror; + config.mirror_vertical = value.mirror_vertical; + } + } + if changed { + if let Err(error) = config.save(&self.config_path) { + log::warn!("镜像同步保存失败:{error}"); + } + } + let packets: Vec<_> = targets + .into_iter() + .filter_map(|id| { + config + .camera_mirrors + .get(&id.to_string()) + .map(|v| v.packet(id)) + }) + .collect(); + drop(config); + if !self.demo { + if let Some(socket) = &self.match_socket { + for packet in packets { + if let Some(bytes) = packet.encode() { + let _ = socket.send_to( + &bytes, + (std::net::Ipv4Addr::BROADCAST, protocol::ARMOR_PORT), + ); + } + } + } + } + } + fn operator_context(&self) -> OperatorContext { let config = self.config(); let clock = self.match_view(); @@ -432,6 +553,8 @@ impl AppState { match_socket, match_error: Mutex::new(match_error), match_changed: tokio::sync::Notify::new(), + mirror_inbox: Mutex::new(Default::default()), + mirror_origin: session.max(1), operator: Mutex::new(OperatorState::new(session)), operator_socket, operator_focused: AtomicBool::new(true), @@ -462,6 +585,17 @@ impl AppState { /// /// 必须在 `Arc` 建好之后调用(sink 里要持有 state 的通道)。 pub fn install_sinks(self: &Arc) { + let weak = Arc::downgrade(self); + self.armor.set_mirror_sink(Arc::new(move |packet| { + if let Some(state) = weak.upgrade() { + if !state.demo && state.mirror_targets().contains(&packet.camera_id) { + cam_core::camera_mirror::merge( + &mut state.mirror_inbox.lock().expect("mirror inbox poisoned"), + packet, + ); + } + } + })); let weak = Arc::downgrade(self); self.armor.set_match_sink(Arc::new(move |packet, ip| { if let Some(state) = weak.upgrade() { @@ -848,6 +982,7 @@ impl AppState { } pub fn tick(&self) { + self.tick_mirrors(); self.tick_match(); let online: Vec = self .discovery @@ -958,12 +1093,19 @@ impl AppState { .apply_outcomes(&mut health); Snapshot { + camera_mirrors: config.camera_mirrors.clone(), operator_control: self.operator.lock().expect("operator poisoned").view(), match_clock: self.match_view(), role: config.role, team: config.team, - mirrored: config.mirror, - mirrored_vertical: config.mirror_vertical, + mirrored: config + .camera_id + .and_then(|id| config.camera_mirrors.get(&id.to_string())) + .map_or(config.mirror, |v| v.mirror), + mirrored_vertical: config + .camera_id + .and_then(|id| config.camera_mirrors.get(&id.to_string())) + .map_or(config.mirror_vertical, |v| v.mirror_vertical), demo: self.demo, diagnostics, unlocked: self.is_unlocked(), diff --git a/client/src-tauri/tauri.conf.json b/client/src-tauri/tauri.conf.json index ebd22ce..061d41d 100644 --- a/client/src-tauri/tauri.conf.json +++ b/client/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "RMIC-2026", - "version": "0.5.0", + "version": "0.6.0", "identifier": "com.simbarobotics.rmic2026", "build": { "beforeDevCommand": "pnpm dev", diff --git a/client/src/components/OperatorControls.tsx b/client/src/components/OperatorControls.tsx index eba3649..8cc4fe6 100644 --- a/client/src/components/OperatorControls.tsx +++ b/client/src/components/OperatorControls.tsx @@ -1,29 +1,39 @@ +import { useEffect, useRef, useState } from "react"; import type { Snapshot } from "../lib/types"; import { operatorGate, type useOperatorControl } from "../lib/use-operator-control"; +import { Slider } from "./controls"; +import { OperatorMapping } from "./OperatorMapping"; export function OperatorControls({ control, snapshot, connected, blocked }: { - control: ReturnType; - snapshot: Snapshot; - connected: boolean; - blocked: boolean; + control: ReturnType; snapshot: Snapshot; connected: boolean; blocked: boolean; }) { + const [open, setOpen] = useState(false); + const root = useRef(null); const matchReason = operatorGate(snapshot, connected, "match"); const debugReason = operatorGate(snapshot, connected, "debug"); - return
event.stopPropagation()} onWheel={event => event.stopPropagation()} onDoubleClick={event => event.stopPropagation()}> - {control.activeMode ? <> - {control.activeMode === "debug" ? "赛前调试发送中" : "操作输入发送中"}{snapshot.demo ? " · 合成输入" : ""} - WASD 移动 · 鼠标控制云台 · 左键发射 · ESC 退出 - {snapshot.demo ? "仅合成预览,无真实发送" : "仅表示客户端发送状态;装甲板及下位机无应答"} - : <> -
- - -
- -

{snapshot.demo ? "预览使用合成数据,不向装甲板发送真实操作。" : "WASD 移动 · 鼠标控制云台速度 · 左键发射;ESC 或失焦立即停止。"}

- {!snapshot.demo &&

仅确认客户端发送,装甲板及下位机未提供应答。装甲板重启或连接超时后,请退出再开启。

} - {matchReason && debugReason &&

{matchReason};{debugReason}

} - {control.error &&

{control.error}

} - } -
; + useEffect(() => { if (blocked || control.activeMode) setOpen(false); }, [blocked, control.activeMode]); + useEffect(() => { + const dismiss = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) setOpen(false); }; + document.addEventListener("pointerdown", dismiss); + return () => document.removeEventListener("pointerdown", dismiss); + }, []); + return <> +
event.stopPropagation()} onWheel={event => event.stopPropagation()} onDoubleClick={event => event.stopPropagation()} onKeyDown={event => { if (open && event.key === "Escape") {event.stopPropagation();setOpen(false);} }}> + + {open &&
+
+ + +
+ + {matchReason && debugReason && {debugReason}} + {snapshot.demo && 合成预览} + {control.error && {control.error}} +
} + {!open && control.error && 操作已停止} +
+ {control.activeMode === "debug" && } + ; } diff --git a/client/src/components/OperatorMapping.tsx b/client/src/components/OperatorMapping.tsx new file mode 100644 index 0000000..849d4ce --- /dev/null +++ b/client/src/components/OperatorMapping.tsx @@ -0,0 +1,21 @@ +import { useEffect, useState, type RefObject, type CSSProperties } from "react"; +import { neutralAxes, type OperatorAxes } from "../lib/operator-input"; + +/** 显示已提交的客户端通道值;不把它描述为串口回执或真实机构速度。 */ +export function OperatorMapping({ source, synthetic }: { source: RefObject; synthetic: boolean }) { + const [axes, setAxes] = useState(neutralAxes); + useEffect(() => { + const timer = window.setInterval(() => setAxes({ ...source.current }), 40); + return () => window.clearInterval(timer); + }, [source]); + const channels = [["CH0", "W / S", "前后", axes.forward], ["CH1", "A / D", "左右", axes.strafe], ["CH2", "MOUSE X", "水平", axes.yaw], ["CH3", "MOUSE Y", "俯仰", axes.pitch]] as const; + return
+
CONTROL / MAPPING{synthetic ? "合成输入" : "客户端输入"}
+
键鼠→UDP→C3 / UART
+
{channels.map(([id, input, label, value]) =>
+ {input}{id} / {label}{value > 0 ? "+" : ""}{value} +
+
)}
+
LMB → FIRE {Number(axes.fire)}±1000 · 速度比例ESC 退出
+
; +} diff --git a/client/src/lib/dev-preview.ts b/client/src/lib/dev-preview.ts index dd11a46..a544cbe 100644 --- a/client/src/lib/dev-preview.ts +++ b/client/src/lib/dev-preview.ts @@ -1,3 +1,4 @@ +const previewMirrors: Record = {}; /** * 仅开发用的浏览器预览。 * @@ -243,6 +244,9 @@ function handle(command: string, args: Record): unknown { case "set_role": state.role = args.role as "team" | "referee"; return configView(); + case "set_camera_mirror": + previewMirrors[String(args.camera)] = { mirror: Boolean(args.mirror), mirrorVertical: Boolean(args.mirrorVertical) }; + return; case "set_mirror": state.mirror = Boolean(args.mirror); return configView(); @@ -432,6 +436,7 @@ function snapshot(): Snapshot { team: state.team, mirrored: state.mirror, mirroredVertical: state.mirrorVertical, + cameraMirrors: previewMirrors, matchClock: previewMatch(), operatorControl: { ...previewOperator }, demo: true, diff --git a/client/src/lib/ipc.ts b/client/src/lib/ipc.ts index 8820f5b..7187e4c 100644 --- a/client/src/lib/ipc.ts +++ b/client/src/lib/ipc.ts @@ -73,6 +73,7 @@ export const api = { call("set_team", { team, password: password ?? null }), setRole: (role: Role, password?: string) => call("set_role", { role, password: password ?? null }), + setCameraMirror: (camera: number, mirror: boolean, mirrorVertical: boolean) => call("set_camera_mirror", { camera, mirror, mirrorVertical }), setMirror: (mirror: boolean) => call("set_mirror", { mirror }), setMirrorVertical: (mirrorVertical: boolean) => call("set_mirror_vertical", { mirrorVertical }), saveHud: (hud: HudView) => call("save_hud", { hud }), diff --git a/client/src/lib/types.ts b/client/src/lib/types.ts index 46147b0..25289fb 100644 --- a/client/src/lib/types.ts +++ b/client/src/lib/types.ts @@ -227,6 +227,7 @@ export interface MediaFileDto { /** `cam_core::snapshot::Snapshot` */ export interface Snapshot { + cameraMirrors: Record; operatorControl: OperatorControlView; matchClock: MatchClockView; role: Role; diff --git a/client/src/lib/use-operator-control.ts b/client/src/lib/use-operator-control.ts index 2443da6..a56a4da 100644 --- a/client/src/lib/use-operator-control.ts +++ b/client/src/lib/use-operator-control.ts @@ -26,6 +26,7 @@ export function operatorGate(snapshot: Snapshot, connected: boolean, mode: Opera } export function useOperatorControl(options: Options) { + const mapping = useRef(neutralAxes()); const target = useRef(null); const current = useRef(options); current.current = options; @@ -43,6 +44,7 @@ export function useOperatorControl(options: Options) { const [error, setError] = useState(""); const stop = useCallback((reason = "") => { + mapping.current = neutralAxes(); generation.current++; attempt.current = null; sampler.current.reset(performance.now()); @@ -177,6 +179,7 @@ export function useOperatorControl(options: Options) { } const sampled = sampler.current.sample(performance.now(), sensitivityRef.current); if (sampled.stalled) { stop("界面输入已超时,操作已停止,请重新开启"); return; } + mapping.current = sampled.axes; session.sender.offer({ input: { captureId: session.id, sequence: ++session.sequence, active: true, ...sampled.axes }, at: performance.now() }); }, INPUT_INTERVAL_MS); return () => { @@ -199,5 +202,5 @@ export function useOperatorControl(options: Options) { sensitivityRef.current = value; setSensitivityState(value); }; - return { target, start, stop, activeMode, pending, error, sensitivity, setSensitivity }; + return { mapping, target, start, stop, activeMode, pending, error, sensitivity, setSensitivity }; } diff --git a/client/src/lib/version.ts b/client/src/lib/version.ts index 1c60265..3489ff9 100644 --- a/client/src/lib/version.ts +++ b/client/src/lib/version.ts @@ -6,16 +6,16 @@ */ export const BUILD = { - version: "0.5.0", + version: "0.6.0", major: 0, - minor: 5, + minor: 6, patch: 0, /** git 提交数,单调递增。 */ - build: 46, + build: 47, /** 线路协议版本。与固件自报的那个数直接比对。 */ protocol: 1, /** 生成时的提交日期(`YYYY-MM-DD`)。 */ - date: "2026-10-31", + date: "2026-11-01", } as const; /** `"0.2.0+57"` —— 界面上放得下的那一行。 */ diff --git a/client/src/pages/RefereePage.tsx b/client/src/pages/RefereePage.tsx index 819e46e..ad9f987 100644 --- a/client/src/pages/RefereePage.tsx +++ b/client/src/pages/RefereePage.tsx @@ -248,8 +248,8 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }: ? "已连接,等待画面…" : `等待${label}的图传` } - mirrored={snapshot.mirrored} - mirroredVertical={snapshot.mirroredVertical} + mirrored={snapshot.cameraMirrors[String(pane.camera)]?.mirror ?? snapshot.mirrored} + mirroredVertical={snapshot.cameraMirrors[String(pane.camera)]?.mirrorVertical ?? snapshot.mirroredVertical} // 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。 crosshair={null} grid={hud.grid} @@ -265,6 +265,13 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }: focused={focused} onSelect={() => setScope((current) => (current === pane.key ? "all" : pane.key))} > + {pane.camera !== null &&
event.stopPropagation()}> + {[false, true].map(vertical => { + const value = snapshot.cameraMirrors[String(pane.camera)] ?? { mirror: snapshot.mirrored, mirrorVertical: snapshot.mirroredVertical }; + const checked = vertical ? value.mirrorVertical : value.mirror; + return ; + })} +
} {hud.health.visible && pane.health && (
diff --git a/client/src/styles/operator.css b/client/src/styles/operator.css index 8228f4c..4e61f50 100644 --- a/client/src/styles/operator.css +++ b/client/src/styles/operator.css @@ -107,16 +107,34 @@ .cockpit .fwfault { top: calc(50% + 64px); bottom: auto; width: max-content; max-width: min(620px, 78%); z-index: 15; } .app--team .calibrate-bar { top: 140px; max-width: calc(100% - 120px); } -.operator-controls { position: absolute; z-index: 16; left: 50%; bottom: clamp(70px, 12vh, 120px); transform: translateX(-50%); width: min(580px, calc(100% - 48px)); padding: 14px 18px; color: var(--ink); background: #07100de8; border: 1px solid #74af8b55; font: 12px/1.5 var(--font-ui); text-align: center; } -.operator-controls__actions { display: flex; justify-content: center; gap: 12px; } -.operator-controls__sensitivity { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 12px; } -.operator-controls__sensitivity input { width: 120px; } -.operator-controls__sensitivity span { min-width: 88px; color: var(--ink-2); } -.operator-controls p { margin: 8px 0 0; color: var(--ink-2); } -.operator-controls .operator-controls__error { color: var(--warn); } -.operator-controls.is-active { width: auto; max-width: calc(100% - 48px); padding: 8px 14px; bottom: 58px; display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 16px; pointer-events: none; } -.operator-controls.is-active strong { color: var(--hud); white-space: nowrap; } -.operator-controls.is-active small { flex-basis: 100%; color: var(--ink-2); font-size: 10px; } -.operator-controls.is-debug { border-color: var(--warn-line); } -.operator-controls.is-debug strong { color: var(--warn); } -@media (max-height: 650px) { .operator-controls { bottom: 68px; padding: 10px 14px; } .operator-controls.is-active { bottom: 42px; } } +/* 操控入口只占左下角一行,参数在二级菜单中展开。 */ +.operator-controls { position: absolute; z-index: 16; left: 28px; bottom: 48px; color: var(--ink); } +.operator-controls__toggle { gap: 10px; min-width: 116px; background: var(--panel); } +.operator-controls__toggle > i { width: 6px; height: 6px; background: var(--ink-3); } +.operator-controls__toggle > i.is-on { background: var(--hud); } +.operator-controls__toggle > span { margin-left: auto; color: var(--ink-3); font: 10px var(--font-mono); } +.operator-controls__menu { position: absolute; bottom: calc(100% + 8px); left: 0; width: min(300px, calc(100vw - 56px)); padding: 16px; display: grid; gap: 16px; border: 1px solid var(--line-3); background: var(--panel); animation: dialog-in var(--dur-short4) var(--m3-emphasized-decelerate) both; } +.operator-controls__actions { display: flex; gap: 8px; } +.operator-controls__actions > button { flex: 1; } +.operator-controls__sensitivity { display: grid; gap: 4px; font-size: 11px; color: var(--ink-2); } +.operator-controls__menu small { font-size: 10px; color: var(--ink-3); } +.operator-controls__fault { margin-left: 10px; font-size: 10px; color: var(--warn); } +.operator-mapping { position: absolute; z-index: 12; pointer-events: none; top: 50%; left: 50%; width: min(460px, calc(100% - 56px)); transform: translate(-50%, -50%); color: var(--hud); padding: 18px 22px; background: rgb(5 16 12 / .28); border: 1px solid #74af8b55; font: 10px/1.5 var(--font-mono); animation: hud-reveal var(--dur-medium2) var(--m3-emphasized-decelerate) both; } +.operator-mapping header, .operator-mapping footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.operator-mapping header { letter-spacing: .12em; } +.operator-mapping header b { font-weight: 400; color: var(--hud-dim); } +.operator-mapping__flow { display: flex; justify-content: center; align-items: center; gap: 20px; padding: 12px 0; color: var(--hud-dim); } +.operator-mapping__flow i { font-style: normal; } +.operator-mapping__channels { display: grid; gap: 10px; } +.operator-mapping__channel { display: grid; grid-template-columns: 80px 1fr 55px; gap: 0 12px; align-items: baseline; } +.operator-mapping__channel > strong { text-align: right; font-size: 16px; font-weight: 400; } +.operator-mapping__channel > span:first-child { color: var(--hud-dim); } +.operator-mapping__track { grid-column: 1 / -1; height: 3px; background: #74af8b22; position: relative; } +.operator-mapping__track > i { position: absolute; height: 100%; background: var(--hud); transition: left var(--dur-short1) var(--m3-standard), width var(--dur-short1) var(--m3-standard); } +.operator-mapping__track > b { position: absolute; left: 50%; top: -2px; height: 7px; width: 1px; background: #74af8b66; } +.operator-mapping footer { border-top: 1px solid #74af8b33; margin-top: 16px; padding-top: 10px; color: var(--hud-dim); } +.operator-mapping .is-firing { color: var(--hud); } +.ref__mirror-controls { position: absolute; z-index: 8; bottom: 42px; right: 12px; display: flex; gap: 6px; } +.ref__mirror-controls .btn { background: var(--panel); font-size: 10px; } +@media (max-height: 650px) { .operator-controls { bottom: 38px; } .operator-mapping { padding: 10px 18px; } } +@media (prefers-reduced-motion: reduce) { .operator-controls__menu, .operator-mapping { animation: none; } .operator-mapping__track > i { transition: none; } } diff --git a/docs/client/client.md b/docs/client/client.md index 4709b51..d7873a9 100644 --- a/docs/client/client.md +++ b/docs/client/client.md @@ -58,10 +58,14 @@ client/ ### 选手键鼠操作 -绑定在线 C3 后,可在画面下方开启操作:WASD 平移、鼠标滑动控制云台速度、左键按住发送发射状态。鼠标锁定后不受窗口边缘限制;按 ESC 退出,再按 ESC 打开菜单。比赛模式仅在比赛进行中有效;“赛前调试”单独开启,准备、待开赛或尚未连接裁判时可使用,开始倒计时会退出。失焦、断连、结束或输入超时均回零,恢复后需重新点击。 +绑定在线 C3 后,可在画面左下角“操控”开关的二级菜单开启操作:WASD 平移、鼠标滑动控制云台速度、左键按住发送发射状态。鼠标锁定后不受窗口边缘限制;按 ESC 退出,再按 ESC 打开菜单。比赛模式仅在比赛进行中有效;“赛前调试”单独开启,准备、待开赛或尚未连接裁判时可使用,开始倒计时会退出。失焦、断连、结束或输入超时均回零,恢复后需重新点击。 默认 1000 像素/秒映射到通道满幅 ±1000,支持本次会话的灵敏度调节。装甲板 TXD/GPIO21 以 115200 8N1 输出项目协议,软件日志改走 USB。客户端与 C3 均需更新,并在下位机接入解析器;当前没有串口操控应答,界面不表示电机已经响应。完整映射、串口帧与 C99 接收示例见[键鼠操作与用户 UART](../protocol/operator-control.md)。 +操控入口默认只保留左下角开关,比赛/赛前调试与灵敏度滑条在二级菜单中。赛前调试发送时,画面中央以半透明 HUD 显示 CH0–CH3 的输入、速度值和发射位;它显示客户端输入,不是下位机实测速度或串口应答。动画使用现有 M3 缓动令牌并支持减少动态效果。 + +画面镜像按图传板 ID 双向同步:选手修改本车后裁判对应一路更新,裁判每路的左右/上下镜像按钮也会回传;旧配置保留原默认方向。两端需更新客户端,固件无需更新,详情见[镜像同步协议](../protocol/udp.md#画面镜像同步类型-12)。 + `pnpm test:input` 检查速度换算、停止与最新输入队列;浏览器预览只模拟本地输入,页面标记“合成输入”,不会发送现场控制。 ### 配色:墨黑蓝打底,只有一支红 diff --git a/docs/protocol/udp.md b/docs/protocol/udp.md index 910965c..7df22b6 100644 --- a/docs/protocol/udp.md +++ b/docs/protocol/udp.md @@ -77,6 +77,7 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b | 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 | | 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 | | 10 `MatchResult` | 裁判端 → 选手端 | 锁定的终局结论与结束计时,广播至 UDP 5601 | +| 12 `CameraMirror` | 选手端 ↔ 裁判端 | 每路图传镜像寄存器,广播 UDP 5601 | | 11 `OperatorControl` | 选手端 → 绑定的装甲板 | 四轴速度和发射状态,定向发送到主板上报端口 | 类型 11 保持线路版本 1,不改变旧消息布局;旧 C3 会忽略该类型,使用操控功能需更新 C3。载荷、租约及下游 UART 帧见[键鼠操作与用户 UART](operator-control.md)。 @@ -289,3 +290,11 @@ UDP 不保证数据报的顺序和到达。接收端等待下一张完整帧, 客户端先进入结束阶段并发送禁止扣血许可,再向固定的本局槽位主板发送同序号复位请求;每 200 ms 随新许可更新请求序号,最多等待 3 秒。板端只接受目标 id 匹配、同一来源 IP/端口与会话、序号等于最新有效禁止扣血许可的请求。首次执行恢复满血并清受击计数、冷却;同复位 id 的重试只回复回执并重发血量,不重复复位。旧复位 id、旧许可序号、过期许可及运行许可下的请求均拒绝。 回执定向发回裁判端,并沿用请求字段;板端同时通过原血量通道广播四路真实血量。客户端逐板核对来源地址、会话、复位 id 和已发送序号,收到回执及其后的四路 100 血上报才完成重置,不根据回执伪造血量。部分成功或超时均保留结束阶段。来源与会话约束防止意外混用,不提供身份认证。旧装甲板忽略 type=9,必须更新固件才能远程复位;图传板无需更新。独立字节核对见 `python armor/scripts/test-probe.py`,探测器不发送复位。 + +### 画面镜像同步(类型 12) + +客户端按图传板 ID 保存水平、垂直镜像,双方均可修改;裁判两路独立。沿用线路版本 1、27 字节头,头部业务字段均为零。固定 21 字节负载依次为 camera_id:u32、revision:u64、origin:u64、flags:u8,均小端;flags bit0 水平、bit1 垂直,其余位必须为零。三个整数必须非零,整包严格 48 字节。 + +revision 为逻辑时钟,本地修改取已知最大修订号加一,origin 为进程实例标识。接收仅应用 `(revision, origin)` 更大的值,重复、乱序和回声不会反复覆盖;并发同修订号按 origin 排序收敛,不依赖两台电脑墙钟。只接收已绑定图传板或裁判当前槽位的设置,每 200 ms 重发这些相机已有的修订记录以补偿 UDP 丢包和晚加入。接收回调只更新最多两路的内存收件箱,配置写盘在后台执行。 + +配置中 `cameraMirrors` 保存每路记录,旧配置缺失时回落到原有镜像默认值。尚未改动过的默认值不广播,避免新加入的客户端覆盖已配置记录。全局设置对当前槽位批量应用,裁判画面下方按钮只修改所在一路。演示预览不收发真实同步消息。需要双方更新客户端,固件无需更新;广播仍受网卡、防火墙和局域网可达性影响,该消息不提供身份认证。 diff --git a/docs/releases/changelog.json b/docs/releases/changelog.json index 8f328e9..4ff3bc7 100644 --- a/docs/releases/changelog.json +++ b/docs/releases/changelog.json @@ -1,12 +1,12 @@ { - "version": "0.5.0", + "version": "0.6.0", "major": 0, - "minor": 5, + "minor": 6, "patch": 0, - "build": 46, + "build": 47, "protocol": 1, - "date": "2026-10-31", - "baseline": "v0.5.0", + "date": "2026-11-01", + "baseline": "v0.6.0", "commits": 0, "groups": {} } diff --git a/docs/releases/changelog.md b/docs/releases/changelog.md index a369e34..068fb10 100644 --- a/docs/releases/changelog.md +++ b/docs/releases/changelog.md @@ -4,6 +4,14 @@ > 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。 > 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。 +## v0.6.0 — 2026-11-01 + +1 个提交 + +### 新增 + +- **client** · 同步每路镜像并精简操控入口与 HUD 映射 + ## v0.5.0 — 2026-10-31 1 个提交 diff --git a/version.json b/version.json index 18b336e..08dc19e 100644 --- a/version.json +++ b/version.json @@ -1,11 +1,11 @@ { - "version": "0.5.0", + "version": "0.6.0", "major": 0, - "minor": 5, + "minor": 6, "patch": 0, - "build": 46, + "build": 47, "protocol": 1, - "date": "2026-10-31", - "baseline": "v0.5.0", + "date": "2026-11-01", + "baseline": "v0.6.0", "note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。" } diff --git a/vt/protocol/src/camera_mirror.rs b/vt/protocol/src/camera_mirror.rs new file mode 100644 index 0000000..7d0fc3f --- /dev/null +++ b/vt/protocol/src/camera_mirror.rs @@ -0,0 +1,77 @@ +use crate::{decode_header, encode_header_into, Header, MsgType, HEADER_LEN}; + +/// 每路画面的镜像寄存器。revision 是逻辑时钟,origin 用于并发写入的确定排序。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CameraMirror { + pub camera_id: u32, + pub revision: u64, + pub origin: u64, + pub mirror: bool, + pub mirror_vertical: bool, +} +impl CameraMirror { + pub fn encode(self) -> Option> { + if self.camera_id == 0 || self.revision == 0 || self.origin == 0 { + return None; + } + let mut bytes = Vec::new(); + encode_header_into( + &Header { + msg_type: MsgType::CameraMirror, + ..Default::default() + }, + &mut bytes, + ); + bytes.extend(self.camera_id.to_le_bytes()); + bytes.extend(self.revision.to_le_bytes()); + bytes.extend(self.origin.to_le_bytes()); + bytes.push(u8::from(self.mirror) | (u8::from(self.mirror_vertical) << 1)); + Some(bytes) + } + pub fn decode(bytes: &[u8]) -> Option { + let h = decode_header(bytes)?; + if h.msg_type != MsgType::CameraMirror + || bytes.len() != HEADER_LEN + 21 + || bytes[7..HEADER_LEN].iter().any(|v| *v != 0) + { + return None; + } + let p = &bytes[HEADER_LEN..]; + if p[20] > 3 { + return None; + } + let value = Self { + camera_id: u32::from_le_bytes(p[..4].try_into().ok()?), + revision: u64::from_le_bytes(p[4..12].try_into().ok()?), + origin: u64::from_le_bytes(p[12..20].try_into().ok()?), + mirror: p[20] & 1 != 0, + mirror_vertical: p[20] & 2 != 0, + }; + value.encode()?; + Some(value) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exact_validated_mirror_roundtrip() { + let p = CameraMirror { + camera_id: 7, + revision: 4, + origin: 2, + mirror: true, + mirror_vertical: false, + }; + let bytes = p.encode().unwrap(); + assert_eq!(CameraMirror::decode(&bytes), Some(p)); + for n in 0..bytes.len() { + assert!(CameraMirror::decode(&bytes[..n]).is_none()); + } + for at in [5, 7, HEADER_LEN + 20] { + let mut bad = bytes.clone(); + bad[at] = 255; + assert!(CameraMirror::decode(&bad).is_none()); + } + } +} diff --git a/vt/protocol/src/lib.rs b/vt/protocol/src/lib.rs index 52e60d0..1125cd3 100644 --- a/vt/protocol/src/lib.rs +++ b/vt/protocol/src/lib.rs @@ -47,6 +47,8 @@ //! ``` use std::net::{Ipv4Addr, SocketAddrV4}; +mod camera_mirror; +pub use camera_mirror::CameraMirror; mod match_state; pub use match_state::MatchState; @@ -136,6 +138,7 @@ pub enum MsgType { MatchResult = 10, /// 选手端定向发送给已绑定装甲板的四轴速度与发射状态。 OperatorControl = 11, + CameraMirror = 12, } impl MsgType { @@ -153,6 +156,7 @@ impl MsgType { 9 => MsgType::ArmorReset, 10 => MsgType::MatchResult, 11 => MsgType::OperatorControl, + 12 => MsgType::CameraMirror, _ => return None, }) } diff --git a/vt/scripts/udp_probe.py b/vt/scripts/udp_probe.py index cabf6b1..48388b2 100644 --- a/vt/scripts/udp_probe.py +++ b/vt/scripts/udp_probe.py @@ -40,6 +40,7 @@ MSG_ARMOR_DAMAGE_CONTROL = 8 MSG_ARMOR_RESET = 9 MSG_MATCH_RESULT = 10 MSG_OPERATOR_CONTROL = 11 +MSG_CAMERA_MIRROR = 12 TYPE_NAMES = { MSG_VIDEO: "video", @@ -53,6 +54,7 @@ TYPE_NAMES = { MSG_ARMOR_RESET: "armor-reset", MSG_MATCH_RESULT: "match-result", MSG_OPERATOR_CONTROL: "operator-control", + MSG_CAMERA_MIRROR: "camera-mirror", }