1use 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
14pub const BOOK_TEX_W: f32 = 512.0;
18pub const BOOK_TEX_H: f32 = 256.0;
19pub const BK_W: f32 = 272.0;
21pub const BK_H: f32 = 180.0;
22pub const PAGE_W: f32 = 116.0;
24pub const PAGE_H: f32 = 156.0;
25pub const TOP_PAD: f32 = 18.0; pub const LEFT_X: f32 = 15.0; pub const RIGHT_X: f32 = 141.0; pub 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#[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 verts.extend_from_slice(&[p[0], p[1], p[2], p[1], p[3], p[2]]);
59}
60
61const 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
98static 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
122struct 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; vao.attrib(ctx, &vbo, 0, 2, DataType::F32, false, STRIDE, 0); vao.attrib(ctx, &vbo, 1, 2, DataType::F32, false, STRIDE, 8); vao.attrib(ctx, &vbo, 2, 4, DataType::F32, false, STRIDE, 16); 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
174impl 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 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 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 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 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#[derive(Clone, Copy, PartialEq)]
274pub(crate) enum SpriteSheet { Book, Crafting }
275
276#[derive(Clone)]
278pub(crate) struct BgSprite {
279 pub sheet: SpriteSheet,
280 pub u: f32, pub v: f32, pub uw: f32, pub uh: f32,
282 pub x: f32, pub y: f32, pub w: f32, pub h: f32,
284}
285
286#[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 McText { text: String, x: f32, y: f32, color: u32 },
294 McItem { item_id: String, x: f32, y: f32, w: f32, h: f32 },
296}
297
298#[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
354fn 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
362fn 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
377pub 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 pub fn register_font(&mut self, id: impl Into<String>, ttf: Vec<u8>) {
421 self.fonts.register(id, ttf);
422 }
423
424 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 if self.gl.is_none() {
436 self.gl = BookGl::init(ctx);
437 }
438
439 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 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 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 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 if let Some(ui) = &mut self.ui {
473 if ui.needs_layout { ui.layout(sw, sh); }
474 ui.render(ctx);
475 }
476
477 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 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
510fn lbl(text: impl Into<String>) -> widget::Widget { widget::label(text).shadow(false) }
514fn btn(text: impl Into<String>) -> widget::Widget { widget::button(text).shadow(false) }
516
517fn 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 let sx = bw / BK_W;
529 let sy = bh / BK_H;
530
531 let pw = PAGE_W * sx;
533 let ph = PAGE_H * sy;
534 let spine_gap = (RIGHT_X - LEFT_X - PAGE_W) * sx; let lx = bx + LEFT_X * sx;
538 let rx = bx + RIGHT_X * sx;
539 let py = by + TOP_PAD * sy;
540
541 let sep_cx = (PAGE_W / 2.0 - SEP_W / 2.0) * sx; if state.at_home {
545 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 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 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 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)) .child(right_page);
599
600 let outer = widget::panel(FlexDir::Column)
603 .w(bw).h(bh)
604 .child(root_widget);
605
606 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
618fn 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 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 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
670fn 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 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 col = col.child(widget::spacer().h(25.0 * sy - header_h));
698
699 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
737fn 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 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)) .child(widget::spacer().h(sep_h_px)) .child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy)) .child(page_body)
793 .child(nav)
794}
795
796fn 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 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 col = col.child(widget::spacer().h((12.0 - 9.0) * sy)); col = col.child(widget::spacer().h((SEP_H * sy).max(1.0))); col = col.child(widget::spacer().h((20.0 - 12.0 - SEP_H) * sy)); 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 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#[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 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 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 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 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 c = c.child(widget::spacer().h((ry + 62.0 + 4.0 - 10.0) * sy));
940 *col = c;
941}
942
943fn 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 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 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 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 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 let rx0 = PAGE_W / 2.0 - 49.0; let ry = 12.0; 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 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 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 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}