enshwick 1.0.0-alpha.11

The Enshwick Loader's modding API for Enshrouded: the one crate mods are written against
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
use core::ffi::c_void;

use crate::abi::{Header, InventoryOp, InventoryRequest, ItemData};
use crate::ecs::{ComponentType, Components};
use crate::engine_ids as ids;
use crate::raw::read_at;
use crate::schedule::Scheduler;
use crate::{Entity, ItemId};
use crate::{Host, Load, Off};

use super::ops::{Batch, Op};
use super::results::{Done, OpError, OpErrors, Outcome, Pending, Ticket, deliver};
use super::slots::{Bar, Fill, InventoryCategory, ItemInfo, Slot, SlotRef};
use super::{LINKS, MAX_DEPTH, MAX_OWNERS, SLOTS};

/// Reflected layouts the reads use.
#[derive(Clone, Copy, Debug)]
pub(super) struct Layout {
    setup: ComponentType,
    inventory: ComponentType,
    durability: ComponentType,
    fuel: ComponentType,
    owner: ComponentType,
    links: usize,
    categories: usize,
    initialized: usize,
    stack: usize,
    stack_count: usize,
    stack_pide: usize,
    durability_max: usize,
    fuel_max: usize,
    /// The game's entity that inventory walks skip.
    skip: usize,
}

/// Inventory reads and transactions on the server; get it from
/// [`Load::inventories`]. Copy it anywhere.
///
/// # Examples
///
/// ```
/// use enshwick::Entity;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     let inventories = load.inventories()?;
///     let (corpse, player) = (Entity(40), Entity(2));
///     load.scheduler()?.next_tick(move || {
///         let full = inventories.read().slots(corpse).iter().filter(|s| !s.is_empty()).count();
///         enshwick::info!("{full} stacks to loot");
///         inventories.move_all(corpse, player, |outcome| {
///             enshwick::info!("looted: {}", outcome.is_committed());
///         });
///     });
///     Ok(())
/// }
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Inventories {
    host: Host,
    components: Components,
    scheduler: Scheduler,
    layout: Layout,
    errors: OpErrors,
}

impl crate::script::Bound for Inventories {
    const NAME: &'static str = "inventory";
    const DOC: &'static str =
        "Inventories on the server: their slots and counts, and items given, taken and moved.";
    const PARTS: &'static [&'static [crate::script::Function<Self>]] = &[Self::SCRIPT_STOCK];

    fn resolve(load: &mut Load<'_>) -> Result<Self, Off> {
        load.inventories()
    }
}

#[crate::script(stock)]
impl Inventories {
    pub(crate) fn resolve(load: &mut Load<'_>) -> Result<Self, Off> {
        let host = load.host();
        let scheduler = load.scheduler()?;
        let status = (host.api().inventory_open)(host.handle());
        if !status.is_ok() {
            return Err(Off::new(format!(
                "inventories: unavailable on this game build (status {})",
                status.0
            )));
        }
        let components = Components::resolve(load)?;
        let offset = |id: &str| {
            load.constant(id)
                .and_then(|v| usize::try_from(v).map_err(|_| Off::new(format!("offset {id}"))))
        };
        let layout = Layout {
            setup: ComponentType::resolve(load, ids::INVENTORY_SETUP)?,
            inventory: ComponentType::resolve(load, ids::INVENTORY)?,
            durability: ComponentType::resolve(load, ids::DURABILITY)?,
            fuel: ComponentType::resolve(load, ids::FUEL)?,
            owner: ComponentType::resolve(load, ids::OWNER)?,
            links: offset(ids::INVENTORY_SETUP_LINKS)?,
            categories: offset(ids::INVENTORY_SETUP_CATEGORIES)?,
            initialized: offset(ids::INVENTORY_SETUP_INITIALIZED)?,
            stack: usize::try_from(load.type_size(ids::ITEM_STACK)?)
                .map_err(|_| Off::new(ids::ITEM_STACK))?,
            stack_count: offset(ids::ITEM_STACK_COUNT)?,
            stack_pide: offset(ids::ITEM_STACK_PIDE)?,
            durability_max: offset(ids::DURABILITY_MAX)?,
            fuel_max: offset(ids::FUEL_MAX)?,
            skip: usize::try_from(load.symbol("inventory.skip_entity")?)
                .map_err(|_| Off::new("inventory.skip_entity"))?,
        };
        Ok(Self {
            host,
            components,
            scheduler,
            layout,
            errors: OpErrors::resolve(load, OpError::IDS),
        })
    }

    /// Reads on the server's game thread, between steps: from a game event
    /// or a [`Scheduler`] task. Elsewhere they return nothing.
    ///
    /// # Examples
    ///
    /// See [`Inventories`].
    #[must_use]
    pub const fn read(&self) -> Reader<'_> {
        Reader {
            inventories: self,
            ctx: core::ptr::null_mut(),
        }
    }

    /// Reads from inside a hooked ECS system, through its context.
    ///
    /// # Safety
    ///
    /// - `ctx` is the live query context the hooked system was called with.
    /// - The reader and every copy of it are used on that system's thread
    ///   during the hook only.
    ///
    /// # Examples
    ///
    /// ```
    /// unsafe fn held(inventories: &enshwick::inventory::Inventories, ctx: *mut u64, player: enshwick::Entity) -> u32 {
    ///     // SAFETY: called from a system's hook with its live context, used at once.
    ///     unsafe { inventories.read_in(ctx) }.count(player, enshwick::ItemId::new(0x0c01))
    /// }
    /// ```
    #[must_use]
    pub const unsafe fn read_in(&self, ctx: *mut u64) -> Reader<'_> {
        Reader {
            inventories: self,
            ctx,
        }
    }

    /// The static data of `item`; none for an unknown item, or while no
    /// world runs. Any thread.
    ///
    /// # Examples
    ///
    /// See [`ItemInfo`].
    #[must_use]
    #[script]
    pub fn item_info(&self, item: ItemId) -> Option<ItemInfo> {
        let mut out = ItemData {
            header: Header::of::<ItemData>(),
            id: ItemId::new(0),
            max_stack: 0,
            category: 0,
            rarity: 0,
            flags: 0,
            placed_entity: [0; 16],
        };
        let status = (self.host.api().item_info)(self.host.handle(), item, &raw mut out);
        status.is_ok().then_some(ItemInfo {
            id: out.id,
            max_stack_size: out.max_stack,
            flags: out.flags,
            category: out.category,
        })
    }

    /// Submits `batch` from any thread. `done` runs on the game thread after
    /// a later step with the outcome, which the returned [`Ticket`] also
    /// holds. A batch that breaks a limit is refused without reaching the
    /// game. If the mod is turned off first, `done` never runs.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::Entity;
    /// use enshwick::inventory::{Batch, Inventories, Op};
    ///
    /// fn trade(inventories: &Inventories, player: Entity) {
    ///     let batch = Batch::new()
    ///         .with(Op::Take { from: player, item: enshwick::ItemId::new(0x0c01), count: 5 })
    ///         .with(Op::Give { to: player, item: enshwick::ItemId::new(0x5e01), count: 1, fill: None });
    ///     let _ticket = inventories.submit(&batch, |outcome| {
    ///         enshwick::info!("trade: {:?}", outcome.done);
    ///     });
    /// }
    /// ```
    pub fn submit(&self, batch: &Batch, done: impl FnOnce(&Outcome) + Send + 'static) -> Ticket {
        let ticket = Ticket::default();
        let pending = Pending {
            ticket: ticket.clone(),
            done: Box::new(done),
            errors: self.errors,
        };
        if let Err(error) = batch.check() {
            self.later(pending, Done::Refused(error));
            return ticket;
        }
        let ops: Vec<InventoryOp> = batch.ops.iter().map(Op::raw).collect();
        let request = InventoryRequest {
            header: Header::of::<InventoryRequest>(),
            flags: batch.request_flags(),
            actor: batch.actor_entity(),
            ops: ops.as_ptr(),
            op_count: u32::try_from(ops.len()).unwrap_or(0),
            reserved: 0,
        };
        let user = Box::into_raw(Box::new(pending));
        let status = (self.host.api().inventory_submit)(
            self.host.handle(),
            &raw const request,
            deliver,
            user.cast(),
        );
        if !status.is_ok() {
            // SAFETY: `user` came from this function's `Box::into_raw`, and the loader
            // refused it, so it keeps no copy and this is the only owner.
            let pending = unsafe { Box::from_raw(user) };
            self.later(*pending, Done::Unavailable);
        }
        ticket
    }

    /// Every slot of the inventory `root`, as a [reader](Reader::slots) reads it
    /// on the server's game thread; empty elsewhere.
    ///
    /// # Examples
    ///
    /// ```
    /// fn first_item(inventories: &enshwick::inventory::Inventories, player: enshwick::Entity) -> Option<enshwick::ItemId> {
    ///     inventories.slots(player).into_iter().find(|s| !s.is_empty()).map(|s| s.item)
    /// }
    /// ```
    #[must_use]
    #[script]
    pub fn slots(&self, root: Entity) -> Vec<Slot> {
        self.read().slots(root)
    }

    /// How many items `item` the inventory `root` holds, as a [reader](Reader::count)
    /// reads it on the server's game thread; 0 elsewhere.
    ///
    /// # Examples
    ///
    /// ```
    /// fn coins(inventories: &enshwick::inventory::Inventories, player: enshwick::Entity) -> u32 {
    ///     inventories.count(player, enshwick::ItemId::new(0x0c01))
    /// }
    /// ```
    #[must_use]
    #[script]
    pub fn count(&self, root: Entity, item: ItemId) -> u32 {
        self.read().count(root, item)
    }

    /// Completes `pending` with `done` on the game thread after the next step.
    fn later(&self, pending: Pending, done: Done) {
        self.scheduler
            .next_tick(move || pending.complete(&Outcome::not_run(done)));
    }

    /// Gives `count` new items `item` to the inventory `to`, all or nothing,
    /// with the game's pickup message.
    ///
    /// # Examples
    ///
    /// ```
    /// fn reward(inventories: &enshwick::inventory::Inventories, player: enshwick::Entity) {
    ///     inventories.give(player, enshwick::ItemId::new(0x0c01), 10, |outcome| {
    ///         if !outcome.is_committed() {
    ///             enshwick::warn!("no room for the reward");
    ///         }
    ///     });
    /// }
    /// ```
    #[script]
    pub fn give(
        &self,
        to: Entity,
        item: ItemId,
        count: u32,
        done: impl FnOnce(&Outcome) + Send + 'static,
    ) -> Ticket {
        self.submit(
            &Batch::new().with(Op::Give {
                to,
                item,
                count,
                fill: None,
            }),
            done,
        )
    }

    /// Takes `count` items `item` from the inventory `from`, all or nothing.
    ///
    /// # Examples
    ///
    /// ```
    /// fn charge(inventories: &enshwick::inventory::Inventories, player: enshwick::Entity) {
    ///     inventories.take(player, enshwick::ItemId::new(0x0c01), 5, |outcome| enshwick::info!("paid: {}", outcome.is_committed()));
    /// }
    /// ```
    #[script]
    pub fn take(
        &self,
        from: Entity,
        item: ItemId,
        count: u32,
        done: impl FnOnce(&Outcome) + Send + 'static,
    ) -> Ticket {
        self.submit(&Batch::new().with(Op::Take { from, item, count }), done)
    }

    /// Destroys the stack in `slot`.
    ///
    /// # Examples
    ///
    /// ```
    /// fn burn(inventories: &enshwick::inventory::Inventories, slot: enshwick::inventory::SlotRef) {
    ///     inventories.destroy_slot(slot, |_| {});
    /// }
    /// ```
    #[script]
    pub fn destroy_slot(
        &self,
        slot: SlotRef,
        done: impl FnOnce(&Outcome) + Send + 'static,
    ) -> Ticket {
        self.submit(&Batch::new().with(Op::DestroySlot(slot)), done)
    }

    /// Moves the stack in `slot`, or `amount` of it, into the inventory `to`;
    /// what does not fit stays in the source.
    ///
    /// # Examples
    ///
    /// ```
    /// fn hand_over(inventories: &enshwick::inventory::Inventories, slot: enshwick::inventory::SlotRef, player: enshwick::Entity) {
    ///     inventories.move_slot(slot, player, None, |_| {});
    /// }
    /// ```
    #[script]
    pub fn move_slot(
        &self,
        slot: SlotRef,
        to: Entity,
        amount: Option<u16>,
        done: impl FnOnce(&Outcome) + Send + 'static,
    ) -> Ticket {
        self.submit(&Batch::new().with(Op::MoveSlot { slot, to, amount }), done)
    }

    /// Moves every stack of the inventory `from` into `to`, as the game's
    /// "take all" does; what does not fit stays in the source. The source's
    /// action bar, equipment and locked slots stay; [a move in a batch](Op::MoveAll)
    /// can include them.
    ///
    /// # Examples
    ///
    /// See [`Inventories`].
    #[script]
    pub fn move_all(
        &self,
        from: Entity,
        to: Entity,
        done: impl FnOnce(&Outcome) + Send + 'static,
    ) -> Ticket {
        let all = Op::MoveAll {
            from,
            to,
            include_special: false,
        };
        self.submit(&Batch::new().with(all), done)
    }

    /// Renews every stack of `items` in the inventory `root` that has no
    /// entity of its own, each with its meter at `fill`, in one
    /// transaction ([`Op::Renew`]): items from before their mod gave them a
    /// meter get one at once. Reads on the game thread, as
    /// [`Inventories::read`]; `None` when nothing needs it, without calling
    /// `done`.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::events::PlayerJoined;
    /// use enshwick::inventory::Fill;
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     const STAFF: enshwick::ItemId = enshwick::ItemId::new(0x5e01);
    ///     let inventories = load.inventories()?;
    ///     load.on::<PlayerJoined>(move |joined| {
    ///         let player = joined.entity;
    ///         let _renewed = inventories.renew(player, &[STAFF], Fill::FULL, |_| {});
    ///     })
    /// }
    /// ```
    pub fn renew(
        &self,
        root: Entity,
        items: &[ItemId],
        fill: Fill,
        done: impl FnOnce(&Outcome) + Send + 'static,
    ) -> Option<Ticket> {
        let mut batch = Batch::new();
        for slot in self.read().slots(root) {
            if !slot.is_empty() && slot.pide.is_none() && items.contains(&slot.item) {
                batch.push(Op::Renew {
                    slot: slot.at,
                    root,
                    item: slot.item,
                    count: slot.count,
                    fill,
                });
            }
        }
        (!batch.ops().is_empty()).then(|| self.submit(&batch, done))
    }
}

/// Synchronous inventory reads; get one from [`Inventories::read`] or
/// [`Inventories::read_in`].
///
/// # Examples
///
/// See [`Inventories`].
#[derive(Clone, Copy, Debug)]
pub struct Reader<'a> {
    inventories: &'a Inventories,
    /// A system's context, or null for the game thread.
    ctx: *mut u64,
}

impl Reader<'_> {
    fn component(&self, entity: Entity, ty: ComponentType) -> Option<*const u8> {
        if entity.is_none() {
            return None;
        }
        if self.ctx.is_null() {
            ty.read(self.inventories.host, entity)
                .map(<*const c_void>::cast)
        } else {
            // SAFETY: a non-null `ctx` comes only from `read_in`, whose caller
            // guarantees the hooked system's live context, used on its thread
            // during the hook, which is the contract of `component`.
            unsafe { self.inventories.components.component(self.ctx, entity, ty) }
                .map(<*mut u8>::cast_const)
        }
    }

    /// Every slot of the inventory `root`, its virtual links followed, empty
    /// slots included, in the game's order; empty when `root` has no
    /// inventory.
    ///
    /// # Examples
    ///
    /// See [`Inventories`].
    #[must_use]
    pub fn slots(&self, root: Entity) -> Vec<Slot> {
        let layout = &self.inventories.layout;
        let skip = if layout.skip == 0 {
            0
        } else {
            // SAFETY: `skip` is not 0 in this branch, and is the build table's
            // `inventory.skip_entity`, a u32 entity id in the game's image,
            // mapped for the process.
            unsafe { read_at::<u32>(core::ptr::with_exposed_provenance(layout.skip), 0) }
        };
        let mut out = Vec::new();
        self.walk(root, 0, skip, &mut out);
        out
    }

    fn walk(&self, root: Entity, depth: u32, skip: u32, out: &mut Vec<Slot>) {
        let layout = &self.inventories.layout;
        let Some(setup) = self.component(root, layout.setup) else {
            return;
        };
        // SAFETY: `component` returned the entity's live InventorySetup, whose
        // `isInitialized` byte sits at the reflected offset `initialized`.
        if unsafe { read_at::<u8>(setup, layout.initialized) } == 0 {
            return;
        }
        for i in 0..LINKS {
            // SAFETY: `setup` is the live InventorySetup, whose `LINKS` u32
            // `linksEntities` start at the reflected offset `links`, and
            // `i < LINKS`.
            let link: u32 = unsafe { read_at(setup, layout.links + i * size_of::<u32>()) };
            if link == 0 {
                break;
            }
            if link == skip {
                continue;
            }
            // SAFETY: `setup` is the live InventorySetup, whose `LINKS`
            // `linksCategories` bytes start at the reflected offset
            // `categories`, and `i < LINKS`.
            let category = InventoryCategory(unsafe { read_at(setup, layout.categories + i) });
            if category == InventoryCategory::VIRTUAL {
                if depth < MAX_DEPTH {
                    self.walk(Entity(link), depth + 1, skip, out);
                }
                continue;
            }
            if let Some(slots) = self.component(Entity(link), layout.inventory) {
                out.extend((0..SLOTS).map(|index| {
                    // SAFETY: `component` returned the link's live Inventory,
                    // which holds `SLOTS` stacks, and `index < SLOTS`.
                    unsafe { self.stack(slots, Entity(link), index, category) }
                }));
            }
        }
    }

    /// The stack `index` of the `Inventory` at `slots`.
    ///
    /// # Safety
    ///
    /// - `slots` points at a live `Inventory`, read while it is valid with no
    ///   concurrent writer.
    /// - `index` is below `SLOTS`.
    unsafe fn stack(
        &self,
        slots: *const u8,
        inventory: Entity,
        index: u8,
        category: InventoryCategory,
    ) -> Slot {
        let layout = &self.inventories.layout;
        let at = usize::from(index) * layout.stack;
        Slot {
            at: SlotRef::new(inventory, index),
            category,
            // SAFETY: the caller guarantees a live `Inventory` and an index
            // below `SLOTS`; stack `index` starts at `at`, `index` times the
            // reflected `ItemStack` size, with its u32 item id.
            item: unsafe { read_at(slots, at) },
            // SAFETY: the caller guarantees a live `Inventory` and an index
            // below `SLOTS`; the stack's u32 count sits at the reflected
            // offset of `ItemStack.data`.
            count: unsafe { read_at(slots, at + layout.stack_count) },
            // SAFETY: the caller guarantees a live `Inventory` and an index
            // below `SLOTS`; the stack's u32 item entity follows its count in
            // `ItemStack.data`.
            pide: Entity::from_raw(unsafe { read_at(slots, at + layout.stack_pide) }),
        }
    }

    /// What `slot` holds, with [`InventoryCategory::INVALID`].
    ///
    /// # Examples
    ///
    /// ```
    /// fn holds(reader: &enshwick::inventory::Reader<'_>, slot: enshwick::inventory::SlotRef) -> bool {
    ///     reader.slot(slot).is_some_and(|s| !s.is_empty())
    /// }
    /// ```
    #[must_use]
    pub fn slot(&self, slot: SlotRef) -> Option<Slot> {
        if slot.index() >= SLOTS {
            return None;
        }
        let slots = self.component(slot.inventory(), self.inventories.layout.inventory)?;
        // SAFETY: `component` returned the inventory's live Inventory, and
        // `index < SLOTS` was checked above.
        Some(unsafe {
            self.stack(
                slots,
                slot.inventory(),
                slot.index(),
                InventoryCategory::INVALID,
            )
        })
    }

    /// How many items `item` the inventory `root` holds.
    ///
    /// # Examples
    ///
    /// See [`Inventories::read_in`].
    #[must_use]
    pub fn count(&self, root: Entity, item: ItemId) -> u32 {
        self.slots(root)
            .iter()
            .filter(|s| s.item == item && !s.is_empty())
            .fold(0, |sum, s| sum.saturating_add(s.count))
    }

    /// The inventory a slot belongs to at the root, the chest or player,
    /// found by climbing `OwnerRelationship` from its sub-inventory; `None`
    /// when the sub-inventory has no owner.
    ///
    /// # Examples
    ///
    /// ```
    /// fn owner(reader: &enshwick::inventory::Reader<'_>, slot: enshwick::inventory::SlotRef) {
    ///     if let Some(root) = reader.root(slot) {
    ///         enshwick::info!("slot of {}", root.0);
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn root(&self, slot: SlotRef) -> Option<Entity> {
        let mut entity = slot.inventory();
        let mut climbed = false;
        for _ in 0..MAX_OWNERS {
            let Some(owner) = self.component(entity, self.inventories.layout.owner) else {
                break;
            };
            // SAFETY: `component` returned the entity's live
            // OwnerRelationship, which is the owner's u32 entity id alone.
            let owner = Entity(unsafe { read_at(owner, 0) });
            if owner.is_none() || owner == entity {
                break;
            }
            entity = owner;
            climbed = true;
        }
        climbed.then_some(entity)
    }

    /// The durability of an item's own entity, its PIDE, as clients see it.
    ///
    /// # Examples
    ///
    /// ```
    /// fn worn(reader: &enshwick::inventory::Reader<'_>, slot: &enshwick::inventory::Slot) -> bool {
    ///     slot.pide.and_then(|pide| reader.durability(pide)).is_some_and(|d| d.current * 4 < d.max)
    /// }
    /// ```
    #[must_use]
    pub fn durability(&self, pide: Entity) -> Option<Bar> {
        let layout = &self.inventories.layout;
        self.bar(pide, layout.durability, layout.durability_max)
    }

    /// The meter of an item's own entity (see
    /// [`FuelSetup`](crate::content::items::FuelSetup)), as clients see it; `None`
    /// for an item without one.
    ///
    /// # Examples
    ///
    /// ```
    /// fn charges(reader: &enshwick::inventory::Reader<'_>, slot: &enshwick::inventory::Slot) -> u16 {
    ///     slot.pide.and_then(|pide| reader.meter(pide)).map_or(0, |m| m.current)
    /// }
    /// ```
    #[must_use]
    pub fn meter(&self, pide: Entity) -> Option<Bar> {
        let layout = &self.inventories.layout;
        self.bar(pide, layout.fuel, layout.fuel_max)
    }

    fn bar(&self, pide: Entity, ty: ComponentType, max: usize) -> Option<Bar> {
        let data = self.component(pide, ty)?;
        Some(Bar {
            // SAFETY: `component` returned the item's live NetworkDurability
            // or NetworkFuel, which starts with its u16 current value.
            current: unsafe { read_at(data, 0) },
            // SAFETY: `data` is the item's live NetworkDurability or
            // NetworkFuel, whose u16 maximum sits at the reflected offset
            // `max`.
            max: unsafe { read_at(data, max) },
        })
    }
}