big-brain 0.22.0

Rusty Utility AI library
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
//! Scorers look at the world and boil down arbitrary characteristics into a
//! range of 0.0..=1.0. This module includes the ScorerBuilder trait and some
//! built-in Composite Scorers.

use std::{cmp::Ordering, sync::Arc};

use bevy::prelude::*;
#[cfg(feature = "trace")]
use bevy::utils::tracing::trace;

use crate::{
    evaluators::Evaluator,
    measures::{Measure, WeightedMeasure},
    thinker::{Actor, Scorer, ScorerSpan},
};

/// Score value between `0.0..=1.0` associated with a Scorer.
#[derive(Clone, Component, Debug, Default, Reflect)]
pub struct Score(pub(crate) f32);

impl Score {
    /// Returns the `Score`'s current value.
    pub fn get(&self) -> f32 {
        self.0
    }

    /// Set the `Score`'s value.
    ///
    /// ### Panics
    ///
    /// Panics if `value` isn't within `0.0..=1.0`.
    pub fn set(&mut self, value: f32) {
        if !(0.0..=1.0).contains(&value) {
            panic!("Score value must be between 0.0 and 1.0");
        }
        self.0 = value;
    }

    /// Set the `Score`'s value. Allows values outside the range `0.0..=1.0`
    /// WARNING: `Scorer`s are significantly harder to compose when there
    /// isn't a set scale. Avoid using unless it's not feasible to rescale
    /// and use `set` instead.
    pub fn set_unchecked(&mut self, value: f32) {
        self.0 = value;
    }
}

/// Trait that must be defined by types in order to be `ScorerBuilder`s.
/// `ScorerBuilder`s' job is to spawn new `Scorer` entities. In general, most
/// of this is already done for you, and the only method you really have to
/// implement is `.build()`.
///
/// The `build()` method MUST be implemented for any `ScorerBuilder`s you want
/// to define.
#[reflect_trait]
pub trait ScorerBuilder: std::fmt::Debug + Sync + Send {
    /// MUST insert your concrete Scorer component into the Scorer [`Entity`],
    ///  using `cmd`. You _may_ use `actor`, but it's perfectly normal to just
    ///  ignore it.
    ///
    /// In most cases, your `ScorerBuilder` and `Scorer` can be the same type.
    /// The only requirement is that your struct implements `Debug`,
    /// `Component, `Clone`. You can then use the derive macro `ScorerBuilder`
    /// to turn your struct into a `ScorerBuilder`
    ///
    /// ### Example
    ///
    /// Using the derive macro (the easy way):
    ///
    /// ```
    /// # use bevy::prelude::*;
    /// # use big_brain::prelude::*;
    /// #[derive(Debug, Clone, Component, ScorerBuilder)]
    /// #[scorer_label = "MyScorerLabel"] // Optional. Defaults to type name.
    /// struct MyScorer;
    /// ```
    ///
    /// Implementing it manually:
    ///
    /// ```
    /// # use bevy::prelude::*;
    /// # use big_brain::prelude::*;
    /// #[derive(Debug)]
    /// struct MyBuilder;
    /// #[derive(Debug, Component)]
    /// struct MyScorer;
    ///
    /// impl ScorerBuilder for MyBuilder {
    ///   fn build(&self, cmd: &mut Commands, scorer: Entity, _actor: Entity) {
    ///     cmd.entity(scorer).insert(MyScorer);
    ///   }
    /// }
    /// ```
    fn build(&self, cmd: &mut Commands, scorer: Entity, actor: Entity);

    /// A label to display when logging using the Scorer's tracing span.
    fn label(&self) -> Option<&str> {
        None
    }
}

pub fn spawn_scorer<T: ScorerBuilder + ?Sized>(
    builder: &T,
    cmd: &mut Commands,
    actor: Entity,
) -> Entity {
    let scorer_ent = cmd.spawn_empty().id();
    let span = ScorerSpan::new(scorer_ent, ScorerBuilder::label(builder));
    let _guard = span.span().enter();
    debug!("New Scorer spawned.");
    cmd.entity(scorer_ent)
        .insert(Name::new("Scorer"))
        .insert(Score::default())
        .insert(Actor(actor));
    builder.build(cmd, scorer_ent, actor);
    std::mem::drop(_guard);
    cmd.entity(scorer_ent).insert(span);
    scorer_ent
}

/// Scorer that always returns the same, fixed score. Good for combining with
/// things creatively!
#[derive(Clone, Component, Debug, Reflect)]
pub struct FixedScore(pub f32);

impl FixedScore {
    pub fn build(score: f32) -> FixedScorerBuilder {
        FixedScorerBuilder { score, label: None }
    }
}

pub fn fixed_score_system(mut query: Query<(&FixedScore, &mut Score, &ScorerSpan)>) {
    for (FixedScore(fixed), mut score, _span) in query.iter_mut() {
        #[cfg(feature = "trace")]
        {
            let _guard = _span.span().enter();
            trace!("FixedScore: {}", fixed);
        }
        score.set(*fixed);
    }
}

#[derive(Debug, Reflect)]
pub struct FixedScorerBuilder {
    score: f32,
    label: Option<String>,
}

impl FixedScorerBuilder {
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }
}

impl ScorerBuilder for FixedScorerBuilder {
    fn build(&self, cmd: &mut Commands, scorer: Entity, _actor: Entity) {
        cmd.entity(scorer).insert(FixedScore(self.score));
    }

    fn label(&self) -> Option<&str> {
        self.label.as_deref().or(Some("FixedScore"))
    }
}

/// Composite Scorer that takes any number of other Scorers and returns the
/// sum of their [`Score`] values if each _individual_ [`Score`] is at or
/// above the configured `threshold`.
///
/// ### Example
///
/// ```
/// # use bevy::prelude::*;
/// # use big_brain::prelude::*;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyScorer;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyOtherScorer;
/// # #[derive(Debug, Clone, Component, ActionBuilder)]
/// # struct MyAction;
/// # fn main() {
/// Thinker::build()
///     .when(
///         AllOrNothing::build(0.8)
///           .push(MyScorer)
///           .push(MyOtherScorer),
///         MyAction);
/// # ;
/// # }
/// ```
#[derive(Component, Debug, Reflect)]
pub struct AllOrNothing {
    threshold: f32,
    scorers: Vec<Scorer>,
}

impl AllOrNothing {
    pub fn build(threshold: f32) -> AllOrNothingBuilder {
        AllOrNothingBuilder {
            threshold,
            scorers: Vec::new(),
            scorer_labels: Vec::new(),
            label: None,
        }
    }
}

pub fn all_or_nothing_system(
    query: Query<(Entity, &AllOrNothing, &ScorerSpan)>,
    mut scores: Query<&mut Score>,
) {
    for (
        aon_ent,
        AllOrNothing {
            threshold,
            scorers: children,
        },
        _span,
    ) in query.iter()
    {
        let mut sum = 0.0;
        for Scorer(child) in children.iter() {
            let score = scores.get_mut(*child).expect("where is it?");
            if score.0 < *threshold {
                sum = 0.0;
                break;
            } else {
                sum += score.0;
            }
        }
        let mut score = scores.get_mut(aon_ent).expect("where did it go?");
        score.set(crate::evaluators::clamp(sum, 0.0, 1.0));
        #[cfg(feature = "trace")]
        {
            let _guard = _span.span().enter();
            trace!("AllOrNothing score: {}", score.get());
        }
    }
}

#[derive(Debug, Clone, Reflect)]
pub struct AllOrNothingBuilder {
    threshold: f32,
    #[reflect(ignore)]
    scorers: Vec<Arc<dyn ScorerBuilder>>,
    scorer_labels: Vec<String>,
    label: Option<String>,
}

impl AllOrNothingBuilder {
    /// Add another Scorer to this [`ScorerBuilder`].
    pub fn push(mut self, scorer: impl ScorerBuilder + 'static) -> Self {
        if let Some(label) = scorer.label() {
            self.scorer_labels.push(label.into());
        } else {
            self.scorer_labels.push("Unnamed Scorer".into());
        }
        self.scorers.push(Arc::new(scorer));
        self
    }

    /// Set a label for this Action.
    pub fn label(mut self, label: impl AsRef<str>) -> Self {
        self.label = Some(label.as_ref().into());
        self
    }
}

impl ScorerBuilder for AllOrNothingBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref().or(Some("AllOrNothing"))
    }

    fn build(&self, cmd: &mut Commands, scorer: Entity, actor: Entity) {
        let scorers: Vec<_> = self
            .scorers
            .iter()
            .map(|scorer| spawn_scorer(&**scorer, cmd, actor))
            .collect();
        cmd.entity(scorer)
            .insert(Score::default())
            .add_children(&scorers[..])
            .insert(Name::new("Scorer"))
            .insert(AllOrNothing {
                threshold: self.threshold,
                scorers: scorers.into_iter().map(Scorer).collect(),
            });
    }
}

/// Composite Scorer that takes any number of other Scorers and returns the sum of their [`Score`] values if the _total_ summed [`Score`] is at or above the configured `threshold`.
///
/// ### Example
///
/// ```
/// # use bevy::prelude::*;
/// # use big_brain::prelude::*;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyScorer;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyOtherScorer;
/// # #[derive(Debug, Clone, Component, ActionBuilder)]
/// # struct MyAction;
/// # fn main() {
/// Thinker::build()
///     .when(
///         SumOfScorers::build(0.8)
///           .push(MyScorer)
///           .push(MyOtherScorer),
///         MyAction)
/// # ;
/// # }
/// ```
#[derive(Component, Debug, Reflect)]
pub struct SumOfScorers {
    threshold: f32,
    scorers: Vec<Scorer>,
    scorer_labels: Vec<String>,
}

impl SumOfScorers {
    pub fn build(threshold: f32) -> SumOfScorersBuilder {
        SumOfScorersBuilder {
            threshold,
            scorers: Vec::new(),
            scorer_labels: Vec::new(),
            label: None,
        }
    }
}

pub fn sum_of_scorers_system(
    query: Query<(Entity, &SumOfScorers, &ScorerSpan)>,
    mut scores: Query<&mut Score>,
) {
    for (
        sos_ent,
        SumOfScorers {
            threshold,
            scorers: children,
            ..
        },
        _span,
    ) in query.iter()
    {
        let mut sum = 0.0;
        for Scorer(child) in children.iter() {
            let score = scores.get_mut(*child).expect("where is it?");
            sum += score.0;
        }
        if sum < *threshold {
            sum = 0.0;
        }
        let mut score = scores.get_mut(sos_ent).expect("where did it go?");
        score.set(crate::evaluators::clamp(sum, 0.0, 1.0));
        #[cfg(feature = "trace")]
        {
            let _guard = _span.span().enter();
            trace!(
                "SumOfScorers score: {}, from {} scores",
                score.get(),
                children.len()
            );
        }
    }
}

#[derive(Debug, Clone, Reflect)]
pub struct SumOfScorersBuilder {
    threshold: f32,
    #[reflect(ignore)]
    scorers: Vec<Arc<dyn ScorerBuilder>>,
    scorer_labels: Vec<String>,
    label: Option<String>,
}

impl SumOfScorersBuilder {
    /// Add a new Scorer to this [`SumOfScorersBuilder`].
    pub fn push(mut self, scorer: impl ScorerBuilder + 'static) -> Self {
        if let Some(label) = scorer.label() {
            self.scorer_labels.push(label.into());
        } else {
            self.scorer_labels.push("Unnamed Scorer".into());
        }
        self.scorers.push(Arc::new(scorer));
        self
    }

    /// Set a label for this Action.
    pub fn label(mut self, label: impl AsRef<str>) -> Self {
        self.label = Some(label.as_ref().into());
        self
    }
}

impl ScorerBuilder for SumOfScorersBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref().or(Some("SumOfScorers"))
    }

    #[allow(clippy::needless_collect)]
    fn build(&self, cmd: &mut Commands, scorer: Entity, actor: Entity) {
        let scorers: Vec<_> = self
            .scorers
            .iter()
            .map(|scorer| spawn_scorer(&**scorer, cmd, actor))
            .collect();
        cmd.entity(scorer)
            .add_children(&scorers[..])
            .insert(SumOfScorers {
                threshold: self.threshold,
                scorers: scorers.into_iter().map(Scorer).collect(),
                scorer_labels: self.scorer_labels.clone(),
            });
    }
}

/// Composite Scorer that takes any number of other Scorers and returns the
/// product of their [`Score`]. If the resulting score is less than the
/// threshold, it returns 0.
///
/// The Scorer can also apply a compensation factor based on the number of
/// Scores passed to it. This can be enabled by passing `true` to the
/// `use_compensation` method on the builder.
///
/// ### Example
///
/// ```
/// # use bevy::prelude::*;
/// # use big_brain::prelude::*;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyScorer;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyOtherScorer;
/// # #[derive(Debug, Clone, Component, ActionBuilder)]
/// # struct MyAction;
/// # fn main() {
/// Thinker::build()
///     .when(
///         ProductOfScorers::build(0.5)
///           .use_compensation(true)
///           .push(MyScorer)
///           .push(MyOtherScorer),
///         MyAction)
/// # ;
/// # }
/// ```

#[derive(Component, Debug, Reflect)]
pub struct ProductOfScorers {
    threshold: f32,
    use_compensation: bool,
    scorers: Vec<Scorer>,
    scorer_labels: Vec<String>,
}

impl ProductOfScorers {
    pub fn build(threshold: f32) -> ProductOfScorersBuilder {
        ProductOfScorersBuilder {
            threshold,
            use_compensation: false,
            scorers: Vec::new(),
            scorer_labels: Vec::new(),
            label: None,
        }
    }
}

pub fn product_of_scorers_system(
    query: Query<(Entity, &ProductOfScorers, &ScorerSpan)>,
    mut scores: Query<&mut Score>,
) {
    for (
        sos_ent,
        ProductOfScorers {
            threshold,
            use_compensation,
            scorers: children,
            ..
        },
        _span,
    ) in query.iter()
    {
        let mut product = 1.0;
        let mut num_scorers = 0;

        for Scorer(child) in children.iter() {
            let score = scores.get_mut(*child).expect("where is it?");
            product *= score.0;
            num_scorers += 1;
        }

        // See for example
        // http://www.gdcvault.com/play/1021848/Building-a-Better-Centaur-AI
        if *use_compensation && product < 1.0 {
            let mod_factor = 1.0 - 1.0 / (num_scorers as f32);
            let makeup = (1.0 - product) * mod_factor;
            product += makeup * product;
        }

        if product < *threshold {
            product = 0.0;
        }

        let mut score = scores.get_mut(sos_ent).expect("where did it go?");
        score.set(product.clamp(0.0, 1.0));
        #[cfg(feature = "trace")]
        {
            let _guard = _span.span().enter();
            trace!(
                "ProductOfScorers score: {}, from {} scores",
                score.get(),
                children.len()
            );
        }
    }
}

#[derive(Debug, Clone)]
pub struct ProductOfScorersBuilder {
    threshold: f32,
    use_compensation: bool,
    scorers: Vec<Arc<dyn ScorerBuilder>>,
    scorer_labels: Vec<String>,
    label: Option<String>,
}

impl ProductOfScorersBuilder {
    /// To account for the fact that the total score will be reduced for
    /// scores with more inputs, we can optionally apply a compensation factor
    /// by calling this and passing `true`
    pub fn use_compensation(mut self, use_compensation: bool) -> Self {
        self.use_compensation = use_compensation;
        self
    }

    /// Add a new scorer to this [`ProductOfScorersBuilder`].
    pub fn push(mut self, scorer: impl ScorerBuilder + 'static) -> Self {
        if let Some(label) = scorer.label() {
            self.scorer_labels.push(label.into());
        } else {
            self.scorer_labels.push("Unnamed Scorer".into());
        }
        self.scorers.push(Arc::new(scorer));
        self
    }

    /// Set a label for this Action.
    pub fn label(mut self, label: impl AsRef<str>) -> Self {
        self.label = Some(label.as_ref().into());
        self
    }
}

impl ScorerBuilder for ProductOfScorersBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref().or(Some("ProductOfScorers"))
    }

    #[allow(clippy::needless_collect)]
    fn build(&self, cmd: &mut Commands, scorer: Entity, actor: Entity) {
        let scorers: Vec<_> = self
            .scorers
            .iter()
            .map(|scorer| spawn_scorer(&**scorer, cmd, actor))
            .collect();
        cmd.entity(scorer)
            .add_children(&scorers[..])
            .insert(ProductOfScorers {
                threshold: self.threshold,
                use_compensation: self.use_compensation,
                scorers: scorers.into_iter().map(Scorer).collect(),
                scorer_labels: self.scorer_labels.clone(),
            });
    }
}

/// Composite Scorer that takes any number of other Scorers and returns the
/// single highest value [`Score`] if  _any_ [`Score`]s are at or above the
/// configured `threshold`.
///
/// ### Example
///
/// ```
/// # use bevy::prelude::*;
/// # use big_brain::prelude::*;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyScorer;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyOtherScorer;
/// # #[derive(Debug, Clone, Component, ActionBuilder)]
/// # struct MyAction;
/// # fn main() {
/// Thinker::build()
///     .when(
///         WinningScorer::build(0.8)
///           .push(MyScorer)
///           .push(MyOtherScorer),
///         MyAction)
/// # ;
/// # }
/// ```

#[derive(Component, Debug, Reflect)]
pub struct WinningScorer {
    threshold: f32,
    scorers: Vec<Scorer>,
    scorer_labels: Vec<String>,
}

impl WinningScorer {
    pub fn build(threshold: f32) -> WinningScorerBuilder {
        WinningScorerBuilder {
            threshold,
            scorers: Vec::new(),
            scorer_labels: Vec::new(),
            label: None,
        }
    }
}

pub fn winning_scorer_system(
    mut query: Query<(Entity, &mut WinningScorer, &ScorerSpan)>,
    mut scores: Query<&mut Score>,
) {
    for (sos_ent, mut winning_scorer, _span) in query.iter_mut() {
        let (threshold, children) = (winning_scorer.threshold, &mut winning_scorer.scorers);
        let mut all_scores = children
            .iter()
            .map(|Scorer(e)| scores.get(*e).expect("where is it?"))
            .collect::<Vec<&Score>>();

        all_scores.sort_by(|a, b| a.get().partial_cmp(&b.get()).unwrap_or(Ordering::Equal));
        let winning_score_or_zero = match all_scores.last() {
            Some(s) => {
                if s.get() < threshold {
                    0.0
                } else {
                    s.get()
                }
            }
            None => 0.0,
        };
        let mut score = scores.get_mut(sos_ent).expect("where did it go?");
        score.set(crate::evaluators::clamp(winning_score_or_zero, 0.0, 1.0));
        #[cfg(feature = "trace")]
        {
            let _guard = _span.span().enter();
            trace!(
                "WinningScorer score: {}, from {} scores",
                score.get(),
                children.len()
            );
        }
    }
}

#[derive(Debug, Clone, Reflect)]
pub struct WinningScorerBuilder {
    threshold: f32,
    #[reflect(ignore)]
    scorers: Vec<Arc<dyn ScorerBuilder>>,
    scorer_labels: Vec<String>,
    label: Option<String>,
}

impl WinningScorerBuilder {
    /// Add another Scorer to this [`WinningScorerBuilder`].
    pub fn push(mut self, scorer: impl ScorerBuilder + 'static) -> Self {
        if let Some(label) = scorer.label() {
            self.scorer_labels.push(label.into());
        } else {
            self.scorer_labels.push("Unnamed Scorer".into())
        }
        self.scorers.push(Arc::new(scorer));
        self
    }

    /// Set a label for this Action.
    pub fn label(mut self, label: impl AsRef<str>) -> Self {
        self.label = Some(label.as_ref().into());
        self
    }
}

impl ScorerBuilder for WinningScorerBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref().or(Some("WinningScorer"))
    }

    #[allow(clippy::needless_collect)]
    fn build(&self, cmd: &mut Commands, scorer: Entity, actor: Entity) {
        let scorers: Vec<_> = self
            .scorers
            .iter()
            .map(|scorer| spawn_scorer(&**scorer, cmd, actor))
            .collect();
        cmd.entity(scorer)
            .add_children(&scorers[..])
            .insert(WinningScorer {
                threshold: self.threshold,
                scorers: scorers.into_iter().map(Scorer).collect(),
                scorer_labels: self.scorer_labels.clone(),
            });
    }
}

/// Composite scorer that takes a `ScorerBuilder` and applies an `Evaluator`.
/// Note that unlike other composite scorers, `EvaluatingScorer` only takes
/// one scorer upon building.
///
/// ### Example
///
/// ```
/// # use bevy::prelude::*;
/// # use big_brain::prelude::*;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyScorer;
/// # #[derive(Debug, Clone, Component, ActionBuilder)]
/// # struct MyAction;
/// # #[derive(Debug, Clone)]
/// # struct MyEvaluator;
/// # impl Evaluator for MyEvaluator {
/// #    fn evaluate(&self, score: f32) -> f32 {
/// #        score
/// #    }
/// # }
/// # fn main() {
/// Thinker::build()
///     .when(
///         EvaluatingScorer::build(MyScorer, MyEvaluator),
///         MyAction)
/// # ;
/// # }
/// ```
#[derive(Component, Debug, Reflect)]
#[reflect(from_reflect = false)]
pub struct EvaluatingScorer {
    scorer: Scorer,
    evaluator_string: String,
    #[reflect(ignore)]
    evaluator: Arc<dyn Evaluator>,
}

impl EvaluatingScorer {
    pub fn build(
        scorer: impl ScorerBuilder + 'static,
        evaluator: impl Evaluator + 'static,
    ) -> EvaluatingScorerBuilder {
        EvaluatingScorerBuilder {
            scorer_label: scorer.label().map(|s| s.into()),
            evaluator: Arc::new(evaluator),
            scorer: Arc::new(scorer),
            label: None,
        }
    }
}

pub fn evaluating_scorer_system(
    query: Query<(Entity, &EvaluatingScorer, &ScorerSpan)>,
    mut scores: Query<&mut Score>,
) {
    for (sos_ent, eval_scorer, _span) in query.iter() {
        // Get the inner score
        let inner_score = scores
            .get(eval_scorer.scorer.0)
            .expect("where did it go?")
            .get();
        // Get composite score
        let mut score = scores.get_mut(sos_ent).expect("where did it go?");
        score.set(crate::evaluators::clamp(
            eval_scorer.evaluator.evaluate(inner_score),
            0.0,
            1.0,
        ));
        #[cfg(feature = "trace")]
        {
            let _guard = _span.span().enter();
            trace!(
                "EvaluatingScorer score: {}, from score: {}",
                score.get(),
                inner_score
            );
        }
    }
}

#[derive(Debug, Reflect)]
#[reflect(from_reflect = false)]
pub struct EvaluatingScorerBuilder {
    #[reflect(ignore)]
    scorer: Arc<dyn ScorerBuilder>,
    scorer_label: Option<String>,
    #[reflect(ignore)]
    evaluator: Arc<dyn Evaluator>,
    label: Option<String>,
}

impl ScorerBuilder for EvaluatingScorerBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref().or(Some("EvaluatingScorer"))
    }

    fn build(&self, cmd: &mut Commands, scorer: Entity, actor: Entity) {
        let inner_scorer = spawn_scorer(&*self.scorer, cmd, actor);
        let scorers = [inner_scorer];
        cmd.entity(scorer)
            .add_children(&scorers[..])
            .insert(EvaluatingScorer {
                evaluator: self.evaluator.clone(),
                scorer: Scorer(inner_scorer),
                evaluator_string: format!("{:#?}", self.evaluator),
            });
    }
}

/// Composite Scorer that allows more fine-grained control of how the scores
/// are combined. The default is to apply a weighting
///
/// ### Example
///
/// Using the default measure ([`WeightedMeasure`]):
///
/// ```
/// # use bevy::prelude::*;
/// # use big_brain::prelude::*;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyScorer;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyOtherScorer;
/// # #[derive(Debug, Clone, Component, ActionBuilder)]
/// # struct MyAction;
/// # fn main() {
/// Thinker::build()
///     .when(
///         MeasuredScorer::build(0.5)
///           .push(MyScorer, 0.9)
///           .push(MyOtherScorer, 0.4),
///         MyAction)
/// # ;
/// # }
/// ```
///
/// Customising the measure:
///
/// ```
/// # use bevy::prelude::*;
/// # use big_brain::prelude::*;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyScorer;
/// # #[derive(Debug, Clone, Component, ScorerBuilder)]
/// # struct MyOtherScorer;
/// # #[derive(Debug, Clone, Component, ActionBuilder)]
/// # struct MyAction;
/// # fn main() {
/// Thinker::build()
///     .when(
///         MeasuredScorer::build(0.5)
///           .measure(ChebyshevDistance)
///           .push(MyScorer, 0.8)
///           .push(MyOtherScorer, 0.2),
///         MyAction)
/// # ;
/// # }
/// ```

#[derive(Component, Debug, Reflect)]
#[reflect(from_reflect = false)]
pub struct MeasuredScorer {
    threshold: f32,
    #[reflect(ignore)]
    measure: Arc<dyn Measure>,
    measure_string: String,
    scorers: Vec<(Scorer, f32)>,
}

impl MeasuredScorer {
    pub fn build(threshold: f32) -> MeasuredScorerBuilder {
        MeasuredScorerBuilder {
            threshold,
            measure: Arc::new(WeightedMeasure),
            measure_string: format!("{WeightedMeasure:#?}"),
            scorers: Vec::new(),
            scorer_labels: Vec::new(),
            label: None,
        }
    }
}

pub fn measured_scorers_system(
    query: Query<(Entity, &MeasuredScorer, &ScorerSpan)>,
    mut scores: Query<&mut Score>,
) {
    for (
        sos_ent,
        MeasuredScorer {
            threshold,
            measure,
            scorers: children,
            ..
        },
        _span,
    ) in query.iter()
    {
        let measured_score = measure.calculate(
            children
                .iter()
                .map(|(scorer, weight)| (scores.get(scorer.0).expect("where is it?"), *weight))
                .collect::<Vec<_>>(),
        );
        let mut score = scores.get_mut(sos_ent).expect("where did it go?");

        if measured_score < *threshold {
            score.set(0.0);
        } else {
            score.set(measured_score.clamp(0.0, 1.0));
        }
        #[cfg(feature = "trace")]
        {
            let _guard = _span.span().enter();
            trace!(
                "MeasuredScorer score: {}, from {} scores",
                score.get(),
                children.len()
            );
        }
    }
}

#[derive(Debug, Reflect)]
#[reflect(from_reflect = false)]
pub struct MeasuredScorerBuilder {
    threshold: f32,
    #[reflect(ignore)]
    measure: Arc<dyn Measure>,
    measure_string: String,
    #[reflect(ignore)]
    scorers: Vec<(Arc<dyn ScorerBuilder>, f32)>,
    scorer_labels: Vec<String>,
    label: Option<String>,
}

impl MeasuredScorerBuilder {
    /// Sets the measure to be used to combine the child scorers
    pub fn measure(mut self, measure: impl Measure + 'static) -> Self {
        self.measure_string = format!("{measure:#?}");
        self.measure = Arc::new(measure);
        self
    }

    pub fn push(mut self, scorer: impl ScorerBuilder + 'static, weight: f32) -> Self {
        if let Some(label) = scorer.label() {
            self.scorer_labels.push(label.into());
        } else {
            self.scorer_labels.push("Unnamed Scorer".into());
        }
        self.scorers.push((Arc::new(scorer), weight));
        self
    }

    /// Set a label for this ScorerBuilder.
    pub fn label(mut self, label: impl AsRef<str>) -> Self {
        self.label = Some(label.as_ref().into());
        self
    }
}

impl ScorerBuilder for MeasuredScorerBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref().or(Some("MeasuredScorer"))
    }

    #[allow(clippy::needless_collect)]
    fn build(&self, cmd: &mut Commands, scorer: Entity, actor: Entity) {
        let scorers: Vec<_> = self
            .scorers
            .iter()
            .map(|(scorer, _)| spawn_scorer(&**scorer, cmd, actor))
            .collect();
        cmd.entity(scorer)
            .add_children(&scorers[..])
            .insert(MeasuredScorer {
                threshold: self.threshold,
                measure: self.measure.clone(),
                scorers: scorers
                    .into_iter()
                    .map(Scorer)
                    .zip(self.scorers.iter().map(|(_, weight)| *weight))
                    .collect(),
                measure_string: self.measure_string.clone(),
            });
    }
}