enshwick 1.0.0-alpha.2

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
//! Loot containers on the server: the corpses and loot bags a dead enemy
//! leaves, and other containers that dissolve once emptied.
//!
//! The game checks every such container each step in its system [`SYSTEM`],
//! on a worker thread. Hook that system and walk its rows with
//! [`Containers::each`] from the hook; [`Containers::container`] reads any
//! entity the same way. Take items out with
//! [`Inventories`](crate::inventory::Inventories): the containers walked here
//! all have an `InventorySetup`, so `move_all` empties one.
//!
//! On a client that hosts a game the system also runs in the client's own
//! world; [`Worlds::is_server`](crate::ecs::Worlds::is_server) tells the two
//! apart.
//!
//! [`Load::add_loot`] puts a mod item into random loot with an exact chance,
//! filtered by [`Source`]: corpses, bosses, chests, locked chests, loot labels.

mod drops;

pub use drops::{Drop, Kinds, MeterRoll, Roll, Source, replace_drops};
pub(crate) use drops::{replace_group, watch_rolls};

use crate::ecs::{Components, Ecs, Entity};
use crate::raw::read_at;
use crate::{Load, Off};

/// The system that checks every loot container each step, for
/// [`Load::system`].
pub const SYSTEM: &str = "destroy_inventory_on_loot";

/// Iterator words of [`SYSTEM`]: context, `InventoryEmptyState`,
/// `InventorySetup`, `DestroyOnLoot` and the change tracker.
const ROW_WORDS: usize = 9;

/// The last interaction a player started with a container.
///
/// # Examples
///
/// See [`Container`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Offer {
    /// The entity that last opened or looted the container; `None` before
    /// anyone did.
    pub guest: Option<Entity>,
    /// When, in the game's nanoseconds; changes with each interaction.
    pub accepted_at: i64,
    /// Whether the game offers no interaction now.
    pub disabled: bool,
}

/// What a loot container is and holds, read in one go.
///
/// # Examples
///
/// ```
/// use enshwick::ecs::Entity;
/// use enshwick::loot::{Container, Offer};
///
/// let corpse = Container {
///     entity: Entity(900),
///     position: [10.0, 2.0, -4.0],
///     empty: false,
///     expires: true,
///     area_loot: Some(true),
///     offer: Some(Offer { guest: None, accepted_at: 0, disabled: false }),
/// };
/// assert!(corpse.is_enemy_loot());
/// assert!(corpse.is_open());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Container {
    /// The container.
    pub entity: Entity,
    /// Where it stands, in metres; y is up.
    pub position: [f64; 3],
    /// Whether it holds nothing, as the game last recorded.
    pub empty: bool,
    /// Whether it despawns on its own after a while (`LifeTime`).
    pub expires: bool,
    /// Its `AreaLootOverride`: `Some(true)` when area loot may take it,
    /// `Some(false)` when excluded (items a player dropped), `None` without
    /// one.
    pub area_loot: Option<bool>,
    /// Its interaction offer; `None` without one.
    pub offer: Option<Offer>,
}

impl Container {
    /// Whether it is loot an enemy left: it dissolves when looted, despawns
    /// on its own and is open to area loot. Player chests, world chests and
    /// quest containers are not.
    ///
    /// # Examples
    ///
    /// See [`Container`].
    #[must_use]
    pub const fn is_enemy_loot(&self) -> bool {
        self.expires && matches!(self.area_loot, Some(true))
    }

    /// Whether it is enemy loot a player could take from now: it holds
    /// something and offers its interaction.
    ///
    /// # Examples
    ///
    /// See [`Container`].
    #[must_use]
    pub const fn is_open(&self) -> bool {
        self.is_enemy_loot()
            && !self.empty
            && matches!(
                self.offer,
                Some(Offer {
                    disabled: false,
                    ..
                })
            )
    }
}

/// Whether `at` lies within `radius` metres of `center` across the ground
/// and within `height` metres above or below it.
///
/// # Examples
///
/// ```
/// use enshwick::loot::near;
///
/// assert!(near([0.0, 0.0, 0.0], [6.0, 3.0, 8.0], 10.0, 4.0));
/// assert!(!near([0.0, 0.0, 0.0], [6.0, 5.0, 8.0], 10.0, 4.0));
/// assert!(!near([0.0, 0.0, 0.0], [9.0, 0.0, 9.0], 12.0, 4.0));
/// ```
#[must_use]
pub fn near(center: [f64; 3], at: [f64; 3], radius: f64, height: f64) -> bool {
    let (dx, dy, dz) = (at[0] - center[0], at[1] - center[1], at[2] - center[2]);
    dx.mul_add(dx, dz * dz) <= radius * radius && dy.abs() <= height
}

/// Component hashes and field offsets, from reflection.
#[derive(Clone, Copy, Debug)]
struct Layout {
    transform: u32,
    empty_state: u32,
    destroy: u32,
    lifetime: u32,
    area_loot: u32,
    offer: u32,
    player_input: u32,
    is_empty: usize,
    exclude: usize,
    accept_time: usize,
    accept_guest: usize,
    disabled: usize,
}

/// Reads of loot containers from inside a hooked system; get it with
/// [`Containers::resolve`].
///
/// # Examples
///
/// ```
/// use enshwick::loot::{Containers, SYSTEM};
///
/// enshwick::detour! {
///     static CHECK: unsafe extern "system" fn(ctx: *mut u64) = check;
/// }
///
/// static CONTAINERS: std::sync::OnceLock<Containers> = std::sync::OnceLock::new();
///
/// fn check(next: enshwick::Next<unsafe extern "system" fn(*mut u64)>, ctx: *mut u64) {
///     // SAFETY: the original system takes its own context.
///     unsafe { next.get()(ctx) };
///     if let Some(containers) = CONTAINERS.get() {
///         let mut open = 0;
///         // SAFETY: the system's live context, on its thread.
///         unsafe { containers.each(ctx, |c| open += usize::from(c.is_open())) };
///         let _ = open;
///     }
/// }
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     let _ = CONTAINERS.set(Containers::resolve(load)?);
///     let system = load.system(SYSTEM)?;
///     // SAFETY: the reflected system takes its context, as `CHECK` does.
///     unsafe { load.hook(&CHECK, system) }
/// }
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Containers {
    ecs: Ecs,
    components: Components,
    layout: Layout,
}

impl Containers {
    /// Resolves the reads for the running build.
    ///
    /// # Errors
    ///
    /// [`Off`] when the loader or the game's reflection lacks a piece.
    ///
    /// # Examples
    ///
    /// See [`Containers`].
    pub fn resolve(load: &mut Load<'_>) -> Result<Self, Off> {
        let world = load.world()?;
        let ty = |name: &str| {
            world
                .component_type(load, name)
                .map(crate::world::ComponentType::hash)
        };
        let offset = |ty: &str, field: &str| {
            load.field_offset(ty, field)
                .and_then(|v| usize::try_from(v).map_err(|_| Off::new("offset")))
        };
        let layout = Layout {
            transform: ty("keen::ecs::CurrentTransform")?,
            empty_state: ty("keen::ecs::InventoryEmptyState")?,
            destroy: ty("keen::ecs::DestroyOnLoot")?,
            lifetime: ty("keen::ecs::LifeTime")?,
            area_loot: ty("keen::ecs::AreaLootOverride")?,
            offer: ty("keen::ecs::InteractionOfferRuntime")?,
            player_input: ty("keen::ecs::PlayerInput")?,
            is_empty: offset("keen::ecs::InventoryEmptyState", "isEmpty")?,
            exclude: offset("keen::ecs::AreaLootOverride", "exclude")?,
            accept_time: offset("keen::ecs::InteractionOfferRuntime", "lastAcceptTime")?,
            accept_guest: offset("keen::ecs::InteractionOfferRuntime", "lastAcceptData")?
                + offset("keen::ecs::InteractionAcceptData", "guestId")?,
            disabled: offset("keen::ecs::InteractionOfferRuntime", "isDisabled")?,
        };
        Ok(Self {
            ecs: Ecs::resolve(load)?,
            components: Components::resolve(load)?,
            layout,
        })
    }

    /// Calls `f` with every loot container [`SYSTEM`] checks this step, in
    /// its order, and leaves the system's row where it was.
    ///
    /// # Safety
    ///
    /// `ctx` is the live context of [`SYSTEM`], used on its thread during
    /// its hook.
    ///
    /// # Examples
    ///
    /// See [`Containers`].
    pub unsafe fn each(&self, ctx: *mut u64, mut f: impl FnMut(&Container)) {
        // SAFETY: the system's live context, as the caller vouches.
        let saved = unsafe { self.ecs.row(ctx) };
        // SAFETY: as above.
        unsafe { self.ecs.set_row(ctx, 0) };
        // SAFETY: as above, with the system's iterator size.
        let mut query = unsafe { self.ecs.query::<ROW_WORDS>(ctx) };
        while query.next().is_some() {
            // SAFETY: as above, on the current row.
            let Some(entity) = (unsafe { self.ecs.entity(ctx) }) else {
                continue;
            };
            // SAFETY: as above.
            if let Some(container) = unsafe { self.container(ctx, entity) } {
                f(&container);
            }
        }
        // SAFETY: as above.
        unsafe { self.ecs.set_row(ctx, saved) };
    }

    /// `entity` read as a loot container; `None` when it is not one (it has
    /// no `DestroyOnLoot`, inventory state or position) or is gone.
    ///
    /// # Safety
    ///
    /// `ctx` is the live context of a hooked system, used on its thread.
    ///
    /// # Examples
    ///
    /// ```
    /// unsafe fn still_full(
    ///     containers: &enshwick::loot::Containers,
    ///     ctx: *mut u64,
    ///     corpse: enshwick::ecs::Entity,
    /// ) -> bool {
    ///     // SAFETY: called from a system's hook with its context.
    ///     unsafe { containers.container(ctx, corpse) }.is_some_and(|c| !c.empty)
    /// }
    /// ```
    #[must_use]
    pub unsafe fn container(&self, ctx: *mut u64, entity: Entity) -> Option<Container> {
        let layout = &self.layout;
        // SAFETY: forwarded from the caller, for each read below.
        let read = |hash| unsafe { self.components.component(ctx, entity, hash) };
        read(layout.destroy)?;
        let state = read(layout.empty_state)?;
        // SAFETY: the row's live CurrentTransform.
        let position = unsafe { crate::ecs::transform_position(read(layout.transform)?) };
        // SAFETY: a live InventoryEmptyState holds its flag here.
        let empty = unsafe { read_at::<u8>(state, layout.is_empty) } != 0;
        let area_loot = read(layout.area_loot).map(|data| {
            // SAFETY: a live AreaLootOverride holds its flag here.
            unsafe { read_at::<u8>(data, layout.exclude) == 0 }
        });
        let offer = read(layout.offer).map(|data| Offer {
            // SAFETY: a live InteractionOfferRuntime holds these fields.
            guest: Entity::from_raw(unsafe { read_at(data, layout.accept_guest) }),
            // SAFETY: as above.
            accepted_at: unsafe { read_at(data, layout.accept_time) },
            // SAFETY: as above.
            disabled: unsafe { read_at::<u8>(data, layout.disabled) } != 0,
        });
        Some(Container {
            entity,
            position,
            empty,
            expires: read(layout.lifetime).is_some(),
            area_loot,
            offer,
        })
    }

    /// `entity`'s position in metres.
    ///
    /// # Safety
    ///
    /// As for [`Containers::container`].
    ///
    /// # Examples
    ///
    /// ```
    /// unsafe fn at(c: &enshwick::loot::Containers, ctx: *mut u64, e: enshwick::ecs::Entity) -> bool {
    ///     // SAFETY: called from a system's hook with its context.
    ///     unsafe { c.position(ctx, e) }.is_some()
    /// }
    /// ```
    #[must_use]
    pub unsafe fn position(&self, ctx: *mut u64, entity: Entity) -> Option<[f64; 3]> {
        // SAFETY: forwarded from the caller.
        let data = unsafe {
            self.components
                .component(ctx, entity, self.layout.transform)
        }?;
        // SAFETY: the entity's live CurrentTransform.
        Some(unsafe { crate::ecs::transform_position(data) })
    }

    /// Whether `entity` is a player character.
    ///
    /// # Safety
    ///
    /// As for [`Containers::container`].
    ///
    /// # Examples
    ///
    /// ```
    /// unsafe fn by_player(c: &enshwick::loot::Containers, ctx: *mut u64, e: enshwick::ecs::Entity) -> bool {
    ///     // SAFETY: called from a system's hook with its context.
    ///     unsafe { c.is_player(ctx, e) }
    /// }
    /// ```
    #[must_use]
    pub unsafe fn is_player(&self, ctx: *mut u64, entity: Entity) -> bool {
        // SAFETY: forwarded from the caller.
        unsafe {
            self.components
                .component(ctx, entity, self.layout.player_input)
        }
        .is_some()
    }
}

/// The loot containers of one run of [`SYSTEM`], for [`Load::on_loot_pass`];
/// valid only during the call.
///
/// # Examples
///
/// See [`Load::on_loot_pass`].
#[derive(Debug)]
pub struct LootPass<'a> {
    containers: &'a Containers,
    ctx: *mut u64,
}

impl LootPass<'_> {
    /// Calls `f` with every loot container this run checks, in its order.
    ///
    /// # Examples
    ///
    /// See [`Load::on_loot_pass`].
    pub fn each(&self, f: impl FnMut(&Container)) {
        // SAFETY: the system's live context, during its hook.
        unsafe { self.containers.each(self.ctx, f) };
    }

    /// `entity` read as a loot container; `None` when it is not one or gone.
    ///
    /// # Examples
    ///
    /// ```
    /// fn full(pass: &enshwick::loot::LootPass<'_>, e: enshwick::ecs::Entity) -> bool {
    ///     pass.container(e).is_some_and(|c| !c.empty)
    /// }
    /// ```
    #[must_use]
    pub fn container(&self, entity: Entity) -> Option<Container> {
        // SAFETY: as for `each`.
        unsafe { self.containers.container(self.ctx, entity) }
    }

    /// `entity`'s position in metres.
    ///
    /// # Examples
    ///
    /// ```
    /// fn here(pass: &enshwick::loot::LootPass<'_>, e: enshwick::ecs::Entity) -> bool {
    ///     pass.position(e).is_some()
    /// }
    /// ```
    #[must_use]
    pub fn position(&self, entity: Entity) -> Option<[f64; 3]> {
        // SAFETY: as for `each`.
        unsafe { self.containers.position(self.ctx, entity) }
    }

    /// Whether `entity` is a player character.
    ///
    /// # Examples
    ///
    /// ```
    /// fn by_player(pass: &enshwick::loot::LootPass<'_>, e: enshwick::ecs::Entity) -> bool {
    ///     pass.is_player(e)
    /// }
    /// ```
    #[must_use]
    pub fn is_player(&self, entity: Entity) -> bool {
        // SAFETY: as for `each`.
        unsafe { self.containers.is_player(self.ctx, entity) }
    }
}

type PassHandler = Box<dyn Fn(&LootPass<'_>) + Send + Sync>;

static PASS: std::sync::OnceLock<(Containers, crate::ecs::Worlds, PassHandler)> =
    std::sync::OnceLock::new();

crate::detour! {
    static CHECK: unsafe extern "system" fn(ctx: *mut u64) = after_check;
}

fn after_check(next: crate::Next<unsafe extern "system" fn(*mut u64)>, ctx: *mut u64) {
    // SAFETY: the original system takes its own context.
    unsafe { next.get()(ctx) };
    if let Some((containers, worlds, handler)) = PASS.get()
        // SAFETY: the system's live context.
        && unsafe { worlds.is_server(ctx) }
    {
        // Guarded here: the detour's own guard would run the system again.
        crate::host::guard(
            "panic in a loot pass handler",
            || (),
            || handler(&LootPass { containers, ctx }),
        );
    }
}

impl Load<'_> {
    /// Runs `handler` after every run of the game's loot container check in
    /// the server's world, on the worker thread that runs it, with that run's
    /// containers. One handler per mod.
    ///
    /// # Errors
    ///
    /// [`Off`] for a second handler, or when the loader or the game lacks a
    /// piece.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.on_loot_pass(|pass| {
    ///         let mut emptied = 0;
    ///         pass.each(|container| emptied += usize::from(container.empty));
    ///         let _ = emptied;
    ///     })
    /// }
    /// ```
    pub fn on_loot_pass<F>(&mut self, handler: F) -> Result<(), Off>
    where
        F: Fn(&LootPass<'_>) + Send + Sync + 'static,
    {
        let containers = Containers::resolve(self)?;
        let worlds = crate::ecs::Worlds::resolve(self)?;
        let system = self.system(SYSTEM)?;
        if PASS.set((containers, worlds, Box::new(handler))).is_err() {
            return Err(Off::new("one loot pass handler per mod"));
        }
        // SAFETY: the reflected system is the check `CHECK` declares.
        unsafe { self.hook(&CHECK, system) }
    }
}

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

    fn corpse() -> Container {
        Container {
            entity: Entity(900),
            position: [0.0; 3],
            empty: false,
            expires: true,
            area_loot: Some(true),
            offer: Some(Offer {
                guest: None,
                accepted_at: 0,
                disabled: false,
            }),
        }
    }

    #[test]
    fn only_open_enemy_loot_passes() {
        assert!(corpse().is_open());
        let chest = Container {
            expires: false,
            ..corpse()
        };
        assert!(!chest.is_enemy_loot());
        let dropped = Container {
            area_loot: Some(false),
            ..corpse()
        };
        assert!(!dropped.is_enemy_loot());
        let quest = Container {
            area_loot: None,
            ..corpse()
        };
        assert!(!quest.is_enemy_loot());
        let looted = Container {
            empty: true,
            ..corpse()
        };
        assert!(looted.is_enemy_loot() && !looted.is_open());
        let closed = Container {
            offer: Some(Offer {
                disabled: true,
                ..corpse().offer.unwrap()
            }),
            ..corpse()
        };
        assert!(!closed.is_open());
        let silent = Container {
            offer: None,
            ..corpse()
        };
        assert!(!silent.is_open());
    }

    #[test]
    fn near_measures_ground_and_height_apart() {
        let c = [100.0, 50.0, -20.0];
        assert!(near(c, c, 0.0, 0.0));
        assert!(near(c, [112.0, 50.0, -20.0], 12.0, 4.0));
        assert!(!near(c, [112.1, 50.0, -20.0], 12.0, 4.0));
        assert!(near(c, [100.0, 46.0, -20.0], 12.0, 4.0));
        assert!(!near(c, [100.0, 54.5, -20.0], 12.0, 4.0));
        assert!(!near(c, [109.0, 50.0, -11.0], 12.0, 4.0));
    }
}