bevy_observed_utility 0.1.0

Ergonomic and Correct Utility AI for Bevy Engine
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
//! Scoring in utility AI involves calculating the [`Score`] of an entity, often based on the scores of its children.
//!
//! # Provided [`Score`] implementations
//!
//! - [`AllOrNothing`]: Scores the sum of all child scores, but only if the sum reaches a certain threshold. Otherwise, the score is 0.
//! - [`Evaluated`]: Scores a single child entity based on an [`Evaluator`] function. See the struct docs for the list of provided evaluators.
//! - [`FixedScore`]: Scores a fixed value.
//! - [`Measured`]: Scores all child entities based on a [`Measure`] function. See the struct docs for the list of provided measures.
//! - [`Product`]: Scores the product of all child scores.
//! - [`Random`] (requires `rand` feature): Scores a random value, optionally within a range.
//! - [`Sum`]: Scores the sum of all child scores.
//! - [`Winning`]: Scores the highest child score.
//!
//! # Provided [`Observer`] utilities
//!
//! - [`score_ancestor`]: Does the busy work of scoring a child entity based on its closest ancestor entity with a given component.

use std::{
    cmp::Ordering,
    ops::{Bound, RangeBounds},
};

use bevy::prelude::*;

use crate::{
    ecs::{AncestorQuery, DFSPostTraversal, TriggerGetEntity},
    event::{OnScore, RunScoring},
};

mod all_or_nothing;
mod evaluator;
mod fixed;
mod measured;
mod product;
#[cfg(feature = "rand")]
mod random;
mod sum;
mod winning;

pub use self::all_or_nothing::*;
pub use self::evaluator::*;
pub use self::fixed::*;
pub use self::measured::*;
pub use self::product::*;
#[cfg(feature = "rand")]
pub use self::random::*;
pub use self::sum::*;
pub use self::winning::*;

/// [`Plugin`] for scoring entities.
pub struct ScoringPlugin;

impl Plugin for ScoringPlugin {
    fn build(&self, app: &mut App) {
        app.observe(Self::run_scoring_post_order_dfs);
    }
}

impl ScoringPlugin {
    /// For each scoreable root entity, perform post-order depth-first traversal,
    /// triggering [`OnScore`] for each entity on the way back up.
    pub fn run_scoring_post_order_dfs(
        trigger: Trigger<RunScoring>,
        mut commands: Commands,
        scoreable_roots: Query<(Entity, Option<&Parent>), With<Score>>,
        root_parents: Query<(), Without<Score>>,
        mut dfs: DFSPostTraversal<With<Score>>,
    ) {
        fn trigger_in_order(root: Entity, mut commands: Commands, dfs: &mut DFSPostTraversal<With<Score>>) {
            let sorted = dfs.iter(root);

            for entity in sorted {
                commands.trigger_targets(OnScore, entity);
            }
        }

        if let Some(targeted_root) = trigger.get_entity() {
            // Do scoring for the given entity
            trigger_in_order(targeted_root, commands.reborrow(), &mut dfs);
        } else {
            // Do scoring globally
            // Find all score entities that have no parents at all, or whose parents are not score entities
            let roots = scoreable_roots.iter().filter_map(|(entity, parent)| {
                if let Some(parent) = parent {
                    if root_parents.contains(**parent) {
                        Some(entity)
                    } else {
                        None
                    }
                } else {
                    Some(entity)
                }
            });
            for root in roots {
                trigger_in_order(root, commands.reborrow(), &mut dfs);
            }
        }
    }
}

/// [`Component`] for an entity's score for a given score type, ranging from 0 to 1.
#[derive(Component, Reflect)]
#[derive(Clone, Copy, PartialEq, PartialOrd, Debug, Default)]
#[reflect(Component)]
pub struct Score {
    /// The score value, clamped to the range `[0, 1]`.
    value: f32,
}

impl Score {
    /// The minimum possible score.
    // SAFETY: The value is within the valid range of `[0, 1]`.
    pub const MIN: Score = unsafe { Score::new_unchecked(0.) };
    /// The maximum possible score.
    // SAFETY: The value is within the valid range of `[0, 1]`.
    pub const MAX: Score = unsafe { Score::new_unchecked(1.) };

    /// Creates a new score with the given value, clamped to the range `[0, 1]`.
    pub fn new(value: f32) -> Self {
        Self {
            value: value.clamp(0., 1.),
        }
    }

    /// Creates a new score with the given value, without clamping.
    ///
    /// # Safety
    ///
    /// The value must be in the range `[0, 1]`.
    pub const unsafe fn new_unchecked(value: f32) -> Self {
        Self { value }
    }

    /// Returns the score's value.
    #[inline(always)]
    pub fn get(&self) -> f32 {
        self.value
    }

    /// Sets the score's value, clamped to the range `[0, 1]`.
    #[inline]
    pub fn set(&mut self, value: f32) {
        self.value = value.clamp(0., 1.);
    }
}

impl From<f32> for Score {
    fn from(value: f32) -> Self {
        Self::new(value)
    }
}

impl From<Score> for f32 {
    fn from(score: Score) -> f32 {
        score.get()
    }
}

impl PartialEq<f32> for Score {
    fn eq(&self, other: &f32) -> bool {
        self.get() == *other
    }
}

impl PartialEq<Score> for f32 {
    fn eq(&self, other: &Score) -> bool {
        *self == other.get()
    }
}

impl PartialOrd<f32> for Score {
    fn partial_cmp(&self, other: &f32) -> Option<Ordering> {
        self.get().partial_cmp(other)
    }
}

impl PartialOrd<Score> for f32 {
    fn partial_cmp(&self, other: &Score) -> Option<Ordering> {
        self.partial_cmp(&other.get())
    }
}

impl std::iter::Sum<Self> for Score {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        // Unwrap the values, sum them, and clamp the result to the range `[0, 1]`.
        iter.map(|v| v.get())
            .fold(Score::MIN.get(), |acc, score| acc + score)
            .into()
    }
}

impl std::iter::Sum<f32> for Score {
    fn sum<I: Iterator<Item = f32>>(iter: I) -> Self {
        // Sum the values, and clamp the result to the range `[0, 1]`.
        iter.fold(Score::MIN.get(), |acc, score| acc + score).into()
    }
}

impl std::iter::Sum<Score> for f32 {
    fn sum<I: Iterator<Item = Score>>(iter: I) -> Self {
        // Unwrap the values, sum them.
        let sum = iter.map(|v| v.get()).fold(Score::MIN.get(), |acc, score| acc + score);
        // Clamp the result to the range `[0, 1]`.
        Score::new(sum).get()
    }
}

/// A range of [`Score`]s.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct ScoreRange {
    /// The minimum score.
    min: Bound<Score>,
    /// The maximum score.
    max: Bound<Score>,
}

impl ScoreRange {
    /// The full range of scores, from 0 to 1.
    pub const FULL: ScoreRange = ScoreRange {
        min: Bound::Included(Score::MIN),
        max: Bound::Included(Score::MAX),
    };

    /// Creates a new score range with the given minimum and maximum scores.
    pub fn new(mut min: Bound<Score>, mut max: Bound<Score>) -> Self {
        match (&mut min, &mut max) {
            (Bound::Included(min), Bound::Included(max))
            | (Bound::Included(min), Bound::Excluded(max))
            | (Bound::Excluded(min), Bound::Included(max))
            | (Bound::Excluded(min), Bound::Excluded(max))
                if *max < *min =>
            {
                std::mem::swap(min, max);
            }
            _ => {}
        };
        Self { min, max }
    }

    /// Creates a new score range from the given [`RangeBounds`].
    pub fn from_bounds(bounds: impl RangeBounds<Score>) -> Self {
        Self::new(bounds.start_bound().cloned(), bounds.end_bound().cloned())
    }

    /// Returns the minimum score.
    pub fn min(&self) -> Bound<Score> {
        self.min
    }

    /// Returns the minimum score as a `f32`.
    pub fn min_f32(&self) -> f32 {
        match self.min {
            Bound::Included(score) => score.get(),
            Bound::Excluded(score) => score.get(),
            Bound::Unbounded => Score::MIN.get(),
        }
    }

    /// Returns the maximum score.
    pub fn max(&self) -> Bound<Score> {
        self.max
    }

    /// Returns the maximum score as a `f32`.
    pub fn max_f32(&self) -> f32 {
        match self.max {
            Bound::Included(score) => score.get(),
            Bound::Excluded(score) => score.get(),
            Bound::Unbounded => Score::MAX.get(),
        }
    }
}

impl Default for ScoreRange {
    fn default() -> Self {
        Self::FULL
    }
}

impl RangeBounds<Score> for ScoreRange {
    fn start_bound(&self) -> Bound<&Score> {
        self.min.as_ref()
    }

    fn end_bound(&self) -> Bound<&Score> {
        self.max.as_ref()
    }
}

/// [`Observer`] helper function that calculates the score of a child [`Score`] entity marked with `ScoreMarker`
/// based on the [`Component`] `T` on its closest ancestor entity, usually the actor entity.
///
/// The [`Component`] `T` must implement [`Into<Score>`] for its reference type `&T`.
///
/// # Example
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy_observed_utility::prelude::*;
///
/// /// This goes on the actor entity.
/// #[derive(Component)]
/// struct Thirst {
///     value: f32,
///     per_second: f32,
/// }
///
/// /// This impl is required for the `score_ancestor` observer.
/// impl From<&Thirst> for Score {
///    fn from(thirst: &Thirst) -> Self {
///       Score::new(thirst.value / 100.)
///    }
/// }
///
/// /// This goes on the score entity.
/// #[derive(Component)]
/// pub struct Thirsty;
///
/// # let mut app = App::new();
/// # app.add_plugins(ObservedUtilityPlugins::RealTime);
/// app.observe(score_ancestor::<Thirst, Thirsty>);
///
/// # let mut world = app.world_mut();
/// # let mut commands = world.commands();
/// let scorer = commands
///     .spawn((Thirsty, Score::default()))
///     .id();
///
/// let actor = commands
///     .spawn(Thirst { value: 50., per_second: 1. })
///     .add_child(scorer)
///     .id();
/// # commands.trigger_targets(RunScoring, scorer);
/// # world.flush();
/// # assert_eq!(0.5, world.get::<Score>(scorer).unwrap().get());
/// ```
pub fn score_ancestor<T: Component, ScoreMarker: Component>(
    trigger: Trigger<OnScore>,
    mut scores: Query<&mut Score, With<ScoreMarker>>,
    mut ancestors: AncestorQuery<&'static T>,
) where
    for<'a> &'a T: Into<Score>,
{
    let scorer = trigger.entity();
    let Ok(mut score) = scores.get_mut(scorer) else {
        return;
    };

    if let Ok(ancestor) = ancestors.get(scorer) {
        *score = ancestor.into();
    } else {
        // If there is no ancestor, set the score to the minimum.
        *score = Score::MIN;
    }
}

#[cfg(test)]
mod tests {
    use approx::assert_relative_eq;
    use bevy::{
        app::App,
        ecs::observer::ObserverState,
        prelude::{BuildWorldChildren, With, World},
    };

    use crate::{
        event::RunScoring,
        scoring::{
            AllOrNothing, Evaluated, FixedScore, Measured, PowerEvaluator, Product, Score, ScoringPlugin, Sum,
            Weighted, WeightedMax, WeightedProduct, WeightedRMS, WeightedSum, Winning,
        },
    };

    #[test]
    fn all_or_nothing() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), AllOrNothing::new(0.2)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.7)));
                parent.spawn((Score::default(), FixedScore::new(0.3)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_eq!(
            1.0,
            world.get::<Score>(parent).unwrap().get(),
            "Parent score should be 1.0."
        );
        assert_eq!(3, count_observers(world));
    }

    #[test]
    fn evaluated_power() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let entity = world
            .spawn((Score::default(), Evaluated::new(PowerEvaluator::default())))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.7)));
            })
            .id();

        world.trigger_targets(RunScoring, entity);
        world.flush();

        assert_relative_eq!(0.49, world.get::<Score>(entity).unwrap().get());
    }

    #[test]
    fn fixed() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let entity = world.spawn((Score::default(), FixedScore::new(0.5))).id();

        world.trigger_targets(RunScoring, entity);
        world.flush();

        assert_eq!(0.5, world.get::<Score>(entity).unwrap().get(), "Score should be 0.5.");
        assert_eq!(2, count_observers(world));
    }

    #[test]
    fn measured_weighted_sum() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), Measured::new(WeightedSum)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.9), Weighted::new(0.9)));
                parent.spawn((Score::default(), FixedScore::new(0.8), Weighted::new(0.1)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_relative_eq!(0.89, world.get::<Score>(parent).unwrap().get());
        assert_eq!(3, count_observers(world));
    }

    #[test]
    fn measured_weighted_product() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), Measured::new(WeightedProduct)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.9), Weighted::new(0.9)));
                parent.spawn((Score::default(), FixedScore::new(0.8), Weighted::new(0.1)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_relative_eq!(0.0648, world.get::<Score>(parent).unwrap().get());
        assert_eq!(3, count_observers(world));
    }

    #[test]
    fn measured_weighted_max() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), Measured::new(WeightedMax)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.9), Weighted::new(0.9)));
                parent.spawn((Score::default(), FixedScore::new(0.8), Weighted::new(0.1)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_relative_eq!(0.81, world.get::<Score>(parent).unwrap().get());
        assert_eq!(3, count_observers(world));
    }

    #[test]
    fn measured_weighted_rms() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), Measured::new(WeightedRMS)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.9), Weighted::new(0.9)));
                parent.spawn((Score::default(), FixedScore::new(0.8), Weighted::new(0.1)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_relative_eq!(0.8905055, world.get::<Score>(parent).unwrap().get());
        assert_eq!(3, count_observers(world));
    }

    #[test]
    fn product() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), Product::new(0.4)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.9)));
                parent.spawn((Score::default(), FixedScore::new(0.8)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_relative_eq!(0.72, world.get::<Score>(parent).unwrap().get(),);
        assert_eq!(3, count_observers(world));
    }

    #[test]
    fn sum() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), Sum::new(0.4)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.9)));
                parent.spawn((Score::default(), FixedScore::new(0.8)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_eq!(
            1.0,
            world.get::<Score>(parent).unwrap().get(),
            "Parent score should be 1.0."
        );
        assert_eq!(3, count_observers(world));
    }

    #[test]
    fn winning() {
        let mut app = App::new();
        app.add_plugins(ScoringPlugin);

        let world = app.world_mut();

        let parent = world
            .spawn((Score::default(), Winning::new(0.5)))
            .with_children(|parent| {
                parent.spawn((Score::default(), FixedScore::new(0.9)));
                parent.spawn((Score::default(), FixedScore::new(0.8)));
            })
            .id();

        world.trigger_targets(RunScoring, parent);
        world.flush();

        assert_eq!(
            0.9,
            world.get::<Score>(parent).unwrap().get(),
            "Parent score should be 0.9."
        );
        assert_eq!(3, count_observers(world));
    }

    fn count_observers(world: &mut World) -> usize {
        world.query_filtered::<(), With<ObserverState>>().iter(world).count()
    }
}