use std::sync::Arc; /// CTL drive multipliers and the authored transitions used to select them. #[derive(Clone, Debug, Default, PartialEq)] pub enum PreparedControlDrive { /// The state cannot affect demand when every record has this multiplier. Uniform(u32), /// States selected by linear and angular velocity and a transition graph. Automatic(Arc), /// The profile needs a selector beyond the velocity-based path. #[default] Unavailable, } #[derive(Clone, Copy, Debug, PartialEq)] struct DriveState { factor_bits: u32, axes: u32, automatic: bool, minimum: [f32; 6], maximum: [f32; 6], } impl DriveState { fn matches(self, velocity: [f32; 6]) -> bool { (0..6).all(|axis| { let flag = if axis < 3 { 1 << axis } else { 2 << axis }; self.axes & flag == 0 || (self.minimum[axis]..=self.maximum[axis]).contains(&velocity[axis]) }) } } #[derive(Clone, Copy, Debug, PartialEq)] struct DriveRoute { cost: f32, next: usize, } const UNREACHABLE: f32 = 1_000_000.0; /// Velocity conditions and shortest transitions between the authored CTL states. #[derive(Debug, PartialEq)] pub struct ControlDriveStates { states: Vec, routes: Vec, } impl ControlDriveStates { fn route(&self, current: usize, destination: usize) -> DriveRoute { self.routes[destination * self.states.len() + current] } /// Chooses a new transition destination at a state that accepts automatic selection. /// Other states finish their queued transition before they can choose again. pub fn destination(&self, current: usize, velocity: [f32; 6]) -> Option { let state = self.states.get(current)?; if !state.automatic { return None; } if state.matches(velocity) { return Some(current); } let mut closest = UNREACHABLE; let mut destination = current; for (index, candidate) in self.states.iter().enumerate() { if index != current && candidate.automatic && candidate.matches(velocity) { let route = self.route(current, index); if route.cost < closest { closest = route.cost; destination = index; } } } Some(destination) } /// Reads the first state in a reachable transition, which can be part of a gait loop. pub fn next_state(&self, current: usize, destination: usize) -> Option { self.states.get(current)?; self.states.get(destination)?; let route = self.route(current, destination); (route.cost < UNREACHABLE).then_some(route.next) } /// Returns the drive multiplier from the selected state. pub fn factor(&self, state: usize) -> Option { Some(f32::from_bits(self.states.get(state)?.factor_bits)) } } pub(super) fn decode( records: &[u8], stride: usize, transition_bytes: &[u8], ) -> PreparedControlDrive { let mut factors = records.chunks_exact(stride).map(|row| word(row, 0x54)); let Some(first) = factors.next() else { return PreparedControlDrive::Unavailable; }; if factors.all(|next| next == first) { return PreparedControlDrive::Uniform(first); } let Some(states) = records .chunks_exact(stride) .map(decode_velocity_state) .collect::>>() else { return PreparedControlDrive::Unavailable; }; let edges: Vec = transition_bytes .chunks_exact(4) .map(|bytes| f32::from_bits(word(bytes, 0))) .collect(); if edges.iter().any(|edge| !edge.is_finite() || *edge < 0.0) { return PreparedControlDrive::Unavailable; } let routes = transition_routes(&edges, states.len()); PreparedControlDrive::Automatic(Arc::new(ControlDriveStates { states, routes })) } fn decode_velocity_state(row: &[u8]) -> Option { // Timed eligibility, action selectors and node conditions use live Control inputs // that the velocity controller does not publish. if word(row, 0x94) != u32::MAX || word(row, 0x98) != u32::MAX || row[0x9c..] .chunks_exact(16) .any(|node| word(node, 4) & 0x300 != 0) { return None; } let limits = |linear, angular| { std::array::from_fn(|axis| { let offset = if axis < 3 { linear + axis * 4 } else { angular + (axis - 3) * 4 }; f32::from_bits(word(row, offset)) }) }; Some(DriveState { factor_bits: word(row, 0x54), axes: word(row, 0), automatic: word(row, 4) & 1 != 0, minimum: limits(0x24, 0x3c), maximum: limits(0x30, 0x48), }) } fn transition_routes(edges: &[f32], count: usize) -> Vec { let mut routes = Vec::with_capacity(edges.len()); for (destination, incoming) in edges.chunks_exact(count).enumerate() { // Control.dll+0x19d0 starts with authored incoming edges, including the // diagonal. There is no implicit zero-cost edge from a state to itself. let mut paths: Vec<_> = incoming .iter() .map(|&cost| DriveRoute { cost, next: destination, }) .collect(); let mut visited = vec![false; count]; loop { let (Some(current), _) = paths.iter().enumerate().fold( (None, UNREACHABLE), |(best, cost), (index, path)| { if !visited[index] && path.cost < cost { (Some(index), path.cost) } else { (best, cost) } }, ) else { break; }; visited[current] = true; let cost = paths[current].cost; let incoming = &edges[current * count..][..count]; for (index, path) in paths .iter_mut() .enumerate() .filter(|(index, _)| !visited[*index]) { let through = cost + incoming[index]; if through < path.cost { *path = DriveRoute { cost: through, next: current, }; } } } routes.extend(paths); } routes } fn word(bytes: &[u8], at: usize) -> u32 { u32::from_le_bytes(bytes[at..at + 4].try_into().expect("complete CTL word")) } #[cfg(test)] mod tests { use super::*; #[test] fn transition_cost_can_select_a_loop_instead_of_the_authored_diagonal() { let inf = UNREACHABLE; // Incoming edges by destination. State 1 is cheaper to repeat by // visiting state 2 than by taking its authored diagonal edge. let routes = transition_routes(&[1.0, 2.0, inf, inf, 5.0, 1.0, 1.0, 1.0, inf], 3); let incoming_to_one = &routes[3..6]; assert_eq!( incoming_to_one, [ DriveRoute { cost: 2.0, next: 2 }, DriveRoute { cost: 2.0, next: 2 }, DriveRoute { cost: 1.0, next: 1 }, ] ); } }