workspaceify
This commit is contained in:
@@ -0,0 +1,396 @@
|
||||
use color::Rgba8;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// The visual representation of a single board cell.
|
||||
///
|
||||
/// `Glyph` holds everything needed to draw one cell on screen: which tile
|
||||
/// index to display and what colors to use. It is stored per-cell (not per
|
||||
/// archetype), so individual cells can vary their appearance independently.
|
||||
///
|
||||
/// `tile` is a left-to-right, top-to-bottom index into the board's bitmap
|
||||
/// font. For the default CP437 font this matches the ASCII/CP437 code point.
|
||||
///
|
||||
/// `Glyph` values come from the map file palette and are set at load time.
|
||||
/// The player is the only entity whose glyph is hardcoded at runtime
|
||||
/// (see [`Glyph::player`]).
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Glyph {
|
||||
/// Tile index into the board's bitmap font (left-to-right, top-to-bottom).
|
||||
pub tile: u32,
|
||||
/// Foreground color, applied to non-background pixels of the tile.
|
||||
pub fg: Rgba8,
|
||||
/// Background color, drawn as a filled rectangle behind the tile.
|
||||
pub bg: Rgba8,
|
||||
}
|
||||
|
||||
impl Hash for Glyph {
|
||||
/// Hash via packed u32 representations so the impl stays in sync with Eq.
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.tile.hash(state);
|
||||
self.fg.to_u32().hash(state);
|
||||
self.bg.to_u32().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Glyph {
|
||||
/// Returns the glyph used to render the player: tile 64 (`@`) in light blue on black.
|
||||
///
|
||||
/// This is the only hardcoded glyph; all other glyphs come from the map
|
||||
/// file palette. It will be removed once the player becomes a scripted
|
||||
/// object with its own palette entry.
|
||||
pub const fn player() -> Self {
|
||||
Self {
|
||||
tile: 64,
|
||||
fg: Rgba8 { r: 173, g: 216, b: 230, a: 255 }, // light blue
|
||||
bg: Rgba8 { r: 0, g: 0, b: 0, a: 255 }, // black
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Specifies a bitmap font for a board.
|
||||
///
|
||||
/// Each board can optionally specify a font image and tile dimensions.
|
||||
/// When absent, the app's default embedded CP437 font is used.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct FontSpec {
|
||||
/// Path to the PNG font image, relative to the working directory.
|
||||
pub path: String,
|
||||
/// Width of each tile in the font image, in pixels.
|
||||
pub tile_w: u32,
|
||||
/// Height of each tile in the font image, in pixels.
|
||||
pub tile_h: u32,
|
||||
}
|
||||
|
||||
/// The behavioral properties of a board cell at runtime.
|
||||
///
|
||||
/// `Behavior` is a plain data struct returned by [`Archetype::behavior`]. It
|
||||
/// contains the properties the engine needs to simulate a cell — currently
|
||||
/// passability and opacity. Future properties (pushable, shootable, etc.) can
|
||||
/// be added here without changing call sites.
|
||||
///
|
||||
/// For scripted objects (`Archetype::Object`), the behavior will eventually be
|
||||
/// determined by the Rhai script rather than this struct. See the Object variant
|
||||
/// for details.
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct Behavior {
|
||||
/// Whether an entity can walk through this cell.
|
||||
pub passable: bool,
|
||||
/// Whether this cell blocks line of sight (reserved for future rendering).
|
||||
pub opaque: bool,
|
||||
}
|
||||
|
||||
/// A class of board cell, encoding its default behavior and appearance.
|
||||
///
|
||||
/// `Archetype` is an enum of the element types the engine knows about. Each
|
||||
/// variant provides a default [`Behavior`] (via [`Archetype::behavior`]) and a
|
||||
/// default [`Glyph`] (via [`Archetype::default_glyph`]) used when the editor
|
||||
/// stamps a cell.
|
||||
///
|
||||
/// Map files reference archetypes by [`name`](Archetype::name) (e.g. `"wall"`),
|
||||
/// so the list of variants can be reordered without breaking saved games.
|
||||
///
|
||||
/// ## Object special case
|
||||
///
|
||||
/// `Archetype::Object` currently returns a static default `Behavior`.
|
||||
/// TODO: In the future, Object passability and opacity will come from the cell's Rhai script
|
||||
/// rather than from this enum. [`Board::is_passable`] will need a special branch
|
||||
/// at that point. `ErrorBlock` is used as a sentinel for unrecognized archetype
|
||||
/// names in map files — it should never appear in a valid board.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Archetype {
|
||||
/// An open cell; the player and other entities can pass through it.
|
||||
Empty,
|
||||
/// A solid wall; impassable and opaque.
|
||||
Wall,
|
||||
/// A scripted object. Behavior defaults to impassable until script-driven.
|
||||
Object,
|
||||
/// Sentinel for map files that reference an unknown archetype name.
|
||||
/// Renders as a yellow `?` on red to make the error visible in-game.
|
||||
ErrorBlock,
|
||||
}
|
||||
|
||||
impl Archetype {
|
||||
/// Returns the default [`Behavior`] for this archetype.
|
||||
///
|
||||
/// For `Object`, this is a placeholder until Rhai scripts drive the behavior.
|
||||
pub fn behavior(&self) -> Behavior {
|
||||
match self {
|
||||
Archetype::Empty => Behavior {
|
||||
passable: true,
|
||||
opaque: false,
|
||||
},
|
||||
Archetype::Wall => Behavior {
|
||||
passable: false,
|
||||
opaque: true,
|
||||
},
|
||||
Archetype::Object => Behavior {
|
||||
passable: false,
|
||||
opaque: false,
|
||||
},
|
||||
Archetype::ErrorBlock => Behavior {
|
||||
passable: false,
|
||||
opaque: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the canonical name used to reference this archetype in map files.
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Archetype::Empty => "empty",
|
||||
Archetype::Wall => "wall",
|
||||
Archetype::Object => "object",
|
||||
Archetype::ErrorBlock => "error_block",
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the default glyph painted when the editor stamps this archetype.
|
||||
///
|
||||
/// This glyph is used only for new cells created in the editor; existing
|
||||
/// cells retain their own per-cell glyph.
|
||||
pub fn default_glyph(&self) -> Glyph {
|
||||
match self {
|
||||
Archetype::Empty => Glyph {
|
||||
tile: 32,
|
||||
fg: Rgba8 { r: 0, g: 0, b: 0, a: 255 },
|
||||
bg: Rgba8 { r: 0, g: 0, b: 0, a: 255 },
|
||||
},
|
||||
Archetype::Wall => Glyph {
|
||||
tile: 35,
|
||||
fg: Rgba8 { r: 0x80, g: 0x80, b: 0x80, a: 255 },
|
||||
bg: Rgba8 { r: 0x60, g: 0x60, b: 0x60, a: 255 },
|
||||
},
|
||||
Archetype::Object => Glyph {
|
||||
tile: 63,
|
||||
fg: Rgba8 { r: 255, g: 255, b: 0, a: 255 }, // yellow
|
||||
bg: Rgba8 { r: 0, g: 0, b: 0, a: 255 },
|
||||
},
|
||||
// Visually distinct so malformed map files are immediately obvious.
|
||||
Archetype::ErrorBlock => Glyph {
|
||||
tile: 63,
|
||||
fg: Rgba8 { r: 255, g: 255, b: 0, a: 255 }, // yellow on red
|
||||
bg: Rgba8 { r: 255, g: 0, b: 0, a: 255 },
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for Archetype {
|
||||
type Error = String;
|
||||
|
||||
/// Parses an archetype by its map-file name.
|
||||
///
|
||||
/// Returns an error for unrecognized names; the caller should substitute
|
||||
/// [`Archetype::ErrorBlock`] and log the error so the problem is visible.
|
||||
fn try_from(name: &str) -> Result<Self, Self::Error> {
|
||||
match name {
|
||||
"empty" => Ok(Archetype::Empty),
|
||||
"wall" => Ok(Archetype::Wall),
|
||||
// "object" is intentionally absent: objects are not valid palette
|
||||
// entries in map files. They live in [[objects]] with their own glyph.
|
||||
_ => Err(format!("unknown archetype: {name}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The archetypes available for placement in the editor, in display order.
|
||||
///
|
||||
/// `ErrorBlock` is excluded — it is a sentinel for load errors, not a valid
|
||||
/// editing choice.
|
||||
pub const ALL_ARCHETYPES: &[Archetype] = &[Archetype::Empty, Archetype::Wall, Archetype::Object];
|
||||
|
||||
/// A scripted object placed on the board, loaded from a map file.
|
||||
///
|
||||
/// `ObjectDef` represents a tile that has Rhai script attached to it.
|
||||
/// Scripts can respond to events like the player touching or shooting the
|
||||
/// tile. Objects are parsed from `[[objects]]` entries in `.toml` map files
|
||||
/// and stored on [`Board`].
|
||||
///
|
||||
/// Objects are rendered as an overlay on top of the board grid — the grid
|
||||
/// cell at `(x, y)` holds the background (floor) that is revealed if the
|
||||
/// object moves away. `glyph` is owned by the object itself and may be
|
||||
/// mutated by its Rhai script at runtime.
|
||||
///
|
||||
/// Script text lives in [`Board::scripts`]; this struct holds only the name
|
||||
/// used to look it up. Two `ObjectDef`s with the same `script_name` share
|
||||
/// source text but will run with independent Rhai scopes when the scripting
|
||||
/// runtime is wired.
|
||||
///
|
||||
/// **Not yet runtime-wired.** Objects are loaded and stored but their scripts
|
||||
/// are not yet executed. Scripting dispatch is a future feature.
|
||||
pub struct ObjectDef {
|
||||
/// Column of this object on the board (0-indexed).
|
||||
pub x: usize,
|
||||
/// Row of this object on the board (0-indexed).
|
||||
pub y: usize,
|
||||
/// Visual representation of this object. Owned by the object (not derived
|
||||
/// from the grid cell), so scripts can change tile, fg, and bg at runtime.
|
||||
pub glyph: Glyph,
|
||||
/// Name of the Rhai script in [`Board::scripts`] that drives this object.
|
||||
/// `None` means this object has no script yet.
|
||||
pub script_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A portal that teleports the player to a named entry point on another board.
|
||||
///
|
||||
/// Portals are loaded from `[[portals]]` entries in `.toml` map files and
|
||||
/// stored on [`Board`]. When the player steps onto a portal's cell, they
|
||||
/// should be moved to `target_entry` on the board named by `target_map`.
|
||||
///
|
||||
/// **Not yet runtime-wired.** Portal navigation (multi-board loading and
|
||||
/// switching) is a future feature.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct PortalDef {
|
||||
/// Column of this portal on the board (0-indexed).
|
||||
pub x: usize,
|
||||
/// Row of this portal on the board (0-indexed).
|
||||
pub y: usize,
|
||||
/// File name (without extension) of the target board, e.g. `"cave"`.
|
||||
pub target_map: String,
|
||||
/// Named entry point on the target board where the player arrives.
|
||||
pub target_entry: String,
|
||||
}
|
||||
|
||||
/// The player's current position on the board.
|
||||
///
|
||||
/// The player is currently a special entity rendered on top of the board
|
||||
/// rather than being stored as a board cell. This is expected to change:
|
||||
/// the player will eventually become a scripted object that responds to
|
||||
/// input events, at which point this struct may be removed or made optional.
|
||||
/// See `ARCHITECTURE.md` for details.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Player {
|
||||
/// Column position (0-indexed, increasing rightward).
|
||||
pub x: i32,
|
||||
/// Row position (0-indexed, increasing downward).
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
/// The complete state of one game board (a single room or screen).
|
||||
///
|
||||
/// `Board` is the central data structure of the engine, equivalent to a
|
||||
/// "board" in ZZT. It contains everything needed to represent and run one
|
||||
/// self-contained area of the game world:
|
||||
///
|
||||
/// - A grid of cells, each with a visual representation ([`Glyph`]) and an [`Archetype`]
|
||||
/// - The current player position
|
||||
/// - Scripted objects and portals (loaded but not yet active)
|
||||
///
|
||||
/// ## Cell storage
|
||||
///
|
||||
/// Cells are stored as `(Glyph, Archetype)` tuples in a row-major `Vec`.
|
||||
/// Each cell directly owns its visual and behavioral class — there is no
|
||||
/// separate element palette or index indirection. Access cells with
|
||||
/// [`Board::get`] and [`Board::get_mut`] using `(x, y)` coordinates.
|
||||
/// Use [`Board::is_passable`] for collision checks.
|
||||
pub struct Board {
|
||||
/// Human-readable name for this board, loaded from the map file and round-tripped on save.
|
||||
pub name: String,
|
||||
/// Width of the board in cells.
|
||||
pub width: usize,
|
||||
/// Height of the board in cells.
|
||||
pub height: usize,
|
||||
/// Row-major grid of `(Glyph, Archetype)` pairs. Use [`Board::get`] to
|
||||
/// access by `(x, y)` coordinates.
|
||||
pub(crate) cells: Vec<(Glyph, Archetype)>,
|
||||
/// Current player position. See [`Player`] for caveats about its future.
|
||||
pub player: Player,
|
||||
/// Scripted objects on this board. Parsed from the map file; not yet active.
|
||||
pub objects: Vec<ObjectDef>,
|
||||
/// Portals on this board. Parsed from the map file; not yet active.
|
||||
pub portals: Vec<PortalDef>,
|
||||
/// Optional font override for this board. When `None`, the app default is used.
|
||||
pub font: Option<FontSpec>,
|
||||
/// Named Rhai scripts available on this board: script name → source text.
|
||||
///
|
||||
/// All script source lives here; [`ObjectDef`]s and [`Board::board_script_name`]
|
||||
/// reference entries by name. This means multiple objects can share the same
|
||||
/// source while each running instance gets its own Rhai scope at runtime.
|
||||
pub scripts: HashMap<String, String>,
|
||||
/// Name of the board-level script in [`Board::scripts`], if any.
|
||||
///
|
||||
/// A board script runs on the board as a whole (e.g. `on_enter`, `on_tick`)
|
||||
/// rather than being tied to a specific object cell.
|
||||
pub board_script_name: Option<String>,
|
||||
}
|
||||
|
||||
impl Board {
|
||||
/// Returns a reference to the cell at `(x, y)`.
|
||||
///
|
||||
/// The cell is a `(Glyph, Archetype)` tuple. Panics if `x` or `y` are
|
||||
/// out of bounds.
|
||||
pub fn get(&self, x: usize, y: usize) -> &(Glyph, Archetype) {
|
||||
&self.cells[y * self.width + x]
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the cell at `(x, y)`.
|
||||
///
|
||||
/// Panics if `x` or `y` are out of bounds.
|
||||
#[allow(dead_code)]
|
||||
pub fn get_mut(&mut self, x: usize, y: usize) -> &mut (Glyph, Archetype) {
|
||||
&mut self.cells[y * self.width + x]
|
||||
}
|
||||
|
||||
/// Returns a slice of all cells in row-major order.
|
||||
///
|
||||
/// Useful for iterating over the full board (e.g. to collect unique glyphs).
|
||||
pub fn cells(&self) -> &[(Glyph, Archetype)] {
|
||||
&self.cells
|
||||
}
|
||||
|
||||
/// Returns `true` if the cell at `(x, y)` allows entities to pass through.
|
||||
///
|
||||
/// Objects block movement before the grid cell archetype is consulted.
|
||||
/// Panics if `x` or `y` are out of bounds.
|
||||
pub fn is_passable(&self, x: usize, y: usize) -> bool {
|
||||
// An object on this cell always blocks (until scripting overrides this).
|
||||
if self.object_at(x, y).is_some() {
|
||||
return false;
|
||||
}
|
||||
self.get(x, y).1.behavior().passable
|
||||
}
|
||||
|
||||
/// Returns the index into [`Board::objects`] of the object at `(x, y)`, if any.
|
||||
pub fn object_at(&self, x: usize, y: usize) -> Option<usize> {
|
||||
self.objects.iter().position(|o| o.x == x && o.y == y)
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds the active game board and provides game-logic operations.
|
||||
///
|
||||
/// `GameState` is the boundary between the engine (rendering, input) and the
|
||||
/// game data ([`Board`]). It owns the current board and exposes methods for
|
||||
/// actions that involve game rules — currently just player movement.
|
||||
///
|
||||
/// As scripting and event dispatch are added, `GameState` will grow to handle
|
||||
/// routing input events to the appropriate Rhai scripts.
|
||||
pub struct GameState {
|
||||
/// The currently active board.
|
||||
pub board: Board,
|
||||
}
|
||||
|
||||
impl GameState {
|
||||
/// Creates a `GameState` from a pre-loaded [`Board`].
|
||||
pub fn new(board: Board) -> Self {
|
||||
Self { board }
|
||||
}
|
||||
|
||||
/// Attempts to move the player by `(dx, dy)` cells.
|
||||
///
|
||||
/// The move is ignored if the target cell is out of bounds or its behavior
|
||||
/// is not passable. No-ops silently (the caller does not need to check).
|
||||
pub fn try_move(&mut self, dx: i32, dy: i32) {
|
||||
let nx = self.board.player.x + dx;
|
||||
let ny = self.board.player.y + dy;
|
||||
if nx >= 0 && ny >= 0 {
|
||||
let nx = nx as usize;
|
||||
let ny = ny as usize;
|
||||
if nx < self.board.width && ny < self.board.height && self.board.is_passable(nx, ny) {
|
||||
self.board.player.x = nx as i32;
|
||||
self.board.player.y = ny as i32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/// Core game types: [`game::Board`], [`game::Glyph`], [`game::Archetype`], etc.
|
||||
pub mod game;
|
||||
/// Map file loading and saving (`.toml` format).
|
||||
pub mod map_file;
|
||||
@@ -0,0 +1,546 @@
|
||||
use crate::game::{Archetype, Board, FontSpec, Glyph, ObjectDef, Player, PortalDef};
|
||||
use color::Rgba8;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::path::Path;
|
||||
|
||||
/// The top-level serialization/deserialization type for a `.toml` map file.
|
||||
///
|
||||
/// This struct mirrors the TOML file structure exactly. On load it is
|
||||
/// immediately converted into a [`Board`] via [`TryFrom<MapFile>`] and then
|
||||
/// discarded. On save a [`Board`] is converted back into this struct via
|
||||
/// [`From<&Board>`] before serialization.
|
||||
///
|
||||
/// See `maps/start.toml` for a complete example of the file format.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct MapFile {
|
||||
/// The `[map]` section: name, dimensions, player start position.
|
||||
pub map: MapHeader,
|
||||
/// The `[palette]` section: maps single-character keys to tile definitions.
|
||||
pub palette: HashMap<String, PaletteEntry>,
|
||||
/// The `[grid]` section: the multi-line string that defines cell layout.
|
||||
pub grid: GridData,
|
||||
/// Optional `[font]` section specifying a bitmap font for this board.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub font: Option<FontHeader>,
|
||||
/// Any `[[objects]]` entries. Optional; defaults to empty.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(crate) objects: Vec<MapFileObjectEntry>,
|
||||
/// Any `[[portals]]` entries. Optional; defaults to empty.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub portals: Vec<PortalDef>,
|
||||
/// The `[scripts]` table: maps script names to Rhai source text.
|
||||
/// Optional; defaults to empty.
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub scripts: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// The `[map]` header section of a map file.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct MapHeader {
|
||||
/// Human-readable name for this board, e.g. `"Opening Room"`.
|
||||
pub name: String,
|
||||
/// Width of the board in cells. Must match the length of every row in `[grid] content`.
|
||||
pub width: usize,
|
||||
/// Height of the board in cells. Must match the number of rows in `[grid] content`.
|
||||
pub height: usize,
|
||||
/// Starting position of the player as `[x, y]` (0-indexed, origin top-left).
|
||||
pub player_start: [i32; 2],
|
||||
/// Name of the board-level script in the `[scripts]` table, if any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub board_script_name: Option<String>,
|
||||
}
|
||||
|
||||
/// The `[font]` section of a map file, specifying a bitmap font for this board.
|
||||
///
|
||||
/// When absent, the app's default embedded CP437 font is used.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct FontHeader {
|
||||
/// Path to the PNG font image, relative to the working directory.
|
||||
pub path: String,
|
||||
/// Width of each tile in the font image, in pixels.
|
||||
pub tile_w: u32,
|
||||
/// Height of each tile in the font image, in pixels.
|
||||
pub tile_h: u32,
|
||||
}
|
||||
|
||||
/// A tile index in a palette entry: either a plain integer or a character literal.
|
||||
///
|
||||
/// Accepting both forms lets map files use `tile = 32` for new files or
|
||||
/// `tile = " "` for convenience (the char is converted to its Unicode scalar).
|
||||
/// This means existing maps that used `ch = "#"` can be migrated by renaming
|
||||
/// the key to `tile`; the char form keeps working.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub(crate) enum TileIndex {
|
||||
/// A direct tile index (e.g. `tile = 35`).
|
||||
Num(u32),
|
||||
/// A single-character shorthand (e.g. `tile = "#"`); converted to its Unicode scalar.
|
||||
Chr(char),
|
||||
}
|
||||
|
||||
impl TileIndex {
|
||||
pub(crate) fn into_u32(self) -> u32 {
|
||||
match self {
|
||||
TileIndex::Num(n) => n,
|
||||
TileIndex::Chr(c) => c as u32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry in the `[palette]` table.
|
||||
///
|
||||
/// Each entry is keyed by a single character (e.g. `"#"` or `" "`).
|
||||
/// That character is used in the `[grid]` content string to place tiles.
|
||||
/// The entry defines both how the tile looks (`tile`, `fg`, `bg`) and which
|
||||
/// [`Archetype`] it uses for behavior.
|
||||
///
|
||||
/// `tile` accepts either an integer (`tile = 35`) or a char (`tile = "#"`).
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct PaletteEntry {
|
||||
/// The archetype name for this tile, e.g. `"wall"` or `"empty"`.
|
||||
pub archetype: String,
|
||||
/// The tile index into the board's bitmap font.
|
||||
/// Accepts either an integer or a single-character string.
|
||||
tile: TileIndex,
|
||||
/// Foreground color as an `"#RRGGBB"` hex string.
|
||||
pub fg: String,
|
||||
/// Background color as an `"#RRGGBB"` hex string.
|
||||
pub bg: String,
|
||||
}
|
||||
|
||||
/// The `[grid]` section of a map file.
|
||||
///
|
||||
/// `content` is a TOML multi-line string. Each line is one row of the board;
|
||||
/// each character in a line is looked up in the palette to determine the
|
||||
/// tile for that cell.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct GridData {
|
||||
/// The raw grid content. Split by [`str::lines`] during loading.
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
/// One `[[objects]]` entry in a map file.
|
||||
///
|
||||
/// Used only for TOML serialization/deserialization. Converted to/from
|
||||
/// [`ObjectDef`] (which holds a [`Glyph`] directly) in the [`TryFrom`] /
|
||||
/// [`From`] impls below.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub(crate) struct MapFileObjectEntry {
|
||||
/// Column of this object on the board (0-indexed).
|
||||
x: usize,
|
||||
/// Row of this object on the board (0-indexed).
|
||||
y: usize,
|
||||
/// Tile index into the board's bitmap font. Accepts integer or single-char string.
|
||||
tile: TileIndex,
|
||||
/// Foreground color as an `"#RRGGBB"` hex string.
|
||||
fg: String,
|
||||
/// Background color as an `"#RRGGBB"` hex string.
|
||||
bg: String,
|
||||
/// Name of the Rhai script in the `[scripts]` table, if any.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
script_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Parses an `"#RRGGBB"` hex color string into an [`Rgba8`].
|
||||
/// Returns opaque black on any parse failure.
|
||||
fn parse_color(hex: &str) -> Rgba8 {
|
||||
let hex = hex.trim_start_matches('#');
|
||||
if hex.len() != 6 {
|
||||
return Rgba8 { r: 0, g: 0, b: 0, a: 255 };
|
||||
}
|
||||
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
|
||||
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
|
||||
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
|
||||
Rgba8 { r, g, b, a: 255 }
|
||||
}
|
||||
|
||||
/// Converts an [`Rgba8`] to an `"#RRGGBB"` hex string (alpha is ignored).
|
||||
fn color_to_hex(color: Rgba8) -> String {
|
||||
format!("#{:02X}{:02X}{:02X}", color.r, color.g, color.b)
|
||||
}
|
||||
|
||||
/// Converts a parsed map file into a runtime [`Board`].
|
||||
///
|
||||
/// Returns `Err(String)` if the grid dimensions do not match the header:
|
||||
/// - wrong number of rows (actual row count ≠ `height`)
|
||||
/// - any row whose character count ≠ `width`
|
||||
///
|
||||
/// The conversion proceeds in two passes:
|
||||
///
|
||||
/// 1. **Palette pass** — each entry is parsed into a `(Glyph, Archetype)` pair
|
||||
/// and stored in a temporary `HashMap` keyed by the palette character.
|
||||
/// Unknown archetype names produce an [`Archetype::ErrorBlock`] and a logged
|
||||
/// warning so malformed maps are visible in-game.
|
||||
///
|
||||
/// 2. **Grid pass** — `grid.content` is split into lines; each character is
|
||||
/// looked up in the palette map and pushed directly into `cells`.
|
||||
impl TryFrom<MapFile> for Board {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(mf: MapFile) -> Result<Self, Self::Error> {
|
||||
let w = mf.map.width;
|
||||
let h = mf.map.height;
|
||||
|
||||
// Pass 1: build a char → (Glyph, Archetype) lookup from the palette.
|
||||
let mut palette: HashMap<char, (Glyph, Archetype)> = HashMap::new();
|
||||
|
||||
for (key, entry) in mf.palette {
|
||||
let key_char = key.chars().next().unwrap_or(' ');
|
||||
let tile = entry.tile.into_u32();
|
||||
match Archetype::try_from(entry.archetype.as_str()) {
|
||||
Ok(archetype) => {
|
||||
let glyph = Glyph {
|
||||
tile,
|
||||
fg: parse_color(&entry.fg),
|
||||
bg: parse_color(&entry.bg),
|
||||
};
|
||||
palette.insert(key_char, (glyph, archetype));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
palette.insert(
|
||||
key_char,
|
||||
(Archetype::ErrorBlock.default_glyph(), Archetype::ErrorBlock),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate grid dimensions before walking cells.
|
||||
// Collect lines eagerly so we can check the count and reuse them.
|
||||
let rows: Vec<&str> = mf.grid.content.lines().collect();
|
||||
if rows.len() != h {
|
||||
return Err(format!(
|
||||
"grid has {} rows but map header declares height = {}",
|
||||
rows.len(),
|
||||
h
|
||||
));
|
||||
}
|
||||
for (i, line) in rows.iter().enumerate() {
|
||||
let col_count = line.chars().count();
|
||||
if col_count != w {
|
||||
return Err(format!(
|
||||
"grid row {} has {} characters but map header declares width = {}",
|
||||
i, col_count, w
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: walk the validated grid and build cells.
|
||||
let mut cells: Vec<(Glyph, Archetype)> = Vec::with_capacity(w * h);
|
||||
for line in &rows {
|
||||
for ch in line.chars() {
|
||||
if let Some(&cell) = palette.get(&ch) {
|
||||
cells.push(cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let font = mf.font.map(|f| FontSpec {
|
||||
path: f.path,
|
||||
tile_w: f.tile_w,
|
||||
tile_h: f.tile_h,
|
||||
});
|
||||
|
||||
// Convert MapFileObjectEntry → ObjectDef, resolving tile index and color strings.
|
||||
let objects = mf
|
||||
.objects
|
||||
.into_iter()
|
||||
.map(|e| ObjectDef {
|
||||
x: e.x,
|
||||
y: e.y,
|
||||
glyph: Glyph {
|
||||
tile: e.tile.into_u32(),
|
||||
fg: parse_color(&e.fg),
|
||||
bg: parse_color(&e.bg),
|
||||
},
|
||||
script_name: e.script_name,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Board {
|
||||
name: mf.map.name,
|
||||
width: w,
|
||||
height: h,
|
||||
cells,
|
||||
player: Player {
|
||||
x: mf.map.player_start[0],
|
||||
y: mf.map.player_start[1],
|
||||
},
|
||||
objects,
|
||||
portals: mf.portals,
|
||||
font,
|
||||
scripts: mf.scripts,
|
||||
board_script_name: mf.map.board_script_name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a runtime [`Board`] back into a serializable [`MapFile`].
|
||||
///
|
||||
/// The palette is reconstructed by enumerating unique `(Glyph, Archetype)`
|
||||
/// combinations in the board's cells and assigning each a single printable
|
||||
/// ASCII character key. The grid is rebuilt by looking up each cell in the
|
||||
/// resulting palette map.
|
||||
impl From<&Board> for MapFile {
|
||||
fn from(board: &Board) -> Self {
|
||||
// Pool for non-empty archetypes: printable ASCII 33-126 ('!' onward),
|
||||
// excluding `"` and `\` which would require escaping inside TOML strings.
|
||||
// Space (32) is reserved exclusively for Archetype::Empty.
|
||||
let pool: Vec<char> = (33u8..=126u8)
|
||||
.filter(|&b| b != b'"' && b != b'\\')
|
||||
.map(|b| b as char)
|
||||
.collect();
|
||||
let mut pool_iter = pool.iter();
|
||||
|
||||
// The canonical empty cell (tile 32, black/black) is always serialized as ' '.
|
||||
// Every other unique (Glyph, Archetype) pair draws from the pool above.
|
||||
let canonical_empty = (Archetype::Empty.default_glyph(), Archetype::Empty);
|
||||
let mut cell_to_key: HashMap<(Glyph, Archetype), char> = HashMap::new();
|
||||
let mut palette: HashMap<String, PaletteEntry> = HashMap::new();
|
||||
|
||||
for y in 0..board.height {
|
||||
for x in 0..board.width {
|
||||
let (glyph, arch) = board.get(x, y);
|
||||
let key = (*glyph, *arch);
|
||||
if !cell_to_key.contains_key(&key) {
|
||||
if key == canonical_empty {
|
||||
cell_to_key.insert(key, ' ');
|
||||
palette.insert(
|
||||
" ".to_string(),
|
||||
PaletteEntry {
|
||||
archetype: arch.name().to_string(),
|
||||
tile: TileIndex::Num(glyph.tile),
|
||||
fg: color_to_hex(glyph.fg),
|
||||
bg: color_to_hex(glyph.bg),
|
||||
},
|
||||
);
|
||||
} else {
|
||||
let ch = *pool_iter
|
||||
.next()
|
||||
.expect("board has more than 92 unique non-canonical cell types");
|
||||
cell_to_key.insert(key, ch);
|
||||
palette.insert(
|
||||
ch.to_string(),
|
||||
PaletteEntry {
|
||||
archetype: arch.name().to_string(),
|
||||
tile: TileIndex::Num(glyph.tile),
|
||||
fg: color_to_hex(glyph.fg),
|
||||
bg: color_to_hex(glyph.bg),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: reconstruct the grid string row by row.
|
||||
let mut rows: Vec<String> = Vec::with_capacity(board.height);
|
||||
for y in 0..board.height {
|
||||
let mut row = String::with_capacity(board.width);
|
||||
for x in 0..board.width {
|
||||
let (glyph, arch) = board.get(x, y);
|
||||
row.push(cell_to_key[&(*glyph, *arch)]);
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
// Trailing newline ensures the last row is complete; str::lines handles it correctly.
|
||||
let content = rows.join("\n") + "\n";
|
||||
|
||||
let font = board.font.as_ref().map(|f| FontHeader {
|
||||
path: f.path.clone(),
|
||||
tile_w: f.tile_w,
|
||||
tile_h: f.tile_h,
|
||||
});
|
||||
|
||||
// Convert ObjectDef → MapFileObjectEntry, encoding the glyph as TOML-compatible fields.
|
||||
let objects: Vec<MapFileObjectEntry> = board
|
||||
.objects
|
||||
.iter()
|
||||
.map(|o| MapFileObjectEntry {
|
||||
x: o.x,
|
||||
y: o.y,
|
||||
tile: TileIndex::Num(o.glyph.tile),
|
||||
fg: color_to_hex(o.glyph.fg),
|
||||
bg: color_to_hex(o.glyph.bg),
|
||||
script_name: o.script_name.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let portals = board
|
||||
.portals
|
||||
.iter()
|
||||
.map(|p| PortalDef {
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
target_map: p.target_map.clone(),
|
||||
target_entry: p.target_entry.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
MapFile {
|
||||
map: MapHeader {
|
||||
name: board.name.clone(),
|
||||
width: board.width,
|
||||
height: board.height,
|
||||
player_start: [board.player.x, board.player.y],
|
||||
board_script_name: board.board_script_name.clone(),
|
||||
},
|
||||
palette,
|
||||
grid: GridData { content },
|
||||
font,
|
||||
objects,
|
||||
portals,
|
||||
scripts: board.scripts.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads a map file from disk and returns a ready-to-use [`Board`].
|
||||
///
|
||||
/// Reads the file at `path`, deserializes it as TOML into a [`MapFile`],
|
||||
/// then converts it via [`TryFrom<MapFile>`]. Propagates I/O errors, TOML
|
||||
/// parse errors, and grid dimension mismatches through the `Box<dyn Error>` return.
|
||||
pub fn load(path: &str) -> Result<Board, Box<dyn std::error::Error>> {
|
||||
let content = std::fs::read_to_string(path)?;
|
||||
let map_file: MapFile = toml::from_str(&content)?;
|
||||
Board::try_from(map_file).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
/// Serializes a [`Board`] to a `.toml` map file at `path`.
|
||||
///
|
||||
/// Converts the board to a [`MapFile`] via [`From<&Board>`], then serializes
|
||||
/// it with `toml::to_string_pretty`. Propagates I/O and serialization errors.
|
||||
pub fn save(board: &Board, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let map_file = MapFile::from(board);
|
||||
let toml_str = toml::to_string_pretty(&map_file)?;
|
||||
std::fs::write(path, toml_str)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Minimal valid TOML with a configurable grid, used as a base for dimension tests.
|
||||
fn minimal_toml(width: usize, height: usize, grid_rows: &[&str]) -> String {
|
||||
let content = grid_rows.join("\n");
|
||||
// Use r##"..."## so the "# in color strings does not close the raw string.
|
||||
format!(
|
||||
r##"
|
||||
[map]
|
||||
name = "Test"
|
||||
width = {width}
|
||||
height = {height}
|
||||
player_start = [0, 0]
|
||||
|
||||
[palette]
|
||||
"." = {{ archetype = "empty", tile = 46, fg = "#000000", bg = "#000000" }}
|
||||
|
||||
[grid]
|
||||
content = """
|
||||
{content}
|
||||
"""
|
||||
"##
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_wrong_row_count_returns_error() {
|
||||
// height = 3 but only 2 rows in the grid
|
||||
let toml = minimal_toml(3, 3, &["...", "..."]);
|
||||
let mf: MapFile = toml::from_str(&toml).unwrap();
|
||||
let result = Board::try_from(mf);
|
||||
assert!(result.is_err());
|
||||
// Use .err().unwrap() instead of .unwrap_err() to avoid requiring Board: Debug.
|
||||
let msg = result.err().unwrap();
|
||||
assert!(msg.contains("2 rows"), "expected row count in error, got: {msg}");
|
||||
assert!(msg.contains("height = 3"), "expected declared height in error, got: {msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_wrong_row_width_returns_error() {
|
||||
// width = 4 but second row is only 3 characters
|
||||
let toml = minimal_toml(4, 2, &["....", "..."]);
|
||||
let mf: MapFile = toml::from_str(&toml).unwrap();
|
||||
let result = Board::try_from(mf);
|
||||
assert!(result.is_err());
|
||||
let msg = result.err().unwrap();
|
||||
assert!(msg.contains("3 characters"), "expected col count in error, got: {msg}");
|
||||
assert!(msg.contains("width = 4"), "expected declared width in error, got: {msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_archetype_in_palette_produces_error_block() {
|
||||
// "object" is no longer a valid palette archetype; it should produce ErrorBlock.
|
||||
let toml = r##"
|
||||
[map]
|
||||
name = "Test"
|
||||
width = 1
|
||||
height = 1
|
||||
player_start = [0, 0]
|
||||
|
||||
[palette]
|
||||
"O" = { archetype = "object", tile = 64, fg = "#00FFFF", bg = "#000000" }
|
||||
|
||||
[grid]
|
||||
content = """
|
||||
O
|
||||
"""
|
||||
"##;
|
||||
let mf: MapFile = toml::from_str(toml).unwrap();
|
||||
let board = Board::try_from(mf).unwrap();
|
||||
let (_, arch) = board.get(0, 0);
|
||||
assert_eq!(*arch, crate::game::Archetype::ErrorBlock);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_glyph_round_trips_through_toml() {
|
||||
// Objects must survive a save→load cycle with their glyph intact.
|
||||
let toml = r##"
|
||||
[map]
|
||||
name = "Test"
|
||||
width = 3
|
||||
height = 3
|
||||
player_start = [0, 0]
|
||||
|
||||
[palette]
|
||||
"." = { archetype = "empty", tile = 46, fg = "#000000", bg = "#000000" }
|
||||
|
||||
[grid]
|
||||
content = """
|
||||
...
|
||||
...
|
||||
...
|
||||
"""
|
||||
|
||||
[[objects]]
|
||||
x = 1
|
||||
y = 1
|
||||
tile = 64
|
||||
fg = "#00FFFF"
|
||||
bg = "#000000"
|
||||
"##;
|
||||
let mf: MapFile = toml::from_str(toml).unwrap();
|
||||
let board = Board::try_from(mf).unwrap();
|
||||
assert_eq!(board.objects.len(), 1);
|
||||
let obj = &board.objects[0];
|
||||
assert_eq!(obj.x, 1);
|
||||
assert_eq!(obj.y, 1);
|
||||
assert_eq!(obj.glyph.tile, 64);
|
||||
assert_eq!(obj.glyph.fg, Rgba8 { r: 0x00, g: 0xFF, b: 0xFF, a: 255 });
|
||||
assert_eq!(obj.glyph.bg, Rgba8 { r: 0, g: 0, b: 0, a: 255 });
|
||||
|
||||
// Save back to TOML and reload; glyph must survive.
|
||||
let map_file = MapFile::from(&board);
|
||||
let toml_out = toml::to_string_pretty(&map_file).unwrap();
|
||||
let mf2: MapFile = toml::from_str(&toml_out).unwrap();
|
||||
let board2 = Board::try_from(mf2).unwrap();
|
||||
let obj2 = &board2.objects[0];
|
||||
assert_eq!(obj2.glyph.tile, obj.glyph.tile);
|
||||
assert_eq!(obj2.glyph.fg, obj.glyph.fg);
|
||||
assert_eq!(obj2.glyph.bg, obj.glyph.bg);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user