feat(match): 添加画面上下镜像、跳过准备和装甲板整局复位
This commit is contained in:
39 files changed
+1092
-52
No files matched your search
@@ -188,6 +188,28 @@ fn main() -> Result<()> {
|
|||||||
damage.accept(command, from, now);
|
damage.accept(command, from, now);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Ok(Some((net::ControlCommand::Reset(mut command), from))) => {
|
||||||
|
if command.board_id == sender_id {
|
||||||
|
if let Some(apply) = damage.accept_reset(command, from, now) {
|
||||||
|
if apply {
|
||||||
|
armor.set_damage_enabled(false);
|
||||||
|
armor.reset();
|
||||||
|
warn!(
|
||||||
|
"referee reset: hp={} reset_id={}",
|
||||||
|
armor.hp(),
|
||||||
|
command.reset_id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
command.acknowledged = true;
|
||||||
|
if let Some(bytes) = command.encode() {
|
||||||
|
if let Err(err) = reporter.send_to(&bytes, from) {
|
||||||
|
warn!("reset acknowledgement failed: {err:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
force_report = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(None) => break,
|
Ok(None) => break,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("client control receive failed: {err:#}");
|
warn!("client control receive failed: {err:#}");
|
||||||
|
|||||||
@@ -21,11 +21,12 @@ use anyhow::{anyhow, Result};
|
|||||||
use esp_idf_svc::sys as ffi;
|
use esp_idf_svc::sys as ffi;
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
|
|
||||||
use armor_protocol::{ArmorControl, ArmorDamageControl, ARMOR_PORT, BROADCAST_ADDR};
|
use armor_protocol::{ArmorControl, ArmorDamageControl, ArmorReset, ARMOR_PORT, BROADCAST_ADDR};
|
||||||
|
|
||||||
pub enum ControlCommand {
|
pub enum ControlCommand {
|
||||||
Team(ArmorControl),
|
Team(ArmorControl),
|
||||||
Damage(ArmorDamageControl),
|
Damage(ArmorDamageControl),
|
||||||
|
Reset(ArmorReset),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 把 Rust 的 socket 地址转成 lwIP 期望的 C 结构。
|
/// 把 Rust 的 socket 地址转成 lwIP 期望的 C 结构。
|
||||||
@@ -98,6 +99,8 @@ impl Reporter {
|
|||||||
ControlCommand::Team(control)
|
ControlCommand::Team(control)
|
||||||
} else if let Some(control) = ArmorDamageControl::decode(bytes) {
|
} else if let Some(control) = ArmorDamageControl::decode(bytes) {
|
||||||
ControlCommand::Damage(control)
|
ControlCommand::Damage(control)
|
||||||
|
} else if let Some(control) = ArmorReset::decode(bytes) {
|
||||||
|
ControlCommand::Reset(control)
|
||||||
} else {
|
} else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
@@ -148,7 +151,11 @@ impl Reporter {
|
|||||||
|
|
||||||
/// 把一个数据报广播到裁判终端。
|
/// 把一个数据报广播到裁判终端。
|
||||||
pub fn broadcast(&self, payload: &[u8]) -> Result<()> {
|
pub fn broadcast(&self, payload: &[u8]) -> Result<()> {
|
||||||
let addr = to_sockaddr(SocketAddrV4::new(BROADCAST_ADDR, ARMOR_PORT));
|
self.send_to(payload, SocketAddrV4::new(BROADCAST_ADDR, ARMOR_PORT))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_to(&self, payload: &[u8], destination: SocketAddrV4) -> Result<()> {
|
||||||
|
let addr = to_sockaddr(destination);
|
||||||
|
|
||||||
// SAFETY: 缓冲区与地址在调用期间都有效;sendto 复制数据而不是持有指针。
|
// SAFETY: 缓冲区与地址在调用期间都有效;sendto 复制数据而不是持有指针。
|
||||||
let rc = unsafe {
|
let rc = unsafe {
|
||||||
|
|||||||
@@ -37,7 +37,7 @@
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
pub use protocol::{id_from_mac, ArmorHealth, MsgType, ARMOR_PORT, BROADCAST_ADDR};
|
pub use protocol::{id_from_mac, ArmorHealth, MsgType, ARMOR_PORT, BROADCAST_ADDR};
|
||||||
pub use protocol::{ArmorControl, ArmorDamageControl, ARMOR_UNASSIGNED};
|
pub use protocol::{ArmorControl, ArmorDamageControl, ArmorReset, ARMOR_UNASSIGNED};
|
||||||
|
|
||||||
pub const CLIENT_LEASE: Duration = Duration::from_secs(2);
|
pub const CLIENT_LEASE: Duration = Duration::from_secs(2);
|
||||||
pub const DAMAGE_LEASE: Duration = Duration::from_secs(1);
|
pub const DAMAGE_LEASE: Duration = Duration::from_secs(1);
|
||||||
@@ -46,6 +46,7 @@ pub const DAMAGE_LEASE: Duration = Duration::from_secs(1);
|
|||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct DamageLink {
|
pub struct DamageLink {
|
||||||
source: Option<(std::net::SocketAddrV4, u64, u64, Duration, bool)>,
|
source: Option<(std::net::SocketAddrV4, u64, u64, Duration, bool)>,
|
||||||
|
last_reset: Option<(std::net::SocketAddrV4, u64, u64)>,
|
||||||
}
|
}
|
||||||
impl DamageLink {
|
impl DamageLink {
|
||||||
pub fn disconnect(&mut self) {
|
pub fn disconnect(&mut self) {
|
||||||
@@ -83,6 +84,40 @@ impl DamageLink {
|
|||||||
self.source
|
self.source
|
||||||
.is_some_and(|(_, _, _, at, enabled)| enabled && now.saturating_sub(at) < DAMAGE_LEASE)
|
.is_some_and(|(_, _, _, at, enabled)| enabled && now.saturating_sub(at) < DAMAGE_LEASE)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Some(true) 执行一次复位;Some(false) 只重发回执;None 拒绝。
|
||||||
|
/// 必须先收到同源、同序号的禁止扣血许可,延迟到达的旧复位不能影响后续阶段。
|
||||||
|
pub fn accept_reset(
|
||||||
|
&mut self,
|
||||||
|
command: ArmorReset,
|
||||||
|
from: std::net::SocketAddrV4,
|
||||||
|
now: Duration,
|
||||||
|
) -> Option<bool> {
|
||||||
|
let (addr, session, sequence, at, enabled) = self.source?;
|
||||||
|
if command.acknowledged
|
||||||
|
|| enabled
|
||||||
|
|| addr != from
|
||||||
|
|| session != command.session
|
||||||
|
|| sequence != command.sequence
|
||||||
|
|| command.reset_id == 0
|
||||||
|
|| command.reset_id > sequence
|
||||||
|
|| now.saturating_sub(at) >= DAMAGE_LEASE
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if let Some((last_addr, last_session, reset_id)) = self.last_reset {
|
||||||
|
if last_addr == from && last_session == session {
|
||||||
|
if command.reset_id < reset_id {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if command.reset_id == reset_id {
|
||||||
|
return Some(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.last_reset = Some((from, session, command.reset_id));
|
||||||
|
Some(true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 只接受当前持有者续约;其他客户端需等租约到期,避免裁判与操作手交替改色。
|
/// 只接受当前持有者续约;其他客户端需等租约到期,避免裁判与操作手交替改色。
|
||||||
@@ -734,6 +769,94 @@ mod tests {
|
|||||||
assert!(!link.enabled(ms(2003)));
|
assert!(!link.enabled(ms(2003)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remote_reset_requires_current_disabled_permission_and_only_applies_once() {
|
||||||
|
let mut link = DamageLink::default();
|
||||||
|
let from = "192.168.1.2:5601".parse().unwrap();
|
||||||
|
let other = "192.168.1.3:5601".parse().unwrap();
|
||||||
|
let mut permit = ArmorDamageControl {
|
||||||
|
board_id: 9,
|
||||||
|
session: 11,
|
||||||
|
sequence: 10,
|
||||||
|
enabled: false,
|
||||||
|
};
|
||||||
|
let mut reset = ArmorReset {
|
||||||
|
board_id: 9,
|
||||||
|
session: 11,
|
||||||
|
sequence: 10,
|
||||||
|
reset_id: 10,
|
||||||
|
acknowledged: false,
|
||||||
|
};
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(0)), None);
|
||||||
|
assert!(link.accept(permit, from, ms(0)));
|
||||||
|
assert_eq!(link.accept_reset(reset, other, ms(1)), None);
|
||||||
|
assert_eq!(
|
||||||
|
link.accept_reset(
|
||||||
|
ArmorReset {
|
||||||
|
session: 12,
|
||||||
|
..reset
|
||||||
|
},
|
||||||
|
from,
|
||||||
|
ms(1)
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
link.accept_reset(
|
||||||
|
ArmorReset {
|
||||||
|
acknowledged: true,
|
||||||
|
..reset
|
||||||
|
},
|
||||||
|
from,
|
||||||
|
ms(1)
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(1)), Some(true));
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(2)), Some(false));
|
||||||
|
|
||||||
|
let mut a = armor();
|
||||||
|
a.on_sample(Plate::Front, 2500, ms(0)).unwrap();
|
||||||
|
assert_eq!(a.hp(), 97);
|
||||||
|
a.set_damage_enabled(false);
|
||||||
|
a.reset();
|
||||||
|
assert_eq!((a.hp(), a.hits(), a.plate_hits(Plate::Front)), (100, 0, 0));
|
||||||
|
assert!(!a.damage_enabled());
|
||||||
|
assert_eq!(a.color(), Rgb::for_team(0));
|
||||||
|
|
||||||
|
// 重试更新许可序号,但保留复位 id;丢回执也不能重复补血。
|
||||||
|
permit.sequence += 1;
|
||||||
|
assert!(link.accept(permit, from, ms(200)));
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(201)), None);
|
||||||
|
reset.sequence = permit.sequence;
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(201)), Some(false));
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(1200)), None);
|
||||||
|
permit.sequence += 1;
|
||||||
|
permit.enabled = true;
|
||||||
|
assert!(link.accept(permit, from, ms(1201)));
|
||||||
|
reset.sequence = permit.sequence;
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(1202)), None);
|
||||||
|
permit.sequence += 1;
|
||||||
|
permit.enabled = false;
|
||||||
|
assert!(link.accept(permit, from, ms(1203)));
|
||||||
|
reset.sequence = permit.sequence;
|
||||||
|
reset.reset_id = permit.sequence;
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(1204)), Some(true));
|
||||||
|
assert_eq!(
|
||||||
|
link.accept_reset(
|
||||||
|
ArmorReset {
|
||||||
|
reset_id: 10,
|
||||||
|
..reset
|
||||||
|
},
|
||||||
|
from,
|
||||||
|
ms(1205)
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
link.disconnect();
|
||||||
|
assert_eq!(link.accept_reset(reset, from, ms(1206)), None);
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- 血量 --
|
// ---------------------------------------------------------------- 血量 --
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ MSG_ARMOR_HEALTH = 5 # MsgType::ArmorHealth
|
|||||||
MSG_ARMOR_CONTROL = 6
|
MSG_ARMOR_CONTROL = 6
|
||||||
MSG_MATCH_STATE = 7 # 比赛计时广播;装甲板探测器忽略
|
MSG_MATCH_STATE = 7 # 比赛计时广播;装甲板探测器忽略
|
||||||
MSG_ARMOR_DAMAGE_CONTROL = 8 # 扣血许可;装甲板探测器忽略
|
MSG_ARMOR_DAMAGE_CONTROL = 8 # 扣血许可;装甲板探测器忽略
|
||||||
|
MSG_ARMOR_RESET = 9 # 复位与回执;探测器只解析,不发送
|
||||||
PROTOCOL_VERSION = 1
|
PROTOCOL_VERSION = 1
|
||||||
TEAM_NAMES = {0: "队伍一", 1: "队伍二", 255: "待分配队伍"}
|
TEAM_NAMES = {0: "队伍一", 1: "队伍二", 255: "待分配队伍"}
|
||||||
|
|
||||||
@@ -66,6 +67,24 @@ def decode_damage_control(data):
|
|||||||
return (board, session, sequence, bool(data[47])) if board and session and sequence else None
|
return (board, session, sequence, bool(data[47])) if board and session and sequence else None
|
||||||
|
|
||||||
|
|
||||||
|
def decode_reset(data):
|
||||||
|
"""独立核对复位及回执的 56 字节格式,不向设备发送复位。"""
|
||||||
|
if len(data) != HEADER + 29 or int.from_bytes(data[:4], "little") != MAGIC:
|
||||||
|
return None
|
||||||
|
if data[4] != MSG_ARMOR_RESET or int.from_bytes(data[5:7], "little") != PROTOCOL_VERSION or data[-1] not in (0, 1):
|
||||||
|
return None
|
||||||
|
board = int.from_bytes(data[27:31], "little")
|
||||||
|
session = int.from_bytes(data[31:39], "little")
|
||||||
|
sequence = int.from_bytes(data[39:47], "little")
|
||||||
|
reset_id = int.from_bytes(data[47:55], "little")
|
||||||
|
acknowledged = bool(data[55])
|
||||||
|
if not board or not session or not 0 < reset_id <= sequence:
|
||||||
|
return None
|
||||||
|
if int.from_bytes(data[7:11], "little") != (board if acknowledged else 0):
|
||||||
|
return None
|
||||||
|
return board, session, sequence, reset_id, acknowledged
|
||||||
|
|
||||||
|
|
||||||
def decode(data):
|
def decode(data):
|
||||||
"""解析一个数据报,返回 (team, index, hp, sender_id, version) 或 None。"""
|
"""解析一个数据报,返回 (team, index, hp, sender_id, version) 或 None。"""
|
||||||
if len(data) < HEADER + 4:
|
if len(data) < HEADER + 4:
|
||||||
|
|||||||
@@ -24,5 +24,13 @@ class WireTests(unittest.TestCase):
|
|||||||
self.assertIsNone(probe.decode(packet))
|
self.assertIsNone(probe.decode(packet))
|
||||||
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x02', packet[:31] + bytes(8) + packet[39:]):
|
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x02', packet[:31] + bytes(8) + packet[39:]):
|
||||||
self.assertIsNone(probe.decode_damage_control(invalid))
|
self.assertIsNone(probe.decode_damage_control(invalid))
|
||||||
|
def test_reset_golden_and_ack_identity(self):
|
||||||
|
packet = bytes.fromhex("3143564d090100" + "00" * 20 + "78563412" + "0807060504030201" + "0300000000000000" + "0200000000000000" + "00")
|
||||||
|
self.assertEqual(probe.decode_reset(packet), (0x12345678, 0x0102030405060708, 3, 2, False))
|
||||||
|
ack = packet[:7] + bytes.fromhex("78563412") + packet[11:-1] + b'\x01'
|
||||||
|
self.assertEqual(probe.decode_reset(ack)[-1], True)
|
||||||
|
self.assertIsNone(probe.decode(packet))
|
||||||
|
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x01', ack[:-1] + b'\x00', packet[:47] + bytes(8) + packet[55:]):
|
||||||
|
self.assertIsNone(probe.decode_reset(invalid))
|
||||||
|
|
||||||
if __name__ == "__main__": unittest.main()
|
if __name__ == "__main__": unittest.main()
|
||||||
@@ -200,6 +200,7 @@ pub struct ArmorHealthStore {
|
|||||||
assignments: Mutex<Vec<(u32, u8)>>,
|
assignments: Mutex<Vec<(u32, u8)>>,
|
||||||
match_sink: Mutex<Option<MatchSink>>,
|
match_sink: Mutex<Option<MatchSink>>,
|
||||||
damage_participants: Mutex<HashSet<u32>>,
|
damage_participants: Mutex<HashSet<u32>>,
|
||||||
|
reset: Mutex<Option<crate::armor_reset::ArmorResetTracker>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ArmorHealthStore {
|
impl Default for ArmorHealthStore {
|
||||||
@@ -217,6 +218,7 @@ impl ArmorHealthStore {
|
|||||||
assignments: Mutex::new(Vec::new()),
|
assignments: Mutex::new(Vec::new()),
|
||||||
match_sink: Mutex::new(None),
|
match_sink: Mutex::new(None),
|
||||||
damage_participants: Mutex::new(HashSet::new()),
|
damage_participants: Mutex::new(HashSet::new()),
|
||||||
|
reset: Mutex::new(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,6 +284,12 @@ impl ArmorHealthStore {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if let Some(packet) = protocol::ArmorReset::decode(bytes) {
|
||||||
|
if let Some(reset) = self.reset.lock().expect("armor reset poisoned").as_mut() {
|
||||||
|
reset.acknowledge(packet, addr);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 同一个端口上可能有别的东西(图传板的心跳、别的协议),解不出来就当不是给
|
// 同一个端口上可能有别的东西(图传板的心跳、别的协议),解不出来就当不是给
|
||||||
// 我的,安静跳过。
|
// 我的,安静跳过。
|
||||||
@@ -383,6 +391,9 @@ impl ArmorHealthStore {
|
|||||||
entry.last_seen = Instant::now();
|
entry.last_seen = Instant::now();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(reset) = self.reset.lock().expect("armor reset poisoned").as_mut() {
|
||||||
|
reset.observe(&report);
|
||||||
|
}
|
||||||
let sink = self.sink.lock().expect("armor sink mutex poisoned").clone();
|
let sink = self.sink.lock().expect("armor sink mutex poisoned").clone();
|
||||||
if let Some(sink) = sink {
|
if let Some(sink) = sink {
|
||||||
sink(report);
|
sink(report);
|
||||||
@@ -474,6 +485,55 @@ impl ArmorHealthStore {
|
|||||||
first_error.map_or(Ok(()), Err)
|
first_error.map_or(Ok(()), Err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn begin_reset(
|
||||||
|
&self,
|
||||||
|
state: &protocol::MatchState,
|
||||||
|
participants: [Option<u32>; 2],
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let tracker =
|
||||||
|
crate::armor_reset::ArmorResetTracker::new(state, participants, &self.boards())?;
|
||||||
|
let mut reset = self.reset.lock().expect("armor reset poisoned");
|
||||||
|
if reset.is_some() {
|
||||||
|
return Err("正在复位装甲板,请等待结果".into());
|
||||||
|
}
|
||||||
|
*reset = Some(tracker);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset_waiting(&self) -> Vec<u32> {
|
||||||
|
self.reset
|
||||||
|
.lock()
|
||||||
|
.expect("armor reset poisoned")
|
||||||
|
.as_ref()
|
||||||
|
.map(|reset| reset.waiting())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish_reset(&self) {
|
||||||
|
*self.reset.lock().expect("armor reset poisoned") = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 与禁止扣血许可使用同一份序号;每次心跳最多向每块待确认主板发送一次。
|
||||||
|
pub fn send_reset_controls(
|
||||||
|
&self,
|
||||||
|
socket: &UdpSocket,
|
||||||
|
state: &protocol::MatchState,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let packets = {
|
||||||
|
let mut reset = self.reset.lock().expect("armor reset poisoned");
|
||||||
|
reset
|
||||||
|
.as_mut()
|
||||||
|
.map(|reset| reset.packets(state))
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
for (packet, addr) in packets {
|
||||||
|
if let Some(bytes) = packet.encode() {
|
||||||
|
socket.send_to(&bytes, addr)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn send_controls(&self, socket: &UdpSocket) {
|
fn send_controls(&self, socket: &UdpSocket) {
|
||||||
let selected = self
|
let selected = self
|
||||||
.assignments
|
.assignments
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
//! 一次有界复位事务:固定目标,等待逐板回执及回执后的四路满血上报。
|
||||||
|
use crate::armor::{ArmorBoard, ArmorReport};
|
||||||
|
use protocol::{ArmorReset, MatchState};
|
||||||
|
use std::net::SocketAddrV4;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Target {
|
||||||
|
id: u32,
|
||||||
|
addr: SocketAddrV4,
|
||||||
|
acknowledged: bool,
|
||||||
|
full_plates: u8,
|
||||||
|
sent_sequence: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ArmorResetTracker {
|
||||||
|
session: u64,
|
||||||
|
reset_id: u64,
|
||||||
|
targets: Vec<Target>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ArmorResetTracker {
|
||||||
|
pub fn new(
|
||||||
|
state: &MatchState,
|
||||||
|
participants: [Option<u32>; 2],
|
||||||
|
boards: &[ArmorBoard],
|
||||||
|
) -> Result<Self, String> {
|
||||||
|
if state.phase != 6 || state.session == 0 || state.sequence == 0 {
|
||||||
|
return Err("请先结束本局,再复位装甲板".into());
|
||||||
|
}
|
||||||
|
if participants[0].is_some() && participants[0] == participants[1] {
|
||||||
|
return Err("两队不能使用同一块装甲板,请检查槽位".into());
|
||||||
|
}
|
||||||
|
let mut targets = Vec::new();
|
||||||
|
for id in participants.into_iter().flatten() {
|
||||||
|
let board = boards
|
||||||
|
.iter()
|
||||||
|
.find(|board| board.id == id && board.is_online())
|
||||||
|
.ok_or_else(|| format!("装甲板 0x{id:08X} 离线,无法复位;请恢复连接后重试"))?;
|
||||||
|
targets.push(Target {
|
||||||
|
id,
|
||||||
|
addr: board.addr,
|
||||||
|
acknowledged: false,
|
||||||
|
full_plates: 0,
|
||||||
|
sent_sequence: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
session: state.session,
|
||||||
|
reset_id: state.sequence,
|
||||||
|
targets,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn packets(&mut self, state: &MatchState) -> Vec<(ArmorReset, SocketAddrV4)> {
|
||||||
|
if state.phase != 6 || state.session != self.session || state.sequence < self.reset_id {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
self.targets
|
||||||
|
.iter_mut()
|
||||||
|
.filter(|target| !target.acknowledged)
|
||||||
|
.map(|target| {
|
||||||
|
target.sent_sequence = state.sequence;
|
||||||
|
(
|
||||||
|
ArmorReset {
|
||||||
|
board_id: target.id,
|
||||||
|
session: self.session,
|
||||||
|
sequence: state.sequence,
|
||||||
|
reset_id: self.reset_id,
|
||||||
|
acknowledged: false,
|
||||||
|
},
|
||||||
|
target.addr,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acknowledge(&mut self, packet: ArmorReset, from: SocketAddrV4) {
|
||||||
|
if !packet.acknowledged
|
||||||
|
|| packet.session != self.session
|
||||||
|
|| packet.reset_id != self.reset_id
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(target) = self.targets.iter_mut().find(|target| {
|
||||||
|
target.id == packet.board_id
|
||||||
|
&& target.addr == from
|
||||||
|
&& packet.sequence >= self.reset_id
|
||||||
|
&& packet.sequence <= target.sent_sequence
|
||||||
|
}) {
|
||||||
|
target.acknowledged = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn observe(&mut self, report: &ArmorReport) {
|
||||||
|
if let Some(target) = self.targets.iter_mut().find(|target| {
|
||||||
|
target.id == report.board && target.addr == report.addr && target.acknowledged
|
||||||
|
}) {
|
||||||
|
if report.hp == 100 && report.index < 4 {
|
||||||
|
target.full_plates |= 1 << report.index;
|
||||||
|
} else {
|
||||||
|
target.full_plates = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn waiting(&self) -> Vec<u32> {
|
||||||
|
self.targets
|
||||||
|
.iter()
|
||||||
|
.filter(|target| !target.acknowledged || target.full_plates != 0b1111)
|
||||||
|
.map(|target| target.id)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -438,6 +438,8 @@ pub struct Config {
|
|||||||
pub armor_id: Option<u32>,
|
pub armor_id: Option<u32>,
|
||||||
/// 左右镜像。摄像头装反了,出图左右颠倒,所以默认翻回来。
|
/// 左右镜像。摄像头装反了,出图左右颠倒,所以默认翻回来。
|
||||||
pub mirror: bool,
|
pub mirror: bool,
|
||||||
|
/// 上下镜像,与左右镜像独立;旧配置默认关闭。
|
||||||
|
pub mirror_vertical: bool,
|
||||||
/// 密码的 Argon2id PHC 字符串。`None` = 还没设过。
|
/// 密码的 Argon2id PHC 字符串。`None` = 还没设过。
|
||||||
///
|
///
|
||||||
/// 只对用户端有意义([`Role::needs_password`])。
|
/// 只对用户端有意义([`Role::needs_password`])。
|
||||||
@@ -463,6 +465,7 @@ impl Default for Config {
|
|||||||
camera_id: None,
|
camera_id: None,
|
||||||
armor_id: None,
|
armor_id: None,
|
||||||
mirror: true,
|
mirror: true,
|
||||||
|
mirror_vertical: false,
|
||||||
password: None,
|
password: None,
|
||||||
hud: HudConfig::default(),
|
hud: HudConfig::default(),
|
||||||
referee: RefereeConfig::default(),
|
referee: RefereeConfig::default(),
|
||||||
@@ -607,6 +610,7 @@ const HEADER: &str = "\
|
|||||||
# cameraId : 图传板 id,由 MAC 派生,重启不变,所以绑定是稳的
|
# cameraId : 图传板 id,由 MAC 派生,重启不变,所以绑定是稳的
|
||||||
# armorId : 装甲板主板 id,同上
|
# armorId : 装甲板主板 id,同上
|
||||||
# mirror : true = 左右镜像(摄像头装反了,默认)
|
# mirror : true = 左右镜像(摄像头装反了,默认)
|
||||||
|
# mirrorVertical: true = 上下镜像(默认关闭,可与左右镜像组合)
|
||||||
# password : Argon2id 哈希(仅 team 端)。这里没有明文,也恢复不出明文;
|
# password : Argon2id 哈希(仅 team 端)。这里没有明文,也恢复不出明文;
|
||||||
# 忘了密码就删掉这一行,然后第一次启动会要求重新设置。
|
# 忘了密码就删掉这一行,然后第一次启动会要求重新设置。
|
||||||
#
|
#
|
||||||
@@ -867,6 +871,14 @@ mod tests {
|
|||||||
assert!(!config.needs_password_setup(), "裁判端不设密码");
|
assert!(!config.needs_password_setup(), "裁判端不设密码");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn existing_configs_keep_their_orientation_without_vertical_mirroring() {
|
||||||
|
let config = Config::parse("mirror = false\nteamNames = [\"红队\", \"蓝队\"]\n").unwrap();
|
||||||
|
assert!(!config.mirror);
|
||||||
|
assert!(!config.mirror_vertical);
|
||||||
|
assert_eq!(config.team_names, ["红队", "蓝队"]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_roundtrip_survives_every_field() {
|
fn the_roundtrip_survives_every_field() {
|
||||||
let mut config = Config::default();
|
let mut config = Config::default();
|
||||||
@@ -877,6 +889,7 @@ mod tests {
|
|||||||
config.camera_id = Some(0x3D4D_8A9A);
|
config.camera_id = Some(0x3D4D_8A9A);
|
||||||
config.armor_id = Some(0x00AB_CDEF);
|
config.armor_id = Some(0x00AB_CDEF);
|
||||||
config.mirror = false;
|
config.mirror = false;
|
||||||
|
config.mirror_vertical = true;
|
||||||
config.password = Some("$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA".to_string());
|
config.password = Some("$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA".to_string());
|
||||||
config.hud.crosshair.offset_x = -0.125;
|
config.hud.crosshair.offset_x = -0.125;
|
||||||
config.hud.crosshair.style = CrosshairStyle::CircleDot;
|
config.hud.crosshair.style = CrosshairStyle::CircleDot;
|
||||||
@@ -894,6 +907,7 @@ mod tests {
|
|||||||
assert_eq!(back.camera_id, Some(0x3D4D_8A9A));
|
assert_eq!(back.camera_id, Some(0x3D4D_8A9A));
|
||||||
assert_eq!(back.armor_id, Some(0x00AB_CDEF));
|
assert_eq!(back.armor_id, Some(0x00AB_CDEF));
|
||||||
assert!(!back.mirror);
|
assert!(!back.mirror);
|
||||||
|
assert!(back.mirror_vertical);
|
||||||
assert_eq!(back.password, config.password);
|
assert_eq!(back.password, config.password);
|
||||||
assert_eq!(back.hud.crosshair.offset_x, -0.125);
|
assert_eq!(back.hud.crosshair.offset_x, -0.125);
|
||||||
assert_eq!(back.hud.crosshair.style, CrosshairStyle::CircleDot);
|
assert_eq!(back.hud.crosshair.style, CrosshairStyle::CircleDot);
|
||||||
|
|||||||
@@ -27,6 +27,7 @@
|
|||||||
//! 那两处要的是当前状态,不是每一帧。
|
//! 那两处要的是当前状态,不是每一帧。
|
||||||
|
|
||||||
pub mod armor;
|
pub mod armor;
|
||||||
|
pub mod armor_reset;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod match_clock;
|
pub mod match_clock;
|
||||||
pub mod password;
|
pub mod password;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ pub const SYNC_LEASE_MS: u64 = 1500;
|
|||||||
#[serde(tag = "type", rename_all = "camelCase")]
|
#[serde(tag = "type", rename_all = "camelCase")]
|
||||||
pub enum MatchAction {
|
pub enum MatchAction {
|
||||||
Prepare,
|
Prepare,
|
||||||
|
SkipPreparation,
|
||||||
Countdown {
|
Countdown {
|
||||||
seconds: u32,
|
seconds: u32,
|
||||||
},
|
},
|
||||||
@@ -162,6 +163,10 @@ impl MatchClock {
|
|||||||
self.state.phase = 1;
|
self.state.phase = 1;
|
||||||
self.state.remaining_ms = 180_000;
|
self.state.remaining_ms = 180_000;
|
||||||
}
|
}
|
||||||
|
MatchAction::SkipPreparation if matches!(self.state.phase, 1 | 2) => {
|
||||||
|
self.state.phase = 2;
|
||||||
|
self.state.remaining_ms = 0;
|
||||||
|
}
|
||||||
MatchAction::Countdown { seconds }
|
MatchAction::Countdown { seconds }
|
||||||
if self.state.phase == 2 && (1..=60).contains(&seconds) =>
|
if self.state.phase == 2 && (1..=60).contains(&seconds) =>
|
||||||
{
|
{
|
||||||
@@ -204,6 +209,20 @@ impl MatchClock {
|
|||||||
self.state.sequence = self.state.sequence.saturating_add(1);
|
self.state.sequence = self.state.sequence.saturating_add(1);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
/// 装甲板复位期间保持结束状态,先停止扣血;确认满血后再 Reset 到未开始。
|
||||||
|
pub fn begin_reset(&mut self, has_outcome: bool, now: u64) -> Result<MatchState, String> {
|
||||||
|
if !self.authority {
|
||||||
|
return Err("只有裁判端可以重置比赛".into());
|
||||||
|
}
|
||||||
|
self.advance(now);
|
||||||
|
if !matches!(self.state.phase, 0 | 6) && !has_outcome {
|
||||||
|
return Err("比赛尚未结束,请先结束本局再重置".into());
|
||||||
|
}
|
||||||
|
self.state.phase = 6;
|
||||||
|
clear_pause(&mut self.state);
|
||||||
|
self.state.sequence = self.state.sequence.saturating_add(1);
|
||||||
|
Ok(self.state.clone())
|
||||||
|
}
|
||||||
fn pause(&mut self, kind: u8, team: u8, reason: String) -> Result<(), String> {
|
fn pause(&mut self, kind: u8, team: u8, reason: String) -> Result<(), String> {
|
||||||
if !(1..=4).contains(&self.state.phase) {
|
if !(1..=4).contains(&self.state.phase) {
|
||||||
return Err("当前阶段不能申请技术暂停".into());
|
return Err("当前阶段不能申请技术暂停".into());
|
||||||
@@ -315,6 +334,71 @@ mod tests {
|
|||||||
assert_eq!((v.phase, v.elapsed_ms), ("finished", 180_000));
|
assert_eq!((v.phase, v.elapsed_ms), ("finished", 180_000));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
|
fn skip_preparation_waits_for_confirmation_and_syncs_without_changing_session() {
|
||||||
|
let mut c = MatchClock::new(true, 44, 0);
|
||||||
|
assert!(c.action(MatchAction::SkipPreparation, 0).is_err());
|
||||||
|
c.action(MatchAction::Prepare, 0).unwrap();
|
||||||
|
c.action(MatchAction::SkipPreparation, 1000).unwrap();
|
||||||
|
let packet = c.broadcast(1000).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(packet.phase, packet.remaining_ms, packet.elapsed_ms),
|
||||||
|
(2, 0, 0)
|
||||||
|
);
|
||||||
|
let mut follower = MatchClock::new(false, 2, 0);
|
||||||
|
assert!(follower.receive(packet.clone(), Ipv4Addr::LOCALHOST, 1000));
|
||||||
|
assert_eq!(follower.view(1000).phase, "ready");
|
||||||
|
assert!(follower.action(MatchAction::SkipPreparation, 1000).is_err());
|
||||||
|
assert_eq!(c.view(200_000).phase, "ready");
|
||||||
|
// 重复操作、准备刚好自然结束时均保持待开赛。
|
||||||
|
c.action(MatchAction::SkipPreparation, 200_000).unwrap();
|
||||||
|
c.action(MatchAction::Countdown { seconds: 5 }, 200_000)
|
||||||
|
.unwrap();
|
||||||
|
assert!(c.action(MatchAction::SkipPreparation, 201_000).is_err());
|
||||||
|
assert_eq!(c.view(205_000).phase, "running");
|
||||||
|
assert!(c.action(MatchAction::SkipPreparation, 205_000).is_err());
|
||||||
|
let later = c.broadcast(205_000).unwrap();
|
||||||
|
assert_eq!(later.session, packet.session);
|
||||||
|
assert!(later.sequence > packet.sequence);
|
||||||
|
assert!(follower.receive(later, Ipv4Addr::LOCALHOST, 205_000));
|
||||||
|
assert!(!follower.receive(packet, Ipv4Addr::LOCALHOST, 205_000));
|
||||||
|
assert_eq!(follower.view(205_000).phase, "running");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn reset_after_a_verdict_stops_the_match_then_clears_all_round_state() {
|
||||||
|
let mut c = MatchClock::new(true, 44, 0);
|
||||||
|
ready(&mut c);
|
||||||
|
c.action(MatchAction::Countdown { seconds: 1 }, 180_000)
|
||||||
|
.unwrap();
|
||||||
|
assert!(c.begin_reset(false, 185_000).is_err());
|
||||||
|
c.action(
|
||||||
|
MatchAction::PauseOfficial {
|
||||||
|
reason: "检查".into(),
|
||||||
|
},
|
||||||
|
185_000,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let stopped = c.begin_reset(true, 186_000).unwrap();
|
||||||
|
assert_eq!((stopped.phase, stopped.pause_kind), (6, 0));
|
||||||
|
assert_eq!(c.view(190_000).elapsed_ms, 4000);
|
||||||
|
c.action(MatchAction::Reset, 190_000).unwrap();
|
||||||
|
let state = c.broadcast(190_000).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
state.phase,
|
||||||
|
state.remaining_ms,
|
||||||
|
state.elapsed_ms,
|
||||||
|
state.pause_elapsed_ms
|
||||||
|
),
|
||||||
|
(0, 0, 0, 0)
|
||||||
|
);
|
||||||
|
assert_eq!(state.resume_phase, 0);
|
||||||
|
assert!(state.reason.is_empty());
|
||||||
|
assert_eq!(state.session, stopped.session);
|
||||||
|
assert!(state.sequence > stopped.sequence);
|
||||||
|
assert!(state.valid());
|
||||||
|
assert!(MatchClock::new(false, 1, 0).begin_reset(true, 0).is_err());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
fn pause_approval_freezes_time_and_expiry_never_resumes() {
|
fn pause_approval_freezes_time_and_expiry_never_resumes() {
|
||||||
let mut c = MatchClock::new(true, 1, 0);
|
let mut c = MatchClock::new(true, 1, 0);
|
||||||
c.action(MatchAction::Prepare, 0).unwrap();
|
c.action(MatchAction::Prepare, 0).unwrap();
|
||||||
|
|||||||
@@ -389,6 +389,7 @@ pub struct Snapshot {
|
|||||||
pub role: Role,
|
pub role: Role,
|
||||||
pub team: u8,
|
pub team: u8,
|
||||||
pub mirrored: bool,
|
pub mirrored: bool,
|
||||||
|
pub mirrored_vertical: bool,
|
||||||
/// 演示模式:画面与血量是本地合成的,不是场上的板子。界面必须把它显示出来,
|
/// 演示模式:画面与血量是本地合成的,不是场上的板子。界面必须把它显示出来,
|
||||||
/// 否则截图与验收会被误读成真实链路。
|
/// 否则截图与验收会被误读成真实链路。
|
||||||
pub demo: bool,
|
pub demo: bool,
|
||||||
@@ -436,6 +437,7 @@ pub struct ConfigView {
|
|||||||
pub armor_id: Option<u32>,
|
pub armor_id: Option<u32>,
|
||||||
pub armor_id_text: Option<String>,
|
pub armor_id_text: Option<String>,
|
||||||
pub mirror: bool,
|
pub mirror: bool,
|
||||||
|
pub mirror_vertical: bool,
|
||||||
pub password_set: bool,
|
pub password_set: bool,
|
||||||
pub hud: HudView,
|
pub hud: HudView,
|
||||||
pub recording_dir: String,
|
pub recording_dir: String,
|
||||||
@@ -465,6 +467,7 @@ impl From<&Config> for ConfigView {
|
|||||||
armor_id: config.armor_id,
|
armor_id: config.armor_id,
|
||||||
armor_id_text: config.armor_id.map(id_text),
|
armor_id_text: config.armor_id.map(id_text),
|
||||||
mirror: config.mirror,
|
mirror: config.mirror,
|
||||||
|
mirror_vertical: config.mirror_vertical,
|
||||||
password_set: config.password.is_some(),
|
password_set: config.password.is_some(),
|
||||||
hud: HudView {
|
hud: HudView {
|
||||||
health: config.hud.health.clone(),
|
health: config.hud.health.clone(),
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
use cam_core::armor::{ArmorBoard, ArmorHealthStore, ArmorReport};
|
||||||
|
use cam_core::armor_reset::ArmorResetTracker;
|
||||||
|
use cam_core::match_clock::{MatchAction, MatchClock};
|
||||||
|
use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
fn board(id: u32) -> ArmorBoard {
|
||||||
|
ArmorBoard {
|
||||||
|
id,
|
||||||
|
addr: SocketAddrV4::new(Ipv4Addr::LOCALHOST, 41000 + id as u16),
|
||||||
|
team: (id - 1) as u8,
|
||||||
|
hp: 0,
|
||||||
|
plates_seen: 15,
|
||||||
|
last_seen: Instant::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn partial_reset_needs_matching_ack_and_four_fresh_full_health_reports() {
|
||||||
|
let mut clock = MatchClock::new(true, 1, 0);
|
||||||
|
let state = clock.begin_reset(true, 0).unwrap();
|
||||||
|
let boards = [board(1), board(2)];
|
||||||
|
let mut reset = ArmorResetTracker::new(&state, [Some(1), Some(2)], &boards).unwrap();
|
||||||
|
let packets = reset.packets(&state);
|
||||||
|
let (request, addr) = packets[0];
|
||||||
|
let ack = protocol::ArmorReset {
|
||||||
|
acknowledged: true,
|
||||||
|
..request
|
||||||
|
};
|
||||||
|
let report = |index, hp| ArmorReport {
|
||||||
|
board: 1,
|
||||||
|
addr,
|
||||||
|
team: 0,
|
||||||
|
index,
|
||||||
|
hp,
|
||||||
|
};
|
||||||
|
for index in 0..4 {
|
||||||
|
reset.observe(&report(index, 100));
|
||||||
|
}
|
||||||
|
assert_eq!(reset.waiting(), [1, 2], "满血本身不能冒充复位回执");
|
||||||
|
reset.acknowledge(ack, boards[1].addr);
|
||||||
|
reset.acknowledge(protocol::ArmorReset { session: 2, ..ack }, addr);
|
||||||
|
reset.acknowledge(protocol::ArmorReset { reset_id: 2, ..ack }, addr);
|
||||||
|
reset.acknowledge(
|
||||||
|
protocol::ArmorReset {
|
||||||
|
sequence: state.sequence + 1,
|
||||||
|
..ack
|
||||||
|
},
|
||||||
|
addr,
|
||||||
|
);
|
||||||
|
assert_eq!(reset.packets(&state).len(), 2);
|
||||||
|
reset.acknowledge(ack, addr);
|
||||||
|
for index in 0..3 {
|
||||||
|
reset.observe(&report(index, 100));
|
||||||
|
}
|
||||||
|
assert_eq!(reset.waiting(), [1, 2]);
|
||||||
|
reset.observe(&report(3, 0));
|
||||||
|
reset.observe(&report(3, 100));
|
||||||
|
assert_eq!(reset.waiting(), [1, 2], "非满血读数会清除这一轮确认");
|
||||||
|
for index in 0..3 {
|
||||||
|
reset.observe(&report(index, 100));
|
||||||
|
}
|
||||||
|
assert_eq!(reset.waiting(), [2], "一块完成不能掩盖另一块失败");
|
||||||
|
assert_eq!(reset.packets(&state).len(), 1, "已回执的主板不再补血");
|
||||||
|
assert!(ArmorResetTracker::new(&state, [Some(1), Some(1)], &boards).is_err());
|
||||||
|
let mut offline = board(1);
|
||||||
|
offline.last_seen -= Duration::from_secs(2);
|
||||||
|
assert!(ArmorResetTracker::new(&state, [Some(1), None], &[offline]).is_err());
|
||||||
|
clock.action(MatchAction::Reset, 0).unwrap();
|
||||||
|
assert!(reset.packets(&clock.broadcast(0).unwrap()).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn udp_reset_retries_lost_request_and_waits_for_real_ack_and_health() {
|
||||||
|
let client = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||||
|
let board = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||||
|
client
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||||
|
.unwrap();
|
||||||
|
board
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||||
|
.unwrap();
|
||||||
|
let store = ArmorHealthStore::new();
|
||||||
|
store.datagram(
|
||||||
|
&protocol::ArmorHealth {
|
||||||
|
team: 0,
|
||||||
|
index: 0,
|
||||||
|
hp: 0,
|
||||||
|
}
|
||||||
|
.encode_from(17),
|
||||||
|
board.local_addr().unwrap(),
|
||||||
|
);
|
||||||
|
let mut clock = MatchClock::new(true, 88, 0);
|
||||||
|
let state = clock.begin_reset(true, 0).unwrap();
|
||||||
|
store.begin_reset(&state, [Some(17), None]).unwrap();
|
||||||
|
let mut bytes = [0; 128];
|
||||||
|
// 首次请求丢失;下一次心跳使用新序号及相同 reset_id 重试。
|
||||||
|
store.send_reset_controls(&client, &state).unwrap();
|
||||||
|
let (n, _) = board.recv_from(&mut bytes).unwrap();
|
||||||
|
let dropped = protocol::ArmorReset::decode(&bytes[..n]).unwrap();
|
||||||
|
let later = clock.broadcast(200).unwrap();
|
||||||
|
store
|
||||||
|
.send_damage_controls(&client, &later, [Some(17), None])
|
||||||
|
.unwrap();
|
||||||
|
let (n, _) = board.recv_from(&mut bytes).unwrap();
|
||||||
|
assert!(
|
||||||
|
!protocol::ArmorDamageControl::decode(&bytes[..n])
|
||||||
|
.unwrap()
|
||||||
|
.enabled
|
||||||
|
);
|
||||||
|
store.send_reset_controls(&client, &later).unwrap();
|
||||||
|
let (n, from) = board.recv_from(&mut bytes).unwrap();
|
||||||
|
let request = protocol::ArmorReset::decode(&bytes[..n]).unwrap();
|
||||||
|
assert_eq!(request.reset_id, dropped.reset_id);
|
||||||
|
assert!(request.sequence > dropped.sequence);
|
||||||
|
assert_eq!(store.reset_waiting(), [17]);
|
||||||
|
let ack = protocol::ArmorReset {
|
||||||
|
acknowledged: true,
|
||||||
|
..request
|
||||||
|
}
|
||||||
|
.encode()
|
||||||
|
.unwrap();
|
||||||
|
board.send_to(&ack, from).unwrap();
|
||||||
|
let (n, from) = client.recv_from(&mut bytes).unwrap();
|
||||||
|
store.datagram(&bytes[..n], from);
|
||||||
|
assert_eq!(store.reset_waiting(), [17]);
|
||||||
|
assert_eq!(store.health_of_board(17), Some(0), "回执不能伪造血量");
|
||||||
|
for index in 0..4 {
|
||||||
|
board
|
||||||
|
.send_to(
|
||||||
|
&protocol::ArmorHealth {
|
||||||
|
team: 0,
|
||||||
|
index,
|
||||||
|
hp: 100,
|
||||||
|
}
|
||||||
|
.encode_from(17),
|
||||||
|
client.local_addr().unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let (n, from) = client.recv_from(&mut bytes).unwrap();
|
||||||
|
store.datagram(&bytes[..n], from);
|
||||||
|
}
|
||||||
|
assert!(store.reset_waiting().is_empty());
|
||||||
|
assert_eq!(store.health_of_board(17), Some(100));
|
||||||
|
store.finish_reset();
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
"test:stream": "node --test scripts/test-stream.mjs",
|
"test:stream": "node --test scripts/test-stream.mjs",
|
||||||
"test:latency": "node --test scripts/test-latency-marker.mjs",
|
"test:latency": "node --test scripts/test-latency-marker.mjs",
|
||||||
"test:match": "node --test scripts/test-match-clock.mjs",
|
"test:match": "node --test scripts/test-match-clock.mjs",
|
||||||
|
"test:video": "node --test scripts/test-video-transform.mjs scripts/test-operator-hud.mjs",
|
||||||
"test:maintenance": "node --test scripts/test-maintenance.mjs"
|
"test:maintenance": "node --test scripts/test-maintenance.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -19,12 +19,13 @@ function load(path, overrides) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const format = { teamColor: team => team === 0 ? "red" : "blue", teamName: team => `队伍${team}`, idText: String, firmwareLabel: () => "测试固件" };
|
const format = { teamColor: team => team === 0 ? "red" : "blue", teamName: team => `队伍${team}`, idText: String, firmwareLabel: () => "测试固件" };
|
||||||
|
const icon = { Icon: () => null };
|
||||||
const healthModule = load("../src/components/HealthBar.tsx", { "../lib/format": format });
|
const healthModule = load("../src/components/HealthBar.tsx", { "../lib/format": format });
|
||||||
const videoModule = load("../src/components/VideoSurface.tsx", { "../lib/store": {}, "../lib/reticle": {} });
|
const videoModule = load("../src/components/VideoSurface.tsx", { "../lib/store": {}, "../lib/reticle": {}, "./Icon": icon });
|
||||||
let connected = true;
|
let connected = true;
|
||||||
const matchTime = load("../src/lib/match-time.ts", {});
|
const matchTime = load("../src/lib/match-time.ts", {});
|
||||||
const matchModule = load("../src/components/MatchClock.tsx", {
|
const matchModule = load("../src/components/MatchClock.tsx", {
|
||||||
"./Dialog": {}, "../lib/ipc": {},
|
"./Dialog": {}, "./Icon": icon, "../lib/ipc": {},
|
||||||
"../lib/store": { useAppStore: () => ({ connected }) },
|
"../lib/store": { useAppStore: () => ({ connected }) },
|
||||||
"../lib/match-time": matchTime,
|
"../lib/match-time": matchTime,
|
||||||
});
|
});
|
||||||
@@ -141,3 +142,35 @@ test("an armor outage alone does not gray the live video", () => {
|
|||||||
value.armorBoards[0].online = false;
|
value.armorBoards[0].online = false;
|
||||||
assert.doesNotMatch(renderTeam(value), /vsurface--signal-lost|vsurface__signal-mask/);
|
assert.doesNotMatch(renderTeam(value), /vsurface--signal-lost|vsurface__signal-mask/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const renderControl = (phase, health = []) => renderToStaticMarkup(createElement(matchModule.RefereeMatchControl, {
|
||||||
|
snapshot: { ...snapshot(), config: { teamNames: ["红队", "蓝队"] }, matchClock: { ...snapshot().matchClock, phase }, health },
|
||||||
|
onError() {},
|
||||||
|
}));
|
||||||
|
|
||||||
|
test("skip preparation is available only while preparing and ready still requires confirmation", () => {
|
||||||
|
assert.match(renderControl("preparation"), /跳过准备倒计时/);
|
||||||
|
for (const phase of ["idle", "ready", "countdown", "running", "paused", "finished"]) {
|
||||||
|
assert.doesNotMatch(renderControl(phase), /跳过准备倒计时/);
|
||||||
|
}
|
||||||
|
assert.match(renderControl("ready"), /确认开赛/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a verdict exposes one-click reset even before the clock finishes, while ongoing play cannot reset", () => {
|
||||||
|
assert.doesNotMatch(renderControl("running"), /重置到未开始/);
|
||||||
|
assert.match(renderControl("finished"), /重置到未开始/);
|
||||||
|
const verdict = renderControl("running", [{ outcome: "defeat" }, { outcome: "victory" }]);
|
||||||
|
assert.match(verdict, /重置到未开始/);
|
||||||
|
assert.doesNotMatch(verdict, /开始 3 分钟准备|结束本局/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the operator feed reports horizontal and vertical mirroring independently", () => {
|
||||||
|
const value = snapshot();
|
||||||
|
value.mirrored = true;
|
||||||
|
assert.match(renderTeam(value), /左右镜像/);
|
||||||
|
assert.doesNotMatch(renderTeam(value), /上下镜像/);
|
||||||
|
value.mirrored = false;
|
||||||
|
value.mirroredVertical = true;
|
||||||
|
assert.match(renderTeam(value), /上下镜像/);
|
||||||
|
assert.doesNotMatch(renderTeam(value), /左右镜像/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import ts from "typescript";
|
||||||
|
|
||||||
|
const exports = {};
|
||||||
|
new Function("exports", ts.transpileModule(readFileSync(new URL("../src/lib/reticle.ts", import.meta.url), "utf8"), {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||||
|
}).outputText)(exports);
|
||||||
|
const { aimPoint, computeLayout } = exports;
|
||||||
|
|
||||||
|
test("calibrated aim follows the same image point through all four mirror combinations", () => {
|
||||||
|
const geometry = computeLayout({ clientWidth: 800, clientHeight: 600 }, 640, 480, { zoom: 2, x: 40, y: -30 });
|
||||||
|
const crosshair = { offsetX: 0.1, offsetY: -0.2 };
|
||||||
|
for (const horizontal of [false, true]) {
|
||||||
|
for (const vertical of [false, true]) {
|
||||||
|
const aim = aimPoint(geometry, crosshair, horizontal, 800, 600, vertical);
|
||||||
|
assert.equal(aim.x, horizontal ? 200 : 600);
|
||||||
|
assert.equal(aim.y, vertical ? 570 : 30);
|
||||||
|
// 校准时向右下拖动 16/12 像素,镜像不改变屏幕上的移动方向。
|
||||||
|
const moved = aimPoint(geometry, {
|
||||||
|
offsetX: crosshair.offsetX + (horizontal ? -16 : 16) / geometry.drawWidth,
|
||||||
|
offsetY: crosshair.offsetY + (vertical ? -12 : 12) / geometry.drawHeight,
|
||||||
|
}, horizontal, 800, 600, vertical);
|
||||||
|
assert.ok(Math.abs(moved.x - aim.x - 16) < 1e-9);
|
||||||
|
assert.ok(Math.abs(moved.y - aim.y - 12) < 1e-9);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("missing frames keep the aim centered regardless of mirror or offsets", () => {
|
||||||
|
const empty = computeLayout({ clientWidth: 800, clientHeight: 600 }, 0, 0, { zoom: 2, x: 40, y: -30 });
|
||||||
|
assert.deepEqual(aimPoint(empty, { offsetX: 0.2, offsetY: -0.1 }, true, 800, 600, true), { x: 400, y: 300 });
|
||||||
|
});
|
||||||
@@ -34,8 +34,15 @@ const FALLBACK_INPUT_FPS: f32 = 20.0;
|
|||||||
type Shared<'a> = State<'a, Arc<AppState>>;
|
type Shared<'a> = State<'a, Arc<AppState>>;
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn match_action(state: Shared<'_>, action: cam_core::match_clock::MatchAction) -> Result<(), String> {
|
pub async fn match_action(
|
||||||
|
state: Shared<'_>,
|
||||||
|
action: cam_core::match_clock::MatchAction,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if matches!(action, cam_core::match_clock::MatchAction::Reset) {
|
||||||
|
state.reset_match().await
|
||||||
|
} else {
|
||||||
state.match_action(action)
|
state.match_action(action)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -208,6 +215,16 @@ pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result<ConfigView, String>
|
|||||||
Ok(ConfigView::from(&state.config()))
|
Ok(ConfigView::from(&state.config()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 上下镜像,独立保存,不改动左右镜像。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn set_mirror_vertical(mirror_vertical: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||||
|
state
|
||||||
|
.update_config(move |config| config.mirror_vertical = mirror_vertical)
|
||||||
|
.map_err(|err| format!("{err}"))?;
|
||||||
|
|
||||||
|
Ok(ConfigView::from(&state.config()))
|
||||||
|
}
|
||||||
|
|
||||||
/// 保存 HUD 设置(血条、瞄准器、网格、命中反馈)。
|
/// 保存 HUD 设置(血条、瞄准器、网格、命中反馈)。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn save_hud(hud: HudConfig, state: Shared<'_>) -> Result<ConfigView, String> {
|
pub fn save_hud(hud: HudConfig, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||||
|
|||||||
@@ -122,21 +122,35 @@ fn spawn_armor(state: Arc<AppState>) {
|
|||||||
let mut ticks = [0u32, 7];
|
let mut ticks = [0u32, 7];
|
||||||
let mut hits = [0usize, 1];
|
let mut hits = [0usize, 1];
|
||||||
let mut dead_for = [0u32, 0];
|
let mut dead_for = [0u32, 0];
|
||||||
|
let mut reset_epoch = 0;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
let epoch = state
|
||||||
|
.demo_reset_epoch
|
||||||
|
.load(std::sync::atomic::Ordering::Acquire);
|
||||||
|
if epoch != reset_epoch {
|
||||||
|
reset_epoch = epoch;
|
||||||
|
hp = [100; 2];
|
||||||
|
ticks = [0, 7];
|
||||||
|
hits = [0, 1];
|
||||||
|
dead_for = [0; 2];
|
||||||
|
}
|
||||||
|
let scripted = reset_epoch == 0 || state.demo_damage_enabled();
|
||||||
for (slot, (board, team, port)) in boards.iter().enumerate() {
|
for (slot, (board, team, port)) in boards.iter().enumerate() {
|
||||||
|
if scripted {
|
||||||
ticks[slot] += 1;
|
ticks[slot] += 1;
|
||||||
|
}
|
||||||
|
|
||||||
if hp[slot] == 0 {
|
if hp[slot] == 0 {
|
||||||
// 打空之后停一会儿再重置:让界面上的胜负横幅真的能被看到。
|
// 打空之后停一会儿再重置:让界面上的胜负横幅真的能被看到。
|
||||||
dead_for[slot] += 1;
|
dead_for[slot] += 1;
|
||||||
if dead_for[slot] >= 10 {
|
if reset_epoch == 0 && dead_for[slot] >= 10 {
|
||||||
hp[slot] = 100;
|
hp[slot] = 100;
|
||||||
dead_for[slot] = 0;
|
dead_for[slot] = 0;
|
||||||
ticks[slot] = 0;
|
ticks[slot] = 0;
|
||||||
log::info!("demo: 0x{board:08X} 重置为满血(长按 BOOT 的等价动作)");
|
log::info!("demo: 0x{board:08X} 重置为满血(长按 BOOT 的等价动作)");
|
||||||
}
|
}
|
||||||
} else if ticks[slot] % 15 == 0 {
|
} else if scripted && ticks[slot] % 15 == 0 {
|
||||||
// 约 3 秒一次。
|
// 约 3 秒一次。
|
||||||
let damage = DAMAGE_CYCLE[hits[slot] % DAMAGE_CYCLE.len()];
|
let damage = DAMAGE_CYCLE[hits[slot] % DAMAGE_CYCLE.len()];
|
||||||
hits[slot] += 1;
|
hits[slot] += 1;
|
||||||
|
|||||||
@@ -342,6 +342,7 @@ fn run() -> Result<(), Box<dyn Error>> {
|
|||||||
commands::set_team,
|
commands::set_team,
|
||||||
commands::set_role,
|
commands::set_role,
|
||||||
commands::set_mirror,
|
commands::set_mirror,
|
||||||
|
commands::set_mirror_vertical,
|
||||||
commands::save_hud,
|
commands::save_hud,
|
||||||
commands::set_team_name,
|
commands::set_team_name,
|
||||||
commands::set_referee_slots,
|
commands::set_referee_slots,
|
||||||
|
|||||||
@@ -59,6 +59,8 @@ pub struct AppState {
|
|||||||
match_clock: Mutex<MatchClock>,
|
match_clock: Mutex<MatchClock>,
|
||||||
match_socket: Option<std::net::UdpSocket>,
|
match_socket: Option<std::net::UdpSocket>,
|
||||||
match_error: Mutex<Option<String>>,
|
match_error: Mutex<Option<String>>,
|
||||||
|
resetting: AtomicBool,
|
||||||
|
pub demo_reset_epoch: AtomicUsize,
|
||||||
discovery: Arc<Discovery>,
|
discovery: Arc<Discovery>,
|
||||||
latest: Arc<LatestFrames>,
|
latest: Arc<LatestFrames>,
|
||||||
|
|
||||||
@@ -88,11 +90,18 @@ impl AppState {
|
|||||||
self.started.elapsed().as_millis().min(u64::MAX as u128) as u64
|
self.started.elapsed().as_millis().min(u64::MAX as u128) as u64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn demo_damage_enabled(&self) -> bool {
|
||||||
|
self.match_view().phase == "running"
|
||||||
|
}
|
||||||
|
|
||||||
pub fn match_action(&self, action: MatchAction) -> Result<(), String> {
|
pub fn match_action(&self, action: MatchAction) -> Result<(), String> {
|
||||||
// 闸门留在后端,选手端不能通过 IPC 修改权威计时。
|
// 闸门留在后端,选手端不能通过 IPC 修改权威计时。
|
||||||
if self.config().role != Role::Referee {
|
if self.config().role != Role::Referee {
|
||||||
return Err("只有裁判端可以控制比赛计时".into());
|
return Err("只有裁判端可以控制比赛计时".into());
|
||||||
}
|
}
|
||||||
|
if self.resetting.load(Ordering::Acquire) {
|
||||||
|
return Err("正在重置本局,请等待装甲板确认".into());
|
||||||
|
}
|
||||||
self.match_clock
|
self.match_clock
|
||||||
.lock()
|
.lock()
|
||||||
.expect("match clock poisoned")
|
.expect("match clock poisoned")
|
||||||
@@ -102,6 +111,89 @@ impl AppState {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn reset_match(&self) -> Result<(), String> {
|
||||||
|
if self.config().role != Role::Referee {
|
||||||
|
return Err("只有裁判端可以重置比赛".into());
|
||||||
|
}
|
||||||
|
self.resetting
|
||||||
|
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||||
|
.map_err(|_| "正在重置本局,请等待装甲板确认".to_string())?;
|
||||||
|
let _guard = MatchResetGuard {
|
||||||
|
busy: &self.resetting,
|
||||||
|
armor: &self.armor,
|
||||||
|
};
|
||||||
|
let config = self.config();
|
||||||
|
let health = [self.health_for(0), self.health_for(1)];
|
||||||
|
let participants = [
|
||||||
|
self.assigned_armor(&config, 0),
|
||||||
|
self.assigned_armor(&config, 1),
|
||||||
|
];
|
||||||
|
if !self.demo
|
||||||
|
&& health
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.any(|(team, health)| health.available && participants[team].is_none())
|
||||||
|
{
|
||||||
|
return Err("有血量上报但未分配对应装甲板,请先检查两队装甲板槽位再重置".into());
|
||||||
|
}
|
||||||
|
let has_outcome = health
|
||||||
|
.iter()
|
||||||
|
.any(|health| health.available && health.hp == Some(0));
|
||||||
|
let packet = self
|
||||||
|
.match_clock
|
||||||
|
.lock()
|
||||||
|
.expect("match clock poisoned")
|
||||||
|
.begin_reset(has_outcome, self.match_now())?;
|
||||||
|
self.tick_match();
|
||||||
|
self.push_snapshot();
|
||||||
|
|
||||||
|
if self.demo {
|
||||||
|
self.demo_reset_epoch.fetch_add(1, Ordering::Release);
|
||||||
|
for (board, team) in [(DEMO_ARMOR_A, 0), (DEMO_ARMOR_B, 1)] {
|
||||||
|
for index in 0..4 {
|
||||||
|
let report = protocol::ArmorHealth {
|
||||||
|
team,
|
||||||
|
index,
|
||||||
|
hp: 100,
|
||||||
|
}
|
||||||
|
.encode_from(board);
|
||||||
|
self.armor
|
||||||
|
.datagram(&report, "127.0.0.1:5601".parse().unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if self.match_socket.is_none() {
|
||||||
|
return Err("装甲板控制通道不可用,请检查 UDP 5601 后重启客户端".into());
|
||||||
|
}
|
||||||
|
self.armor.begin_reset(&packet, participants)?;
|
||||||
|
self.tick_match();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(3);
|
||||||
|
loop {
|
||||||
|
let waiting = self.armor.reset_waiting();
|
||||||
|
if waiting.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
let ids = waiting
|
||||||
|
.iter()
|
||||||
|
.map(|id| format!("0x{id:08X}"))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("、");
|
||||||
|
return Err(format!("装甲板 {ids} 未确认复位或未上报四路满血;本局保持结束。请检查连接并更新装甲板固件后重试,也可长按 BOOT 复位"));
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.armor.finish_reset();
|
||||||
|
self.match_clock
|
||||||
|
.lock()
|
||||||
|
.expect("match clock poisoned")
|
||||||
|
.action(MatchAction::Reset, self.match_now())?;
|
||||||
|
self.tick_match();
|
||||||
|
self.push_snapshot();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn release_match_source(&self) -> Result<(), String> {
|
pub fn release_match_source(&self) -> Result<(), String> {
|
||||||
self.match_clock
|
self.match_clock
|
||||||
.lock()
|
.lock()
|
||||||
@@ -219,6 +311,8 @@ impl AppState {
|
|||||||
match_clock: Mutex::new(MatchClock::new(role == Role::Referee, session, 0)),
|
match_clock: Mutex::new(MatchClock::new(role == Role::Referee, session, 0)),
|
||||||
match_socket,
|
match_socket,
|
||||||
match_error: Mutex::new(match_error),
|
match_error: Mutex::new(match_error),
|
||||||
|
resetting: AtomicBool::new(false),
|
||||||
|
demo_reset_epoch: AtomicUsize::new(0),
|
||||||
discovery,
|
discovery,
|
||||||
latest,
|
latest,
|
||||||
fps: Mutex::new(HashMap::new()),
|
fps: Mutex::new(HashMap::new()),
|
||||||
@@ -349,6 +443,9 @@ impl AppState {
|
|||||||
|
|
||||||
/// 改配置、落盘、重新套用闸门。
|
/// 改配置、落盘、重新套用闸门。
|
||||||
pub fn update_config(&self, change: impl FnOnce(&mut Config)) -> Result<Config> {
|
pub fn update_config(&self, change: impl FnOnce(&mut Config)) -> Result<Config> {
|
||||||
|
if self.resetting.load(Ordering::Acquire) {
|
||||||
|
anyhow::bail!("正在重置本局,请等待装甲板确认后修改配置");
|
||||||
|
}
|
||||||
let updated = {
|
let updated = {
|
||||||
let mut config = self.config.lock().expect("config mutex poisoned");
|
let mut config = self.config.lock().expect("config mutex poisoned");
|
||||||
change(&mut config);
|
change(&mut config);
|
||||||
@@ -569,8 +666,10 @@ impl AppState {
|
|||||||
.armor
|
.armor
|
||||||
.send_damage_controls(socket, &packet, participants)
|
.send_damage_controls(socket, &packet, participants)
|
||||||
.err();
|
.err();
|
||||||
|
let reset_error = self.armor.send_reset_controls(socket, &packet).err();
|
||||||
let error = sync_error
|
let error = sync_error
|
||||||
.or(damage_error)
|
.or(damage_error)
|
||||||
|
.or(reset_error)
|
||||||
.map(|err| format!("比赛状态发送失败:{err}。请检查网络和防火墙"));
|
.map(|err| format!("比赛状态发送失败:{err}。请检查网络和防火墙"));
|
||||||
*self.match_error.lock().expect("match error poisoned") = error;
|
*self.match_error.lock().expect("match error poisoned") = error;
|
||||||
}
|
}
|
||||||
@@ -690,6 +789,7 @@ impl AppState {
|
|||||||
role: config.role,
|
role: config.role,
|
||||||
team: config.team,
|
team: config.team,
|
||||||
mirrored: config.mirror,
|
mirrored: config.mirror,
|
||||||
|
mirrored_vertical: config.mirror_vertical,
|
||||||
demo: self.demo,
|
demo: self.demo,
|
||||||
diagnostics,
|
diagnostics,
|
||||||
unlocked: self.is_unlocked(),
|
unlocked: self.is_unlocked(),
|
||||||
@@ -781,3 +881,15 @@ pub const DEMO_CAMERA_A: u32 = 0x0DE0_0001;
|
|||||||
pub const DEMO_CAMERA_B: u32 = 0x0DE0_0002;
|
pub const DEMO_CAMERA_B: u32 = 0x0DE0_0002;
|
||||||
pub const DEMO_ARMOR_A: u32 = 0x0A20_0001;
|
pub const DEMO_ARMOR_A: u32 = 0x0A20_0001;
|
||||||
pub const DEMO_ARMOR_B: u32 = 0x0A20_0002;
|
pub const DEMO_ARMOR_B: u32 = 0x0A20_0002;
|
||||||
|
|
||||||
|
struct MatchResetGuard<'a> {
|
||||||
|
busy: &'a AtomicBool,
|
||||||
|
armor: &'a ArmorHealthStore,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for MatchResetGuard<'_> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.armor.finish_reset();
|
||||||
|
self.busy.store(false, Ordering::Release);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
* # 它一直显示到血量被重置
|
* # 它一直显示到血量被重置
|
||||||
*
|
*
|
||||||
* 不做 3 秒淡出:淡出之后屏幕上就再没有"这局结束了"的痕迹,截图、回放、现场的争议都
|
* 不做 3 秒淡出:淡出之后屏幕上就再没有"这局结束了"的痕迹,截图、回放、现场的争议都
|
||||||
* 无从对照。血量被重置(长按 BOOT / 下一局开始)时它自己消失——那个动作本来就是
|
* 无从对照。血量复位(长按 BOOT / 裁判端重置到未开始)时横幅消失——这个动作表示
|
||||||
* "这局翻篇了"。
|
* "这局翻篇了"。
|
||||||
*
|
*
|
||||||
* # 为什么要加电影黑边
|
* # 为什么要加电影黑边
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ export function RefereeMatchControl({ snapshot, onError }: { snapshot: Snapshot;
|
|||||||
const [approved, setApproved] = useState(false);
|
const [approved, setApproved] = useState(false);
|
||||||
const [seconds, setSeconds] = useState(5);
|
const [seconds, setSeconds] = useState(5);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
const canReset = clock.phase === "finished" || snapshot.health.some(health => health.outcome != null);
|
||||||
const active = ["preparation", "ready", "countdown", "running"].includes(clock.phase);
|
const active = ["preparation", "ready", "countdown", "running"].includes(clock.phase);
|
||||||
const run = async (action: MatchAction, close?: () => void) => {
|
const run = async (action: MatchAction, close?: () => void) => {
|
||||||
if (busy) return;
|
if (busy) return;
|
||||||
@@ -97,8 +98,21 @@ export function RefereeMatchControl({ snapshot, onError }: { snapshot: Snapshot;
|
|||||||
<div className="match-control__identity"><span className="label">MATCH CONTROL</span><span>{snapshot.demo ? "本机演示 · 合成计时" : "裁判计时 / 局域网同步"}</span>{!snapshot.demo && <small className={snapshot.matchClock.syncError ? "is-error" : ""}>{snapshot.matchClock.syncError ?? "仅对局进行中扣血;准备与暂停时只闪灯"}</small>}</div>
|
<div className="match-control__identity"><span className="label">MATCH CONTROL</span><span>{snapshot.demo ? "本机演示 · 合成计时" : "裁判计时 / 局域网同步"}</span>{!snapshot.demo && <small className={snapshot.matchClock.syncError ? "is-error" : ""}>{snapshot.matchClock.syncError ?? "仅对局进行中扣血;准备与暂停时只闪灯"}</small>}</div>
|
||||||
<Readout clock={clock} names={snapshot.config.teamNames} />
|
<Readout clock={clock} names={snapshot.config.teamNames} />
|
||||||
<div className="match-control__actions">
|
<div className="match-control__actions">
|
||||||
{clock.phase === "idle" || clock.phase === "finished" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "prepare" })}><Icon name="timer" />开始 3 分钟准备</button> : clock.phase === "ready" ? <div className="match-control__start"><label>开赛倒计时 <input aria-label="开赛倒计时秒数" type="number" min="1" max="60" step="1" value={seconds} onChange={e => setSeconds(Number(e.target.value))} /> 秒</label><button className="btn btn--primary" disabled={busy || !Number.isInteger(seconds) || seconds < 1 || seconds > 60} onClick={() => void run({ type: "countdown", seconds })}><Icon name="play" />确认开赛</button></div> : clock.phase === "paused" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "resume" })}><Icon name="play" />恢复{clock.resumePhase === "preparation" ? "准备" : clock.resumePhase === "ready" ? "待开赛阶段" : clock.resumePhase === "countdown" ? "倒计时" : "对局"}</button> : <span className="match-control__hint">{clock.phase === "preparation" ? "准备结束后等待裁判确认开赛" : clock.phase === "countdown" ? "请选手就位" : "计时到零结束本局"}</span>}
|
{canReset ? <>
|
||||||
<div className="match-control__buttons"><button className="btn" disabled={busy || !active} onClick={() => openPause("player")}><Icon name="pause" />选手暂停</button><button className="btn" disabled={busy || !active} onClick={() => openPause("official")}><Icon name="pause" />官方暂停</button>{active || clock.phase === "paused" ? <button className="btn btn--quiet" disabled={busy} onClick={() => setDialog("end")}><Icon name="stop" />结束本局</button> : clock.phase === "finished" && <button className="btn btn--quiet" disabled={busy} onClick={() => void run({ type: "reset" })}><Icon name="reset" />清除计时</button>}</div>
|
<span className="match-control__hint">{busy ? "等待装甲板回执与满血上报" : "重置后恢复满血,保留设备槽位和设置"}</span>
|
||||||
|
<button className="btn btn--primary" disabled={busy} title="恢复装甲板满血,清除本局计时和结果,保留设备槽位与设置" onClick={() => void run({ type: "reset" })}><Icon name="reset" />{busy ? "正在重置本局…" : "重置到未开始"}</button>
|
||||||
|
</> : <>
|
||||||
|
{clock.phase === "idle" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "prepare" })}><Icon name="timer" />开始 3 分钟准备</button>
|
||||||
|
: clock.phase === "preparation" ? <button className="btn" disabled={busy} title="结束准备,进入等待裁判确认开赛" onClick={() => void run({ type: "skipPreparation" })}><Icon name="play" />跳过准备倒计时</button>
|
||||||
|
: clock.phase === "ready" ? <div className="match-control__start"><label>开赛倒计时 <input aria-label="开赛倒计时秒数" type="number" min="1" max="60" step="1" value={seconds} onChange={e => setSeconds(Number(e.target.value))} /> 秒</label><button className="btn btn--primary" disabled={busy || !Number.isInteger(seconds) || seconds < 1 || seconds > 60} onClick={() => void run({ type: "countdown", seconds })}><Icon name="play" />确认开赛</button></div>
|
||||||
|
: clock.phase === "paused" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "resume" })}><Icon name="play" />恢复{clock.resumePhase === "preparation" ? "准备" : clock.resumePhase === "ready" ? "待开赛阶段" : clock.resumePhase === "countdown" ? "倒计时" : "对局"}</button>
|
||||||
|
: <span className="match-control__hint">{clock.phase === "countdown" ? "请选手就位" : "计时到零结束本局"}</span>}
|
||||||
|
<div className="match-control__buttons">
|
||||||
|
<button className="btn" disabled={busy || !active} onClick={() => openPause("player")}><Icon name="pause" />选手暂停</button>
|
||||||
|
<button className="btn" disabled={busy || !active} onClick={() => openPause("official")}><Icon name="pause" />官方暂停</button>
|
||||||
|
{(active || clock.phase === "paused") && <button className="btn btn--quiet" disabled={busy} onClick={() => setDialog("end")}><Icon name="stop" />结束本局</button>}
|
||||||
|
</div>
|
||||||
|
</>}
|
||||||
</div>
|
</div>
|
||||||
{dialog && <Dialog title={dialog === "end" ? "结束本局计时" : dialog === "player" ? "选手技术暂停" : "官方技术暂停"} closeDisabled={busy} onClose={() => setDialog(null)} className="match-dialog">
|
{dialog && <Dialog title={dialog === "end" ? "结束本局计时" : dialog === "player" ? "选手技术暂停" : "官方技术暂停"} closeDisabled={busy} onClose={() => setDialog(null)} className="match-dialog">
|
||||||
{close => <div className="match-dialog__body">{dialog === "end" ? <><p>结束当前计时并同步到选手端,同时停止装甲板扣血。比赛结果由裁判判定。</p><button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "end" }, close)}><Icon name="stop" />确认结束本局</button></> : <>
|
{close => <div className="match-dialog__body">{dialog === "end" ? <><p>结束当前计时并同步到选手端,同时停止装甲板扣血。比赛结果由裁判判定。</p><button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "end" }, close)}><Icon name="stop" />确认结束本局</button></> : <>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent }
|
|||||||
import { api } from "../lib/ipc";
|
import { api } from "../lib/ipc";
|
||||||
import { BUILD, VERSION_LABEL } from "../lib/version";
|
import { BUILD, VERSION_LABEL } from "../lib/version";
|
||||||
import { firmwareLabel, teamName } from "../lib/format";
|
import { firmwareLabel, teamName } from "../lib/format";
|
||||||
import { paintCrosshair, paintGrid, type Geometry } from "../lib/reticle";
|
import { aimPoint, paintCrosshair, paintGrid, type Geometry } from "../lib/reticle";
|
||||||
import type { ConfigView, CrosshairConfig, HudView, Snapshot, TeamHealthDto } from "../lib/types";
|
import type { ConfigView, CrosshairConfig, HudView, Snapshot, TeamHealthDto } from "../lib/types";
|
||||||
import { Button, Field, Select, Slider, Switch } from "./controls";
|
import { Button, Field, Select, Slider, Switch } from "./controls";
|
||||||
import { HealthBar } from "./HealthBar";
|
import { HealthBar } from "./HealthBar";
|
||||||
@@ -156,6 +156,10 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
|||||||
const board = snapshot.armorBoards.find(item => item.id === config.armorId);
|
const board = snapshot.armorBoards.find(item => item.id === config.armorId);
|
||||||
const cameraState = !connected ? "本地通道断开" : config.cameraId === null ? "未绑定" : !camera?.online ? "离线" : !camera.compatible ? "协议不匹配" : cameraStats?.online && cameraStats.hasFrames ? "正在接收" : "已发现 · 等待画面";
|
const cameraState = !connected ? "本地通道断开" : config.cameraId === null ? "未绑定" : !camera?.online ? "离线" : !camera.compatible ? "协议不匹配" : cameraStats?.online && cameraStats.hasFrames ? "正在接收" : "已发现 · 等待画面";
|
||||||
const armorState = !connected ? "本地通道断开" : config.armorId === null ? "未绑定" : !board?.online ? "离线" : board.team === 255 ? "等待队伍设置" : board.team !== config.team ? "队伍不匹配" : "在线";
|
const armorState = !connected ? "本地通道断开" : config.armorId === null ? "未绑定" : !board?.online ? "离线" : board.team === 255 ? "等待队伍设置" : board.team !== config.team ? "队伍不匹配" : "在线";
|
||||||
|
const mirrorControls = <>
|
||||||
|
<Switch checked={config.mirror} label="左右镜像画面" onChange={mirror => void run(() => api.setMirror(mirror))} />
|
||||||
|
<Switch checked={config.mirrorVertical} label="上下镜像画面" onChange={mirror => void run(() => api.setMirrorVertical(mirror))} />
|
||||||
|
</>;
|
||||||
|
|
||||||
const content = () => {
|
const content = () => {
|
||||||
switch (current.id) {
|
switch (current.id) {
|
||||||
@@ -185,7 +189,7 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
|||||||
{ value: 1, label: `${teamName(1, config.teamNames)}(蓝)` },
|
{ value: 1, label: `${teamName(1, config.teamNames)}(蓝)` },
|
||||||
]} onChange={team => void run(() => api.setTeam(team))} />
|
]} onChange={team => void run(() => api.setTeam(team))} />
|
||||||
</Field>
|
</Field>
|
||||||
<Switch checked={config.mirror} label="左右镜像画面" onChange={mirror => void run(() => api.setMirror(mirror))} />
|
{mirrorControls}
|
||||||
<div className="settings__device-state settings__span" aria-live="polite">
|
<div className="settings__device-state settings__span" aria-live="polite">
|
||||||
<span><b>图传</b><strong>{config.cameraIdText ?? "—"}</strong><em>{cameraState}</em></span>
|
<span><b>图传</b><strong>{config.cameraIdText ?? "—"}</strong><em>{cameraState}</em></span>
|
||||||
<span><b>装甲板</b><strong>{config.armorIdText ?? "—"}</strong><em>{armorState}</em></span>
|
<span><b>装甲板</b><strong>{config.armorIdText ?? "—"}</strong><em>{armorState}</em></span>
|
||||||
@@ -228,6 +232,7 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
|||||||
{snapshot.diagnostics && <Switch checked={hud.showStats} label="显示丢包率(诊断模式)" onChange={showStats => update(draft => { draft.showStats = showStats; })} />}
|
{snapshot.diagnostics && <Switch checked={hud.showStats} label="显示丢包率(诊断模式)" onChange={showStats => update(draft => { draft.showStats = showStats; })} />}
|
||||||
</>;
|
</>;
|
||||||
case "slots": return <>
|
case "slots": return <>
|
||||||
|
{mirrorControls}
|
||||||
<div className="settings__span"><Switch checked={snapshot.slots.manual} label="手动指定槽位" onChange={manual => void run(() => api.setRefereeSlots({ ...snapshot.slots, manual }))} /></div>
|
<div className="settings__span"><Switch checked={snapshot.slots.manual} label="手动指定槽位" onChange={manual => void run(() => api.setRefereeSlots({ ...snapshot.slots, manual }))} /></div>
|
||||||
<Field label={`左格 · ${teamName(0, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraA} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraA => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraA, manual: true }))} /></Field>
|
<Field label={`左格 · ${teamName(0, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraA} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraA => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraA, manual: true }))} /></Field>
|
||||||
<Field label={`右格 · ${teamName(1, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraB} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraB => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraB, manual: true }))} /></Field>
|
<Field label={`右格 · ${teamName(1, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraB} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraB => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraB, manual: true }))} /></Field>
|
||||||
@@ -288,7 +293,7 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
|||||||
<div className="settings__page-head"><span className="label">{current.en}</span><h2>{current.label}</h2><p>{current.hint}</p></div>
|
<div className="settings__page-head"><span className="label">{current.en}</span><h2>{current.label}</h2><p>{current.hint}</p></div>
|
||||||
<div className="settings__workspace">
|
<div className="settings__workspace">
|
||||||
<fieldset className="settings__form" disabled={locked || closing}>{content()}</fieldset>
|
<fieldset className="settings__form" disabled={locked || closing}>{content()}</fieldset>
|
||||||
{current.preview && <Preview hud={hud} team={snapshot.team} />}
|
{current.preview && <Preview hud={hud} team={snapshot.team} mirrored={config.mirror} mirroredVertical={config.mirrorVertical} />}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -307,7 +312,7 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
|||||||
*
|
*
|
||||||
* 血量那根滑杆是刻意加的:低血阈值与脉动只有真的把血拖下去才看得见。
|
* 血量那根滑杆是刻意加的:低血阈值与脉动只有真的把血拖下去才看得见。
|
||||||
*/
|
*/
|
||||||
function Preview({ hud, team }: { hud: HudView; team: number }) {
|
function Preview({ hud, team, mirrored, mirroredVertical }: { hud: HudView; team: number; mirrored: boolean; mirroredVertical: boolean }) {
|
||||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||||
const [demoHp, setDemoHp] = useState(68);
|
const [demoHp, setDemoHp] = useState(68);
|
||||||
|
|
||||||
@@ -329,6 +334,9 @@ function Preview({ hud, team }: { hud: HudView; team: number }) {
|
|||||||
|
|
||||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
ctx.clearRect(0, 0, width, height);
|
ctx.clearRect(0, 0, width, height);
|
||||||
|
ctx.save();
|
||||||
|
ctx.translate(mirrored ? width : 0, mirroredVertical ? height : 0);
|
||||||
|
ctx.scale(mirrored ? -1 : 1, mirroredVertical ? -1 : 1);
|
||||||
|
|
||||||
// 伪画面:一块低饱和的远景色 + 一条地平线。它的作用是让准星与网格有一个"深色背景
|
// 伪画面:一块低饱和的远景色 + 一条地平线。它的作用是让准星与网格有一个"深色背景
|
||||||
// 之上"的参照,而不是浮在一片纯黑里看不出对比。
|
// 之上"的参照,而不是浮在一片纯黑里看不出对比。
|
||||||
@@ -354,12 +362,12 @@ function Preview({ hud, team }: { hud: HudView; team: number }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (hud.grid.visible) paintGrid(ctx, geometry, hud.grid);
|
if (hud.grid.visible) paintGrid(ctx, geometry, hud.grid);
|
||||||
|
ctx.restore();
|
||||||
|
|
||||||
if (hud.crosshair.visible) {
|
if (hud.crosshair.visible) {
|
||||||
// 预览里的偏移按比例缩到这块小画布上,方向与真画面一致。
|
// 预览里的偏移按比例缩到这块小画布上,方向与真画面一致。
|
||||||
const cx = width * (0.5 + hud.crosshair.offsetX);
|
const aim = aimPoint(geometry, hud.crosshair, mirrored, width, height, mirroredVertical);
|
||||||
const cy = height * (0.5 + hud.crosshair.offsetY);
|
paintCrosshair(ctx, aim.x, aim.y, Math.min(width, height), hud.crosshair);
|
||||||
paintCrosshair(ctx, cx, cy, Math.min(width, height), hud.crosshair);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -374,7 +382,7 @@ function Preview({ hud, team }: { hud: HudView; team: number }) {
|
|||||||
cancelAnimationFrame(raf);
|
cancelAnimationFrame(raf);
|
||||||
observer.disconnect();
|
observer.disconnect();
|
||||||
};
|
};
|
||||||
}, [hud]);
|
}, [hud, mirrored, mirroredVertical]);
|
||||||
|
|
||||||
// 预览用的血量。`available` 恒为 true:占位符的形态在真画面上看更清楚。
|
// 预览用的血量。`available` 恒为 true:占位符的形态在真画面上看更清楚。
|
||||||
const mock: TeamHealthDto = {
|
const mock: TeamHealthDto = {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
* - **网格**画在图像矩形里,跟着缩放走:它标的是画面里的比例,用来估距离。
|
* - **网格**画在图像矩形里,跟着缩放走:它标的是画面里的比例,用来估距离。
|
||||||
* - **瞄准器**的**位置**跟着图像走,**大小**不跟着:像真瞄具一样,放大之后准星不会
|
* - **瞄准器**的**位置**跟着图像走,**大小**不跟着:像真瞄具一样,放大之后准星不会
|
||||||
* 跟着变粗,而是覆盖画面里更小的一块——那正是放大有用武之地的原因。
|
* 跟着变粗,而是覆盖画面里更小的一块——那正是放大有用武之地的原因。
|
||||||
* - 镜像靠 `scale(-1, 1)`,同时把拖动方向也翻过来,否则向右拖画面会往左走。
|
* - 左右、上下镜像分别反转对应轴,同时反转拖动输入,让画面跟随鼠标移动。
|
||||||
*
|
*
|
||||||
* # 缩放是"追"上去的,平移是"贴"着手的
|
* # 缩放是"追"上去的,平移是"贴"着手的
|
||||||
*
|
*
|
||||||
@@ -63,6 +63,7 @@ interface Props {
|
|||||||
camera: number | null;
|
camera: number | null;
|
||||||
emptyText: string;
|
emptyText: string;
|
||||||
mirrored: boolean;
|
mirrored: boolean;
|
||||||
|
mirroredVertical?: boolean;
|
||||||
crosshair: CrosshairConfig | null;
|
crosshair: CrosshairConfig | null;
|
||||||
grid: GridConfig | null;
|
grid: GridConfig | null;
|
||||||
view: ViewTransform;
|
view: ViewTransform;
|
||||||
@@ -100,6 +101,7 @@ export function VideoSurface({
|
|||||||
camera,
|
camera,
|
||||||
emptyText,
|
emptyText,
|
||||||
mirrored,
|
mirrored,
|
||||||
|
mirroredVertical = false,
|
||||||
crosshair,
|
crosshair,
|
||||||
grid,
|
grid,
|
||||||
view,
|
view,
|
||||||
@@ -120,8 +122,8 @@ export function VideoSurface({
|
|||||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||||
|
|
||||||
// 绘制循环不随 props 重建,所以最新一份 props 放在 ref 里给它读。
|
// 绘制循环不随 props 重建,所以最新一份 props 放在 ref 里给它读。
|
||||||
const props = useRef({ camera, mirrored, crosshair, grid, view, hit, hitFeedback, onFramePainted });
|
const props = useRef({ camera, mirrored, mirroredVertical, crosshair, grid, view, hit, hitFeedback, onFramePainted });
|
||||||
props.current = { camera, mirrored, crosshair, grid, view, hit, hitFeedback, onFramePainted };
|
props.current = { camera, mirrored, mirroredVertical, crosshair, grid, view, hit, hitFeedback, onFramePainted };
|
||||||
|
|
||||||
/** 屏幕上**当前**的视图。它追着 `view` 走,但有自己的惯性。 */
|
/** 屏幕上**当前**的视图。它追着 `view` 走,但有自己的惯性。 */
|
||||||
const shown = useRef<ViewTransform>({ ...view });
|
const shown = useRef<ViewTransform>({ ...view });
|
||||||
@@ -132,7 +134,7 @@ export function VideoSurface({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dirty.current = true;
|
dirty.current = true;
|
||||||
}, [camera, mirrored, crosshair, grid, view, hit, hitFeedback]);
|
}, [camera, mirrored, mirroredVertical, crosshair, grid, view, hit, hitFeedback]);
|
||||||
|
|
||||||
// canvas 的像素尺寸跟着 CSS 尺寸与 DPR 走。不这么做的话在 Retina 上会糊。
|
// canvas 的像素尺寸跟着 CSS 尺寸与 DPR 走。不这么做的话在 Retina 上会糊。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -261,15 +263,15 @@ export function VideoSurface({
|
|||||||
// 一次移动一小步,然后把起点挪过来。
|
// 一次移动一小步,然后把起点挪过来。
|
||||||
drag.current = { ...start, x: event.clientX, y: event.clientY };
|
drag.current = { ...start, x: event.clientX, y: event.clientY };
|
||||||
const sign = mirrored ? -1 : 1;
|
const sign = mirrored ? -1 : 1;
|
||||||
onCalibrate((sign * dx) / drawWidth, dy / drawHeight);
|
onCalibrate((sign * dx) / drawWidth, ((mirroredVertical ? -1 : 1) * dy) / drawHeight);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (view.zoom <= MIN_ZOOM) return;
|
if (view.zoom <= MIN_ZOOM) return;
|
||||||
|
|
||||||
// 镜像时把横向拖动也翻过来:否则向右拖,画面往左走,看起来像拖动坏了。
|
// 镜像时反转对应轴的输入,保持画面跟随鼠标移动。
|
||||||
const sign = mirrored ? -1 : 1;
|
const sign = mirrored ? -1 : 1;
|
||||||
onView({ ...view, x: start.originX + sign * dx, y: start.originY + dy });
|
onView({ ...view, x: start.originX + sign * dx, y: start.originY + (mirroredVertical ? -dy : dy) });
|
||||||
};
|
};
|
||||||
|
|
||||||
const endDrag = () => {
|
const endDrag = () => {
|
||||||
@@ -359,6 +361,7 @@ export function VideoSurface({
|
|||||||
interface CanvasProps {
|
interface CanvasProps {
|
||||||
camera: number | null;
|
camera: number | null;
|
||||||
mirrored: boolean;
|
mirrored: boolean;
|
||||||
|
mirroredVertical: boolean;
|
||||||
crosshair: CrosshairConfig | null;
|
crosshair: CrosshairConfig | null;
|
||||||
grid: GridConfig | null;
|
grid: GridConfig | null;
|
||||||
hit: HitPulse | null;
|
hit: HitPulse | null;
|
||||||
@@ -392,21 +395,18 @@ function draw(
|
|||||||
if (frame) {
|
if (frame) {
|
||||||
ctx.save();
|
ctx.save();
|
||||||
|
|
||||||
if (current.mirrored) {
|
ctx.translate(current.mirrored ? width : 0, current.mirroredVertical ? height : 0);
|
||||||
ctx.translate(width, 0);
|
ctx.scale(current.mirrored ? -1 : 1, current.mirroredVertical ? -1 : 1);
|
||||||
ctx.scale(-1, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 放大超过 3 倍时关掉插值:这时候要看的是像素本身,双线性插值只会把它糊掉。
|
// 放大超过 3 倍时关掉插值:这时候要看的是像素本身,双线性插值只会把它糊掉。
|
||||||
ctx.imageSmoothingEnabled = view.zoom < 3;
|
ctx.imageSmoothingEnabled = view.zoom < 3;
|
||||||
ctx.drawImage(frame.bitmap, geometry.left, geometry.top, geometry.drawWidth, geometry.drawHeight);
|
ctx.drawImage(frame.bitmap, geometry.left, geometry.top, geometry.drawWidth, geometry.drawHeight);
|
||||||
ctx.restore();
|
|
||||||
|
|
||||||
if (current.grid?.visible) paintGrid(ctx, geometry, current.grid);
|
if (current.grid?.visible) paintGrid(ctx, geometry, current.grid);
|
||||||
|
ctx.restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
const crosshair = current.crosshair;
|
const crosshair = current.crosshair;
|
||||||
const aim = aimPoint(geometry, crosshair, current.mirrored, width, height);
|
const aim = aimPoint(geometry, crosshair, current.mirrored, width, height, current.mirroredVertical);
|
||||||
|
|
||||||
if (crosshair?.visible) {
|
if (crosshair?.visible) {
|
||||||
paintCrosshair(ctx, aim.x, aim.y, Math.min(width, height), crosshair);
|
paintCrosshair(ctx, aim.x, aim.y, Math.min(width, height), crosshair);
|
||||||
|
|||||||
@@ -113,11 +113,13 @@ interface PreviewState {
|
|||||||
/** 两边显示的名字,与后端配置里的 `teamNames` 对应。 */
|
/** 两边显示的名字,与后端配置里的 `teamNames` 对应。 */
|
||||||
teamNames: [string, string];
|
teamNames: [string, string];
|
||||||
mirror: boolean;
|
mirror: boolean;
|
||||||
|
mirrorVertical: boolean;
|
||||||
unlocked: boolean;
|
unlocked: boolean;
|
||||||
password: string | null;
|
password: string | null;
|
||||||
calibrating: boolean;
|
calibrating: boolean;
|
||||||
recordings: { camera: number; frames: number; startedMs: number }[];
|
recordings: { camera: number; frames: number; startedMs: number }[];
|
||||||
hp: [number, number];
|
hp: [number, number];
|
||||||
|
matchControlled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const state: PreviewState = {
|
const state: PreviewState = {
|
||||||
@@ -128,13 +130,16 @@ const state: PreviewState = {
|
|||||||
team: 0,
|
team: 0,
|
||||||
teamNames: wideLayoutPreview ? ["用户端长队名布局验证一队", "用户端长队名布局验证二队"] : ["队伍一", "队伍二"],
|
teamNames: wideLayoutPreview ? ["用户端长队名布局验证一队", "用户端长队名布局验证二队"] : ["队伍一", "队伍二"],
|
||||||
mirror: true,
|
mirror: true,
|
||||||
|
mirrorVertical: false,
|
||||||
// 预览里直接是已解锁状态,免得每次刷新都要输密码。
|
// 预览里直接是已解锁状态,免得每次刷新都要输密码。
|
||||||
unlocked: false,
|
unlocked: false,
|
||||||
password: "1234",
|
password: "1234",
|
||||||
calibrating: false,
|
calibrating: false,
|
||||||
recordings: [],
|
recordings: [],
|
||||||
hp: [100, 100],
|
hp: [100, 100],
|
||||||
|
matchControlled: new URLSearchParams(location.search).has("match"),
|
||||||
};
|
};
|
||||||
|
if (new URLSearchParams(location.search).get("match") === "finished") state.hp = [0, 76];
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 假的命令实现
|
// 假的命令实现
|
||||||
@@ -148,10 +153,14 @@ export async function previewInvoke<T>(command: string, args?: Record<string, un
|
|||||||
|
|
||||||
function handle(command: string, args: Record<string, unknown>): unknown {
|
function handle(command: string, args: Record<string, unknown>): unknown {
|
||||||
switch (command) {
|
switch (command) {
|
||||||
case "match_action":
|
case "match_action": {
|
||||||
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
|
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
|
||||||
previewMatchAction(args.action as MatchAction);
|
const action = args.action as MatchAction;
|
||||||
|
previewMatchAction(action);
|
||||||
|
state.matchControlled = true;
|
||||||
|
if (action.type === "reset") state.hp = [100, 100];
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
case "release_match_source": return;
|
case "release_match_source": return;
|
||||||
case "stream_info":
|
case "stream_info":
|
||||||
return { url: "preview://", port: 0, clients: 1 };
|
return { url: "preview://", port: 0, clients: 1 };
|
||||||
@@ -201,6 +210,9 @@ function handle(command: string, args: Record<string, unknown>): unknown {
|
|||||||
case "set_mirror":
|
case "set_mirror":
|
||||||
state.mirror = Boolean(args.mirror);
|
state.mirror = Boolean(args.mirror);
|
||||||
return configView();
|
return configView();
|
||||||
|
case "set_mirror_vertical":
|
||||||
|
state.mirrorVertical = Boolean(args.mirrorVertical);
|
||||||
|
return configView();
|
||||||
case "save_hud":
|
case "save_hud":
|
||||||
state.hud = args.hud as HudView;
|
state.hud = args.hud as HudView;
|
||||||
return configView();
|
return configView();
|
||||||
@@ -258,6 +270,7 @@ function configView(): ConfigView {
|
|||||||
armorId: state.armorId,
|
armorId: state.armorId,
|
||||||
armorIdText: state.armorId === null ? null : hex(state.armorId),
|
armorIdText: state.armorId === null ? null : hex(state.armorId),
|
||||||
mirror: state.mirror,
|
mirror: state.mirror,
|
||||||
|
mirrorVertical: state.mirrorVertical,
|
||||||
passwordSet: needsPassword ? false : state.password !== null,
|
passwordSet: needsPassword ? false : state.password !== null,
|
||||||
hud: structuredClone(state.hud),
|
hud: structuredClone(state.hud),
|
||||||
recordingDir: "/预览模式/recordings",
|
recordingDir: "/预览模式/recordings",
|
||||||
@@ -374,6 +387,7 @@ function snapshot(): Snapshot {
|
|||||||
role: state.role,
|
role: state.role,
|
||||||
team: state.team,
|
team: state.team,
|
||||||
mirrored: state.mirror,
|
mirrored: state.mirror,
|
||||||
|
mirroredVertical: state.mirrorVertical,
|
||||||
matchClock: previewMatch(),
|
matchClock: previewMatch(),
|
||||||
demo: true,
|
demo: true,
|
||||||
diagnostics: true,
|
diagnostics: true,
|
||||||
@@ -453,11 +467,12 @@ export function startPreview(client: StreamClient, emit: (msg: WireMsg) => void)
|
|||||||
let tick = 0;
|
let tick = 0;
|
||||||
const hitTimer = window.setInterval(() => {
|
const hitTimer = window.setInterval(() => {
|
||||||
if (offlinePreview) return;
|
if (offlinePreview) return;
|
||||||
|
if (state.matchControlled && previewMatch().phase !== "running") return;
|
||||||
tick += 1;
|
tick += 1;
|
||||||
const team = tick % 2;
|
const team = tick % 2;
|
||||||
|
|
||||||
if (state.hp[team] === 0) {
|
if (state.hp[team] === 0) {
|
||||||
state.hp[team] = 100;
|
if (!state.matchControlled) state.hp[team] = 100;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export const api = {
|
|||||||
setRole: (role: Role, password?: string) =>
|
setRole: (role: Role, password?: string) =>
|
||||||
call<ConfigView>("set_role", { role, password: password ?? null }),
|
call<ConfigView>("set_role", { role, password: password ?? null }),
|
||||||
setMirror: (mirror: boolean) => call<ConfigView>("set_mirror", { mirror }),
|
setMirror: (mirror: boolean) => call<ConfigView>("set_mirror", { mirror }),
|
||||||
|
setMirrorVertical: (mirrorVertical: boolean) => call<ConfigView>("set_mirror_vertical", { mirrorVertical }),
|
||||||
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
|
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
|
||||||
/** 改一边的队名(0 = 队伍一,1 = 队伍二)。一次只改一边,避免覆盖另一边的改动。 */
|
/** 改一边的队名(0 = 队伍一,1 = 队伍二)。一次只改一边,避免覆盖另一边的改动。 */
|
||||||
setTeamName: (team: number, name: string, password?: string) =>
|
setTeamName: (team: number, name: string, password?: string) =>
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ export function previewMatchAction(action: MatchAction) {
|
|||||||
previewMatch();
|
previewMatch();
|
||||||
switch (action.type) {
|
switch (action.type) {
|
||||||
case "prepare": view = { ...blank(), phase: "preparation", remainingMs: 180_000 }; break;
|
case "prepare": view = { ...blank(), phase: "preparation", remainingMs: 180_000 }; break;
|
||||||
|
case "skipPreparation":
|
||||||
|
if (view.phase !== "preparation" && view.phase !== "ready") throw new Error("当前阶段不能跳过准备");
|
||||||
|
view.phase = "ready"; view.remainingMs = 0; break;
|
||||||
case "countdown": view.phase = "countdown"; view.remainingMs = action.seconds * 1000; break;
|
case "countdown": view.phase = "countdown"; view.remainingMs = action.seconds * 1000; break;
|
||||||
case "pausePlayer":
|
case "pausePlayer":
|
||||||
if (!action.approved) throw new Error("选手技术暂停须经主裁判批准");
|
if (!action.approved) throw new Error("选手技术暂停须经主裁判批准");
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ export function computeLayout(
|
|||||||
/**
|
/**
|
||||||
* 瞄准点的屏幕位置。
|
* 瞄准点的屏幕位置。
|
||||||
*
|
*
|
||||||
* 图像坐标系里的 `(0.5 + offsetX, 0.5 + offsetY)` 再换到屏幕。镜像时横向要翻过来,
|
* 图像坐标系里的 `(0.5 + offsetX, 0.5 + offsetY)` 再换到屏幕。镜像时对应轴要翻过来,
|
||||||
* 否则准星会站在画面的另一边——偏移量是相对**摄像头光轴**定的,光轴在镜像之后换了位置。
|
* 否则准星会站在画面的另一边——偏移量是相对**摄像头光轴**定的,光轴在镜像之后换了位置。
|
||||||
*/
|
*/
|
||||||
export function aimPoint(
|
export function aimPoint(
|
||||||
@@ -67,15 +67,17 @@ export function aimPoint(
|
|||||||
mirrored: boolean,
|
mirrored: boolean,
|
||||||
canvasWidth: number,
|
canvasWidth: number,
|
||||||
canvasHeight: number,
|
canvasHeight: number,
|
||||||
|
mirroredVertical = false,
|
||||||
): { x: number; y: number } {
|
): { x: number; y: number } {
|
||||||
if (!crosshair || geometry.drawWidth <= 0) {
|
if (!crosshair || geometry.drawWidth <= 0) {
|
||||||
return { x: canvasWidth / 2, y: canvasHeight / 2 };
|
return { x: canvasWidth / 2, y: canvasHeight / 2 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawX = geometry.left + (0.5 + crosshair.offsetX) * geometry.drawWidth;
|
const rawX = geometry.left + (0.5 + crosshair.offsetX) * geometry.drawWidth;
|
||||||
|
const rawY = geometry.top + (0.5 + crosshair.offsetY) * geometry.drawHeight;
|
||||||
return {
|
return {
|
||||||
x: mirrored ? canvasWidth - rawX : rawX,
|
x: mirrored ? canvasWidth - rawX : rawX,
|
||||||
y: geometry.top + (0.5 + crosshair.offsetY) * geometry.drawHeight,
|
y: mirroredVertical ? canvasHeight - rawY : rawY,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -80,7 +80,9 @@ function handleMessage(msg: WireMsg) {
|
|||||||
return; // Consumed by StreamClient before reaching application state.
|
return; // Consumed by StreamClient before reaching application state.
|
||||||
case "snapshot": {
|
case "snapshot": {
|
||||||
const { t: _tag, ...snapshot } = msg;
|
const { t: _tag, ...snapshot } = msg;
|
||||||
emit({ snapshot: snapshot as Snapshot });
|
const reset = snapshot.matchClock.phase === "idle" && (store.snapshot?.matchClock.phase !== "idle"
|
||||||
|
|| store.snapshot?.health.some(health => health.outcome != null));
|
||||||
|
emit({ snapshot: snapshot as Snapshot, ...(reset ? { lastHit: null } : {}) });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case "hit":
|
case "hit":
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ export interface ConfigView {
|
|||||||
armorId: number | null;
|
armorId: number | null;
|
||||||
armorIdText: string | null;
|
armorIdText: string | null;
|
||||||
mirror: boolean;
|
mirror: boolean;
|
||||||
|
mirrorVertical: boolean;
|
||||||
passwordSet: boolean;
|
passwordSet: boolean;
|
||||||
hud: HudView;
|
hud: HudView;
|
||||||
recordingDir: string;
|
recordingDir: string;
|
||||||
@@ -210,6 +211,7 @@ export interface Snapshot {
|
|||||||
role: Role;
|
role: Role;
|
||||||
team: number;
|
team: number;
|
||||||
mirrored: boolean;
|
mirrored: boolean;
|
||||||
|
mirroredVertical: boolean;
|
||||||
demo: boolean;
|
demo: boolean;
|
||||||
diagnostics: boolean;
|
diagnostics: boolean;
|
||||||
unlocked: boolean;
|
unlocked: boolean;
|
||||||
@@ -242,7 +244,7 @@ export interface MatchClockView {
|
|||||||
source: string | null;
|
source: string | null;
|
||||||
syncError: string | null;
|
syncError: string | null;
|
||||||
}
|
}
|
||||||
export type MatchAction = { type: "prepare" | "resume" | "end" | "reset" }
|
export type MatchAction = { type: "prepare" | "skipPreparation" | "resume" | "end" | "reset" }
|
||||||
| { type: "countdown"; seconds: number }
|
| { type: "countdown"; seconds: number }
|
||||||
| { type: "pausePlayer"; team: number; reason: string; approved: boolean }
|
| { type: "pausePlayer"; team: number; reason: string; approved: boolean }
|
||||||
| { type: "pauseOfficial"; reason: string };
|
| { type: "pauseOfficial"; reason: string };
|
||||||
|
|||||||
@@ -89,9 +89,12 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
|||||||
// 命中流水:最近三次,放在控制台头部。裁判在争执时需要的是"刚才谁掉了多少"。
|
// 命中流水:最近三次,放在控制台头部。裁判在争执时需要的是"刚才谁掉了多少"。
|
||||||
const [ledger, setLedger] = useState<HitPulseRecord[]>([]);
|
const [ledger, setLedger] = useState<HitPulseRecord[]>([]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!lastHit) return;
|
if (!lastHit) { setLedger([]); return; }
|
||||||
setLedger((current) => [lastHit, ...current].slice(0, 3));
|
setLedger((current) => [lastHit, ...current].slice(0, 3));
|
||||||
}, [lastHit]);
|
}, [lastHit]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (snapshot.matchClock.phase === "idle") setLedger([]);
|
||||||
|
}, [snapshot.matchClock.phase]);
|
||||||
|
|
||||||
const panes = useMemo(
|
const panes = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -246,6 +249,7 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
|||||||
: `等待${label}的图传`
|
: `等待${label}的图传`
|
||||||
}
|
}
|
||||||
mirrored={snapshot.mirrored}
|
mirrored={snapshot.mirrored}
|
||||||
|
mirroredVertical={snapshot.mirroredVertical}
|
||||||
// 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。
|
// 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。
|
||||||
crosshair={null}
|
crosshair={null}
|
||||||
grid={hud.grid}
|
grid={hud.grid}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
|||||||
return <div className="op cockpit">
|
return <div className="op cockpit">
|
||||||
<div className="op__stage">
|
<div className="op__stage">
|
||||||
<VideoSurface camera={camera} label="" emptyText={emptyText} signalLost={!hasVideo}
|
<VideoSurface camera={camera} label="" emptyText={emptyText} signalLost={!hasVideo}
|
||||||
mirrored={snapshot.mirrored} crosshair={hasVideo ? hud.crosshair : null} grid={hasVideo ? hud.grid : null} view={view} onView={setView}
|
mirrored={snapshot.mirrored} mirroredVertical={snapshot.mirroredVertical} crosshair={hasVideo ? hud.crosshair : null} grid={hasVideo ? hud.grid : null} view={view} onView={setView}
|
||||||
calibrating={calibrating} onCalibrate={calibrating ? onCalibrate : undefined} hit={pulse} hitFeedback={hud.hitFeedback} showZoom={hud.showZoom} showResetControl={false}>
|
calibrating={calibrating} onCalibrate={calibrating ? onCalibrate : undefined} hit={pulse} hitFeedback={hud.hitFeedback} showZoom={hud.showZoom} showResetControl={false}>
|
||||||
<div className="cockpit__overlay">
|
<div className="cockpit__overlay">
|
||||||
<div className="cockpit__health">
|
<div className="cockpit__health">
|
||||||
@@ -64,7 +64,7 @@ export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="cockpit__frame" aria-hidden="true"><i /><i /><i /><i /></div>
|
<div className="cockpit__frame" aria-hidden="true"><i /><i /><i /><i /></div>
|
||||||
<div className="cockpit__telemetry">
|
<div className="cockpit__telemetry">
|
||||||
<div className="cockpit__feed"><span className="label">VIDEO SOURCE</span><strong className="num">{camera === null ? "NO BINDING" : boundCamera?.idText ?? idText(camera)}</strong><span>{cameraLive && stats?.hasFrames ? `${stats.width} × ${stats.height}${snapshot.mirrored ? " / 镜像" : ""}` : "等待图传连接"}</span></div>
|
<div className="cockpit__feed"><span className="label">VIDEO SOURCE</span><strong className="num">{camera === null ? "NO BINDING" : boundCamera?.idText ?? idText(camera)}</strong><span>{cameraLive && stats?.hasFrames ? `${stats.width} × ${stats.height}${snapshot.mirrored ? " / 左右镜像" : ""}${snapshot.mirroredVertical ? " / 上下镜像" : ""}` : "等待图传连接"}</span></div>
|
||||||
<div className="cockpit__fps"><span className="label">RECEIVE / FPS</span><strong className="num">{cameraLive && stats?.hasFrames ? stats.fps.toFixed(1) : "—"}</strong>{hud.showStats && snapshot.diagnostics && <span>丢包 {cameraLive && stats?.hasFrames ? `${stats.lossPercent.toFixed(1)}%` : "—"}</span>}</div>
|
<div className="cockpit__fps"><span className="label">RECEIVE / FPS</span><strong className="num">{cameraLive && stats?.hasFrames ? stats.fps.toFixed(1) : "—"}</strong>{hud.showStats && snapshot.diagnostics && <span>丢包 {cameraLive && stats?.hasFrames ? `${stats.lossPercent.toFixed(1)}%` : "—"}</span>}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="cockpit__footer"><span><kbd>ESC</kbd> 菜单 / 设置</span><span className="num">{calibrating ? "瞄准校准中" : hud.showZoom ? `OPTICAL ×${view.zoom.toFixed(1)}` : ""}</span><span>{snapshot.config.armorId === null ? "ARMOR / —" : `ARMOR / ${board?.idText ?? idText(snapshot.config.armorId)}`}</span></div>
|
<div className="cockpit__footer"><span><kbd>ESC</kbd> 菜单 / 设置</span><span className="num">{calibrating ? "瞄准校准中" : hud.showZoom ? `OPTICAL ×${view.zoom.toFixed(1)}` : ""}</span><span>{snapshot.config.armorId === null ? "ARMOR / —" : `ARMOR / ${board?.idText ?? idText(snapshot.config.armorId)}`}</span></div>
|
||||||
|
|||||||
+11
-5
@@ -32,9 +32,13 @@ client/
|
|||||||
|
|
||||||
计时依据 [2026 比赛流程](https://docs.simba-robotics.com/zh-cn/competition/matches/):准备 3 分钟、对局 3 分钟、选手技术暂停 5 分钟。准备结束进入“等待裁判”,不会自动开赛;裁判确认后先执行短倒计时,再开始对局。短倒计时可设 1–60 秒,默认 5 秒,是客户端设置,并非规则页规定的时长。
|
计时依据 [2026 比赛流程](https://docs.simba-robotics.com/zh-cn/competition/matches/):准备 3 分钟、对局 3 分钟、选手技术暂停 5 分钟。准备结束进入“等待裁判”,不会自动开赛;裁判确认后先执行短倒计时,再开始对局。短倒计时可设 1–60 秒,默认 5 秒,是客户端设置,并非规则页规定的时长。
|
||||||
|
|
||||||
裁判端顶部的比赛控制条提供准备、确认开赛、选手暂停、官方暂停、恢复和结束本局等操作。发起选手暂停时,需选择申请方、填写原因并勾选“已获得主裁判批准”;按下开始按钮后才计入暂停时间。
|
裁判端顶部的比赛控制条提供准备、跳过准备倒计时、确认开赛、选手暂停、官方暂停、恢复和结束本局等操作。准备期间点击“跳过准备倒计时”会进入“准备结束 · 等待裁判”;仍需点击“确认开赛”,经过短倒计时后才开始对局。发起选手暂停时,需选择申请方、填写原因并勾选“已获得主裁判批准”;按下开始按钮后才计入暂停时间。
|
||||||
|
|
||||||
暂停期间,原阶段与对局用时冻结。选手暂停满 5 分钟后显示到期,等待裁判手动恢复,也允许提前恢复。官方暂停显示已用时,不设自动恢复时限,因为规则页未规定其时长。恢复后继续暂停前的阶段,不重新计整局。提前结束会停止计时和装甲板扣血,胜负由裁判判定;计时不能控制机器人运动、重置血量或代替判罚。
|
暂停期间,原阶段与对局用时冻结。选手暂停满 5 分钟后显示到期,等待裁判手动恢复,也允许提前恢复。官方暂停显示已用时,不设自动恢复时限,因为规则页未规定其时长。恢复后继续暂停前的阶段,不重新计整局。提前结束会停止计时和装甲板扣血,胜负由裁判判定;计时不能控制机器人运动或代替判罚。
|
||||||
|
|
||||||
|
一方血量归零显示胜负后,或本局计时结束后,控制条显示“重置到未开始”。点击一次会先停止本局计时和扣血,再向当前装甲板槽位定向发送复位请求。收到每块目标主板的回执及回执后的四路 100 血上报后,才清除本局计时、暂停信息和最近命中流水,回到等待准备;胜负横幅随真实血量恢复而消失。设备槽位、队伍名、画面及录制设置保留,已有录制文件不删除。重置后的等待准备状态会同步到选手端,血量仍来自装甲板的真实上报。
|
||||||
|
|
||||||
|
远程复位需要更新装甲板固件。请求最多等待 3 秒,未确认或未收到四路满血时保留结束状态,提示具体主板及检查步骤;部分主板成功复位时也不会报告整局重置成功。离线主板或两队误用同一块主板会报错。重置过程中禁止开赛和修改配置;没有分配装甲板时只重置计时。旧固件仍可长按 BOOT 复位血量,但不会确认远程请求,不能完成这项一键重置。
|
||||||
|
|
||||||
选手端将阶段与剩余时间放在顶部两条血条中间,悬停可查看对局用时与暂停原因。开赛前最后 5 秒覆盖整个画面,逐秒缩放数字并显示环形动效,最后 2 秒加强颜色提示;收到正式开赛状态后短暂显示“开始”,随后恢复操作画面。系统开启“减少动态效果”时停用动画,仍保留数字倒计时。计时失联或比赛暂停时不显示全屏倒计时。原始规则和状态机在 Rust 核心,前端仅在有效快照期限内插值。两台电脑通过同一局域网 UDP 5601 广播同步,需允许客户端的本地网络收发;与装甲板共用接收端口,不需要图传板或装甲板配合转发。旧客户端没有同步显示能力。
|
选手端将阶段与剩余时间放在顶部两条血条中间,悬停可查看对局用时与暂停原因。开赛前最后 5 秒覆盖整个画面,逐秒缩放数字并显示环形动效,最后 2 秒加强颜色提示;收到正式开赛状态后短暂显示“开始”,随后恢复操作画面。系统开启“减少动态效果”时停用动画,仍保留数字倒计时。计时失联或比赛暂停时不显示全屏倒计时。原始规则和状态机在 Rust 核心,前端仅在有效快照期限内插值。两台电脑通过同一局域网 UDP 5601 广播同步,需允许客户端的本地网络收发;与装甲板共用接收端口,不需要图传板或装甲板配合转发。旧客户端没有同步显示能力。
|
||||||
|
|
||||||
@@ -44,9 +48,9 @@ client/
|
|||||||
|
|
||||||
计时不写入个人配置。裁判进程重启后从等待准备开始,需现场人工核对,不会自行恢复或判罚上一局。
|
计时不写入个人配置。裁判进程重启后从等待准备开始,需现场人工核对,不会自行恢复或判罚上一局。
|
||||||
|
|
||||||
`--demo` 和浏览器预览只在本机合成,不发送、跟随现场计时。浏览器可用 `?preview=referee&match=ready` 检查确认开赛,`match=preparation` / `countdown` / `running` / `paused-player` / `paused-official` / `paused-expired` 检查各状态;去掉 `preview=referee` 可检查选手 HUD,`?match=offline` 检查冻结提示。演示不代表跨电脑广播验证。
|
`--demo` 和浏览器预览只在本机合成,不发送、跟随现场计时或向真实装甲板发送复位。浏览器可用 `?preview=referee&match=ready` 检查确认开赛,`match=preparation` / `countdown` / `running` / `paused-player` / `paused-official` / `paused-expired` 检查各状态;`match=finished` 合成一方归零,供检查一键重置。去掉 `preview=referee` 可检查选手 HUD,`?match=offline` 检查冻结提示。演示中的重置只恢复合成血量,不代表跨电脑广播或硬件复位验证。
|
||||||
|
|
||||||
自动验证入口:`pnpm test:match` 检查显示插值与断线冻结;`client/core` 主机测试覆盖规则转换、暂停冻结、过期、乱序和角色限制,集成测试 `match_sync` 使用真实回环 UDP 经生产消息分流到跟随计时器。协议测试检查长度、版本、UTF-8 和字段拒收。发布前仍需在两台电脑上检查广播可达、各网卡与防火墙、暂停同步和裁判重启后的人工重连。
|
自动验证入口:`pnpm test:match` 检查显示插值与断线冻结;`pnpm test:video` 检查镜像坐标、用户端 HUD 和裁判操作入口。`client/core` 主机测试覆盖规则转换、跳过准备、重置、暂停冻结、过期、乱序和角色限制,集成测试 `match_sync` 使用真实回环 UDP 经生产消息分流到跟随计时器,`armor_reset` 验证复位重试、回执与满血确认。协议测试检查长度、版本、UTF-8 和字段拒收,装甲板规则测试覆盖复位去重及许可限制。发布前仍需在两台电脑和真实主板上检查广播可达、各网卡与防火墙、复位和暂停同步,以及裁判重启后的人工重连。
|
||||||
|
|
||||||
固件维护页用简化线条绘制 C3 装甲板和 S3 图传板,配色沿用界面的冷蓝黑底与状态色。装甲板保留横向比例,S3 的 USB 接线指向右侧接口。图中的状态点表示 USB 识别,进度环表示当前维护任务,不推断实物 Wi-Fi、灯色或传感器状态。
|
固件维护页用简化线条绘制 C3 装甲板和 S3 图传板,配色沿用界面的冷蓝黑底与状态色。装甲板保留横向比例,S3 的 USB 接线指向右侧接口。图中的状态点表示 USB 识别,进度环表示当前维护任务,不推断实物 Wi-Fi、灯色或传感器状态。
|
||||||
|
|
||||||
@@ -135,6 +139,7 @@ python scripts/generate-brand-assets.py
|
|||||||
### 每页最顺手的那个操作
|
### 每页最顺手的那个操作
|
||||||
|
|
||||||
- 用户端通过滚轮缩放、拖动平移、双击复位。顶栏和常驻操作按钮已收进 ESC 菜单,画面边缘持续显示当前图传、接收帧率、图传及绑定装甲板状态。未绑定或离线时显示对应状态,不显示旧帧率;准星与网格在收到画面后显示。顶部身份与链路、双方血条、底部读数各自分区,放大血条不会盖住对方。菜单开合和维护步骤有短过渡,系统开启“减少动态效果”时停用。
|
- 用户端通过滚轮缩放、拖动平移、双击复位。顶栏和常驻操作按钮已收进 ESC 菜单,画面边缘持续显示当前图传、接收帧率、图传及绑定装甲板状态。未绑定或离线时显示对应状态,不显示旧帧率;准星与网格在收到画面后显示。顶部身份与链路、双方血条、底部读数各自分区,放大血条不会盖住对方。菜单开合和维护步骤有短过渡,系统开启“减少动态效果”时停用。
|
||||||
|
- 用户端设置的“设备绑定”和裁判端设置的“画面槽位”提供“左右镜像画面”和“上下镜像画面”两个独立开关,可组合使用,自动保存到本机配置;上下镜像默认关闭,旧配置保持原方向。用户端和裁判端的图像、网格、准星偏移、拖动与校准随对应轴翻转,HUD 文字保持正向。镜像只影响本机显示,截图和录制仍使用原始图像。
|
||||||
- 按 ESC 打开操作菜单,可继续操作、进入画面与设备设置、打开固件维护、切换全屏或退出。再次按 ESC 返回;设置和退出沿用密码规则。菜单打开时图传接收与受击上报继续运行,并不暂停比赛。
|
- 按 ESC 打开操作菜单,可继续操作、进入画面与设备设置、打开固件维护、切换全屏或退出。再次按 ESC 返回;设置和退出沿用密码规则。菜单打开时图传接收与受击上报继续运行,并不暂停比赛。
|
||||||
- 裁判端点击左侧画面后,下方列表只显示该侧的装甲板;再次点击恢复显示全部,键盘 `1` / `2` / `0` 也可切换。拖动中间的竖线可调整两路画面的宽度,双击恢复等宽。拖动画面与控制台之间的横线可调整回放区域高度。
|
- 裁判端点击左侧画面后,下方列表只显示该侧的装甲板;再次点击恢复显示全部,键盘 `1` / `2` / `0` 也可切换。拖动中间的竖线可调整两路画面的宽度,双击恢复等宽。拖动画面与控制台之间的横线可调整回放区域高度。
|
||||||
- 设置覆盖整个窗口,左侧切换分类,中间只显示当前分类的控件。用户端包含常规、设备绑定、瞄准器、瞄点校准、辅助网格、装甲条、受击与提示、录制与截图、安全;裁判端提供画面槽位分类。分类可用鼠标或方向键切换,按 ESC 返回。控件分列排布,低高度窗口仅在当前分类内滚动,不再浏览整页设置。
|
- 设置覆盖整个窗口,左侧切换分类,中间只显示当前分类的控件。用户端包含常规、设备绑定、瞄准器、瞄点校准、辅助网格、装甲条、受击与提示、录制与截图、安全;裁判端提供画面槽位分类。分类可用鼠标或方向键切换,按 ESC 返回。控件分列排布,低高度窗口仅在当前分类内滚动,不再浏览整页设置。
|
||||||
@@ -347,7 +352,7 @@ Rust 侧的配置修改命令会调用 `AppState::require_unlocked`。即使从
|
|||||||
一方血量归零后,图传中央显示结果:获胜方为“胜利”,落败方为“落败”,双方同时归零为“平局”。提示带上对手名字,便于在裁判端两路画面中判断胜负。
|
一方血量归零后,图传中央显示结果:获胜方为“胜利”,落败方为“落败”,双方同时归零为“平局”。提示带上对手名字,便于在裁判端两路画面中判断胜负。
|
||||||
|
|
||||||
- 结果由 Rust 侧计算(`snapshot::resolve_outcomes`,有单测)。自己归零即可判负,即使对手掉线;判胜则要求对手归零且自己仍有血,避免在本队从未上报时误判获胜。
|
- 结果由 Rust 侧计算(`snapshot::resolve_outcomes`,有单测)。自己归零即可判负,即使对手掉线;判胜则要求对手归零且自己仍有血,避免在本队从未上报时误判获胜。
|
||||||
- 横幅持续显示到血量重置(长按 BOOT / 下一局开始),供截图、回放和现场核对。
|
- 横幅持续显示到装甲板血量复位(长按 BOOT,或裁判端“重置到未开始”),供截图、回放和现场核对。单纯开始准备不会补血。
|
||||||
- 比赛结果放在画面中央;比赛中的命中反馈避开中央瞄准区域。
|
- 比赛结果放在画面中央;比赛中的命中反馈避开中央瞄准区域。
|
||||||
|
|
||||||
### 瞄准器
|
### 瞄准器
|
||||||
@@ -443,6 +448,7 @@ teamNames = ["队伍一", "队伍二"]
|
|||||||
cameraId = "0x0DE00001"
|
cameraId = "0x0DE00001"
|
||||||
armorId = "0x0A200001"
|
armorId = "0x0A200001"
|
||||||
mirror = false
|
mirror = false
|
||||||
|
mirrorVertical = false
|
||||||
password = "$argon2id$v=19$m=19456,t=2,p=1$..."
|
password = "$argon2id$v=19$m=19456,t=2,p=1$..."
|
||||||
|
|
||||||
[recording]
|
[recording]
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
> 状态:部分实现,其余待确认。准备、开赛倒计时、对局计时、选手/官方暂停和选手端同步已实现,操作方法与边界见[比赛计时与暂停](../client/client.md#比赛计时与暂停)。其余内容保留为 2026-10-19 草案;下文的布局、命令、快捷键和验收数字均不代表当前能力或测试结果。
|
> 状态:部分实现,其余待确认。准备、开赛倒计时、对局计时、选手/官方暂停和选手端同步已实现,操作方法与边界见[比赛计时与暂停](../client/client.md#比赛计时与暂停)。其余内容保留为 2026-10-19 草案;下文的布局、命令、快捷键和验收数字均不代表当前能力或测试结果。
|
||||||
> 比赛判负、系列赛比分、直播页和双路同步回放仍需确认。已实现的 USB 维护与固件包格式见[固件维护](../maintenance/firmware.md)。计时同步实际使用类型 7 `MatchState`;类型 6 已用于 `ArmorControl`,下文原协议草案不作为线路定义。
|
> 比赛判负、系列赛比分、直播页和双路同步回放仍需确认。已实现的 USB 维护与固件包格式见[固件维护](../maintenance/firmware.md)。计时同步实际使用类型 7 `MatchState`;类型 6 已用于 `ArmorControl`,下文原协议草案不作为线路定义。
|
||||||
|
> 当前还已实现跳过准备后等待确认开赛,以及结束后的定向装甲板复位。扣血许可使用类型 8,复位与回执使用类型 9;需更新装甲板固件,主机测试不代表板上验证。下文关于暂停不影响硬件扣血、尚无下行控制及复位未实现的描述保留为原草案背景,以[UDP 协议](../protocol/udp.md)和[客户端说明](../client/client.md)为准。
|
||||||
> 原草案中的旧色板、字体方案、单文件 CSS 基线、烧录实现计划和排期已被当前实现取代,不再作为开发依据。
|
> 原草案中的旧色板、字体方案、单文件 CSS 基线、烧录实现计划和排期已被当前实现取代,不再作为开发依据。
|
||||||
> 规则依据:[2026 校内赛参赛手册](https://docs.simba-robotics.com/zh-cn/competition/)、[对抗赛与奖项](https://docs.simba-robotics.com/zh-cn/competition/matches/)、[裁判系统](https://docs.simba-robotics.com/zh-cn/competition/referee-system/)。规则摘录沿用原稿,实施前需核对手册。
|
> 规则依据:[2026 校内赛参赛手册](https://docs.simba-robotics.com/zh-cn/competition/)、[对抗赛与奖项](https://docs.simba-robotics.com/zh-cn/competition/matches/)、[裁判系统](https://docs.simba-robotics.com/zh-cn/competition/referee-system/)。规则摘录沿用原稿,实施前需核对手册。
|
||||||
|
|
||||||
|
|||||||
@@ -50,12 +50,14 @@ armor/
|
|||||||
| 受击阈值 | 原始 12 bit ADC > 2000(`ARMOR_THRESHOLD` 可改) | `Rules::threshold` |
|
| 受击阈值 | 原始 12 bit ADC > 2000(`ARMOR_THRESHOLD` 可改) | `Rules::threshold` |
|
||||||
| 血量归零 | 四路全黑,直到复位 | `Armor::strip` |
|
| 血量归零 | 四路全黑,直到复位 | `Armor::strip` |
|
||||||
| 正常颜色 | 队伍一红(`0xFF0000`)、队伍二蓝(`0x0000FF`) | `Rgb::for_team` |
|
| 正常颜色 | 队伍一红(`0xFF0000`)、队伍二蓝(`0x0000FF`) | `Rgb::for_team` |
|
||||||
| 复位(新一局) | 长按 BOOT ≥500 ms → 满血、清计数 | `Button` + `Armor::reset` |
|
| 复位(新一局) | 长按 BOOT ≥500 ms,或裁判端定向复位 → 满血、清计数;保留队伍与灯色 | `Button` / `DamageLink::accept_reset` + `Armor::reset` |
|
||||||
| 打印状态 | 短按 BOOT → 立刻打一行状态并重发上报 | `ButtonEvent::Click` |
|
| 打印状态 | 短按 BOOT → 立刻打一行状态并重发上报 | `ButtonEvent::Click` |
|
||||||
|
|
||||||
整车共用一条血量,由主板计算;裁判端负责发送扣血许可和显示血量。四条上报的 `hp` 相同,`index` 分别为 0..3。界面按 `(team, index)` 收齐四条后显示同一个数值。
|
整车共用一条血量,由主板计算;裁判端负责发送扣血许可和显示血量。四条上报的 `hp` 相同,`index` 分别为 0..3。界面按 `(team, index)` 收齐四条后显示同一个数值。
|
||||||
|
|
||||||
装甲板默认禁止扣血。正式裁判端仅在对局进行中允许当前比赛装甲板扣血,其他阶段均禁止。禁止扣血时,受击路仍熄灭 50 ms,冷却与检测继续,血量不变。许可每 200 ms 续约,超过 1 秒未收到新许可、Wi-Fi 断开或客户端保活失效后停止扣血。恢复许可不会补血,开始新一局仍需长按 BOOT 复位。此功能需要更新装甲板固件,旧固件会忽略许可消息。线路和来源规则见[UDP 协议](../protocol/udp.md#装甲板扣血许可)。
|
装甲板默认禁止扣血。正式裁判端仅在对局进行中允许当前比赛装甲板扣血,其他阶段均禁止。禁止扣血时,受击路仍熄灭 50 ms,冷却与检测继续,血量不变。许可每 200 ms 续约,超过 1 秒未收到新许可、Wi-Fi 断开或客户端保活失效后停止扣血。恢复许可不会补血,新一局可长按 BOOT 或使用裁判端“重置到未开始”复位。扣血许可及远程复位都需要对应版本的装甲板固件;旧固件会忽略未知消息。线路和来源规则见[UDP 协议](../protocol/udp.md#装甲板扣血许可)。
|
||||||
|
|
||||||
|
远程复位只接受目标 id 匹配、同一裁判来源与会话、序号等于最新有效禁止扣血许可的请求。首次执行恢复 100 血、清受击计数和冷却,保留队伍与灯色;同一个复位 id 的重试只回执,不再次补血。板端定向回复回执并立即广播四路血量,客户端确认后才回到未开始。运行许可、过期许可和旧序号下的复位均拒绝。此规则已有主机测试,板上复位、丢包重试及两台电脑同步仍需实测。
|
||||||
|
|
||||||
参考实现使用全局 50 ms 冷却,一路受击会抑制其余路在该窗口内的击打。当前四路分别冷却,由 `cooldown_is_per_plate_not_global` 测试验证。
|
参考实现使用全局 50 ms 冷却,一路受击会抑制其余路在该窗口内的击打。当前四路分别冷却,由 `cooldown_is_per_plate_not_global` 测试验证。
|
||||||
|
|
||||||
@@ -293,4 +295,4 @@ UART0 是主控制台,USB Serial/JTAG 是次控制台,因此原生 USB 也
|
|||||||
- **从板加 MCU 的方案**:如果以后从板也装单片机(走 UART 或无线回传),
|
- **从板加 MCU 的方案**:如果以后从板也装单片机(走 UART 或无线回传),
|
||||||
`armor-protocol` 里已经预留了板位枚举与上报格式,加一个 `slave` bin 即可。
|
`armor-protocol` 里已经预留了板位枚举与上报格式,加一个 `slave` bin 即可。
|
||||||
- **双击 / 多击**:`Button` 只实现短按与长按,参考实现里未使用的 OneButton 功能没有移植。
|
- **双击 / 多击**:`Button` 只实现短按与长按,参考实现里未使用的 OneButton 功能没有移植。
|
||||||
- **下发血量**:当前由板子计算血量,裁判端只显示该数值。若以后改由裁判端决定血量并下发血量/复位,需要新增一条下行消息,由 `client` 发送。
|
- **下发任意血量**:当前仍由板子计算血量。裁判端可通过独立的复位消息恢复满血,但尚不支持指定任意血量或远程判负。
|
||||||
+1
-1
@@ -35,7 +35,7 @@
|
|||||||
|
|
||||||
- [改动记录](releases/changelog.md):由 Git 历史生成;[JSON](releases/changelog.json)供程序读取。
|
- [改动记录](releases/changelog.md):由 Git 历史生成;[JSON](releases/changelog.json)供程序读取。
|
||||||
- [早期人工记录](releases/changelog-legacy.md):自动版本机制建立前的记录。
|
- [早期人工记录](releases/changelog-legacy.md):自动版本机制建立前的记录。
|
||||||
- [比赛计时与暂停](client/client.md#比赛计时与暂停):裁判控制、选手同步及验证边界。
|
- [比赛计时与暂停](client/client.md#比赛计时与暂停):裁判控制、跳过准备、一键复位、选手同步及验证边界。
|
||||||
- [比赛控制与直播提案](design/match-and-broadcast.md):未实现的判罚、比分、直播与回放需求。
|
- [比赛控制与直播提案](design/match-and-broadcast.md):未实现的判罚、比分、直播与回放需求。
|
||||||
|
|
||||||
## 文档维护
|
## 文档维护
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b
|
|||||||
| 6 `ArmorControl` | 客户端 → 指定装甲板 | 运行时选择队伍并保活(回复广播源端口) |
|
| 6 `ArmorControl` | 客户端 → 指定装甲板 | 运行时选择队伍并保活(回复广播源端口) |
|
||||||
| 7 `MatchState` | 裁判端 → 选手端 | 完整比赛计时快照,广播至 UDP 5601,5 Hz |
|
| 7 `MatchState` | 裁判端 → 选手端 | 完整比赛计时快照,广播至 UDP 5601,5 Hz |
|
||||||
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
|
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
|
||||||
|
| 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 |
|
||||||
|
|
||||||
### 比赛计时快照(类型 7)
|
### 比赛计时快照(类型 7)
|
||||||
|
|
||||||
@@ -251,3 +252,19 @@ UDP 不保证数据报的顺序和到达。接收端等待下一张完整帧,
|
|||||||
板端默认禁止扣血。只有 Wi-Fi 可用、客户端颜色保活有效且扣血许可在 1 秒内收到新序号时才允许扣血。同一来源与会话的重复包、旧序号不能续约。租约有效时拒绝其他来源或会话,过期后可接受新的裁判来源。该机制用于现场状态同步,不提供身份认证。
|
板端默认禁止扣血。只有 Wi-Fi 可用、客户端颜色保活有效且扣血许可在 1 秒内收到新序号时才允许扣血。同一来源与会话的重复包、旧序号不能续约。租约有效时拒绝其他来源或会话,过期后可接受新的裁判来源。该机制用于现场状态同步,不提供身份认证。
|
||||||
|
|
||||||
扣血许可与 `ArmorControl` 分开管理,裁判发送许可不会抢占操作手的灯色控制。禁止扣血时,ADC 检测、每板冷却和受击熄灯 50 ms 继续执行,血量保持不变;恢复许可不会自动补血。旧装甲板固件会忽略 type=8,必须更新固件才能使用此规则。独立字节核对包含在 `python armor/scripts/test-probe.py` 中,探测器不发送扣血许可。
|
扣血许可与 `ArmorControl` 分开管理,裁判发送许可不会抢占操作手的灯色控制。禁止扣血时,ADC 检测、每板冷却和受击熄灯 50 ms 继续执行,血量保持不变;恢复许可不会自动补血。旧装甲板固件会忽略 type=8,必须更新固件才能使用此规则。独立字节核对包含在 `python armor/scripts/test-probe.py` 中,探测器不发送扣血许可。
|
||||||
|
|
||||||
|
### 装甲板复位与回执
|
||||||
|
|
||||||
|
`ArmorReset` 使用 `type=9`、协议版本 1 和原有 27 字节头,不改变视频、血量及其他消息载荷。请求的 `sender_id=0`,回执的 `sender_id=board_id`,其余头部业务字段置零。负载严格为 29 字节,完整数据报 56 字节:
|
||||||
|
|
||||||
|
| 载荷偏移 | 类型 | 含义 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 0 | u32 LE | 目标 `board_id`,非零 |
|
||||||
|
| 4 | u64 LE | 裁判计时会话,非零 |
|
||||||
|
| 12 | u64 LE | 本次禁止扣血许可的序号,非零 |
|
||||||
|
| 20 | u64 LE | `reset_id`,非零且不大于序号;同次操作重试保持不变 |
|
||||||
|
| 28 | u8 | 0 请求,1 回执,其他值拒收 |
|
||||||
|
|
||||||
|
客户端先进入结束阶段并发送禁止扣血许可,再向固定的本局槽位主板发送同序号复位请求;每 200 ms 随新许可更新请求序号,最多等待 3 秒。板端只接受目标 id 匹配、同一来源 IP/端口与会话、序号等于最新有效禁止扣血许可的请求。首次执行恢复满血并清受击计数、冷却;同复位 id 的重试只回复回执并重发血量,不重复复位。旧复位 id、旧许可序号、过期许可及运行许可下的请求均拒绝。
|
||||||
|
|
||||||
|
回执定向发回裁判端,并沿用请求字段;板端同时通过原血量通道广播四路真实血量。客户端逐板核对来源地址、会话、复位 id 和已发送序号,收到回执及其后的四路 100 血上报才完成重置,不根据回执伪造血量。部分成功或超时均保留结束阶段。来源与会话约束防止意外混用,不提供身份认证。旧装甲板忽略 type=9,必须更新固件才能远程复位;图传板无需更新。独立字节核对见 `python armor/scripts/test-probe.py`,探测器不发送复位。
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
use crate::{decode_header, encode_header_into, Header, MsgType, HEADER_LEN, PROTOCOL_VERSION};
|
||||||
|
|
||||||
|
/// 定向复位及回执。sequence 对齐本次禁止扣血许可;reset_id 在重试间保持不变。
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct ArmorReset {
|
||||||
|
pub board_id: u32,
|
||||||
|
pub session: u64,
|
||||||
|
pub sequence: u64,
|
||||||
|
pub reset_id: u64,
|
||||||
|
pub acknowledged: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ArmorReset {
|
||||||
|
pub fn encode(&self) -> Option<Vec<u8>> {
|
||||||
|
if self.board_id == 0
|
||||||
|
|| self.session == 0
|
||||||
|
|| self.reset_id == 0
|
||||||
|
|| self.sequence < self.reset_id
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut out = Vec::with_capacity(HEADER_LEN + 29);
|
||||||
|
encode_header_into(
|
||||||
|
&Header {
|
||||||
|
msg_type: MsgType::ArmorReset,
|
||||||
|
version: PROTOCOL_VERSION,
|
||||||
|
sender_id: if self.acknowledged { self.board_id } else { 0 },
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&mut out,
|
||||||
|
);
|
||||||
|
out.extend(self.board_id.to_le_bytes());
|
||||||
|
out.extend(self.session.to_le_bytes());
|
||||||
|
out.extend(self.sequence.to_le_bytes());
|
||||||
|
out.extend(self.reset_id.to_le_bytes());
|
||||||
|
out.push(u8::from(self.acknowledged));
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||||
|
let h = decode_header(bytes)?;
|
||||||
|
if h.msg_type != MsgType::ArmorReset || bytes.len() != HEADER_LEN + 29 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let p = &bytes[HEADER_LEN..];
|
||||||
|
let value = Self {
|
||||||
|
board_id: u32::from_le_bytes(p[0..4].try_into().ok()?),
|
||||||
|
session: u64::from_le_bytes(p[4..12].try_into().ok()?),
|
||||||
|
sequence: u64::from_le_bytes(p[12..20].try_into().ok()?),
|
||||||
|
reset_id: u64::from_le_bytes(p[20..28].try_into().ok()?),
|
||||||
|
acknowledged: match p[28] {
|
||||||
|
0 => false,
|
||||||
|
1 => true,
|
||||||
|
_ => return None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
(value.board_id != 0
|
||||||
|
&& value.session != 0
|
||||||
|
&& value.reset_id != 0
|
||||||
|
&& value.sequence >= value.reset_id
|
||||||
|
&& h.sender_id
|
||||||
|
== if value.acknowledged {
|
||||||
|
value.board_id
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
})
|
||||||
|
.then_some(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reset_matches_the_independent_probe_golden_bytes() {
|
||||||
|
let bytes = ArmorReset {
|
||||||
|
board_id: 0x12345678,
|
||||||
|
session: 0x0102030405060708,
|
||||||
|
sequence: 3,
|
||||||
|
reset_id: 2,
|
||||||
|
acknowledged: false,
|
||||||
|
}
|
||||||
|
.encode()
|
||||||
|
.unwrap();
|
||||||
|
let hex = bytes
|
||||||
|
.iter()
|
||||||
|
.map(|byte| format!("{byte:02x}"))
|
||||||
|
.collect::<String>();
|
||||||
|
assert_eq!(
|
||||||
|
hex,
|
||||||
|
concat!(
|
||||||
|
"3143564d090100",
|
||||||
|
"0000000000000000000000000000000000000000",
|
||||||
|
"78563412",
|
||||||
|
"0807060504030201",
|
||||||
|
"0300000000000000",
|
||||||
|
"0200000000000000",
|
||||||
|
"00"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reset_roundtrip_is_exact_and_rejects_invalid_identity_and_bounds() {
|
||||||
|
for acknowledged in [false, true] {
|
||||||
|
let packet = ArmorReset {
|
||||||
|
board_id: 17,
|
||||||
|
session: 88,
|
||||||
|
sequence: 123,
|
||||||
|
reset_id: 120,
|
||||||
|
acknowledged,
|
||||||
|
};
|
||||||
|
let bytes = packet.encode().unwrap();
|
||||||
|
assert_eq!(bytes.len(), 56);
|
||||||
|
assert_eq!(ArmorReset::decode(&bytes), Some(packet));
|
||||||
|
assert!(crate::ArmorDamageControl::decode(&bytes).is_none());
|
||||||
|
assert!(crate::ArmorHealth::decode_from(&bytes).is_none());
|
||||||
|
for n in 0..bytes.len() {
|
||||||
|
assert!(ArmorReset::decode(&bytes[..n]).is_none());
|
||||||
|
}
|
||||||
|
for (at, byte) in [(4, 8), (5, 99), (7, 42), (55, 2)] {
|
||||||
|
let mut bad = bytes.clone();
|
||||||
|
bad[at] = byte;
|
||||||
|
assert!(ArmorReset::decode(&bad).is_none());
|
||||||
|
}
|
||||||
|
for range in [27..31, 31..39, 39..47, 47..55] {
|
||||||
|
let mut bad = bytes.clone();
|
||||||
|
bad[range].fill(0);
|
||||||
|
assert!(ArmorReset::decode(&bad).is_none());
|
||||||
|
}
|
||||||
|
let mut bad = bytes;
|
||||||
|
bad.push(0);
|
||||||
|
assert!(ArmorReset::decode(&bad).is_none());
|
||||||
|
assert!(ArmorReset {
|
||||||
|
reset_id: 124,
|
||||||
|
..packet
|
||||||
|
}
|
||||||
|
.encode()
|
||||||
|
.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,6 +52,8 @@ mod match_state;
|
|||||||
pub use match_state::MatchState;
|
pub use match_state::MatchState;
|
||||||
mod armor_damage;
|
mod armor_damage;
|
||||||
pub use armor_damage::ArmorDamageControl;
|
pub use armor_damage::ArmorDamageControl;
|
||||||
|
mod armor_reset;
|
||||||
|
pub use armor_reset::ArmorReset;
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 端口
|
// 端口
|
||||||
@@ -124,6 +126,8 @@ pub enum MsgType {
|
|||||||
MatchState = 7,
|
MatchState = 7,
|
||||||
/// 裁判端下发本局的扣血许可,定向发送到装甲板上报端口。
|
/// 裁判端下发本局的扣血许可,定向发送到装甲板上报端口。
|
||||||
ArmorDamageControl = 8,
|
ArmorDamageControl = 8,
|
||||||
|
/// 裁判定向复位装甲板及板端回执。
|
||||||
|
ArmorReset = 9,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MsgType {
|
impl MsgType {
|
||||||
@@ -138,6 +142,7 @@ impl MsgType {
|
|||||||
6 => MsgType::ArmorControl,
|
6 => MsgType::ArmorControl,
|
||||||
7 => MsgType::MatchState,
|
7 => MsgType::MatchState,
|
||||||
8 => MsgType::ArmorDamageControl,
|
8 => MsgType::ArmorDamageControl,
|
||||||
|
9 => MsgType::ArmorReset,
|
||||||
_ => return None,
|
_ => return None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ MSG_ARMOR_HEALTH = 5
|
|||||||
MSG_ARMOR_CONTROL = 6
|
MSG_ARMOR_CONTROL = 6
|
||||||
MSG_MATCH_STATE = 7
|
MSG_MATCH_STATE = 7
|
||||||
MSG_ARMOR_DAMAGE_CONTROL = 8
|
MSG_ARMOR_DAMAGE_CONTROL = 8
|
||||||
|
MSG_ARMOR_RESET = 9
|
||||||
|
|
||||||
TYPE_NAMES = {
|
TYPE_NAMES = {
|
||||||
MSG_VIDEO: "video",
|
MSG_VIDEO: "video",
|
||||||
@@ -47,6 +48,7 @@ TYPE_NAMES = {
|
|||||||
MSG_ARMOR_CONTROL: "armor-control",
|
MSG_ARMOR_CONTROL: "armor-control",
|
||||||
MSG_MATCH_STATE: "match-state",
|
MSG_MATCH_STATE: "match-state",
|
||||||
MSG_ARMOR_DAMAGE_CONTROL: "armor-damage-control",
|
MSG_ARMOR_DAMAGE_CONTROL: "armor-damage-control",
|
||||||
|
MSG_ARMOR_RESET: "armor-reset",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user