1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
|
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<ControlDriveStates>),
/// 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<DriveState>,
routes: Vec<DriveRoute>,
}
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<usize> {
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<usize> {
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<f32> {
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::<Option<Vec<_>>>()
else {
return PreparedControlDrive::Unavailable;
};
let edges: Vec<f32> = 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<DriveState> {
// 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<DriveRoute> {
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 },
]
);
}
}
|