aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock1
-rw-r--r--README.md2
-rw-r--r--apps/fparkan-game/src/main.rs6
-rw-r--r--apps/fparkan-game/src/mission_help.rs228
-rw-r--r--apps/fparkan-game/src/mission_hints.rs6
-rw-r--r--apps/fparkan-game/src/mission_notices.rs13
-rw-r--r--apps/fparkan-game/src/mission_overlay.rs23
-rw-r--r--crates/fparkan-assets/Cargo.toml1
-rw-r--r--crates/fparkan-assets/src/help_screen.rs432
-rw-r--r--crates/fparkan-assets/src/lib.rs1
-rw-r--r--crates/fparkan-assets/src/mission_pager.rs108
-rw-r--r--crates/fparkan-font/src/bitmap.rs5
-rw-r--r--docs/appendices/knowledge-boundaries.md3
-rw-r--r--docs/tomes/06-behavior.md12
14 files changed, 787 insertions, 54 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 696ba441..d17f0784 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -469,6 +469,7 @@ version = "0.1.0"
name = "fparkan-assets"
version = "0.1.0"
dependencies = [
+ "encoding_rs",
"fparkan-binary",
"fparkan-font",
"fparkan-material",
diff --git a/README.md b/README.md
index a46805bf..3cff0015 100644
--- a/README.md
+++ b/README.md
@@ -46,6 +46,8 @@ cargo run --release -p fparkan-game -- `
фиксированной позы или фазы материала тоже включают этот режим.
При оконном запуске в Windows загрузчик показывает стадию подготовки миссии
и закрывается после первого кадра игры.
+`F1` открывает справку с советами миссии, таблицей управления и журналом
+полных сообщений. В одиночной миссии справка ставит игру на паузу.
Если в одиночной миссии найден один герой с точкой `CameraCenter`, окно
открывается с видом из его кабины. Стрелки двигают героя вперёд, назад и
вбок. Мышь поворачивает корпус по горизонтали и наклоняет взгляд по
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 507a45b0..9fd8e667 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -17,6 +17,8 @@ use control_effects::advance_control_effect_instances;
mod damage_visibility;
mod debris;
mod destruction_effects;
+#[cfg(windows)]
+mod mission_help;
mod mission_hints;
mod mission_loading;
mod mission_notices;
@@ -12350,6 +12352,10 @@ impl ApplicationHandler for StaticVulkanApp {
if Some(window_id) != self.window_id {
return;
}
+ #[cfg(windows)]
+ if self.handle_mission_help_event(&event) {
+ return;
+ }
match event {
WindowEvent::CloseRequested => {
self.complete(event_loop);
diff --git a/apps/fparkan-game/src/mission_help.rs b/apps/fparkan-game/src/mission_help.rs
new file mode 100644
index 00000000..78b0474e
--- /dev/null
+++ b/apps/fparkan-game/src/mission_help.rs
@@ -0,0 +1,228 @@
+//! Window and Vulkan integration for the in-mission help terminal.
+
+use super::{
+ append_environment_gradient_material, append_environment_range, environment_vertex,
+ quad_indices, screen_tl_quad_vertices_pixels, world_pipeline_state, DirectoryVfs,
+ EnvironmentGpuRange, Instant, LegacyBlendMode, LegacyDepthMode, StaticPreviewScene,
+ StaticVulkanApp, VulkanSmokeRenderer, VulkanStaticMesh, VulkanStaticTexture,
+};
+use fparkan_assets::help_screen::{HelpAction, HelpLabels, HelpScreen, EXTENT};
+use fparkan_platform_winit::text::StringResources;
+use std::path::Path;
+use winit::{
+ event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent},
+ keyboard::{KeyCode, PhysicalKey},
+};
+
+pub(super) struct MissionHelp {
+ range: EnvironmentGpuRange,
+ screen: HelpScreen,
+ pause_before: Option<bool>,
+ dirty: bool,
+ cursor: [f32; 2],
+}
+
+impl MissionHelp {
+ pub(super) fn load(
+ root: &Path,
+ mission: &str,
+ preview: &mut StaticPreviewScene,
+ ) -> Result<Self, String> {
+ let strings = StringResources::open(&root.join("iron3d.dll"))?;
+ let read = |id| {
+ strings
+ .get(id)
+ .ok_or_else(|| format!("missing help string {id:#06x}"))
+ };
+ let labels = HelpLabels {
+ tabs: [read(0x13df)?, read(0x13e0)?, read(0x13e2)?],
+ controls: [read(0x1813)?, read(0x1811)?, read(0x1812)?, read(0x1814)?],
+ common_keys: read(0x1841)?,
+ game_menu_hint: read(0x1842)?,
+ empty_journal: read(0x1817)?,
+ message_number: read(0x1818)?,
+ };
+ let screen = HelpScreen::load(&DirectoryVfs::new(root), mission, labels)?;
+ let material = append_environment_gradient_material(&mut preview.materials)?;
+ preview.materials[material].screen_tl = true;
+ preview.materials[material].sky_far_depth = false;
+ preview.materials[material].texture =
+ texture(vec![0; (EXTENT[0] * EXTENT[1] * 4) as usize]);
+ let range = append_environment_range(
+ &mut preview.mesh,
+ material,
+ vec![environment_vertex([0.0; 3], [1.0; 3], [0.0; 2]); 4],
+ quad_indices(1)?,
+ world_pipeline_state(LegacyBlendMode::SourceAlpha, LegacyDepthMode::Disabled),
+ )?;
+ Ok(Self {
+ range,
+ screen,
+ pause_before: None,
+ dirty: true,
+ cursor: [f32::NAN; 2],
+ })
+ }
+
+ pub(super) fn post(&mut self, sender: &str, body: &str) -> Result<(), String> {
+ self.screen.post(sender, body)?;
+ self.dirty = true;
+ Ok(())
+ }
+
+ pub(super) fn range_index(&self) -> usize {
+ self.range.range_index
+ }
+
+ pub(super) fn draw(
+ &mut self,
+ renderer: &mut VulkanSmokeRenderer,
+ mesh: &mut VulkanStaticMesh,
+ viewport: [f32; 2],
+ ) -> Result<(), String> {
+ let visible = self.pause_before.is_some();
+ if visible {
+ if self.dirty {
+ let image = self.screen.paint()?;
+ renderer
+ .update_material_texture(self.range.material_index, 0, &texture(image.rgba8))
+ .map_err(|error| error.to_string())?;
+ self.dirty = false;
+ }
+ let half = viewport.map(|dimension| dimension * 0.5);
+ let vertices = screen_tl_quad_vertices_pixels(
+ half,
+ half[0],
+ half[1],
+ viewport,
+ [1.0; 3],
+ 1.0,
+ [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]],
+ );
+ mesh.vertices[self.range.vertex_start..self.range.vertex_start + vertices.len()]
+ .copy_from_slice(&vertices);
+ }
+ renderer
+ .set_draw_range_index_count(self.range.range_index, if visible { 6 } else { 0 })
+ .map_err(|error| error.to_string())
+ }
+}
+
+impl StaticVulkanApp {
+ pub(super) fn handle_mission_help_event(&mut self, event: &WindowEvent) -> bool {
+ if let WindowEvent::KeyboardInput { event, .. } = event {
+ if let PhysicalKey::Code(key) = event.physical_key {
+ return self.handle_help_key(key, event.state, event.repeat);
+ }
+ }
+ let Some(help) = &mut self.overlay.help else {
+ return false;
+ };
+ if let WindowEvent::CursorMoved { position, .. } = event {
+ if let Some(window) = &self.window {
+ let size = window.inner_size();
+ if size.width != 0 && size.height != 0 {
+ help.cursor = [
+ position.x as f32 * 640.0 / size.width as f32,
+ position.y as f32 * 480.0 / size.height as f32,
+ ];
+ }
+ }
+ }
+ if help.pause_before.is_none() {
+ return false;
+ }
+ let action = match event {
+ WindowEvent::MouseInput {
+ state: ElementState::Pressed,
+ button: MouseButton::Left,
+ ..
+ } => HelpScreen::hit_test(help.cursor),
+ WindowEvent::MouseWheel { delta, .. } => {
+ let y = match delta {
+ MouseScrollDelta::LineDelta(_, y) => *y,
+ MouseScrollDelta::PixelDelta(position) => position.y as f32,
+ };
+ (y != 0.0).then(|| HelpAction::Scroll(-2 * y.signum() as i32))
+ }
+ _ => None,
+ };
+ if let Some(action) = action {
+ self.navigate_mission_help(action);
+ }
+ matches!(
+ event,
+ WindowEvent::KeyboardInput { .. }
+ | WindowEvent::MouseInput { .. }
+ | WindowEvent::MouseWheel { .. }
+ | WindowEvent::CursorMoved { .. }
+ )
+ }
+
+ fn handle_help_key(&mut self, key: KeyCode, state: ElementState, repeat: bool) -> bool {
+ let Some(help) = &mut self.overlay.help else {
+ return false;
+ };
+ let open = help.pause_before.is_some();
+ if key == KeyCode::F1 {
+ if state == ElementState::Pressed && !repeat {
+ if open {
+ self.navigate_mission_help(HelpAction::Close);
+ } else if self.factory_menu.is_none() {
+ help.pause_before = Some(self.mission_paused);
+ self.player_fire_held = false;
+ self.player_fire_pressed = false;
+ self.pressed_keys.clear();
+ self.set_mission_paused_at(true, Instant::now());
+ self.schedule_next_redraw();
+ }
+ }
+ return true;
+ }
+ if !open {
+ return false;
+ }
+ if state == ElementState::Pressed {
+ let action = match key {
+ KeyCode::ArrowUp => Some(HelpAction::Scroll(-1)),
+ KeyCode::ArrowDown => Some(HelpAction::Scroll(1)),
+ KeyCode::Tab | KeyCode::ArrowRight | KeyCode::ArrowLeft => {
+ if help.screen.cycle(key == KeyCode::ArrowLeft) {
+ help.dirty = true;
+ self.schedule_next_redraw();
+ }
+ None
+ }
+ _ => None,
+ };
+ if let Some(action) = action {
+ self.navigate_mission_help(action);
+ }
+ }
+ true
+ }
+
+ fn navigate_mission_help(&mut self, action: HelpAction) {
+ let Some(help) = &mut self.overlay.help else {
+ return;
+ };
+ if action == HelpAction::Close {
+ if let Some(paused) = help.pause_before.take() {
+ self.set_mission_paused_at(paused, Instant::now());
+ self.schedule_next_redraw();
+ }
+ } else if help.screen.navigate(action) {
+ help.dirty = true;
+ self.schedule_next_redraw();
+ }
+ }
+}
+
+fn texture(rgba8: Vec<u8>) -> VulkanStaticTexture {
+ VulkanStaticTexture {
+ width: EXTENT[0],
+ height: EXTENT[1],
+ rgba8,
+ mip_levels: Vec::new(),
+ }
+}
diff --git a/apps/fparkan-game/src/mission_hints.rs b/apps/fparkan-game/src/mission_hints.rs
index ac7cb008..47ecc25c 100644
--- a/apps/fparkan-game/src/mission_hints.rs
+++ b/apps/fparkan-game/src/mission_hints.rs
@@ -92,7 +92,7 @@ impl MissionHints {
})
}
- pub(super) fn post(&mut self, index: u32, clock: u32) -> Result<(), String> {
+ pub(super) fn post(&mut self, index: u32, clock: u32) -> Result<(&str, &str), String> {
let messages = self
.messages
.as_ref()
@@ -121,13 +121,13 @@ impl MissionHints {
if sender.is_none() {
eprintln!("sim_coverage mission_text_unavailable=1 sender={sender_id} index={index}");
}
- self.pending = Some(PagerMessage {
+ let pending = self.pending.insert(PagerMessage {
index,
sender: sender.unwrap_or_default(),
body,
posted_ms: clock,
});
- Ok(())
+ Ok((&pending.sender, &pending.body))
}
pub(super) fn toggle_current(&mut self) {
diff --git a/apps/fparkan-game/src/mission_notices.rs b/apps/fparkan-game/src/mission_notices.rs
index 6b876e3d..b633856c 100644
--- a/apps/fparkan-game/src/mission_notices.rs
+++ b/apps/fparkan-game/src/mission_notices.rs
@@ -27,10 +27,17 @@ impl StaticVulkanApp {
.as_mut()
.ok_or_else(|| "mission text resources unavailable".to_string())
.and_then(|hints| hints.post(index, clock_ms));
- if let Err(error) = posted {
- eprintln!(
+ match posted {
+ Ok((sender, body)) => {
+ if let Some(help) = &mut self.overlay.help {
+ if let Err(error) = help.post(sender, body) {
+ eprintln!("mission_help_message_unavailable index={index} reason={error}");
+ }
+ }
+ }
+ Err(error) => eprintln!(
"sim_coverage mission_text_unavailable=1 index={index} reason={error}"
- );
+ ),
}
}
#[cfg(not(windows))]
diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs
index 7c8c54d6..e692e5b5 100644
--- a/apps/fparkan-game/src/mission_overlay.rs
+++ b/apps/fparkan-game/src/mission_overlay.rs
@@ -3,7 +3,7 @@ use super::{
satellite_map::SatelliteMap, StaticPreviewScene, StaticVulkanApp,
};
#[cfg(windows)]
-use super::{mission_hints::MissionHints, weapon_hud::WeaponHud};
+use super::{mission_help::MissionHelp, mission_hints::MissionHints, weapon_hud::WeaponHud};
use fparkan_runtime::{
cockpit_altimeter::cockpit_altimeter,
radar::{cockpit_radar_period, cockpit_range_readout},
@@ -21,6 +21,8 @@ pub(super) struct MissionOverlay {
#[cfg(windows)]
pub(super) hints: Option<MissionHints>,
#[cfg(windows)]
+ pub(super) help: Option<MissionHelp>,
+ #[cfg(windows)]
weapons: Option<WeaponHud>,
}
@@ -74,6 +76,15 @@ impl MissionOverlay {
None
})
});
+ #[cfg(windows)]
+ let help = cockpit.and_then(|_| {
+ MissionHelp::load(root, mission, preview)
+ .map(Some)
+ .unwrap_or_else(|error| {
+ eprintln!("mission_help_unavailable reason={error}");
+ None
+ })
+ });
#[cfg(not(windows))]
let _ = weapon_rows;
Self {
@@ -83,6 +94,8 @@ impl MissionOverlay {
#[cfg(windows)]
hints,
#[cfg(windows)]
+ help,
+ #[cfg(windows)]
weapons,
}
}
@@ -121,6 +134,10 @@ impl MissionOverlay {
if let Some(weapons) = &self.weapons {
remove(weapons.range_index(), ranges, counts);
}
+ #[cfg(windows)]
+ if let Some(help) = &self.help {
+ remove(help.range_index(), ranges, counts);
+ }
}
}
@@ -194,6 +211,10 @@ impl StaticVulkanApp {
});
weapons.draw(renderer, &mut self.mesh, frame.viewport, current)?;
}
+ #[cfg(windows)]
+ if let Some(help) = &mut self.overlay.help {
+ help.draw(renderer, &mut self.mesh, frame.viewport)?;
+ }
Ok(())
}
}
diff --git a/crates/fparkan-assets/Cargo.toml b/crates/fparkan-assets/Cargo.toml
index 663da7c5..a5e65591 100644
--- a/crates/fparkan-assets/Cargo.toml
+++ b/crates/fparkan-assets/Cargo.toml
@@ -6,6 +6,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
+encoding_rs = "0.8"
fparkan-binary = { path = "../fparkan-binary" }
fparkan-font = { path = "../fparkan-font" }
fparkan-material = { path = "../fparkan-material" }
diff --git a/crates/fparkan-assets/src/help_screen.rs b/crates/fparkan-assets/src/help_screen.rs
new file mode 100644
index 00000000..c0e6a950
--- /dev/null
+++ b/crates/fparkan-assets/src/help_screen.rs
@@ -0,0 +1,432 @@
+//! The mission terminal's text pages and original atlas controls.
+
+use crate::{
+ game_font::{load_game_font, BitmapFont},
+ help_resources::{HelpBinding, HelpResources, MissionTip},
+ mission_pager::{copy_sprite, scale, UiFrame},
+ ui_sprite::load_ui_sprites,
+ RgbaImage,
+};
+use encoding_rs::WINDOWS_1251;
+use fparkan_vfs::Vfs;
+
+/// Drawable extent used to compose the original font profile.
+pub const EXTENT: [u32; 2] = [800, 600];
+const PAGE: [u32; 4] = [15, 35, 637, 430];
+const TAB_X: [u32; 3] = [2, 199, 396];
+const CLOSE: [u32; 4] = [593, 2, 640, 23];
+const SCROLL: [[u32; 4]; 2] = [[526, 458, 576, 477], [576, 458, 626, 477]];
+const WHITE: [u8; 3] = [255; 3];
+const GREEN: [u8; 3] = [0, 255, 0];
+const YELLOW: [u8; 3] = [255, 255, 0];
+
+/// A hit in the native 640×480 coordinate space.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum HelpAction {
+ /// Selects the specified native tab.
+ Tab(usize),
+ /// Scrolls a number of lines.
+ Scroll(i32),
+ /// Closes the terminal.
+ Close,
+}
+
+/// Strings read from the game's localized table.
+pub struct HelpLabels {
+ /// Mission, controls and journal tab captions.
+ pub tabs: [String; 3],
+ /// Headings of the four control tables.
+ pub controls: [String; 4],
+ /// Heading of the commonly used commands.
+ pub common_keys: String,
+ /// Localized sentence with the game-menu key placeholder.
+ pub game_menu_hint: String,
+ /// Journal text before any messages are received.
+ pub empty_journal: String,
+ /// Localized format for a journal sequence number.
+ pub message_number: String,
+}
+
+/// Original UI page data, independent of the window and GPU backend.
+pub struct HelpScreen {
+ font: BitmapFont,
+ frame: UiFrame,
+ tab: [RgbaImage; 3],
+ buttons: [RgbaImage; 3],
+ icons: [RgbaImage; 3],
+ labels: HelpLabels,
+ pages: [Vec<Row>; 3],
+ tab_index: usize,
+ scroll: [usize; 3],
+ message_count: usize,
+}
+
+#[derive(Default)]
+struct Row {
+ spans: Vec<(Vec<u8>, [u8; 3])>,
+ width: u32,
+ advance: u32,
+}
+
+impl HelpScreen {
+ /// Prepares original mission and keyboard help pages and their shared frame.
+ pub fn load(vfs: &dyn Vfs, mission: &str, labels: HelpLabels) -> Result<Self, String> {
+ let data = HelpResources::load(vfs, mission, false)?;
+ let mut screen = Self {
+ font: load_game_font(vfs)?,
+ frame: UiFrame::load(vfs)?,
+ tab: load_ui_sprites(
+ vfs,
+ "ui/compaund.cfg",
+ ["ccres_ending_text", "ccres_body_text", "ccres_ending_stub"],
+ )?,
+ buttons: load_ui_sprites(
+ vfs,
+ "ui/compaund.cfg",
+ [
+ "ccres_exit_button_normal",
+ "ccres_long_button_off",
+ "ccres_long_button_normal",
+ ],
+ )?,
+ icons: load_ui_sprites(
+ vfs,
+ "ui/hq.cfg",
+ ["exit_icon", "scroll_down_icon", "scroll_up_icon"],
+ )?,
+ labels,
+ pages: Default::default(),
+ tab_index: 0,
+ scroll: [0; 3],
+ message_count: 0,
+ };
+ screen.pages = [
+ screen.mission_rows(data.mission)?,
+ screen.control_rows(data.controls)?,
+ vec![
+ screen.row(150)?,
+ screen.text_row(&screen.labels.empty_journal, YELLOW)?,
+ ],
+ ];
+ Ok(screen)
+ }
+
+ /// Adds the complete body to the journal before the pager shortens it.
+ pub fn post(&mut self, sender: &str, body: &str) -> Result<(), String> {
+ let count = self.message_count + 1;
+ let header = self.labels.message_number.replace("%d", &count.to_string());
+ let mut rows = Vec::new();
+ if self.message_count == 0 {
+ rows.push(self.row(150)?);
+ }
+ rows.push(self.text_row(&format!("{header} {sender}"), YELLOW)?);
+ rows.extend(
+ self.font
+ .wrap_pager_lines(body, self.wrap_width() as u16)?
+ .iter()
+ .map(|line| self.text_row(line, WHITE))
+ .collect::<Result<Vec<_>, _>>()?,
+ );
+ rows.push(self.row(150)?);
+ let journal = &mut self.pages[2];
+ if self.message_count == 0 {
+ journal.clear();
+ }
+ journal.extend(rows);
+ self.message_count = count;
+ Ok(())
+ }
+
+ /// Changes the selected tab or scroll position and reports a redraw.
+ pub fn navigate(&mut self, action: HelpAction) -> bool {
+ match action {
+ HelpAction::Tab(index) if index < self.pages.len() => {
+ let changed = self.tab_index != index;
+ self.tab_index = index;
+ changed
+ }
+ HelpAction::Scroll(lines) => {
+ let before = self.scroll[self.tab_index];
+ let position = before.saturating_add_signed(lines as isize);
+ self.scroll[self.tab_index] = position.min(self.last_scroll());
+ before != self.scroll[self.tab_index]
+ }
+ _ => false,
+ }
+ }
+
+ /// Advances or reverses the tab order with wraparound.
+ pub fn cycle(&mut self, reverse: bool) -> bool {
+ let offset = if reverse { self.pages.len() - 1 } else { 1 };
+ self.navigate(HelpAction::Tab(
+ (self.tab_index + offset) % self.pages.len(),
+ ))
+ }
+
+ /// Looks up a tab or terminal control from a normalized 640×480 point.
+ pub fn hit_test([x, y]: [f32; 2]) -> Option<HelpAction> {
+ let hit =
+ |[l, t, r, b]: [u32; 4]| x >= l as f32 && x < r as f32 && y >= t as f32 && y < b as f32;
+ for (index, l) in TAB_X.into_iter().enumerate() {
+ if hit([l, 2, l + 197, 23]) {
+ return Some(HelpAction::Tab(index));
+ }
+ }
+ if hit(CLOSE) {
+ return Some(HelpAction::Close);
+ }
+ SCROLL
+ .into_iter()
+ .position(hit)
+ .map(|index| HelpAction::Scroll(if index == 0 { 1 } else { -1 }))
+ }
+
+ /// Paints the selected page from the original UI parts and game font.
+ pub fn paint(&self) -> Result<RgbaImage, String> {
+ let [width, height] = EXTENT;
+ let mut image = RgbaImage {
+ width,
+ height,
+ rgba8: vec![0; (width * height * 4) as usize],
+ };
+ for pixel in image.rgba8.chunks_exact_mut(4) {
+ pixel[3] = 255;
+ }
+ self.frame
+ .paint(&mut image, [2, 24, 637, 454], [0, 64, 0, 255]);
+ for (index, left) in TAB_X.into_iter().enumerate() {
+ let tint = if index == self.tab_index {
+ WHITE
+ } else {
+ GREEN
+ };
+ let [leading, body, ending] = &self.tab;
+ sprite(&mut image, leading, [left, 2, left + 5, 21], WHITE);
+ sprite(&mut image, body, [left + 5, 2, left + 184, 21], WHITE);
+ sprite(&mut image, ending, [left + 184, 2, left + 189, 21], WHITE);
+ let text = encode(&self.labels.tabs[index])?;
+ let width = u32::from(self.font.line_metrics_bytes(&text)?[0]);
+ let center = scale(left + 94);
+ self.text(
+ &mut image,
+ &text,
+ [center.saturating_sub(width / 2), scale(6)],
+ tint,
+ )?;
+ }
+ sprite(&mut image, &self.buttons[0], [593, 2, 640, 21], WHITE);
+ sprite(&mut image, &self.icons[0], [610, 5, 623, 18], WHITE);
+ let start = self.scroll[self.tab_index];
+ let enabled = [start < self.last_scroll(), start > 0];
+ for (index, bounds) in SCROLL.into_iter().enumerate() {
+ let [l, t, _, _] = bounds;
+ sprite(
+ &mut image,
+ &self.buttons[1 + usize::from(enabled[index])],
+ bounds,
+ WHITE,
+ );
+ sprite(
+ &mut image,
+ &self.icons[index + 1],
+ [l + 10, t + 2, l + 40, t + 17],
+ WHITE,
+ );
+ }
+ let mut y = scale(PAGE[1]);
+ let [_, glyph_height] = self.font.line_metrics("")?;
+ for row in &self.pages[self.tab_index][start..] {
+ if y + u32::from(glyph_height) > scale(PAGE[3]) {
+ break;
+ }
+ let mut x = scale(PAGE[0]);
+ for (bytes, color) in &row.spans {
+ self.text(&mut image, bytes, [x, y], *color)?;
+ x += u32::from(self.font.line_metrics_bytes(bytes)?[0]);
+ }
+ y += row.advance;
+ }
+ Ok(image)
+ }
+
+ fn last_scroll(&self) -> usize {
+ let rows = &self.pages[self.tab_index];
+ let visible = scale(PAGE[3]) - scale(PAGE[1]);
+ let mut height = 0;
+ let count = rows
+ .iter()
+ .rev()
+ .take_while(|row| {
+ height += row.advance;
+ height <= visible
+ })
+ .count();
+ rows.len().saturating_sub(count.max(1))
+ }
+
+ fn mission_rows(&self, tips: Option<Vec<MissionTip>>) -> Result<Vec<Row>, String> {
+ let Some(tips) = tips else {
+ return Ok(vec![
+ self.row(100)?,
+ self.text_row("No mission tips", YELLOW)?,
+ self.row(100)?,
+ ]);
+ };
+ let mut rows = Vec::new();
+ let mut color = WHITE;
+ let mut spacing = 100;
+ let mut row = self.row(spacing)?;
+ for token in tips {
+ match token {
+ MissionTip::Break => rows.push(std::mem::replace(&mut row, self.row(spacing)?)),
+ MissionTip::Color(value) => color = value,
+ MissionTip::EndColor => color = WHITE,
+ MissionTip::Interleave(value) => {
+ spacing = value;
+ row.advance = self.row(spacing)?.advance;
+ }
+ MissionTip::Text(bytes) => {
+ for word in bytes
+ .split(u8::is_ascii_whitespace)
+ .filter(|word| !word.is_empty())
+ {
+ let word_width = u32::from(self.font.line_metrics_bytes(word)?[0]);
+ let space = u32::from(self.font.line_metrics_bytes(b" ")?[0]);
+ if row.width + space + word_width > self.wrap_width() && row.width != 0 {
+ rows.push(std::mem::replace(&mut row, self.row(spacing)?));
+ }
+ if row.width != 0 {
+ row.spans.push((vec![b' '], color));
+ row.width += space;
+ }
+ row.spans.push((word.to_vec(), color));
+ row.width += word_width;
+ }
+ }
+ }
+ }
+ if !row.spans.is_empty() {
+ rows.push(row);
+ }
+ Ok(rows)
+ }
+
+ fn control_rows(&self, groups: [Vec<HelpBinding>; 4]) -> Result<Vec<Row>, String> {
+ let mut rows = vec![
+ self.text_row(&self.labels.common_keys, YELLOW)?,
+ self.row(100)?,
+ ];
+ let mut menu_key = &[][..];
+ for command in ["CMD_HELP", "CMD_GAME_MENU", "CMD_JAMES_MISSION_OBJ"] {
+ let entry = groups[3]
+ .iter()
+ .find(|entry| entry.command == command)
+ .ok_or_else(|| format!("missing common help binding {command}"))?;
+ rows.push(self.control_row(entry)?);
+ if command == "CMD_GAME_MENU" {
+ menu_key = &entry.keys[1];
+ }
+ }
+ let (key, _, _) = WINDOWS_1251.decode(menu_key);
+ rows.push(self.text_row(&self.labels.game_menu_hint.replace("%s", &key), WHITE)?);
+ rows.push(self.row(100)?);
+ for (group, title) in groups.iter().zip(&self.labels.controls) {
+ rows.push(self.text_row(title, YELLOW)?);
+ for entry in group {
+ rows.push(self.control_row(entry)?);
+ }
+ rows.push(self.row(150)?);
+ }
+ Ok(rows)
+ }
+
+ fn control_row(&self, entry: &HelpBinding) -> Result<Row, String> {
+ let mut row = self.row(150)?;
+ let mut keys = entry.keys.iter().filter(|key| !key.is_empty());
+ if let Some(key) = keys.next() {
+ let mut label = key.clone();
+ if let Some(second) = keys.next() {
+ label.extend_from_slice(b" + ");
+ label.extend_from_slice(second);
+ }
+ label.extend_from_slice(b" : ");
+ row.spans.push((label, WHITE));
+ }
+ row.spans.push((entry.description.clone(), [230; 3]));
+ Ok(row)
+ }
+
+ fn wrap_width(&self) -> u32 {
+ ((PAGE[2] - PAGE[0]) as f32 * 1.25 * 0.98).round_ties_even() as u32
+ }
+
+ fn row(&self, spacing: u16) -> Result<Row, String> {
+ let [_, height] = self.font.line_metrics("")?;
+ Ok(Row {
+ advance: (u32::from(height) * u32::from(spacing) / 100).max(1),
+ ..Row::default()
+ })
+ }
+
+ fn text_row(&self, text: &str, color: [u8; 3]) -> Result<Row, String> {
+ let mut row = self.row(150)?;
+ row.spans.push((encode(text)?, color));
+ Ok(row)
+ }
+
+ fn text(
+ &self,
+ image: &mut RgbaImage,
+ text: &[u8],
+ [x, y]: [u32; 2],
+ color: [u8; 3],
+ ) -> Result<(), String> {
+ let [w, h] = self.font.line_metrics_bytes(text)?;
+ if w > 0 {
+ let raster = self.font.centered_line_bytes(text, w, h)?;
+ copy_sprite(
+ image,
+ &raster,
+ [x, y, x + raster.width, y + raster.height],
+ [false; 2],
+ color,
+ );
+ }
+ Ok(())
+ }
+}
+
+fn sprite(image: &mut RgbaImage, source: &RgbaImage, rect: [u32; 4], color: [u8; 3]) {
+ copy_sprite(image, source, rect.map(scale), [false; 2], color);
+}
+
+fn encode(text: &str) -> Result<Vec<u8>, String> {
+ let (bytes, _, unmappable) = WINDOWS_1251.encode(text);
+ if unmappable {
+ return Err("help text contains characters outside CP1251".into());
+ }
+ Ok(bytes.into_owned())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn help_hit_targets_select_native_tabs_and_scroll_directions() {
+ assert_eq!(
+ HelpScreen::hit_test([410.0, 10.0]),
+ Some(HelpAction::Tab(2))
+ );
+ assert_eq!(HelpScreen::hit_test([620.0, 10.0]), Some(HelpAction::Close));
+ assert_eq!(
+ HelpScreen::hit_test([540.0, 469.0]),
+ Some(HelpAction::Scroll(1))
+ );
+ assert_eq!(
+ HelpScreen::hit_test([620.0, 469.0]),
+ Some(HelpAction::Scroll(-1))
+ );
+ assert_eq!(HelpScreen::hit_test([300.0, 400.0]), None);
+ }
+}
diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs
index 83231ebb..70e0de6d 100644
--- a/crates/fparkan-assets/src/lib.rs
+++ b/crates/fparkan-assets/src/lib.rs
@@ -37,6 +37,7 @@ mod control_weapon_sound;
mod explosion_profile;
pub mod game_font;
pub mod help_resources;
+pub mod help_screen;
pub mod mission_loader;
pub mod mission_pager;
pub mod object_descriptions;
diff --git a/crates/fparkan-assets/src/mission_pager.rs b/crates/fparkan-assets/src/mission_pager.rs
index 97708880..ba3e7596 100644
--- a/crates/fparkan-assets/src/mission_pager.rs
+++ b/crates/fparkan-assets/src/mission_pager.rs
@@ -14,14 +14,15 @@ const MAX_BODY_LINES: usize = 6;
/// Original frame parts and the gameplay bitmap font.
pub struct MissionPager {
- parts: [RgbaImage; 6],
+ frame: UiFrame,
font: BitmapFont,
}
-impl MissionPager {
- /// Loads the frame and 800×600 font from the installed game.
- pub fn load(vfs: &dyn Vfs) -> Result<Self, String> {
- let parts = load_ui_sprites(
+pub(crate) struct UiFrame([RgbaImage; 6]);
+
+impl UiFrame {
+ pub(crate) fn load(vfs: &dyn Vfs) -> Result<Self, String> {
+ load_ui_sprites(
vfs,
"ui/compaund.cfg",
[
@@ -32,9 +33,16 @@ impl MissionPager {
"ccres_frame_edge_h",
"ccres_frame_edge_v",
],
- )?;
+ )
+ .map(Self)
+ }
+}
+
+impl MissionPager {
+ /// Loads the frame and 800×600 font from the installed game.
+ pub fn load(vfs: &dyn Vfs) -> Result<Self, String> {
Ok(Self {
- parts,
+ frame: UiFrame::load(vfs)?,
font: load_game_font(vfs)?,
})
}
@@ -76,7 +84,8 @@ impl MissionPager {
height: pixels[1],
rgba8: vec![0; (pixels[0] * pixels[1] * 4) as usize],
};
- self.paint_frame(&mut panel, width, height);
+ self.frame
+ .paint(&mut panel, [0, 0, width, height], [0, 128, 0, 128]);
self.paint_text(&mut panel, sender, sender_y, 255)?;
for (index, line) in lines.iter().enumerate() {
self.paint_text(&mut panel, line, first_line_y + index as u32 * advance, 220)?;
@@ -88,8 +97,40 @@ impl MissionPager {
Ok((panel, [x as f32, y as f32, width as f32, height as f32]))
}
- fn paint_frame(&self, panel: &mut RgbaImage, width: u32, height: u32) {
- let [tl, tr, br, bl, horizontal, vertical] = &self.parts;
+ fn paint_text(
+ &self,
+ panel: &mut RgbaImage,
+ text: &str,
+ y: u32,
+ tint: u8,
+ ) -> Result<(), String> {
+ let [w, h] = self.font.line_metrics(text)?;
+ if w == 0 {
+ return Ok(());
+ }
+ let sprite = self.font.centered_line(text, w, h)?;
+ let [x, y] = [scale(8), scale(y)];
+ copy_sprite(
+ panel,
+ &sprite,
+ [x, y, x + sprite.width, y + sprite.height],
+ [false, false],
+ [tint; 3],
+ );
+ Ok(())
+ }
+}
+
+impl UiFrame {
+ pub(crate) fn paint(
+ &self,
+ panel: &mut RgbaImage,
+ [x, y, right, bottom]: [u32; 4],
+ fill: [u8; 4],
+ ) {
+ let [tl, tr, br, bl, horizontal, vertical] = &self.0;
+ let width = right - x;
+ let height = bottom - y;
let middle = [8, 8, width - 8, height - 8];
for (sprite, rect, flip) in [
(tl, [0, 0, 8, 8], [false, false]),
@@ -117,40 +158,25 @@ impl MissionPager {
[false, false],
),
] {
- copy_sprite(panel, sprite, rect.map(scale), flip, 255);
+ let [l, t, r, b] = rect;
+ copy_sprite(
+ panel,
+ sprite,
+ [x + l, y + t, x + r, y + b].map(scale),
+ flip,
+ [255; 3],
+ );
}
let inset = horizontal.height;
- let [left, top, right, bottom] = [inset, inset, width - inset, height - inset].map(scale);
+ let [left, top, right, bottom] =
+ [x + inset, y + inset, right - inset, bottom - inset].map(scale);
for y in top..bottom {
for x in left..right {
let dest = offset(panel.width, x, y);
- source_over(&mut panel.rgba8[dest..dest + 4], &[0, 128, 0, 128]);
+ source_over(&mut panel.rgba8[dest..dest + 4], &fill);
}
}
}
-
- fn paint_text(
- &self,
- panel: &mut RgbaImage,
- text: &str,
- y: u32,
- tint: u8,
- ) -> Result<(), String> {
- let [w, h] = self.font.line_metrics(text)?;
- if w == 0 {
- return Ok(());
- }
- let sprite = self.font.centered_line(text, w, h)?;
- let [x, y] = [scale(8), scale(y)];
- copy_sprite(
- panel,
- &sprite,
- [x, y, x + sprite.width, y + sprite.height],
- [false, false],
- tint,
- );
- Ok(())
- }
}
fn panel_rows(advance: u32, lines: u32, footer: bool) -> [u32; 3] {
@@ -162,16 +188,16 @@ fn panel_rows(advance: u32, lines: u32, footer: bool) -> [u32; 3] {
]
}
-fn scale(coordinate: u32) -> u32 {
+pub(crate) fn scale(coordinate: u32) -> u32 {
(f64::from(coordinate) * FONT_SCALE).round_ties_even() as u32
}
-fn copy_sprite(
+pub(crate) fn copy_sprite(
panel: &mut RgbaImage,
sprite: &RgbaImage,
[left, top, right, bottom]: [u32; 4],
[flip_x, flip_y]: [bool; 2],
- tint: u8,
+ tint: [u8; 3],
) {
for y in top..bottom.min(panel.height) {
let mut v = (y - top) * sprite.height / (bottom - top);
@@ -187,8 +213,8 @@ fn copy_sprite(
let dest = offset(panel.width, x, y);
let mut texel = [0; 4];
texel.copy_from_slice(&sprite.rgba8[src..src + 4]);
- for component in &mut texel[..3] {
- *component = (u16::from(*component) * u16::from(tint) / 255) as u8;
+ for (component, weight) in texel[..3].iter_mut().zip(tint) {
+ *component = (u16::from(*component) * u16::from(weight) / 255) as u8;
}
source_over(&mut panel.rgba8[dest..dest + 4], &texel);
}
diff --git a/crates/fparkan-font/src/bitmap.rs b/crates/fparkan-font/src/bitmap.rs
index 0110de40..5a919dcd 100644
--- a/crates/fparkan-font/src/bitmap.rs
+++ b/crates/fparkan-font/src/bitmap.rs
@@ -137,6 +137,11 @@ impl BitmapFont {
if unmappable {
return Err("game text contains characters outside CP1251".into());
}
+ self.line_metrics_bytes(&bytes)
+ }
+
+ /// Measures an original CP1251 string in atlas pixels.
+ pub fn line_metrics_bytes(&self, bytes: &[u8]) -> Result<[u16; 2], String> {
let width = bytes.iter().map(|&byte| self.advance(byte)).sum::<usize>();
let width = u16::try_from(width).map_err(|_| "game text is too wide")?;
let height = u16::try_from(self.glyph_height).map_err(|_| "game font is too tall")?;
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 30b13d62..ba93a1f3 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -57,7 +57,8 @@ authoring API без динамического подтверждения.
`live_basement_stub` отмечает сценарную стройку, для которой вырез отклонён.
Окно обновляет поверхность для игрока и тени. Нативные пересечения новых
фундаментов, удаление вырезов и поверхность для симуляции без окна открыты.
-`mission_message_ui_stub` отмечает открытые историю подсказок и панель целей.
+`mission_message_ui_stub` отмечает открытую панель целей и неперенесённые
+типы сообщений. Сценарные подсказки уже попадают в журнал справки по F1.
`mission_outcome_display_approx` отмечает временную надпись об исходе в Windows.
Оформление оригинала и команды перезапуска и загрузки ещё открыты.
`mission_text_display_approx` отмечает открытые варианты раскладки пейджера
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 83fc6fb1..cac5c755 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -3403,9 +3403,8 @@ FParkan применяет эту формулу к ручному полёту
Углы и кромки читаются из `ui/compaund.cfg` и страницы `ui_menu`.
В `iron3d.dll` по RVA `0x802a0` вычисляются координаты текста и рамки,
а вспомогательная функция по RVA `0x9af40` собирает края и полупрозрачный
-зелёный фон. Для `F1` используется строка с ID `0x1840`. Экран полного
-текста по этой клавише ещё открыт. Файл `Mistips.mis` относится к экрану
-сведений о миссии, его путь собирается по RVA `0x695f0`.
+зелёный фон. Подсказка о полном тексте по `F1` берётся из строки с ID
+`0x1840`.
### Справка в миссии
@@ -3431,8 +3430,11 @@ FParkan применяет эту формулу к ручному полёту
(2, 24)–(637, 454), содержимое страницы ограничено областью
(15, 35)–(637, 430).
-FParkan разбирает файлы советов и таблицы управления. Показ справки
-и её журнал ещё предстоит подключить.
+В FParkan F1 открывает эту справку в одиночной миссии. Клавиши ←/→ и
+щелчки по вкладкам меняют страницу, колёсико прокручивает текст. Журнал получает
+сообщение из сценария до того, как пейджер ограничит его шестью строками.
+Форматирование таблицы клавиш и состояния кнопок ещё требуют сверки
+в оригинальном окне.
### Состояние героя и базы