Skip to main content

yog_book/
renderer.rs

1//! Book renderer — ties together yog-ui layout, yog-gfx GPU pipeline,
2//! SVG icon rasterization, and custom font rendering.
3
4use std::collections::HashMap;
5use yog_gfx::{GfxContext, gl, core::{DrawMode, DataType, blend}};
6use yog_ui::{widget, FlexDir, Align, UiRoot};
7
8use crate::{Book, BookPage};
9use crate::state::BookViewState;
10use crate::theme::BookTheme;
11use crate::font::{BookFontRegistry, FontAtlas};
12use crate::svg;
13
14// Patchouli-compatible book texture layout (512×256 sprite sheet).
15// UV coordinates are in pixels on a 512×256 sheet.
16// The full open-book background occupies 272×180 at UV (0,0).
17pub const BOOK_TEX_W: f32   = 512.0;
18pub const BOOK_TEX_H: f32   = 256.0;
19// Open-book dimensions in texture-space
20pub const BK_W: f32         = 272.0;
21pub const BK_H: f32         = 180.0;
22// Per-page dimensions and offsets (in book-local coords)
23pub const PAGE_W: f32       = 116.0;
24pub const PAGE_H: f32       = 156.0;
25pub const TOP_PAD: f32      = 18.0;   // vertical space above page text area
26pub const LEFT_X: f32       = 15.0;   // left page X inside book
27pub const RIGHT_X: f32      = 141.0;  // right page X inside book
28// Separator strip UV origin on the sprite sheet
29pub const SEP_U: f32        = 140.0;
30pub const SEP_V: f32        = 180.0;
31pub const SEP_W: f32        = 110.0;
32pub const SEP_H: f32        = 3.0;
33
34// ── Vertex for the custom 2D shader (pos + uv + color) ───────────────────────
35
36#[repr(C)]
37#[derive(Copy, Clone)]
38struct Vert { x: f32, y: f32, u: f32, v: f32, r: f32, g: f32, b: f32, a: f32 }
39
40fn rgba_f(c: u32) -> (f32, f32, f32, f32) {
41    let a = ((c >> 24) & 0xFF) as f32 / 255.0;
42    let r = ((c >> 16) & 0xFF) as f32 / 255.0;
43    let g = ((c >>  8) & 0xFF) as f32 / 255.0;
44    let b = ( c        & 0xFF) as f32 / 255.0;
45    (r, g, b, a)
46}
47
48fn quad(verts: &mut Vec<Vert>, x: f32, y: f32, w: f32, h: f32,
49        u0: f32, v0: f32, u1: f32, v1: f32, color: u32) {
50    let (r, g, b, a) = rgba_f(color);
51    let p = [
52        Vert { x,        y,        u: u0, v: v0, r, g, b, a },
53        Vert { x: x+w,   y,        u: u1, v: v0, r, g, b, a },
54        Vert { x,        y: y+h,   u: u0, v: v1, r, g, b, a },
55        Vert { x: x+w,   y: y+h,   u: u1, v: v1, r, g, b, a },
56    ];
57    // two triangles: 0,1,2  1,3,2
58    verts.extend_from_slice(&[p[0], p[1], p[2], p[1], p[3], p[2]]);
59}
60
61// ── GLSL shaders ─────────────────────────────────────────────────────────────
62
63const VERT: &str = r#"
64#version 330 core
65layout(location = 0) in vec2 aPos;
66layout(location = 1) in vec2 aUv;
67layout(location = 2) in vec4 aCol;
68out vec2 fUv;
69out vec4 fCol;
70uniform vec2 uScreen;
71void main() {
72    fUv  = aUv;
73    fCol = aCol;
74    vec2 ndc = aPos / uScreen * 2.0 - vec2(1.0);
75    gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
76}
77"#;
78
79const FRAG: &str = r#"
80#version 330 core
81in vec2 fUv;
82in vec4 fCol;
83out vec4 outColor;
84uniform sampler2D uTex;
85uniform int uMode;  // 0 = solid color, 1 = RGBA texture, 2 = alpha-only (font)
86void main() {
87    if (uMode == 0) {
88        outColor = fCol;
89    } else if (uMode == 1) {
90        outColor = texture(uTex, fUv) * fCol;
91    } else {
92        float alpha = texture(uTex, fUv).a;
93        outColor = vec4(fCol.rgb, fCol.a * alpha);
94    }
95}
96"#;
97
98// ── Embedded textures ─────────────────────────────────────────────────────────
99
100static BOOK_PNG:     &[u8] = include_bytes!("../assets/book_brown.png");
101static CRAFTING_PNG: &[u8] = include_bytes!("../assets/crafting.png");
102
103fn decode_png(data: &[u8]) -> Option<(Vec<u8>, u32, u32)> {
104    use png::Decoder;
105    let decoder = Decoder::new(std::io::Cursor::new(data));
106    let mut reader = decoder.read_info().ok()?;
107    let mut buf = vec![0u8; reader.output_buffer_size()];
108    let info = reader.next_frame(&mut buf).ok()?;
109    let rgba = match info.color_type {
110        png::ColorType::Rgba => buf[..info.buffer_size()].to_vec(),
111        png::ColorType::Rgb  => {
112            let rgb = &buf[..info.buffer_size()];
113            let mut out = Vec::with_capacity(rgb.len() / 3 * 4);
114            for px in rgb.chunks(3) { out.extend_from_slice(px); out.push(255); }
115            out
116        }
117        _ => return None,
118    };
119    Some((rgba, info.width, info.height))
120}
121
122// ── GL resource cache ─────────────────────────────────────────────────────────
123
124struct BookGl {
125    prog:         gl::ShaderProgram,
126    vao:          gl::VertexArray,
127    vbo:          gl::Buffer,
128    book_tex:     Option<(gl::Texture, u32, u32)>,
129    crafting_tex: Option<(gl::Texture, u32, u32)>,
130    svg_tex:      HashMap<u64, (gl::Texture, u32, u32)>,
131    font_atlas:   HashMap<u64, (gl::Texture, FontAtlas)>,
132}
133
134impl BookGl {
135    fn init(ctx: &GfxContext) -> Option<Self> {
136        let prog = ctx.create_shader(VERT, FRAG).ok()?;
137        let vbo  = ctx.create_buffer();
138        let vao  = ctx.create_vao();
139
140        const STRIDE: u32 = 32; // 8 × f32
141        vao.attrib(ctx, &vbo, 0, 2, DataType::F32, false, STRIDE, 0);  // pos
142        vao.attrib(ctx, &vbo, 1, 2, DataType::F32, false, STRIDE, 8);  // uv
143        vao.attrib(ctx, &vbo, 2, 4, DataType::F32, false, STRIDE, 16); // col
144
145        let load = |data: &[u8]| decode_png(data).map(|(rgba, w, h)| {
146            let tex = ctx.create_texture_rgba(w, h, &rgba, true);
147            (tex, w, h)
148        });
149        let book_tex     = load(BOOK_PNG);
150        let crafting_tex = load(CRAFTING_PNG);
151
152        Some(BookGl { prog, vao, vbo, book_tex, crafting_tex,
153                      svg_tex: HashMap::new(), font_atlas: HashMap::new() })
154    }
155
156    fn svg_tex(&mut self, ctx: &GfxContext, hash: u64, data: &str, w: u32, h: u32)
157        -> Option<&(gl::Texture, u32, u32)>
158    {
159        if !self.svg_tex.contains_key(&hash) {
160            let pixels = svg::rasterize(data, w, h)?;
161            let tex = ctx.create_texture_rgba(w, h, &pixels, true);
162            self.svg_tex.insert(hash, (tex, w, h));
163        }
164        self.svg_tex.get(&hash)
165    }
166
167    fn flush(&self, ctx: &GfxContext, verts: &[Vert]) {
168        if verts.is_empty() { return; }
169        unsafe { self.vbo.upload(ctx, verts, true); }
170        ctx.draw_arrays(&self.vao, &self.prog, DrawMode::Triangles, 0, verts.len() as u32);
171    }
172}
173
174// ── Draw helpers ──────────────────────────────────────────────────────────────
175
176impl BookGl {
177    fn begin_frame(&self, ctx: &GfxContext, sw: f32, sh: f32) {
178        ctx.set_blend(true, blend::SRC_ALPHA, blend::ONE_MINUS_SRC_ALPHA);
179        ctx.set_depth(false, false);
180        self.prog.uniform_2f(ctx, "uScreen", sw, sh);
181        self.prog.uniform_1i(ctx, "uTex", 0);
182    }
183
184    /// Blit a subrect of a sprite sheet at an arbitrary screen position.
185    fn draw_book_sprite(&self, ctx: &GfxContext, spr: &BgSprite) {
186        let sheet = match spr.sheet {
187            SpriteSheet::Book     => &self.book_tex,
188            SpriteSheet::Crafting => &self.crafting_tex,
189        };
190        let Some((tex, tw, th)) = sheet else { return };
191        let u0 = spr.u  / *tw as f32;
192        let v0 = spr.v  / *th as f32;
193        let u1 = (spr.u + spr.uw) / *tw as f32;
194        let v1 = (spr.v + spr.uh) / *th as f32;
195        self.prog.uniform_1i(ctx, "uMode", 1);
196        ctx.bind_texture(0, tex);
197        let mut v = Vec::with_capacity(6);
198        quad(&mut v, spr.x, spr.y, spr.w, spr.h, u0, v0, u1, v1, 0xFF_FFFFFF);
199        self.flush(ctx, &v);
200    }
201
202    /// Blit the open-book background from the embedded book texture.
203    fn draw_book_bg(&self, ctx: &GfxContext, bx: f32, by: f32, bw: f32, bh: f32) {
204        let Some((tex, tw, th)) = &self.book_tex else { return };
205        let su = BK_W / *tw as f32;
206        let sv = BK_H / *th as f32;
207        self.prog.uniform_1i(ctx, "uMode", 1);
208        ctx.bind_texture(0, tex);
209        let mut v = Vec::with_capacity(6);
210        quad(&mut v, bx, by, bw, bh, 0.0, 0.0, su, sv, 0xFF_FFFFFF);
211        self.flush(ctx, &v);
212    }
213
214    fn draw_svg(&mut self, ctx: &GfxContext, data: &str, x: f32, y: f32, w: f32, h: f32) {
215        let hash = svg::svg_hash(data);
216        let tw = w as u32; let th = h as u32;
217        if let Some(&(tex, _, _)) = self.svg_tex(ctx, hash, data, tw, th) {
218            self.prog.uniform_1i(ctx, "uMode", 1);
219            ctx.bind_texture(0, &tex);
220            let mut v = Vec::with_capacity(6);
221            quad(&mut v, x, y, w, h, 0.0, 0.0, 1.0, 1.0, 0xFF_FFFFFF);
222            self.flush(ctx, &v);
223        }
224    }
225
226    fn draw_text_custom(&mut self, ctx: &GfxContext, ttf: &[u8], size_px: f32,
227                        text: &str, mut x: f32, y: f32, color: u32) {
228        let hash = font_hash(ttf);
229        if !self.font_atlas.contains_key(&hash) {
230            if let Some(atlas) = FontAtlas::build(ttf, size_px) {
231                let tex = ctx.create_texture_rgba(
232                    atlas.atlas_size, atlas.atlas_size, &atlas.pixels, true);
233                self.font_atlas.insert(hash, (tex, atlas));
234            }
235        }
236        // Get raw pointers so the borrow of self.font_atlas ends before we call
237        // self.prog / self.flush, which also borrow fields of self.
238        let ptrs = self.font_atlas.get(&hash)
239            .map(|(t, a)| (t as *const gl::Texture, a as *const FontAtlas));
240        if let Some((tex_ptr, atlas_ptr)) = ptrs {
241            // SAFETY: we hold &mut self; font_atlas is not mutated below.
242            let tex   = unsafe { &*tex_ptr   };
243            let atlas = unsafe { &*atlas_ptr };
244            self.prog.uniform_1i(ctx, "uMode", 2);
245            ctx.bind_texture(0, tex);
246            let baseline = y + size_px;
247            let mut verts = Vec::new();
248            for ch in text.chars() {
249                if let Some(g) = atlas.glyphs.get(&ch) {
250                    if g.width > 0 {
251                        let gx = x + g.xoff;
252                        let gy = baseline - g.yoff - g.height as f32;
253                        quad(&mut verts, gx, gy, g.width as f32, g.height as f32,
254                             g.u0, g.v0, g.u1, g.v1, color);
255                    }
256                    x += g.advance;
257                }
258            }
259            self.flush(ctx, &verts);
260        }
261    }
262}
263
264fn font_hash(data: &[u8]) -> u64 {
265    use std::hash::{Hash, Hasher};
266    let mut h = std::collections::hash_map::DefaultHasher::new();
267    data.hash(&mut h);
268    h.finish()
269}
270
271// ── Background sprite (texture blit, drawn before yog-ui) ────────────────────
272
273#[derive(Clone, Copy, PartialEq)]
274pub(crate) enum SpriteSheet { Book, Crafting }
275
276/// A subrect blit from one of the embedded sprite sheets, drawn before yog-ui.
277#[derive(Clone)]
278pub(crate) struct BgSprite {
279    pub sheet: SpriteSheet,
280    /// Source rect in pixels on the sheet.
281    pub u: f32, pub v: f32, pub uw: f32, pub uh: f32,
282    /// Destination on screen.
283    pub x: f32, pub y: f32, pub w: f32, pub h: f32,
284}
285
286// ── Pending overlay draw commands ─────────────────────────────────────────────
287
288#[derive(Clone)]
289pub(crate) enum OverlayCmd {
290    Svg    { data: String, x: f32, y: f32, w: f32, h: f32 },
291    Text   { text: String, font: crate::font::BookFont, x: f32, y: f32, color: u32 },
292    /// MC default-font text rendered via draw2d (e.g. nameplate title/subtitle).
293    McText { text: String, x: f32, y: f32, color: u32 },
294    /// Item icon rendered through our GL pipeline from an MC-managed texture.
295    McItem { item_id: String, x: f32, y: f32, w: f32, h: f32 },
296}
297
298// ── Recipe visuals (parsed from registered recipe JSON) ───────────────────────
299
300#[derive(Clone)]
301pub(crate) enum RecipeVis {
302    Shaped    { grid: Vec<Option<String>>, width: usize, output: String, count: u32 },
303    Shapeless { ingredients: Vec<String>, output: String, count: u32 },
304    Smelting  { input: String, output: String },
305}
306
307fn parse_recipe(json: &str) -> Option<RecipeVis> {
308    let v: serde_json::Value = serde_json::from_str(json).ok()?;
309    match v.get("type")?.as_str()? {
310        "minecraft:crafting_shaped" => {
311            let pattern: Vec<&str> = v.get("pattern")?.as_array()?
312                .iter().filter_map(|p| p.as_str()).collect();
313            let width = pattern.iter().map(|r| r.chars().count()).max()?.max(1);
314            let key = v.get("key")?.as_object()?;
315            let mut grid = Vec::new();
316            for row in &pattern {
317                let mut chars: Vec<char> = row.chars().collect();
318                chars.resize(width, ' ');
319                for ch in chars {
320                    grid.push(key.get(&ch.to_string())
321                        .and_then(|k| k.get("item")).and_then(|i| i.as_str())
322                        .map(str::to_owned));
323                }
324            }
325            let result = v.get("result")?;
326            Some(RecipeVis::Shaped {
327                grid, width,
328                output: result.get("item")?.as_str()?.to_owned(),
329                count:  result.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as u32,
330            })
331        }
332        "minecraft:crafting_shapeless" => {
333            let ingredients = v.get("ingredients")?.as_array()?.iter()
334                .filter_map(|i| i.get("item").and_then(|x| x.as_str()).map(str::to_owned))
335                .collect();
336            let result = v.get("result")?;
337            Some(RecipeVis::Shapeless {
338                ingredients,
339                output: result.get("item")?.as_str()?.to_owned(),
340                count:  result.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as u32,
341            })
342        }
343        "minecraft:smelting" | "minecraft:blasting"
344        | "minecraft:smoking" | "minecraft:campfire_cooking" => {
345            Some(RecipeVis::Smelting {
346                input:  v.get("ingredient")?.get("item")?.as_str()?.to_owned(),
347                output: v.get("result")?.as_str()?.to_owned(),
348            })
349        }
350        _ => None,
351    }
352}
353
354/// Normalize icon ids like "yog:item/ruby" / "yog:block/x" to registry item
355/// ids ("yog:ruby") accepted by the MC item renderer.
356fn normalize_item_id(id: &str) -> String {
357    let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
358    let name = path.trim_start_matches("item/").trim_start_matches("block/");
359    format!("{ns}:{name}")
360}
361
362/// "yog:ruby_block" → "Ruby Block" (fallback display name from an item id).
363fn pretty_item_name(id: &str) -> String {
364    let name = id.rsplit(':').next().unwrap_or(id);
365    name.split('_')
366        .map(|w| {
367            let mut c = w.chars();
368            match c.next() {
369                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
370                None    => String::new(),
371            }
372        })
373        .collect::<Vec<_>>()
374        .join(" ")
375}
376
377// ── BookRenderer ──────────────────────────────────────────────────────────────
378
379pub struct BookRenderer {
380    pub book:  Book,
381    pub state: BookViewState,
382    pub theme: BookTheme,
383    fonts:        BookFontRegistry,
384    recipes:      HashMap<String, RecipeVis>,
385    gl:           Option<BookGl>,
386    pub ui:       Option<UiRoot>,
387    bg_sprites:   Vec<BgSprite>,
388    overlays:     Vec<OverlayCmd>,
389    dirty:   bool,
390    last_sw: f32,
391    last_sh: f32,
392}
393
394impl BookRenderer {
395    pub fn new(book: Book) -> Self {
396        let theme = BookTheme::default().with_nameplate(&book.nameplate_color);
397        Self {
398            book,
399            state: BookViewState::default(),
400            theme,
401            fonts: BookFontRegistry::default(),
402            recipes: HashMap::new(),
403            gl: None,
404            ui: None,
405            bg_sprites: Vec::new(),
406            overlays: Vec::new(),
407            dirty: true,
408            last_sw: 0.0,
409            last_sh: 0.0,
410        }
411    }
412
413    pub fn handle_event(&mut self, ev: &str) {
414        if self.state.handle(ev, &self.book) {
415            self.dirty = true;
416        }
417    }
418
419    /// Register a custom TTF/OTF font for use in `BookPage::CustomText`.
420    pub fn register_font(&mut self, id: impl Into<String>, ttf: Vec<u8>) {
421        self.fonts.register(id, ttf);
422    }
423
424    /// Register a recipe (vanilla recipe JSON) so Crafting/Smelting pages can
425    /// render it visually. Unknown recipe types are ignored.
426    pub fn add_recipe(&mut self, id: impl Into<String>, json: &str) {
427        if let Some(vis) = parse_recipe(json) {
428            self.recipes.insert(id.into(), vis);
429            self.dirty = true;
430        }
431    }
432
433    pub fn render(&mut self, ctx: &GfxContext, sw: f32, sh: f32) {
434        // Lazy GL init.
435        if self.gl.is_none() {
436            self.gl = BookGl::init(ctx);
437        }
438
439        // Render at Patchouli-native size (272×180 GUI pixels). Scale DOWN only
440        // if the screen is smaller; never scale up (MC font is designed for 1×).
441        let scale = ((sw - 16.0) / BK_W).min((sh - 16.0) / BK_H).min(1.0).max(0.4);
442        let bw = BK_W * scale;
443        let bh = BK_H * scale;
444        let bx = (sw - bw) / 2.0;
445        let by = (sh - bh) / 2.0;
446
447        // Rebuild widget tree if dirty or screen resized.
448        if self.dirty || sw != self.last_sw || sh != self.last_sh {
449            let (root, bg_sprites, overlays) = build_ui(&self.book, &self.state, &self.theme, &self.recipes, sw, sh, bx, by, bw, bh);
450            self.ui = Some(root);
451            self.bg_sprites = bg_sprites;
452            self.overlays = overlays;
453            self.dirty = false;
454            self.last_sw = sw;
455            self.last_sh = sh;
456        }
457
458        // 1. Draw book background texture first.
459        if let Some(gl) = &mut self.gl {
460            gl.begin_frame(ctx, sw, sh);
461            gl.draw_book_bg(ctx, bx, by, bw, bh);
462        }
463
464        // 1b. Background sprites (nameplate banner, separator lines) from book texture.
465        if let Some(gl) = &mut self.gl {
466            for spr in &self.bg_sprites {
467                gl.draw_book_sprite(ctx, spr);
468            }
469        }
470
471        // 2. yog-ui: text, buttons, icons (transparent BG — texture is already there).
472        if let Some(ui) = &mut self.ui {
473            if ui.needs_layout { ui.layout(sw, sh); }
474            ui.render(ctx);
475        }
476
477        // 3. Custom GL overlays (SVG icons, custom font text) — raw GL first.
478        if let Some(gl) = &mut self.gl {
479            gl.begin_frame(ctx, sw, sh);
480            for ov in self.overlays.clone() {
481                match ov {
482                    OverlayCmd::Svg  { data, x, y, w, h } =>
483                        gl.draw_svg(ctx, &data, x, y, w, h),
484                    OverlayCmd::Text { text, font, x, y, color } => {
485                        if let Some(ttf) = self.fonts.get(&font.font_id) {
486                            gl.draw_text_custom(ctx, ttf, font.size_px, &text, x, y, color);
487                        }
488                    }
489                    OverlayCmd::McText { .. } | OverlayCmd::McItem { .. } => {}
490                }
491            }
492        }
493
494        // 4. MC-pipeline overlays (item stacks, MC-font text) — after all raw
495        //    GL, because item rendering resyncs and mutates MC's GL state.
496        for ov in self.overlays.clone() {
497            match ov {
498                OverlayCmd::McItem { item_id, x, y, w, h } => {
499                    ctx.draw2d().item(&normalize_item_id(&item_id), x, y, w.min(h));
500                }
501                OverlayCmd::McText { text, x, y, color } => {
502                    ctx.draw2d().text(&text, x, y, color, false);
503                }
504                _ => {}
505            }
506        }
507    }
508}
509
510// ── UI builder ────────────────────────────────────────────────────────────────
511
512/// Book label: MC font, no drop-shadow (Patchouli draws book text shadowless).
513fn lbl(text: impl Into<String>) -> widget::Widget { widget::label(text).shadow(false) }
514/// Book button: no drop-shadow.
515fn btn(text: impl Into<String>) -> widget::Widget { widget::button(text).shadow(false) }
516
517/// Build the yog-ui widget tree + bg sprites + overlay commands for the current book state.
518/// `bx/by/bw/bh` are the screen-space book rect (same values used to blit the bg texture).
519fn build_ui(book: &Book, state: &BookViewState, theme: &BookTheme,
520             recipes: &HashMap<String, RecipeVis>,
521             sw: f32, sh: f32,
522             bx: f32, by: f32, bw: f32, bh: f32) -> (UiRoot, Vec<BgSprite>, Vec<OverlayCmd>) {
523    let _ = (sw, sh);
524    let mut bg_sprites: Vec<BgSprite> = Vec::new();
525    let mut overlays:   Vec<OverlayCmd> = Vec::new();
526
527    // Scale from Patchouli's fixed BK_W×BK_H coordinate space → actual bw×bh.
528    let sx = bw / BK_W;
529    let sy = bh / BK_H;
530
531    // In book-local: left page starts at x=LEFT_X, right at RIGHT_X, both y=TOP_PAD.
532    let pw = PAGE_W * sx;
533    let ph = PAGE_H * sy;
534    let spine_gap = (RIGHT_X - LEFT_X - PAGE_W) * sx; // ≈10px scaled
535
536    // Content x/y in screen space (for SVG overlay positioning).
537    let lx = bx + LEFT_X  * sx;
538    let rx = bx + RIGHT_X * sx;
539    let py = by + TOP_PAD  * sy;
540
541    // Separator x offset within a page: centered = PAGE_W/2 - SEP_W/2 = 58-55 = 3.
542    let sep_cx = (PAGE_W / 2.0 - SEP_W / 2.0) * sx; // = 3*sx
543
544    if state.at_home {
545        // Nameplate banner: book-local (-8, 12) from LEFT_PAGE_X, size 140×31.
546        bg_sprites.push(BgSprite {
547            sheet: SpriteSheet::Book,
548            u: 0.0, v: 180.0, uw: 140.0, uh: 31.0,
549            x: bx + (LEFT_X - 8.0) * sx,
550            y: by + 12.0 * sy,
551            w: 140.0 * sx,
552            h: 31.0 * sy,
553        });
554        // Separator below "Categories" header on right page (y=12 page-local), centered.
555        bg_sprites.push(BgSprite {
556            sheet: SpriteSheet::Book,
557            u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
558            x: rx + sep_cx,
559            y: by + (TOP_PAD + 12.0) * sy,
560            w: SEP_W * sx,
561            h: (SEP_H * sy).max(1.0),
562        });
563    } else {
564        // Entry view: separator on right page below category name (y=12 page-local).
565        bg_sprites.push(BgSprite {
566            sheet: SpriteSheet::Book,
567            u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
568            x: rx + sep_cx,
569            y: by + (TOP_PAD + 12.0) * sy,
570            w: SEP_W * sx,
571            h: (SEP_H * sy).max(1.0),
572        });
573    }
574
575    let (left_page, right_page) = if state.at_home {
576        let l = build_landing_left(book, theme, pw, ph, lx, py, sx, sy, bx, by, &mut overlays);
577        let r = build_categories_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
578        (l, r)
579    } else {
580        let l = build_entry_left(book, state, theme, recipes, pw, ph, lx, py, sx, sy, sep_cx, &mut bg_sprites, &mut overlays);
581        let r = build_entries_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
582        (l, r)
583    };
584
585    // Root row spans the full book width.
586    // padding-left = LEFT_X*sx offsets both pages from the left cover edge.
587    // padding-top  = TOP_PAD*sy offsets from the header banner.
588    // spine_gap spacer sits between the two pages.
589    // gap must be 0: analytic overlay positions assume pages sit exactly at
590    // LEFT_X / RIGHT_X — any flex gap would shift widgets (and their focus
591    // highlights) away from the absolutely-positioned icons.
592    let root_widget = widget::panel(FlexDir::Row)
593        .w(bw).h(bh)
594        .gap(0.0)
595        .padding(TOP_PAD * sy, 0.0, 0.0, LEFT_X * sx)
596        .child(left_page)
597        .child(widget::spacer().w(spine_gap))  // spine gap
598        .child(right_page);
599
600    // Outer shell: positions the book on screen via a full-screen transparent Row.
601    // We use a Column + Row arrangement to apply top/left offsets without margin support.
602    let outer = widget::panel(FlexDir::Column)
603        .w(bw).h(bh)
604        .child(root_widget);
605
606    // Screen-level container: positions book at (bx, by).
607    // bx offset via padding, by offset via padding-top.
608    // Note: layout computes from (0,0), so we pass bx/by into the UiRoot manually
609    // by wrapping in a full-screen panel with the right padding.
610    let screen_root = widget::panel(FlexDir::Row)
611        .padding(by, 0.0, 0.0, bx)
612        .child(outer);
613
614    let ui = UiRoot::new(&book.id, screen_root);
615    (ui, bg_sprites, overlays)
616}
617
618// ── Left page: landing (home view) ───────────────────────────────────────────
619
620fn build_landing_left(
621    book: &Book, theme: &BookTheme,
622    page_w: f32, page_h: f32,
623    _lx: f32, _py: f32,
624    sx: f32, sy: f32,
625    bx: f32, by: f32,
626    overlays: &mut Vec<OverlayCmd>,
627) -> widget::Widget {
628    // Patchouli: title at book-local (13, 16), subtitle at (24, 24).
629    // These overlap the nameplate sprite which is above/within the page top.
630    overlays.push(OverlayCmd::McText {
631        text: book.name.clone(),
632        x: bx + 13.0 * sx,
633        y: by + 16.0 * sy,
634        color: theme.nameplate,
635    });
636    if let Some(author) = &book.author {
637        overlays.push(OverlayCmd::McText {
638            text: format!("by {}", author),
639            x: bx + 24.0 * sx,
640            y: by + 24.0 * sy,
641            color: theme.nameplate,
642        });
643    }
644
645    // Widget content: landing text + entry count.
646    // Landing text starts at page-local y=25 (= book-local y=43).
647    // We push it down with top padding = 25*sy.
648    let mut col = widget::panel(FlexDir::Column)
649        .w(page_w).h(page_h)
650        .padding(25.0 * sy, 6.0, 4.0, 4.0)
651        .gap(0.0);
652
653    for para in book.landing_text.split('\n') {
654        if para.is_empty() {
655            col = col.child(widget::spacer().h(4.0 * sy));
656        } else {
657            col = col.child(lbl(para).color(theme.text));
658        }
659    }
660
661    let total = book.entries.len();
662    col = col.child(widget::spacer().flex(1.0));
663    col = col.child(
664        lbl(format!("{} entries", total))
665            .color(theme.nav).h(9.0 * sy).align(Align::Center)
666    );
667    col
668}
669
670// ── Right page: category list (home view) ────────────────────────────────────
671
672fn build_categories_right(
673    book: &Book, state: &BookViewState, theme: &BookTheme,
674    page_w: f32, page_h: f32,
675    rx: f32, py: f32,
676    sx: f32, sy: f32,
677    overlays: &mut Vec<OverlayCmd>,
678) -> widget::Widget {
679    // Patchouli right-page layout (landing):
680    //   "Categories" header at page-local y=0, centered
681    //   Separator at page-local y=12 (drawn as bg sprite, not here)
682    //   4-column 24×24 icon grid starting at page-local (10, 25)
683    let cell_w = 24.0 * sx;
684    let cell_h = 24.0 * sy;
685    let grid_pad_left = 10.0 * sx;
686    let header_h = 9.0 * sy;
687
688    let mut col = widget::panel(FlexDir::Column)
689        .w(page_w).h(page_h)
690        .padding(0.0, 4.0, 4.0, 0.0)
691        .gap(0.0);
692
693    col = col.child(
694        lbl("Categories").color(theme.divider).h(header_h).align(Align::Center)
695    );
696    // Gap covering the separator region up to grid start (page-local y=25).
697    col = col.child(widget::spacer().h(25.0 * sy - header_h));
698
699    // 4-column icon grid; icons drawn as GL overlays at exact Patchouli positions.
700    let cats = &book.categories;
701    let icon_s = 16.0 * sx.min(sy);
702    let mut row_i = 0usize;
703    loop {
704        let row_start = row_i * 4;
705        if row_start >= cats.len() { break; }
706        let mut row = widget::panel(FlexDir::Row)
707            .h(cell_h)
708            .gap(0.0)
709            .padding(0.0, 0.0, 0.0, grid_pad_left);
710        for col_i in 0..4 {
711            let idx = row_start + col_i;
712            if idx >= cats.len() { break; }
713            let cat = &cats[idx];
714            let selected = !state.at_home && idx == state.cat;
715            let bg = if selected { theme.nav_selected_bg } else { 0 };
716
717            if let Some(icon_id) = &cat.icon {
718                overlays.push(OverlayCmd::McItem {
719                    item_id: icon_id.clone(),
720                    x: rx + (10.0 + col_i as f32 * 24.0 + 4.0) * sx,
721                    y: py + (25.0 + row_i as f32 * 24.0 + 4.0) * sy,
722                    w: icon_s, h: icon_s,
723                });
724            }
725            let cell = widget::panel(FlexDir::Column)
726                .w(cell_w).h(cell_h).bg(bg)
727                .on_click(format!("cat:{}", idx))
728                .id(format!("book_cat_{}", idx));
729            row = row.child(cell);
730        }
731        col = col.child(row);
732        row_i += 1;
733    }
734    col
735}
736
737// ── Left page: entry content (entry view) ────────────────────────────────────
738
739fn build_entry_left(
740    book: &Book, state: &BookViewState, theme: &BookTheme,
741    recipes: &HashMap<String, RecipeVis>,
742    page_w: f32, page_h: f32,
743    ox: f32, oy: f32,
744    sx: f32, sy: f32,
745    sep_cx: f32,
746    bg_sprites: &mut Vec<BgSprite>,
747    overlays: &mut Vec<OverlayCmd>,
748) -> widget::Widget {
749    let entry      = state.current_entry(book);
750    let page       = entry.and_then(|e| e.pages.get(state.page));
751    let page_count = state.page_count(book);
752    let title_text = entry.map(|e| e.name.as_str()).unwrap_or("");
753
754    // Patchouli PageText page 0:
755    //   title centered at page-local (PAGE_W/2, 0)
756    //   separator at page-local (0, 12)  → centered ≡ sep_cx offset
757    //   text body at page-local (0, 22)
758    let title_h  = 9.0 * sy;
759    let sep_h_px = (SEP_H * sy).max(1.0);
760    let sep_y    = oy + 12.0 * sy;
761    let body_oy  = oy + 22.0 * sy;
762
763    bg_sprites.push(BgSprite {
764        sheet: SpriteSheet::Book,
765        u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
766        x: ox + sep_cx, y: sep_y,
767        w: SEP_W * sx, h: sep_h_px,
768    });
769
770    let page_label = format!("{}/{}", state.page + 1, page_count);
771    let nav = widget::panel(FlexDir::Row)
772        .h(12.0 * sy).gap(4.0)
773        .padding(0.0, 2.0, 0.0, 2.0)
774        .child(btn("◀").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
775            .on_click("prev_page").id("prev_page"))
776        .child(lbl(&page_label).color(theme.nav).flex(1.0).align(Align::Center))
777        .child(btn("⌂").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
778            .on_click("home").id("book_home"))
779        .child(btn("▶").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
780            .on_click("next_page").id("next_page"));
781
782    let page_body = build_page(page, state.page, theme, recipes, bg_sprites, overlays, ox, body_oy, sx, sy);
783
784    widget::panel(FlexDir::Column)
785        .w(page_w).h(page_h)
786        .padding(0.0, 6.0, 4.0, 4.0)
787        .gap(0.0)
788        .child(lbl(title_text).color(theme.title).h(title_h).align(Align::Center))
789        .child(widget::spacer().h((12.0 - 9.0) * sy))  // gap: title end → sep start
790        .child(widget::spacer().h(sep_h_px))             // height occupied by sep sprite
791        .child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy)) // gap: sep end → body
792        .child(page_body)
793        .child(nav)
794}
795
796// ── Right page: entry list for selected category (entry view) ─────────────────
797
798fn build_entries_right(
799    book: &Book, state: &BookViewState, theme: &BookTheme,
800    page_w: f32, page_h: f32, rx: f32, py: f32,
801    sx: f32, sy: f32,
802    overlays: &mut Vec<OverlayCmd>,
803) -> widget::Widget {
804    let entries  = state.entries_visible(book);
805    let cat_name = book.categories.get(state.cat).map(|c| c.name.as_str()).unwrap_or("Entries");
806    let spread_count = state.list_spread_count(book);
807
808    // Patchouli GuiBookEntryList layout (right page):
809    //   category name at page-local y=0, centered
810    //   separator at page-local y=12 (drawn as bg sprite in build_ui)
811    //   entries start at page-local y=20, each h=11
812    let header_h   = 9.0 * sy;
813    let row_h      = 11.0 * sy;
814    let icon_size  = 8.0 * sx.min(sy);
815
816    let mut col = widget::panel(FlexDir::Column)
817        .w(page_w).h(page_h)
818        .padding(0.0, 4.0, 4.0, 0.0)
819        .gap(0.0);
820
821    col = col.child(lbl(cat_name).color(theme.divider).h(header_h).align(Align::Center));
822    // sep region: y=9..15 (sep h=3), then gap to entries start at y=20
823    col = col.child(widget::spacer().h((12.0 - 9.0) * sy));    // gap to sep
824    col = col.child(widget::spacer().h((SEP_H * sy).max(1.0))); // sep height
825    col = col.child(widget::spacer().h((20.0 - 12.0 - SEP_H) * sy)); // gap to entries
826
827    let abs_start = state.list_spread_start();
828    for (i, entry) in entries.iter().enumerate() {
829        let abs_i    = abs_start + i;
830        let selected = abs_i == state.entry;
831        let bg    = if selected { theme.nav_selected_bg } else { 0 };
832        let color = if selected { theme.nav_selected } else { theme.nav };
833
834        // Icon at page-local (1, 20 + i*11 + 1), 8×8 (Patchouli renders entry
835        // icons at 0.5× scale).
836        if let Some(icon_id) = &entry.icon {
837            overlays.push(OverlayCmd::McItem {
838                item_id: icon_id.clone(),
839                x: rx + 1.0 * sx,
840                y: py + (20.0 + i as f32 * 11.0 + 1.0) * sy,
841                w: icon_size, h: icon_size,
842            });
843        }
844
845        let mut row = widget::panel(FlexDir::Row)
846            .h(row_h).gap(2.0).bg(bg)
847            .on_click(format!("entry:{}", abs_i))
848            .id(format!("book_entry_{}", abs_i))
849            .padding(1.0, 2.0, 1.0, 2.0);
850
851        row = row.child(widget::spacer().w(icon_size + 2.0));
852        row = row.child(lbl(&entry.name).color(color).flex(1.0));
853        col = col.child(row);
854    }
855
856    if spread_count > 1 {
857        col = col.child(widget::spacer().flex(1.0));
858        let spread_label = format!("{}/{}", state.list_spread + 1, spread_count);
859        col = col.child(
860            widget::panel(FlexDir::Row).h(12.0 * sy).gap(2.0)
861                .child(btn("◀").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
862                    .on_click("prev_list").id("prev_list"))
863                .child(lbl(&spread_label).color(theme.nav)
864                    .flex(1.0).align(Align::Center))
865                .child(btn("▶").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
866                    .on_click("next_list").id("next_list"))
867        );
868    }
869    col
870}
871
872/// Draw a Patchouli-style crafting recipe: title, 100×62 grid background
873/// (UV 0,0 on the crafting sheet), 3×N ingredient icons, output item.
874/// `rx0`/`ry` are body-local recipe origin; `ox`/`oy` the body screen origin.
875#[allow(clippy::too_many_arguments)]
876fn draw_crafting_grid(
877    theme: &BookTheme,
878    bg_sprites: &mut Vec<BgSprite>,
879    overlays: &mut Vec<OverlayCmd>,
880    col: &mut widget::Widget,
881    grid: &[Option<String>], width: usize,
882    output: &str, count: u32, shapeless: bool,
883    ox: f32, oy: f32, rx0: f32, ry: f32, sx: f32, sy: f32,
884) {
885    let mut c = std::mem::replace(col, widget::panel(FlexDir::Column));
886    c = c.child(lbl(pretty_item_name(output)).color(theme.title)
887        .h(10.0 * sy).align(Align::Center));
888
889    // Grid background: blit at (rx0-2, ry-2) size 100×62, UV(0,0).
890    bg_sprites.push(BgSprite {
891        sheet: SpriteSheet::Crafting,
892        u: 0.0, v: 0.0, uw: 100.0, uh: 62.0,
893        x: ox + (rx0 - 2.0) * sx, y: oy + (ry - 2.0) * sy,
894        w: 100.0 * sx, h: 62.0 * sy,
895    });
896    // Shapeless marker: UV(0,64) 11×11 at (rx0+62, ry+2).
897    if shapeless {
898        bg_sprites.push(BgSprite {
899            sheet: SpriteSheet::Crafting,
900            u: 0.0, v: 64.0, uw: 11.0, uh: 11.0,
901            x: ox + (rx0 + 62.0) * sx, y: oy + (ry + 2.0) * sy,
902            w: 11.0 * sx, h: 11.0 * sy,
903        });
904    }
905
906    let icon_s = 16.0 * sx.min(sy);
907    let width = width.max(1);
908    for (i, slot) in grid.iter().enumerate() {
909        if let Some(item) = slot {
910            overlays.push(OverlayCmd::McItem {
911                item_id: item.clone(),
912                x: ox + (rx0 + 3.0 + (i % width) as f32 * 19.0) * sx,
913                y: oy + (ry  + 3.0 + (i / width) as f32 * 19.0) * sy,
914                w: icon_s, h: icon_s,
915            });
916        }
917    }
918    // Output item at (rx0+79, ry+22); stack count below it when > 1.
919    overlays.push(OverlayCmd::McItem {
920        item_id: output.to_owned(),
921        x: ox + (rx0 + 79.0) * sx, y: oy + (ry + 22.0) * sy,
922        w: icon_s, h: icon_s,
923    });
924    if count > 1 {
925        overlays.push(OverlayCmd::McText {
926            text: format!("x{}", count),
927            x: ox + (rx0 + 81.0) * sx, y: oy + (ry + 40.0) * sy,
928            color: theme.title,
929        });
930    }
931    // Patchouli's "toast symbol" under the output: the crafting table.
932    overlays.push(OverlayCmd::McItem {
933        item_id: "minecraft:crafting_table".into(),
934        x: ox + (rx0 + 79.0) * sx, y: oy + (ry + 41.0) * sy,
935        w: icon_s, h: icon_s,
936    });
937
938    // Spacer from title end (10) to below the grid (ry+62+4).
939    c = c.child(widget::spacer().h((ry + 62.0 + 4.0 - 10.0) * sy));
940    *col = c;
941}
942
943// ── Page content builder ──────────────────────────────────────────────────────
944
945/// Build the content widget for a single page.
946/// `ox/oy` = screen top-left of the page body area.
947/// `sx/sy` = book-local-to-screen scale factors.
948fn build_page(
949    page: Option<&BookPage>,
950    page_num: usize,
951    theme: &BookTheme,
952    recipes: &HashMap<String, RecipeVis>,
953    bg_sprites: &mut Vec<BgSprite>,
954    overlays: &mut Vec<OverlayCmd>,
955    ox: f32, oy: f32,
956    sx: f32, sy: f32,
957) -> widget::Widget {
958    let mut col = widget::panel(FlexDir::Column).flex(1.0).gap(4.0);
959
960    let Some(page) = page else {
961        return col.child(lbl("No entries yet.").color(theme.nav));
962    };
963
964    match page {
965        BookPage::Text { text, title } => {
966            // On non-first pages, show an optional section title + separator.
967            if page_num > 0 {
968                if let Some(t) = title {
969                    let sep_h_px = (SEP_H * sy).max(1.0);
970                    let title_h  = 9.0 * sy;
971                    col = col.child(lbl(t.as_str()).color(theme.title)
972                        .h(title_h).align(Align::Center));
973                    // sep at y=12 page-local, centered
974                    bg_sprites.push(BgSprite {
975                        sheet: SpriteSheet::Book,
976                        u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
977                        x: ox + (PAGE_W / 2.0 - SEP_W / 2.0) * sx,
978                        y: oy + 12.0 * sy,
979                        w: SEP_W * sx, h: sep_h_px,
980                    });
981                    col = col.child(widget::spacer().h((12.0 - 9.0) * sy));
982                    col = col.child(widget::spacer().h(sep_h_px));
983                    col = col.child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy));
984                }
985            }
986            for para in text.split('\n') {
987                col = col.child(lbl(para).color(theme.text));
988            }
989        }
990
991        BookPage::Spotlight { item, title, text } => {
992            // Patchouli PageSpotlight (page-body-local coordinates):
993            //   title at y=0 centered, item frame at (PAGE_W/2-33, 10) 66×26
994            //   (UV 0,102 on the 128×256 crafting sheet), item at (PAGE_W/2-8, 15),
995            //   text at y=40.
996            bg_sprites.push(BgSprite {
997                sheet: SpriteSheet::Crafting,
998                u: 0.0, v: 102.0, uw: 66.0, uh: 26.0,
999                x: ox + (PAGE_W / 2.0 - 33.0) * sx,
1000                y: oy + 10.0 * sy,
1001                w: 66.0 * sx, h: 26.0 * sy,
1002            });
1003
1004            let item_name = title.as_deref()
1005                .or(item.name.as_deref())
1006                .unwrap_or(item.id.as_str());
1007            col = col.child(lbl(item_name).color(theme.title)
1008                .h(10.0 * sy).align(Align::Center));
1009
1010            let icon_s = 16.0 * sx.min(sy);
1011            overlays.push(OverlayCmd::McItem {
1012                item_id: item.id.clone(),
1013                x: ox + (PAGE_W / 2.0 - 8.0) * sx,
1014                y: oy + 15.0 * sy,
1015                w: icon_s, h: icon_s,
1016            });
1017
1018            // Spacer from title end (y=10) to text start (y=40).
1019            col = col.child(widget::spacer().h(30.0 * sy));
1020
1021            if let Some(t) = text {
1022                col = col.child(lbl(t.as_str()).color(theme.text));
1023            }
1024        }
1025
1026        BookPage::Crafting { recipe_id, text } => {
1027            // Patchouli PageCrafting: recipe origin at page-local
1028            // (PAGE_W/2-49, 4); we place it in body-local coords below a title.
1029            let rx0 = PAGE_W / 2.0 - 49.0; // = 9
1030            let ry  = 12.0;                // body-local recipe y (title occupies 0..10)
1031            match recipes.get(recipe_id.as_str()) {
1032                Some(RecipeVis::Shaped { grid, width, output, count })  => {
1033                    draw_crafting_grid(theme, bg_sprites, overlays, &mut col,
1034                        grid, *width, output, *count, false, ox, oy, rx0, ry, sx, sy);
1035                }
1036                Some(RecipeVis::Shapeless { ingredients, output, count }) => {
1037                    let grid: Vec<Option<String>> =
1038                        ingredients.iter().cloned().map(Some).collect();
1039                    draw_crafting_grid(theme, bg_sprites, overlays, &mut col,
1040                        &grid, 3, output, *count, true, ox, oy, rx0, ry, sx, sy);
1041                }
1042                _ => {
1043                    col = col.child(lbl(format!("[Recipe: {}]", recipe_id))
1044                        .color(theme.nav));
1045                }
1046            }
1047            if let Some(t) = text {
1048                col = col.child(lbl(t.as_str()).color(theme.text));
1049            }
1050        }
1051
1052        BookPage::Smelting { recipe_id, text } => {
1053            // Patchouli PageSmelting: bg UV(11,71) 96×24, input at +4,+4,
1054            // output at +76,+4.
1055            let rx0 = PAGE_W / 2.0 - 49.0;
1056            let ry  = 12.0;
1057            match recipes.get(recipe_id.as_str()) {
1058                Some(RecipeVis::Smelting { input, output }) => {
1059                    col = col.child(lbl(pretty_item_name(output)).color(theme.title)
1060                        .h(10.0 * sy).align(Align::Center));
1061                    bg_sprites.push(BgSprite {
1062                        sheet: SpriteSheet::Crafting,
1063                        u: 11.0, v: 71.0, uw: 96.0, uh: 24.0,
1064                        x: ox + rx0 * sx, y: oy + ry * sy,
1065                        w: 96.0 * sx, h: 24.0 * sy,
1066                    });
1067                    let icon_s = 16.0 * sx.min(sy);
1068                    overlays.push(OverlayCmd::McItem {
1069                        item_id: input.clone(),
1070                        x: ox + (rx0 + 4.0) * sx, y: oy + (ry + 4.0) * sy,
1071                        w: icon_s, h: icon_s,
1072                    });
1073                    // Center: the furnace itself (Patchouli's "toast symbol").
1074                    overlays.push(OverlayCmd::McItem {
1075                        item_id: "minecraft:furnace".into(),
1076                        x: ox + (rx0 + 40.0) * sx, y: oy + (ry + 4.0) * sy,
1077                        w: icon_s, h: icon_s,
1078                    });
1079                    overlays.push(OverlayCmd::McItem {
1080                        item_id: output.clone(),
1081                        x: ox + (rx0 + 76.0) * sx, y: oy + (ry + 4.0) * sy,
1082                        w: icon_s, h: icon_s,
1083                    });
1084                    // Spacer from title end (10) to below the furnace strip (ry+24+4).
1085                    col = col.child(widget::spacer().h((ry + 24.0 + 4.0 - 10.0) * sy));
1086                }
1087                _ => {
1088                    col = col.child(lbl(format!("[Recipe: {}]", recipe_id))
1089                        .color(theme.nav));
1090                }
1091            }
1092            if let Some(t) = text {
1093                col = col.child(lbl(t.as_str()).color(theme.text));
1094            }
1095        }
1096
1097        BookPage::Image { texture, title, text, .. } => {
1098            if let Some(t) = title {
1099                col = col.child(lbl(t.as_str()).color(theme.title));
1100            }
1101            col = col.child(widget::mc_image(texture, 80.0, 80.0));
1102            if let Some(t) = text {
1103                col = col.child(lbl(t.as_str()).color(theme.text));
1104            }
1105        }
1106
1107        BookPage::Svg { data, title, text } => {
1108            if let Some(t) = title {
1109                col = col.child(lbl(t.as_str()).color(theme.title));
1110            }
1111            overlays.push(OverlayCmd::Svg { data: data.clone(), x: ox, y: oy, w: 64.0, h: 64.0 });
1112            col = col.child(widget::spacer().h(68.0));
1113            if let Some(t) = text {
1114                col = col.child(lbl(t.as_str()).color(theme.text));
1115            }
1116        }
1117
1118        BookPage::CustomText { text, font, color } => {
1119            overlays.push(OverlayCmd::Text {
1120                text: text.clone(), font: font.clone(), x: ox, y: oy, color: *color,
1121            });
1122            col = col.child(widget::spacer().h(font.size_px * 1.5));
1123        }
1124
1125        BookPage::Relations { entries, text } => {
1126            if let Some(t) = text {
1127                col = col.child(lbl(t.as_str()).color(theme.text));
1128            }
1129            col = col.child(lbl("See also:").color(theme.title));
1130            for e in entries {
1131                col = col.child(lbl(format!("• {}", e)).color(theme.nav));
1132            }
1133        }
1134
1135        BookPage::Entity { entity_type, name, text } => {
1136            let display = name.as_deref().unwrap_or(entity_type.as_str());
1137            col = col.child(lbl(display).color(theme.title));
1138            if let Some(t) = text {
1139                col = col.child(lbl(t.as_str()).color(theme.text));
1140            }
1141        }
1142
1143        BookPage::Pattern { op_id, input, output, text, .. } => {
1144            col = col.child(lbl(op_id.as_str()).color(theme.title));
1145            col = col.child(
1146                lbl(format!("{} → {}", input, output)).color(theme.nav)
1147            );
1148            if !text.is_empty() {
1149                col = col.child(lbl(text.as_str()).color(theme.text));
1150            }
1151        }
1152
1153        BookPage::Empty => {}
1154    }
1155
1156    col
1157}