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
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
use crate::resource::{Resource, ResourceSet, ResourceTypeId, Resources};
use crate::schedule::{Runnable, Schedulable};
use bit_set::BitSet;
use derivative::Derivative;
use fxhash::FxHashMap;
use legion_core::{
    borrow::{AtomicRefCell, RefMut},
    command::CommandBuffer,
    cons::{ConsAppend, ConsFlatten},
    filter::EntityFilter,
    index::ArchetypeIndex,
    permission::Permissions,
    query::{Query, Read, View, Write},
    storage::{Component, ComponentTypeId, TagTypeId},
    subworld::{ArchetypeAccess, SubWorld},
    world::{World, WorldId},
};
use std::any::TypeId;
use std::borrow::Cow;
use std::marker::PhantomData;
use tracing::{debug, info, span, Level};

/// Structure describing the resource and component access conditions of the system.
#[derive(Derivative, Debug, Clone)]
#[derivative(Default(bound = ""))]
pub struct SystemAccess {
    pub resources: Permissions<ResourceTypeId>,
    pub components: Permissions<ComponentTypeId>,
    pub tags: Permissions<TagTypeId>,
}

/// This trait is for providing abstraction across tuples of queries for populating the type
/// information in the system closure. This trait also provides access to the underlying query
/// information.
pub trait QuerySet: Send + Sync {
    /// Returns the archetypes accessed by this collection of queries. This allows for caching
    /// effiency and granularity for system dispatching.
    fn filter_archetypes(&mut self, world: &World, archetypes: &mut BitSet);
}

macro_rules! impl_queryset_tuple {
    ($($ty: ident),*) => {
        paste::item! {
            #[allow(unused_parens, non_snake_case)]
            impl<$([<$ty V>], [<$ty F>], )*> QuerySet for ($(Query<[<$ty V>], [<$ty F>]>, )*)
            where
                $([<$ty V>]: for<'v> View<'v>,)*
                $([<$ty F>]: EntityFilter + Send + Sync,)*
            {
                fn filter_archetypes(&mut self, world: &World, bitset: &mut BitSet) {
                    let ($($ty,)*) = self;

                    $(
                        let storage = world.storage();
                        $ty.filter.iter_archetype_indexes(storage).for_each(|ArchetypeIndex(id)| { bitset.insert(id); });
                    )*
                }
            }
        }
    };
}

impl QuerySet for () {
    fn filter_archetypes(&mut self, _: &World, _: &mut BitSet) {}
}

impl<AV, AF> QuerySet for Query<AV, AF>
where
    AV: for<'v> View<'v>,
    AF: EntityFilter + Send + Sync,
{
    fn filter_archetypes(&mut self, world: &World, bitset: &mut BitSet) {
        let storage = world.storage();
        self.filter
            .iter_archetype_indexes(storage)
            .for_each(|ArchetypeIndex(id)| {
                bitset.insert(id);
            });
    }
}

impl_queryset_tuple!(A);
impl_queryset_tuple!(A, B);
impl_queryset_tuple!(A, B, C);
impl_queryset_tuple!(A, B, C, D);
impl_queryset_tuple!(A, B, C, D, E);
impl_queryset_tuple!(A, B, C, D, E, F);
impl_queryset_tuple!(A, B, C, D, E, F, G);
impl_queryset_tuple!(A, B, C, D, E, F, G, H);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y);
impl_queryset_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SystemId {
    name: Cow<'static, str>,
    type_id: TypeId,
}

struct Unspecified;

impl SystemId {
    pub fn of<T: 'static>(name: Option<String>) -> Self {
        Self {
            name: name
                .unwrap_or_else(|| std::any::type_name::<T>().to_string())
                .into(),
            type_id: TypeId::of::<T>(),
        }
    }
}

impl std::fmt::Display for SystemId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl<T: Into<Cow<'static, str>>> From<T> for SystemId {
    fn from(name: T) -> SystemId {
        SystemId {
            name: name.into(),
            type_id: TypeId::of::<Unspecified>(),
        }
    }
}

/// The concrete type which contains the system closure provided by the user.  This struct should
/// not be instantiated directly, and instead should be created using `SystemBuilder`.
///
/// Implements `Schedulable` which is consumable by the `StageExecutor`, executing the closure.
///
/// Also handles caching of archetype information in a `BitSet`, as well as maintaining the provided
/// information about what queries this system will run and, as a result, its data access.
///
/// Queries are stored generically within this struct, and the `SystemQuery` types are generated
/// on each `run` call, wrapping the world and providing the set to the user in their closure.
pub struct System<R, Q, F>
where
    R: ResourceSet,
    Q: QuerySet,
    F: SystemFn<Resources = <R as ResourceSet>::PreparedResources, Queries = Q>,
{
    name: SystemId,
    _resources: PhantomData<R>,
    queries: AtomicRefCell<Q>,
    run_fn: AtomicRefCell<F>,
    archetypes: ArchetypeAccess,

    // These are stored statically instead of always iterated and created from the
    // query types, which would make allocations every single request
    access: SystemAccess,

    // We pre-allocate a command buffer for ourself. Writes are self-draining so we never have to rellocate.
    command_buffer: FxHashMap<WorldId, AtomicRefCell<CommandBuffer>>,
}

impl<R, Q, F> Runnable for System<R, Q, F>
where
    R: ResourceSet,
    Q: QuerySet,
    F: SystemFn<Resources = <R as ResourceSet>::PreparedResources, Queries = Q>,
{
    fn name(&self) -> &SystemId { &self.name }

    fn reads(&self) -> (&[ResourceTypeId], &[ComponentTypeId]) {
        (
            self.access.resources.reads(),
            self.access.components.reads(),
        )
    }
    fn writes(&self) -> (&[ResourceTypeId], &[ComponentTypeId]) {
        (
            self.access.resources.writes(),
            self.access.components.writes(),
        )
    }

    fn prepare(&mut self, world: &World) {
        if let ArchetypeAccess::Some(bitset) = &mut self.archetypes {
            self.queries.get_mut().filter_archetypes(world, bitset);
        }
    }

    fn accesses_archetypes(&self) -> &ArchetypeAccess { &self.archetypes }

    fn command_buffer_mut(&self, world: WorldId) -> Option<RefMut<CommandBuffer>> {
        self.command_buffer.get(&world).map(|cmd| cmd.get_mut())
    }

    unsafe fn run_unsafe(&mut self, world: &World, resources: &Resources) {
        let span = span!(Level::INFO, "System", system = %self.name);
        let _guard = span.enter();

        debug!("Initializing");
        let mut resources = R::fetch_unchecked(resources);
        let mut queries = self.queries.get_mut();
        //let mut prepared_queries = queries.prepare();
        let mut world_shim =
            SubWorld::new_unchecked(world, &self.access.components, &self.archetypes);
        let cmd = self
            .command_buffer
            .entry(world.id())
            .or_insert_with(|| AtomicRefCell::new(CommandBuffer::new(world)));

        info!(permissions = ?self.access, archetypes = ?self.archetypes, "Running");
        use std::ops::DerefMut;
        let mut borrow = self.run_fn.get_mut();
        borrow.deref_mut().run(
            &mut cmd.get_mut(),
            &mut world_shim,
            &mut resources,
            //&mut prepared_queries,
            queries.deref_mut(),
        );
    }
}

/// Supertrait used for defining systems. All wrapper objects for systems implement this trait.
///
/// This trait will generally not be used by users.
pub trait SystemFn {
    type Resources;
    type Queries;

    fn run(
        &mut self,
        commands: &mut CommandBuffer,
        world: &mut SubWorld,
        resources: &mut Self::Resources,
        queries: &mut Self::Queries,
    );
}

struct SystemFnWrapper<R, Q, F: FnMut(&mut CommandBuffer, &mut SubWorld, &mut R, &mut Q) + 'static>(
    F,
    PhantomData<(R, Q)>,
);

impl<F, R, Q> SystemFn for SystemFnWrapper<R, Q, F>
where
    F: FnMut(&mut CommandBuffer, &mut SubWorld, &mut R, &mut Q) + 'static,
{
    type Resources = R;
    type Queries = Q;

    fn run(
        &mut self,
        commands: &mut CommandBuffer,
        world: &mut SubWorld,
        resources: &mut Self::Resources,
        queries: &mut Self::Queries,
    ) {
        (self.0)(commands, world, resources, queries);
    }
}

// This builder uses a Cons/Hlist implemented in cons.rs to generated the static query types
// for this system. Access types are instead stored and abstracted in the top level vec here
// so the underlying ResourceSet type functions from the queries don't need to allocate.
// Otherwise, this leads to excessive alloaction for every call to reads/writes
/// The core builder of `System` types, which are systems within Legion. Systems are implemented
/// as singular closures for a given system - providing queries which should be cached for that
/// system, as well as resource access and other metadata.
/// ```rust
/// # use legion_core::prelude::*;
/// # use legion_systems::prelude::*;
/// # #[derive(Copy, Clone, Debug, PartialEq)]
/// # struct Position;
/// # #[derive(Copy, Clone, Debug, PartialEq)]
/// # struct Velocity;
/// # #[derive(Copy, Clone, Debug, PartialEq)]
/// # struct Model;
/// #[derive(Copy, Clone, Debug, PartialEq)]
/// struct Static;
/// #[derive(Debug)]
/// struct TestResource {}
///
///  let mut system_one = SystemBuilder::<()>::new("TestSystem")
///            .read_resource::<TestResource>()
///            .with_query(<(Read<Position>, Tagged<Model>)>::query()
///                         .filter(!tag::<Static>() | changed::<Position>()))
///            .build(move |commands, world, resource, queries| {
///               let mut count = 0;
///                {
///                    for (entity, pos) in queries.iter_entities_mut(&mut *world) {
///
///                    }
///                }
///            });
/// ```
pub struct SystemBuilder<Q = (), R = ()> {
    name: SystemId,

    queries: Q,
    resources: R,

    resource_access: Permissions<ResourceTypeId>,
    component_access: Permissions<ComponentTypeId>,
    access_all_archetypes: bool,
}

impl SystemBuilder<(), ()> {
    /// Create a new system builder to construct a new system.
    ///
    /// Please note, the `name` argument for this method is just for debugging and visualization
    /// purposes and is not logically used anywhere.
    pub fn new<T: Into<SystemId>>(name: T) -> Self {
        Self {
            name: name.into(),
            queries: (),
            resources: (),
            resource_access: Permissions::default(),
            component_access: Permissions::default(),
            access_all_archetypes: false,
        }
    }
}

impl<Q, R> SystemBuilder<Q, R>
where
    Q: 'static + Send + ConsFlatten,
    R: 'static + Send + ConsFlatten,
{
    /// Defines a query to provide this system for its execution. Multiple queries can be provided,
    /// and queries are cached internally for efficiency for filtering and archetype ID handling.
    ///
    /// It is best practice to define your queries here, to allow for the caching to take place.
    /// These queries are then provided to the executing closure as a tuple of queries.
    pub fn with_query<V, F>(
        mut self,
        query: Query<V, F>,
    ) -> SystemBuilder<<Q as ConsAppend<Query<V, F>>>::Output, R>
    where
        V: for<'a> View<'a>,
        F: 'static + EntityFilter,
        Q: ConsAppend<Query<V, F>>,
    {
        self.component_access.add(V::requires_permissions());

        SystemBuilder {
            name: self.name,
            queries: ConsAppend::append(self.queries, query),
            resources: self.resources,
            resource_access: self.resource_access,
            component_access: self.component_access,
            access_all_archetypes: self.access_all_archetypes,
        }
    }

    /// Flag this resource type as being read by this system.
    ///
    /// This will inform the dispatcher to not allow any writes access to this resource while
    /// this system is running. Parralel reads still occur during execution.
    pub fn read_resource<T>(mut self) -> SystemBuilder<Q, <R as ConsAppend<Read<T>>>::Output>
    where
        T: 'static + Resource,
        R: ConsAppend<Read<T>>,
        <R as ConsAppend<Read<T>>>::Output: ConsFlatten,
    {
        self.resource_access.push_read(ResourceTypeId::of::<T>());

        SystemBuilder {
            name: self.name,
            queries: self.queries,
            resources: ConsAppend::append(self.resources, Read::<T>::default()),
            resource_access: self.resource_access,
            component_access: self.component_access,
            access_all_archetypes: self.access_all_archetypes,
        }
    }

    /// Flag this resource type as being written by this system.
    ///
    /// This will inform the dispatcher to not allow any parallel access to this resource while
    /// this system is running.
    pub fn write_resource<T>(mut self) -> SystemBuilder<Q, <R as ConsAppend<Write<T>>>::Output>
    where
        T: 'static + Resource,
        R: ConsAppend<Write<T>>,
        <R as ConsAppend<Write<T>>>::Output: ConsFlatten,
    {
        self.resource_access.push(ResourceTypeId::of::<T>());

        SystemBuilder {
            name: self.name,
            queries: self.queries,
            resources: ConsAppend::append(self.resources, Write::<T>::default()),
            resource_access: self.resource_access,
            component_access: self.component_access,
            access_all_archetypes: self.access_all_archetypes,
        }
    }

    /// This performs a soft resource block on the component for writing. The dispatcher will
    /// generally handle dispatching read and writes on components based on archetype, allowing
    /// for more granular access and more parallelization of systems.
    ///
    /// Using this method will mark the entire component as read by this system, blocking writing
    /// systems from accessing any archetypes which contain this component for the duration of its
    /// execution.
    ///
    /// This type of access with `SubWorld` is provided for cases where sparse component access
    /// is required and searching entire query spaces for entities is inefficient.
    pub fn read_component<T>(mut self) -> Self
    where
        T: Component,
    {
        self.component_access.push_read(ComponentTypeId::of::<T>());
        self.access_all_archetypes = true;

        self
    }

    /// This performs a exclusive resource block on the component for writing. The dispatcher will
    /// generally handle dispatching read and writes on components based on archetype, allowing
    /// for more granular access and more parallelization of systems.
    ///
    /// Using this method will mark the entire component as written by this system, blocking other
    /// systems from accessing any archetypes which contain this component for the duration of its
    /// execution.
    ///
    /// This type of access with `SubWorld` is provided for cases where sparse component access
    /// is required and searching entire query spaces for entities is inefficient.
    pub fn write_component<T>(mut self) -> Self
    where
        T: Component,
    {
        self.component_access.push(ComponentTypeId::of::<T>());
        self.access_all_archetypes = true;

        self
    }

    /// Builds a standard legion `System`. A system is considered a closure for all purposes. This
    /// closure is `FnMut`, allowing for capture of variables for tracking state for this system.
    /// Instead of the classic OOP architecture of a system, this lets you still maintain state
    /// across execution of the systems while leveraging the type semantics of closures for better
    /// ergonomics.
    pub fn build<F>(self, run_fn: F) -> Box<dyn Schedulable>
    where
        <R as ConsFlatten>::Output: ResourceSet + Send + Sync,
        <Q as ConsFlatten>::Output: QuerySet + Send + Sync,
        <<R as ConsFlatten>::Output as ResourceSet>::PreparedResources: Send + Sync,
        F: FnMut(
                &mut CommandBuffer,
                &mut SubWorld,
                &mut <<R as ConsFlatten>::Output as ResourceSet>::PreparedResources,
                &mut <Q as ConsFlatten>::Output,
            ) + Send
            + Sync
            + 'static,
    {
        let run_fn = SystemFnWrapper(run_fn, PhantomData);
        Box::new(System {
            name: self.name,
            run_fn: AtomicRefCell::new(run_fn),
            _resources: PhantomData::<<R as ConsFlatten>::Output>,
            queries: AtomicRefCell::new(self.queries.flatten()),
            archetypes: if self.access_all_archetypes {
                ArchetypeAccess::All
            } else {
                ArchetypeAccess::Some(BitSet::default())
            },
            access: SystemAccess {
                resources: self.resource_access,
                components: self.component_access,
                tags: Permissions::default(),
            },
            command_buffer: FxHashMap::default(),
        })
    }

    /// Builds a system which is not `Schedulable`, as it is not thread safe (!Send and !Sync),
    /// but still implements all the calling infrastructure of the `Runnable` trait. This provides
    /// a way for legion consumers to leverage the `System` construction and type-handling of
    /// this build for thread local systems which cannot leave the main initializing thread.
    pub fn build_thread_local<F>(self, run_fn: F) -> Box<dyn Runnable>
    where
        <R as ConsFlatten>::Output: ResourceSet + Send + Sync,
        <Q as ConsFlatten>::Output: QuerySet,
        F: FnMut(
                &mut CommandBuffer,
                &mut SubWorld,
                &mut <<R as ConsFlatten>::Output as ResourceSet>::PreparedResources,
                &mut <Q as ConsFlatten>::Output,
            ) + 'static,
    {
        let run_fn = SystemFnWrapper(run_fn, PhantomData);
        Box::new(System {
            name: self.name,
            run_fn: AtomicRefCell::new(run_fn),
            _resources: PhantomData::<<R as ConsFlatten>::Output>,
            queries: AtomicRefCell::new(self.queries.flatten()),
            archetypes: if self.access_all_archetypes {
                ArchetypeAccess::All
            } else {
                ArchetypeAccess::Some(BitSet::default())
            },
            access: SystemAccess {
                resources: self.resource_access,
                components: self.component_access,
                tags: Permissions::default(),
            },
            command_buffer: FxHashMap::default(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schedule::*;
    use legion_core::prelude::*;
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Pos(f32, f32, f32);
    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Vel(f32, f32, f32);

    #[derive(Default)]
    struct TestResource(pub i32);
    #[derive(Default)]
    struct TestResourceTwo(pub i32);
    #[derive(Default)]
    struct TestResourceThree(pub i32);
    #[derive(Default)]
    struct TestResourceFour(pub i32);

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct TestComp(f32, f32, f32);
    #[derive(Clone, Copy, Debug, PartialEq)]
    struct TestCompTwo(f32, f32, f32);
    #[derive(Clone, Copy, Debug, PartialEq)]
    struct TestCompThree(f32, f32, f32);

    #[test]
    fn builder_schedule_execute() {
        let _ = tracing_subscriber::fmt::try_init();

        let universe = Universe::new();
        let mut world = universe.create_world();

        let mut resources = Resources::default();
        resources.insert(TestResource(123));
        resources.insert(TestResourceTwo(123));

        let components = vec![
            (Pos(1., 2., 3.), Vel(0.1, 0.2, 0.3)),
            (Pos(4., 5., 6.), Vel(0.4, 0.5, 0.6)),
        ];

        let mut expected = HashMap::<Entity, (Pos, Vel)>::new();

        for (i, e) in world.insert((), components.clone()).iter().enumerate() {
            if let Some((pos, rot)) = components.get(i) {
                expected.insert(*e, (*pos, *rot));
            }
        }

        #[derive(Debug, Eq, PartialEq)]
        pub enum TestSystems {
            TestSystemOne,
            TestSystemTwo,
            TestSystemThree,
            TestSystemFour,
        }

        let runs = Arc::new(Mutex::new(Vec::new()));

        let system_one_runs = runs.clone();
        let system_one = SystemBuilder::<()>::new("TestSystem1")
            .read_resource::<TestResource>()
            .with_query(Read::<Pos>::query())
            .with_query(Write::<Vel>::query())
            .build(move |_commands, _world, _resource, _queries| {
                tracing::trace!("system_one");
                system_one_runs
                    .lock()
                    .unwrap()
                    .push(TestSystems::TestSystemOne);
            });

        let system_two_runs = runs.clone();
        let system_two = SystemBuilder::<()>::new("TestSystem2")
            .write_resource::<TestResourceTwo>()
            .with_query(Read::<Vel>::query())
            .build(move |_commands, _world, _resource, _queries| {
                tracing::trace!("system_two");
                system_two_runs
                    .lock()
                    .unwrap()
                    .push(TestSystems::TestSystemTwo);
            });

        let system_three_runs = runs.clone();
        let system_three = SystemBuilder::<()>::new("TestSystem3")
            .read_resource::<TestResourceTwo>()
            .with_query(Read::<Vel>::query())
            .build(move |_commands, _world, _resource, _queries| {
                tracing::trace!("system_three");
                system_three_runs
                    .lock()
                    .unwrap()
                    .push(TestSystems::TestSystemThree);
            });
        let system_four_runs = runs.clone();
        let system_four = SystemBuilder::<()>::new("TestSystem4")
            .write_resource::<TestResourceTwo>()
            .with_query(Read::<Vel>::query())
            .build(move |_commands, _world, _resource, _queries| {
                tracing::trace!("system_four");
                system_four_runs
                    .lock()
                    .unwrap()
                    .push(TestSystems::TestSystemFour);
            });

        let order = vec![
            TestSystems::TestSystemOne,
            TestSystems::TestSystemTwo,
            TestSystems::TestSystemThree,
            TestSystems::TestSystemFour,
        ];

        let systems = vec![system_one, system_two, system_three, system_four];

        let mut executor = Executor::new(systems);
        executor.execute(&mut world, &mut resources);

        assert_eq!(*(runs.lock().unwrap()), order);
    }

    #[test]
    fn builder_create_and_execute() {
        let _ = tracing_subscriber::fmt::try_init();

        let universe = Universe::new();
        let mut world = universe.create_world();

        let mut resources = Resources::default();
        resources.insert(TestResource(123));

        let components = vec![
            (Pos(1., 2., 3.), Vel(0.1, 0.2, 0.3)),
            (Pos(4., 5., 6.), Vel(0.4, 0.5, 0.6)),
        ];

        let mut expected = HashMap::<Entity, (Pos, Vel)>::new();

        for (i, e) in world.insert((), components.clone()).iter().enumerate() {
            if let Some((pos, rot)) = components.get(i) {
                expected.insert(*e, (*pos, *rot));
            }
        }

        let mut system = SystemBuilder::<()>::new("TestSystem")
            .read_resource::<TestResource>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_commands, world, resource, queries| {
                assert_eq!(resource.0, 123);
                let mut count = 0;
                {
                    for (entity, pos) in queries.0.iter_entities(world) {
                        assert_eq!(expected.get(&entity).unwrap().0, *pos);
                        count += 1;
                    }
                }

                assert_eq!(components.len(), count);
            });
        system.prepare(&world);
        system.run(&mut world, &mut resources);
    }

    #[test]
    fn fnmut_stateful_system_test() {
        let _ = tracing_subscriber::fmt::try_init();

        let universe = Universe::new();
        let mut world = universe.create_world();

        let mut resources = Resources::default();
        resources.insert(TestResource(123));

        let components = vec![
            (Pos(1., 2., 3.), Vel(0.1, 0.2, 0.3)),
            (Pos(4., 5., 6.), Vel(0.4, 0.5, 0.6)),
        ];

        let mut expected = HashMap::<Entity, (Pos, Vel)>::new();

        for (i, e) in world.insert((), components.clone()).iter().enumerate() {
            if let Some((pos, rot)) = components.get(i) {
                expected.insert(*e, (*pos, *rot));
            }
        }

        let mut system = SystemBuilder::<()>::new("TestSystem")
            .read_resource::<TestResource>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_, _, _, _| {});

        system.prepare(&world);
        system.run(&mut world, &mut resources);
    }

    #[test]
    fn system_mutate_archetype() {
        let _ = tracing_subscriber::fmt::try_init();

        let universe = Universe::new();
        let mut world = universe.create_world();
        let mut resources = Resources::default();

        #[derive(Default, Clone, Copy)]
        pub struct Balls(u32);

        let components = vec![
            (Pos(1., 2., 3.), Vel(0.1, 0.2, 0.3)),
            (Pos(4., 5., 6.), Vel(0.4, 0.5, 0.6)),
        ];

        let mut expected = HashMap::<Entity, (Pos, Vel)>::new();

        for (i, e) in world.insert((), components.clone()).iter().enumerate() {
            if let Some((pos, rot)) = components.get(i) {
                expected.insert(*e, (*pos, *rot));
            }
        }

        let expected_copy = expected.clone();
        let mut system = SystemBuilder::<()>::new("TestSystem")
            .with_query(<(Read<Pos>, Read<Vel>)>::query())
            .build(move |_, world, _, query| {
                let mut count = 0;
                {
                    for (entity, (pos, vel)) in query.iter_entities(world) {
                        assert_eq!(expected_copy.get(&entity).unwrap().0, *pos);
                        assert_eq!(expected_copy.get(&entity).unwrap().1, *vel);
                        count += 1;
                    }
                }

                assert_eq!(components.len(), count);
            });

        system.prepare(&world);
        system.run(&mut world, &mut resources);

        world
            .add_component(*(expected.keys().nth(0).unwrap()), Balls::default())
            .unwrap();

        system.prepare(&world);
        system.run(&mut world, &mut resources);
    }

    #[test]
    fn system_mutate_archetype_buffer() {
        let _ = tracing_subscriber::fmt::try_init();

        let universe = Universe::new();
        let mut world = universe.create_world();
        let mut resources = Resources::default();

        #[derive(Default, Clone, Copy)]
        pub struct Balls(u32);

        let components = (0..30000)
            .map(|_| (Pos(1., 2., 3.), Vel(0.1, 0.2, 0.3)))
            .collect::<Vec<_>>();

        let mut expected = HashMap::<Entity, (Pos, Vel)>::new();

        for (i, e) in world.insert((), components.clone()).iter().enumerate() {
            if let Some((pos, rot)) = components.get(i) {
                expected.insert(*e, (*pos, *rot));
            }
        }

        let expected_copy = expected.clone();
        let mut system = SystemBuilder::<()>::new("TestSystem")
            .with_query(<(Read<Pos>, Read<Vel>)>::query())
            .build(move |command_buffer, world, _, query| {
                let mut count = 0;
                {
                    for (entity, (pos, vel)) in query.iter_entities(world) {
                        assert_eq!(expected_copy.get(&entity).unwrap().0, *pos);
                        assert_eq!(expected_copy.get(&entity).unwrap().1, *vel);
                        count += 1;

                        command_buffer.add_component(entity, Balls::default());
                    }
                }

                assert_eq!(components.len(), count);
            });

        system.prepare(&world);
        system.run(&mut world, &mut resources);

        system
            .command_buffer_mut(world.id())
            .unwrap()
            .write(&mut world);

        system.prepare(&world);
        system.run(&mut world, &mut resources);
    }

    #[test]
    #[cfg(feature = "par-schedule")]
    fn par_res_write() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let _ = tracing_subscriber::fmt::try_init();

        #[derive(Default)]
        struct AtomicRes(AtomicRefCell<AtomicUsize>);

        let universe = Universe::new();
        let mut world = universe.create_world();

        let mut resources = Resources::default();
        resources.insert(AtomicRes::default());

        let system1 = SystemBuilder::<()>::new("TestSystem1")
            .write_resource::<AtomicRes>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_, _, resource, _| {
                resource.0.get_mut().fetch_add(1, Ordering::SeqCst);
            });

        let system2 = SystemBuilder::<()>::new("TestSystem2")
            .write_resource::<AtomicRes>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_, _, resource, _| {
                resource.0.get_mut().fetch_add(1, Ordering::SeqCst);
            });

        let system3 = SystemBuilder::<()>::new("TestSystem3")
            .write_resource::<AtomicRes>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_, _, resource, _| {
                resource.0.get_mut().fetch_add(1, Ordering::SeqCst);
            });

        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(8)
            .build()
            .unwrap();

        tracing::debug!(
            reads = ?system1.reads(),
            writes = ?system1.writes(),
            "System access"
        );

        let systems = vec![system1, system2, system3];
        let mut executor = Executor::new(systems);
        pool.install(|| {
            for _ in 0..1000 {
                executor.execute(&mut world, &mut resources);
            }
        });

        assert_eq!(
            resources
                .get::<AtomicRes>()
                .unwrap()
                .0
                .get()
                .load(Ordering::SeqCst),
            3 * 1000,
        );
    }

    #[test]
    #[cfg(feature = "par-schedule")]
    fn par_res_readwrite() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let _ = tracing_subscriber::fmt::try_init();

        #[derive(Default)]
        struct AtomicRes(AtomicRefCell<AtomicUsize>);

        let universe = Universe::new();
        let mut world = universe.create_world();

        let mut resources = Resources::default();
        resources.insert(AtomicRes::default());

        let system1 = SystemBuilder::<()>::new("TestSystem1")
            .read_resource::<AtomicRes>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_, _, resource, _| {
                resource.0.get().fetch_add(1, Ordering::SeqCst);
            });

        let system2 = SystemBuilder::<()>::new("TestSystem2")
            .write_resource::<AtomicRes>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_, _, resource, _| {
                resource.0.get_mut().fetch_add(1, Ordering::SeqCst);
            });

        let system3 = SystemBuilder::<()>::new("TestSystem3")
            .write_resource::<AtomicRes>()
            .with_query(Read::<Pos>::query())
            .with_query(Read::<Vel>::query())
            .build(move |_, _, resource, _| {
                resource.0.get_mut().fetch_add(1, Ordering::SeqCst);
            });

        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(8)
            .build()
            .unwrap();

        tracing::debug!(
            reads = ?system1.reads(),
            writes = ?system1.writes(),
            "System access"
        );

        let systems = vec![system1, system2, system3];
        let mut executor = Executor::new(systems);
        pool.install(|| {
            for _ in 0..1000 {
                executor.execute(&mut world, &mut resources);
            }
        });
    }

    #[test]
    #[cfg(feature = "par-schedule")]
    #[allow(clippy::float_cmp)]
    fn par_comp_readwrite() {
        let _ = tracing_subscriber::fmt::try_init();

        let universe = Universe::new();
        let mut world = universe.create_world();

        #[derive(Clone, Copy, Debug, PartialEq)]
        struct Comp1(f32, f32, f32);
        #[derive(Clone, Copy, Debug, PartialEq)]
        struct Comp2(f32, f32, f32);

        let components = vec![
            (Comp1(69., 69., 69.), Comp2(69., 69., 69.)),
            (Comp1(69., 69., 69.), Comp2(69., 69., 69.)),
        ];

        let mut expected = HashMap::<Entity, (Comp1, Comp2)>::new();

        for (i, e) in world.insert((), components.clone()).iter().enumerate() {
            if let Some((pos, rot)) = components.get(i) {
                expected.insert(*e, (*pos, *rot));
            }
        }

        let system1 = SystemBuilder::<()>::new("TestSystem1")
            .with_query(<(Read<Comp1>, Read<Comp2>)>::query())
            .build(move |_, world, _, query| {
                query.iter(world).for_each(|(one, two)| {
                    assert_eq!(one.0, 69.);
                    assert_eq!(one.1, 69.);
                    assert_eq!(one.2, 69.);

                    assert_eq!(two.0, 69.);
                    assert_eq!(two.1, 69.);
                    assert_eq!(two.2, 69.);
                });
            });

        let system2 = SystemBuilder::<()>::new("TestSystem2")
            .with_query(<(Write<Comp1>, Read<Comp2>)>::query())
            .build(move |_, world, _, query| {
                query.iter_mut(world).for_each(|(mut one, two)| {
                    one.0 = 456.;
                    one.1 = 456.;
                    one.2 = 456.;

                    assert_eq!(two.0, 69.);
                    assert_eq!(two.1, 69.);
                    assert_eq!(two.2, 69.);
                });
            });

        let system3 = SystemBuilder::<()>::new("TestSystem3")
            .with_query(<(Write<Comp1>, Write<Comp2>)>::query())
            .build(move |_, world, _, query| {
                query.iter_mut(world).for_each(|(mut one, mut two)| {
                    assert_eq!(one.0, 456.);
                    assert_eq!(one.1, 456.);
                    assert_eq!(one.2, 456.);

                    assert_eq!(two.0, 69.);
                    assert_eq!(two.1, 69.);
                    assert_eq!(two.2, 69.);

                    one.0 = 789.;
                    one.1 = 789.;
                    one.2 = 789.;

                    two.0 = 789.;
                    two.1 = 789.;
                    two.2 = 789.;
                });
            });

        let system4 = SystemBuilder::<()>::new("TestSystem4")
            .with_query(<(Read<Comp1>, Read<Comp2>)>::query())
            .build(move |_, world, _, query| {
                query.iter(world).for_each(|(one, two)| {
                    assert_eq!(one.0, 789.);
                    assert_eq!(one.1, 789.);
                    assert_eq!(one.2, 789.);

                    assert_eq!(two.0, 789.);
                    assert_eq!(two.1, 789.);
                    assert_eq!(two.2, 789.);
                });
            });

        let system5 = SystemBuilder::<()>::new("TestSystem5")
            .with_query(<(Write<Comp1>, Write<Comp2>)>::query())
            .build(move |_, world, _, query| {
                query.iter_mut(world).for_each(|(mut one, mut two)| {
                    assert_eq!(one.0, 789.);
                    assert_eq!(one.1, 789.);
                    assert_eq!(one.2, 789.);

                    assert_eq!(two.0, 789.);
                    assert_eq!(two.1, 789.);
                    assert_eq!(two.2, 789.);

                    one.0 = 69.;
                    one.1 = 69.;
                    one.2 = 69.;

                    two.0 = 69.;
                    two.1 = 69.;
                    two.2 = 69.;
                });
            });

        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(8)
            .build()
            .unwrap();

        tracing::debug!(
            reads = ?system1.reads(),
            writes = ?system1.writes(),
            "System access"
        );

        let systems = vec![system1, system2, system3, system4, system5];
        let mut executor = Executor::new(systems);
        pool.install(|| {
            for _ in 0..1000 {
                executor.execute(&mut world, &mut Resources::default());
            }
        });
    }

    #[test]
    fn split_world() {
        let mut world = World::new();

        let system = SystemBuilder::new("split worlds")
            .with_query(Write::<usize>::query())
            .with_query(Write::<bool>::query())
            .build(|_, world, _, (query_a, query_b)| {
                let (mut left, mut right) = world.split_for_query(&query_a);
                for _ in query_a.iter_mut(&mut left) {
                    let _ = query_b.iter_mut(&mut right);
                }
            });

        let mut schedule = Schedule::builder().add_system(system).build();
        schedule.execute(&mut world, &mut Resources::default());
    }

    #[test]
    fn split_world2() {
        let system = SystemBuilder::new("system")
            .with_query(<(Read<usize>, Write<isize>)>::query())
            .write_component::<bool>()
            .build_thread_local(move |_, world, _, query| {
                let (_, mut world) = world.split_for_query(&query);
                let (_, _) = world.split::<Write<bool>>();
            });

        let mut schedule = Schedule::builder().add_thread_local(system).build();

        let mut world = World::new();
        schedule.execute(&mut world, &mut Resources::default());
    }

    #[test]
    fn overlapped_reads() {
        let _ = tracing_subscriber::fmt::try_init();

        #[derive(Debug)]
        struct Money(f64);
        #[derive(Debug)]
        struct Health(f64);
        struct Food(f64);

        let universe = Universe::new();
        let mut world = universe.create_world();

        world.insert((), vec![(Money(5.0), Food(5.0))]);

        world.insert(
            (),
            vec![
                (Money(4.0), Health(3.0)),
                (Money(4.0), Health(3.0)),
                (Money(4.0), Health(3.0)),
            ],
        );

        let show_me_the_money = SystemBuilder::new("money_show")
            .with_query(<(Read<Money>, Read<Food>)>::query())
            .build(|_, world, _, query| {
                for (money, _food) in query.iter(world) {
                    info!("Look at my money {:?}", money);
                }
            });

        let health_conscious = SystemBuilder::new("healthy")
            .with_query(<(Read<Money>, Read<Health>)>::query())
            .build(|_, world, _, query| {
                for (_money, health) in query.iter(world) {
                    info!("So healthy {:?}", health);
                }
            });

        let mut schedule = Schedule::builder()
            .add_system(show_me_the_money)
            .flush()
            .add_system(health_conscious)
            .flush()
            .build();

        let mut resources = Resources::default();
        schedule.execute(&mut world, &mut resources);
    }
}