bevy_immediate_core 0.5.1

A simple, fast, and modular immediate mode UI library 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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
use std::{marker::PhantomData, sync::Arc};

use crate::{CapSet, ImmCapAccessRequests, ImmCapAccessRequestsResource};
use bevy_ecs::{
    bundle::Bundle,
    change_detection::DetectChanges,
    component::{Component, Mutable},
    entity::Entity,
    event::EntityEvent,
    hierarchy::ChildOf,
    query::{QueryEntityError, Without},
    resource::Resource,
    system::{Commands, EntityCommands, IntoObserverSystem, Query},
    world::{FilteredEntityRef, Mut, error::ResourceFetchError},
};

/// Plugin for immediate mode functionality in bevy
///
/// Can be initialized multiple times without problems
pub struct BevyImmediatePlugin<Caps = ()>(PhantomData<Caps>);

impl<Caps> BevyImmediatePlugin<Caps> {
    /// Construct plugin
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<Caps> Default for BevyImmediatePlugin<Caps> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Caps> bevy_app::Plugin for BevyImmediatePlugin<Caps>
where
    Caps: CapSet,
{
    fn build(&self, app: &mut bevy_app::App) {
        if app.is_plugin_added::<Self>() {
            return;
        }

        entity_mapping::init::<Caps>(app);
        upkeep::init::<Caps>(app);
        cached_hash::init::<Caps>(app);

        let mut capabilities = ImmCapAccessRequests::<Caps>::default();
        Caps::initialize(app, &mut capabilities);
        app.insert_resource(ImmCapAccessRequestsResource::new(capabilities));

        #[cfg(feature = "hotpatching")]
        hotpatching::init(app);
    }

    fn is_unique(&self) -> bool {
        // Users do not need to track
        // if this plugin has been initialized in only one place
        false
    }
}

/// Adds support for bevy inbuilt hotpatching mechanism
#[cfg(feature = "hotpatching")]
pub mod hotpatching;

mod system_set;
pub use system_set::ImmediateSystemSet;

mod ctx;
pub use ctx::ImmCtx;

mod id;
use crate::utils::ImmTypeMap;
pub use id::{ImmId, ImmIdBuilder, imm_id};

mod cached_hash;
mod entity_mapping;
mod upkeep;

/// Helper type to more easily write queries
pub type ImmQuery<'w, 's, Caps, D, F = ()> = Query<'w, 's, D, (Without<ImmMarker<Caps>>, F)>;

/// Immediate mode in a state where child components can be added
///
/// We can not be sure that:
/// * there is parent entity,
/// * if it even exists or is currently being spawned,
/// * if it even is managed by current immediate mode logic
///
/// Use [`Self::reinterpret_as_entity`] if you are sure about
/// what kind of data can be accessed about parent entity.
pub struct Imm<'w, 's, Caps: CapSet> {
    ctx: ImmCtx<'w, 's, Caps>,
    current: Current,
}

#[derive(Clone, Copy)]
struct Current {
    id: ImmId,
    entity: Option<CurrentEntity>,
    id_pref: ImmId,
    auto_id_idx: usize,
}

#[derive(Clone, Copy)]
struct CurrentEntity {
    entity: Entity,
    will_be_spawned: bool,
}

impl<'w, 's, Caps: CapSet> Imm<'w, 's, Caps> {
    /// Build new entity with auto generated id.
    ///
    /// Use [`Self::ch_id`] if building entities that may not always exist when parent entity exists.
    ///
    /// Read more [`ImmId`], [`ImmIdBuilder`].
    pub fn ch(&mut self) -> ImmEntity<'_, 'w, 's, Caps> {
        self.ch_with_manual_id(ImmIdBuilder::Auto)
    }

    /// Build new entity with manually provided id that will be combined with parent entity id to
    /// make truly unique id.
    ///
    /// Ids must be unique between sibling entities.
    ///
    /// Read more [`ImmId`], [`ImmIdBuilder`].
    pub fn ch_id<T: std::hash::Hash>(&mut self, id: T) -> ImmEntity<'_, 'w, 's, Caps> {
        self.ch_with_manual_id(ImmIdBuilder::Hierarchy(ImmId::new(id)))
    }

    /// Build new entity with provided id.
    ///
    /// Read more [`ImmId`], [`ImmIdBuilder`].
    pub fn ch_with_manual_id(&mut self, id: ImmIdBuilder) -> ImmEntity<'_, 'w, 's, Caps> {
        let id = id.resolve(self);

        let mut will_be_spawned = false;

        let entity = 'entity_retrieval: {
            'entity_full_reuse: {
                let Some(entity) = self.ctx.mapping.id_to_entity.get(&id).copied() else {
                    break 'entity_full_reuse;
                };

                let Ok(mut qentity) = self.ctx.entity_query.get_mut(entity) else {
                    break 'entity_full_reuse;
                };

                // Update iteration for entity upkeep tracking
                qentity.tracker.iteration = self.ctx.state.iteration;

                if qentity.child_of.map(|ch| ch.parent()) != self.current.entity.map(|e| e.entity) {
                    // Parent changed
                    let mut entity_commands = self.ctx.commands.entity(entity);
                    match self.current.entity {
                        Some(entity) => {
                            entity_commands.insert(ChildOf(entity.entity));
                        }
                        None => {
                            entity_commands.remove::<ChildOf>();
                        }
                    }
                }

                break 'entity_retrieval entity;
            }

            // Spawn entity by default if valid entity not found
            let mut commands = self.ctx.commands.spawn((
                // Add marker component that users can use in QueryFilter Without statements
                ImmMarker::<Caps> {
                    id,
                    iteration: self.ctx.state.iteration,
                    _ph: PhantomData,
                },
            ));

            if let Some(entity) = self.current.entity {
                commands.insert(ChildOf(entity.entity));
            }
            will_be_spawned = true;
            commands.id()
        };

        // TODO: Avoid clone
        let access_requests: Arc<_> = self.ctx.access_requests.capabilities.clone();

        let mut entity = ImmEntity {
            imm: self,
            e: EntityParams {
                id,
                entity,
                will_be_spawned,
            },
            tmp_store: ImmTypeMap::new(),
        };

        for on_children in access_requests.on_children.iter() {
            (on_children)(&mut entity);
        }

        entity
    }

    /// Add additional id to final id generation
    ///
    /// Useful in situations where multiple elements require unique id.
    pub fn with_add_id_pref(
        &mut self,
        id: impl std::hash::Hash,
    ) -> ImmScopeGuard<'_, 'w, 's, Caps> {
        ImmScopeGuard::add_id_pref(self, id)
    }

    /// Add additional id to final id generation
    ///
    /// Useful in situations where multiple elements require unique id.
    #[deprecated = "Use with_add_id_pref"]
    pub fn with_local_auto_id_guard(
        &mut self,
        id: impl std::hash::Hash,
    ) -> ImmScopeGuard<'_, 'w, 's, Caps> {
        ImmScopeGuard::add_id_pref(self, id)
    }

    /// Useful to spawn new unrooted entity trees
    ///
    /// In context of UI, useful for tooltips, popups.
    pub fn unrooted<T: std::hash::Hash>(&mut self, id: T, f: impl FnOnce(&mut Imm<'w, 's, Caps>)) {
        let id = ImmIdBuilder::Hierarchy(ImmId::new(id)).resolve(self);

        // Create new unrooted context
        let mut imm = ImmScopeGuard::new_scope(
            self,
            Current {
                id,
                entity: None,
                auto_id_idx: 0,
                id_pref: ImmId::new(49382395483011234u64),
            },
        );
        f(&mut imm);
    }

    /// Entity that is currently being managed
    ///
    /// If building root of entity tree, this value may be [`None`]
    #[inline]
    pub fn current_entity(&self) -> Option<Entity> {
        self.current.entity.map(|e| e.entity)
    }

    /// Immediate mode unique id
    #[inline]
    pub fn current_imm_id(&self) -> ImmId {
        self.current.id
    }

    /// Retrieve access to commands
    #[inline]
    pub fn commands_mut(&mut self) -> &mut Commands<'w, 's> {
        &mut self.ctx.commands
    }

    /// Access underlaying context
    ///
    /// Useful for implementing [crate::ImmCapability]
    #[inline]
    pub fn ctx(&self) -> &ImmCtx<'w, 's, Caps> {
        &self.ctx
    }

    /// Access underlaying context
    ///
    /// Useful for implementing [crate::ImmCapability]
    #[inline]
    pub fn ctx_mut(&mut self) -> &mut ImmCtx<'w, 's, Caps> {
        &mut self.ctx
    }

    /// Retrieve [`ImmCtx`] from which immediate mode entity tree was built
    pub fn deconstruct(self) -> ImmCtx<'w, 's, Caps> {
        self.ctx
    }

    fn add_child_entities_scope(
        &mut self,
        EntityParams {
            id,
            entity,
            will_be_spawned,
        }: EntityParams,
    ) -> ImmScopeGuard<'_, 'w, 's, Caps> {
        ImmScopeGuard::new_scope(
            self,
            Current {
                id,
                entity: Some(CurrentEntity {
                    entity,
                    will_be_spawned,
                }),
                auto_id_idx: 0,
                id_pref: ImmId::new(49382395483011234u64),
            },
        )
    }

    /// Manage entity with provided [`ImmId`] and [`Entity`] attributes with provided closure
    fn add_child_entities<R>(
        &mut self,
        params: EntityParams,
        f: impl FnOnce(&mut Imm<'w, 's, Caps>) -> R,
    ) -> R {
        self.add_child_entities_dyn(params, Box::new(f))
    }

    /// Manage entity with provided [`ImmId`] and [`Entity`] attributes with provided closure
    #[allow(clippy::type_complexity)]
    fn add_child_entities_dyn<R>(
        &mut self,
        params: EntityParams,
        f: Box<dyn FnOnce(&mut Imm<'w, 's, Caps>) -> R + '_>,
    ) -> R {
        let mut imm = self.add_child_entities_scope(params);
        f(&mut imm)
    }

    /// Manage current context as entity
    ///
    /// It returns `None` only in cases where Imm is not rooted to existing entity.
    ///
    /// Useful in rare cases where access to parent entity is needed.
    /// If parent entity is not managed by Immediate mode, may result in panic
    /// when capabilities try to access data from queries that query only immediate mode entities.
    /// Capabilities will have access to empty temporary store.
    pub fn reinterpret_as_entity(&mut self) -> Option<ImmEntity<'_, 'w, 's, Caps>> {
        if let Some(current_entity) = self.current.entity {
            let e = EntityParams {
                id: self.current.id,
                entity: current_entity.entity,
                will_be_spawned: current_entity.will_be_spawned,
            };
            Some(ImmEntity {
                imm: self,
                e,
                tmp_store: ImmTypeMap::new(),
            })
        } else {
            None
        }
    }

    /// Helper function to correctly detect changes that could have happened even in this system
    pub fn has_changed<T>(&self, value: &Mut<'_, T>) -> bool {
        self.change_detector().has_changed(value)
    }

    /// Helper object for state change detection
    pub fn change_detector(&self) -> ChangeDetector {
        ChangeDetector {
            last_run: self.ctx.system_change_tick.last_run(),
        }
    }
}

/// Entity during construction in immediate mode approach
///
/// Can be used to issue commands and check such conditions as `.clicked()`.
pub struct ImmEntity<'r, 'w, 's, Caps: CapSet> {
    imm: &'r mut Imm<'w, 's, Caps>,
    /// Entity managed by this instance
    e: EntityParams,
    tmp_store: ImmTypeMap,
}

#[derive(Clone, Copy)]
struct EntityParams {
    id: ImmId,
    entity: Entity,
    will_be_spawned: bool,
}

impl<'r, 'w, 's, Caps: CapSet> ImmEntity<'r, 'w, 's, Caps> {
    /// Build descendants of this entity
    ///
    /// If closure return value is needed, use `[Self::add_with_return]``
    #[allow(clippy::should_implement_trait)]
    pub fn add(self, f: impl FnOnce(&mut Imm<'w, 's, Caps>)) -> Self {
        self.imm.add_child_entities(self.e, f);
        self
    }

    /// Build descendants of this entity and retrieve return value of inner closure.
    pub fn add_with_return<R>(self, f: impl FnOnce(&mut Imm<'w, 's, Caps>) -> R) -> (Self, R) {
        let value = self.imm.add_child_entities(self.e, f);
        (self, value)
    }

    /// Build descendants of this entity using returned [`Imm`] scope
    ///
    /// This function works exactly like [`Self::add`], but without
    /// introducing additional nesting level
    pub fn add_scoped(&mut self) -> ImmScopeGuard<'_, 'w, 's, Caps> {
        self.imm.add_child_entities_scope(self.e)
    }

    /// Spawn new entity trees (unrooted)
    ///
    /// In UI useful for Tooltips, Popups, etc.
    pub fn unrooted<T: std::hash::Hash>(
        self,
        id: T,
        f: impl FnOnce(&mut Imm<'w, 's, Caps>),
    ) -> Self {
        self.add(|ui| {
            ui.unrooted(id, f);
        })
    }

    /// Retrieve system param ctx for immediate mode
    pub fn ctx(&self) -> &ImmCtx<'w, 's, Caps> {
        &self.imm.ctx
    }

    /// Retrieve system param ctx for immediate mode
    pub fn ctx_mut(&mut self) -> &mut ImmCtx<'w, 's, Caps> {
        &mut self.imm.ctx
    }

    /// Helper method to simplify entity retrieval
    pub fn cap_get_entity(
        &self,
    ) -> Result<FilteredEntityRef<'_, 's>, bevy_ecs::query::QueryEntityError> {
        self.ctx().cap_entities.get(self.entity())
    }

    /// Helper method to simplify entity retrieval
    pub fn cap_get_entity_mut(
        &mut self,
    ) -> Result<bevy_ecs::world::FilteredEntityMut<'_, 's>, bevy_ecs::query::QueryEntityError> {
        let entity = self.entity();
        self.ctx_mut().cap_entities.get_mut(entity)
    }

    /// Retrieve [`Entity`] value for this entity
    pub fn entity(&self) -> Entity {
        self.e.entity
    }

    /// Immediate mode unique id for this entity
    #[inline]
    pub fn imm_id(&self) -> ImmId {
        self.e.id
    }

    /// Gain access to [`Commands`]
    pub fn commands(&mut self) -> &mut Commands<'w, 's> {
        &mut self.imm.ctx.commands
    }

    /// Gain access to [`EntityCommands`] for this entity
    pub fn entity_commands(&mut self) -> EntityCommands<'_> {
        self.imm.ctx.commands.entity(self.e.entity)
    }

    /// Entity will be spawned when [`Commands`] will be processed.
    pub fn will_be_spawned(&self) -> bool {
        self.e.will_be_spawned
    }

    /// Issue [`EntityCommands`] at this moment
    pub fn at_this_moment_apply_commands<F>(mut self, f: F) -> Self
    where
        F: FnOnce(&mut EntityCommands<'_>),
    {
        let mut entity_commands = self.entity_commands();
        f(&mut entity_commands);
        self
    }

    /// Issue [`EntityCommands`] at this moment if condition is met
    pub fn at_this_moment_apply_commands_if<F>(self, f: F, condition: impl FnOnce() -> bool) -> Self
    where
        F: FnOnce(&mut EntityCommands<'_>),
    {
        if condition() {
            self.at_this_moment_apply_commands(f)
        } else {
            self
        }
    }

    /// Issue [`EntityCommands`]
    /// (issued only when entity is created).
    pub fn on_spawn_apply_commands<F>(self, f: F) -> Self
    where
        F: FnOnce(&mut EntityCommands<'_>),
    {
        if self.e.will_be_spawned {
            self.at_this_moment_apply_commands(f)
        } else {
            self
        }
    }

    /// Issue [`EntityCommands`] if condition is met.
    /// (issued only when entity is created).
    pub fn on_spawn_apply_commands_if<F>(self, f: F, condition: impl FnOnce() -> bool) -> Self
    where
        F: FnOnce(&mut EntityCommands<'_>),
    {
        if self.e.will_be_spawned {
            self.at_this_moment_apply_commands_if(f, condition)
        } else {
            self
        }
    }

    /// Insert [`Bundle`] similarly to [`EntityCommands::insert`].
    /// (inserted only when entity is created).
    pub fn on_spawn_insert<F, B>(self, f: F) -> Self
    where
        F: FnOnce() -> B,
        B: Bundle,
    {
        self.on_spawn_apply_commands(|commands| {
            commands.insert(f());
        })
    }

    /// Insert [`Bundle`] similarly to [`EntityCommands::insert_if`]
    /// (inserted only when entity is created).
    pub fn on_spawn_insert_if<F, B, Cond>(self, f: F, condition: impl FnOnce() -> bool) -> Self
    where
        F: FnOnce() -> B,
        B: Bundle,
    {
        self.on_spawn_apply_commands_if(
            |commands| {
                commands.insert(f());
            },
            condition,
        )
    }

    /// Insert [`Bundle`] similarly to [`EntityCommands::insert_if_new`].
    /// (inserted only when entity is created).
    pub fn on_spawn_insert_if_new<F, B>(self, f: F) -> Self
    where
        F: FnOnce() -> B,
        B: Bundle,
    {
        self.on_spawn_apply_commands(|commands| {
            commands.insert_if_new(f());
        })
    }

    /// Insert [`Bundle`] similarly to [`EntityCommands::insert_if_new_and`].
    /// (inserted only when entity is created).
    pub fn on_spawn_insert_if_new_and<F, B>(self, f: F, condition: impl FnOnce() -> bool) -> Self
    where
        F: FnOnce() -> B,
        B: Bundle,
    {
        self.on_spawn_apply_commands_if(
            |commands| {
                commands.insert_if_new(f());
            },
            condition,
        )
    }

    /// Observe with [`bevy_ecs::system::ObserverSystem`]
    /// (added only when entity is created).
    pub fn on_spawn_observe<E: EntityEvent, B: Bundle, M>(
        self,
        observer: impl IntoObserverSystem<E, B, M>,
    ) -> Self {
        self.on_spawn_apply_commands(|commands| {
            commands.observe(observer);
        })
    }

    /// If entity spawned or changed value is `true`, insert [`Bundle`] into entity
    pub fn on_change_insert<F, B>(mut self, changed: bool, f: F) -> Self
    where
        F: FnOnce() -> B,
        B: Bundle,
    {
        if self.e.will_be_spawned || changed {
            self.entity_commands().insert(f());
            self
        } else {
            self
        }
    }

    /// Check if current entity contains component in capability requirements
    ///
    /// Useful in implementing capabilities [`crate::ImmCapabiility`]
    pub fn cap_entity_contains<T: Component>(&self) -> bool {
        let Ok(entity) = self.cap_get_entity() else {
            return false;
        };

        entity.contains::<T>()
    }

    /// Retrieve component for entity that was requested by capabilities
    ///
    /// Useful in implementing capabilities [`crate::ImmCapabiility`]
    pub fn cap_get_component<T: Component>(&self) -> Result<Option<&T>, QueryEntityError> {
        let entity = self.cap_get_entity()?;
        Ok(entity.get::<T>())
    }

    /// Retrieve component for entity that was requested by capabilities
    ///
    /// Useful in implementing capabilities [`crate::ImmCapabiility`]
    pub fn cap_get_component_mut<'a, T: Component<Mutability = Mutable>>(
        &'a mut self,
    ) -> Result<Option<bevy_ecs::world::Mut<'a, T>>, QueryEntityError> {
        let entity = self.cap_get_entity_mut()?;
        Ok(entity.into_mut::<T>())
    }

    /// Retrieve resource from capabilities
    ///
    /// Useful in implementing capabilities [`crate::ImmCapabiility`]
    pub fn cap_get_resource<R: Resource>(
        &self,
    ) -> Result<bevy_ecs::world::Ref<'_, R>, ResourceFetchError> {
        self.ctx().cap_resources.get::<R>()
    }

    /// Retrieve mutable resource from capabilities
    ///
    /// Useful in implementing capabilities [`crate::ImmCapabiility`]
    pub fn cap_get_resource_mut<R: Resource>(
        &mut self,
    ) -> Result<bevy_ecs::world::Mut<'_, R>, ResourceFetchError> {
        self.ctx_mut().cap_resources.get_mut::<R>()
    }

    /// Helper function to correctly detect changes that could have happened even in this system
    pub fn changed_for<T>(&self, value: &Mut<'_, T>) -> bool {
        value.is_changed() || value.last_changed() == self.ctx().system_change_tick.last_run()
    }

    /// Helper function to correctly detect changes that could have happened even in this system
    pub fn has_changed<T>(&self, value: &Mut<'_, T>) -> bool {
        self.imm.has_changed(value)
    }

    /// Access data store for current entity.
    ///
    /// It exists only during entity construction
    pub fn cap_entity_tmp_store(&self) -> &ImmTypeMap {
        &self.tmp_store
    }

    /// Access data store for current entity.
    ///
    /// It exists only during entity construction
    pub fn cap_entity_tmp_store_mut(&mut self) -> &mut ImmTypeMap {
        &mut self.tmp_store
    }

    /// Get [`Entity`] for parent entity of this entity
    pub fn parent_entity(&self) -> Option<Entity> {
        self.imm.current_entity()
    }

    /// Function to implement change detection using stored hashed value
    ///
    /// Hash values are stored for each entity separately.
    ///
    /// This function returns true if hash for `key` was
    /// provided for the first time or if hash value changed.
    ///
    /// Hash is stored until entity is despawned
    pub fn hash_update(&mut self, key: ImmId, value: Option<ImmId>) -> bool {
        match value {
            Some(value) => self.hash_set(key, value),
            None => self.hash_remove(key).is_some(),
        }
    }

    /// Function to implement change detection using stored hashed value
    ///
    /// Hash values are stored for each entity separately.
    ///
    /// This function returns true if hash for `Marker` was
    /// provided for the first time or if hash value changed.
    ///
    /// Hash is stored until entity is despawned
    pub fn hash_update_typ<UniqueMarker: 'static>(&mut self, value: Option<ImmId>) -> bool {
        match value {
            Some(value) => self.hash_set_typ::<UniqueMarker>(value),
            None => self.hash_remove_typ::<UniqueMarker>().is_some(),
        }
    }

    /// Stores provided hash value for key. See [`Self::hash_update`]
    pub fn hash_set(&mut self, key: ImmId, value: ImmId) -> bool {
        let entity = self.entity();
        self.imm.ctx.cached_hash.set(entity, key, value)
    }

    /// Stores provided hash value for key. See [`Self::hash_update_typ`]
    pub fn hash_set_typ<UniqueMarker: 'static>(&mut self, value: ImmId) -> bool {
        let entity = self.entity();
        self.imm
            .ctx
            .cached_hash
            .set_typ::<UniqueMarker>(entity, value)
    }

    /// Function to retrieve currently stored hash value with given key for entity.
    /// See [`Self::hash_update`]
    pub fn hash_get(&self, key: ImmId) -> Option<ImmId> {
        let entity = self.entity();
        self.imm.ctx.cached_hash.get(entity, key)
    }

    /// Function to retrieve currently stored hash value with given `UniqueMarker` type for entity.
    /// See [`Self::hash_update_typ`]
    pub fn hash_get_typ<UniqueMarker: 'static>(&self) -> Option<ImmId> {
        let entity = self.entity();
        self.imm.ctx.cached_hash.get_typ::<UniqueMarker>(entity)
    }

    /// Function to retrieve currently stored hash value with given key for entity.
    /// See [`Self::hash_update`]
    pub fn hash_remove(&mut self, key: ImmId) -> Option<ImmId> {
        let entity = self.entity();
        self.imm.ctx.cached_hash.remove(entity, key)
    }

    /// Function to retrieve currently stored hash value with given `UniqueMarker` type for entity.
    /// See [`Self::hash_update_typ`]
    pub fn hash_remove_typ<UniqueMarker: 'static>(&mut self) -> Option<ImmId> {
        let entity = self.entity();
        self.imm.ctx.cached_hash.remove_typ::<UniqueMarker>(entity)
    }

    /// Insert bundle on entity when provided value hash changes (including first function call)
    pub fn on_hash_change_insert<H, F, B>(mut self, key: &str, value: &H, f: F) -> Self
    where
        H: std::hash::Hash,
        F: FnOnce() -> B,
        B: Bundle,
    {
        let key = imm_id(key);
        let value = imm_id(value);
        let current = self.hash_get(key);
        if current != Some(value) {
            self.entity_commands().insert(f());
            self.hash_set(key, value);
        }
        self
    }

    /// Insert bundle on entity when provided value hash changes (including first function call)
    pub fn on_hash_change_typ_insert<Key, H, F, B>(mut self, value: &H, f: F) -> Self
    where
        Key: 'static,
        H: std::hash::Hash,
        F: FnOnce() -> B,
        B: Bundle,
    {
        let value = imm_id(value);
        let current = self.hash_get_typ::<Key>();
        if current != Some(value) {
            self.entity_commands().insert(f());
            self.hash_set_typ::<Key>(value);
        }
        self
    }
}

/// Component that is added to entities that are managed by immediate mode system
///
/// Useful to add query filter [`WithoutImm<()>`] or [`bevy_ecs::query::Without<ImmMarker<()>>`]
/// to your queries. Replace `()` with `Cap` that you use.
#[derive(bevy_ecs::component::Component)]
pub struct ImmMarker<Caps> {
    id: ImmId,
    iteration: u32,
    _ph: PhantomData<Caps>,
}

/// Type to use in QueryFilter to avoid query collisions
pub type WithoutImm<Caps = ()> = Without<ImmMarker<Caps>>;

/// Helper structure for immediate mode compatbile state change detection
pub struct ChangeDetector {
    last_run: bevy_ecs::change_detection::Tick,
}

impl ChangeDetector {
    /// Has state changed since and including last time system was executed
    pub fn has_changed<T>(&self, value: &Mut<'_, T>) -> bool {
        value.is_changed() || value.last_changed() == self.last_run
    }
}

/// Helper guard structure to handle scope for child creation without introducing additional
/// nesting level
///
/// Useful in for loops, match statements, if else statements to create unique ids for this scope
pub struct ImmScopeGuard<'r, 'w, 's, Caps: CapSet> {
    imm: &'r mut Imm<'w, 's, Caps>,
    stored_current: Current,
}

impl<'r, 'w, 's, Caps: CapSet> std::ops::Deref for ImmScopeGuard<'r, 'w, 's, Caps> {
    type Target = Imm<'w, 's, Caps>;

    fn deref(&self) -> &Self::Target {
        self.imm
    }
}

impl<'r, 'w, 's, Caps: CapSet> std::ops::DerefMut for ImmScopeGuard<'r, 'w, 's, Caps> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.imm
    }
}

impl<'r, 'w, 's, Caps: CapSet> Drop for ImmScopeGuard<'r, 'w, 's, Caps> {
    fn drop(&mut self) {
        self.imm.current = self.stored_current;
    }
}

impl<'r, 'w, 's, Caps: CapSet> ImmScopeGuard<'r, 'w, 's, Caps> {
    /// Construct guard with unique auto id generation parameter
    pub fn add_id_pref(
        imm: &'r mut Imm<'w, 's, Caps>,
        additional_auto_id: impl std::hash::Hash,
    ) -> Self {
        let auto_id_pref = imm.current.id_pref.with(additional_auto_id);

        Self::new_scope(
            imm,
            Current {
                id: imm.current.id,
                entity: imm.current.entity,
                auto_id_idx: 0,
                id_pref: auto_id_pref,
            },
        )
    }

    fn new_scope(imm: &'r mut Imm<'w, 's, Caps>, mut new_current: Current) -> Self {
        std::mem::swap(&mut new_current, &mut imm.current);
        Self {
            imm,
            stored_current: new_current,
        }
    }
}