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
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
//! Keeshond's very own ECS framework, and where all the action in your game takes place

pub mod iter;

use bitflags::bitflags;
use downcast_rs::Downcast;
use rustc_hash::FxHasher;
use bit_set::BitSet;
use bitarray_set::BitArraySet;
use smallvec::SmallVec;

use strum::EnumCount;
use strum_macros::{EnumCount, EnumString};
use generic_array::{GenericArray, sequence::GenericSequence};
use generic_array::typenum::U1024;
use typenum::Unsigned;

#[cfg(feature = "imgui_feature")]
use imgui;

use serde::{Serialize, Deserialize};

use std::any::TypeId;
use std::cell::{RefCell, RefMut, Ref, BorrowMutError, BorrowError};
use std::collections::{HashMap, VecDeque};
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use std::hash::BuildHasherDefault;
use std::str::FromStr;

use crate::datapack::DataMultistore;
use crate::gameloop::GameControl;
use crate::renderer::{DrawControl, DrawTransform};
use crate::scene::iter::{ComponentAllIter, ComponentAllIterMut, ComponentIter, ComponentIterMut, ComponentFilterIter, ComponentFilterIterMut};

#[cfg(feature = "imgui_feature")]
use std::marker::PhantomData;

type ComponentTypeMax = U1024;

const MAX_RESERVE_CAPACITY_HINT : usize = 2097152;
const CHUNKED_VEC_CHUNK_SIZE : usize = 1024; // Size of a 4kB memory page

/// Helper macro to define an enum of different spawnable objects. Basic format:
///
#[cfg(not(doctest))]
/// ```
/// keeshond::spawnables!
/// {
///     SpawnId;
///     Coin,
///     Dragon : path::to::Dragon,
///     Key : path::to::Key
/// }
/// ```
///
/// The first item, `SpawnId`, is the type name for the enum. After the semicolon is a comma-separated
///  list of different spawnable objects. Each object name may optionally be followed by a colon and
///  a path to a struct that implements [SpawnableConfig]. This allows defining the
///  [Components](Component) for the spawnable in a different module.
#[macro_export] macro_rules! spawnables
{
    [$name:ident; $($item:ident $(: $spawnstruct:ty)?),*] =>
    {
        #[derive(Copy, Clone, keeshond::crate_reexport::strum_macros::EnumString, keeshond::crate_reexport::strum_macros::EnumCount)]
        #[strum(crate = "keeshond::crate_reexport::strum")]
        pub enum $name
        {
            $( $item, )*
        }

        impl Into<usize> for $name
        {
            fn into(self) -> usize
            {
                self as usize
            }
        }

        impl keeshond::scene::SpawnableEnum for $name
        {
            fn spawn(&self, spawn : &mut SpawnControl, game : &mut GameControl,
                x : f64, y : f64, args : &DynArgList)
            {
                match &self
                {
                    $( $name::$item =>
                    {
                        $(
                            <$spawnstruct>::spawn(spawn, game, x, y, args);
                        )?
                    })*
                }
            }
        }

        const _ : () =
        {
            fn assert_spawnable_config<T : keeshond::scene::SpawnableConfig>() {}
            fn assert_all()
            {
                $(
                    //$item
                    $(
                        assert_spawnable_config::<$spawnstruct>();
                    )?
                )*
            }
        };
    }
}

#[macro_export] macro_rules! darg
{
    [$( $item:expr ),*] =>
    {{
        let mut args = DynArgList::new();
        $( args.push($item.into()); )*
        args
    }};
}

#[macro_export] macro_rules! darg_named
{
    [$( $item:expr ),*;$($name:expr => $nameditem:expr),*] =>
    {{
        let mut args = DynArgList::new();
        $( args.push($item.into()); )*
        $( args.push_named(String::from($name), $nameditem.into()); )*
        args
    }};
}


////////////////////////////////////////////////////////////

/// A handle to a living object in a [Scene]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Clone)]
pub struct Entity
{
    #[serde(rename = "i")]
    #[serde(alias = "id")]
    id : usize,
    #[serde(rename = "g")]
    #[serde(alias = "generation")]
    generation : u64
}

impl Entity
{
    /// Creates a new Entity with the given ID and generation value. You don't normally need to
    /// call this directly. Instead, use [Scene::add_entity()].
    pub fn new(id : usize, generation : u64) -> Entity
    {
        Entity { id, generation }
    }

    /// Creates a "null" Entity that refers to no object in particular.
    pub fn null() -> Entity
    {
        Entity { id : 0, generation : 0 }
    }
    
    /// Returns this Entity's identifier, used for indexing operations. ID values may be reused
    /// with other Entities, though only one Entity with a given ID may be alive at a time.
    #[inline(always)]
    pub fn id(&self) -> usize
    {
        self.id
    }
    
    /// Returns this Entity's generation. This is incremented by one every time an Entity
    /// is removed and put back into the pool for reuse. When querying based on Entity,
    /// both the id and generation must match. This prevents the use of stale Entity handlers.
    #[inline(always)]
    pub fn generation(&self) -> u64
    {
        self.generation
    }

    /// Return true if this is a "null" Entity that refers to no object.
    #[inline(always)]
    pub fn is_null(&self) -> bool
    {
        self.generation == 0
    }
}

impl Display for Entity
{
    // This trait requires `fmt` with this exact signature.
    fn fmt(&self, formatter: &mut Formatter) -> std::fmt::Result
    {
        if self.generation == 0
        {
            write!(formatter, "null")
        }
        else
        {
            write!(formatter, "{}:{}", self.id, self.generation)
        }
    }
}

impl Default for Entity
{
    fn default() -> Self
    {
        Entity::null()
    }
}

/// A data struct which may be added to an [Entity]
pub trait Component
{
    /// Whether to maintain insertion order when removing components. By default, the slower method
    /// that maintains ordering is used. The performance penalty is based on the size of the data
    /// in the component type, so it is a good idea to disable this for larger components that
    /// don't need strict ordering, as the faster swap removal method is used. Keep in mind that
    /// this will disturb the iteration order of the components in the store.
    fn maintain_ordering() -> bool where Self : Sized { true }
    
    /// How many components of this type that memory should be reserved for in advance.
    fn capacity_hint() -> usize where Self : Sized { 0 }

    /// The priority used to determine which component types are added to the scene first when
    ///  doing deferred spawns. Lower numbers are added first.
    fn add_priority() -> i32 where Self : Sized { 0 }
}

pub trait ComponentRef<'a>
{
    /// Reference type to return when retrieving or iterating over the component via [ComponentStore]
    type StoreRef;

    /// Used to get a reference type for this object when retrieving or iterating over the
    ///  component via [ComponentStore]
    fn store_get(&'a self) -> Self::StoreRef;
}

pub trait ComponentRefMut<'a>
{
    /// Reference type to return when mutably retrieving or iterating over the component via [ComponentStore]
    type StoreRefMut;

    /// Used to get a mutable reference type for this object when retrieving or iterating over the
    ///  component via [ComponentStore]
    fn store_get_mut(&'a mut self) -> Self::StoreRefMut;
}

// A struct that contains both an entity and a component, for passing entity-component pairs around
pub struct EntityComponent<C : Component + 'static>
{
    pub entity : Entity,
    pub component : C
}

pub struct ThinkerArgs<'a, T : SceneType + 'static>
{
    pub components : &'a mut ComponentControl,
    pub scene : &'a mut SceneControl<T>,
    pub game : &'a mut GameControl
}

pub struct DrawerArgs<'a>
{
    pub components : &'a ComponentControl,
    pub resources : &'a DataMultistore,
    pub drawing : &'a mut Box<dyn DrawControl>,
    pub transform : &'a DrawTransform,
    pub interpolation : f32
}

/// A system that runs game logic every frame, typically giving [Entities](Entity) behaviors based
/// on which [Components](Component) they have.
pub trait ThinkerSystem<T : SceneType + 'static>
{
    /// Called before the first frame of logic processing. You can use this to spawn in objects and
    ///  do any other necessary setup.
    #[allow(unused_variables)]
    fn start(&mut self, args : ThinkerArgs<T>) {}
    /// Called after [ThinkerSystem::start()] but before the first frame of logic processing. This
    ///  is useful if you need to do initialization tasks after any deferred actions such as
    ///  object spawning.
    #[allow(unused_variables)]
    fn start_late(&mut self, args : ThinkerArgs<T>) {}
    /// Called once every logic frame. This is where you do your main processing.
    fn think(&mut self, args : ThinkerArgs<T>);
    /// Called when the scene is ending, such as when the gameloop is switching to a new scene.
    ///  This is a good place to do resource cleanup, save settings and persistent data, or other
    ///  tasks.
    #[allow(unused_variables)]
    fn end(&mut self, args : ThinkerArgs<T>) {}
    /// Used to determine the order of execution of each [ThinkerSystem]. Lower number priority
    ///  systems are executed first.
    fn priority(&self) -> i32 { 0 }
}

/// A system that handles drawing logic every frame, typically giving [Entities](Entity) behaviors based
/// on which [Components](Component) they have. Mutable access to the [Components](Component) is not
/// permitted, as this could lead to behavior that is framerate-dependent.
pub trait DrawerSystem
{
    /// Called once every render frame. This is where you draw your sprites and other graphics.
    ///  This may be called multiple times between logic frames if frame interpolation is available.
    ///  In such a scenario, use the value in [DrawerArgs::interpolation] to perform this
    ///  interpolation.
    fn draw(&self, args : DrawerArgs);
    /// Used to determine the order of execution of each [DrawerSystem]. Lower number priority
    ///  systems are executed first.
    fn priority(&self) -> i32 { 0 }
}

#[cfg(feature = "imgui_feature")]
pub trait ImGuiSystem<T : SceneType + 'static>
{
    #[allow(unused_variables)]
    fn start(&mut self, args : ThinkerArgs<T>) {}
    fn imgui_think(&mut self, ui : &mut imgui::Ui, args : ThinkerArgs<T>);
    #[allow(unused_variables)]
    fn end(&mut self, args : ThinkerArgs<T>) {}
}

#[cfg(feature = "imgui_feature")]
struct NullImGuiSystem<T : SceneType + 'static>
{
    _phantom : PhantomData<T>
}

#[cfg(feature = "imgui_feature")]
impl<T : SceneType + 'static> ImGuiSystem<T> for NullImGuiSystem<T>
{
    #[allow(unused_variables)]
    fn imgui_think(&mut self, ui : &mut imgui::Ui, args : ThinkerArgs<T>) {}
}

////////////////////////////////////////////////////////////


#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum DynArg
{
    Empty,
    Bool(bool),
    Int(i32),
    Float(f64),
    Entity(Entity),
    String(String)
}

impl From<bool> for DynArg
{
    fn from(value : bool) -> Self
    {
        DynArg::Bool(value)
    }
}

impl From<i32> for DynArg
{
    fn from(value : i32) -> Self
    {
        DynArg::Int(value)
    }
}

impl From<f64> for DynArg
{
    fn from(value : f64) -> Self
    {
        DynArg::Float(value)
    }
}

impl From<&str> for DynArg
{
    fn from(value : &str) -> Self
    {
        DynArg::String(value.to_string())
    }
}

impl From<String> for DynArg
{
    fn from(value : String) -> Self
    {
        DynArg::String(value)
    }
}

impl From<Entity> for DynArg
{
    fn from(value : Entity) -> Self
    {
        DynArg::Entity(value.clone())
    }
}

impl DynArg
{
    pub fn from_value_str(input : &str) -> DynArg
    {
        if input.starts_with('\"') && input.ends_with('\"')
        {
            return DynArg::String(input[1..input.len() - 1].to_string())
        }
        else if input == "true"
        {
            return DynArg::Bool(true);
        }
        else if input == "false"
        {
            return DynArg::Bool(false);
        }
        else if let Ok(value) = input.parse::<i32>()
        {
            return DynArg::Int(value);
        }
        else if let Ok(value) = input.parse::<f64>()
        {
            return DynArg::Float(value);
        }

        DynArg::Empty
    }

    pub fn to_value_string(&self) -> String
    {
        match self
        {
            DynArg::Empty => { String::new() }
            DynArg::Bool(value) => { value.to_string() }
            DynArg::Int(value) => { value.to_string() }
            DynArg::Float(value) =>
            {
                if value.fract() == 0.0
                {
                    return format!("{}.0", value);
                }

                return value.to_string();
            }
            DynArg::String(value) => { format!("\"{}\"", value) }
            DynArg::Entity(value) => { value.to_string() }
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DynArgList
{
    list : SmallVec<[DynArg; 8]>,
    named : HashMap<String, DynArg, BuildHasherDefault<FxHasher>>
}

impl DynArgList
{
    pub fn new() -> DynArgList
    {
        DynArgList
        {
            list : SmallVec::new(),
            named : HashMap::with_hasher(BuildHasherDefault::<FxHasher>::default())
        }
    }

    pub fn from_vec(vec_list : Vec<DynArg>) -> DynArgList
    {
        DynArgList
        {
            list : SmallVec::from_vec(vec_list),
            named : HashMap::with_hasher(BuildHasherDefault::<FxHasher>::default())
        }
    }

    pub fn to_vec_named(&self) -> (Vec<DynArg>, Vec<(String, DynArg)>)
    {
        let numbered = self.list.to_vec();
        let mut named = Vec::new();

        for (name, args) in &self.named
        {
            named.push((name.clone(), args.clone()));
        }

        named.sort_by(|a, b| a.0.cmp(&b.0));

        (numbered, named)
    }

    pub fn is_empty(&self) -> bool
    {
        self.list.is_empty() && self.named.is_empty()
    }

    pub fn set_numbered(&mut self, vec_list : Vec<DynArg>)
    {
        self.list = SmallVec::from_vec(vec_list);
    }

    pub fn push(&mut self, arg : DynArg) -> &mut Self
    {
        self.list.push(arg);

        self
    }

    pub fn push_named(&mut self, name : String, arg : DynArg) -> &mut Self
    {
        self.named.insert(name, arg);

        self
    }

    pub fn remove_named(&mut self, name : &str) -> &mut Self
    {
        self.named.remove(name);

        self
    }

    pub fn get(&self, index : usize) -> Option<&DynArg>
    {
        self.list.get(index)
    }

    pub fn get_named(&self, name : &str) -> Option<&DynArg>
    {
        self.named.get(name)
    }

    pub fn get_bool(&self, index : usize, default : bool) -> bool
    {
        if let Some(&DynArg::Bool(value)) = self.list.get(index) { return value; }

        default
    }

    pub fn get_int(&self, index : usize, default : i32) -> i32
    {
        if let Some(&DynArg::Int(value)) = self.list.get(index) { return value; }

        default
    }

    pub fn get_float(&self, index : usize, default : f64) -> f64
    {
        if let Some(&DynArg::Float(value)) = self.list.get(index) { return value; }

        default
    }

    pub fn get_string<'a>(&'a self, index : usize, default : &'a str) -> &'a str
    {
        if let Some(&DynArg::String(value)) = self.list.get(index).as_ref() { return &value; }

        default
    }

    pub fn get_entity(&self, index : usize, default : Entity) -> Entity
    {
        if let Some(DynArg::Entity(value)) = self.list.get(index) { return value.clone(); }

        default
    }

    pub fn get_bool_named(&self, name : &str, default : bool) -> bool
    {
        if let Some(&DynArg::Bool(value)) = self.named.get(name) { return value; }

        default
    }

    pub fn get_int_named(&self, name : &str, default : i32) -> i32
    {
        if let Some(&DynArg::Int(value)) = self.named.get(name) { return value; }

        default
    }

    pub fn get_float_named(&self, name : &str, default : f64) -> f64
    {
        if let Some(&DynArg::Float(value)) = self.named.get(name) { return value; }

        default
    }

    pub fn get_string_named<'a>(&'a self, name : &str, default : &'a str) -> &'a str
    {
        if let Some(&DynArg::String(value)) = self.named.get(name).as_ref() { return &value; }

        default
    }

    pub fn get_entity_named(&self, name : &str, default : Entity) -> Entity
    {
        if let Some(DynArg::Entity(value)) = self.named.get(name) { return value.clone(); }

        default
    }

    pub fn count(&self) -> usize
    {
        self.list.len()
    }
}

impl From<DynArg> for DynArgList
{
    fn from(arg : DynArg) -> Self
    {
        let mut list = SmallVec::new();
        list.push(arg);

        DynArgList
        {
            list,
            named : HashMap::with_hasher(BuildHasherDefault::<FxHasher>::default())
        }
    }
}

impl From<Vec<DynArg>> for DynArgList
{
    fn from(value : Vec<DynArg>) -> Self
    {
        DynArgList::from_vec(value)
    }
}

/// An enum that identifies spawnables. It is recommended that you use the [spawnables!] macro to
///  define this.
pub trait SpawnableEnum : Copy + Clone + FromStr + EnumCount + Into<usize>
{
    /// Used to construct a set of [Components](Component) for the associated spawnable type.
    ///  It is recommended that you use the [spawnables!] macro instead of implementing this
    ///  function (or trait) yourself.
    #[allow(unused_variables)]
    fn spawn(&self, spawn : &mut SpawnControl, game : &mut GameControl,
             x : f64, y : f64, args : &DynArgList) {}
}

pub trait SpawnableConfig
{
    /// Used to construct a set of [Components](Component) for the associated spawnable type.
    ///  This is often preferable to defining the [Components](Component) in [SceneType::spawn()]
    ///  as you can put the logic in a separate module.
    fn spawn(spawn : &mut SpawnControl, game : &mut GameControl,
                 x : f64, y : f64, args : &DynArgList);
}


trait ComponentStoreBase : Downcast
{
    fn preview_remove_entity(&mut self, entity : &Entity) -> bool;
    fn do_remove_entity(&mut self, entity : &Entity);
    fn purge_entities(&mut self);
    fn do_set_frozen(&mut self, entity : &Entity, freeze_flags : FreezeFlags, freeze : bool);
}
impl_downcast!(ComponentStoreBase);

struct NullComponentStore {}

impl ComponentStoreBase for NullComponentStore
{
    fn preview_remove_entity(&mut self, _entity: &Entity) -> bool
    {
        false
    }
    fn do_remove_entity(&mut self, _entity: &Entity) {}
    fn purge_entities(&mut self) {}
    fn do_set_frozen(&mut self, _entity : &Entity, _freeze_flags : FreezeFlags, _freeze : bool) {}
}

bitflags!
{
    /// Bit field that indicates for which reasons, if any, a component is frozen
    pub struct FreezeFlags : u16
    {
        /// Component is frozen due to a simulation pause
        ///  (it's strongly recommended to use nested scenes instead if you want to pause your game,
        ///  both for correctness and performance reasons)
        const REASON_PAUSE = 0b0000_0000_0000_0001;
        /// Component is frozen due to a special effect such as a hitstun or special attack flourish
        const REASON_EFFECT = 0b0000_0000_0000_0010;
        /// Component is frozen because it is too far outside the view
        const REASON_CULLED = 0b0000_0000_0000_0100;
        /// Component is frozen because it is hidden (even though it may be inside the view)
        const REASON_HIDDEN = 0b0000_0000_0000_1000;
        /// Component is frozen due to a custom behavior toggle (1)
        const REASON_BEHAVIOR_1 = 0b0000_0000_0001_0000;
        /// Component is frozen due to a custom behavior toggle (2)
        const REASON_BEHAVIOR_2 = 0b0000_0000_0010_0000;
        /// Component is frozen due to a custom behavior toggle (3)
        const REASON_BEHAVIOR_3 = 0b0000_0000_0100_0000;
        /// Component is frozen due to a custom behavior toggle (4)
        const REASON_BEHAVIOR_4 = 0b0000_0000_1000_0000;
        /// Component is frozen due to a user-specified reason (1)
        const REASON_USER_1 = 0b0000_0001_0000_0000;
        /// Component is frozen due to a user-specified reason (2)
        const REASON_USER_2 = 0b0000_0010_0000_0000;
        /// Component is frozen due to a user-specified reason (3)
        const REASON_USER_3 = 0b0000_0100_0000_0000;
        /// Component is frozen due to a user-specified reason (4)
        const REASON_USER_4 = 0b0000_1000_0000_0000;
        /// Component is frozen due to a user-specified reason (5)
        const REASON_USER_5 = 0b0001_0000_0000_0000;
        /// Component is frozen due to a user-specified reason (6)
        const REASON_USER_6 = 0b0010_0000_0000_0000;
        /// Component is frozen due to a user-specified reason (7)
        const REASON_USER_7 = 0b0100_0000_0000_0000;
        /// Component is frozen due to a user-specified reason (8)
        const REASON_USER_8 = 0b1000_0000_0000_0000;
    }
}

#[derive(Debug)]
struct ComponentListEntry<C : Component + 'static>
{
    component : C,
    entity : Entity,
    freeze_flags : FreezeFlags
}

trait EntityMapping
{
    fn with_capacity(capacity_hint : usize) -> Self where Self : Sized;
    fn get(&self, entity_id : usize) -> Option<usize>;
    fn contains(&self, entity_id : usize) -> bool;
    fn add(&mut self, entity_id : usize, index : usize);
    fn set(&mut self, entity_id : usize, index : usize);
    fn remove(&mut self, entity_id : usize);
    fn reserve(&mut self, additional : usize);
    fn shrink_to_fit(&mut self);
}

#[derive(Debug)]
struct ChunkedVecEntityMapping
{
    lists : Vec<Option<Box<[u32; CHUNKED_VEC_CHUNK_SIZE]>>>,
    counts : Vec<usize>
}

impl EntityMapping for ChunkedVecEntityMapping
{
    fn with_capacity(capacity_hint : usize) -> Self where Self : Sized
    {
        ChunkedVecEntityMapping
        {
            lists : Vec::with_capacity(capacity_hint / CHUNKED_VEC_CHUNK_SIZE),
            counts : Vec::with_capacity(capacity_hint / CHUNKED_VEC_CHUNK_SIZE)
        }
    }

    fn get(&self, entity_id : usize) -> Option<usize>
    {
        let first_index = entity_id / CHUNKED_VEC_CHUNK_SIZE;

        if first_index < self.lists.len()
        {
            if let Some(list) = &self.lists[first_index]
            {
                let value = list[entity_id % CHUNKED_VEC_CHUNK_SIZE];

                if value < u32::MAX
                {
                    return Some(value as usize);
                }
            }
        }

        None
    }

    fn contains(&self, entity_id : usize) -> bool
    {
        let first_index = entity_id / CHUNKED_VEC_CHUNK_SIZE;

        if first_index < self.lists.len()
        {
            if let Some(list) = &self.lists[first_index]
            {
                let value = list[entity_id % CHUNKED_VEC_CHUNK_SIZE];

                return value < u32::MAX;
            }
        }

        false
    }

    fn add(&mut self, entity_id : usize, index : usize)
    {
        // This is already checked in SceneControl::get_next_entity(), but just in case...
        debug_assert!((entity_id as u32) < u32::MAX, "Too many entities");

        let first_index = entity_id / CHUNKED_VEC_CHUNK_SIZE;

        while first_index >= self.lists.len()
        {
            // TODO: Make faster?
            self.lists.push(None);
            self.counts.push(0);
        }

        if self.lists[first_index].is_none()
        {
            self.lists[first_index] = Some(Box::new([u32::MAX; CHUNKED_VEC_CHUNK_SIZE]));
        }

        let list = &mut self.lists[first_index].as_mut().unwrap();

        list[entity_id % CHUNKED_VEC_CHUNK_SIZE] = index as u32;

        self.counts[first_index] += 1;
    }

    fn set(&mut self, entity_id : usize, index : usize)
    {
        let first_index = entity_id / CHUNKED_VEC_CHUNK_SIZE;
        let list = &mut self.lists[first_index].as_mut().unwrap();

        list[entity_id % CHUNKED_VEC_CHUNK_SIZE] = index as u32;
    }

    fn remove(&mut self, entity_id : usize)
    {
        let first_index = entity_id / CHUNKED_VEC_CHUNK_SIZE;

        if first_index < self.lists.len()
        {
            if let Some(list) = &mut self.lists[first_index]
            {
                list[entity_id % CHUNKED_VEC_CHUNK_SIZE] = u32::MAX;

                self.counts[first_index] -= 1;

                if self.counts[first_index] == 0
                {
                    self.lists[first_index] = None;
                }
            }
        }
    }

    fn reserve(&mut self, _additional : usize)
    {
        // No-op
    }

    fn shrink_to_fit(&mut self)
    {
        // No-op
    }
}

/// Stores all instances of a [Component] for a given type, indexed based on the [Entities](Entity)
/// they belong to.
#[derive(Debug)]
pub struct ComponentStore<C : Component + 'static>
{
    component_list : Vec<ComponentListEntry<C>>,
    removed_components : BitSet<u32>,
    entity_mapping : ChunkedVecEntityMapping,
    singleton_item : Option<C>,
    need_purge : bool,
    ordered_removal : bool
}

impl<C : Component + 'static> ComponentStore<C>
{
    fn new(ordered_removal : bool, capacity_hint : usize) -> ComponentStore<C>
    {
        ComponentStore::<C>
        {
            component_list : Vec::with_capacity(capacity_hint),
            removed_components : BitSet::new(),
            entity_mapping : ChunkedVecEntityMapping::with_capacity(capacity_hint),
            singleton_item : None,
            need_purge : false,
            ordered_removal
        }
    }

    fn add_entity(&mut self, entity : &Entity, component : C) -> bool
    {
        if !self.entity_mapping.contains(entity.id) || self.removed_components.contains(entity.id)
        {
            self.entity_mapping.add(entity.id, self.component_list.len());
            self.component_list.push(ComponentListEntry
            {
                component, entity : entity.clone(), freeze_flags : FreezeFlags::empty()
            });
            self.removed_components.remove(entity.id);

            return true;
        }

        error!("Component {} already exists at ID {}", std::any::type_name::<C>(), entity.id);

        false
    }

    #[inline]
    fn get_nth_index(&self, entity : &Entity) -> Option<usize>
    {
        if let Some(index) = self.entity_mapping.get(entity.id)
        {
            let entry = &self.component_list[index];

            if entry.entity.generation != entity.generation
            {
                return None;
            }

            return Some(index as usize);
        }

        None
    }

    /// Returns an immutable reference to the [Component] for the given [Entity], or [None]
    /// if it does not exist.
    pub fn get_entity<'a>(&'a self, entity : &Entity) -> Option<C::StoreRef> where C : ComponentRef<'a>
    {
        match self.get_nth_index(entity)
        {
            None => { None }
            Some(index) =>
            {
                Some(self.component_list[index].component.store_get())
            }
        }
    }

    /// Returns a mutable reference to the [Component] for the given [Entity], or [None]
    /// if it does not exist.
    pub fn get_entity_mut<'a>(&'a mut self, entity : &Entity) -> Option<C::StoreRefMut> where C : ComponentRefMut<'a>
    {
        match self.get_nth_index(entity)
        {
            None => { None }
            Some(index) =>
            {
                Some(self.component_list[index].component.store_get_mut())
            }
        }
    }

    /// Returns a clone of the [Component] for the given [Entity]. This is useful
    ///  for getting around issues with the Rust borrow checker preventing you from accessing more
    ///  than one component in the store at a time.
    pub fn clone_from_entity<'a>(&'a self, entity : &Entity) -> Option<C> where C : Clone + ComponentRef<'a>
    {
        match self.get_nth_index(entity)
        {
            None => { None }
            Some(index) =>
            {
                Some(self.component_list[index].component.clone())
            }
        }
    }

    /// Returns an immutable reference to the "n-th" [Component] in the store. This is primarily
    ///  useful for when you want to get the first, last, or random component, etc. The index
    ///  you use here should not be cached, as the components may move around in the store.
    ///  In most cases you should use [ComponentStore::get_entity()] instead.
    pub fn get_nth<'a>(&'a self, index : usize) -> Option<(Entity, C::StoreRef)> where C : ComponentRef<'a>
    {
        match self.component_list.get(index)
        {
            None => { None }
            Some(entry) =>
            {
                Some((entry.entity.clone(), entry.component.store_get()))
            }
        }
    }

    /// Returns a mutable reference to the "n-th" [Component] in the store. This is primarily
    ///  useful for when you want to get the first, last, or random component, etc. The index
    ///  you use here should not be cached, as the components may move around in the store.
    ///  In most cases you should use [ComponentStore::get_entity_mut()] instead.
    pub fn get_nth_mut<'a>(&'a mut self, index : usize) -> Option<(Entity, C::StoreRefMut)> where C : ComponentRefMut<'a>
    {
        match self.component_list.get_mut(index)
        {
            None => { None }
            Some(entry) =>
            {
                Some((entry.entity.clone(), entry.component.store_get_mut()))
            }
        }
    }

    pub fn first<'a>(&'a self) -> Option<(Entity, C::StoreRef)> where C : ComponentRef<'a>
    {
        self.get_nth(0)
    }

    pub fn first_mut<'a>(&'a mut self) -> Option<(Entity, C::StoreRefMut)> where C : ComponentRefMut<'a>
    {
        self.get_nth_mut(0)
    }

    /// Returns the number of [Entities](Entity) with this [Component]
    pub fn count(&self) -> usize
    {
        self.component_list.len()
    }

    /// Returns true if there is a [Component] for the given [Entity]
    pub fn contains(&self, entity : &Entity) -> bool
    {
        self.get_nth_index(entity).is_some()
    }

    /// Returns the [FreezeFlags] for the given entity.
    pub fn freeze_flags(&self, entity : &Entity) -> Option<FreezeFlags>
    {
        match self.get_nth_index(entity)
        {
            None => None,
            Some(index) =>
            {
                return Some(self.component_list[index].freeze_flags);
            }
        }
    }

    /// Returns the [FreezeFlags] for the "n-th" [Component] in the store. The index
    ///  you use here should not be cached, as the components may move around in the store.
    ///  In most cases you should use [ComponentStore::freeze_flags()] instead.
    pub fn freeze_flags_nth(&self, index : usize) -> Option<FreezeFlags>
    {
        match self.component_list.get(index)
        {
            None => { None }
            Some(entry) =>
            {
                Some(entry.freeze_flags)
            }
        }
    }

    /// Sets or unsets the [FreezeFlags] for the [Component] of the given [Entity], deactivating the
    ///  component if any flags are set.
    pub fn set_frozen(&mut self, entity : &Entity, freeze_flags : FreezeFlags, freeze : bool) -> bool
    {
        match self.get_nth_index(entity)
        {
            None => false,
            Some(index) =>
            {
                self.component_list[index].freeze_flags.set(freeze_flags, freeze);

                true
            }
        }
    }

    /// Sets or unsets the [FreezeFlags] for the "n-th" [Component] in the store. The index
    /// you use here should not be cached, as the components may move around in the store.
    ///  In most cases you should use [ComponentStore::set_frozen()] instead.
    pub fn set_frozen_nth(&mut self, index : usize, freeze_flags : FreezeFlags, freeze : bool) -> bool
    {
        match self.component_list.get_mut(index)
        {
            None => false,
            Some(entry) =>
            {
                entry.freeze_flags.set(freeze_flags, freeze);

                true
            }
        }
    }

    pub fn sort<F : FnMut(&C, &C) -> Ordering>(&mut self, mut compare : F)
    {
        self.component_list.sort_unstable_by(|a, b|
        {
            match compare(&a.component, &b.component)
            {
                Ordering::Equal => { a.entity.cmp(&b.entity) },
                other => { other }
            }
        });

        for i in 0..self.component_list.len()
        {
            let entry = &self.component_list[i];

            self.entity_mapping.set(entry.entity.id, i);
        }
    }

    /// Returns a [ComponentIter] that iterates through all [Components](Component)
    ///  in the store that are unfrozen.
    pub fn iter<'a>(&'a self) -> ComponentIter<C> where C : ComponentRef<'a>
    {
        ComponentIter::<C>::new(self)
    }

    /// Returns a [ComponentIterMut] that iterates through all [Components](Component)
    ///  in the store that are unfrozen.
    pub fn iter_mut<'a>(&'a mut self) -> ComponentIterMut<C> where C : ComponentRefMut<'a>
    {
        ComponentIterMut::<C>::new(self)
    }

    /// Returns a [ComponentAllIter] that iterates through all [Components](Component)
    ///  in the store. Unlike [ComponentStore::iter()] and [ComponentStore::iter_filtered()], this
    ///  includes frozen components as well.
    pub fn iter_all<'a>(&'a self) -> ComponentAllIter<C> where C : ComponentRef<'a>
    {
        ComponentAllIter::<C>::new(self)
    }

    /// Returns a [ComponentAllIterMut] that iterates through all [Components](Component)
    ///  in the store. Unlike [ComponentStore::iter_mut()] and
    ///  [ComponentStore::iter_filtered_mut()], this includes frozen components as well.
    pub fn iter_all_mut<'a>(&'a mut self) -> ComponentAllIterMut<C> where C : ComponentRefMut<'a>
    {
        ComponentAllIterMut::<C>::new(self)
    }

    /// Returns a [ComponentFilterIter] that iterates through all [Components](Component)
    ///  in the store that are unfrozen according to the given [FreezeFlags].
    pub fn iter_filtered<'a>(&'a self, freeze_flags : FreezeFlags) -> ComponentFilterIter<C> where C : ComponentRef<'a>
    {
        ComponentFilterIter::<C>::new(self, freeze_flags)
    }

    /// Returns a [ComponentFilterIterMut] that iterates through all [Components](Component)
    ///  in the store that are unfrozen according to the given [FreezeFlags].
    pub fn iter_filtered_mut<'a>(&'a mut self, freeze_flags : FreezeFlags) -> ComponentFilterIterMut<C> where C : ComponentRefMut<'a>
    {
        ComponentFilterIterMut::<C>::new(self, freeze_flags)
    }

    pub fn singleton(&self) -> Option<&C>
    {
        self.singleton_item.as_ref()
    }

    pub fn singleton_mut(&mut self) -> &mut C where C : Default
    {
        if self.singleton_item.is_none()
        {
            self.singleton_item = Some(C::default());
        }

        self.singleton_item.as_mut().unwrap()
    }

    pub fn singleton_mut_or<F : FnMut() -> C>(&mut self, mut func : F) -> &mut C
    {
        if self.singleton_item.is_none()
        {
            self.singleton_item = Some(func());
        }

        self.singleton_item.as_mut().unwrap()
    }

    pub fn reserve_capacity(&mut self, additional : usize)
    {
        self.component_list.reserve(additional);
        self.entity_mapping.reserve(additional);
    }

    pub fn shrink_to_fit(&mut self)
    {
        self.component_list.shrink_to_fit();
        self.entity_mapping.shrink_to_fit();
    }
}

impl<C : Component + 'static> ComponentStoreBase for ComponentStore<C>
{
    fn preview_remove_entity(&mut self, entity : &Entity) -> bool
    {
        if let Some(index) = self.entity_mapping.get(entity.id)
        {
            let entry = &mut self.component_list[index];

            if entry.entity.generation != entity.generation
            {
                return false;
            }

            return true;
        }

        false
    }

    fn do_remove_entity(&mut self, entity : &Entity)
    {
        if let Some(index) = self.entity_mapping.get(entity.id)
        {
            if self.ordered_removal
            {
                self.entity_mapping.remove(entity.id);
                self.removed_components.insert(entity.id);
                self.need_purge = true;
            }
            else
            {
                if !self.component_list.is_empty()
                {
                    let entry = &self.component_list[self.component_list.len() - 1];
                    self.entity_mapping.set(entry.entity.id, index);
                }

                self.component_list.swap_remove(index);
                self.entity_mapping.remove(entity.id);
            }
        }
        else
        {
            panic!("Tried to remove unmapped entity {}", entity);
        }
    }

    fn purge_entities(&mut self)
    {
        if !self.need_purge
        {
            return;
        }

        let mut set = BitSet::new();

        std::mem::swap(&mut set, &mut self.removed_components);

        self.component_list.retain(|entry| !set.contains(entry.entity.id));

        std::mem::swap(&mut set, &mut self.removed_components);

        for i in 0..self.component_list.len()
        {
            let entry = &self.component_list[i];

            self.entity_mapping.set(entry.entity.id, i);
        }

        self.removed_components.clear();
        self.need_purge = false;
    }

    fn do_set_frozen(&mut self, entity : &Entity, freeze_flags : FreezeFlags, freeze : bool)
    {
        if let Some(index) = self.entity_mapping.get(entity.id)
        {
            self.component_list[index as usize].freeze_flags.set(freeze_flags, freeze);
        }
    }
}


////////////////////////////////////////////////////////////


struct ComponentControlData
{
    index_to_component_id : Vec<TypeId>,
    component_id_to_index : HashMap<TypeId, usize, BuildHasherDefault<FxHasher>>,
}

pub type ComponentAddRemoveCallbackFn = Box<dyn Fn(&Entity, &mut ComponentControl)>;

pub struct ComponentCallbacks
{
    add_callbacks : Vec<ComponentAddRemoveCallbackFn>,
    remove_callbacks : Vec<ComponentAddRemoveCallbackFn>
}

impl ComponentCallbacks
{
    pub fn new() -> ComponentCallbacks
    {
        ComponentCallbacks
        {
            add_callbacks : Vec::new(),
            remove_callbacks : Vec::new()
        }
    }

    pub fn push_add_component_callback(&mut self, func : ComponentAddRemoveCallbackFn)
    {
        self.add_callbacks.push(func);
    }

    pub fn push_remove_component_callback(&mut self, func : ComponentAddRemoveCallbackFn)
    {
        self.remove_callbacks.push(func);
    }

    fn call_add_component_callback(&self, entity : &Entity, components : &mut ComponentControl)
    {
        for func in &self.add_callbacks
        {
            func(entity, components);
        }
    }

    fn call_remove_component_callback(&self, entity : &Entity, components : &mut ComponentControl)
    {
        for func in &self.remove_callbacks
        {
            func(entity, components);
        }
    }

    pub fn append(&mut self, mut other: ComponentCallbacks)
    {
        self.add_callbacks.append(&mut other.add_callbacks);
        self.remove_callbacks.append(&mut other.remove_callbacks);
    }
}


#[derive(Debug, Fail)]
pub enum ComponentControlError
{
    #[fail(display = "Mutable access is not allowed while drawing")]
    MutableAccessLocked,
    #[fail(display = "ComponentStore already borrowed")]
    AlreadyBorrowed
}

impl From<BorrowError> for ComponentControlError
{
    fn from(_: BorrowError) -> Self
    {
        ComponentControlError::AlreadyBorrowed
    }
}

impl From<BorrowMutError> for ComponentControlError
{
    fn from(_: BorrowMutError) -> Self
    {
        ComponentControlError::AlreadyBorrowed
    }
}

/// Allows working with [ComponentStores](ComponentStore) from within systems.
pub struct ComponentControl
{
    component_stores : GenericArray<RefCell<Box<dyn ComponentStoreBase>>, ComponentTypeMax>,
    data : RefCell<ComponentControlData>,
    locked : bool
}

impl ComponentControl
{
    fn new() -> ComponentControl
    {
        let component_stores = GenericArray::<RefCell<Box<dyn ComponentStoreBase>>, ComponentTypeMax>::generate(|_| RefCell::new(Box::new(NullComponentStore {})));

        let data = ComponentControlData
        {
            index_to_component_id : Vec::new(),
            component_id_to_index : HashMap::with_capacity_and_hasher(component_stores.len(),
                                                                      BuildHasherDefault::<FxHasher>::default())
        };

        ComponentControl
        {
            component_stores,
            data : RefCell::new(data),
            locked : false
        }
    }

    fn register_component_type<C : Component + 'static>(&self) -> bool
    {
        let wanted_type = TypeId::of::<C>();
        let component_store = ComponentStore::<C>::new(C::maintain_ordering(), C::capacity_hint());

        self.register_boxed_component_type(wanted_type, Box::new(component_store))
    }

    fn register_boxed_component_type(&self, type_id : TypeId, mut component_store : Box<dyn ComponentStoreBase>) -> bool
    {
        let mut data = self.data.try_borrow_mut().expect("ComponentStore data already in use!");

        if !data.component_id_to_index.contains_key(&type_id)
        {
            if data.index_to_component_id.len() >= self.component_stores.len()
            {
                panic!("Too many component types in this scene! Limit is {}", self.component_stores.len());
            }

            let insert_pos = data.index_to_component_id.len();

            let mut placeholder = self.component_stores[insert_pos].try_borrow_mut().expect("Placeholder under use somehow!");
            std::mem::swap(&mut *placeholder, &mut component_store);

            data.component_id_to_index.insert(type_id, insert_pos);
            data.index_to_component_id.push(type_id);

            return true;
        }

        false
    }

    fn component_type_registered(&self, wanted_type : TypeId) -> bool
    {
        let data = self.data.try_borrow().expect("ComponentStore data already in use!");

        data.component_id_to_index.contains_key(&wanted_type)
    }

    pub fn store<C : Component + 'static>(&self) -> Ref<ComponentStore<C>>
    {
        match self.try_store()
        {
            Ok(store) =>
            {
                return store;
            }
            Err(error) =>
            {
                panic!("ComponentStore for {} unavailable: {}", std::any::type_name::<C>(), error);
            }
        }
    }

    pub fn store_mut<C : Component + 'static>(&self) -> RefMut<ComponentStore<C>>
    {
        match self.try_store_mut()
        {
            Ok(store) =>
            {
                return store;
            }
            Err(error) =>
            {
                panic!("ComponentStore for {} unavailable: {}", std::any::type_name::<C>(), error);
            }
        }
    }

    pub fn try_store<C : Component + 'static>(&self) -> Result<Ref<ComponentStore<C>>, ComponentControlError>
    {
        let wanted_type = TypeId::of::<C>();

        if !self.component_type_registered(wanted_type)
        {
            self.register_component_type::<C>();
        }

        let data = self.data.try_borrow().expect("ComponentStore data already in use!");
        let index = data.component_id_to_index[&wanted_type];

        Ok(Ref::map(self.component_stores[index].try_borrow()?,
                             |b| b.downcast_ref::<ComponentStore<C>>().expect("ComponentStore downcast failed!")))
    }

    pub fn try_store_mut<C : Component + 'static>(&self) -> Result<RefMut<ComponentStore<C>>, ComponentControlError>
    {
        if self.locked
        {
            return Err(ComponentControlError::MutableAccessLocked);
        }

        let wanted_type = TypeId::of::<C>();

        if !self.component_type_registered(wanted_type)
        {
            self.register_component_type::<C>();
        }

        let data = self.data.try_borrow().expect("ComponentStore data already in use!");
        let index = data.component_id_to_index[&wanted_type];

        Ok(RefMut::map(self.component_stores[index].try_borrow_mut()?,
                           |b| b.downcast_mut::<ComponentStore<C>>().expect("ComponentStore borrow failed!")))
    }
}


////////////////////////////////////////////////////////////

trait DeferredComponentListBase : Downcast
{
    fn add_to_scene(&mut self, scene_components : &mut SceneComponents);
    fn priority(&self) -> i32;
}
impl_downcast!(DeferredComponentListBase);

struct DeferredComponentList<C : Component + 'static>
{
    list : Vec<EntityComponent<C>>
}

impl<C : Component + 'static> DeferredComponentList<C>
{
    fn new(reserve_capacity : usize) -> DeferredComponentList<C>
    {
        DeferredComponentList
        {
            list : Vec::with_capacity(reserve_capacity)
        }
    }
}

impl<C : Component + 'static> DeferredComponentListBase for DeferredComponentList<C>
{
    fn add_to_scene(&mut self, scene_components : &mut SceneComponents)
    {
        let mut store = scene_components.control.store_mut::<C>();

        if self.list.len() > store.count()
        {
            store.reserve_capacity(self.list.len());
        }

        std::mem::drop(store);

        let mut list = Vec::<EntityComponent<C>>::new();
        std::mem::swap(&mut list, &mut self.list);

        scene_components.add_multiple_components(list);
    }

    fn priority(&self) -> i32
    {
        C::add_priority()
    }
}


struct DeferredComponentAdds
{
    lists : Vec<Box<dyn DeferredComponentListBase>>,
    type_map : HashMap<TypeId, usize, BuildHasherDefault<FxHasher>>,
    reserve_capacity : usize
}

impl DeferredComponentAdds
{
    fn new() -> DeferredComponentAdds
    {
        DeferredComponentAdds
        {
            lists : Vec::new(),
            type_map : HashMap::with_hasher(BuildHasherDefault::<FxHasher>::default()),
            reserve_capacity : 0
        }
    }

    fn push<C : Component + 'static>(&mut self, entity : Entity, component : C)
    {
        if let Some(index) = self.type_map.get(&TypeId::of::<C>())
        {
            let list_downcast = self.lists[*index].downcast_mut::<DeferredComponentList<C>>().expect("Bad deferred list downcast!");

            list_downcast.list.push(EntityComponent
            {
                entity,
                component
            });
        }
        else
        {
            self.type_map.insert(TypeId::of::<C>(), self.lists.len());
            self.lists.push(Box::new(DeferredComponentList::<C>::new(self.reserve_capacity.min(MAX_RESERVE_CAPACITY_HINT))));

            self.push(entity, component);
        }
    }

    fn clear(&mut self)
    {
        self.type_map.clear();
        self.lists.clear();
        self.reserve_capacity = 0;
    }

    fn is_empty(&self) -> bool
    {
        self.lists.is_empty()
    }
}

/// Control for adding and removing [Entities](Entity) and [Components](Component) while the scene
///  is running.
pub struct SceneControl<T : SceneType + 'static>
{
    unused_pool : VecDeque<Entity>,
    deferred_adds : Vec<Entity>,
    deferred_removals : Vec<Entity>,
    deferred_component_removals : Vec<(TypeId, Entity)>,
    deferred_freezes: Vec<(Entity, FreezeFlags, bool)>,
    deferred_callback_adds : Vec<(TypeId, ComponentCallbacks)>,
    deferred_flag : bool,
    spawn_control : SpawnControl,
    next_entity_id : usize,
    scene_type : T
}

impl<T : SceneType + 'static> SceneControl<T>
{
    fn new() -> SceneControl<T>
    {
        SceneControl
        {
            unused_pool : VecDeque::new(),
            deferred_adds : Vec::new(),
            deferred_removals : Vec::new(),
            deferred_component_removals : Vec::new(),
            deferred_freezes: Vec::new(),
            deferred_callback_adds : Vec::new(),
            deferred_flag : false,
            spawn_control : SpawnControl::new(),
            next_entity_id : 0,
            scene_type : T::new()
        }
    }

    /// Adds an [Entity] after the current [ThinkerSystem::think()] finishes. Returns the [Entity]
    ///  which you can immediately schedule adding components to using
    ///  [SceneControl::add_component_later()].
    pub fn add_entity_later(&mut self) -> Entity
    {
        let entity = self.get_next_entity();

        self.deferred_adds.push(entity.clone());
        self.deferred_flag = true;

        entity
    }

    /// Removes the given [Entity] and all its [Components](Component) after the current
    ///  [ThinkerSystem::think()] finishes.
    pub fn remove_entity_later(&mut self, entity : &Entity)
    {
        self.deferred_removals.push(Entity::new(entity.id, entity.generation));
        self.deferred_flag = true;
    }

    /// Adds a [Component] to the given [Entity] after the current [ThinkerSystem::think()]
    ///  finishes.
    pub fn add_component_later<C : Component + 'static>(&mut self, entity : &Entity, component : C)
    {
        self.spawn_control.deferred_adds.push(entity.clone(), component);
        self.create_component_factory::<C>();

        self.deferred_flag = true;
    }

    #[inline(always)]
    fn create_component_factory<C : Component + 'static>(&mut self)
    {
        self.spawn_control.create_component_factory::<C>();
    }

    /// Removes the given [Component] from the given [Entity] after the current
    ///  [ThinkerSystem::think()] finishes.
    pub fn remove_component_later<C : Component + 'static>(&mut self, entity : &Entity)
    {
        self.deferred_component_removals.push((TypeId::of::<C>(), Entity::new(entity.id, entity.generation)));
        self.deferred_flag = true;
    }

    /// Spawns an object with pre-configured [Components](Component) after the current
    ///  [ThinkerSystem::think()] finishes. The [Components](Component) to assign are given by the
    ///  implementation of [SceneType::spawn()] for the current scene.
    pub fn spawn_later(&mut self, spawnable_id : T::SpawnableIdType, game : &mut GameControl,
                            x : f64, y : f64) -> Entity
    {
        self.spawn_later_with(spawnable_id, game, x, y, &DynArgList::new())
    }

    /// Spawns an object with pre-configured [Components](Component) after the current
    ///  [ThinkerSystem::think()] finishes. The [Components](Component) to assign are given by the
    ///  implementation of [SceneType::spawn()] for the current scene. The given [DynArgList] may
    ///  be used to influence how the [Components](Component) are created.
    pub fn spawn_later_with(&mut self, spawnable_id : T::SpawnableIdType, game : &mut GameControl,
                            x : f64, y : f64, args : &DynArgList) -> Entity
    {
        let entity = self.get_next_entity();

        self.spawn_control.entity = entity.clone();
        self.scene_type.spawn(&mut self.spawn_control, spawnable_id, game, x, y, args);

        self.deferred_adds.push(entity.clone());
        self.deferred_flag = true;

        entity
    }

    /// Sets or unsets the [FreezeFlags] for the given [Entity] and all its [Components](Component)
    ///  after the current [ThinkerSystem::think()] finishes.
    pub fn set_entity_frozen_later(&mut self, entity : &Entity, freeze_flags : FreezeFlags, freeze : bool)
    {
        self.deferred_freezes.push((Entity::new(entity.id, entity.generation), freeze_flags, freeze));
        self.deferred_flag = true;
    }

    /// Registers a set of callbacks after the current [ThinkerSystem::think()] finishes. These
    ///  callbacks will fire whenever a [Component] of this type is added or removed. The callbacks
    ///  are not guaranteed to be called in the exact order that the components were created in this
    ///  frame, as multiple components of a given type may be batched together. The callbacks will
    ///  not be called if the component is assigned to directly.
    pub fn register_callbacks_later<C : Component + 'static>(&mut self, callbacks : ComponentCallbacks)
    {
        self.deferred_callback_adds.push((TypeId::of::<C>(), callbacks));
        self.deferred_flag = true;
    }

    fn get_next_entity(&mut self) -> Entity
    {
        let entity;

        if self.unused_pool.is_empty()
        {
            if self.next_entity_id as u32 >= u32::MAX
            {
                panic!("Too many entities");
            }

            entity = Entity { id : self.next_entity_id, generation : 1 };
            
            self.next_entity_id += 1;
        }
        else
        {
            entity = self.unused_pool.pop_front().unwrap();
        }
        
        entity
    }

    /// (Advanced) Hints to the deferred spawning system that this many additional
    ///  [Components](Component) may be created. This is a performance tuning option and in most
    ///  cases you probably don't need or want to use this.
    pub fn deferred_reserve_capacity_hint(&mut self, additional : usize)
    {
        self.spawn_control.deferred_adds.reserve_capacity = additional;
    }
}


////////////////////////////////////////////////////////////


pub struct SpawnControl
{
    store_factories : HashMap<TypeId, Box<dyn Fn() -> Box<dyn ComponentStoreBase>>, BuildHasherDefault<FxHasher>>,
    deferred_adds : DeferredComponentAdds,
    entity : Entity
}

impl SpawnControl
{
    fn new() -> SpawnControl
    {
        SpawnControl
        {
            store_factories : HashMap::with_capacity_and_hasher(ComponentTypeMax::to_usize(),
                                                                BuildHasherDefault::<FxHasher>::default()),
            deferred_adds : DeferredComponentAdds::new(),
            entity : Entity::null()
        }
    }

    pub fn with<C : Component + 'static>(&mut self, component : C)
    {
        self.create_component_factory::<C>();

        self.deferred_adds.push(self.entity.clone(), component);
    }

    #[inline(always)]
    fn create_component_factory<C : Component + 'static>(&mut self)
    {
        let component_type = TypeId::of::<C>();

        if !self.store_factories.contains_key(&component_type)
        {
            self.store_factories.insert(component_type, Box::new(||
            {
                Box::new(ComponentStore::<C>::new(C::maintain_ordering(), C::capacity_hint()))
            }));
        }
    }
}


/// Contains information about how to initialize the scene, such as which systems to use, and
///  the singletons to create
pub struct SceneConfig<T : SceneType + 'static>
{
    thinkers : Vec<Box<dyn ThinkerSystem<T>>>,
    drawers : Vec<Box<dyn DrawerSystem>>,
    #[cfg(feature = "imgui_feature")]
    imgui : Option<Box<dyn ImGuiSystem<T>>>,
    store_factories : HashMap<TypeId, Box<dyn FnOnce() -> Box<dyn ComponentStoreBase>>>,
}

impl<T : SceneType + 'static> SceneConfig<T>
{
    pub fn new() -> SceneConfig<T>
    {
        SceneConfig::<T>
        {
            thinkers: Vec::new(),
            drawers: Vec::new(),
            #[cfg(feature = "imgui_feature")]
            imgui: None,
            store_factories : HashMap::new(),
        }
    }

    pub fn thinker<S : ThinkerSystem<T> + 'static>(&mut self, thinker : S) -> &mut Self
    {
        self.thinkers.push(Box::new(thinker));

        self
    }

    pub fn drawer<S : DrawerSystem + 'static>(&mut self, drawer : S) -> &mut Self
    {
        self.drawers.push(Box::new(drawer));

        self
    }

    #[cfg(feature = "imgui_feature")]
    pub fn imgui<S : ImGuiSystem<T> + 'static>(&mut self, imgui : Option<S>) -> &mut Self
    {
        match imgui
        {
            None => self.imgui = None,
            Some(imgui_some) => self.imgui = Some(Box::new(imgui_some))
        }

        self
    }

    pub fn singleton<C : Component + 'static>(&mut self, singleton : C) -> &mut Self
    {
        let component_type = TypeId::of::<C>();

        self.store_factories.insert(component_type, Box::new(||
        {
            let mut store = ComponentStore::<C>::new(C::maintain_ordering(), C::capacity_hint());

            store.singleton_item = Some(singleton);

            Box::new(store)
        }));

        self
    }
}


/// A trait containing information on how to instantiate spawnables in the scene,
/// and which systems this scene should include.
pub trait SceneType
{
    /// The enum to use to identify different spawnables. You can generate this using the
    ///  [spawnables!] macro.
    type SpawnableIdType : SpawnableEnum + 'static;

    /// Creates a new instance of the [SceneType]
    fn new() -> Self where Self : Sized;
    /// Used to create a [SceneConfig] object, which includes information such as which systems
    ///  to use.
    #[allow(unused_variables)]
    fn config(&mut self, game : &mut GameControl) -> SceneConfig<Self> where Self : Sized;
    /// Used to construct a set of [Components](Component) given a spawnable type. It is recommended
    ///  that you use the [spawnables!] macro and [SpawnableConfig] trait to define this logic in
    ///  separate modules.
    #[allow(unused_variables)]
    fn spawn(&mut self, spawn : &mut SpawnControl, spawnable_id : Self::SpawnableIdType, game : &mut GameControl,
        x : f64, y : f64, args : &DynArgList) {}
}

pub struct NullSceneType
{

}

#[derive(Copy, Clone, EnumString, EnumCount)]
pub enum NullSpawnable {}

impl Into<usize> for NullSpawnable
{
    fn into(self) -> usize
    {
        self as usize
    }
}

impl SpawnableEnum for NullSpawnable
{

}

impl SceneType for NullSceneType
{
    type SpawnableIdType = NullSpawnable;
    
    fn new() -> Self where Self : Sized { NullSceneType {} }
    fn config(&mut self, _game: &mut GameControl) -> SceneConfig<Self> { SceneConfig::new() }
}

pub type SimpleScene = Scene::<NullSceneType>;


/// A base trait for scenes that can be run from within the gameloop
pub trait BaseScene
{
    /// Runs the think logic. Ideally, processes all the [ThinkerSystems](ThinkerSystem) in this scene.
    fn think(&mut self, game : &mut GameControl);
    /// Runs the draw logic. Ideally, processes all the [DrawerSystems](DrawerSystem) in this scene.
    fn draw(&mut self, resources : &DataMultistore, drawing : &mut Box<dyn DrawControl>, transform : &DrawTransform, interpolation : f32);
    #[cfg(feature = "imgui_feature")]
    fn imgui_think(&mut self, ui : &mut imgui::Ui, game : &mut GameControl);
    /// Called to run initialization logic. Ideally, calls [ThinkerSystem::start()] on all the
    /// [ThinkerSystems](ThinkerSystem) in this scene.
    fn start(&mut self, game : &mut GameControl) -> bool;
    /// Called to run deinitialization logic. Ideally, calls [ThinkerSystem::end()] on all the
    /// [ThinkerSystems](ThinkerSystem) in this scene.
    fn end(&mut self, game : &mut GameControl) -> bool;
    /// Returns the number of [Entities](Entity) in the scene
    fn entity_count(&self) -> usize;
    /// Returns the number of [Components](Component) in the scene
    fn component_count(&self) -> usize;
}


struct EntityRecord
{
    component_bits : BitArraySet<u32, ComponentTypeMax>,
    generation : u64
}

struct SceneComponents
{
    control : ComponentControl,
    entity_records : Vec<EntityRecord>,
    num_entities : usize,
    num_components : usize,
    component_callbacks : GenericArray<ComponentCallbacks, ComponentTypeMax>,
    need_purge : bool,
    stores_to_purge : BitArraySet<u32, ComponentTypeMax>,
}

impl SceneComponents
{
    fn new() -> SceneComponents
    {
        let component_callbacks = GenericArray::<ComponentCallbacks, ComponentTypeMax>::generate(|_| ComponentCallbacks::new());

        SceneComponents
        {
            control : ComponentControl::new(),
            entity_records : Vec::new(),
            num_entities : 0,
            num_components : 0,
            component_callbacks,
            need_purge : false,
            stores_to_purge : BitArraySet::new()
        }
    }

    fn add_component<C : Component + 'static>(&mut self, entity : &Entity, component : C) -> bool
    {
        let wanted_type = TypeId::of::<C>();

        if entity.id >= self.entity_records.len()
        {
            return false;
        }

        if !self.control.component_type_registered(wanted_type)
        {
            self.control.register_component_type::<C>();
        }

        let record = &mut self.entity_records[entity.id];

        if entity.generation != record.generation
        {
            return false;
        }

        let data = self.control.data.try_borrow_mut().expect("ComponentStore data already in use!");
        let index = data.component_id_to_index[&wanted_type];

        let mut component_store = RefMut::map(self.control.component_stores[index].borrow_mut(),
                                              |b| b.downcast_mut::<ComponentStore<C>>().expect("ComponentStore borrow failed!"));

        let result = component_store.add_entity(entity, component);

        std::mem::drop(data);
        std::mem::drop(component_store);

        if result
        {
            self.num_components += 1;
            record.component_bits.insert(index);

            self.component_callbacks[index].call_add_component_callback(entity, &mut self.control);
        }

        return result;
    }

    fn add_multiple_components<C : Component + 'static>(&mut self, mut list : Vec<EntityComponent<C>>)
    {
        let wanted_type = TypeId::of::<C>();

        if !self.control.component_type_registered(wanted_type)
        {
            self.control.register_component_type::<C>();
        }

        let data = self.control.data.try_borrow_mut().expect("ComponentStore data already in use!");
        let component_index = data.component_id_to_index[&wanted_type];

        std::mem::drop(data);

        for item in list.drain(..)
        {
            if item.entity.id >= self.entity_records.len()
            {
                continue;
            }

            let record = &mut self.entity_records[item.entity.id];

            if item.entity.generation != record.generation
            {
                continue;
            }

            let mut component_store = RefMut::map(self.control.component_stores[component_index].borrow_mut(),
                                                  |b| b.downcast_mut::<ComponentStore<C>>().expect("ComponentStore borrow failed!"));

            let result = component_store.add_entity(&item.entity, item.component);

            std::mem::drop(component_store);

            if result
            {
                self.num_components += 1;
                record.component_bits.insert(component_index);

                self.component_callbacks[component_index].call_add_component_callback(&item.entity, &mut self.control);
            }
        }
    }

    fn remove_component(&mut self, entity : &Entity, component_type : TypeId) -> bool
    {
        let data = self.control.data.try_borrow_mut().expect("ComponentStore data already in use!");

        if entity.id >= self.entity_records.len() || !data.component_id_to_index.contains_key(&component_type)
        {
            return false;
        }

        let record = &mut self.entity_records[entity.id];

        if entity.generation != record.generation
        {
            return false;
        }

        let index = data.component_id_to_index[&component_type];

        let mut component_store = self.control.component_stores[index].borrow_mut();
        let result = component_store.preview_remove_entity(entity);

        std::mem::drop(data);

        if result
        {
            component_store.do_remove_entity(entity);

            std::mem::drop(component_store);

            self.num_components -= 1;
            record.component_bits.remove(index);
            self.stores_to_purge.insert(index);
            self.need_purge = true;

            self.component_callbacks[index].call_remove_component_callback(entity, &mut self.control);
        }

        return result;
    }
}

/// A world in which [Entities](Entity), [Components](Component), and [ThinkerSystems](ThinkerSystem)/[DrawerSystems](DrawerSystem) reside.
///  You will normally only be working with this API if you are directly managing a Scene within a Scene.
///  Usually you will be using SceneControl and ComponentControl instead.
pub struct Scene<T : SceneType + 'static>
{
    components : SceneComponents,
    control : SceneControl<T>,
    thinker_systems : Vec<Box<dyn ThinkerSystem<T>>>,
    drawer_systems : Vec<Box<dyn DrawerSystem>>,
    #[cfg(feature = "imgui_feature")]
    imgui_system : Box<dyn ImGuiSystem<T>>,
    init_done : bool,
    deinit_done : bool
}

impl<T : SceneType + 'static> BaseScene for Scene<T>
{
    /// Processes all the [ThinkerSystems](ThinkerSystem) in this scene. You normally do not need
    /// to call this yourself, as the [Gameloop](crate::gameloop::Gameloop) handles this for you.
    fn think(&mut self, game : &mut GameControl)
    {
        if self.deinit_done
        {
            return;
        }

        self.start(game);
        self.do_deferred_actions();

        let mut list = Vec::new();
        
        std::mem::swap(&mut list, &mut self.thinker_systems);
        
        for system in list.iter_mut()
        {
            system.think(ThinkerArgs
            {
                components : &mut self.components.control, scene : &mut self.control, game
            });
            
            self.do_deferred_actions();
        }
        
        std::mem::swap(&mut list, &mut self.thinker_systems);
    }

    /// Allows all the [ThinkerSystems](ThinkerSystem) to process their "start of scene" actions.
    /// You normally do not need to call this yourself, as the
    /// [Gameloop](crate::gameloop::Gameloop) handles this for you.
    fn start(&mut self, game : &mut GameControl) -> bool
    {
        if self.init_done
        {
            return false;
        }

        let config = self.control.scene_type.config(game);

        for thinker in config.thinkers
        {
            self.add_thinker_system(thinker);
        }
        for drawer in config.drawers
        {
            self.add_drawer_system(drawer);
        }
        #[cfg(feature = "imgui_feature")]
        {
            if let Some(imgui_system) = config.imgui
            {
                self.set_imgui_system(imgui_system);
            }
        }
        for (type_id, factory) in config.store_factories
        {
            self.components.control.register_boxed_component_type(type_id, factory());
        }

        let mut list = Vec::new();

        std::mem::swap(&mut list, &mut self.thinker_systems);

        for system in list.iter_mut()
        {
            system.start(ThinkerArgs { components : &mut self.components.control, scene : &mut self.control, game });

            self.do_deferred_actions();
        }

        for system in list.iter_mut()
        {
            system.start_late(ThinkerArgs { components : &mut self.components.control, scene : &mut self.control, game });

            self.do_deferred_actions();
        }

        std::mem::swap(&mut list, &mut self.thinker_systems);

        #[cfg(feature = "imgui_feature")]
        {
            self.imgui_system.start(ThinkerArgs
            {
                components : &mut self.components.control, scene : &mut self.control, game
            });

            self.do_deferred_actions();
        }

        self.init_done = true;

        true
    }
    
    /// Allows all the [ThinkerSystems](ThinkerSystem) to process their "end of scene" actions.
    /// You normally do not need to call this yourself, as the
    /// [Gameloop](crate::gameloop::Gameloop) handles this for you.
    fn end(&mut self, game : &mut GameControl) -> bool
    {
        if !self.init_done || self.deinit_done
        {
            return false;
        }
        
        self.do_deferred_actions();

        let mut list = Vec::new();
        
        std::mem::swap(&mut list, &mut self.thinker_systems);
        
        for system in list.iter_mut()
        {
            system.end(ThinkerArgs
            {
                components : &mut self.components.control, scene : &mut self.control, game
            });
            
            self.do_deferred_actions();
        }
        
        std::mem::swap(&mut list, &mut self.thinker_systems);

        #[cfg(feature = "imgui_feature")]
        {
            self.imgui_system.end(ThinkerArgs
            {
                components : &mut self.components.control, scene : &mut self.control, game
            });

            self.do_deferred_actions();
        }
        
        self.deinit_done = true;

        true
    }
    
    /// Processes all the [DrawerSystems](DrawerSystem) in this scene. You normally do not need
    /// to call this yourself, as the [Gameloop](crate::gameloop::Gameloop) handles this for you.
    fn draw(&mut self, resources : &DataMultistore, drawing : &mut Box<dyn DrawControl>, transform : &DrawTransform, interpolation : f32)
    {
        if !self.init_done || self.deinit_done
        {
            return;
        }
        
        let mut list = Vec::new();
        
        std::mem::swap(&mut list, &mut self.drawer_systems);
        self.components.control.locked = true;
        
        for system in list.iter()
        {
            system.draw(DrawerArgs
            {
                components : &self.components.control, resources, drawing, transform, interpolation
            });
        }

        self.components.control.locked = false;
        std::mem::swap(&mut list, &mut self.drawer_systems);
    }
    
    #[cfg(feature = "imgui_feature")]
    fn imgui_think(&mut self, ui : &mut imgui::Ui, game : &mut GameControl)
    {
        if !self.init_done || self.deinit_done
        {
            return;
        }
        
        self.imgui_system.imgui_think(ui, ThinkerArgs
        {
            components : &mut self.components.control, scene : &mut self.control, game
        });
    }
    
    /// Returns the number of [Entities](Entity) in the scene
    fn entity_count(&self) -> usize
    {
        self.components.num_entities
    }
    
    /// Returns the number of [Components](Component) in the scene
    fn component_count(&self) -> usize
    {
        self.components.num_components
    }
}

impl<T : SceneType + 'static> Scene<T>
{
    /// Creates a new [Scene]
    pub fn new() -> Self
    {
        Scene
        {
            components : SceneComponents::new(),
            control : SceneControl::<T>::new(),
            thinker_systems : Vec::new(),
            drawer_systems : Vec::new(),
            #[cfg(feature = "imgui_feature")]
            imgui_system : Box::new(NullImGuiSystem { _phantom : PhantomData }),
            init_done : false,
            deinit_done : false,
        }
    }
    
    /// Returns a reference to the control used to access [ComponentStores](ComponentStore). You
    /// normally don't need to call this yourself.
    pub fn component_control(&self) -> &ComponentControl
    {
        &self.components.control
    }
    
    /// Returns a mutable reference to the control used to access [ComponentStores](ComponentStore). You
    /// normally don't need to call this yourself.
    pub fn component_control_mut(&mut self) -> &mut ComponentControl
    {
        &mut self.components.control
    }
    
    pub fn register_component_type<C : Component + 'static>(&mut self) -> bool
    {
        self.components.control.register_component_type::<C>()
    }
    
    /// Attaches a [Component] to the given [Entity]. Returns true if successful.
    pub fn add_component<C : Component + 'static>(&mut self, entity : &Entity, component : C) -> bool
    {
        self.components.add_component(entity, component)
    }

    /// Attaches multiple [Components](Component) to their given [Entities](Entity). Calling this
    ///  should be faster than calling add_component() multiple times.
    pub fn add_multiple_components<C : Component + 'static>(&mut self, list : Vec<EntityComponent<C>>)
    {
        self.components.add_multiple_components(list)
    }
    
    /// Detaches a [Component] from the given [Entity]. Returns true if successful.
    pub fn remove_component<C : Component + 'static>(&mut self, entity : &Entity) -> bool
    {
        let result = self.components.remove_component(entity, TypeId::of::<C>());

        if result
        {
            self.control.deferred_flag = true;
        }

        result
    }
    
    /// Creates a new [Entity] within the scene, returning its handler.
    pub fn add_entity(&mut self) -> Entity
    {
        let entity = self.control.get_next_entity();
        
        self.add_entity_internal(&entity);
        
        entity
    }
    
    fn add_entity_internal(&mut self, entity : &Entity)
    {
        debug_assert_ne!(entity.generation, 0);

        if entity.id < self.components.entity_records.len()
        {
            let record = &mut self.components.entity_records[entity.id];

            record.component_bits = BitArraySet::new();
            record.generation = entity.generation;
        }
        else if entity.id == self.components.entity_records.len()
        {
            self.components.entity_records.insert(entity.id, EntityRecord
            {
                component_bits : BitArraySet::new(),
                generation : entity.generation
            });
        }
        else
        {
            panic!("Unexpected entity ID number. Got {}, expected {} or lower", entity.id, self.components.entity_records.len());
        }
        
        self.components.num_entities += 1;
    }
    
    /// Removes the [Entity] with the given handle from the scene. Returns true if successful.
    pub fn remove_entity(&mut self, entity : &Entity) -> bool
    {
        if entity.id >= self.components.entity_records.len()
        {
            return false;
        }
        
        let record = &mut self.components.entity_records[entity.id];

        if entity.generation != record.generation
        {
            return false;
        }

        for component_index in &record.component_bits
        {
            if self.components.control.component_stores[component_index].borrow_mut().preview_remove_entity(&entity)
            {
                self.components.component_callbacks[component_index].call_remove_component_callback(entity, &mut self.components.control);

                let mut component_store = self.components.control.component_stores[component_index].borrow_mut();

                component_store.do_remove_entity(&entity);
                self.components.num_components -= 1;
                self.components.stores_to_purge.insert(component_index);
                self.components.need_purge = true;
                self.control.deferred_flag = true;
            }
        }

        record.generation = 0;

        let mut next_generation = entity.generation + 1;

        if next_generation == 0
        {
            warn!("Generation overflow for entity ID {}!", entity.id);
            next_generation = 1;
        }

        self.control.unused_pool.push_back(Entity::new(entity.id, next_generation));

        self.components.num_entities -= 1;

        return true;
    }
    
    /// Returns true if the scene has the given [Entity].
    pub fn has_entity(&self, entity : &Entity) -> bool
    {
        if entity.id >= self.components.entity_records.len()
        {
            return false;
        }
        
        let record = &self.components.entity_records[entity.id];

        record.generation > 0 && entity.generation == record.generation
    }

    pub fn spawn(&mut self, spawnable_id : T::SpawnableIdType, game : &mut GameControl,
                 x : f64, y : f64)
    {
        self.spawn_with(spawnable_id, game, x, y, &DynArgList::new())
    }
    
    pub fn spawn_with(&mut self, spawnable_id : T::SpawnableIdType, game : &mut GameControl,
        x : f64, y : f64, args : &DynArgList)
    {
        let entity = self.add_entity();

        self.control.spawn_control.entity = entity.clone();
        self.control.scene_type.spawn(&mut self.control.spawn_control, spawnable_id, game, x, y, args);

        for list in &mut self.control.spawn_control.deferred_adds.lists
        {
            list.add_to_scene(&mut self.components);
        }

        self.control.spawn_control.deferred_adds.clear();
    }

    /// Sets or unsets the [FreezeFlags] for every [Component] in the given [Entity], deactivating
    ///  the components if any flags are set.
    pub fn set_entity_frozen(&mut self, entity : &Entity, freeze_flags : FreezeFlags, freeze : bool) -> bool
    {
        if entity.id >= self.components.entity_records.len()
        {
            return false;
        }

        let record = &mut self.components.entity_records[entity.id];

        if entity.generation != record.generation
        {
            return false;
        }

        for component_index in &record.component_bits
        {
            let mut component_store = self.components.control.component_stores[component_index].borrow_mut();

            component_store.do_set_frozen(&entity, freeze_flags, freeze);
        }

        return true;
    }

    fn push_callbacks_internal(&mut self, component_type : TypeId, callbacks : ComponentCallbacks)
    {
        self.ensure_boxed_component_registered(component_type);

        let data = self.components.control.data.try_borrow_mut().expect("ComponentStore data already in use!");
        let index = data.component_id_to_index.get(&component_type).expect("Unregistered Component type for callback!");

        self.components.component_callbacks[*index].append(callbacks);
    }

    #[inline(always)]
    fn ensure_boxed_component_registered(&mut self, component_type : TypeId)
    {
        if !self.components.control.component_type_registered(component_type)
        {
            let factory = self.control.spawn_control.store_factories.remove(&component_type).unwrap();
            let component_store = factory();

            self.components.control.register_boxed_component_type(component_type, component_store);
        }
    }
    
    /// Adds the given [ThinkerSystem] to the scene
    pub fn add_thinker_system(&mut self, system : Box<dyn ThinkerSystem<T>>)
    {
        self.thinker_systems.push(system);
        self.thinker_systems.sort_by(|a, b|
        {
            a.priority().partial_cmp(&b.priority()).unwrap()
        });
    }
    
    /// Adds the given [DrawerSystem] to the scene
    pub fn add_drawer_system(&mut self, system : Box<dyn DrawerSystem>)
    {
        self.drawer_systems.push(system);
        self.drawer_systems.sort_by(|a, b|
        {
            a.priority().partial_cmp(&b.priority()).unwrap()
        });
    }
    
    #[cfg(feature = "imgui_feature")]
    pub fn set_imgui_system(&mut self, system : Box<dyn ImGuiSystem<T>>)
    {
        self.imgui_system = system;
    }
    
    fn do_deferred_actions(&mut self)
    {
        if !self.control.deferred_flag
        {
            return;
        }

        if self.control.deferred_callback_adds.len() > 0
        {
            let mut list = Vec::new();
            std::mem::swap(&mut list, &mut self.control.deferred_callback_adds);

            for (component_type, callbacks) in list
            {
                self.push_callbacks_internal(component_type, callbacks);
            }
        }
        
        if self.control.deferred_adds.len() > 0
        {
            let mut list = Vec::new();
            std::mem::swap(&mut list, &mut self.control.deferred_adds);
            
            for entity in &list
            {
                self.add_entity_internal(entity);
            }
        }
        
        if !self.control.spawn_control.deferred_adds.is_empty()
        {
            let mut deferred_component_adds = DeferredComponentAdds::new();
            std::mem::swap(&mut deferred_component_adds, &mut self.control.spawn_control.deferred_adds);

            deferred_component_adds.lists.sort_by(|a, b| { a.priority().cmp(&b.priority()) });

            for list in &mut deferred_component_adds.lists
            {
                list.add_to_scene(&mut self.components);
            }

            std::mem::swap(&mut deferred_component_adds, &mut self.control.spawn_control.deferred_adds);

            self.control.spawn_control.deferred_adds.clear();
        }

        if self.control.deferred_component_removals.len() > 0
        {
            let mut list = Vec::new();
            std::mem::swap(&mut list, &mut self.control.deferred_component_removals);

            for (component_type, entity) in &list
            {
                self.components.remove_component(entity, *component_type);
            }
        }

        if self.control.deferred_removals.len() > 0
        {
            let mut list = Vec::new();
            std::mem::swap(&mut list, &mut self.control.deferred_removals);

            for entity in &list
            {
                self.remove_entity(entity);
            }
        }

        if self.components.need_purge
        {
            for index in &self.components.stores_to_purge
            {
                self.components.control.component_stores[index].borrow_mut().purge_entities();
            }
            self.components.stores_to_purge.clear();
            self.components.need_purge = false;
        }

        if self.control.deferred_freezes.len() > 0
        {
            let mut list = Vec::new();
            std::mem::swap(&mut list, &mut self.control.deferred_freezes);

            for (entity, freeze_flags, freeze) in &list
            {
                self.set_entity_frozen(entity, *freeze_flags, *freeze);
            }
        }
        
        self.control.deferred_flag = false;
    }
}