yog-registry 0.6.0

Yog content registry — register items, blocks, recipes, etc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Content registration — declare custom items and blocks from Rust.
//!
//! Definitions are collected at registration time and handed to the host, which
//! registers real `Item`/`Block` objects before the game's registries freeze,
//! puts them in per-namespace creative tabs, and applies their properties.
//! (Textures, models and recipes are assets/data shipped in the `.yog` and
//! served to the game.)
//!
//! ```
//! # use yog_registry::{ItemDef, BlockDef, FoodDef};
//! ItemDef::new("mymod:ruby").name("Ruby").tooltip("A shiny gem.").max_stack(16);
//! ItemDef::new("mymod:pie").food(FoodDef::new(4, 0.3));
//! BlockDef::new("mymod:lamp").light_level(15).sound("stone");
//! ```

// ── Items ────────────────────────────────────────────────────────────────────

/// Nutritional properties for a food item.
#[derive(Debug, Clone)]
pub struct FoodDef {
    /// Hunger points restored (1 unit = half a drumstick).
    pub nutrition: u32,
    /// Saturation modifier applied after eating.
    pub saturation: f32,
    /// If `true`, edible even when the hunger bar is full.
    pub can_always_eat: bool,
}

impl FoodDef {
    pub fn new(nutrition: u32, saturation: f32) -> Self {
        Self { nutrition, saturation, can_always_eat: false }
    }

    pub fn can_always_eat(mut self) -> Self {
        self.can_always_eat = true;
        self
    }
}

/// A custom item to register, identified by `namespace:path`.
#[derive(Debug, Clone)]
pub struct ItemDef {
    pub id: String,
    pub max_stack: u8,
    pub name: Option<String>,
    pub tooltip: Option<String>,
    /// Durability. `0` = non-damageable. If set, `max_stack` is forced to 1.
    pub max_damage: u32,
    /// Immune to fire and lava damage (like netherite items).
    pub fire_resistant: bool,
    /// Furnace fuel burn time in ticks (`0` = not fuel; 200 = one coal equivalent).
    pub fuel_ticks: u32,
    /// Nutritional properties; `None` = not food.
    pub food: Option<FoodDef>,
}

impl ItemDef {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            max_stack: 64,
            name: None,
            tooltip: None,
            max_damage: 0,
            fire_resistant: false,
            fuel_ticks: 0,
            food: None,
        }
    }

    /// Maximum stack size (default 64). Ignored when `max_damage` is set.
    pub fn max_stack(mut self, n: u8) -> Self {
        self.max_stack = n;
        self
    }

    /// Display name shown in-game.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// A tooltip line shown on hover.
    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    /// Make this a damageable item (tool/weapon/armour). Forces stack size to 1.
    pub fn max_damage(mut self, durability: u32) -> Self {
        self.max_damage = durability;
        self
    }

    /// Make this item fire-resistant (won't burn in fire or lava).
    pub fn fire_resistant(mut self) -> Self {
        self.fire_resistant = true;
        self
    }

    /// Register as furnace fuel burning for `ticks` (200 ticks = 1 item smelted).
    pub fn fuel(mut self, ticks: u32) -> Self {
        self.fuel_ticks = ticks;
        self
    }

    /// Make this item edible with the given nutritional properties.
    pub fn food(mut self, food: FoodDef) -> Self {
        self.food = Some(food);
        self
    }
}

// ── Recipes ──────────────────────────────────────────────────────────────────

/// A shaped crafting recipe (3×3 grid with a pattern and key mapping).
///
/// ```
/// # use yog_registry::ShapedRecipe;
/// ShapedRecipe::new("yog:ruby_sword", "yog:ruby_shard", 1)
///     .row("R  ").row("RS ").row(" S ")
///     .key('R', "yog:ruby_shard").key('S', "minecraft:stick");
/// ```
#[derive(Debug, Clone)]
pub struct ShapedRecipe {
    pub id:     String,
    pub output: String,
    pub count:  u32,
    rows:       Vec<String>,
    keys:       Vec<(char, String)>,
}

impl ShapedRecipe {
    pub fn new(id: impl Into<String>, output: impl Into<String>, count: u32) -> Self {
        Self { id: id.into(), output: output.into(), count, rows: Vec::new(), keys: Vec::new() }
    }

    pub fn row(mut self, pattern: impl Into<String>) -> Self {
        self.rows.push(pattern.into());
        self
    }

    pub fn key(mut self, symbol: char, item_id: impl Into<String>) -> Self {
        self.keys.push((symbol, item_id.into()));
        self
    }

    /// Generate the Minecraft 1.20 recipe JSON for this recipe.
    pub fn to_json(&self) -> String {
        let pattern: String = self.rows.iter()
            .map(|r| format!("\"{}\"", r))
            .collect::<Vec<_>>()
            .join(",");
        let keys: String = self.keys.iter()
            .map(|(ch, item)| format!("\"{}\":{{\"item\":\"{}\"}}", ch, item))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            "{{\"type\":\"minecraft:crafting_shaped\",\"pattern\":[{}],\"key\":{{{}}},\"result\":{{\"item\":\"{}\",\"count\":{}}}}}",
            pattern, keys, self.output, self.count
        )
    }

    /// Split `namespace:name` from the recipe id.
    pub fn ns_name(&self) -> (&str, &str) {
        self.id.split_once(':').unwrap_or(("minecraft", &self.id))
    }
}

/// A shapeless crafting recipe (unordered ingredients).
#[derive(Debug, Clone)]
pub struct ShapelessRecipe {
    pub id:          String,
    pub output:      String,
    pub count:       u32,
    pub ingredients: Vec<String>,
}

impl ShapelessRecipe {
    pub fn new(id: impl Into<String>, output: impl Into<String>, count: u32) -> Self {
        Self { id: id.into(), output: output.into(), count, ingredients: Vec::new() }
    }

    pub fn ingredient(mut self, item_id: impl Into<String>) -> Self {
        self.ingredients.push(item_id.into());
        self
    }

    pub fn to_json(&self) -> String {
        let ingr: String = self.ingredients.iter()
            .map(|i| format!("{{\"item\":\"{}\"}}", i))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            "{{\"type\":\"minecraft:crafting_shapeless\",\"ingredients\":[{}],\"result\":{{\"item\":\"{}\",\"count\":{}}}}}",
            ingr, self.output, self.count
        )
    }

    pub fn ns_name(&self) -> (&str, &str) {
        self.id.split_once(':').unwrap_or(("minecraft", &self.id))
    }
}

/// A furnace smelting recipe.
#[derive(Debug, Clone)]
pub struct FurnaceRecipe {
    pub id:         String,
    pub input:      String,
    pub output:     String,
    pub count:      u32,
    pub experience: f32,
    pub cook_time:  u32,
}

impl FurnaceRecipe {
    pub fn new(
        id: impl Into<String>,
        input: impl Into<String>,
        output: impl Into<String>,
        count: u32,
    ) -> Self {
        Self { id: id.into(), input: input.into(), output: output.into(), count, experience: 0.1, cook_time: 200 }
    }

    pub fn experience(mut self, xp: f32) -> Self {
        self.experience = xp;
        self
    }

    /// Cooking time in ticks (default 200 = 10 seconds).
    pub fn cook_time(mut self, ticks: u32) -> Self {
        self.cook_time = ticks;
        self
    }

    pub fn to_json(&self) -> String {
        format!(
            "{{\"type\":\"minecraft:smelting\",\"ingredient\":{{\"item\":\"{}\"}},\"result\":\"{}\",\"experience\":{},\"cookingtime\":{}}}",
            self.input, self.output, self.experience, self.cook_time
        )
    }

    pub fn ns_name(&self) -> (&str, &str) {
        self.id.split_once(':').unwrap_or(("minecraft", &self.id))
    }
}

// ── BookRecipe (like Patchouli's shapeless_book_recipe) ──────────────────────

/// A shapeless recipe that produces a book from `yog-book`.
/// Replaces `patchouli:shapeless_book_recipe`.
#[derive(Debug, Clone)]
pub struct BookRecipe {
    pub id: String,
    pub book: String,
    pub ingredients: Vec<String>,
}

impl BookRecipe {
    pub fn new(id: impl Into<String>, book: impl Into<String>) -> Self {
        Self { id: id.into(), book: book.into(), ingredients: Vec::new() }
    }

    pub fn ingredient(mut self, item_id: impl Into<String>) -> Self {
        self.ingredients.push(item_id.into());
        self
    }

    pub fn to_json(&self) -> String {
        let ingr: String = self.ingredients.iter()
            .map(|i| format!("{{\"item\":\"{}\"}}", i))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            "{{\"type\":\"yog:crafting_book\",\"ingredients\":[{}],\"book\":\"{}\"}}",
            ingr, self.book
        )
    }

    pub fn ns_name(&self) -> (&str, &str) {
        self.id.split_once(':').unwrap_or(("yog", &self.id))
    }
}

// ── ItemModifier ─────────────────────────────────────────────────────────────

/// An item modifier applied during loot generation (like smelting, enchanted, etc.).
#[derive(Debug, Clone)]
pub struct ItemModifier {
    pub id: String,
    /// Modifier function identifier, e.g. "yog:set_count" or "hexcasting:amethyst_shard_reducer".
    pub function: String,
    /// Parameters as JSON object.
    pub parameters: std::collections::HashMap<String, String>,
}

impl ItemModifier {
    pub fn new(id: impl Into<String>, function: impl Into<String>) -> Self {
        Self { id: id.into(), function: function.into(), parameters: std::collections::HashMap::new() }
    }

    pub fn param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.parameters.insert(key.into(), value.into());
        self
    }

    pub fn to_json(&self) -> String {
        let params: String = self.parameters.iter()
            .map(|(k, v)| format!("\"{}\":{}", k, v))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            "{{\"function\":\"{}\",{}}}",
            self.function, if params.is_empty() { String::new() } else { params }
        )
    }
}

// ── StartupGrant ─────────────────────────────────────────────────────────────

/// Grant items/books to every player once when they first join.
/// This is the Yog-side replacement for `grant_patchi_book.json`.
#[derive(Debug, Clone)]
pub struct StartupGrant {
    pub id: String,
    pub items: Vec<String>,
    pub book: Option<String>,
    pub command: Option<String>,
}

impl StartupGrant {
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into(), items: Vec::new(), book: None, command: None }
    }

    pub fn item(mut self, item_id: impl Into<String>) -> Self {
        self.items.push(item_id.into());
        self
    }

    pub fn book(mut self, book: impl Into<String>) -> Self {
        self.book = Some(book.into());
        self
    }

    pub fn command(mut self, cmd: impl Into<String>) -> Self {
        self.command = Some(cmd.into());
        self
    }

    pub fn to_json(&self) -> String {
        let items: Vec<String> = self.items.iter().map(|i| format!("{{\"item\":\"{}\"}}", i)).collect();
        let mut entries = String::new();
        if !items.is_empty() {
            entries.push_str(&format!("[{}]", items.join(",")));
        }
        if let Some(book) = &self.book {
            if !entries.is_empty() {
                entries.push(',');
            }
            let book_entry = format!(
                "{{\"type\":\"item\",\"name\":\"minecraft:written_book\",\"functions\":[{{\"function\":\"set_nbt\",\"tag\":\"{{yog_book:\\\"{}\\\"}}\"}}]}}",
                book
            );
            entries.push_str(&book_entry);
        }
        if let Some(cmd) = &self.command {
            if !entries.is_empty() {
                entries.push(',');
            }
            entries.push_str(&format!(
                "{{\"type\":\"minecraft:command\",\"command\":\"{}\"}}",
                cmd.replace('"', "\\\"")
            ));
        }
        format!(
            "{{\"type\":\"yog:startup_grant\",\"entries\":{},\"id\":\"{}\"}}",
            if entries.is_empty() { "[]".to_string() } else { entries },
            self.id
        )
    }
}

// ── Blocks ───────────────────────────────────────────────────────────────────
#[derive(Debug, Clone)]
pub struct AdvancementReward {
    pub id: String,
    /// The item to grant (default: special book item when book rewards).
    pub item: String,
    /// Optional NBT tag to apply.
    pub nbt: Option<String>,
    /// If set, the reward links to a yog-book.
    pub book: Option<String>,
}

impl AdvancementReward {
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into(), item: "minecraft:written_book".into(), nbt: None, book: None }
    }

    pub fn item(mut self, item: impl Into<String>) -> Self {
        self.item = item.into();
        self
    }

    pub fn nbt(mut self, nbt: impl Into<String>) -> Self {
        self.nbt = Some(nbt.into());
        self
    }

    pub fn book(mut self, book: impl Into<String>) -> Self {
        let book_str: String = book.into();
        self.book = Some(book_str.clone());
        self.nbt = Some(format!("{{yog_book:\"{}\",title:\"Yog Book\",author:\"Yog\"}}", book_str));
        self
    }

    pub fn to_json(&self) -> String {
        let nbt_part = self.nbt.as_ref().map(|n| format!("{{\"function\":\"set_nbt\",\"tag\":{}}}", n));
        let entries = if let Some(nbt_part) = nbt_part {
            format!("[{{\"type\":\"item\",\"name\":\"{}\",\"functions\":[{}]}}]", self.item, nbt_part)
        } else {
            format!("[{{\"type\":\"item\",\"name\":\"{}\"}}]", self.item)
        };
        format!(
            "{{\"type\":\"advancement_reward\",\"pools\":[{{\"rolls\":1,\"entries\":{}}}]}}",
            entries
        )
    }
}

// ── Blocks ───────────────────────────────────────────────────────────────────

/// A custom block to register; it also gets a matching block-item.
#[derive(Debug, Clone)]
pub struct BlockDef {
    pub id: String,
    pub hardness: f32,
    pub resistance: f32,
    pub name: Option<String>,
    /// Optional collision/outline box in pixel units (0–16): `[x1,y1,z1,x2,y2,z2]`.
    /// `None` = full cube.
    pub shape: Option<[f32; 6]>,
    /// Light emitted by this block (0 = none, 15 = max, like a torch).
    pub light_level: u8,
    /// Sound group id: `"stone"`, `"wood"`, `"grass"`, `"sand"`, `"snow"`,
    /// `"gravel"`, `"metal"`, `"glass"`, `"wool"`, `"nether_brick"`.
    /// `None` = stone (Minecraft default).
    pub sound: Option<String>,
    /// If `true`, the correct tool (from the block's tags) is required for drops.
    pub requires_tool: bool,
    /// If `true`, entities pass through this block (like flowers or torches).
    pub no_collision: bool,
    /// Friction coefficient. `0.0` = default (0.6). Ice = 0.989.
    pub slipperiness: f32,
}

impl BlockDef {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            hardness: 1.5,
            resistance: 6.0,
            name: None,
            shape: None,
            light_level: 0,
            sound: None,
            requires_tool: false,
            no_collision: false,
            slipperiness: 0.0,
        }
    }

    /// Mining hardness and blast resistance (defaults 1.5 / 6.0).
    pub fn strength(mut self, hardness: f32, resistance: f32) -> Self {
        self.hardness = hardness;
        self.resistance = resistance;
        self
    }

    /// Display name shown in-game.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Custom hitbox/outline in pixel units (0–16).
    pub fn shape(mut self, x1: f32, y1: f32, z1: f32, x2: f32, y2: f32, z2: f32) -> Self {
        self.shape = Some([x1, y1, z1, x2, y2, z2]);
        self
    }

    /// Emitted light level (0–15).
    pub fn light_level(mut self, level: u8) -> Self {
        self.light_level = level.min(15);
        self
    }

    /// Sound group: `"stone"`, `"wood"`, `"grass"`, `"sand"`, `"snow"`,
    /// `"gravel"`, `"metal"`, `"glass"`, `"wool"`, `"nether_brick"`.
    pub fn sound(mut self, group: impl Into<String>) -> Self {
        self.sound = Some(group.into());
        self
    }

    /// Correct tool required for loot drops (equivalent to `requiresTool()`).
    pub fn requires_tool(mut self) -> Self {
        self.requires_tool = true;
        self
    }

    /// No physical collision — entities pass through (like flowers).
    pub fn no_collision(mut self) -> Self {
        self.no_collision = true;
        self
    }

    /// Friction (default 0.6). Set to 0.989 for ice-like slipperiness.
    pub fn slipperiness(mut self, value: f32) -> Self {
        self.slipperiness = value;
        self
    }
}