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

//third-party shortcuts
use bevy::prelude::*;
use crossbeam::channel::Sender;

//standard shortcuts
use core::any::TypeId;
use std::marker::PhantomData;

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

fn track_removals<C: ReactComponent>(mut cache: ResMut<ReactCache>)
{
    cache.track_removals::<C>();
}

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

/// Tag for tracking despawns of entities with despawn reactors.
#[derive(Component)]
struct DespawnTracker
{
    parent   : Entity,
    notifier : Sender<Entity>,
}

impl Drop for DespawnTracker
{
    fn drop(&mut self)
    {
        let _ = self.notifier.send(self.parent);
    }
}

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

fn register_insertion_reactor<C: ReactComponent>(In(handle): In<ReactorHandle>, mut cache: ResMut<ReactCache>)
{
    cache.register_insertion_reactor::<C>(handle);
}

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

fn register_mutation_reactor<C: ReactComponent>(In(handle): In<ReactorHandle>, mut cache: ResMut<ReactCache>)
{
    cache.register_mutation_reactor::<C>(handle);
}

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

fn register_removal_reactor<C: ReactComponent>(In(handle): In<ReactorHandle>, mut cache: ResMut<ReactCache>)
{
    cache.track_removals::<C>();
    cache.register_removal_reactor::<C>(handle);
}

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

fn register_any_entity_event_reactor<E: 'static>(In(handle): In<ReactorHandle>, mut cache: ResMut<ReactCache>)
{
    cache.register_any_entity_event_reactor::<E>(handle);
}

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

fn register_resource_mutation_reactor<R: ReactResource>(In(handle): In<ReactorHandle>, mut cache: ResMut<ReactCache>)
{
    cache.register_resource_mutation_reactor::<R>(handle);
}

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

fn register_broadcast_reactor<E: Send + Sync + 'static>(In(handle): In<ReactorHandle>, mut cache: ResMut<ReactCache>)
{
    cache.register_broadcast_reactor::<E>(handle);
}

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

fn register_despawn_reactor(
    In((entity, handle)) : In<(Entity, ReactorHandle)>,
    world                : &mut World,
){
    world.resource_scope(
        move |world, mut cache: Mut<ReactCache>|
        {
            // Check if the entity is still alive.
            let Ok(mut entity_mut) = world.get_entity_mut(entity) else { return; };

            // Register the reactor.
            cache.register_despawn_reactor(entity, handle);

            // Leave if the entity already has a despawn tracker.
            // - We don't want to accidentally trigger `DespawnTracker::drop()` by replacing the existing component.
            if entity_mut.contains::<DespawnTracker>() { return; }

            // Insert a new despawn tracker.
            entity_mut.insert(DespawnTracker{ parent: entity, notifier: cache.despawn_sender() });
        }
    );
}

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

/// Adds a reactor to an entity.
///
/// The reactor will be invoked when the trigger targets the entity.
fn register_entity_reactor(
    In((
        rtype,
        entity,
        handle
    ))                  : In<(EntityReactionType, Entity, ReactorHandle)>,
    mut commands        : Commands,
    mut entity_reactors : Query<&mut EntityReactors>,
){
    // add callback to entity
    match entity_reactors.get_mut(entity)
    {
        Ok(mut entity_reactors) => entity_reactors.insert(rtype, handle),
        _ =>
        {
            let Some(mut entity_commands) = commands.get_entity(entity) else { return; };

            // make new reactor tracker for the entity
            let mut entity_reactors = EntityReactors::default();

            // add callback and insert to entity
            entity_reactors.insert(rtype, handle);
            entity_commands.insert(entity_reactors);
        }
    }
}

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

/// Reaction trigger for [`ReactComponent`] insertions on any entity.
/// - For reactors that take the entity the component was inserted to.
pub struct InsertionTrigger<C: ReactComponent>(PhantomData<C>);
impl<C: ReactComponent> Default for InsertionTrigger<C> { fn default() -> Self { Self(PhantomData::default()) } }
impl<C: ReactComponent> Clone for InsertionTrigger<C> { fn clone(&self) -> Self { *self } }
impl<C: ReactComponent> Copy for InsertionTrigger<C> {}

impl<C: ReactComponent> ReactionTrigger for InsertionTrigger<C>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::ComponentInsertion(TypeId::of::<C>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        commands.syscall(handle.clone(), register_insertion_reactor::<C>);
    }
}

/// Returns a [`InsertionTrigger`] reaction trigger.
pub fn insertion<C: ReactComponent>() -> InsertionTrigger<C> { InsertionTrigger::default() }

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

/// Reaction trigger for [`ReactComponent`] mutations on any entity.
/// - For reactors that take the entity the component was mutated on.
pub struct MutationTrigger<C: ReactComponent>(PhantomData<C>);
impl<C: ReactComponent> Default for MutationTrigger<C> { fn default() -> Self { Self(PhantomData::default()) } }
impl<C: ReactComponent> Clone for MutationTrigger<C> { fn clone(&self) -> Self { *self } }
impl<C: ReactComponent> Copy for MutationTrigger<C> {}

impl<C: ReactComponent> ReactionTrigger for MutationTrigger<C>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::ComponentMutation(TypeId::of::<C>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        commands.syscall(handle.clone(), register_mutation_reactor::<C>);
    }
}

/// Returns a [`MutationTrigger`] reaction trigger.
pub fn mutation<C: ReactComponent>() -> MutationTrigger<C> { MutationTrigger::default() }

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

/// Reaction trigger for [`ReactComponent`] removals from any entity.
/// - Reactions are not triggered if the entity was despawned.
pub struct RemovalTrigger<C: ReactComponent>(PhantomData<C>);
impl<C: ReactComponent> Default for RemovalTrigger<C> { fn default() -> Self { Self(PhantomData::default()) } }
impl<C: ReactComponent> Clone for RemovalTrigger<C> { fn clone(&self) -> Self { *self } }
impl<C: ReactComponent> Copy for RemovalTrigger<C> {}

impl<C: ReactComponent> ReactionTrigger for RemovalTrigger<C>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::ComponentRemoval(TypeId::of::<C>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        commands.syscall(handle.clone(), register_removal_reactor::<C>);
    }
}

/// Returns a [`RemovalTrigger`] reaction trigger.
pub fn removal<C: ReactComponent>() -> RemovalTrigger<C> { RemovalTrigger::default() }

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

/// Reaction trigger for [`ReactComponent`] insertions on a specific entity.
/// - Registration does nothing if the entity does not exist.
pub struct EntityInsertionTrigger<C: ReactComponent>(Entity, PhantomData<C>);
impl<C: ReactComponent> Clone for EntityInsertionTrigger<C> { fn clone(&self) -> Self { *self } }
impl<C: ReactComponent> Copy for EntityInsertionTrigger<C> {}

impl<C: ReactComponent> ReactionTrigger for EntityInsertionTrigger<C>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::EntityInsertion(self.0, TypeId::of::<C>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        let handle = handle.clone();
        commands.syscall((EntityReactionType::Insertion(TypeId::of::<C>()), self.0, handle), register_entity_reactor);
    }
}

impl<C: ReactComponent> EntityTrigger for EntityInsertionTrigger<C>
{
    fn new_trigger(entity: Entity) -> Self
    {
        entity_insertion(entity)
    }

    fn entity(&self) -> Entity
    {
        self.0
    }
}

/// Returns a [`EntityInsertionTrigger`] reaction trigger.
pub fn entity_insertion<C: ReactComponent>(entity: Entity) -> EntityInsertionTrigger<C>
{
    EntityInsertionTrigger(entity, PhantomData::default())
}

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

/// Reaction trigger for [`ReactComponent`] mutations on a specific entity.
/// - Registration does nothing if the entity does not exist.
pub struct EntityMutationTrigger<C: ReactComponent>(Entity, PhantomData<C>);
impl<C: ReactComponent> Clone for EntityMutationTrigger<C> { fn clone(&self) -> Self { *self } }
impl<C: ReactComponent> Copy for EntityMutationTrigger<C> {}

impl<C: ReactComponent> ReactionTrigger for EntityMutationTrigger<C>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::EntityMutation(self.0, TypeId::of::<C>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        let handle = handle.clone();
        commands.syscall((EntityReactionType::Mutation(TypeId::of::<C>()), self.0, handle), register_entity_reactor);
    }
}

impl<C: ReactComponent> EntityTrigger for EntityMutationTrigger<C>
{
    fn new_trigger(entity: Entity) -> Self
    {
        entity_mutation(entity)
    }

    fn entity(&self) -> Entity
    {
        self.0
    }
}

/// Returns a [`EntityMutationTrigger`] reaction trigger.
pub fn entity_mutation<C: ReactComponent>(entity: Entity) -> EntityMutationTrigger<C>
{
    EntityMutationTrigger(entity, PhantomData::default())
}

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

/// Reaction trigger for [`ReactComponent`] removals from a specific entity.
/// - Registration does nothing if the entity does not exist.
pub struct EntityRemovalTrigger<C: ReactComponent>(Entity, PhantomData<C>);
impl<C: ReactComponent> Clone for EntityRemovalTrigger<C> { fn clone(&self) -> Self { *self } }
impl<C: ReactComponent> Copy for EntityRemovalTrigger<C> {}

impl<C: ReactComponent> ReactionTrigger for EntityRemovalTrigger<C>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::EntityRemoval(self.0, TypeId::of::<C>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        let handle = handle.clone();
        commands.syscall((), track_removals::<C>);
        commands.syscall((EntityReactionType::Removal(TypeId::of::<C>()), self.0, handle), register_entity_reactor);
    }
}

impl<C: ReactComponent> EntityTrigger for EntityRemovalTrigger<C>
{
    fn new_trigger(entity: Entity) -> Self
    {
        entity_removal(entity)
    }

    fn entity(&self) -> Entity
    {
        self.0
    }
}

/// Returns a [`EntityRemovalTrigger`] reaction trigger.
pub fn entity_removal<C: ReactComponent>(entity: Entity) -> EntityRemovalTrigger<C>
{
    EntityRemovalTrigger(entity, PhantomData::default())
}

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

/// Reaction trigger for entity events.
/// - Reactions only occur for events sent via [`ReactCommands::<E>::entity_event()`].
pub struct EntityEventTrigger<E: Send + Sync + 'static>(Entity, PhantomData<E>);
impl<E: Send + Sync + 'static> Clone for EntityEventTrigger<E> { fn clone(&self) -> Self { *self } }
impl<E: Send + Sync + 'static> Copy for EntityEventTrigger<E> {}

impl<E: Send + Sync + 'static> ReactionTrigger for EntityEventTrigger<E>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::EntityEvent(self.0, TypeId::of::<E>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        let handle = handle.clone();
        commands.syscall((EntityReactionType::Event(TypeId::of::<E>()), self.0, handle), register_entity_reactor);
    }
}

impl<E: Send + Sync + 'static> EntityTrigger for EntityEventTrigger<E>
{
    fn new_trigger(entity: Entity) -> Self
    {
        entity_event(entity)
    }

    fn entity(&self) -> Entity
    {
        self.0
    }
}

/// Returns an [`EntityEventTrigger`] reaction trigger.
pub fn entity_event<E: Send + Sync + 'static>(target: Entity) -> EntityEventTrigger<E>
{
    EntityEventTrigger(target, PhantomData::default())
}

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

/// Reaction trigger for any entity event of a given type.
/// - Reactions only occur for events sent via [`ReactCommands::<E>::entity_event()`].
pub struct AnyEntityEventTrigger<E: Send + Sync + 'static>(PhantomData<E>);
impl<E: Send + Sync + 'static> Clone for AnyEntityEventTrigger<E> { fn clone(&self) -> Self { *self } }
impl<E: Send + Sync + 'static> Copy for AnyEntityEventTrigger<E> {}

impl<E: Send + Sync + 'static> ReactionTrigger for AnyEntityEventTrigger<E>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::AnyEntityEvent(TypeId::of::<E>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        commands.syscall(handle.clone(), register_any_entity_event_reactor::<E>);
    }
}

/// Returns an [`AnyEntityEventTrigger`] reaction trigger.
pub fn any_entity_event<E: Send + Sync + 'static>() -> AnyEntityEventTrigger<E>
{
    AnyEntityEventTrigger(PhantomData::default())
}

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

/// Reaction trigger for [`ReactResource`] mutations.
pub struct ResourceMutationTrigger<R: ReactResource>(PhantomData<R>);
impl<R: ReactResource> Default for ResourceMutationTrigger<R> { fn default() -> Self { Self(PhantomData::default()) } }
impl<R: ReactResource> Clone for ResourceMutationTrigger<R> { fn clone(&self) -> Self { *self } }
impl<R: ReactResource> Copy for ResourceMutationTrigger<R> {}

impl<R: ReactResource> ReactionTrigger for ResourceMutationTrigger<R>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::ResourceMutation(TypeId::of::<R>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        commands.syscall(handle.clone(), register_resource_mutation_reactor::<R>);
    }
}

/// Returns a [`ResourceMutationTrigger`] reaction trigger.
pub fn resource_mutation<R: ReactResource>() -> ResourceMutationTrigger<R> { ResourceMutationTrigger::default() }

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

/// Reaction trigger for broadcast events.
/// - Reactions only occur for events sent via [`ReactCommands::<E>::broadcast()`].
pub struct BroadcastTrigger<E: Send + Sync + 'static>(PhantomData<E>);
impl<E: Send + Sync + 'static> Default for BroadcastTrigger<E> { fn default() -> Self { Self(PhantomData::default()) } }
impl<E: Send + Sync + 'static> Clone for BroadcastTrigger<E> { fn clone(&self) -> Self { *self } }
impl<E: Send + Sync + 'static> Copy for BroadcastTrigger<E> {}

impl<E: Send + Sync + 'static> ReactionTrigger for BroadcastTrigger<E>
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::Broadcast(TypeId::of::<E>())
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        commands.syscall(handle.clone(), register_broadcast_reactor::<E>);
    }
}

/// Returns a [`BroadcastTrigger`] reaction trigger.
pub fn broadcast<E: Send + Sync + 'static>() -> BroadcastTrigger<E> { BroadcastTrigger::default() }

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

/// Reaction trigger for despawns.
/// - Registration does nothing if the entity does not exist.
///
/// Note that `DespawnTrigger` does not implement [`EntityTrigger`] because [`EntityWorldReactor`] only runs for entities
/// that exist.
#[derive(Copy, Clone)]
pub struct DespawnTrigger(Entity);

impl ReactionTrigger for DespawnTrigger
{
    fn reactor_type(&self) -> ReactorType
    {
        ReactorType::Despawn(self.0)
    }

    fn register(&self, commands: &mut Commands, handle: &ReactorHandle)
    {
        // check if the entity exists
        let Some(_) = commands.get_entity(self.0) else { return; };

        // add despawn tracker
        commands.syscall((self.0, handle.clone()), register_despawn_reactor);
    }
}

/// Returns a [`DespawnTrigger`] reaction trigger.
pub fn despawn(entity: Entity) -> DespawnTrigger { DespawnTrigger(entity) }

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