Add bitmap font rendering via PNG tilesheet
Replace egui text rendering with a BitmapFont system: - Glyph.tile: u32 replaces ch: char; top-left pixel of PNG is background sentinel - BitmapFont loads/preprocesses PNG to opaque-white + transparent, tinted at render time - Default font: assets/vga-font-8x16.png (CP437, 8×16 tiles); placeholder generated if missing - Boards can specify a per-board font via [font] in their .toml file - Editor Board tab: "Font…" button opens font dialog (rfd file picker, tile dims, tilesheet preview) - Glyph picker: tile grid from active font replaces hardcoded ASCII char grid - map_file: TileIndex untagged enum accepts char or integer in palette entries Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+75
-41
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use serde::Deserialize;
|
||||
use crate::game::{Archetype, Board, FontSpec, Glyph, ObjectDef, Player, PortalDef};
|
||||
use eframe::egui::Color32;
|
||||
use crate::game::{Archetype, Board, Glyph, ObjectDef, Player, PortalDef};
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The top-level deserialization type for a `.toml` map file.
|
||||
///
|
||||
@@ -15,11 +15,12 @@ pub struct MapFile {
|
||||
/// The `[map]` section: name, dimensions, player start position.
|
||||
pub map: MapHeader,
|
||||
/// The `[palette]` section: maps single-character keys to tile definitions.
|
||||
/// Each entry defines both the visual ([`Glyph`]) and the [`Archetype`]
|
||||
/// for all cells that use that character in the grid.
|
||||
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)]
|
||||
pub font: Option<FontHeader>,
|
||||
/// Any `[[objects]]` entries. Optional; defaults to empty.
|
||||
#[serde(default)]
|
||||
pub objects: Vec<ObjectDef>,
|
||||
@@ -32,40 +33,68 @@ pub struct MapFile {
|
||||
#[derive(Deserialize)]
|
||||
pub struct MapHeader {
|
||||
/// Human-readable name for this board, e.g. `"Opening Room"`.
|
||||
/// Not yet displayed anywhere at runtime.
|
||||
#[allow(dead_code)]
|
||||
pub name: String,
|
||||
/// Width of the board in cells. Must match the length of every row in
|
||||
/// `[grid] content`.
|
||||
/// 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`.
|
||||
/// 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). This field will become optional once the player is a
|
||||
/// scripted object rather than a hardcoded entity.
|
||||
/// Starting position of the player as `[x, y]` (0-indexed, origin top-left).
|
||||
pub player_start: [i32; 2],
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
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)]
|
||||
#[serde(untagged)]
|
||||
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 {
|
||||
fn into_u32(self) -> u32 {
|
||||
match self {
|
||||
TileIndex::Num(n) => n,
|
||||
TileIndex::Chr(c) => c as u32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry in the `[palette]` table.
|
||||
///
|
||||
/// Each palette entry is keyed by a single character (e.g. `"#"` or `" "`).
|
||||
/// 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 (`ch`, `fg`, `bg`) and which
|
||||
/// The entry defines both how the tile looks (`tile`, `fg`, `bg`) and which
|
||||
/// [`Archetype`] it uses for behavior.
|
||||
///
|
||||
/// Note that `ch` (the display character) does not have to match the palette
|
||||
/// key. The key is just a label for the grid; `ch` is what actually gets
|
||||
/// rendered. This allows, for example, using `"W"` as the palette key for a
|
||||
/// wall tile that displays as `#`.
|
||||
/// `tile` accepts either an integer (`tile = 35`) or a char (`tile = "#"`).
|
||||
#[derive(Deserialize)]
|
||||
pub struct PaletteEntry {
|
||||
/// The archetype name for this tile, e.g. `"wall"` or `"empty"`.
|
||||
/// Parsed via [`Archetype::try_from`]; unknown names produce an
|
||||
/// [`Archetype::ErrorBlock`] cell and a logged warning.
|
||||
pub archetype: String,
|
||||
/// The character displayed in this cell.
|
||||
pub ch: char,
|
||||
/// 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.
|
||||
@@ -76,9 +105,7 @@ pub struct PaletteEntry {
|
||||
///
|
||||
/// `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. TOML automatically strips the newline immediately
|
||||
/// following the opening `"""`, so no special handling is needed for a
|
||||
/// leading blank line.
|
||||
/// tile for that cell.
|
||||
#[derive(Deserialize)]
|
||||
pub struct GridData {
|
||||
/// The raw grid content. Split by [`str::lines`] during loading.
|
||||
@@ -104,13 +131,11 @@ fn parse_color(hex: &str) -> Color32 {
|
||||
///
|
||||
/// 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.
|
||||
/// 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`.
|
||||
/// Unknown characters are silently skipped, so a malformed grid will
|
||||
/// result in a `cells` vec shorter than `width * height`.
|
||||
/// 2. **Grid pass** — `grid.content` is split into lines; each character is
|
||||
/// looked up in the palette map and pushed directly into `cells`.
|
||||
impl From<MapFile> for Board {
|
||||
fn from(mf: MapFile) -> Self {
|
||||
let w = mf.map.width;
|
||||
@@ -119,19 +144,24 @@ impl From<MapFile> for Board {
|
||||
// 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 {
|
||||
for (key, entry) in mf.palette {
|
||||
let key_char = key.chars().next().unwrap_or(' ');
|
||||
// Unknown archetype names fall back to ErrorBlock so the error is
|
||||
// visible in-game rather than silently producing empty tiles.
|
||||
let tile = entry.tile.into_u32();
|
||||
match Archetype::try_from(entry.archetype.as_str()) {
|
||||
Ok(archetype) => {
|
||||
let glyph = Glyph { ch: entry.ch, fg: parse_color(&entry.fg), bg: parse_color(&entry.bg) };
|
||||
let glyph = Glyph {
|
||||
tile,
|
||||
fg: parse_color(&entry.fg),
|
||||
bg: parse_color(&entry.bg),
|
||||
};
|
||||
palette.insert(key_char, (glyph, archetype));
|
||||
}
|
||||
Err(e) => {
|
||||
// Be sure to log and ignore the default glyph for an unknown archetype
|
||||
eprintln!("{e}");
|
||||
palette.insert(key_char, (Archetype::ErrorBlock.default_glyph(), Archetype::ErrorBlock));
|
||||
palette.insert(
|
||||
key_char,
|
||||
(Archetype::ErrorBlock.default_glyph(), Archetype::ErrorBlock),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,6 +176,12 @@ impl From<MapFile> for Board {
|
||||
}
|
||||
}
|
||||
|
||||
let font = mf.font.map(|f| FontSpec {
|
||||
path: f.path,
|
||||
tile_w: f.tile_w,
|
||||
tile_h: f.tile_h,
|
||||
});
|
||||
|
||||
Board {
|
||||
width: w,
|
||||
height: h,
|
||||
@@ -156,6 +192,7 @@ impl From<MapFile> for Board {
|
||||
},
|
||||
objects: mf.objects,
|
||||
portals: mf.portals,
|
||||
font,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,9 +202,6 @@ impl From<MapFile> for Board {
|
||||
/// Reads the file at `path`, deserializes it as TOML into a [`MapFile`],
|
||||
/// then converts it via [`From<MapFile>`]. Propagates both I/O errors and
|
||||
/// TOML parse errors through the `Box<dyn Error>` return.
|
||||
///
|
||||
/// Called from `main()` before the window is created so that board
|
||||
/// dimensions are available for window sizing.
|
||||
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)?;
|
||||
|
||||
Reference in New Issue
Block a user