workspaceify

This commit is contained in:
2026-05-30 20:20:09 -05:00
parent d19737c113
commit a0d21bde20
14 changed files with 128 additions and 64 deletions
+262
View File
@@ -0,0 +1,262 @@
use eframe::egui;
use egui::{Sense, vec2};
use crate::font::BitmapFont;
use crate::font_dialog::{FontDialogState, show as show_font_dialog};
use crate::render::{PALETTE_PANEL_W, paint_glyph};
use kiln_core::game::{ALL_ARCHETYPES, Archetype, Board, Glyph};
/// Which tab is active in the editor side panel.
#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum EditorTab {
/// Archetype + glyph palette for painting cells.
Palette,
/// Object placement and script assignment.
Objects,
/// Board-level properties (font, board script).
Board,
/// Named script library for this board.
Scripts,
/// World-level properties (placeholder).
World,
}
/// Transient editor state. Only meaningful when the app is in Edit mode.
pub(crate) struct EditorState {
/// The archetype that will be stamped when the user clicks a cell.
pub(crate) selected: Archetype,
/// The glyph (tile index + colors) to stamp. Independent of the archetype's default.
pub(crate) glyph: Glyph,
/// Whether the glyph picker dialog is currently open (Palette tab).
pub(crate) glyph_picker_open: bool,
/// Whether the font picker dialog is currently open.
pub(crate) font_dialog_open: bool,
/// In-progress state for the font dialog while it is open.
pub(crate) font_dialog_state: FontDialogState,
/// Which side-panel tab is currently shown.
pub(crate) tab: EditorTab,
/// Index into `board.objects` of the currently selected object, or `None`.
pub(crate) selected_object: Option<usize>,
/// Whether the glyph picker is open for editing the selected object's glyph.
pub(crate) object_glyph_picker_open: bool,
/// Local copy of the selected object's glyph for the picker to edit.
///
/// Kept separate from `board.objects` to avoid a borrow conflict while the
/// glyph picker holds `&mut Glyph` and the board is also borrowed. Written
/// back to `board.objects[i].glyph` each frame while an object is selected.
pub(crate) object_editing_glyph: Glyph,
/// When `true`, the next board click in the Objects tab places a new object.
/// Set by the "Add Object" button; cleared after placement or on tab switch.
pub(crate) placing_object: bool,
}
impl EditorState {
/// Creates editor state with `Wall` selected and all dialogs closed.
pub(crate) fn new() -> Self {
Self {
selected: Archetype::Wall,
glyph: Archetype::Wall.default_glyph(),
glyph_picker_open: false,
font_dialog_open: false,
font_dialog_state: FontDialogState::from_spec(None),
tab: EditorTab::Palette,
selected_object: None,
object_glyph_picker_open: false,
object_editing_glyph: Glyph::player(), // overwritten on first selection
placing_object: false,
}
}
}
/// Renders the editor side panel (must be called before `CentralPanel`).
///
/// Shows tab bar (Palette / Objects / Board / Scripts / World) and the content
/// for the active tab. `board` is the current board, used by the Objects and
/// Scripts tabs and to read/write the board font. `active_font` is the resolved
/// font currently in use for rendering.
pub(crate) fn show_editor_panel(
ctx: &egui::Context,
editor: &mut EditorState,
board: &mut Board,
active_font: &BitmapFont,
) {
let tw = active_font.tile_w as f32;
let th = active_font.tile_h as f32;
egui::SidePanel::right("palette_panel")
.resizable(true)
.default_width(PALETTE_PANEL_W)
.show(ctx, |ui| {
// Tab bar — wraps automatically if the panel is narrow.
ui.horizontal_wrapped(|ui| {
ui.selectable_value(&mut editor.tab, EditorTab::Palette, "Palette");
ui.selectable_value(&mut editor.tab, EditorTab::Objects, "Objects");
ui.selectable_value(&mut editor.tab, EditorTab::Board, "Board");
ui.selectable_value(&mut editor.tab, EditorTab::Scripts, "Scripts");
ui.selectable_value(&mut editor.tab, EditorTab::World, "World");
});
ui.separator();
match editor.tab {
EditorTab::Palette => {
ui.label("Element");
// Scrollable archetype list; shows at most 5 rows before scrolling.
let row_h = th + ui.spacing().item_spacing.y;
egui::ScrollArea::vertical()
.max_height(row_h * 5.0)
.id_salt("arch_list")
.show(ui, |ui| {
for &archetype in ALL_ARCHETYPES {
let is_selected = editor.selected == archetype;
let glyph = archetype.default_glyph();
ui.horizontal(|ui| {
let (r, cell_resp) =
ui.allocate_exact_size(vec2(tw, th), Sense::click());
paint_glyph(ui.painter(), r, &glyph, active_font);
let label_resp =
ui.selectable_label(is_selected, archetype.name());
if cell_resp.clicked() || label_resp.clicked() {
editor.selected = archetype;
editor.glyph = archetype.default_glyph();
}
});
}
});
ui.separator();
ui.label("Glyph");
// Paint a preview cell showing the current glyph, sized like a board cell.
let (cell_rect, glyph_btn) =
ui.allocate_exact_size(vec2(tw, th), Sense::click());
paint_glyph(ui.painter(), cell_rect, &editor.glyph, active_font);
if glyph_btn.clicked() {
editor.glyph_picker_open = true;
}
}
EditorTab::Objects => {
// "Add Object" toggles placement mode; next board click places a new object.
let add_label = if editor.placing_object {
"Cancel Add"
} else {
"Add Object"
};
if ui.button(add_label).clicked() {
editor.placing_object = !editor.placing_object;
editor.selected_object = None;
}
if editor.placing_object {
ui.label("Click on the board to place.");
}
ui.separator();
match editor.selected_object {
None => {
if !editor.placing_object {
ui.label("Click an object on the board to select it.");
}
}
Some(i) => {
// Collect sorted script names before taking a mutable borrow on objects.
let mut script_names: Vec<String> =
board.scripts.keys().cloned().collect();
script_names.sort();
ui.label("Glyph");
// Preview button — same pattern as Palette tab.
let (cell_rect, glyph_btn) =
ui.allocate_exact_size(vec2(tw, th), Sense::click());
paint_glyph(
ui.painter(),
cell_rect,
&editor.object_editing_glyph,
active_font,
);
if glyph_btn.clicked() {
editor.object_glyph_picker_open = true;
}
let obj = &mut board.objects[i];
let current =
obj.script_name.as_deref().unwrap_or("(none)").to_string();
ui.label("Script");
egui::ComboBox::from_id_salt("obj_script")
.selected_text(&current)
.show_ui(ui, |ui| {
// "(none)" clears the script assignment.
if ui
.selectable_label(obj.script_name.is_none(), "(none)")
.clicked()
{
obj.script_name = None;
}
for name in &script_names {
let is_sel =
obj.script_name.as_deref() == Some(name.as_str());
if ui.selectable_label(is_sel, name.as_str()).clicked() {
obj.script_name = Some(name.clone());
}
}
// Placeholder for future "create and edit a new script" flow.
let _ = ui.selectable_label(false, "(create new...)");
});
if ui.button("Edit Script").clicked() {
// TODO: open script editor
}
}
}
}
EditorTab::Board => {
let font_label = match &board.font {
Some(s) => s.path.clone(),
None => "(default)".to_owned(),
};
ui.label(format!("Font: {font_label}"));
if ui.button("Font…").clicked() {
editor.font_dialog_state =
FontDialogState::from_spec(board.font.as_ref());
editor.font_dialog_open = true;
}
}
EditorTab::Scripts => {
if board.scripts.is_empty() {
ui.label("No scripts defined.");
} else {
let mut names: Vec<&String> = board.scripts.keys().collect();
names.sort();
egui::ScrollArea::vertical()
.id_salt("scripts_list")
.show(ui, |ui| {
for name in names {
ui.horizontal(|ui| {
ui.label(name);
if ui.button("Edit").clicked() {
// TODO: open script editor
}
});
}
});
}
}
EditorTab::World => {}
}
});
// Font dialog floats outside the side panel; show it here so it renders on top.
if editor.font_dialog_open {
show_font_dialog(
ctx,
&mut editor.font_dialog_open,
&mut editor.font_dialog_state,
&mut board.font,
);
}
}
+263
View File
@@ -0,0 +1,263 @@
use eframe::egui;
use egui::{ColorImage, Rect, TextureHandle, TextureOptions, vec2};
use image::GenericImageView;
use std::path::Path;
/// Computes a UV rectangle for `tile` within an image of known dimensions.
///
/// This is the core tile-index-to-UV mapping; pulled out so tests can verify
/// it without needing an egui [`Context`] to construct a [`BitmapFont`].
fn compute_tile_uv(tile: u32, tile_w: u32, tile_h: u32, img_w: u32, img_h: u32) -> Rect {
let tiles_per_row = (img_w / tile_w).max(1);
let col = tile % tiles_per_row;
let row = tile / tiles_per_row;
let u0 = col as f32 * tile_w as f32 / img_w as f32;
let v0 = row as f32 * tile_h as f32 / img_h as f32;
let u1 = u0 + tile_w as f32 / img_w as f32;
let v1 = v0 + tile_h as f32 / img_h as f32;
Rect::from_min_max(egui::pos2(u0, v0), egui::pos2(u1, v1))
}
/// A loaded bitmap font ready for rendering.
///
/// Wraps an egui texture that has been pre-processed to a two-value RGBA
/// image: "background" pixels (matching the top-left pixel of the source
/// image) become fully transparent, and all other pixels become opaque white.
///
/// At render time, each tile is drawn by:
/// 1. Filling the cell rect with the glyph's `bg` color.
/// 2. Calling `painter.image(…, tile_uv(tile), fg_color)` — egui tints the
/// opaque-white foreground pixels to `fg` and the transparent pixels stay
/// transparent, revealing the `bg` fill underneath.
pub struct BitmapFont {
/// The uploaded egui texture (preprocessed to opaque-white / transparent).
pub texture: TextureHandle,
/// Width of each tile in pixels.
pub tile_w: u32,
/// Height of each tile in pixels.
pub tile_h: u32,
/// Width of the full font image in pixels.
img_w: u32,
/// Height of the full font image in pixels.
img_h: u32,
}
impl BitmapFont {
/// Loads a bitmap font from raw PNG bytes (e.g. via `include_bytes!`).
///
/// `label` is passed to egui as the texture name for debugging.
/// Returns an error if the image cannot be decoded.
#[allow(dead_code)]
pub fn from_bytes(
ctx: &egui::Context,
bytes: &[u8],
tile_w: u32,
tile_h: u32,
label: &str,
) -> Result<Self, Box<dyn std::error::Error>> {
let img = image::load_from_memory(bytes)?;
Self::from_image(ctx, img, tile_w, tile_h, label)
}
/// Loads a bitmap font from a PNG file on disk.
pub fn load(
ctx: &egui::Context,
path: &Path,
tile_w: u32,
tile_h: u32,
) -> Result<Self, Box<dyn std::error::Error>> {
let img = image::open(path)?;
let label = path.to_string_lossy();
Self::from_image(ctx, img, tile_w, tile_h, &label)
}
fn from_image(
ctx: &egui::Context,
img: image::DynamicImage,
tile_w: u32,
tile_h: u32,
label: &str,
) -> Result<Self, Box<dyn std::error::Error>> {
let img_w = img.width();
let img_h = img.height();
// The top-left pixel defines the "background" color to treat as transparent.
let bg_pixel = img.get_pixel(0, 0);
let [br, bg, bb, _] = bg_pixel.0;
// Convert to RGBA: bg-colored pixels → transparent, all others → opaque white.
let rgba = img.to_rgba8();
let mut pixels: Vec<egui::Color32> = Vec::with_capacity((img_w * img_h) as usize);
for pixel in rgba.pixels() {
let [r, g, b, _] = pixel.0;
if r == br && g == bg && b == bb {
pixels.push(egui::Color32::TRANSPARENT);
} else {
pixels.push(egui::Color32::WHITE);
}
}
let color_image = ColorImage {
size: [img_w as usize, img_h as usize],
pixels,
source_size: vec2(img_w as f32, img_h as f32),
};
let texture = ctx.load_texture(label, color_image, TextureOptions::NEAREST);
Ok(Self {
texture,
tile_w,
tile_h,
img_w,
img_h,
})
}
/// Returns the UV rectangle (in 0.01.0 coordinates) for `tile` in the font image.
///
/// Tiles are numbered left-to-right, top-to-bottom. For a 16-column font,
/// tile 0 is top-left, tile 15 is top-right, tile 16 is the first tile of
/// row 2, etc.
pub fn tile_uv(&self, tile: u32) -> Rect {
compute_tile_uv(tile, self.tile_w, self.tile_h, self.img_w, self.img_h)
}
/// Returns the number of tile columns in the font image.
pub fn tile_cols(&self) -> u32 {
(self.img_w / self.tile_w).max(1)
}
/// Returns the total number of tiles in this font image.
pub fn tile_count(&self) -> u32 {
let rows = (self.img_h / self.tile_h).max(1);
self.tile_cols() * rows
}
/// Width of the full font image in pixels.
pub fn img_w(&self) -> u32 {
self.img_w
}
/// Height of the full font image in pixels.
pub fn img_h(&self) -> u32 {
self.img_h
}
/// Creates a procedural placeholder font (16×16 grid of 8×8 tiles).
///
/// Each tile renders the 8 bits of its index as a vertical bar pattern,
/// making tiles visually distinct. Used as a fallback when no font file
/// is present.
pub fn create_placeholder(ctx: &egui::Context) -> Self {
let tile_w: u32 = 8;
let tile_h: u32 = 8;
let cols: u32 = 16;
let rows: u32 = 16;
let img_w = cols * tile_w;
let img_h = rows * tile_h;
let mut pixels = vec![egui::Color32::TRANSPARENT; (img_w * img_h) as usize];
for tile in 0..256u32 {
let tc = tile % cols;
let tr = tile / cols;
// Render the 8 bits of the tile index as a column bar pattern (rows 16).
let byte = (tile & 0xFF) as u8;
for py in 1u32..7 {
for px in 0u32..8 {
let bit = (byte >> (7 - px)) & 1;
if bit == 1 {
let x = tc * tile_w + px;
let y = tr * tile_h + py;
pixels[(y * img_w + x) as usize] = egui::Color32::WHITE;
}
}
}
}
let color_image = ColorImage {
size: [img_w as usize, img_h as usize],
pixels,
source_size: vec2(img_w as f32, img_h as f32),
};
let texture = ctx.load_texture(
"default_font_placeholder",
color_image,
TextureOptions::NEAREST,
);
Self {
texture,
tile_w,
tile_h,
img_w,
img_h,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn approx_eq(a: f32, b: f32) -> bool {
(a - b).abs() < 1e-5
}
fn rect_approx_eq(a: Rect, b: Rect) -> bool {
approx_eq(a.min.x, b.min.x)
&& approx_eq(a.min.y, b.min.y)
&& approx_eq(a.max.x, b.max.x)
&& approx_eq(a.max.y, b.max.y)
}
#[test]
fn tile_zero_is_top_left() {
let uv = compute_tile_uv(0, 8, 8, 128, 128);
assert!(rect_approx_eq(
uv,
Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0 / 16.0, 1.0 / 16.0))
));
}
#[test]
fn tile_at_end_of_first_row() {
// 16 cols, so tile 15 is top-right.
let uv = compute_tile_uv(15, 8, 8, 128, 128);
assert!(approx_eq(uv.min.x, 15.0 / 16.0));
assert!(approx_eq(uv.min.y, 0.0));
}
#[test]
fn tile_at_start_of_second_row() {
// Tile 16 should be col 0, row 1.
let uv = compute_tile_uv(16, 8, 8, 128, 128);
assert!(approx_eq(uv.min.x, 0.0));
assert!(approx_eq(uv.min.y, 1.0 / 16.0));
}
#[test]
fn tile_64_is_at_position() {
// '@' = ASCII 64; in a 16-col font: col = 64%16 = 0, row = 64/16 = 4.
let uv = compute_tile_uv(64, 8, 8, 128, 128);
assert!(approx_eq(uv.min.x, 0.0));
assert!(approx_eq(uv.min.y, 4.0 / 16.0));
}
#[test]
fn non_square_font_layout() {
// 32 columns, 8 rows = 256 tiles; 6×8 tiles; image 192×64.
// tile 32 = col 0, row 1.
let uv = compute_tile_uv(32, 6, 8, 192, 64);
assert!(approx_eq(uv.min.x, 0.0));
assert!(approx_eq(uv.min.y, 1.0 / 8.0));
}
#[test]
fn uv_width_matches_tile_fraction() {
let uv = compute_tile_uv(0, 8, 8, 128, 128);
// Each tile is 1/16 of the image width.
assert!(approx_eq(uv.width(), 1.0 / 16.0));
assert!(approx_eq(uv.height(), 1.0 / 16.0));
}
}
+180
View File
@@ -0,0 +1,180 @@
use eframe::egui;
use egui::{Color32, DragValue, Rect, Stroke, vec2};
use crate::font::BitmapFont;
use kiln_core::game::FontSpec;
/// State for the font-picker dialog.
///
/// Holds the in-progress edit of font path and tile dimensions, and a loaded
/// preview font so the user can see the tilesheet before applying.
pub(crate) struct FontDialogState {
/// Path string as edited by the user (may differ from the applied font).
pub path: String,
/// Tile width being edited.
pub tile_w: u32,
/// Tile height being edited.
pub tile_h: u32,
/// Loaded preview of the current path+dimensions, if valid.
pub preview: Option<BitmapFont>,
}
impl FontDialogState {
/// Creates dialog state pre-populated from an existing [`FontSpec`], or
/// defaults (8×8, empty path) when there is no board-level font.
pub(crate) fn from_spec(spec: Option<&FontSpec>) -> Self {
match spec {
Some(s) => Self {
path: s.path.clone(),
tile_w: s.tile_w,
tile_h: s.tile_h,
preview: None,
},
None => Self {
path: String::new(),
tile_w: 8,
tile_h: 8,
preview: None,
},
}
}
}
/// Renders the floating font-picker dialog.
///
/// Lets the user choose a PNG file, set tile dimensions, preview the tilesheet
/// with grid lines, and apply the selection. When the user clicks "Apply",
/// `font_spec` is written and `open` is set to `false`.
pub(crate) fn show(
ctx: &egui::Context,
open: &mut bool,
state: &mut FontDialogState,
font_spec: &mut Option<FontSpec>,
) {
let mut should_close = false;
egui::Window::new("Font")
.collapsible(false)
.resizable(true)
.open(open)
.show(ctx, |ui| {
// --- File chooser ---
ui.horizontal(|ui| {
ui.label("File:");
ui.text_edit_singleline(&mut state.path);
if ui.button("Browse…").clicked() {
if let Some(path) = rfd::FileDialog::new()
.add_filter("PNG image", &["png"])
.pick_file()
{
state.path = path.to_string_lossy().into_owned();
state.preview = None; // reload on next reload click
}
}
});
// --- Tile dimensions ---
ui.horizontal(|ui| {
ui.label("Tile W:");
if ui
.add(DragValue::new(&mut state.tile_w).range(1..=64))
.changed()
{
state.preview = None;
}
ui.label("Tile H:");
if ui
.add(DragValue::new(&mut state.tile_h).range(1..=64))
.changed()
{
state.preview = None;
}
if ui.button("Load").clicked() {
state.preview = None;
if !state.path.is_empty() {
match BitmapFont::load(
ctx,
std::path::Path::new(&state.path),
state.tile_w,
state.tile_h,
) {
Ok(f) => state.preview = Some(f),
Err(e) => eprintln!("font load error: {e}"),
}
}
}
});
ui.separator();
// --- Preview ---
if let Some(font) = &state.preview {
let tw = font.tile_w as f32;
let th = font.tile_h as f32;
let preview_size = vec2(font.img_w() as f32, font.img_h() as f32);
egui::ScrollArea::both()
.max_width(400.0)
.max_height(200.0)
.id_salt("font_preview")
.show(ui, |ui| {
let (rect, _) = ui.allocate_exact_size(preview_size, egui::Sense::hover());
// Draw the full font texture.
ui.painter().image(
font.texture.id(),
rect,
Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
Color32::WHITE,
);
// Overlay grid lines at tile boundaries.
let p = ui.painter();
let cols = font.tile_cols();
let rows = font.img_h() / font.tile_h;
let stroke =
Stroke::new(0.5, Color32::from_rgba_unmultiplied(255, 255, 0, 120));
for c in 0..=cols {
let x = rect.min.x + c as f32 * tw;
p.line_segment(
[egui::pos2(x, rect.min.y), egui::pos2(x, rect.max.y)],
stroke,
);
}
for r in 0..=rows {
let y = rect.min.y + r as f32 * th;
p.line_segment(
[egui::pos2(rect.min.x, y), egui::pos2(rect.max.x, y)],
stroke,
);
}
});
} else {
ui.label("(no preview — click Load after setting path and tile size)");
}
ui.separator();
// --- Apply / Clear ---
ui.horizontal(|ui| {
let can_apply = state.preview.is_some();
if ui
.add_enabled(can_apply, egui::Button::new("Apply"))
.clicked()
{
*font_spec = Some(FontSpec {
path: state.path.clone(),
tile_w: state.tile_w,
tile_h: state.tile_h,
});
should_close = true;
}
if ui.button("Use default").clicked() {
*font_spec = None;
should_close = true;
}
});
});
if should_close {
*open = false;
}
}
+136
View File
@@ -0,0 +1,136 @@
use std::collections::HashSet;
use eframe::egui;
use egui::{Color32, Rect, Sense, Stroke, vec2};
use crate::font::BitmapFont;
use crate::render::{paint_glyph, pos_to_cell, rgba8_to_color32};
use kiln_core::game::{Archetype, Glyph};
/// Renders the floating glyph-picker dialog and updates `glyph` in place.
///
/// Shows three sections: board palette (unique glyphs on the current board),
/// FG/BG color pickers, and a scrollable grid of all tiles in the active font.
/// Closes when the window's X button is clicked, writing `false` to `open`.
pub(crate) fn show(
ctx: &egui::Context,
open: &mut bool,
glyph: &mut Glyph,
board_cells: &[(Glyph, Archetype)],
font: &BitmapFont,
) {
// Collect unique glyphs from the board before the window closure borrows
// `glyph` mutably, to avoid a borrow conflict with `board_cells`.
let board_glyphs: Vec<Glyph> = {
let mut seen: HashSet<Glyph> = HashSet::new();
board_cells
.iter()
.map(|(g, _)| *g)
.filter(|g| seen.insert(*g))
.collect()
};
let tw = font.tile_w as f32;
let th = font.tile_h as f32;
egui::Window::new("Glyph")
.collapsible(false)
.resizable(false)
.open(open)
.show(ctx, |ui| {
ui.label("Board palette");
ui.horizontal_wrapped(|ui| {
for &g in &board_glyphs {
let (r, resp) = ui.allocate_exact_size(vec2(tw, th), Sense::click());
let p = ui.painter();
paint_glyph(p, r, &g, font);
if g == *glyph {
p.rect_stroke(
r,
0.0,
Stroke::new(1.0, Color32::WHITE),
egui::epaint::StrokeKind::Middle,
);
}
if resp.clicked() {
*glyph = g;
}
}
});
ui.separator();
ui.label("Colors");
ui.horizontal(|ui| {
// The color picker works with Color32; convert to/from Rgba8 around the call.
let mut fg = rgba8_to_color32(glyph.fg);
ui.label("FG");
egui::color_picker::color_edit_button_srgba(
ui,
&mut fg,
egui::color_picker::Alpha::Opaque,
);
glyph.fg = color::Rgba8 { r: fg.r(), g: fg.g(), b: fg.b(), a: fg.a() };
let mut bg = rgba8_to_color32(glyph.bg);
ui.label("BG");
egui::color_picker::color_edit_button_srgba(
ui,
&mut bg,
egui::color_picker::Alpha::Opaque,
);
glyph.bg = color::Rgba8 { r: bg.r(), g: bg.g(), b: bg.b(), a: bg.a() };
});
ui.separator();
// Full tile grid: column count matches the font image layout so the
// picker visually mirrors the tilesheet.
ui.label("Tile");
let tile_cols = font.tile_cols() as usize;
let tile_count = font.tile_count() as usize;
let rows = tile_count.div_ceil(tile_cols);
let grid_size = vec2(tile_cols as f32 * tw, rows as f32 * th);
egui::ScrollArea::vertical()
.max_height(th * 16.0)
.id_salt("tile_grid")
.show(ui, |ui| {
let (grid_rect, grid_resp) = ui.allocate_exact_size(grid_size, Sense::click());
{
let p = ui.painter();
for i in 0..tile_count {
let col = i % tile_cols;
let row = i / tile_cols;
let tl = grid_rect.min + vec2(col as f32 * tw, row as f32 * th);
let cell = Rect::from_min_size(tl, vec2(tw, th));
let tile_glyph = Glyph {
tile: i as u32,
fg: glyph.fg,
bg: glyph.bg,
};
paint_glyph(p, cell, &tile_glyph, font);
if i as u32 == glyph.tile {
p.rect_stroke(
cell,
0.0,
Stroke::new(1.0, Color32::WHITE),
egui::epaint::StrokeKind::Middle,
);
}
}
}
if grid_resp.clicked()
&& let Some(pos) = grid_resp.interact_pointer_pos()
{
let (col, row) = pos_to_cell(grid_rect.min, pos, tw, th);
if col >= 0 && row >= 0 {
let idx = row as usize * tile_cols + col as usize;
if idx < tile_count {
glyph.tile = idx as u32;
}
}
}
});
});
}
+315
View File
@@ -0,0 +1,315 @@
use eframe::egui;
use egui::{Key, Sense, vec2};
use std::path::{Path, PathBuf};
mod editor;
mod font;
mod font_dialog;
mod glyph_picker;
mod render;
use editor::{EditorState, EditorTab, show_editor_panel};
use font::BitmapFont;
use kiln_core::game::{Archetype, FontSpec, GameState, Glyph, ObjectDef};
use kiln_core::map_file;
use render::{
DEFAULT_WINDOW_H, DEFAULT_WINDOW_W, MIN_WINDOW_H, MIN_WINDOW_W, board_origin, draw_board,
draw_object_overlays, pos_to_cell,
};
/// Whether the application is in play mode or edit mode.
///
/// In `Play` mode the game runs normally: arrow keys move the player.
/// In `Edit` mode arrow keys are inactive, a side panel shows the archetype
/// palette, and clicking on the viewport paints cells.
#[derive(Copy, Clone, PartialEq, Eq)]
enum AppMode {
/// Normal game play. Arrow keys control the player.
Play,
/// Board editing. Side panel shows archetypes; click to paint cells.
Edit,
}
fn main() -> eframe::Result<()> {
let start_path = PathBuf::from("maps/start.toml");
let board = map_file::load(start_path.to_str().unwrap()).expect("failed to load maps/start.toml");
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([DEFAULT_WINDOW_W, DEFAULT_WINDOW_H])
.with_min_inner_size([MIN_WINDOW_W, MIN_WINDOW_H]),
..Default::default()
};
eframe::run_native(
"Kiln",
options,
Box::new(move |cc| Ok(Box::new(App::new(board, &cc.egui_ctx, start_path)))),
)
}
/// The eframe application. Owns the game state and drives the frame loop.
///
/// eframe calls [`App::update`] every frame. All input handling, game logic
/// updates, and rendering happen there. There is no separate game loop thread.
struct App {
state: GameState,
mode: AppMode,
editor: EditorState,
/// The default font, embedded in the binary and loaded at startup.
default_font: BitmapFont,
/// A per-board font loaded from `board.font`, if one is specified.
board_font: Option<BitmapFont>,
/// Path of the file currently open. `None` until the user saves for the first time.
/// Used by Save to write without prompting; Save As always prompts and updates this.
current_file_path: Option<PathBuf>,
}
impl App {
/// Creates the app with the given board, starting in Play mode.
///
/// `egui_ctx` is needed to upload font textures before the first frame.
/// `initial_path` is the file the board was loaded from and becomes the
/// default Save target.
fn new(board: kiln_core::game::Board, egui_ctx: &egui::Context, initial_path: PathBuf) -> Self {
// Default font is embedded in the binary; no runtime file I/O needed.
let font_bytes = include_bytes!("../assets/vga-font-8x16.png");
let default_font = BitmapFont::from_bytes(egui_ctx, font_bytes, 8, 16, "vga-font-8x16")
.unwrap_or_else(|_| BitmapFont::create_placeholder(egui_ctx));
// If the board specifies its own font, try to load it now.
let board_font = board.font.as_ref().and_then(|spec| {
BitmapFont::load(egui_ctx, Path::new(&spec.path), spec.tile_w, spec.tile_h)
.map_err(|e| eprintln!("board font load error: {e}"))
.ok()
});
Self {
state: GameState::new(board),
mode: AppMode::Play,
editor: EditorState::new(),
default_font,
board_font,
current_file_path: Some(initial_path),
}
}
/// Reloads `board_font` from `font_spec`, or clears it if `font_spec` is `None`.
///
/// Called after the font dialog applies a change.
fn apply_font_spec(&mut self, egui_ctx: &egui::Context, font_spec: Option<&FontSpec>) {
self.board_font = font_spec.and_then(|spec| {
BitmapFont::load(egui_ctx, Path::new(&spec.path), spec.tile_w, spec.tile_h)
.map_err(|e| eprintln!("font apply error: {e}"))
.ok()
});
}
}
impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// --- Input ---
// Arrow keys move the player only in Play mode.
if self.mode == AppMode::Play {
ctx.input(|i| {
if i.key_pressed(Key::ArrowUp) {
self.state.try_move(0, -1);
}
if i.key_pressed(Key::ArrowDown) {
self.state.try_move(0, 1);
}
if i.key_pressed(Key::ArrowLeft) {
self.state.try_move(-1, 0);
}
if i.key_pressed(Key::ArrowRight) {
self.state.try_move(1, 0);
}
});
}
// --- Menu bar ---
egui::TopBottomPanel::top("menu_bar").show(ctx, |ui| {
egui::MenuBar::new().ui(ui, |ui| {
ui.menu_button("File", |ui| {
if ui.button("Save").clicked() {
ui.close();
let path = self.current_file_path.clone();
if let Some(path) = path {
if let Err(e) = map_file::save(&self.state.board, &path) {
eprintln!("save error: {e}");
}
} else if let Some(path) = rfd::FileDialog::new()
.add_filter("Map file", &["toml"])
.save_file()
{
if let Err(e) = map_file::save(&self.state.board, &path) {
eprintln!("save error: {e}");
} else {
self.current_file_path = Some(path);
}
}
}
if ui.button("Save As…").clicked() {
ui.close();
if let Some(path) = rfd::FileDialog::new()
.add_filter("Map file", &["toml"])
.save_file()
{
if let Err(e) = map_file::save(&self.state.board, &path) {
eprintln!("save error: {e}");
} else {
self.current_file_path = Some(path);
}
}
}
ui.separator();
if ui.button("Exit").clicked() {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
});
// Mode toggle: Play keeps the game running; Edit shows the palette panel.
ui.separator();
ui.selectable_value(&mut self.mode, AppMode::Play, "Play");
ui.selectable_value(&mut self.mode, AppMode::Edit, "Edit");
});
});
// --- Editor side panel ---
// Must be declared before CentralPanel so egui allocates its space first.
// Track whether font_spec changed so we can reload the board font.
let font_spec_before = self.state.board.font.clone();
if self.mode == AppMode::Edit {
// Split borrows explicitly: active_font borrows board_font/default_font,
// while show_editor_panel takes &mut editor and &mut board separately.
let active_font = self.board_font.as_ref().unwrap_or(&self.default_font);
show_editor_panel(
ctx,
&mut self.editor,
&mut self.state.board,
active_font,
);
}
// If the board's font spec was changed by the editor, reload the board font.
if self.state.board.font != font_spec_before {
let spec = self.state.board.font.clone();
self.apply_font_spec(ctx, spec.as_ref());
}
// Snapshot the active font for this frame so all rendering uses the same one.
// We re-borrow active_font here since apply_font_spec may have changed board_font.
let font = self.board_font.as_ref().unwrap_or(&self.default_font);
let tw = font.tile_w as f32;
let th = font.tile_h as f32;
// --- Board rendering ---
// The board is drawn using the egui Painter API (direct 2D drawing).
egui::CentralPanel::default().show(ctx, |ui| {
let board_w = self.state.board.width;
let board_h = self.state.board.height;
let board_px = vec2(board_w as f32 * tw, board_h as f32 * th);
if self.mode == AppMode::Edit {
// Edit mode: ScrollArea lets the user scroll when the board overflows.
egui::ScrollArea::new([true, true]).show(ui, |ui| {
let (rect, response) = ui.allocate_exact_size(board_px, Sense::click());
draw_board(ui.painter(), rect.min, &self.state.board, font);
// When the Objects tab is active, overlay the object highlights.
if self.editor.tab == EditorTab::Objects {
draw_object_overlays(
ui.painter(),
rect.min,
&self.state.board,
font,
self.editor.selected_object,
);
}
if response.clicked()
&& let Some(pos) = response.interact_pointer_pos()
{
let (cx, cy) = pos_to_cell(rect.min, pos, tw, th);
if cx >= 0 && cy >= 0 {
let cx = cx as usize;
let cy = cy as usize;
let board = &mut self.state.board;
if cx < board.width && cy < board.height {
if self.editor.tab == EditorTab::Objects {
if self.editor.placing_object {
// Placement mode: create a new object here if none exists.
if board.object_at(cx, cy).is_none() {
board.objects.push(ObjectDef {
x: cx,
y: cy,
glyph: Glyph {
tile: Archetype::Object.default_glyph().tile,
fg: Archetype::Object.default_glyph().fg,
bg: Archetype::Object.default_glyph().bg,
},
script_name: None,
});
}
self.editor.placing_object = false;
} else {
// Selection mode: click to select an existing object.
let found = board.object_at(cx, cy);
self.editor.selected_object = found;
self.editor.object_glyph_picker_open = false;
if let Some(i) = found {
// Snapshot the object's glyph for the picker.
self.editor.object_editing_glyph =
board.objects[i].glyph;
}
}
} else {
// Other tabs: paint the grid cell (floor only).
// Objects on this cell are left untouched — they sit on top.
*board.get_mut(cx, cy) = (self.editor.glyph, self.editor.selected);
}
}
}
}
});
} else {
// Play mode: player-centered viewport, no scroll bars.
let available = ui.available_rect_before_wrap();
let player = self.state.board.player;
let origin = board_origin(available, board_w, board_h, player, font);
draw_board(ui.painter(), origin, &self.state.board, font);
}
});
// --- Glyph picker dialog (Palette tab) ---
// Rendered after all panels so it floats on top.
if self.editor.glyph_picker_open {
let font = self.board_font.as_ref().unwrap_or(&self.default_font);
glyph_picker::show(
ctx,
&mut self.editor.glyph_picker_open,
&mut self.editor.glyph,
&self.state.board.cells(),
font,
);
}
// --- Object glyph picker (Objects tab) ---
// Uses object_editing_glyph as the target to avoid aliasing board.cells.
if self.editor.object_glyph_picker_open && self.editor.tab == EditorTab::Objects {
let font = self.board_font.as_ref().unwrap_or(&self.default_font);
glyph_picker::show(
ctx,
&mut self.editor.object_glyph_picker_open,
&mut self.editor.object_editing_glyph,
&self.state.board.cells(),
font,
);
}
// --- Write back the object editing glyph to the board each frame ---
// Any change the picker made to object_editing_glyph is flushed here.
if let Some(i) = self.editor.selected_object {
if i < self.state.board.objects.len() {
self.state.board.objects[i].glyph = self.editor.object_editing_glyph;
}
}
}
}
+203
View File
@@ -0,0 +1,203 @@
// Layout constants — which value controls which part of the window:
//
// One board cell (size varies with the active font's tile dimensions):
//
// ◄── tile_w ──►
// ╔═════════════╗ ▲
// ║ @ ║ │ tile_h
// ╚═════════════╝ ▼
//
// Full window (Edit mode shown; side panel absent in Play mode):
//
// ◄────────────────── DEFAULT_WINDOW_W (840 px) ───────────────────►
// ┌────────────────────────────────────────────────────────────────┐ ▲
// │ File │ Play Edit │ │ MENU_H (24 px)
// ├────────────────────────────────────────────────┬───────────────┤ ▼
// │ PANEL_MARGIN (8 px) on all sides │ PALETTE_ │ ▲
// │ ┌──────────────────────────────────────────┐ │ PANEL_W │ │
// │ │ │ │ (200 px) │ │ DEFAULT_
// │ │ board cells (tile_w × tile_h each) │ │ Edit mode │ │ WINDOW_H
// │ │ │ │ only │ │ (524 px)
// │ └──────────────────────────────────────────┘ │ │ │
// │ │ │ ▼
// └────────────────────────────────────────────────┴───────────────┘
//
// MIN_WINDOW_W and MIN_WINDOW_H are derived: 10 cells wide / 5 cells tall plus margins.
use eframe::egui;
use egui::{Color32, Pos2, Rect, vec2};
use crate::font::BitmapFont;
use kiln_core::game::{Board, Glyph, Player};
/// Converts a core [`Glyph`] color ([`color::Rgba8`]) to egui [`Color32`].
pub(crate) fn rgba8_to_color32(c: color::Rgba8) -> Color32 {
Color32::from_rgba_unmultiplied(c.r, c.g, c.b, c.a)
}
/// Approximate height of the egui menu bar in pixels, used for window sizing.
pub(crate) const MENU_H: f32 = 24.0;
/// Default inner margin that egui's CentralPanel adds on all sides, in pixels.
pub(crate) const PANEL_MARGIN: f32 = 8.0;
/// Default width of the editor side panel in pixels. The panel is resizable.
pub(crate) const PALETTE_PANEL_W: f32 = 200.0;
/// Default window width in pixels. Independent of map size.
pub(crate) const DEFAULT_WINDOW_W: f32 = 840.0;
/// Default window height in pixels. Independent of map size.
pub(crate) const DEFAULT_WINDOW_H: f32 = 524.0;
/// Minimum window width: enough room for 10 cells plus margins (using 8 px tile width).
pub(crate) const MIN_WINDOW_W: f32 = 8.0 * 10.0 + 2.0 * PANEL_MARGIN;
/// Minimum window height: enough room for 5 cells plus menu and margins (using 8 px tile height).
pub(crate) const MIN_WINDOW_H: f32 = 8.0 * 5.0 + MENU_H + 2.0 * PANEL_MARGIN;
/// Paints a glyph into an already-allocated `rect` using a bitmap font.
///
/// Fills `rect` with `glyph.bg`, then draws the tile from `font` tinted with
/// `glyph.fg`. Unlike [`draw_glyph`], the caller owns the rect and handles
/// interaction — use this when you need the click [`egui::Response`].
pub(crate) fn paint_glyph(painter: &egui::Painter, rect: Rect, glyph: &Glyph, font: &BitmapFont) {
painter.rect_filled(rect, 0.0, rgba8_to_color32(glyph.bg));
let uv = font.tile_uv(glyph.tile);
painter.image(font.texture.id(), rect, uv, rgba8_to_color32(glyph.fg));
}
/// Draws a single cell at grid position `(x, y)` using the given glyph and font.
///
/// `origin` is the pixel position of cell `(0, 0)` — the top-left corner of
/// the board within the panel. Cell positions are computed from `origin` using
/// the font's tile dimensions.
pub(crate) fn draw_glyph(
painter: &egui::Painter,
origin: Pos2,
x: usize,
y: usize,
glyph: &Glyph,
font: &BitmapFont,
) {
let tw = font.tile_w as f32;
let th = font.tile_h as f32;
let tl = origin + vec2(x as f32 * tw, y as f32 * th);
let rect = Rect::from_min_size(tl, vec2(tw, th));
paint_glyph(painter, rect, glyph, font);
}
/// Draws all board cells, then the object overlay, then the player at `origin`.
///
/// Rendering order: grid (floor) → objects → player. Objects are drawn on top
/// of their grid cell's background, which is revealed if the object moves away.
pub(crate) fn draw_board(painter: &egui::Painter, origin: Pos2, board: &Board, font: &BitmapFont) {
// Pass 1: grid floor.
for y in 0..board.height {
for x in 0..board.width {
let (glyph, _) = board.get(x, y);
draw_glyph(painter, origin, x, y, glyph, font);
}
}
// Pass 2: objects drawn on top of the floor.
for obj in &board.objects {
draw_glyph(painter, origin, obj.x, obj.y, &obj.glyph, font);
}
// Pass 3: player overlay. Will be removed once the player becomes a scripted object.
let player_glyph = Glyph::player();
draw_glyph(
painter,
origin,
board.player.x as usize,
board.player.y as usize,
&player_glyph,
font,
);
}
/// Draws the objects-mode overlay over an already-drawn board.
///
/// Dims the entire board with a semi-transparent fill, then for each
/// [`ObjectDef`](crate::game::ObjectDef) redraws that cell at full brightness
/// and outlines it in white. The selected object (by index into
/// `board.objects`) gets a yellow outline instead.
pub(crate) fn draw_object_overlays(
painter: &egui::Painter,
origin: Pos2,
board: &Board,
font: &BitmapFont,
selected: Option<usize>,
) {
let tw = font.tile_w as f32;
let th = font.tile_h as f32;
// Dim the whole board so non-object cells recede visually.
let board_rect = Rect::from_min_size(
origin,
vec2(board.width as f32 * tw, board.height as f32 * th),
);
painter.rect_filled(board_rect, 0.0, Color32::from_black_alpha(160));
// Redraw each object cell at full brightness and surround it with an outline.
for (i, obj) in board.objects.iter().enumerate() {
let tl = origin + vec2(obj.x as f32 * tw, obj.y as f32 * th);
let rect = Rect::from_min_size(tl, vec2(tw, th));
// Redraw on top of the dim overlay so this cell remains bright.
paint_glyph(painter, rect, &obj.glyph, font);
// Yellow outline for the selected object, white for all others.
let outline = if selected == Some(i) {
Color32::YELLOW
} else {
Color32::WHITE
};
painter.rect_stroke(rect, 0.0, (1.0, outline), egui::StrokeKind::Outside);
}
}
/// Converts a pixel position to cell coordinates relative to `origin`.
///
/// Uses floor so positions above or left of `origin` produce negative values —
/// callers must guard `>= 0` before treating the result as a valid cell index.
pub(crate) fn pos_to_cell(origin: Pos2, pos: Pos2, tile_w: f32, tile_h: f32) -> (i32, i32) {
let rel = pos - origin;
(
(rel.x / tile_w).floor() as i32,
(rel.y / tile_h).floor() as i32,
)
}
/// Computes the pixel position of board cell (0, 0) within `available`.
///
/// If the board fits along an axis, it is centered. If it overflows, the
/// viewport is centered on the player and clamped so no empty space appears
/// at the board edges.
pub(crate) fn board_origin(
available: Rect,
board_w: usize,
board_h: usize,
player: Player,
font: &BitmapFont,
) -> Pos2 {
let tw = font.tile_w as f32;
let th = font.tile_h as f32;
let board_px_w = board_w as f32 * tw;
let board_px_h = board_h as f32 * th;
let origin_x = if board_px_w <= available.width() {
// Board fits: center it horizontally.
available.min.x + (available.width() - board_px_w) / 2.0
} else {
// Board overflows: keep player at viewport center, clamp to board edges.
let player_px_x = player.x as f32 * tw + tw / 2.0;
(available.center().x - player_px_x)
.max(available.max.x - board_px_w) // right edge must reach viewport right
.min(available.min.x) // left edge must reach viewport left
};
let origin_y = if board_px_h <= available.height() {
available.min.y + (available.height() - board_px_h) / 2.0
} else {
let player_px_y = player.y as f32 * th + th / 2.0;
(available.center().y - player_px_y)
.max(available.max.y - board_px_h)
.min(available.min.y)
};
Pos2::new(origin_x, origin_y)
}