bevy_cobweb 0.13.0

Reactivity primitives for Bevy
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
//local shortcuts
use crate::prelude::*;

//third-party shortcuts
use bevy::prelude::*;
use bevy::utils::{HashMap, HashSet};
use crossbeam::channel::{Receiver, Sender};

//standard shortcuts
use core::any::TypeId;
use std::vec::Vec;

//-------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------

struct ComponentReactors
{
    insertion_callbacks : Vec<ReactorHandle>,
    mutation_callbacks  : Vec<ReactorHandle>,
    removal_callbacks   : Vec<ReactorHandle>,
}

impl ComponentReactors
{
    fn is_empty(&self) -> bool
    {
        self.insertion_callbacks.is_empty() &&
        self.mutation_callbacks.is_empty()  &&
        self.removal_callbacks.is_empty()
    }
}

impl Default for ComponentReactors
{
    fn default() -> Self
    {
        Self{
            insertion_callbacks : Vec::new(),
            mutation_callbacks  : Vec::new(),
            removal_callbacks   : Vec::new(),
        }
    }
}

//-------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------

/// Collect component removals.
///
/// Note: `RemovedComponents` acts like an event reader, so multiple invocations of this system within one tick will
/// not see duplicate removals.
fn collect_component_removals<C: ReactComponent>(
    In(mut buffer) : In<Vec<Entity>>,
    mut removed    : RemovedComponents<React<C>>,
) -> Vec<Entity>
{
    buffer.clear();
    removed.read().for_each(|entity| buffer.push(entity));
    buffer
}

//-------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------

struct RemovalChecker
{
    component_id : TypeId,
    checker      : SysCall<(), Vec<Entity>, Vec<Entity>>
}

impl RemovalChecker
{
    fn new<C: ReactComponent>() -> Self
    {
        Self{
            component_id : TypeId::of::<C>(),
            checker      : SysCall::new(|world, buffer| syscall(world, buffer, collect_component_removals::<C>)),
        }
    }
}

//-------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------

/// Schedules reactions to an entity mutation.
fn schedule_entity_reaction_impl(
    buffer          : &mut Vec<ReactionCommand>,
    reaction_source : Entity,
    reaction_type   : EntityReactionType,
    entity_reactors : &EntityReactors
){
    if let EntityReactionType::Event(id) = reaction_type
    { tracing::error!(?id, "tried queuing entity event as entity reaction"); return; }

    for reactor in entity_reactors.iter_rtype(reaction_type)
    {
        buffer.push(
                ReactionCommand::EntityReaction{
                    reaction_source,
                    reaction_type,
                    reactor,
                }
            );
    }
}

//-------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------

#[derive(Resource)]
pub(crate) struct ReactCache
{
    /// Cached buffer for collecting reaction commands.
    reaction_commands_buffer: Vec<ReactionCommand>,

    /// Per-component reactors
    component_reactors: HashMap<TypeId, ComponentReactors>,

    /// Components with removal reactors (cached to prevent duplicate insertion)
    tracked_removals: HashSet<TypeId>,
    /// Component removal checkers (as a vec for efficient iteration)
    removal_checkers: Vec<RemovalChecker>,
    /// Removal checker buffer (cached for reuse)
    removal_buffer: Option<Vec<Entity>>,

    // Entity despawn reactors
    despawn_reactors: HashMap<Entity, Vec<ReactorHandle>>,
    /// Despawn sender (cached for reuse with new despawn trackers)
    despawn_sender: Sender<Entity>,
    /// Despawn receiver
    despawn_receiver: Receiver<Entity>,

    /// Any entity event reactors
    any_entity_event_reactors: HashMap<TypeId, Vec<ReactorHandle>>,

    /// Resource mutation reactors
    resource_reactors: HashMap<TypeId, Vec<ReactorHandle>>,

    /// Broadcast event reactors
    broadcast_reactors: HashMap<TypeId, Vec<ReactorHandle>>,
}

impl ReactCache
{
    pub(crate) fn despawn_sender(&self) -> Sender<Entity>
    {
        self.despawn_sender.clone()
    }

    pub(crate) fn track_removals<C: ReactComponent>(&mut self)
    {
        // track removals of this component if untracked
        if self.tracked_removals.contains(&TypeId::of::<C>()) { return; };
        self.tracked_removals.insert(TypeId::of::<C>());
        self.removal_checkers.push(RemovalChecker::new::<C>());
    }

    pub(crate) fn register_insertion_reactor<C: ReactComponent>(&mut self, handle: ReactorHandle)
    {
        self.component_reactors
            .entry(TypeId::of::<C>())
            .or_default()
            .insertion_callbacks
            .push(handle);
    }

    pub(crate) fn register_mutation_reactor<C: ReactComponent>(&mut self, handle: ReactorHandle)
    {
        self.component_reactors
            .entry(TypeId::of::<C>())
            .or_default()
            .mutation_callbacks
            .push(handle);
    }

    pub(crate) fn register_removal_reactor<C: ReactComponent>(&mut self, handle: ReactorHandle)
    {
        self.component_reactors
            .entry(TypeId::of::<C>())
            .or_default()
            .removal_callbacks
            .push(handle);
    }

    pub(crate) fn register_any_entity_event_reactor<E: 'static>(&mut self, handle: ReactorHandle)
    {
        self.any_entity_event_reactors
            .entry(TypeId::of::<E>())
            .or_default()
            .push(handle);
    }

    pub(crate) fn register_resource_mutation_reactor<R: ReactResource>(&mut self, handle: ReactorHandle)
    {
        self.resource_reactors
            .entry(TypeId::of::<R>())
            .or_default()
            .push(handle);
    }

    pub(crate) fn register_broadcast_reactor<E: 'static>(&mut self, handle: ReactorHandle)
    {
        self.broadcast_reactors
            .entry(TypeId::of::<E>())
            .or_default()
            .push(handle);
    }

    pub(crate) fn register_despawn_reactor(&mut self, entity: Entity, handle: ReactorHandle)
    {
        self.despawn_reactors
            .entry(entity)
            .or_default()
            .push(handle);
    }

    /// Revokes a component insertion reactor.
    pub(crate) fn revoke_component_reactor(&mut self, rtype: EntityReactionType, reactor_id: SystemCommand)
    {
        // get cached callbacks
        let (comp_id, reactors) = match rtype
        {
            EntityReactionType::Insertion(comp_id) => (comp_id, self.component_reactors.get_mut(&comp_id)),
            EntityReactionType::Mutation(comp_id)  => (comp_id, self.component_reactors.get_mut(&comp_id)),
            EntityReactionType::Removal(comp_id)   => (comp_id, self.component_reactors.get_mut(&comp_id)),
            EntityReactionType::Event(_)           => unreachable!(),
        };
        let Some(reactors) = reactors else { return; };
        let callbacks = match rtype
        {
            EntityReactionType::Insertion(_) => &mut reactors.insertion_callbacks,
            EntityReactionType::Mutation(_)  => &mut reactors.mutation_callbacks,
            EntityReactionType::Removal(_)   => &mut reactors.removal_callbacks,
            EntityReactionType::Event(_)     => unreachable!(),
        };

        // revoke reactor
        for (idx, handle) in callbacks.iter().enumerate()
        {
            if handle.sys_command() != reactor_id { continue; }
            let _ = callbacks.remove(idx);

            break;
        }

        // cleanup empty hashmap entries
        if !reactors.is_empty() { return; }
        let _ = self.component_reactors.remove(&comp_id);
    }

    /// Revokes a resource mutation reactor.
    pub(crate) fn revoke_any_entity_event_reactor(&mut self, event_id: TypeId, reactor_id: SystemCommand)
    {
        // get callbacks
        let Some(callbacks) = self.any_entity_event_reactors.get_mut(&event_id) else { return; };

        // revoke reactor
        for (idx, handle) in callbacks.iter().enumerate()
        {
            if handle.sys_command() != reactor_id { continue; }
            let _ = callbacks.remove(idx);
            break;
        }

        // cleanup empty hashmap entries
        if callbacks.len() > 0 { return; }
        let _ = self.any_entity_event_reactors.remove(&event_id);
    }

    /// Revokes a resource mutation reactor.
    pub(crate) fn revoke_resource_mutation_reactor(&mut self, resource_id: TypeId, reactor_id: SystemCommand)
    {
        // get callbacks
        let Some(callbacks) = self.resource_reactors.get_mut(&resource_id) else { return; };

        // revoke reactor
        for (idx, handle) in callbacks.iter().enumerate()
        {
            if handle.sys_command() != reactor_id { continue; }
            let _ = callbacks.remove(idx);
            break;
        }

        // cleanup empty hashmap entries
        if callbacks.len() > 0 { return; }
        let _ = self.resource_reactors.remove(&resource_id);
    }

    /// Revokes an event reactor.
    pub(crate) fn revoke_broadcast_reactor(&mut self, event_id: TypeId, reactor_id: SystemCommand)
    {
        // get callbacks
        let Some(callbacks) = self.broadcast_reactors.get_mut(&event_id) else { return; };

        // revoke reactor
        for (idx, handle) in callbacks.iter().enumerate()
        {
            if handle.sys_command() != reactor_id { continue; }
            let _ = callbacks.remove(idx);
            break;
        }

        // cleanup empty hashmap entries
        if callbacks.len() > 0 { return; }
        let _ = self.broadcast_reactors.remove(&event_id);
    }

    /// Revokes a despawn reactor.
    pub(crate) fn revoke_despawn_reactor(&mut self, entity: Entity, reactor_id: SystemCommand)
    {
        // get callbacks
        let Some(callbacks) = self.despawn_reactors.get_mut(&entity) else { return; };

        // revoke reactor
        for (idx, handle) in callbacks.iter().enumerate()
        {
            if handle.sys_command() != reactor_id { continue; }
            let _ = callbacks.remove(idx);
            break;
        }

        // cleanup empty hashmap entries
        if callbacks.len() > 0 { return; }
        let _ = self.despawn_reactors.remove(&entity);
    }

    /// Queues reactions to a component insertion on an entity.
    pub(crate) fn schedule_insertion_reaction<C: ReactComponent>(
        In(entity)      : In<Entity>,
        mut cache       : ResMut<ReactCache>,
        mut commands    : Commands,
        entity_reactors : Query<&EntityReactors>,
    ){
        let rtype = EntityReactionType::Insertion(TypeId::of::<C>());

        // entity-specific reactors
        if let Ok(entity_reactors) = entity_reactors.get(entity)
        {
            let _ = schedule_entity_reaction_impl(&mut cache.reaction_commands_buffer, entity, rtype, &entity_reactors);
        }

        for command in cache.reaction_commands_buffer.drain(..) {
            commands.queue(command);
        }

        // entity-agnostic component reactors
        if let Some(handlers) = cache.component_reactors.get(&TypeId::of::<C>())
        {
            for handle in handlers.insertion_callbacks.iter()
            {
                commands.queue(
                        ReactionCommand::EntityReaction{
                            reaction_source : entity,
                            reaction_type   : rtype,
                            reactor         : handle.sys_command(),
                        }
                    );
            }
        }
    }

    /// Queues reactions to a component mutation on an entity.
    pub(crate) fn schedule_mutation_reaction<C: ReactComponent>(
        In(entity)      : In<Entity>,
        mut cache       : ResMut<ReactCache>,
        mut commands    : Commands,
        entity_reactors : Query<&EntityReactors>,
    ){
        let rtype = EntityReactionType::Mutation(TypeId::of::<C>());

        // entity-specific reactors
        if let Ok(entity_reactors) = entity_reactors.get(entity)
        {
            let _ = schedule_entity_reaction_impl(&mut cache.reaction_commands_buffer, entity, rtype, &entity_reactors);
        }

        for command in cache.reaction_commands_buffer.drain(..) {
            commands.queue(command);
        }

        // entity-agnostic component reactors
        if let Some(handlers) = cache.component_reactors.get(&TypeId::of::<C>())
        {
            for handle in handlers.mutation_callbacks.iter()
            {
                commands.queue(
                        ReactionCommand::EntityReaction{
                            reaction_source : entity,
                            reaction_type   : rtype,
                            reactor         : handle.sys_command(),
                        }
                    );
            }
        }
    }

    /// Schedules component removal reactors.
    pub(crate) fn schedule_removal_reactions(&mut self, world: &mut World)
    {
        // extract cached
        let mut buffer = self.removal_buffer.take().unwrap_or_else(|| Vec::default());
        let mut commands_buff = std::mem::take(&mut self.reaction_commands_buffer);

        // process all removal checkers
        for checker in &mut self.removal_checkers
        {
            // check for removals
            buffer = checker.checker.call(world, buffer);
            if buffer.len() == 0 { continue; }

            // queue removal callbacks
            let rtype = EntityReactionType::Removal(checker.component_id);
            for entity in buffer.iter()
            {
                // entity-specific component reactors
                if let Some(entity_reactors) = world.get_mut::<EntityReactors>(*entity)
                {
                    schedule_entity_reaction_impl(
                            &mut commands_buff,
                            *entity,
                            rtype,
                            &entity_reactors
                        );
                }

                // Need to do this in a separate step due to borrow checker on world mut access.
                for command in commands_buff.drain(..) {
                    world.commands().queue(command);
                }

                // entity-agnostic component reactors
                let Some(reactors) = self.component_reactors.get(&checker.component_id) else { continue; };
                for handle in reactors.removal_callbacks.iter()
                {
                    world.commands().queue(
                            ReactionCommand::EntityReaction{
                                reaction_source : *entity,
                                reaction_type   : rtype,
                                reactor         : handle.sys_command(),
                            }
                        );
                }
            }
        }

        // return cached
        self.removal_buffer = Some(buffer);
        self.reaction_commands_buffer = commands_buff;
    }

    /// Queues reactions to an entity event.
    pub(crate) fn schedule_entity_event_reaction<E: Send + Sync + 'static>(
        In((target, event)) : In<(Entity, E)>,
        mut commands        : Commands,
        cache               : Res<ReactCache>,
        entity_reactors     : Query<&EntityReactors>,
    ){
        // get reactors
        let entity_reactors = entity_reactors.get(target);
        let handlers = cache.any_entity_event_reactors.get(&TypeId::of::<E>());

        // if there are no handlers, just drop the event data
        let reaction_type = EntityReactionType::Event(TypeId::of::<E>());
        let num = entity_reactors.map(|e| e.count(reaction_type)).unwrap_or_default()
            + handlers.map(|h| h.len()).unwrap_or_default();
        if num == 0 { return; }

        // prep entity data
        let data_entity = commands.spawn((DataEntityCounter::new(num), EntityEventData::new(target, event))).id();

        // entity-specific reactors
        if let Ok(entity_reactors) = entity_reactors
        {
            for reactor in entity_reactors.iter_rtype(reaction_type)
            {
                commands.queue(
                        ReactionCommand::EntityEvent{
                            target,
                            data_entity,
                            reactor,
                        }
                    );
            }
        }

        // Entity-agnostic reactors
        if let Some(handlers) = cache.any_entity_event_reactors.get(&TypeId::of::<E>())
        {
            // queue reactors
            for handle in handlers.iter()
            {
                commands.queue(
                    ReactionCommand::EntityEvent{
                        target,
                        data_entity,
                        reactor: handle.sys_command(),
                    }
                );
            }
        }
    }

    /// Queues reactions to tracked despawns.
    pub(crate) fn schedule_despawn_reactions(&mut self, world: &mut World)
    {
        while let Ok(despawned_entity) = self.despawn_receiver.try_recv()
        {
            let Some(mut despawn_reactors) = self.despawn_reactors.remove(&despawned_entity) else { continue; };

            // queue despawn callbacks
            for handle in despawn_reactors.drain(..)
            {
                world.commands().queue(
                        ReactionCommand::Despawn{
                            reaction_source : despawned_entity,
                            reactor         : handle.sys_command(),
                            handle,
                        }
                    );
            }
        }
    }

    /// Queues reactions to a resource mutation.
    pub(crate) fn schedule_resource_mutation_reaction<R: ReactResource>(
        cache        : Res<ReactCache>,
        mut commands : Commands,
    ){
        let Some(handlers) = cache.resource_reactors.get(&TypeId::of::<R>()) else { return; };

        // queue reactors
        for handle in handlers.iter()
        {
            commands.queue(
                ReactionCommand::Resource{ reactor: handle.sys_command() }
            );
        }
    }

    /// Queues reactions to a broadcasted event.
    pub(crate) fn schedule_broadcast_reaction<E: Send + Sync + 'static>(
        In(event)    : In<E>,
        cache        : Res<ReactCache>,
        mut commands : Commands,
    ){
        let Some(handlers) = cache.broadcast_reactors.get(&TypeId::of::<E>()) else { return; };

        // if there are no handlers, just drop the event data
        let num = handlers.len();
        if num == 0 { return; }

        // prep event data
        let data_entity = commands.spawn((DataEntityCounter::new(num), BroadcastEventData::new(event))).id();

        // queue reactors
        for handle in handlers.iter()
        {
            commands.queue(
                ReactionCommand::BroadcastEvent{ data_entity, reactor: handle.sys_command() }
            );
        }
    }
}

impl Default for ReactCache
{
    fn default() -> Self
    {
        // prep despawn channel
        let (despawn_sender, despawn_receiver) = crossbeam::channel::unbounded();

        Self{
            reaction_commands_buffer : Vec::default(),
            component_reactors    : HashMap::default(),
            tracked_removals      : HashSet::default(),
            removal_checkers      : Vec::new(),
            removal_buffer        : None,
            despawn_reactors      : HashMap::new(),
            despawn_sender,
            despawn_receiver,
            any_entity_event_reactors : HashMap::new(),
            resource_reactors         : HashMap::new(),
            broadcast_reactors        : HashMap::new(),
        }
    }
}

//-------------------------------------------------------------------------------------------------------------------