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
//! Survivors: who answers the game's question "which entity is this
//! survivor", their beds, summoning staffs and the client's survivor menu.
//!
//! The game keeps one entity per survivor and asks for it from many systems.
//! A mod that keeps several entities of a survivor answers each asker with
//! the one that suits it; the platform tells the askers apart and reads what
//! they work on. Cells are whole 0.5 m cells, as
//! in [`altars`](crate::altars).
//!
//! # Examples
//!
//! ```
//! use enshwick::survivors::{Answer, Purpose};
//!
//! fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
//!     // Never move a survivor with its staff: always spawn a new one.
//!     load.on_survivor_lookup(|lookup| match lookup.purpose {
//!         Purpose::Spawn { .. } => Answer::Nobody,
//!         _ => Answer::Vanilla,
//!     })
//! }
//! ```

use core::ffi::c_void;

use crate::abi::{
    BedCheck as RawBedCheck, HostApi, Summon as RawSummon, SurvivorLookup as RawLookup,
};
use crate::content::Guid;
use crate::inventory::{Bar, SlotRef};
use crate::{Entity, ItemId};
use crate::{Load, Off};

mod workshop;

pub use workshop::{WORKSHOP_SURVIVORS, WorkshopSurvivor};

pub use crate::abi::NpcId;

/// Who asks for a survivor's entity, with what it works on.
///
/// The name is enshwick's, not the game's.
///
/// # Examples
///
/// See the [module](self).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Purpose {
    /// The pass that keeps one entity per survivor looks at `entity`, whose
    /// home is `home`. Answer `entity` to keep it, another entity to have the
    /// game remove `entity`, or [`Answer::Nobody`] when there is no entity yet. After
    /// an answer that keeps another entity than the game's, the survivor's
    /// record stays on the game's own.
    Uniqueness {
        /// The entity looked at.
        entity: Entity,
        /// Its saved spawn cell, or where it stands.
        home: [i64; 3],
    },
    /// A summoning staff used at `target`: answer the entity to move there,
    /// or [`Answer::Nobody`] to spawn a new one. The move then reaches only
    /// the answered entity.
    Spawn {
        /// The cell the staff aims at.
        target: [i64; 3],
    },
    /// A bed at `bed_at` binding its sleeper: answer the entity that may
    /// sleep there, or [`Answer::Nobody`].
    BedOwner {
        /// The bed's cell.
        bed_at: [i64; 3],
    },
    /// A player gives `bed` at `bed_at` to the survivor with its staff:
    /// answer the entity that gets it.
    AssignBed {
        /// The bed.
        bed: Entity,
        /// Its cell.
        bed_at: [i64; 3],
    },
    /// The same assignment asks who slept in `bed` before: answer that
    /// entity, or [`Answer::Nobody`]. [`Lookup::bed_of`] tells.
    PreviousOccupant {
        /// The bed.
        bed: Entity,
        /// Its cell.
        bed_at: [i64; 3],
    },
    /// A survivor's idle behaviour: `entity` stands at `at`; answer the entity
    /// whose base it keeps to.
    Roaming {
        /// The survivor's entity.
        entity: Entity,
        /// Where it stands.
        at: [i64; 3],
    },
    /// The first binding of beds after a load, before beds bind their
    /// sleepers.
    BedBinding,
    /// The cursor measuring how far a bed lies from the survivor before it
    /// offers to assign it; [`Answer::Nobody`] skips the measure. A client
    /// alone asks this too, about its own cursor.
    Cursor,
}

/// A lookup the game makes, from [`Load::on_survivor_lookup`].
///
/// # Examples
///
/// See the [module](self).
#[derive(Debug)]
pub struct Lookup {
    /// The survivor.
    pub survivor: NpcId,
    /// The game's own answer, if any.
    pub vanilla: Option<Entity>,
    /// Who asks.
    pub purpose: Purpose,
    bed_of: Option<unsafe extern "system" fn(*mut c_void, Entity) -> Entity>,
    token: *mut c_void,
}

impl Lookup {
    /// The bed `entity` sleeps in, during a
    /// [`Purpose::PreviousOccupant`] or another lookup that can tell.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::Entity;
    /// use enshwick::survivors::{Answer, Lookup, Purpose};
    ///
    /// fn previous(lookup: &Lookup, entities: &[Entity]) -> Answer {
    ///     match lookup.purpose {
    ///         Purpose::PreviousOccupant { bed, .. } => entities
    ///             .iter()
    ///             .find(|&&entity| lookup.bed_of(entity) == Some(bed))
    ///             .map_or(Answer::Nobody, |&entity| Answer::Entity(entity)),
    ///         _ => Answer::Vanilla,
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn bed_of(&self, entity: Entity) -> Option<Entity> {
        let bed_of = self.bed_of?;
        // SAFETY: the loader's function and token, valid for this call.
        let bed = unsafe { bed_of(self.token, entity) };
        (!bed.is_none()).then_some(bed)
    }
}

/// The answer to a [`Lookup`].
///
/// The name is enshwick's, not the game's.
///
/// # Examples
///
/// See the [module](self).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Answer {
    /// The game's own answer.
    Vanilla,
    /// This entity.
    Entity(Entity),
    /// No entity.
    Nobody,
}

/// A survivor's bed the game kept, from [`Load::on_survivor_bed_check`].
/// The name is enshwick's; the game's own bed check has none.
///
/// # Examples
///
/// See [`Load::on_survivor_bed_check`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BedCheck {
    /// The survivor, as the game's active NPC state names it.
    pub npc_id: NpcId,
    /// Its entity.
    pub entity: Entity,
    /// The bed, as the survivor's NPC record names it.
    pub bed_id: Entity,
    /// Where the survivor belongs: its saved spawn cell, or where it stands.
    pub home: [i64; 3],
    /// Where the bed stands.
    pub bed_at: [i64; 3],
}

/// A summoning staff's use, from [`Load::on_summon`] and
/// [`Load::on_summoned`].
///
/// # Examples
///
/// See [`Load::on_summon`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Summon {
    /// The item used.
    pub item: ItemId,
    /// The ammunition used, if any.
    pub ammo: Option<ItemId>,
    /// The template it places.
    pub template: Guid,
    /// The target cell.
    pub target: [i64; 3],
    /// The slot the used item lies in.
    pub slot: SlotRef,
    /// The used item's own entity; `None` for an item without one.
    pub pide: Option<Entity>,
    /// The used item's meter (see [`FuelSetup`](crate::content::items::FuelSetup))
    /// as clients see it; `None` for an item without one.
    pub meter: Option<Bar>,
    /// In [`Load::on_summoned`]: whether the use took the item.
    pub consumed: bool,
}

impl Summon {
    /// The use as the loader hands it on.
    fn from_raw(raw: &RawSummon) -> Self {
        let [current, max] = raw.meter;
        Self {
            item: raw.item,
            ammo: (raw.ammo.get() != 0).then_some(raw.ammo),
            template: Guid(raw.template),
            target: raw.target,
            slot: SlotRef(raw.slot),
            pide: Entity::from_raw(raw.pide.0),
            meter: (max != 0).then_some(Bar { current, max }),
            consumed: raw.consumed != 0,
        }
    }
}

unsafe extern "system" fn run_lookup<F>(
    call: *const RawLookup,
    user: *mut c_void,
    out: *mut Entity,
) -> u8
where
    F: Fn(&Lookup) -> Answer,
{
    // SAFETY: the loader passes a valid call for the duration of this one.
    let Some(call) = (unsafe { call.as_ref() }) else {
        return 0;
    };
    let entity = call.entity;
    let purpose = match call.purpose {
        RawLookup::UNIQUENESS => Purpose::Uniqueness {
            entity,
            home: call.cell,
        },
        RawLookup::SPAWN => Purpose::Spawn { target: call.cell },
        RawLookup::BED_OWNER => Purpose::BedOwner { bed_at: call.cell },
        RawLookup::ASSIGN_BED => Purpose::AssignBed {
            bed: entity,
            bed_at: call.cell,
        },
        RawLookup::PREVIOUS_OCCUPANT => Purpose::PreviousOccupant {
            bed: entity,
            bed_at: call.cell,
        },
        RawLookup::ROAMING => Purpose::Roaming {
            entity,
            at: call.cell,
        },
        RawLookup::BED_BINDING => Purpose::BedBinding,
        RawLookup::CURSOR => Purpose::Cursor,
        _ => return 0,
    };
    let lookup = Lookup {
        survivor: call.survivor,
        vanilla: (!call.vanilla.is_none()).then_some(call.vanilla),
        purpose,
        bed_of: call.bed_of,
        token: call.token,
    };
    // SAFETY: `user` is the leaked `F` this function was registered with.
    let handler = unsafe { &*user.cast::<F>() };
    let answer = crate::host::guard(
        "panic in a survivor lookup",
        || Answer::Vanilla,
        || handler(&lookup),
    );
    let value = match answer {
        Answer::Vanilla => return 0,
        Answer::Entity(entity) => entity,
        Answer::Nobody => Entity::NONE,
    };
    if !out.is_null() {
        // SAFETY: the loader's out pointer.
        unsafe { out.write(value) };
    }
    1
}

unsafe extern "system" fn run_bed_check<F>(check: *const RawBedCheck, user: *mut c_void) -> u8
where
    F: Fn(&BedCheck) -> bool,
{
    // SAFETY: the loader passes a valid check for the duration of the call.
    let Some(check) = (unsafe { check.as_ref() }) else {
        return 1;
    };
    let call = BedCheck {
        npc_id: check.npc_id,
        entity: check.entity,
        bed_id: check.bed_id,
        home: check.home,
        bed_at: check.bed_at,
    };
    // SAFETY: `user` is the leaked `F` this function was registered with.
    let handler = unsafe { &*user.cast::<F>() };
    let keep = crate::host::guard("panic in a survivor bed check", || true, || handler(&call));
    u8::from(keep)
}

/// The loader's summon, read as far as its header says it reaches.
///
/// # Safety
///
/// - `summon` is null, or points at a summon the loader wrote, readable for
///   the size its header states.
/// - No other thread writes that summon during the call.
unsafe fn read_summon(summon: *const RawSummon) -> Option<Summon> {
    // SAFETY: `read_headed` needs `summon` null or readable for its header's
    // size with no concurrent writer, which this function's `# Safety`
    // bullets guarantee; every loader writes the fields up to the slot.
    let raw = unsafe { crate::abi::read_headed(summon, core::mem::offset_of!(RawSummon, slot)) }?;
    Some(Summon::from_raw(&raw))
}

/// What a summon filter makes of a staff's use, from [`Load::on_summon`].
///
/// The name is enshwick's, not the game's.
///
/// # Examples
///
/// See [`Load::on_summon`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SummonVerdict {
    /// The use goes on as the game decides.
    Allow,
    /// The use takes the staff, in the same transaction as the spawn or
    /// move and only when that works.
    Take,
    /// The use is refused: nothing spawns, moves or is taken.
    Refuse,
}

unsafe extern "system" fn run_summon<F>(summon: *const RawSummon, user: *mut c_void) -> u8
where
    F: Fn(&Summon) -> SummonVerdict,
{
    // SAFETY: the loader passes a valid summon for the duration of the call.
    let Some(call) = (unsafe { read_summon(summon) }) else {
        return 0;
    };
    // SAFETY: `user` is the leaked `F` this function was registered with.
    let handler = unsafe { &*user.cast::<F>() };
    let verdict = crate::host::guard(
        "panic in a summon filter",
        || SummonVerdict::Allow,
        || handler(&call),
    );
    match verdict {
        SummonVerdict::Allow => 0,
        SummonVerdict::Take => RawSummon::TAKE,
        SummonVerdict::Refuse => RawSummon::REFUSE,
    }
}

unsafe extern "system" fn run_summoned<F>(summon: *const RawSummon, user: *mut c_void) -> u8
where
    F: Fn(&Summon),
{
    // SAFETY: the loader passes a valid summon for the duration of the call.
    let Some(call) = (unsafe { read_summon(summon) }) else {
        return 0;
    };
    // SAFETY: `user` is the leaked `F` this function was registered with.
    let handler = unsafe { &*user.cast::<F>() };
    crate::host::guard("panic in a summon handler", || (), || handler(&call));
    0
}

unsafe extern "system" fn run_status<F>(
    survivor: NpcId,
    statuses: *const u8,
    count: usize,
    user: *mut c_void,
) -> u32
where
    F: Fn(NpcId, &[u8]) -> Option<u8>,
{
    let statuses = if statuses.is_null() || count == 0 {
        &[][..]
    } else {
        // SAFETY: `count` bytes at `statuses`, valid for the call.
        unsafe { core::slice::from_raw_parts(statuses, count) }
    };
    // SAFETY: `user` is the leaked `F` this function was registered with.
    let handler = unsafe { &*user.cast::<F>() };
    let shown = crate::host::guard(
        "panic in a survivor status merge",
        || None,
        || handler(survivor, statuses),
    );
    shown.map_or(0, |byte| crate::abi::SURVIVOR_STATUS_SET | u32::from(byte))
}

type Register<R> = extern "system" fn(crate::abi::ModHandle, R, *mut c_void) -> crate::abi::Status;

impl Load<'_> {
    fn register<F, R>(
        &mut self,
        what: &str,
        pick: fn(&HostApi) -> Register<R>,
        run: R,
        handler: F,
    ) -> Result<(), Off> {
        let host = self.host();
        let register = pick(host.api());
        crate::load::hand_over(handler, |user| register(host.handle(), run, user), what)
    }

    /// Makes `handler` the answer to the game's survivor lookups; one mod at
    /// a time. It runs on the server's worker threads, in the dedicated
    /// server or a hosting client, and for [`Purpose::Cursor`] on a client
    /// alone too: keep it quick and never block.
    ///
    /// Several engine systems look survivors up for every survivor on every
    /// tick, so `handler` runs many times a frame: answer from state read
    /// without contention, such as a read lock or an atomic snapshot, and
    /// never allocate on the common path.
    ///
    /// # Errors
    ///
    /// [`Off`] after init, when another mod answers already, or on a build
    /// that lacks a piece.
    ///
    /// # Examples
    ///
    /// See the [module](self).
    pub fn on_survivor_lookup<F>(&mut self, handler: F) -> Result<(), Off>
    where
        F: Fn(&Lookup) -> Answer + Send + Sync + 'static,
    {
        self.register(
            "the survivor lookup",
            |api| api.survivor_lookup,
            run_lookup::<F> as crate::abi::SurvivorLookupFn,
            handler,
        )
    }

    /// Runs `filter` after a survivor's own check kept its bed; returning
    /// `false` makes the game clear the bed. Server's worker threads, for
    /// every survivor with a bed on every tick: keep it quick and never
    /// block.
    ///
    /// # Errors
    ///
    /// As for [`Load::on_survivor_lookup`], without the one-mod rule.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     // Survivors keep beds within 100 m of home.
    ///     load.on_survivor_bed_check(|check| (0..3).all(|a| (check.home[a] - check.bed_at[a]).abs() < 200))
    /// }
    /// ```
    pub fn on_survivor_bed_check<F>(&mut self, filter: F) -> Result<(), Off>
    where
        F: Fn(&BedCheck) -> bool + Send + Sync + 'static,
    {
        self.register(
            "the survivor bed check",
            |api| api.survivor_bed_check,
            run_bed_check::<F> as crate::abi::BedCheckFn,
            filter,
        )
    }

    /// Runs `filter` before a summoning staff spawns or moves a survivor:
    /// [`SummonVerdict::Take`] makes the use take the item, in the same
    /// transaction and only when the spawn or move works;
    /// [`SummonVerdict::Refuse`] refuses the use, and nothing spawns, moves
    /// or is taken. On the thread of the use, inside the game's step.
    ///
    /// # Errors
    ///
    /// As for [`Load::on_survivor_bed_check`].
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::survivors::SummonVerdict;
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     const MY_STAFF: enshwick::ItemId = enshwick::ItemId::new(0x5e01);
    ///     load.on_summon(|summon| {
    ///         if summon.item == MY_STAFF && summon.ammo.is_none() {
    ///             SummonVerdict::Take
    ///         } else {
    ///             SummonVerdict::Allow
    ///         }
    ///     })
    /// }
    /// ```
    pub fn on_summon<F>(&mut self, filter: F) -> Result<(), Off>
    where
        F: Fn(&Summon) -> SummonVerdict + Send + Sync + 'static,
    {
        self.register(
            "the summon filter",
            |api| api.summon_filter,
            run_summon::<F> as crate::abi::SummonFn,
            filter,
        )
    }

    /// Runs `handler` after a summoning staff's use spawned or moved a
    /// survivor, with [`Summon::consumed`] saying whether it took the item:
    /// the place to spend a charge of a staff with a meter. On the thread
    /// of the use, inside the game's step: hand game work to the
    /// [`Scheduler`](crate::schedule::Scheduler).
    ///
    /// # Errors
    ///
    /// As for [`Load::on_survivor_bed_check`].
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.on_summoned(|summon| {
    ///         if let (Some(pide), Some(meter), false) = (summon.pide, summon.meter, summon.consumed) {
    ///             enshwick::debug!("item {pide} summoned with {meter:?} left");
    ///         }
    ///     })
    /// }
    /// ```
    pub fn on_summoned<F>(&mut self, handler: F) -> Result<(), Off>
    where
        F: Fn(&Summon) + Send + Sync + 'static,
    {
        self.register(
            "the summon handler",
            |api| api.summoned,
            run_summoned::<F> as crate::abi::SummonFn,
            handler,
        )
    }

    /// Files item `item` as a summoning staff of `survivor`, so the game
    /// treats it as that survivor's staff on both sides: the cursor, the
    /// unlock check and the placement.
    ///
    /// # Errors
    ///
    /// [`Off`] after init or on a build that lacks the registry.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::survivors::NpcId;
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.add_summon_item(enshwick::ItemId::new(0x5e01), NpcId(1_201_801_546))
    /// }
    /// ```
    pub fn add_summon_item(&mut self, item: ItemId, survivor: NpcId) -> Result<(), Off> {
        let host = self.host();
        let status = (host.api().summon_item)(host.handle(), item, survivor);
        if status.is_ok() {
            Ok(())
        } else {
            Err(Off::new(format!(
                "summon item {:#x} refused by the loader (status {})",
                item.get(),
                status.0
            )))
        }
    }

    /// Makes `merge` decide what the client's survivor menu shows for a
    /// survivor with several entities: it gets the status byte of each and
    /// returns the byte to show, or `None` for the game's. Client only; one
    /// mod at a time. It runs every frame while the menu shows, once per such
    /// survivor: it must not allocate or lock.
    ///
    /// # Errors
    ///
    /// [`Off`] on the server, and as for [`Load::on_survivor_lookup`].
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     // Show only the bits every entity has.
    ///     load.on_survivor_status(|_, statuses| {
    ///         (statuses.len() >= 2).then(|| statuses.iter().fold(u8::MAX, |all, s| all & s))
    ///     })
    /// }
    /// ```
    pub fn on_survivor_status<F>(&mut self, merge: F) -> Result<(), Off>
    where
        F: Fn(NpcId, &[u8]) -> Option<u8> + Send + Sync + 'static,
    {
        self.register(
            "the survivor menu merge",
            |api| api.survivor_status,
            run_status::<F> as crate::abi::SurvivorStatusFn,
            merge,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abi::Header;

    fn raw(pide: u32, meter: [u16; 2]) -> RawSummon {
        RawSummon {
            header: Header::of::<RawSummon>(),
            item: ItemId::new(7),
            ammo: ItemId::new(0),
            template: [1; 16],
            target: [1, 2, 3],
            slot: 0x3_0000_0041,
            pide: Entity(pide),
            meter,
            consumed: 1,
            reserved: [0; 3],
        }
    }

    #[test]
    fn a_use_names_its_item_and_meter() {
        let use_ = Summon::from_raw(&raw(900, [2, 3]));
        assert_eq!(
            (use_.slot.inventory(), use_.slot.index()),
            (Entity(0x41), 3)
        );
        assert_eq!(use_.pide, Some(Entity(900)));
        assert_eq!(use_.meter, Some(Bar { current: 2, max: 3 }));
        assert!(use_.consumed);
        assert_eq!(Summon::from_raw(&raw(0, [0; 2])).meter, None);
    }

    #[test]
    fn an_older_loader_s_use_reads_without_the_item() {
        let mut old = raw(900, [2, 3]);
        old.header.size = u32::try_from(core::mem::offset_of!(RawSummon, slot)).unwrap();
        // SAFETY: a valid summon, its header naming the older size.
        let use_ = unsafe { read_summon(&raw const old) }.unwrap();
        assert_eq!(
            (use_.item, use_.pide, use_.meter),
            (ItemId::new(7), None, None)
        );
    }
}