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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
|
//! Text and controls used by the original in-mission help terminal.
use crate::ui_configuration::read;
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_vfs::{Vfs, VfsError};
use std::collections::BTreeMap;
const CONTROL_TABLES: [&str; 4] = ["ui_hero", "ui_bots", "ui_hq", "ui_other"];
/// A token from a mission's CP1251 `Mistips.mis`.
#[derive(Debug, PartialEq, Eq)]
pub enum MissionTip {
/// Original bytes to draw with the game font.
Text(Vec<u8>),
/// An explicit line break independent of the file's physical newlines.
Break,
/// RGB tint for the following text.
Color([u8; 3]),
/// Closes a color span.
EndColor,
/// Line spacing as a percentage.
Interleave(u16),
}
/// One entry in a help command table, in its original CP1251 encoding.
#[derive(Debug, PartialEq, Eq)]
pub struct HelpBinding {
/// Command identifier as read from a `.man` file.
pub command: String,
/// Localized description from `Command.dsc`.
pub description: Vec<u8>,
/// Modifier and primary key labels from `Scancode.dsc`.
pub keys: [Vec<u8>; 2],
}
/// Resource-backed pages that are available before any messages have arrived.
#[derive(Debug)]
pub struct HelpResources {
/// None for maps without a `Mistips.mis` file.
pub mission: Option<Vec<MissionTip>>,
/// Battle suit, warbot, bunker/MCU, and additional controls, in native order.
pub controls: [Vec<HelpBinding>; 4],
}
impl HelpResources {
/// Loads the selected mission's tips and the original help bindings.
/// The alternate input profile reads the `_d.man` variants.
pub fn load(vfs: &dyn Vfs, mission: &str, alternate_controls: bool) -> Result<Self, String> {
let mission_directory = mission
.rsplit_once(['/', '\\'])
.map_or("", |(directory, _)| directory);
let tips = if mission_directory.is_empty() {
"Mistips.mis".into()
} else {
format!("{mission_directory}/Mistips.mis")
};
let path = normalize_relative(tips.as_bytes(), PathPolicy::StrictLegacy)
.map_err(|error| error.to_string())?;
let mission = match vfs.read(&path) {
Ok(bytes) => Some(parse_tips(&bytes)?),
Err(VfsError::NotFound(_)) => None,
Err(error) => return Err(error.to_string()),
};
let commands = read(vfs, "Command.dsc")?;
let scancodes = read(vfs, "Scancode.dsc")?;
let commands = descriptions(&commands);
let scancodes = descriptions(&scancodes);
let mut controls = std::array::from_fn(|_| Vec::new());
for (section, base) in controls.iter_mut().zip(CONTROL_TABLES) {
let suffix = if alternate_controls { "_d" } else { "" };
let path = format!("{base}{suffix}.man");
let data = read(vfs, &path)?;
*section = control_table(&data, &commands, &scancodes)
.map_err(|error| format!("{path}: {error}"))?;
}
Ok(Self { mission, controls })
}
}
fn parse_tips(mut input: &[u8]) -> Result<Vec<MissionTip>, String> {
let mut output = Vec::new();
while let Some(start) = input.windows(2).position(|pair| pair == b"<<") {
if start != 0 {
output.push(MissionTip::Text(input[..start].to_vec()));
}
input = &input[start + 2..];
let end = input
.windows(2)
.position(|pair| pair == b">>")
.ok_or("unterminated mission advice directive")?;
let command = std::str::from_utf8(&input[..end])
.map_err(|_| "mission advice directive is outside ASCII")?;
output.push(parse_tip_directive(command)?);
input = &input[end + 2..];
}
if !input.is_empty() {
output.push(MissionTip::Text(input.to_vec()));
}
Ok(output)
}
fn parse_tip_directive(command: &str) -> Result<MissionTip, String> {
if command == "br" {
return Ok(MissionTip::Break);
}
if command == "/color" {
return Ok(MissionTip::EndColor);
}
if let Some(value) = command.strip_prefix("interleave=") {
return value
.parse()
.map(MissionTip::Interleave)
.map_err(|_| format!("invalid mission advice spacing {value}"));
}
if let Some(value) = command.strip_prefix("color=") {
let channels = value
.split(',')
.map(str::parse)
.collect::<Result<Vec<u8>, _>>();
if let Ok(channels) = channels {
if let Ok(rgb) = channels.try_into() {
return Ok(MissionTip::Color(rgb));
}
}
return Err(format!("invalid mission advice color {value}"));
}
Err(format!("unknown mission advice directive {command}"))
}
fn descriptions(input: &[u8]) -> BTreeMap<&[u8], &[u8]> {
input
.split(|&byte| byte == b'\n')
.map(<[u8]>::trim_ascii)
.filter(|line| line.starts_with(b"SCAN_") || line.starts_with(b"CMD_"))
.map(|line| {
let end = line
.iter()
.position(u8::is_ascii_whitespace)
.unwrap_or(line.len());
(&line[..end], line[end..].trim_ascii())
})
.collect()
}
fn control_table(
input: &[u8],
commands: &BTreeMap<&[u8], &[u8]>,
scancodes: &BTreeMap<&[u8], &[u8]>,
) -> Result<Vec<HelpBinding>, String> {
input
.split(|&byte| byte == b'\n')
.map(<[u8]>::trim_ascii)
.filter(|line| !line.is_empty())
.map(|line| {
let mut fields = line
.split(u8::is_ascii_whitespace)
.filter(|part| !part.is_empty());
let (Some(command), Some(modifier), Some(key), None) =
(fields.next(), fields.next(), fields.next(), fields.next())
else {
return Err("expected command, modifier, and scancode".into());
};
let description = description_field(commands, command)?;
let keys = [
description_field(scancodes, modifier)?,
description_field(scancodes, key)?,
];
let command = std::str::from_utf8(command)
.map_err(|_| "command identifier is outside ASCII")?
.to_owned();
Ok(HelpBinding {
command,
description,
keys,
})
})
.collect()
}
fn description_field(
records: &BTreeMap<&[u8], &[u8]>,
identifier: &[u8],
) -> Result<Vec<u8>, String> {
records
.get(identifier)
.map(|&value| value.to_vec())
.ok_or_else(|| {
format!(
"missing help description for {}",
String::from_utf8_lossy(identifier)
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn advice_preserves_cp1251_and_explicit_breaks() {
assert_eq!(
parse_tips(b"<<interleave=150>><<color=255,0,0>>\xcd\xe0<</color>><<br>>").unwrap(),
[
MissionTip::Interleave(150),
MissionTip::Color([255, 0, 0]),
MissionTip::Text(vec![0xcd, 0xe0]),
MissionTip::EndColor,
MissionTip::Break,
]
);
assert!(parse_tips(b"<<color=255,0>>").is_err());
assert!(parse_tips(b"unfinished <<br").is_err());
}
#[test]
#[ignore = "requires licensed corpus"]
fn resolves_stock_fireline_help_and_f1_from_game_files() {
let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
let vfs = fparkan_vfs::DirectoryVfs::new(root);
let help = HelpResources::load(
&vfs,
"MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma",
false,
)
.unwrap();
assert!(matches!(
help.mission.unwrap().first(),
Some(MissionTip::Interleave(150))
));
assert_eq!(help.controls.each_ref().map(Vec::len), [8, 13, 8, 44]);
let help_key = help.controls[3]
.iter()
.find(|binding| binding.command == "CMD_HELP")
.unwrap();
assert_eq!(help_key.keys, [vec![], b"F1".to_vec()]);
assert!(!help_key.description.is_empty());
HelpResources::load(
&vfs,
"MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma",
true,
)
.unwrap();
let prefix = normalize_relative(b"MISSIONS", PathPolicy::StrictLegacy).unwrap();
let mut documents = 0;
for entry in vfs.list(&prefix).unwrap() {
if entry
.path
.as_bytes()
.rsplit(|&byte| byte == b'/')
.next()
.is_some_and(|name| name.eq_ignore_ascii_case(b"mistips.mis"))
{
let bytes = vfs.read(&entry.path).unwrap();
parse_tips(&bytes)
.unwrap_or_else(|error| panic!("{}: {error}", entry.path.as_str()));
documents += 1;
}
}
assert!(documents > 1);
}
}
|