Module triggers

Source
Expand description

Bounded, opt-in sensor occupancy derived from accepted ContactEvents.

A physical pair maps to one caller-selected direction: a logical sensor and actor. Both keys may represent a collider, body, or a game-owned ID. For sensor/sensor pairs the caller chooses a direction (or uses a second tracker for the reverse direction). Solid contacts must explicitly resolve to StartResolution::Ignore; this module never detects or classifies contacts.

Feed each valid outer step’s events once, in world order, before removing the objects needed to resolve starts. Starts cache full generational handles and logical keys until the matching stop, even after explicit actor removal. Duplicate starts for a retained pair do not resolve again or add references; unknown/duplicate stops do nothing and report PairUpdate::UntrackedStop. Reversed handle order is equivalent. Different handle generations are not.

§Input loss and reconciliation

An incomplete batch freezes updates before consuming any of its events. SensorOccupancyTracker::mark_incomplete does the same for a separately reported loss. Retained state and queued events remain available as historical observations, but occupancy is no longer authoritative. No timeout, missing pair, or truncated input invents an exit. Recover with a complete caller-owned SensorOccupancyTracker::reconcile snapshot, or SensorOccupancyTracker::reset at a known empty baseline. Neither operation synthesizes gameplay events.

Capacity/resolution errors reject the current event without mutating tracker state. A batch may already have accepted a prefix: retry its rejected suffix before later input, or mark the stream incomplete. Drain output to recover event capacity. Pair capacity requires eventual stops or reconciliation; explicit removal retains mappings and therefore does not free pair capacity. Resolver side effects are outside this atomicity guarantee.

The caller must report missing or reordered input. Unknown stops can also be ignored solid contacts, so they cannot automatically establish loss. A stale same-generation start after its stop is indistinguishable from a real reentry; this tracker is not a replay/sequence-number deduplicator. Sensor classification changes without lifecycle events require explicit reconciliation as well.

All storage is inline. Construction, updates, queries, removal, reconciliation and output draining allocate nothing. Pair lookup/counting is linear in PAIRS; removal, distinct occupancy iteration and reconciliation are at most quadratic. Choose modest capacities; reconciliation uses another PAIRS-slot array on the stack. There is no wall clock, polling or simulation stepping here. Caller callbacks and key comparisons own their allocation/panic behavior; keys must implement stable, lawful equality. Panics do not promise rollback.

§Runnable first-party sensor/compound recipe

This runs with either dimensional frontend. Replace the event assertions with checkpoint/pickup rules and route feedback only from accepted occupancy events.

use ferravex_physics::triggers::{
    InputCompleteness, Occupancy, OccupancyEvent, SensorOccupancyTracker,
    StartResolution,
};
let mut world = PhysicsWorld::default();
let actor = world.insert_compound(RigidBodyBuilder::fixed(), [
    ColliderBuilder::ball(1.).translation(-Vector::X),
    ColliderBuilder::ball(1.).translation(Vector::X),
]).unwrap();
let child = world.bodies[actor].colliders()[0];
let (_, sensor) = world.insert(
    RigidBodyBuilder::fixed(), ColliderBuilder::ball(3.).sensor(true),
);
let occupant = Occupancy { sensor, actor };
let mut tracker = SensorOccupancyTracker::<8, 4>::new();
world.step(1. / 120.); // Actual accepted world events, once per valid step.
tracker.consume_batch(world.contact_events(), InputCompleteness::Complete, |a, b| {
    let other = if a == sensor { b } else if b == sensor { a } else {
        return StartResolution::Ignore;
    };
    // This authored sensor is explicitly classified, not inferred from Started.
    assert!(world.colliders[sensor].is_sensor());
    match world.colliders.get(other).and_then(|c| c.parent()) {
        Some(actor) => StartResolution::Track(Occupancy { sensor, actor }),
        None => StartResolution::Unresolved,
    }
}).unwrap();
assert_eq!(tracker.active_pairs(occupant), 2);
assert_eq!(tracker.pop_event(), Some(OccupancyEvent::Entered(occupant)));
assert_eq!(tracker.pop_event(), None);
world.remove_collider(child).unwrap();
world.step(1. / 120.);
tracker.consume_batch(world.contact_events(), InputCompleteness::Complete,
    |_, _| panic!("stops use cached identities")).unwrap();
assert_eq!(tracker.active_pairs(occupant), 1);
assert_eq!(tracker.pop_event(), None);
assert!(world.remove_body(actor));
world.step(1. / 120.); // Stop still has the removed child's original generation.
tracker.consume_batch(world.contact_events(), InputCompleteness::Complete,
    |_, _| panic!("removed bodies need no lookup")).unwrap();
assert_eq!(tracker.pop_event(), Some(OccupancyEvent::Exited(occupant)));
assert_eq!(tracker.pair_count(), 0);

Structs§

BatchError
Batch failure and the exact accepted prefix length. Retry events[consumed..] before later input, or explicitly freeze/reconcile the tracker.
Occupancy
Caller-resolved, stable logical identity. Defaults use generational physics handles. See the module recipe; custom keys should include their own lifetime generation if IDs can be reused before old stops arrive.
ResolvedPair
Physical pair and its single logical association for baseline reconciliation. Input may use either collider order; duplicate pairs are rejected.
SensorOccupancyTracker
Inline pair mappings and a bounded FIFO of logical events. PAIRS counts cached physical pairs (including explicitly removed occupants awaiting stops). EVENTS counts undrained output. Zero capacities are supported. See the module recipe for the default generational-handle keys.

Enums§

InputCompleteness
Whether the supplied batch/snapshot contains all relevant records. Complete is a caller assertion, not something this adapter can discover.
OccupancyEvent
An accepted logical occupancy transition, in consumption order. Explicit removal also emits exits; reset/reconciliation/input loss never do.
PairUpdate
Result of one accepted input event. A tracked start/stop need not produce a logical transition if other children still occupy the same sensor.
StartResolution
Explicit policy for a previously unknown start. Resolution is never requested for stops or retained duplicate starts. Use Unresolved when identity or classification is unavailable, rather than silently ignoring a sensor.
TriggerError
Rejected operation. Unless documented for an incomplete batch, state and pending output are unchanged; no accepted event is silently dropped.