Skip to main content

minkowski_space/
m_world.rs

1use crate::collision::collision_calculator::CollisionCalculator;
2use crate::collision::hashgrid::HashGrid;
3use crate::collision::{Collision, CollisionGroup, CollisionPair};
4use crate::config::{ConfigError, MotionMode, ObjectConfig, StartPosition, WorldConfig};
5use crate::m_event::{DetectionObject, EventDetection, MEvent};
6use crate::m_object::{MObject, ObjectState};
7use crate::m_vector::MVector;
8use crate::object_tracker::{ObjectTracker, ReceiverData};
9use crate::observation::{EventObservation, ObjectObservation, VisibleObjectObservation};
10use crate::{CollisionGroupPair, EPSILON};
11use rayon::iter::IntoParallelRefIterator;
12use rayon::iter::{IntoParallelRefMutIterator, ParallelBridge, ParallelIterator};
13use std::cmp::Ordering;
14use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet};
15use std::sync::Arc;
16use vector2d::Vector2D;
17
18struct PendingCollision(Collision);
19
20impl PartialEq for PendingCollision {
21    fn eq(&self, other: &Self) -> bool {
22        self.0.position.time.total_cmp(&other.0.position.time) == Ordering::Equal
23    }
24}
25
26impl Eq for PendingCollision {}
27
28impl PartialOrd for PendingCollision {
29    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
30        Some(self.cmp(other))
31    }
32}
33
34impl Ord for PendingCollision {
35    fn cmp(&self, other: &Self) -> Ordering {
36        other.0.position.time.total_cmp(&self.0.position.time)
37    }
38}
39
40/// A simulation world with a laboratory frame and a moving observer.
41///
42/// Objects are stored and advanced in laboratory coordinates. The observer has
43/// its own world line and proper time, and observations are reported in the
44/// observer's instantaneous frame.
45///
46/// # Example
47///
48/// ```
49/// use minkowski_space::{MWorld, Vector2D};
50///
51/// let mut world = MWorld::new();
52/// world.set_observer_velocity(Vector2D::new(0.5, 0.0));
53/// world.advance_by_proper_time(1.0);
54///
55/// assert!(world.lab_time() > world.observer_tau());
56/// ```
57pub struct MWorld {
58    config: WorldConfig,
59
60    observer_object: MObject,
61
62    registered_objects: HashMap<usize, (MObject, ObjectTracker)>,
63
64    events: HashMap<usize, MEvent>,
65
66    event_possible_to_detect: HashMap<usize, HashSet<usize>>,
67
68    counter: usize,
69
70    hash_grid: HashGrid,
71
72    active_collision_pairs: BTreeMap<CollisionPair, f64>,
73
74    pending_collisions: BinaryHeap<PendingCollision>,
75}
76
77/// A notification produced while advancing the simulation.
78///
79/// Notifications are returned by [`MWorld::advance_by_proper_time`].
80#[derive(Debug)]
81pub enum ProcessTimeCallback {
82    /// Two collision-enabled objects reached a collision.
83    Collision(Collision),
84    /// An object or the observer detected a spacetime event - it means that event is inside past light cone of some object
85    Event(EventDetection),
86}
87
88/// Selects either the observer or a registered object.
89///
90/// The observer can also be selected by passing the integer `0` to methods
91/// accepting `Into<ObjectSelection>`. Registered object IDs are returned by
92/// [`MWorld::register_object`] and [`MWorld::try_register_object`].
93#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
94pub enum ObjectSelection {
95    /// The observer object.
96    Observer,
97    /// A registered object identified by its ID.
98    Object(usize),
99}
100
101impl From<usize> for ObjectSelection {
102    fn from(value: usize) -> Self {
103        match value {
104            0 => ObjectSelection::Observer,
105            x => ObjectSelection::Object(x),
106        }
107    }
108}
109
110impl From<&usize> for ObjectSelection {
111    fn from(value: &usize) -> Self {
112        match value {
113            0 => ObjectSelection::Observer,
114            x => ObjectSelection::Object(*x),
115        }
116    }
117}
118
119impl Default for MWorld {
120    fn default() -> Self {
121        Self::new()
122    }
123}
124
125impl MWorld {
126    /// Creates a world with [`WorldConfig::default`].
127    ///
128    /// # Example
129    ///
130    /// ```
131    /// use minkowski_space::MWorld;
132    ///
133    /// let world = MWorld::new();
134    /// assert_eq!(world.lab_time(), 0.0);
135    /// ```
136    pub fn new() -> Self {
137        Self::with_config(WorldConfig::default()).expect("default world configuration is valid")
138    }
139
140    /// Creates a world using `config`.
141    ///
142    /// # Errors
143    ///
144    /// Returns [`ConfigError`] when the configuration contains invalid values,
145    /// such as a non-positive time step or an invalid collision-group pair.
146    ///
147    /// # Example
148    ///
149    /// ```
150    /// use minkowski_space::{MWorld, WorldConfig};
151    ///
152    /// let world = MWorld::with_config(WorldConfig::default()).unwrap();
153    /// assert_eq!(world.lab_time(), 0.0);
154    /// ```
155    pub fn with_config(mut config: WorldConfig) -> Result<Self, ConfigError> {
156        config.validate()?;
157        config.collision_pairs = config
158            .collision_pairs
159            .into_iter()
160            .map(|pair| pair.canonical())
161            .collect();
162        let observer_config = ObjectConfig {
163            radius: config.observer_collision_radius,
164            ..ObjectConfig::default_with_group(config.observer_collision_group)
165        };
166        Ok(Self {
167            observer_object: MObject::new(observer_config, config.proper_time_step, 0.0, 0),
168            hash_grid: HashGrid::init(&config),
169            config,
170            registered_objects: Default::default(),
171            events: Default::default(),
172            event_possible_to_detect: HashMap::from([(0, HashSet::new())]),
173            counter: 1,
174            active_collision_pairs: BTreeMap::new(),
175            pending_collisions: BinaryHeap::new(),
176        })
177    }
178
179    /// Registers an object and returns its unique ID.
180    ///
181    /// The object's initial position is interpreted in laboratory coordinates.
182    /// An object using [`MotionMode::AlwaysConstantVelocity`] starts with its
183    /// complete constant-velocity trajectory prepared for observation.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`ConfigError`] when `object_config` is invalid, for example
188    /// when its velocity is superluminal or its radius is negative.
189    ///
190    /// # Example
191    ///
192    /// ```
193    /// use minkowski_space::{MWorld, ObjectConfig, Vector2D};
194    ///
195    /// let mut world = MWorld::new();
196    /// let object_id = world.try_register_object(
197    ///     ObjectConfig::at_position_with_const_speed(
198    ///         Vector2D::new(0.0, 0.0),
199    ///         Vector2D::new(0.5, 0.0),
200    ///     ),
201    /// ).unwrap();
202    ///
203    /// assert!(world.object(object_id).is_some());
204    /// ```
205    pub fn try_register_object(
206        &mut self,
207        object_config: ObjectConfig,
208    ) -> Result<usize, ConfigError> {
209        object_config.validate()?;
210        let id = self.counter;
211        let mut m_object = MObject::new(
212            object_config,
213            self.config.proper_time_step,
214            self.observer_object.position().time,
215            id,
216        );
217        let mut object_tracker = ObjectTracker::new();
218        self.counter += 1;
219        if object_config.motion_mode == MotionMode::AlwaysConstantVelocity {
220            let photons = m_object.emmit_all_photons();
221            object_tracker.track_photons(photons);
222        }
223        self.insert_event_possible_to_detect_for_new_object(id, &mut m_object);
224        self.registered_objects
225            .insert(id, (m_object, object_tracker));
226        Ok(id)
227    }
228
229    /// Registers an object and returns its ID.
230    ///
231    /// Prefer [`Self::try_register_object`] when invalid user input must be
232    /// reported to the caller. If registration fails, this convenience method
233    /// returns `usize::MAX`.
234    ///
235    /// # Example
236    ///
237    /// ```
238    /// use minkowski_space::{MWorld, ObjectConfig, Vector2D};
239    ///
240    /// let mut world = MWorld::new();
241    /// let id = world.register_object(ObjectConfig::at_position(
242    ///     Vector2D::new(1.0, 0.0),
243    /// ));
244    /// assert_ne!(id, usize::MAX);
245    /// ```
246    pub fn register_object(&mut self, object_config: ObjectConfig) -> usize {
247        self.try_register_object(object_config)
248            .unwrap_or(usize::MAX)
249    }
250
251    /// Creates an event at the current laboratory time with a collision group.
252    ///
253    /// The returned ID can be passed to [`Self::event`], [`Self::observe_event`]
254    /// and [`Self::unregister_event`].
255    pub fn create_event_with_collision_group(
256        &mut self,
257        event_position: Vector2D<f64>,
258        collision_group: CollisionGroup,
259    ) -> usize {
260        let event = MVector::new(self.lab_time(), event_position);
261        self.create_event_at_impl(event, collision_group)
262    }
263
264    /// Creates an event at the current laboratory time.
265    ///
266    /// The event uses [`CollisionGroup::All`].
267    ///
268    /// # Example
269    ///
270    /// ```
271    /// use minkowski_space::{MWorld, Vector2D};
272    ///
273    /// let mut world = MWorld::new();
274    /// let event_id = world.create_event(Vector2D::new(1.0, 0.0));
275    /// assert!(world.event(&event_id).is_some());
276    /// ```
277    pub fn create_event(&mut self, event_position: Vector2D<f64>) -> usize {
278        let event = MVector::new(self.lab_time(), event_position);
279        self.create_event_at_impl(event, CollisionGroup::All)
280    }
281
282    /// Creates an event at an explicit spacetime position.
283    ///
284    /// The `time` component of `event` is laboratory time. The event uses
285    /// [`CollisionGroup::All`].
286    pub fn create_event_at(&mut self, event: MVector<f64>) -> usize {
287        self.create_event_at_impl(event, CollisionGroup::All)
288    }
289
290    /// Removes a registered object from the world.
291    ///
292    /// Passing [`ObjectSelection::Observer`] has no effect. Removing an object
293    /// also removes its active collision pairs.
294    pub fn unregister_object<T: Into<ObjectSelection>>(&mut self, id: T) {
295        match id.into() {
296            ObjectSelection::Object(id) => {
297                self.registered_objects.remove(&id);
298                self.event_possible_to_detect.remove(&id);
299                self.active_collision_pairs
300                    .retain(|pair, _| !pair.contains(ObjectSelection::Object(id)));
301            }
302            ObjectSelection::Observer => {}
303        }
304    }
305
306    /// Removes an event from the world.
307    ///
308    /// Passing an unknown ID has no effect.
309    pub fn unregister_event(&mut self, id: &usize) {
310        self.events.remove(id);
311        self.event_possible_to_detect.iter_mut().for_each(|s| {
312            s.1.remove(id);
313        });
314    }
315
316    /// Enables or disables collision detection for the selected object.
317    ///
318    /// This does not remove the object. Passing [`ObjectSelection::Observer`]
319    /// changes collision detection for the observer.
320    pub fn set_object_collision_enabled<T: Into<ObjectSelection>>(
321        &mut self,
322        id: T,
323        collision_enabled: bool,
324    ) {
325        let selection = id.into();
326        if !collision_enabled {
327            self.active_collision_pairs
328                .retain(|pair, _| !pair.contains(selection));
329        }
330        if let Some(object) = self.get_object_with_selection_mut(&selection) {
331            object.set_collision_enabled(collision_enabled);
332        }
333    }
334
335    /// Returns a snapshot of the selected object's current state in lab coordinates.
336    /// Don't use this method for observation from observer frame - use [`self.observe_object`] instead
337    /// Returns `None` when the selected registered object does not exist.
338    ///
339    /// # Example
340    ///
341    /// ```
342    /// use minkowski_space::{MWorld, ObjectConfig, Vector2D};
343    ///
344    /// let mut world = MWorld::new();
345    /// let id = world.register_object(ObjectConfig::at_position(Vector2D::new(0.0, 0.0)));
346    /// assert_eq!(world.object(id).unwrap().id, id);
347    /// ```
348    pub fn object<T: Into<ObjectSelection>>(&self, id: T) -> Option<ObjectState> {
349        self.get_object_with_selection(&id.into())
350            .map(|e| e.state())
351    }
352
353    /// Returns a snapshot of the observer's current state.
354    ///
355    /// The state is expressed in laboratory coordinates.
356    pub fn observer_object(&self) -> ObjectState {
357        self.observer_object.state()
358    }
359
360    /// Returns an event's position in laboratory coordinates.
361    ///
362    /// Returns `None` when the event ID is unknown.
363    pub fn event(&self, id: &usize) -> Option<MVector<f64>> {
364        self.events.get(id).map(|e| *e.position())
365    }
366    /// Returns the observer's current observation of a registered object.
367    ///
368    /// Returns `None` when the object ID is unknown. A known object can still
369    /// return [`ObjectObservation::NotVisible`] if its emitted light has not
370    /// reached the observer.
371    pub fn observe_object(&self, id: &usize) -> Option<ObjectObservation> {
372        self.registered_objects
373            .get(id)
374            .map(|e| match e.1.get_object_was_seen() {
375                true => ObjectObservation::Visible(e.1.to_visible_observation()),
376                false => ObjectObservation::NotVisible,
377            })
378    }
379
380    /// Observes an event in the observer's current frame.
381    ///
382    /// Returns `None` when the event ID is unknown. A known event returns
383    /// [`EventObservation::Visible`] when it lies in the observer's past light
384    /// cone; otherwise it returns [`EventObservation::NotVisible`].
385    ///
386    /// The visible position is relative to the observer and expressed in the
387    /// observer's frame.
388    ///
389    /// # Example
390    ///
391    /// ```
392    /// use minkowski_space::{EventObservation, MWorld, Vector2D};
393    ///
394    /// let mut world = MWorld::new();
395    /// let event_id = world.create_event(Vector2D::new(0.0, 0.0));
396    ///
397    /// assert!(matches!(
398    ///     world.observe_event(&event_id),
399    ///     Some(EventObservation::Visible(_))
400    /// ));
401    /// ```
402    pub fn observe_event(&self, id: &usize) -> Option<EventObservation> {
403        self.events.get(id).map(|event| {
404            let relative = *event.position() - *self.observer_object.position();
405            if relative.is_time_or_light_like() {
406                EventObservation::Visible(
407                    relative.lorentz_transform(*self.observer_object.get_velocity()),
408                )
409            } else {
410                EventObservation::NotVisible
411            }
412        })
413    }
414
415    /// Returns whether an event is currently observable by the observer.
416    ///
417    /// Returns `false` when the event ID is unknown or when the event is
418    /// outside the observer's past light cone.
419    pub fn is_event_in_light_cone(&self, id: &usize) -> bool {
420        self.events
421            .get(id)
422            .map(|event| {
423                let relative = *event.position() - *self.observer_object.position();
424                relative.is_time_or_light_like()
425            })
426            .unwrap_or(false)
427    }
428
429    /// Returns the visible observation of a registered object.
430    ///
431    /// Returns `None` when the object is unknown or has not yet been observed.
432    /// Unlike [`Self::observe_object`], this method returns the observation
433    /// directly instead of returning [`ObjectObservation::NotVisible`].
434    pub fn observe_visible_object(&self, id: &usize) -> Option<VisibleObjectObservation> {
435        self.registered_objects
436            .get(id)
437            .and_then(|e| match e.1.get_object_was_seen() {
438                true => Some(e.1.to_visible_observation()),
439                false => None,
440            })
441    }
442
443    /// Sets the velocity of the observer or a dynamic registered object.
444    ///
445    /// The velocity is expressed in laboratory coordinates and in units where
446    /// the speed of light is `1`.
447    ///
448    /// # Errors
449    ///
450    /// Returns [`ConfigError::SuperluminalVelocity`] for a non-finite or
451    /// superluminal velocity. Returns [`ConfigError::UnsupportedOperation`]
452    /// when the selected object does not exist or uses
453    /// [`MotionMode::AlwaysConstantVelocity`].
454    ///
455    /// # Example
456    ///
457    /// ```
458    /// use minkowski_space::{MWorld, Vector2D};
459    ///
460    /// let mut world = MWorld::new();
461    /// world.set_velocity(0, Vector2D::new(0.4, 0.0)).unwrap();
462    /// assert_eq!(world.observer_object().velocity, Vector2D::new(0.4, 0.0));
463    /// ```
464    pub fn set_velocity<T: Into<ObjectSelection>>(
465        &mut self,
466        id: T,
467        velocity: Vector2D<f64>,
468    ) -> Result<(), ConfigError> {
469        if !velocity.x.is_finite()
470            || !velocity.y.is_finite()
471            || velocity.length_squared() >= crate::MAX_SAFE_SPEED_SQUARED
472        {
473            return Err(ConfigError::SuperluminalVelocity);
474        }
475        if let Some(object) = self.get_object_with_selection_mut(&id.into()) {
476            if object.constant_velocity() {
477                return Err(ConfigError::UnsupportedOperation(
478                    "set_velocity on constant-velocity object",
479                ));
480            }
481            object.set_velocity(velocity);
482            return Ok(());
483        }
484        Err(ConfigError::UnsupportedOperation("unknown object"))
485    }
486
487    /// Sets the acceleration of the observer or a dynamic registered object.
488    ///
489    /// This operation has no effect for an unknown object or an object using
490    /// [`MotionMode::AlwaysConstantVelocity`].
491    pub fn set_acceleration<T: Into<ObjectSelection>>(
492        &mut self,
493        id: T,
494        acceleration: Vector2D<f64>,
495    ) {
496        if let Some(object) = self.get_object_with_selection_mut(&id.into()) {
497            object.set_acceleration(acceleration);
498        }
499    }
500
501    /// Sets the observer's velocity in laboratory coordinates.
502    ///
503    /// The velocity is expressed in units where the speed of light is `1`.
504    /// Invalid velocities are ignored; use [`Self::set_velocity`] when the
505    /// error needs to be handled explicitly.
506    ///
507    /// # Example
508    ///
509    /// ```
510    /// use minkowski_space::{MWorld, Vector2D};
511    ///
512    /// let mut world = MWorld::new();
513    /// world.set_observer_velocity(Vector2D::new(0.6, 0.0));
514    /// assert_eq!(world.observer_object().velocity, Vector2D::new(0.6, 0.0));
515    /// ```
516    pub fn set_observer_velocity(&mut self, velocity: Vector2D<f64>) {
517        self.set_velocity(0, velocity).ok();
518    }
519    /// Returns the observer's proper time since the beginning of the simulation.
520    ///
521    /// Proper time is measured along the observer's worldline.
522    pub fn observer_tau(&self) -> f64 {
523        self.observer_object.get_tau()
524    }
525
526    /// Returns the current time in the laboratory frame.
527    pub fn lab_time(&self) -> f64 {
528        self.observer_object.position().time
529    }
530
531    /// Returns the observer's current position in laboratory coordinates.
532    pub fn observer_position(&self) -> MVector<f64> {
533        *self.observer_object.position()
534    }
535
536    /// Advances the simulation by an amount of the observer's proper time.
537    ///
538    /// The observer is advanced first. Registered objects are then advanced to
539    /// the resulting laboratory time. The returned notifications contain event
540    /// detections and collisions found during this step.
541    ///
542    /// # Arguments
543    ///
544    /// * `delta` - The observer's proper-time increment. A negative value does
545    ///   not advance the simulation.
546    ///
547    /// # Example
548    ///
549    /// ```
550    /// use minkowski_space::MWorld;
551    ///
552    /// let mut world = MWorld::new();
553    /// let callbacks = world.advance_by_proper_time(1.0);
554    ///
555    /// assert!(!callbacks.iter().any(|_| false));
556    /// assert!(world.observer_tau() >= 1.0);
557    /// ```
558    pub fn advance_by_proper_time(&mut self, delta: f64) -> Vec<ProcessTimeCallback> {
559        let observer_events_to_check = self.get_observer_events_to_check();
560        let observer_detections = self
561            .observer_object
562            .process_as_observer_object_tau(delta, observer_events_to_check);
563
564        let target_time = self.lab_time();
565
566        let receiver_data = Arc::new(ReceiverData {
567            m_pos: *self.observer_object.position(),
568            velocity: *self.observer_object.get_velocity(),
569        });
570
571        let events_to_check: HashMap<usize, HashMap<usize, MVector<f64>>> =
572            self.get_events_to_check(target_time);
573
574        let detected_events: Vec<(usize, usize, MVector<f64>)> =
575            self.advance_objects_parallel(delta, target_time, receiver_data, events_to_check);
576
577        self.hash_grid
578            .build_grid(&self.observer_object, &self.registered_objects);
579
580        let mut callbacks = self.get_event_callbacks(observer_detections, detected_events);
581        let collisions = self.detect_collisions();
582        callbacks.extend(collisions);
583
584        callbacks
585    }
586}
587
588//Crate private
589impl MWorld {
590    pub(crate) fn get_registered_objects(&self) -> &HashMap<usize, (MObject, ObjectTracker)> {
591        &self.registered_objects
592    }
593
594    pub(crate) fn get_object_with_selection(
595        &self,
596        selection: &ObjectSelection,
597    ) -> Option<&MObject> {
598        match selection {
599            ObjectSelection::Object(id) => Some(&self.registered_objects.get(id)?.0),
600            ObjectSelection::Observer => Some(&self.observer_object),
601        }
602    }
603
604    pub(crate) fn get_object_with_selection_mut(
605        &mut self,
606        selection: &ObjectSelection,
607    ) -> Option<&mut MObject> {
608        match selection {
609            ObjectSelection::Object(id) => Some(&mut self.registered_objects.get_mut(id)?.0),
610            ObjectSelection::Observer => Some(&mut self.observer_object),
611        }
612    }
613
614    pub(crate) fn get_hash_grid(&self) -> &HashGrid {
615        &self.hash_grid
616    }
617
618    pub(crate) fn configured_pairs(&self) -> &BTreeSet<CollisionGroupPair> {
619        &self.config.collision_pairs
620    }
621}
622
623//Private
624impl MWorld {
625    fn detect_collisions(&mut self) -> Vec<ProcessTimeCallback> {
626        let collisions = CollisionCalculator { world: self }.detect_collisions();
627        let now = self.lab_time();
628
629        for collision in collisions {
630            let pair = CollisionPair::new(collision.object_a, collision.object_b);
631            let was_active = self.active_collision_pairs.contains_key(&pair);
632            let collision_time = collision.position.time;
633            self.active_collision_pairs
634                .insert(pair, collision_time + EPSILON);
635
636            if !was_active && collision_time > now - EPSILON {
637                self.pending_collisions.push(PendingCollision(collision));
638            }
639        }
640        self.active_collision_pairs
641            .retain(|_, keep_until| *keep_until > now);
642
643        let mut callbacks = Vec::new();
644        while self
645            .pending_collisions
646            .peek()
647            .is_some_and(|pending| pending.0.position.time <= now)
648        {
649            let pending = self
650                .pending_collisions
651                .pop()
652                .expect("pending collision disappeared after peek");
653            callbacks.push(ProcessTimeCallback::Collision(pending.0));
654        }
655
656        callbacks
657    }
658
659    fn insert_event_possible_to_detect_for_new_object(
660        &mut self,
661        id: usize,
662        m_object: &mut MObject,
663    ) {
664        if matches!(m_object.collision_group(), CollisionGroup::Empty) {
665            return;
666        }
667        self.event_possible_to_detect.insert(
668            id,
669            self.events
670                .iter()
671                .filter(|e| {
672                    e.1.collision_group().collision_group_matches(
673                        m_object.collision_group(),
674                        &self.config.collision_pairs,
675                    )
676                })
677                .filter(|e| (*m_object.position() - *e.1.position()).is_space_like())
678                .map(|e| *e.0)
679                .collect(),
680        );
681    }
682    fn advance_objects_parallel(
683        &mut self,
684        delta: f64,
685        target_time: f64,
686        receiver_data: Arc<ReceiverData>,
687        events_to_check: HashMap<usize, HashMap<usize, MVector<f64>>>,
688    ) -> Vec<(usize, usize, MVector<f64>)> {
689        self.registered_objects
690            .par_iter_mut()
691            .flat_map_iter(|(id, (object, tracker))| {
692                let candidates = events_to_check.get(id).cloned().unwrap_or_default();
693                let (photons, detected) = object.process_time(target_time, candidates);
694                tracker.track_photons(photons);
695                tracker.recalculate_properties(object, receiver_data.as_ref(), delta);
696                detected
697                    .into_iter()
698                    .map(move |(event_id, detection_position)| (*id, event_id, detection_position))
699            })
700            .collect()
701    }
702
703    fn get_events_to_check(
704        &mut self,
705        target_time: f64,
706    ) -> HashMap<usize, HashMap<usize, MVector<f64>>> {
707        self.registered_objects
708            .keys()
709            .map(|id| (*id, self.get_events_per_object_to_check(id, target_time)))
710            .collect()
711    }
712
713    fn get_event_callbacks(
714        &mut self,
715        observer_detections: Vec<(usize, MVector<f64>)>,
716        detected_events: Vec<(usize, usize, MVector<f64>)>,
717    ) -> Vec<ProcessTimeCallback> {
718        let mut res = Vec::new();
719        for (event_id, event_detection_position) in observer_detections {
720            self.remove_object_event_possible_to_detect(0, event_id);
721            if let Some(callback) =
722                self.handle_observer_event_detection(event_id, event_detection_position)
723            {
724                res.push(callback);
725            }
726        }
727        for (object_id, event_id, event_detection_position) in detected_events {
728            self.remove_object_event_possible_to_detect(object_id, event_id);
729            if let Some(callback) =
730                self.handle_event_detection(object_id, event_id, event_detection_position)
731            {
732                res.push(callback);
733            }
734        }
735        res
736    }
737    fn create_event_at_impl(
738        &mut self,
739        event: MVector<f64>,
740        collision_group: CollisionGroup,
741    ) -> usize {
742        let id = self.counter;
743        self.counter += 1;
744        let m_event = MEvent::new(event, collision_group);
745        if matches!(m_event.collision_group(), CollisionGroup::Empty) {
746            self.events.insert(id, m_event);
747            return id;
748        }
749        let event_ids_to_insert: Vec<_> = self
750            .event_possible_to_detect
751            .iter()
752            .map(|e| *e.0)
753            .filter(|object_id| {
754                self.get_object_with_selection(&object_id.into())
755                    .is_some_and(|object| {
756                        object.collision_group().collision_group_matches(
757                            m_event.collision_group(),
758                            &self.config.collision_pairs,
759                        )
760                    })
761            })
762            .collect();
763
764        event_ids_to_insert.into_iter().for_each(|object_id| {
765            self.event_possible_to_detect
766                .entry(object_id)
767                .and_modify(|s| {
768                    s.insert(id);
769                });
770        });
771        self.events.insert(id, m_event);
772        id
773    }
774    fn get_observer_events_to_check(&self) -> HashMap<usize, MVector<f64>> {
775        self.event_possible_to_detect
776            .get(&0)
777            .iter()
778            .flat_map(|e| e.iter())
779            .filter_map(|id| self.events.get(id).map(|event| (*id, *event.position())))
780            .collect()
781    }
782
783    fn handle_observer_event_detection(
784        &mut self,
785        event_id: usize,
786        event_detection_position: MVector<f64>,
787    ) -> Option<ProcessTimeCallback> {
788        if !self.events.contains_key(&event_id) {
789            return None;
790        }
791        let detection = EventDetection {
792            event_id,
793            detection_object: DetectionObject::Observer,
794            event_detection_position,
795        };
796        Some(ProcessTimeCallback::Event(detection))
797    }
798
799    fn remove_object_event_possible_to_detect(&mut self, object_id: usize, event_id: usize) {
800        if let Some(possible_events) = self.event_possible_to_detect.get_mut(&object_id) {
801            possible_events.remove(&event_id);
802        }
803    }
804
805    fn handle_event_detection(
806        &mut self,
807        object_id: usize,
808        event_id: usize,
809        event_detection_position: MVector<f64>,
810    ) -> Option<ProcessTimeCallback> {
811        if !self.events.contains_key(&event_id) {
812            return None;
813        }
814        let detection = EventDetection {
815            event_id,
816            detection_object: DetectionObject::MObject(object_id),
817            event_detection_position,
818        };
819        Some(ProcessTimeCallback::Event(detection))
820    }
821
822    fn get_events_per_object_to_check(
823        &self,
824        object_id: &usize,
825        target_time: f64,
826    ) -> HashMap<usize, MVector<f64>> {
827        if let (Some((object, _)), Some(events_possible_to_detect)) = (
828            self.registered_objects.get(object_id),
829            self.event_possible_to_detect.get(object_id),
830        ) {
831            return events_possible_to_detect
832                .iter()
833                .filter_map(|e| self.events.get(e).map(|v| (e, v)))
834                .filter(|e| {
835                    let mut event_to_object = *object.position() - *e.1.position();
836                    let dt = target_time - object.position().time;
837                    event_to_object.time += 2.0 * dt;
838                    event_to_object.is_time_or_light_like()
839                })
840                .map(|e| (*e.0, *e.1.position()))
841                .collect();
842        }
843        Default::default()
844    }
845}