ghast-inventory 0.5.3

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! The 26.1 click simulation: what the vanilla 26.1 client does with a click
//! (`AbstractContainerMenu.doClick` with every `ContainerInput`, quick-craft drags included),
//! the slot rules of every menu a server can open (`Slot` and its subclasses, the containers'
//! `setItem` / `removeItem` / `setChanged`), each menu's quick move and the client-side result
//! updates some menus make (smithing, stonecutter, cartography, grindstone when its result is
//! empty, crafting results taken with their remainders), bundles and creative mode.
//!
//! The simulation works on the same [`Model`] as the older versions but follows the 26.1
//! control flow, which differs in many places (slot-dependent stack limits, `safeInsert` /
//! `tryRemove`, quick-move loops, drags, bundles). Whatever depends on data the client gets
//! from elsewhere (villager offers, anvil and loom results, the player's experience when it is
//! unknown) returns [`Unpredictable`]; the caller then sends the click without a prediction.
//!
//! Proven against the real client's click handling on every menu type
//! (`tests/oracle_clicks_26_1.rs`).

use bytes::{BufMut, Bytes, BytesMut};
use ghast_protocol::codec::{McWrite, Reader};

use crate::data26::{Data26, Holders, Reg};
use crate::item26::{self as v, Equip};
use crate::sim::{Loc, Model, OUTSIDE, Unpredictable};
use crate::stack::{ItemData, Stack};
use crate::tables::Mv;
use crate::tables::kind as c;

mod click;
mod items;
mod quick_move;
mod results;
mod slots;
#[cfg(test)]
mod tests;

pub(crate) use self::items::fastutil_order;
use self::items::*;

type R<T> = Result<T, Unpredictable>;

/// The menus a 26.1 server opens with `open_screen` (`minecraft:menu` registry order), plus
/// window 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Kind {
    /// `InventoryMenu` (window 0).
    Player,
    /// `ChestMenu` with this many rows.
    Chest(u8),
    /// `DispenserMenu`.
    Dispenser,
    /// `CrafterMenu`: 9 grid slots, the player's 36, then a result slot (index 45).
    Crafter,
    Anvil,
    Beacon,
    /// `AbstractFurnaceMenu`: furnace, blast furnace, smoker (their inputs differ).
    Furnace(Oven),
    Brewing,
    Crafting,
    Enchanting,
    Grindstone,
    Hopper,
    /// `LecternMenu`: one slot, no player inventory.
    Lectern,
    Loom,
    Merchant,
    Shulker,
    Smithing,
    Cartography,
    Stonecutter,
    /// A horse / donkey / llama / camel / nautilus screen (`horse_screen_open`) with this many
    /// inventory columns: saddle, body armor, `columns * 3` chest slots, the player's 36.
    Mount(u8),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Oven {
    Furnace,
    Blast,
    Smoker,
}

impl Kind {
    /// The menu of `open_screen`'s `minecraft:menu` registry id.
    pub(crate) fn from_menu(menu: i32) -> Option<Kind> {
        Some(match menu {
            0..=5 => Kind::Chest(menu as u8 + 1),
            6 => Kind::Dispenser,
            7 => Kind::Crafter,
            8 => Kind::Anvil,
            9 => Kind::Beacon,
            10 => Kind::Furnace(Oven::Blast),
            11 => Kind::Brewing,
            12 => Kind::Crafting,
            13 => Kind::Enchanting,
            14 => Kind::Furnace(Oven::Furnace),
            15 => Kind::Grindstone,
            16 => Kind::Hopper,
            17 => Kind::Lectern,
            18 => Kind::Loom,
            19 => Kind::Merchant,
            20 => Kind::Shulker,
            21 => Kind::Smithing,
            22 => Kind::Furnace(Oven::Smoker),
            23 => Kind::Cartography,
            24 => Kind::Stonecutter,
            _ => return None,
        })
    }

    /// Container slots before the player's 36 (all of them for the lectern).
    pub(crate) fn head(self) -> usize {
        match self {
            Kind::Player => 0,
            Kind::Chest(r) => usize::from(r) * 9,
            Kind::Dispenser | Kind::Crafter => 9,
            Kind::Anvil | Kind::Grindstone | Kind::Merchant | Kind::Cartography => 3,
            Kind::Furnace(_) => 3,
            Kind::Beacon | Kind::Lectern => 1,
            Kind::Brewing | Kind::Hopper => 5,
            Kind::Crafting => 10,
            Kind::Enchanting | Kind::Stonecutter => 2,
            Kind::Loom | Kind::Smithing => 4,
            Kind::Shulker => 27,
            Kind::Mount(c) => 2 + usize::from(c) * 3,
        }
    }

    /// Screen slots.
    pub(crate) fn len(self) -> usize {
        match self {
            Kind::Player => 46,
            Kind::Lectern => 1,
            Kind::Crafter => 46,
            k => k.head() + 36,
        }
    }

    /// Where screen slot `i` keeps its stack.
    pub(crate) fn loc(self, i: usize) -> Option<Loc> {
        if i >= self.len() {
            return None;
        }
        Some(match self {
            Kind::Player => match i {
                0 => Loc::CraftResult,
                1..=4 => Loc::Craft(i - 1),
                5..=8 => Loc::Player(39 - (i - 5)),
                9..=35 => Loc::Player(i),
                36..=44 => Loc::Player(i - 36),
                _ => Loc::Player(40),
            },
            Kind::Lectern => Loc::Container(0),
            k => {
                let n = k.head();
                if i < n {
                    Loc::Container(i)
                } else if i < n + 27 {
                    Loc::Player(i - n + 9)
                } else if i < n + 36 {
                    Loc::Player(i - n - 27)
                } else {
                    Loc::Container(n + i - n - 36)
                }
            }
        })
    }

    /// The container's stack cap applied by `setItem` (`SimpleContainer` / `MerchantContainer`
    /// `limitSize(min(getMaxStackSize(), stack max))`); `None` for containers that store as is
    /// (player inventory, crafting grids, result containers).
    pub(crate) fn cap(self, l: Loc) -> Option<i32> {
        let Loc::Container(k) = l else {
            return None;
        };
        match (self, k) {
            (Kind::Crafting | Kind::Crafter, _) => None,
            (Kind::Beacon, _) => Some(1),
            // the mount's equipment slot containers store as is
            (Kind::Mount(_), 0 | 1) => None,
            (Kind::Anvil | Kind::Grindstone | Kind::Cartography, 2) => None,
            (Kind::Smithing, 3) | (Kind::Stonecutter, 1) => None,
            _ => Some(99),
        }
    }
}

/// What a slot is (`Slot` subclass and the container it reads).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ty {
    /// Player inventory slot (main, hotbar) or window 0's offhand.
    Inv,
    /// Window 0 armor slot: 0 head … 3 feet.
    Armor(u8),
    /// Crafting `ResultSlot` (window 0 slot 0, crafting table slot 0).
    Result,
    /// Crafting grid (`TransientCraftingContainer`).
    Grid,
    /// `CrafterSlot` (index into the lock flags).
    CrafterGrid,
    /// `NonInteractiveResultSlot` (crafter result).
    Fixed,
    /// Plain `Slot` over a `SimpleContainer` (chests, hopper, dispenser, lectern, furnace input).
    Plain,
    Shulker,
    FurnaceFuel,
    FurnaceResult,
    Potion,
    BrewIngredient,
    BrewFuel,
    EnchantItem,
    Lapis,
    Payment,
    /// Anvil / smithing input `k`.
    CombinerIn(u8),
    CombinerResult,
    GrindIn,
    GrindResult,
    CutterIn,
    CutterResult,
    LoomBanner,
    LoomDye,
    LoomPattern,
    LoomResult,
    MapIn,
    MapExtra,
    MapResult,
    TradeIn,
    TradeResult,
    /// Mount saddle / body armor (`ArmorSlot` over the entity's equipment).
    MountSaddle,
    MountBody,
}

fn ty(kind: Kind, i: usize) -> Ty {
    if kind == Kind::Player && (5..=8).contains(&i) {
        return Ty::Armor((i - 5) as u8);
    }
    let l = kind.loc(i);
    match l {
        Some(Loc::Player(_)) | None => return Ty::Inv,
        Some(Loc::Craft(_)) => return Ty::Grid,
        Some(Loc::CraftResult) => return Ty::Result,
        Some(Loc::Container(_)) => {}
    }
    let Some(Loc::Container(k)) = l else {
        return Ty::Inv;
    };
    match kind {
        Kind::Player => Ty::Inv,
        Kind::Chest(_) | Kind::Dispenser | Kind::Hopper | Kind::Lectern => Ty::Plain,
        Kind::Shulker => Ty::Shulker,
        Kind::Crafter => {
            if k < 9 {
                Ty::CrafterGrid
            } else {
                Ty::Fixed
            }
        }
        Kind::Crafting => {
            if k == 0 {
                Ty::Result
            } else {
                Ty::Grid
            }
        }
        Kind::Furnace(_) => match k {
            0 => Ty::Plain,
            1 => Ty::FurnaceFuel,
            _ => Ty::FurnaceResult,
        },
        Kind::Brewing => match k {
            0..=2 => Ty::Potion,
            3 => Ty::BrewIngredient,
            _ => Ty::BrewFuel,
        },
        Kind::Enchanting => {
            if k == 0 {
                Ty::EnchantItem
            } else {
                Ty::Lapis
            }
        }
        Kind::Beacon => Ty::Payment,
        Kind::Anvil => {
            if k < 2 {
                Ty::CombinerIn(k as u8)
            } else {
                Ty::CombinerResult
            }
        }
        Kind::Smithing => {
            if k < 3 {
                Ty::CombinerIn(k as u8)
            } else {
                Ty::CombinerResult
            }
        }
        Kind::Grindstone => {
            if k < 2 {
                Ty::GrindIn
            } else {
                Ty::GrindResult
            }
        }
        Kind::Stonecutter => {
            if k == 0 {
                Ty::CutterIn
            } else {
                Ty::CutterResult
            }
        }
        Kind::Loom => match k {
            0 => Ty::LoomBanner,
            1 => Ty::LoomDye,
            2 => Ty::LoomPattern,
            _ => Ty::LoomResult,
        },
        Kind::Cartography => match k {
            0 => Ty::MapIn,
            1 => Ty::MapExtra,
            _ => Ty::MapResult,
        },
        Kind::Merchant => {
            if k < 2 {
                Ty::TradeIn
            } else {
                Ty::TradeResult
            }
        }
        Kind::Mount(_) => match k {
            0 => Ty::MountSaddle,
            1 => Ty::MountBody,
            _ => Ty::Plain,
        },
    }
}

/// A quick-craft (drag) in progress: `AbstractContainerMenu.quickcraftStatus`,
/// `quickcraftType` and `quickcraftSlots`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Drag {
    status: u8,
    ty: u8,
    slots: Vec<u16>,
}

impl Drag {
    /// `resetQuickCraft`.
    pub(crate) fn reset(&mut self) {
        self.status = 0;
        self.slots.clear();
    }
}

/// What the client knows from elsewhere: the server's recipe item sets, its game mode and
/// experience level, the open menu's data slots.
#[derive(Debug, Clone)]
pub(crate) struct World26 {
    /// `RecipePropertySet`s from `update_recipes` (sorted item ids).
    pub furnace_input: Vec<i32>,
    pub blast_input: Vec<i32>,
    pub smoker_input: Vec<i32>,
    pub smithing_base: Vec<i32>,
    pub smithing_template: Vec<i32>,
    pub smithing_addition: Vec<i32>,
    /// 26.3 `brewing_reagent` / `brewing_input` property sets (empty before 26.3).
    pub brewing_reagent: Vec<i32>,
    pub brewing_input: Vec<i32>,
    /// Stonecutter recipe inputs (sorted item ids); `None` when one names a tag.
    pub cutter_inputs: Option<Vec<i32>>,
    /// `hasInfiniteMaterials()` (abilities: instant build) and `isCreative()`.
    pub creative: bool,
    /// `experienceLevel`, if the server sent it.
    pub xp_level: Option<i32>,
    /// `minecraft:binding_curse` registry id (the `prevent_armor_change` enchantment).
    pub binding_curse: Option<i32>,
    /// `player.canDropItems()` (the drop spam throttle is below its threshold).
    pub can_drop: bool,
}

impl Default for World26 {
    fn default() -> Self {
        World26 {
            furnace_input: Vec::new(),
            blast_input: Vec::new(),
            smoker_input: Vec::new(),
            smithing_base: Vec::new(),
            smithing_template: Vec::new(),
            smithing_addition: Vec::new(),
            brewing_reagent: Vec::new(),
            brewing_input: Vec::new(),
            cutter_inputs: Some(Vec::new()),
            creative: false,
            xp_level: None,
            binding_curse: None,
            can_drop: true,
        }
    }
}

fn has(set: &[i32], id: i32) -> bool {
    set.binary_search(&id).is_ok()
}

/// Per-screen state the client keeps between clicks.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Screen26 {
    /// Drag in progress.
    pub drag: Drag,
    /// Stonecutter: the item of `StonecutterMenu.input` (0 = empty).
    pub cutter_input: i32,
    /// Anvil: the client's `cost` data slot (set by the server, and by `createResult`).
    pub anvil_cost: i32,
    /// Crafter: locked slots (data slots 0..9 = 1).
    pub crafter_locked: u16,
    /// Anvil: `itemName` (set by [`crate::Inventory::anvil_rename_26_1`]).
    pub anvil_name: Option<String>,
    /// Anvil: `repairItemCountCost` and `onlyRenaming` of the last `createResult`.
    pub anvil_repair_count: i32,
    pub anvil_only_renaming: bool,
    /// Loom: `selectablePatterns` (banner pattern registry ids) and `selectedBannerPatternIndex`.
    pub loom_patterns: Vec<i32>,
    pub loom_selected: i32,
    /// Merchant: the offers of `merchant_offers`, `selectionHint`, `activeOffer`.
    pub offers: Vec<Offer>,
    pub trade_hint: i32,
    pub trade_active: Option<usize>,
    /// Mount: entity type registry id and `canUseSlot(SADDLE)` / `canUseSlot(BODY)`.
    pub mount_type: i32,
    pub mount_saddle: bool,
    pub mount_body: bool,
}

/// One `ItemCost` of a villager offer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Cost {
    pub item: i32,
    pub count: i32,
    /// `DataComponentExactPredicate`: components the stack must have with these values.
    pub components: Vec<(i32, Bytes)>,
}

/// A villager offer as the client holds it (`MerchantOffer`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Offer {
    pub cost_a: Cost,
    pub cost_b: Option<Cost>,
    pub result: Option<Stack>,
    pub uses: i32,
    pub max_uses: i32,
    pub special: i32,
    pub multiplier_bits: u32,
    pub demand: i32,
}

/// Parses a `merchant_offers` body: the container id and its offers.
pub(crate) fn parse_offers(mv: Mv, body: &Bytes) -> Option<(i32, Vec<Offer>)> {
    let mut r = Reader::new(body);
    let window = r.read_varint().ok()?;
    let cost = |r: &mut Reader<'_>| -> Option<Cost> {
        let item = r.read_varint().ok()?;
        let count = r.read_varint().ok()?;
        let n = r.read_varint().ok()?;
        let mut components = Vec::new();
        for _ in 0..n.max(0) {
            let mut v = r.clone();
            let ty = v.read_varint().ok()?;
            let start = v.position();
            mv.skip_component(r).ok()?;
            components.push((ty, body.slice(start..r.position())));
        }
        Some(Cost {
            item,
            count,
            components,
        })
    };
    let n = r.read_varint().ok()?;
    let mut offers = Vec::new();
    for _ in 0..n.max(0) {
        let cost_a = cost(&mut r)?;
        let result = mv.read_stack(&mut r).ok()?.map(Stack::from_v775);
        let cost_b = if r.read_bool().ok()? {
            Some(cost(&mut r)?)
        } else {
            None
        };
        let out_of_stock = r.read_bool().ok()?;
        let uses = r.read_i32().ok()?;
        let max_uses = r.read_i32().ok()?;
        let _xp = r.read_i32().ok()?;
        let special = r.read_i32().ok()?;
        let multiplier_bits = r.read_f32().ok()?.to_bits();
        let demand = r.read_i32().ok()?;
        offers.push(Offer {
            cost_a,
            cost_b,
            result,
            // `setToOutOfStock`: uses = maxUses
            uses: if out_of_stock { max_uses } else { uses },
            max_uses,
            special,
            multiplier_bits,
            demand,
        });
    }
    Some((window, offers))
}

/// One click being simulated.
pub(crate) struct Sim26<'a> {
    pub kind: Kind,
    pub m: &'a mut Model,
    pub s: &'a mut Screen26,
    pub w: &'a World26,
    /// Tags and enchantment definitions (parsed before a click in a menu that reads them).
    pub d: &'a Data26,
    /// Registry names (banner patterns).
    pub reg: &'a v::HashRegistries,
    /// The version's tables.
    pub mv: Mv,
    /// `ServerboundSwingPacket`s the click makes the client send first (each drop swings).
    pub swings: u8,
    /// Experience levels the click spent (taking an anvil result).
    pub xp_spent: i32,
}

/// Fraction arithmetic of `org.apache.commons.lang3.math.Fraction` (reduced, positive
/// denominators), for bundle weights.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Frac(i64, i64);

impl Frac {
    const ZERO: Frac = Frac(0, 1);
    const ONE: Frac = Frac(1, 1);
    fn new(n: i64, d: i64) -> Frac {
        let g = gcd(n.abs(), d.abs()).max(1);
        let (n, d) = (n / g, d / g);
        if d < 0 { Frac(-n, -d) } else { Frac(n, d) }
    }
    fn add(self, o: Frac) -> Frac {
        Frac::new(self.0 * o.1 + o.0 * self.1, self.1 * o.1)
    }
    fn sub(self, o: Frac) -> Frac {
        Frac::new(self.0 * o.1 - o.0 * self.1, self.1 * o.1)
    }
    fn mul(self, k: i64) -> Frac {
        Frac::new(self.0 * k, self.1)
    }
    /// `divideBy(o).intValue()` (truncates toward zero).
    fn div_int(self, o: Frac) -> i64 {
        let f = Frac::new(self.0 * o.1, self.1 * o.0);
        f.0 / f.1
    }
}

fn gcd(a: i64, b: i64) -> i64 {
    if b == 0 { a } else { gcd(b, a % b) }
}