flecs_ecs 0.2.1

Rust API for the C/CPP flecs ECS library <https://github.com/SanderMertens/flecs>
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
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
//! Compile tests for the flecs docs in the core C repo.
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(clippy::print_stdout)]
#![allow(unused_must_use)]
#![allow(path_statements)]
#![allow(clippy::no_effect)]
#![allow(clippy::if_same_then_else)]
use std::os::raw::c_void;

use flecs_ecs::macros::*;
use flecs_ecs::prelude::*;
use flecs_ecs::sys;

#[derive(Component, Default)]
struct Position {
    pub x: f32,
    pub y: f32,
}

#[derive(Component, Default)]
struct Velocity {
    pub x: f32,
    pub y: f32,
}

#[derive(Component, Default)]
struct Game {
    pub time: f32,
}

#[derive(Component, Default)]
struct Foo;

#[derive(Component, Default)]
struct Plate;

#[derive(Component, Default)]
struct Npc;

#[derive(Component, Default)]
struct Likes;

#[derive(Component, Default)]
struct Tag;

#[derive(Component, Default)]
struct Speed;

#[derive(Component, Default, Clone, Copy, PartialEq)]
struct Mass {
    value: f32,
}

#[derive(Component, Default)]
struct Bar;

#[derive(Component, Default)]
struct SimTime {
    value: f32,
}

#[derive(Component, Default)]
struct SimConfig {
    sim_speed: f32,
}

#[derive(Component, Default)]
struct Player;

#[derive(Component, Default)]
struct Input;

#[derive(Component, Default)]
struct SpaceShip;

#[derive(Component, Default)]
struct Planet;

#[derive(Component, Default)]
struct DockedTo;

#[derive(Component, Default)]
struct Depth {
    value: i32,
}

#[derive(Component, Default)]
struct TimeOfDay {
    pub value: f32,
}

#[derive(Component, Default)]
struct Eats {
    amount: u32,
}

#[derive(Component, Default)]
struct Apples;

#[derive(Component, Default)]
struct MaxSpeed {
    value: u32,
}

#[derive(Component, Default)]
struct Defense {
    value: u32,
}

#[derive(Component, Default)]
struct Serializable;

#[derive(Component, Default)]
struct Gravity {
    x: i32,
    y: i32,
}

#[derive(Component, Default)]
struct Transform;

#[derive(Component, Default)]
struct Mesh;

#[derive(Component, Default)]
struct Health {
    value: u32,
}

#[derive(Component, Default)]
struct Archer;

#[derive(Component, Default)]
struct Node;

fn flecs_system_docs_compile_test() {
    let world = World::new();

    let sys = world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .each(|(p, v)| {
            p.x += v.x;
            p.y += v.y;
        });
    sys.run();

    world.progress();

    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .kind(0)
        .each(|(p, v)| {
            p.x += v.x;
            p.y += v.y;
        });

    let q = world.new_query::<(&mut Position, &Velocity)>();

    // Query iteration (each)
    q.each(|(p, v)| { /* ... */ });

    // System iteration (each)
    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .each(|(p, v)| { /* ... */ });

    // Query iteration (run)
    q.run(|mut it| {
        while it.next() {
            let mut p = it
                .field_mut::<Position>(0)
                .expect("query term changed and not at the same index anymore");
            let v = it
                .field::<Velocity>(1)
                .expect("query term changed and not at the same index anymore");
            for i in it.iter() {
                p[i].x += v[i].x;
                p[i].y += v[i].y;
            }
        }
    });

    // System iteration (run)
    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .run(|mut it| {
            while it.next() {
                let mut p = it
                    .field_mut::<Position>(0)
                    .expect("query term changed and not at the same index anymore");
                let v = it
                    .field::<Velocity>(1)
                    .expect("query term changed and not at the same index anymore");
                for i in it.iter() {
                    p[i].x += v[i].x;
                    p[i].y += v[i].y;
                }
            }
        });

    // Query iteration (run_iter)
    q.run(|mut it| {
        while it.next() {
            let mut p = it.field_mut::<Position>(0);
            let v = it.field::<Velocity>(1);
            for i in it.iter() {
                p[i].x += v[i].x;
                p[i].y += v[i].y;
            }
        }
    });

    // System iteration (run_iter)
    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .run(|mut it| {
            while it.next() {
                let mut p = it.field_mut::<Position>(0);
                let v = it.field::<Velocity>(1);
                for i in it.iter() {
                    p[i].x += v[i].x;
                    p[i].y += v[i].y;
                }
            }
        });

    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .each_iter(|it, i, (p, v)| {
            p.x += v.x * it.delta_time();
            p.y += v.y * it.delta_time();
        });

    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .run(|mut it| {
            while it.next() {
                let mut p = it.field_mut::<Position>(0);
                let v = it.field::<Velocity>(1);
                for i in it.iter() {
                    p[i].x += v[i].x * it.delta_time();
                    p[i].y += v[i].y * it.delta_time();
                }
            }
        });

    let delta_time = 1.0;
    world.progress_time(delta_time);

    world.system_named::<()>("PrintTime").run(|mut it| {
        while it.next() {
            println!("Time: {}", it.delta_time());
        }
    });

    world
        .system_named::<&Game>("PrintTime")
        .term_at(0)
        .singleton()
        .kind(id::<flecs::pipeline::OnUpdate>())
        .run(|mut it| {
            while it.next() {
                println!("Time: {}", it.field::<Game>(0)[9].time);
            }
        });

    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .kind(id::<flecs::pipeline::OnUpdate>())
        .each(|(p, v)| {
            // ...
        });

    // Phases must have the EcsPhase tag
    #[derive(Component, Default)]
    struct Physics;

    // a component to represent the phase
    let physics = world
        .component::<Physics>()
        .add(id::<flecs::pipeline::Phase>());
    // a (dynamic) entity to represent the phase
    let collisions = world.entity().add(id::<flecs::pipeline::Phase>());

    // Phases can (but don't have to) depend on other phases which forces ordering
    physics.add_trait::<(flecs::DependsOn, flecs::pipeline::OnUpdate)>();
    collisions.add_trait::<(flecs::DependsOn, Physics)>();

    // Custom phases can be used just like regular phases
    world
        .system_named::<(&Position, &Velocity)>("Collide")
        .kind(collisions) // .has(Physics::id())
        .each(|(p, v)| {
            // ...
        });

    world
        .pipeline()
        .with(id::<flecs::system::System>())
        .with(id::<flecs::pipeline::Phase>())
        .cascade_id(id::<flecs::DependsOn>())
        .without(id::<flecs::Disabled>())
        .up_id(id::<flecs::DependsOn>())
        .without(id::<flecs::Disabled>())
        .up_id(id::<flecs::ChildOf>())
        .build();

    // Create custom pipeline
    let pipeline = world
        .pipeline()
        .with(id::<flecs::system::System>())
        .with(Foo::id()) // or `.with(foo) if an id`
        .build();

    // Configure the world to use the custom pipeline
    world.set_pipeline(pipeline);

    // Create system
    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .kind(Foo::id()) // or `.kind(foo) if an id`
        .each(|(p, v)| {
            p.x += v.x;
            p.y += v.y;
        });

    // Runs the pipeline & system
    world.progress();

    sys.disable_self();
    sys.enable_self();
    sys.add(id::<flecs::Disabled>());

    world
        .system::<&Position>()
        .with(&mut Transform::id())
        .each(|p| {
            // ...
        });

    world
        .system::<&Position>()
        .with(&Transform::id())
        .each(|p| {
            // ...
        });

    world
        .system_named::<&Plate>("AssignPlate")
        .immediate(true)
        .run(|mut it| {
            while it.next() {
                // ...
            }
        });

    world
        .system_named::<&Plate>("AssignPlate")
        .immediate(true)
        .run(|mut it| {
            while it.next() {
                // ECS operations ran here are visible after running the system
                it.world().defer_suspend();
                // ECS operations ran here are immediately visible
                it.world().defer_resume();
                // ECS operations ran here are visible after running the system
            }
        });

    world.set_threads(4);

    world.system::<&Position>().par_each(|p| {
        // ...
    });

    world.set_task_threads(4);

    world
        .system::<&Position>()
        .set_interval(1.0) // Run at 1Hz
        .each(|p| {
            // ...
        });

    world
        .system::<&Position>()
        .set_rate(2) // Run every other frame
        .each(|p| {
            // ...
        });

    // A rate filter can be created with .set_rate(2)
    //let tick_source = world.timer().set_interval(1.0);
    //TODO

    // world
    //     .system::<(&Position, &Velocity)>()
    //     .tick_source_id(tick_source) // Set tick source for system
    //     .each(|(p, v)| {
    //         // ...
    //     });

    //TODO

    //
    // // Pause timer
    // tick_source.stop();

    // // Resume timer
    // tick_source.start();
    //
}

fn flecs_query_docs_compile_test() {
    let world = World::new();

    // Create Position, Velocity query that matches empty archetypes.
    let q = world
        .query::<(&mut Position, &Velocity)>()
        .set_cached()
        .query_flags(QueryFlags::MatchEmptyTables)
        .build();

    // Delete empty archetypes that have been empty for 10 calls to this function.
    world.delete_empty_tables(sys::ecs_delete_empty_tables_desc_t {
        clear_generation: 10,
        delete_generation: 0,
        time_budget_seconds: 0.0,
    });

    let q = world.new_query::<(&mut Position, &Velocity)>();

    q.each(|(p, v)| {
        p.x += v.x;
        p.y += v.y;
    });

    let add_npc = true;

    let mut q = world.query::<(&mut Position, &Velocity)>();
    q.with(&Velocity::id());

    if add_npc {
        q.with(&Foo::id()); // Conditionally add
    }

    q.build(); // Create query

    let q = world.new_query::<(&mut Position, &Velocity)>();

    q.each_entity(|e, (p, v)| {
        println!("Entity: {}", e.name());
        p.x += v.x;
        p.y += v.y;
    });

    let q = world
        .query::<&Position>()
        .read((Likes::id(), id::<flecs::Wildcard>()))
        .build();

    q.each_iter(|it, index, p| {
        println!(
            "Entity: {}: {}",
            it.get_entity(index).unwrap().name(),
            it.id(1).to_str()
        );
    });

    #[derive(Component, Default)]
    struct Tag;

    world.new_query::<&Tag>().each_entity(|e, tag| { /* */ });

    world
        .query::<()>()
        .with(&Tag)
        .build()
        .each_entity(|e, _| { /* */ });

    let q = world.new_query::<(&Position, &Velocity)>();

    q.run(|mut it| {
        while it.next() {
            let mut p = it.field_mut::<Position>(0);
            let v = it.field::<Velocity>(1);
            for i in it.iter() {
                p[i].x += v[i].x;
                p[i].y += v[i].y;
                println!("Entity: {}", it.get_entity(i).unwrap().name());
            }
        }
    });

    let q = world.new_query::<&Position>();

    q.each_entity(|e, p| {
        e.add(Velocity::id()); // OK
    });

    let q = world.new_query::<&Position>();

    world.defer(|| {
        q.each_entity(|e, p| {
            e.add(Velocity::id()); // OK
        });
    }); // operations are executed here

    let q = world.new_query::<&Position>();

    world.defer_begin();

    q.each_entity(|e, p| {
        e.add(Velocity::id()); // OK
    });

    world.defer_end(); // operations are executed here

    let q = world.new_query::<(&mut Position, &Velocity)>();

    q.each(|(p, v)| { /* */ });

    let q = world.query::<&mut Position>().with(&Velocity::id()).build();

    let npc = world.entity();
    let platoon_01 = world.entity();

    let q = world
        .query::<(&mut Position, &Velocity)>()
        .with(npc)
        .with(platoon_01)
        .build();

    // Register component type so we can look it up by name
    world.component::<Position>();

    // Create entity with name so we can look it up
    let npc = world.entity_named("npc");

    let q = world
        .query::<(&Position, &Npc)>()
        .with("npc")
        .with("Position")
        .build();

    let e = world.entity().add(Position::id()).add(Velocity::id());

    let q = world.query::<()>().with(id::<flecs::Wildcard>()).build();

    let e = world.entity().add(Position::id()).add(Velocity::id());

    let q = world.query::<()>().with(id::<flecs::Any>()).build();

    #[derive(Component, Default)]
    struct Eats {
        value: f32,
    }

    #[derive(Component, Default)]
    struct Apples;

    let q = world.new_query::<&mut (Eats, Apples)>();

    q.each(|eats| {
        eats.value += 1.0;
    });

    let eats = world.component::<Eats>();
    let apples = world.component::<Apples>();

    let q1 = world.query::<()>().with((Eats::id(), Apples::id())).build();

    let q2 = world.query::<()>().with((Eats::id(), apples)).build();

    let q3 = world.query::<()>().with((eats, apples)).build();

    let q = world
        .query::<()>()
        .term()
        .set_first(Eats::id())
        .set_second(apples)
        .build();

    let q = world
        .query::<()>()
        .term()
        .set_first("Eats")
        .set_second("Apples")
        .build();

    let q = world
        .query::<()>()
        .with((Eats::id(), id::<flecs::Wildcard>()))
        .build();

    q.each_iter(|it, index, _| {
        let pair = it.pair(0).unwrap();
        let second = pair.second_id();
        let e = it.get_entity(index).unwrap();

        println!("Entity {} likes {}", e.name(), second.name());
    });

    // The following two queries are the same:
    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .set_inout_kind(InOutKind::In)
        .build();

    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .set_in() // shorthand for .set_inout_kind(InOutKind::In)
        .build();

    // Velocity term will be added with InOutKind::In modifier due to `&`
    let q = world.new_query::<(&mut Position, &Velocity)>();

    let q = world
        .query::<()>()
        .with(&mut Position::id())
        .with(&Velocity::id()) // uses InOutKind::In modifier
        .build();

    let q = world
        .query::<()>()
        .with(&mut Position::id())
        .with(&Velocity::id())
        .build();

    q.run(|mut it| {
        while it.next() {
            let p = it.field_mut::<Position>(0);
            let v = it.field::<Velocity>(1);
        }
    });

    let q = world
        .query::<()>()
        .with(Position::id())
        .set_inout()
        .with(Velocity::id())
        .set_in()
        .build();

    let q = world
        .query::<()>()
        .with(Position::id())
        .and()
        .with(Velocity::id())
        .and()
        .build();

    let q = world.new_query::<(&mut Position, &Velocity)>();

    let q2 = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .build();

    let q3 = world
        .query::<()>()
        .with(Position::id())
        .set_oper(OperKind::And)
        .with(Velocity::id())
        .set_oper(OperKind::And)
        .build();

    // Position, Velocity || Speed, Mass
    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .set_oper(OperKind::Or)
        .with(Speed::id())
        .with(Mass::id())
        .build();

    q.run(|mut it| {
        while it.next() {
            let p = it.field_mut::<Position>(0);
            let v = it.field::<Mass>(2); // not 4, because of the Or expression

            let vs_id = it.id(1);
            if vs_id == world.component_id::<Velocity>() {
                // We can only use ecs_field if the field type is the same for all results,
                // but we can use table_range() to get the table column directly.
                let v = it.range().unwrap().get_mut::<Velocity>();
                // iterate as usual
            } else if vs_id == world.component_id::<Speed>() {
                let s = it.range().unwrap().get_mut::<Speed>();
                // iterate as usual
            }
        }
    });

    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .or()
        .with(Speed::id())
        .with(Mass::id())
        .build();

    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .set_oper(OperKind::Not)
        .build();

    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .not()
        .build();

    let q = world
        .query::<()>()
        .with(Position::id())
        .without(Velocity::id())
        .build();

    let q = world.new_query::<(&Position, Option<&Velocity>)>();

    q.each(|(p, v)| {
        if let Some(v) = v {
            // ...
        }
    });

    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .set_oper(OperKind::Optional)
        .build();

    q.run(|mut it| {
        while it.next() {
            let p = it.field_mut::<Position>(0);
            if let Some(v) = it.field::<Velocity>(1) {
                // iterate as usual
            }
        }
    });

    let q = world
        .query::<()>()
        .with(Position::id())
        .with(Velocity::id())
        .optional()
        .build();

    world
        .query::<()>()
        // $this == Foo
        .with((id::<flecs::PredEq>(), Foo::id()))
        // $this != Foo
        .without((id::<flecs::PredEq>(), Bar::id()))
        // $this == "Foo"
        .with(id::<flecs::PredEq>())
        .set_second("Foo")
        .flags(sys::EcsIsName)
        // $this ~= "Fo"
        .with(id::<flecs::PredMatch>())
        .set_second("Fo")
        .flags(sys::EcsIsName)
        .build();

    let type_list = world.prefab().add(Position::id()).add(Velocity::id());

    let q = world
        .query::<()>()
        .with(type_list)
        .set_oper(OperKind::AndFrom) // match Position, Velocity
        .with(type_list)
        .set_oper(OperKind::OrFrom) // match Position || Velocity
        .with(type_list)
        .set_oper(OperKind::NotFrom) // match !Position, !Velocity
        .build();

    let q = world
        .query::<()>()
        .with(type_list)
        .and_from()
        .with(type_list)
        .or_from()
        .with(type_list)
        .not_from()
        .build();

    world
        .query::<()>()
        // Position, !{ Velocity || Speed }
        .with(Position::id())
        .scope_open()
        .not()
        .with(Velocity::id())
        .or()
        .with(Speed::id())
        .scope_close()
        .build();

    let game = world.entity().add(SimTime::id());

    let q = world
        .query::<()>()
        .with(Position::id()) // normal term, uses $this source
        .with(Velocity::id()) // normal term, uses $this source
        .with(SimTime::id())
        .set_src(game) // fixed source, match SimTime on Game
        .build();

    q.run(|mut it| {
        while it.next() {
            let mut p = it.field_mut::<Position>(0);
            let v = it.field::<Velocity>(1);
            let st = it.field::<SimTime>(2);

            for i in it.iter() {
                p[i].x += v[i].x * st[0].value;
                p[i].y += v[i].y * st[0].value;
            }
        }
    });

    let q = world
        .query::<(&mut Position, &Velocity, &SimTime)>()
        .term_at(2)
        .set_src(game) // fixed source for 3rd template argument (SimTime)
        .build();

    // Because all components are now part of the query type, we can use each
    q.each_entity(|e, (p, v, st)| {
        p.x += v.x * st.value;
        p.y += v.y * st.value;
    });

    let cfg = world.entity().add(SimConfig::id());

    let q = world
        .query::<(&SimConfig, &mut SimTime)>()
        .term_at(0)
        .set_src(cfg)
        .term_at(1)
        .set_src(game)
        .build();

    // Ok (note that it.count() will be 0)
    q.run(|mut it| {
        while it.next() {
            let sc = it.field::<SimConfig>(0);
            let mut st = it.field_mut::<SimTime>(1);
            st[0].value += sc[0].sim_speed; // 0 because it's a single source element
        }
    });

    // Ok
    q.each(|(sc, st)| {
        st.value += sc.sim_speed;
    });

    // Ok
    q.each_iter(|it, index, (sc, st)| {
        st.value += sc.sim_speed;
    });

    // Not ok: there is no entity to pass to first argument
    q.each_entity(|e, (sc, st)| {
        st.value += sc.sim_speed;
    });

    let q = world
        .query::<(&SimConfig, &SimTime)>()
        .term_at(0)
        .set_src("cfg")
        .term_at(1)
        .set_src("game")
        .build();

    let q = world
        .query::<(&Player, &Position)>()
        .with(Input::id())
        .set_src(Input::id()) // match Input on itself
        .build();

    let q = world
        .query::<(&Player, &Position)>()
        .with(Input::id())
        .singleton() // match Input on itself
        .build();

    let q = world
        .query::<(&Player, &Position, &Input)>()
        .term_at(2)
        .singleton() // match Input on itself
        .build();

    // These three queries are the same:
    let q1 = world
        .query::<()>()
        .with(Mass::id())
        .up_id(id::<flecs::ChildOf>())
        .build();

    let q2 = world
        .query::<()>()
        .with(Mass::id())
        .up() // defaults to .up(flecs::ChildOf)
        .build();

    let q3 = world
        .query::<()>()
        .with(Mass::id())
        .parent() // shortcut for .up(flecs::ChildOf)
        .build();

    // Register an inheritable component 'Mass'
    world
        .component::<Mass>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    // These two queries are the same:
    let q1 = world
        .query::<()>()
        .with(Mass::id())
        .self_()
        .up_id(id::<flecs::IsA>())
        .build();

    let q2 = world
        .query::<()>()
        .with(Mass::id()) // defaults to .self().up(flecs::IsA)
        .build();

    // Register an inheritable component 'Mass'
    world
        .component::<Mass>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    let base = world.entity().add(Mass::id());

    let parent = world.entity().is_a(base); // inherits Mass

    let child = world.entity().child_of(parent);

    // Matches 'child', because parent inherits Mass from prefab
    let q = world
        .query::<()>()
        .with(Mass::id())
        .up() // traverses ChildOf upwards
        .build();

    // Register inheritable 'Position' component
    world
        .component::<Position>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    let base = world.entity().add(Position::id());

    let inst = world.entity().is_a(base); // short for .add(flecs::IsA, base);

    // The following two queries are the same:
    let q1 = world.new_query::<&Position>();

    let q2 = world
        .query::<&Position>()
        .term_at(0)
        .self_()
        .up_id(flecs::IsA::ID)
        .build();

    let parent = world.entity().add(Position::id());

    let child = world.entity().child_of(parent); // short for .add((flecs::ChildOf::ID, base));

    let q = world.query::<&Position>().term_at(0).up().build();

    // Create a new traversable relationship
    let contained_by = world.entity().add(id::<flecs::Traversable>());

    let parent = world.entity().add(Position::id());

    let child = world.entity().add((contained_by, parent));

    let q = world
        .query::<&Position>()
        .term_at(0)
        .up_id(contained_by)
        .build();

    let q = world
        .query::<(&Position, &Mass)>()
        .term_at(0)
        // Never inherit Position
        .self_()
        .build();

    q.run(|mut it| {
        while it.next() {
            let mut p = it.field_mut::<Position>(0);
            let m = it.field::<Mass>(1);

            if it.is_self(1) {
                // Mass is matched on self, access as array
                for i in it.iter() {
                    p[i].x += 1.0 / m[i].value;
                    p[i].y += 1.0 / m[i].value;
                }
            } else {
                // Mass is matched on other entity, access as single value
                for i in it.iter() {
                    p[i].x += 1.0 / m[0].value; // [0] because it is a single value
                    p[i].y += 1.0 / m[0].value;
                }
            }
        }
    });

    let q = world
        .query::<()>()
        .with(SpaceShip::id())
        .with(DockedTo::id())
        .set_second("$Location")
        .with(Planet::id())
        .set_src("$Location")
        .build();

    let q = world
        .query::<()>()
        .with(SpaceShip::id())
        .with(DockedTo::id())
        .second()
        .set_var("$Location")
        .with(Planet::id())
        .src()
        .set_var("$Location")
        .build();

    let earth = world.entity();

    let location_var = q.find_var("$Location").unwrap();

    q.iterable().set_var(location_var, earth).each(|it| {
        // iterate as usual
    });

    let earth = world.entity();

    q.iterable().set_var_expr("$Location", earth).each(|it| {
        // iterate as usual
    });

    #[derive(Component, Default)]
    struct Movement {
        value: Entity,
    }

    //TODO META
    /*
    struct Movement {
      flecs::entity_t value;
    };

    // Register 'Movement' component and reflection data
    world.component::<Movement>()
      .member("value", &Movement::value);

    // Create two entities for the direction
    flecs::entity Left = world.entity();
    flecs::entity Right = world.entity();

    // Create two entities with different directions
    flecs::entity e1 = world.entity().set(Movement{ Left });
    flecs::entity e2 = world.entity().set(Movement{ Right });

    // Create query that only matches e1
    flecs::query<> q = world.query()
      .with("Movement.value", Left)
      .build();
        */

    // Query used for change detection. Note that change detection is not enabled on
    // the query itself, but by calling change detection functions for the query.
    let q_read = world.new_query::<&Position>();

    // Query used to create changes
    let q_write = world.new_query::<&mut Position>(); // defaults to inout

    // Test if changes have occurred for anything matching the query. If this is the
    // first call to the function, it will enable change detection for the query.
    let changed = q_read.is_changed();

    // Setting a component will update the changed state
    let e = world.entity().set(Position { x: 10.0, y: 20.0 });

    q_write.run(|mut it| {
        while it.next() {
            if !changed {
                // If no changes are made to the iterated table, the skip function can be
                // called to prevent marking the matched components as dirty.
                it.skip();
            } else {
                // Iterate as usual. It does not matter whether the code actually writes the
                // components or not: when a table is not skipped, components matched with
                // inout or out terms will be marked dirty by the iterator.
            }
        }
    });

    q_read.run(|mut it| {
        while it.next() {
            if it.is_changed() {
                // Check if the current table has changed. The change state will be reset
                // after the table is iterated, so code can respond to changes in individual
                // tables.
            }
        }
    });

    // Use readonly term for component used for sorting
    let q = world
        .query::<(&Depth, &Position)>()
        .order_by::<Depth>(|e1, d1: &Depth, e2, d2: &Depth| {
            (d1.value > d2.value) as i32 - (d1.value < d2.value) as i32
        })
        .build();

    let depth_id = world.component::<Depth>();

    let q = world
        .query::<&Position>()
        .with(depth_id)
        .set_in()
        .order_by_id(depth_id, |e1, d1: *const c_void, e2, d2: *const c_void| {
            let d1 = unsafe { &*(d1 as *const Depth) };
            let d2 = unsafe { &*(d2 as *const Depth) };
            (d1.value > d2.value) as i32 - (d1.value < d2.value) as i32
        })
        .build();

    let q = world
        .query::<&Position>()
        .order_by_id(0, |e1, _d1: *const c_void, e2, _d2: *const c_void| {
            (e1 > e2) as i32 - (e1 < e2) as i32
        })
        .build();

    //TODO group by section

    #[derive(Component)]
    struct Unit;

    let unit = world.component::<Unit>();
    let melee_unit = world.entity().is_a(Unit::id());
    let ranged_unit = world.entity().is_a(Unit::id());

    let unit_01 = world.entity().add(melee_unit);
    let unit_02 = world.entity().add(ranged_unit);

    // Matches entities with Unit, MeleeUnit and RangedUnit
    let q = world.query::<&Unit>();

    // Iterate as usual

    // Create locatedin relationship with transitive property
    #[derive(Component)]
    struct LocatedIn;

    world
        .component::<LocatedIn>()
        .add(id::<flecs::Transitive>());

    let new_york = world.entity();
    let manhattan = world.entity().add((LocatedIn::id(), new_york));
    let central_park = world.entity().add((LocatedIn::id(), manhattan));
    let bob = world.entity().add((LocatedIn::id(), central_park));

    // Matches ManHattan, CentralPark, bob
    let q = world
        .query::<()>()
        .with((LocatedIn::id(), new_york))
        .build();

    // Iterate as usual

    // Matches:
    //  - ManHattan (Place = newyork)
    //  - CentralPark (Place = ManHattan, newyork)
    //  - bob (Place = CentralPark, ManHattan, newyork)
    let q = world
        .query::<()>()
        .with(LocatedIn::id())
        .set_second("$Place")
        .build();

    #[derive(Component)]
    struct City;

    // Add City property to newyork
    new_york.add(City::id());

    // Matches:
    //  - ManHattan (Place = newyork)
    //  - CentralPark (Place = newyork)
    //  - bob (Place = newyork)

    let q = world
        .query::<()>()
        .with(LocatedIn::id())
        .set_second("$Place")
        .with(City::id())
        .set_src("$Place")
        .build();

    let tree = world.entity();
    let oak = world.entity().is_a(tree);

    // Matches Tree, Oak
    let q = world.query::<()>().with((id::<flecs::IsA>(), tree)).build();

    // Iterate as usual
}

fn flecs_entities_components_docs_compile_test() {
    let world = World::new();

    let my_entity = world.entity();

    my_entity.destruct();

    let e1 = world.entity(); // Returns 500v0
    e1.destruct(); // Recycles 500
    let e2 = world.entity(); // Returns 500v1
    // Fails, 500v0 is not alive
    e1.add(Npc::id());
    // OK, 500v1 is alive
    e2.add(Npc::id());

    let e1 = world.entity();
    e1.destruct();
    e1.destruct(); // OK: post condition is satisfied

    my_entity.clear();

    let e1 = world.entity();
    let e2 = world.entity();
    e1.destruct();
    e1.is_alive(); // False
    e2.is_alive(); // True

    let e1 = world.entity();
    let e2 = world.entity();
    e1.destruct();
    e1.is_valid(); // False
    world.entity_from_id(0).is_valid(); // False

    let e = world.make_alive(1000);

    //TODO does not exist yet
    //world.set_version(versioned_id);

    world.set_entity_range(5000, 0);

    world.set_entity_range(5000, 10000);

    world.enable_range_check(true);

    let e = world.entity_named("MyEntity");
    if e == world.lookup("MyEntity") {
        // true
    }
    println!("{}", e.name());

    let p = world.entity_named("Parent");
    let e = world.entity_named("Child").child_of(p);
    if e == world.lookup("Parent::Child") {
        // true
    }

    let p = world.entity_named("Parent");
    let e = world.entity_named("Child").child_of(p);
    if e == p.lookup("Child") {
        // true
    }

    let p = world.entity_named("Parent");
    let e = world.entity_named("Child").child_of(p);
    // Returns entity name, does not allocate
    println!("{}", e.name()); // Child
    // Returns entity path, does allocate
    println!("{}", e.path().unwrap()); // Parent.Child

    let e1 = world.entity_named("Parent::Child");
    let e2 = world.entity_named("Parent::Child");
    if e1 == e2 {
        // true
    }

    let e = world.entity_named("Foo");
    // Change name
    e.set_name("Bar");

    let ten = world.entity_named("10");
    let twenty = world.entity_named("20");

    let e = world.entity();
    // Enable entity
    e.enable_self();
    // Disable entity
    e.disable_self();

    // Three entities to disable
    let e1 = world.entity();
    let e2 = world.entity();
    let e3 = world.entity();
    // Create prefab that has the three entities
    let p = world.prefab();
    p.add(e1);
    p.add(e2);
    p.add(e3);
    // Disable entities
    p.disable_self();
    // Enable entities
    p.enable_self();

    // Three entities to disable
    let e1 = world.entity();
    let e2 = world.entity();
    let e3 = world.entity();

    // Create prefab hierarchy with the three entities
    let p1 = world.prefab().add(e1);
    let p2 = world.prefab().is_a(p1).add(e2).add(e3);

    // Disable e1, e2, e3
    p2.disable_self();

    // Enable e1
    p1.enable_self();

    e.add(id::<flecs::Disabled>());

    // Get the entity for the Position component
    let pos = world.component::<Position>();
    // Component entities have the Component component
    pos.get::<&flecs::Component>(|comp_data| {
        println!(
            "size: {}, alignment: {}",
            comp_data.size, comp_data.alignment
        );
    });

    // Register a sparse component
    world.component::<Position>().add_trait::<flecs::Sparse>();

    fn main() {
        let world = World::new();
        let e1 = world
            .entity()
            .set(Position { x: 10.0, y: 20.0 }) // Position registered here
            .set(Velocity { x: 1.0, y: 2.0 }); // Velocity registered here
        let e2 = world
            .entity()
            .set(Position { x: 10.0, y: 20.0 }) // Position already registered
            .set(Velocity { x: 1.0, y: 2.0 }); // Velocity already registered
    }

    world.component::<Position>();

    use flecs_ecs::prelude::*;
    #[derive(Component)]
    struct Movement;
    impl Module for Movement {
        fn module(world: &World) {
            world.module::<Movement>("Movement");
            // Define components, systems, triggers, ... as usual. They will be
            // letmatically created inside the scope of the module.
        }
    }
    let world = World::new();
    world.import::<Movement>();

    //TODO Rust API does not exist yet
    // let desc = sys::ecs_component_desc_t {
    //     type_: sys::ecs_type_info_t {
    //         size: 8,
    //         alignment: 8,
    //         ..Default::default()
    //     },
    //     ..Default::default()
    // };
    // let comp = sys::ecs_component_init(world, &desc);
    // let e = world.entity();
    // // Add component
    // e.add(comp);
    // // Get component
    // let ptr = e.get(comp);

    //ToDO Rust API does not exist yet
    // let desc = ecs_component_desc_t {
    //     entity: world.entity_named("MyComponent"),
    //     size: 8,
    //     alignment: 8,
    //     ..Default::default()
    // };
    // let comp = ecs_component_init(world, &desc);
    // let e = world.entity();
    // // Add component
    // e.add(comp);
    // // Get component
    // let ptr = e.get(comp);

    let pos = world.component::<Position>();

    // Create entity with Position
    let e = world.entity().add(Position::id());

    // Unregister the component
    pos.destruct();

    // Position is removed from e

    // Set singleton
    world.set(TimeOfDay { value: 0.5 });
    // Get singleton
    world.get::<&TimeOfDay>(|time| println!("{}", time.value));

    // Set singleton
    world.set(TimeOfDay { value: 0.5 });
    // Equivalent to:
    world.component::<TimeOfDay>().set(TimeOfDay { value: 0.5 });

    // Register toggle-able component
    world
        .component::<Position>()
        .add_trait::<flecs::CanToggle>();
    let e = world.entity().set(Position { x: 10.0, y: 20.0 });

    // Disable component
    e.disable(Position::id());
    assert!(!e.is_enabled(Position::id())); // False
    // Enable component
    e.enable(Position::id());
    assert!(e.is_enabled(Position::id())); // True
}

fn flecs_docs_relationships_compile_test() {
    let world = World::new();

    let likes = world.entity();
    let bob = world.entity();
    let alice = world.entity();

    // bob likes alice
    bob.add((likes, alice));

    // bob likes alice no more
    bob.remove((likes, alice));

    let bob = world.entity();
    let eats = world.entity();
    let apples = world.entity();
    let pears = world.entity();
    bob.add((eats, apples));
    bob.add((eats, pears));
    bob.has((eats, apples)); // true
    bob.has((eats, pears)); // true

    // Find all entities that eat apples
    let q = world.query::<()>().expr("(Eats, Apples)").build();
    // Find all entities that eat anything
    let q = world.query::<()>().expr("(Eats, *)").build();
    // With the query builder API:
    let q = world.query::<()>().with((eats, apples)).build();
    // Or when using pair types, when both relationship & target are compile time types, they can be represented as a tuple:
    let q = world.new_query::<&(Eats, Apples)>();

    bob.has((eats, apples));

    bob.has((eats, flecs::Wildcard::ID));

    let parent = bob.parent();

    let food = bob.target(eats, 0); // first target

    let mut index = 0;
    while bob.target(eats, index).is_some() {
        index += 1;
    }

    let parent = bob.target_for(Position::id(), flecs::ChildOf::ID);

    bob.each_component(|id| {
        if id.is_pair() {
            let first = id.first_id();
            let second = id.second_id();
        }
    });

    world
        .query::<()>()
        .with((eats, apples))
        .build()
        .each_entity(|e, _| {
            // Iterate as usual
        });

    world
        .query::<()>()
        .with((eats, flecs::Wildcard::ID))
        .build()
        .each_iter(|it, i, _| {
            let food = it.pair(0).unwrap().second_id(); // Apples, ...
            let e = it.get_entity(i).unwrap();
            // Iterate as usual
        });

    let parent = world.entity();

    parent.each_child(|child| {
        // ...
    });

    // Empty types (types without members) are letmatically interpreted as tags
    #[derive(Component)]
    struct Begin;
    #[derive(Component)]
    struct End;
    // Tags
    let likes = world.entity();
    let apples = world.entity();
    let e = world.entity();
    // Both likes and Apples are tags, so (likes, Apples) is a tag
    e.add((likes, apples));
    // Eats is a type and Apples is a tag, so (Eats, Apples) has type Eats
    e.set_pair::<Eats, Apples>(Eats { amount: 1 });
    // Begin is a tags and Position is a type, so (Begin, Position) has type Position
    e.set_pair::<Begin, Position>(Position { x: 10.0, y: 20.0 });
    e.set_pair::<End, Position>(Position { x: 100.0, y: 20.0 }); // Same for End
    // ChildOf has the Tag property, so even though Position is a type, the pair
    // does not assume the Position type
    e.add((flecs::ChildOf::ID, world.component_id::<Position>()));
    e.add((id::<flecs::ChildOf>(), Position::id()));

    let e = world.entity();
    let first = world.entity();
    let second = world.entity();
    let third = world.entity();
    // Add component position 3 times, for 3 different objects
    e.set_first::<Position>(Position { x: 1.0, y: 2.0 }, first);
    e.set_first::<Position>(Position { x: 3.0, y: 4.0 }, second);
    e.set_first::<Position>(Position { x: 5.0, y: 6.0 }, third);

    let q = world
        .query::<()>()
        .with((likes, flecs::Wildcard::ID))
        .build();
    q.each_iter(|it, i, _| {
        println!(
            "entity {} has relationship {} {}",
            it.get_entity(i).unwrap(),
            it.pair(0).unwrap().first_id().name(),
            it.pair(0).unwrap().second_id().name()
        );
    });

    let q = world.query::<()>().expr("(likes, *)").build();

    // bob eats apples and pears
    let bob = world.entity();
    let eats = world.entity();
    let apples = world.entity();
    let pears = world.entity();
    bob.add((eats, apples));
    bob.add((eats, pears));
    // Find all (Eats, *) relationships in bob's type
    bob.each_pair(eats, flecs::Wildcard::ID, |id| {
        println!("bob eats {}", id.second_id().name());
    });
    // For target wildcard pairs, each_target() can be used:
    bob.each_target(eats, |entity| {
        println!("bob eats {}", entity.name());
    });

    let apple = world.entity();
    let fruit = world.entity();
    apple.add((flecs::IsA::ID, fruit));

    apple.is_a(fruit);

    let granny_smith = world.entity();
    granny_smith.add((flecs::IsA::ID, apple));

    let spaceship = world
        .entity()
        .set(MaxSpeed { value: 100 })
        .set(Defense { value: 50 });
    let frigate = world
        .entity()
        .is_a(spaceship) // shorthand for .add(flecs::IsA, Spaceship)
        .set(Defense { value: 75 });

    // Obtain the inherited component from Spaceship
    let is_100 = frigate.get::<&mut MaxSpeed>(|v| {
        v.value == 100 // True
    });

    // Obtain the overridden component from Frigate
    let is_75 = frigate.get::<&mut Defense>(|v| {
        v.value == 75 // True
    });

    let fast_frigate = world.entity().is_a(frigate).set(MaxSpeed { value: 200 });
    // Obtain the overridden component from FastFrigate
    let is_200 = fast_frigate.get::<&mut MaxSpeed>(|v| {
        v.value == 200 // True
    });
    // Obtain the inherited component from Frigate
    let is_75 = fast_frigate.get::<&mut Defense>(|v| {
        v.value == 75 // True
    });

    let spaceship = world.entity();
    let cockpit = world.entity();
    cockpit.add((flecs::ChildOf::ID, spaceship));

    cockpit.child_of(spaceship);

    let parent = world.entity_named("Parent");
    let child = world.entity_named("Child").child_of(parent);
    child == world.lookup("Parent::Child"); // true
    child == parent.lookup("Child"); // true

    let parent = world.entity();
    let prev = world.set_scope(parent);
    let child_a = world.entity();
    let child_b = world.entity();
    // Restore the previous scope
    world.set_scope(prev);
    child_a.has((flecs::ChildOf::ID, parent)); // true
    child_b.has((flecs::ChildOf::ID, parent)); // true

    let parent = world.entity().run_in_scope(|| {
        let child_a = world.entity();
        let child_b = world.entity();
        child_a.has((flecs::ChildOf::ID, parent)); // true
        child_b.has((flecs::ChildOf::ID, parent)); // true
    });
}

fn flecs_docs_quick_start_compile_test() {
    let world = World::new();
    let eats = world.entity();
    let apples = world.entity();
    let pears = world.entity();
    let grows = world.entity();

    let world = World::new();

    // Do the ECS stuff

    let e = world.entity();
    e.is_alive(); // true!

    e.destruct();
    e.is_alive(); // false!

    let e = world.entity_named("bob");

    println!("Entity name: {}", e.name());

    let e = world.lookup("bob");

    let e = world.entity();

    // Add a component. This creates the component in the ECS storage, but does not
    // assign it with a value.
    e.add(Velocity::id());

    // Set the value for the Position & Velocity components. A component will be
    // added if the entity doesn't have it yet.
    e.set(Position { x: 10.0, y: 20.0 })
        .set(Velocity { x: 1.0, y: 2.0 });

    // Get a component
    e.get::<&Position>(|p| {
        println!("Position: ({}, {})", p.x, p.y);
    });

    // Remove component
    e.remove(Position::id());

    //Rust applications can use the `world::entity_from` function.

    let pos_e = world.entity_from::<Position>();
    println!("Name: {}", pos_e.name()); // outputs 'Name: Position'

    // It's possible to add components like you would for any entity
    pos_e.add(Serializable::id());

    let pos_e = world.entity_from::<Position>();

    pos_e.get::<&flecs::Component>(|c| {
        println!("Component size: {}", c.size);
    });

    // Option 1: create Tag as empty struct
    #[derive(Component)]
    struct Enemy;

    // Create entity, add Enemy tag
    let e = world.entity().add(Enemy::id());
    e.has(Enemy::id()); // true!

    e.remove(Enemy::id());
    e.has(Enemy::id()); // false!

    // Option 2: create Tag as entity
    let enemy = world.entity();

    // Create entity, add Enemy tag
    let e = world.entity().add(enemy);
    e.has(enemy); // true!

    e.remove(enemy);
    e.has(enemy); // false!

    // Create Likes relationship as empty type (tag)
    #[derive(Component)]
    struct Likes;

    // Create a small graph with two entities that like each other
    let bob = world.entity();
    let alice = world.entity();

    bob.add((Likes::id(), alice)); // bob likes alice
    alice.add((Likes::id(), bob)); // alice likes bob
    bob.has((Likes::id(), alice)); // true!

    bob.remove((Likes::id(), alice));
    bob.has((Likes::id(), alice)); // false!

    let id_likes_apples = world.id_view_from((Likes::id(), Apples::id()));
    if id_likes_apples.is_pair() {
        let relationship = id_likes_apples.first_id();
        let target = id_likes_apples.second_id();
    }

    let bob = world.entity();
    bob.add((eats, apples));
    bob.add((eats, pears));
    bob.add((grows, pears));

    bob.has((eats, apples)); // true!
    bob.has((eats, pears)); // true!
    bob.has((grows, pears)); // true!

    let alice = world.entity().add((Likes::id(), bob));
    let o = alice.target(Likes::id(), 0); // Returns bob

    let parent = world.entity();
    let child = world.entity().child_of(parent);

    // Deleting the parent also deletes its children
    parent.destruct();

    let parent = world.entity_named("parent");
    let child = world.entity_named("child").child_of(parent);
    println!("Child path: {}", child.path().unwrap()); // output: 'parent::child'

    world.lookup("parent::child"); // returns child
    parent.lookup("child"); // returns child

    let q = world
        .query::<(&Position, &mut Position)>()
        .term_at(1)
        .parent()
        .cascade()
        .build();

    q.each(|(p, p_parent)| {
        // Do the thing
    });

    let e = world.entity().add(Position::id()).add(Velocity::id());

    println!("Components: {}", e.archetype().to_string().unwrap()); // output: 'Position,Velocity'

    e.each_component(|id| {
        if id == world.component_id::<Position>() {
            // Found Position component!
        }
    });

    // Set singleton component
    world.set(Gravity { x: 10, y: 20 });

    // Get singleton component
    world.get::<&Gravity>(|g| {
        println!("Gravity: {}, {}", g.x, g.y);
    });

    let grav_e = world.entity_from::<Gravity>();

    grav_e.set(Gravity { x: 10, y: 20 });

    grav_e.get::<&Gravity>(|g| {
        println!("Gravity: {}, {}", g.x, g.y);
    });

    world
        .query::<(&Velocity, &Gravity)>()
        .term_at(1)
        .singleton()
        .build();

    // For simple queries the world::each function can be used
    world.each::<(&mut Position, &Velocity)>(|(p, v)| {
        // EntityView argument is optional, use each_entity to get it
        p.x += v.x;
        p.y += v.y;
    });

    // More complex queries can first be created, then iterated
    let q = world
        .query::<&Position>()
        .with((flecs::ChildOf::ID, parent))
        .build();

    // Option 1: the each() callback iterates over each entity
    q.each_entity(|e, p| {
        println!("{}: ({}, {})", e.name(), p.x, p.y);
    });

    // Option 2: the run() callback offers more control over the iteration
    q.run(|mut it| {
        while it.next() {
            let p = it.field_mut::<Position>(0);

            for i in it.iter() {
                println!(
                    "{}: ({}, {})",
                    it.get_entity(i).unwrap().name(),
                    p[i].x,
                    p[i].y
                );
            }
        }
    });

    let q = world
        .query::<()>()
        .with((id::<flecs::ChildOf>(), id::<flecs::Wildcard>()))
        .with(Position::id())
        .set_oper(OperKind::Not)
        .build();

    // Iteration code is the same

    // Use each_entity() function that iterates each individual entity
    let move_sys = world
        .system::<(&mut Position, &Velocity)>()
        .each_iter(|it, i, (p, v)| {
            p.x += v.x * it.delta_time();
            p.y += v.y * it.delta_time();
        });

    // Just like with queries, systems have both the run() and
    // each() methods to iterate entities.

    move_sys.run();

    println!("System: {}", move_sys.name());
    move_sys.add(id::<flecs::pipeline::OnUpdate>());
    move_sys.destruct();

    flecs::pipeline::OnLoad;
    flecs::pipeline::PostLoad;
    flecs::pipeline::PreUpdate;
    flecs::pipeline::OnUpdate;
    flecs::pipeline::OnValidate;
    flecs::pipeline::PostUpdate;
    flecs::pipeline::PreStore;
    flecs::pipeline::OnStore;

    world
        .system_named::<(&mut Position, &Velocity)>("Move")
        .kind(id::<flecs::pipeline::OnUpdate>())
        .each(|(p, v)| {});
    world
        .system_named::<(&mut Position, &Transform)>("Transform")
        .kind(id::<flecs::pipeline::PostUpdate>())
        .each(|(p, t)| {});
    world
        .system_named::<(&Transform, &mut Mesh)>("Render")
        .kind(id::<flecs::pipeline::OnStore>())
        .each(|(t, m)| {});

    world.progress();

    move_sys.add(id::<flecs::pipeline::OnUpdate>());
    move_sys.remove(id::<flecs::pipeline::PostUpdate>());

    world
        .observer_named::<flecs::OnSet, (&Position, &Velocity)>("OnSetPosition")
        .each(|(p, v)| {}); // Callback code is same as system

    let e = world.entity(); // Doesn't invoke the observer
    e.set(Position { x: 10.0, y: 20.0 }); // Doesn't invoke the observer
    e.set(Velocity { x: 1.0, y: 2.0 }); // Invokes the observer
    e.set(Position { x: 30.0, y: 40.0 }); // Invokes the observer

    #[derive(Component)]
    struct MyModule;

    impl Module for MyModule {
        fn module(world: &World) {
            world.module::<MyModule>("MyModule");
            // Define components, systems, triggers, ... as usual. They will be
            // letmatically created inside the scope of the module.
        }
    }

    // Import code
    world.import::<MyModule>();
}

fn flecs_docs_observers_compile_test() {
    let world = World::new();

    // Create observer that is invoked whenever Position is set
    world
        .observer::<flecs::OnSet, &Position>()
        .each_entity(|e, p| {
            println!("Position set: {{ {}, {} }}", p.x, p.y);
        });

    world.entity().set(Position { x: 10.0, y: 20.0 }); // Invokes observer

    let e = world.entity();

    // OnAdd observer fires
    e.add(Position::id());

    // OnAdd observer doesn't fire, entity already has component
    e.add(Position::id());

    let e = world.entity();

    // OnAdd observer fires first, then OnSet observer fires
    e.set(Position { x: 10.0, y: 20.0 });

    // OnAdd observer doesn't fire, OnSet observer fires
    e.set(Position { x: 10.0, y: 20.0 });

    let p = world.prefab().set(Position { x: 10.0, y: 20.0 });

    // Produces OnSet event for Position
    let i = world.entity().is_a(p);

    let p = world.prefab().set(Position { x: 10.0, y: 20.0 });

    // Produces OnSet event for inherited Position component
    let i = world.entity().is_a(p);

    // Override component. Produces regular OnSet event.
    i.set(Position { x: 20.0, y: 30.0 });

    // Reexposes inherited component, produces OnSet event
    i.remove(Position::id());

    let p = world.prefab().set(Position { x: 10.0, y: 20.0 });

    // Produces OnSet event for Position
    let i = world.entity().is_a(p);

    let e = world.entity().set(Position { x: 10.0, y: 20.0 });

    // OnRemove observer fires
    e.remove(Position::id());

    // OnRemove observer doesn't fire, entity doesn't have the component
    e.remove(Position::id());

    // Observer that listens for both OnAdd and OnRemove events
    world
        .observer::<flecs::OnAdd, ()>()
        .with(Position::id())
        .add_event(id::<flecs::OnRemove>())
        .each_entity(|e, p| {
            // ...
        });

    world
        .observer::<flecs::OnAdd, ()>()
        .add_event(id::<flecs::OnRemove>())
        .with(Position::id())
        .each_iter(|it, i, p| {
            if it.event() == flecs::OnAdd::ID {
                // ...
            } else if it.event() == flecs::OnRemove::ID {
                // ...
            }
        });

    // Observer that listens for all events for Position
    world
        .observer::<flecs::Wildcard, &Position>()
        .each_entity(|e, p| {
            // ...
        });

    // Observer that listens for entities with both Position and Velocity
    world
        .observer::<flecs::OnAdd, ()>()
        .with(Position::id())
        .with(Velocity::id())
        .each_entity(|e, _| {
            // ...
        });

    let e = world.entity();

    // Does not trigger "Position, Velocity" observer
    e.add(Position::id());

    // Entity now matches "Position, Velocity" query, triggers observer
    e.add(Velocity::id());

    // Observer that only triggers on Position, not on Velocity
    world
        .observer::<flecs::OnAdd, ()>()
        .with(Position::id())
        .with(Velocity::id())
        .filter()
        .each_entity(|e, p| {
            // ...
        });

    let e = world.entity();

    // Doesn't trigger, entity doesn't have Velocity
    e.set(Position { x: 10.0, y: 20.0 });

    // Doesn't trigger, Velocity is a filter term
    e.set(Velocity { x: 1.0, y: 2.0 });

    // Triggers, entity now matches observer query
    e.set(Position { x: 20.0, y: 30.0 });

    // OnSet observer with both component and tag
    world
        .observer::<flecs::OnSet, &Position>()
        .with(Npc::id()) // Tag
        .each_entity(|e, p| {
            // ...
        });

    let e = world.entity();

    // Doesn't trigger, entity doesn't have Npc
    e.set(Position { x: 10.0, y: 20.0 });

    // Produces and OnAdd event & triggers observer
    e.add(Npc::id());

    // Produces an OnSet event & triggers observer
    e.set(Position { x: 20.0, y: 30.0 });

    // Observer with a Not term
    world
        .observer::<flecs::OnAdd, ()>()
        .with(Position::id())
        .without(Velocity::id())
        .each_entity(|e, p| {
            // ...
        });

    let e = world.entity();

    // Triggers the observer
    e.set(Position { x: 10.0, y: 20.0 });

    // Doesn't trigger the observer, entity doesn't match the observer query
    e.set(Velocity { x: 1.0, y: 2.0 });

    // Triggers the observer, as the Velocity term was inverted to OnRemove
    e.remove(Velocity::id());

    // Monitor observer
    world
        .observer::<flecs::Monitor, (&Position, &Velocity)>()
        .each_iter(|it, i, (p, v)| {
            if it.event() == flecs::OnAdd::ID {
                // Entity started matching query
            } else if it.event() == flecs::OnRemove::ID {
                // Entity stopped matching query
            }
        });

    let e = world.entity();

    // Doesn't trigger the monitor, entity doesn't match
    e.set(Position { x: 10.0, y: 20.0 });

    // Entity now matches, triggers monitor with OnAdd event
    e.set(Velocity { x: 1.0, y: 2.0 });

    // Entity no longer matches, triggers monitor with OnRemove event
    e.remove(Position::id());

    // Entity created before the observer
    let e1 = world.entity().set(Position { x: 10.0, y: 20.0 });

    // Yield existing observer
    world
        .observer::<flecs::OnAdd, ()>()
        .with(Position::id())
        .with(Velocity::id())
        .yield_existing()
        .each_iter(|it, i, _| {
            // ...
        });

    // Observer is invoked for e1

    // Fires observer as usual
    let e2 = world.entity().set(Position { x: 10.0, y: 20.0 });

    // Entity used for fixed source
    let game = world.entity().set(TimeOfDay { value: 0.0 });

    // Observer with fixed source
    world
        .observer::<flecs::OnSet, &TimeOfDay>()
        .term_at(0)
        .set_src(game) // Match TimeOfDay on game
        .each_iter(|it, i, time| {
            // ...
        });

    // Triggers observer
    game.set(TimeOfDay { value: 1.0 });

    // Does not trigger observer
    let e = world.entity().set(TimeOfDay { value: 0.0 });

    world.set(TimeOfDay { value: 0.0 });

    // Observer with singleton source
    world
        .observer::<flecs::OnSet, &TimeOfDay>()
        .term_at(0)
        .singleton()
        .each_iter(|it, i, time| {
            // ...
        });

    // Triggers observer
    world.set(TimeOfDay { value: 1.0 });

    // Does not trigger observer
    let e = world.entity().set(TimeOfDay { value: 0.0 });

    // Create an observer that matches OnSet(Position) events on self and a parent
    world
        .observer::<flecs::OnSet, &Position>()
        .term_at(0)
        .self_()
        .up() // .trav(flecs::ChildOf) (default)
        .each_entity(|e, p| {
            // ...
        });

    let parent = world.entity();
    let child = world.entity().child_of(parent);

    // Invokes observer twice: once for the parent and once for the child
    parent.set(Position { x: 10.0, y: 20.0 });

    // Create an observer that matches OnAdd(Position) events on a parent
    world
        .observer::<flecs::OnAdd, ()>()
        .with(Position::id())
        .term_at(0)
        .up() // .trav(flecs::ChildOf) (default)
        .each_entity(|e, _| {
            // ...
        });

    let parent = world.entity().set(Position { x: 10.0, y: 20.0 });

    // Forwards OnAdd event for Position to child
    let child = world.entity().child_of(parent);

    // Create a custom event
    #[derive(Component)]
    struct Synchronized;

    // Alternatively, an plain entity could also be used as event
    // let Synchronized = world.entity();

    // Create an observer that matches a custom event
    world
        .observer::<Synchronized, &Position>()
        .each_entity(|e, p| {
            // ...
        });

    let e = world.entity().set(Position { x: 10.0, y: 20.0 });

    // Emit custom event
    world
        .event()
        .add(Position::id())
        .entity(e)
        .emit(&Synchronized);

    // Create a custom event
    #[derive(Component)]
    struct Clicked;

    // Create entity
    let widget = world.entity_named("widget");

    // Create an entity observer
    widget.observe::<Clicked>(|| {
        // ...
    });

    // Emit entity event
    widget.emit(&Clicked);

    // Create a custom event
    #[derive(Component)]
    struct Resize {
        width: u32,
        height: u32,
    }

    // Create entity
    let widget = world.entity_named("widget");

    // Create an entity observer
    widget.observe_payload::<&Resize>(|r| {
        // ...
    });

    // Emit entity event
    widget.emit(&Resize {
        width: 100,
        height: 200,
    });

    world
        .observer::<flecs::OnSet, &Position>()
        .each_entity(|e, p| {
            // ...
        });

    // Observer is invoked as part of operation
    e.set(Position { x: 10.0, y: 20.0 });

    world.defer_begin();
    e.set(Position { x: 20.0, y: 30.0 });
    // Operation is delayed until here, observer is also invoked here
    world.defer_end();
}

fn flecs_docs_prefabs_compile_test() {
    let world = World::new();

    #[derive(Component)]
    struct Defense {
        value: u32,
    }

    // Create a spaceship prefab with a Defense component.
    let spaceship = world.prefab_named("spaceship").set(Defense { value: 50 });

    // Create two prefab instances
    let inst_1 = world.entity().is_a(spaceship);
    let inst_2 = world.entity().is_a(spaceship);

    // Get instantiated component
    inst_1.get::<&Defense>(|defense| {
        println!("Defense value: {}", defense.value);
    });

    let myprefab = world.entity().add(id::<flecs::Prefab>());

    // or the shortcut

    let myprefab = world.prefab();

    // Only match prefab entities
    world
        .query::<&Position>()
        .with(id::<flecs::Prefab>())
        .build();

    // Only match prefab entities
    world
        .query::<&Position>()
        .with(id::<flecs::Prefab>())
        .optional()
        .build();

    // Only match prefab entities
    world
        .query::<&Position>()
        .query_flags(QueryFlags::MatchPrefab)
        .build();

    // Make Defense component inheritable
    world
        .component::<Defense>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    // Create prefab
    let spaceship = world
        .prefab()
        .set(Health { value: 100 })
        .set(Defense { value: 50 });

    // Create prefab instance
    let inst = world.entity().is_a(spaceship);

    // Component is retrieved from instance
    inst.get::<&Health>(|health| {
        println!("Health value: {}", health.value);
    });

    // Component is retrieved from prefab
    inst.get::<&Defense>(|defense| {
        println!("Defense value: {}", defense.value);
    });

    if inst.owns(Defense::id()) {
        // not inherited
    }

    let inherited_from = inst.target(Defense::id(), 0);
    if inherited_from.is_none() {
        // not inherited
    }

    // Make Defense component inheritable
    world
        .component::<Defense>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    // Create prefab
    let spaceship = world.prefab().set(Defense { value: 50 });

    // Create prefab instance
    let inst_a = world.entity().is_a(spaceship);
    let inst_b = world.entity().is_a(spaceship);

    // Override Defense only for inst_a
    inst_a.set(Defense { value: 75 });

    // Make Defense component inheritable
    world
        .component::<Defense>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    // Create prefab
    let spaceship = world.prefab().set(Defense { value: 50 });

    // Create prefab instance
    let inst_a = world.entity().is_a(spaceship);
    let inst_b = world.entity().is_a(spaceship);

    // Override Defense only for inst_a
    inst_a.add(Defense::id()); // Initialized with value 50

    // Make Defense component inheritable
    world
        .component::<Defense>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    // Create prefab
    let spaceship = world.prefab().set_auto_override(Defense { value: 50 }); // Set & let override Defense

    // Create prefab instance
    let inst = world.entity().is_a(spaceship);
    inst.owns(Defense::id()); // true

    // Create prefab
    let spaceship = world
        .prefab_named("spaceship")
        .set(Defense { value: 50 })
        .set(Health { value: 100 });

    // Create prefab variant
    let freighter = world
        .prefab_named("Freighter")
        .is_a(spaceship)
        .set(Health { value: 150 }); // Override the Health component of the freighter

    // Create prefab instance
    let inst = world.entity().is_a(freighter);
    inst.get::<&Health>(|health| {
        println!("Health value: {}", health.value); // 150
    });
    inst.get::<&Defense>(|defense| {
        println!("Defense value: {}", defense.value); // 50
    });

    let spaceship = world.prefab_named("Spaceship");
    let cockpit = world.prefab_named("Cockpit").child_of(spaceship);

    // Instantiate the prefab hierarchy
    let inst = world.entity().is_a(spaceship);

    // Lookup instantiated child
    let inst_cockpit = inst.lookup("Cockpit");

    let spaceship = world.prefab_named("Spaceship");
    let cockpit = world.prefab_named("Cockpit").child_of(spaceship).slot(); // Defaults to (SlotOf, spaceship)

    // Instantiate the prefab hierarchy
    let inst = world.entity().is_a(spaceship);

    // Lookup instantiated child
    let inst_cockpit = inst.target(cockpit, 0);

    #[derive(Component)]
    struct Spaceship;

    // Create prefab associated with the spaceship type
    world
        .prefab_type::<Spaceship>()
        .set(Defense { value: 50 })
        .set(Health { value: 100 });

    // Instantiate prefab with type
    let inst = world.entity().is_a(Spaceship::id());

    // Lookup prefab handle
    let prefab = world.lookup("spaceship");
}

fn flecs_docs_component_traits_compile_test() {
    let world = World::new();
    let e = world.entity();
    let parent = world.entity();
    let archer = world.entity();

    #[derive(Component)]
    struct MyComponent {
        e: Entity, // Not covered by cleanup traits
    }

    e.child_of(parent); // Covered by cleanup traits

    world.remove_all(archer);

    world.remove_all(archer);
    world.remove_all((archer, flecs::Wildcard::ID));
    world.remove_all((flecs::Wildcard::ID, archer));

    // Remove Archer from entities when Archer is deleted
    world
        .component::<Archer>()
        .add_trait::<(flecs::OnDelete, flecs::Remove)>();

    let e = world.entity().add(Archer::id());

    // This will remove Archer from e
    world.component::<Archer>().destruct();

    // Delete entities with Archer when Archer is deleted
    world
        .component::<Archer>()
        .add_trait::<(flecs::OnDelete, flecs::Delete)>();

    let e = world.entity().add(Archer::id());

    // This will delete e
    world.component::<Archer>().destruct();

    // Delete children when deleting parent
    world
        .component::<flecs::ChildOf>()
        .add_trait::<(flecs::OnDeleteTarget, flecs::Delete)>();

    let p = world.entity();
    let e = world.entity().add((id::<flecs::ChildOf>(), p));

    // This will delete both p and e
    p.destruct();

    world
        .observer::<flecs::OnRemove, &Node>()
        .each_entity(|e, node| {
            // This observer will be invoked when a Node is removed
        });

    let p = world.entity().add(Node::id());
    let c = world.entity().add(Node::id()).child_of(p);

    {
        #[derive(Component)]
        struct Serializable;

        world
            .component::<Serializable>()
            .add_trait::<flecs::Trait>();
    }

    {
        #[derive(Component)]
        struct Likes;
        #[derive(Component)]
        struct Apples;

        world
            .component::<Likes>()
            .add_trait::<flecs::Relationship>();

        let e = world
            .entity()
            .add(Likes::id()) // Panic, 'Likes' is not used as relationship
            .add((Apples::id(), Likes::id())) // Panic, 'Likes' is not used as relationship, but as target
            .add((Likes::id(), Apples::id())); // OK
    }
    {
        #[derive(Component)]
        struct Likes;
        #[derive(Component)]
        struct Loves;

        world
            .component::<Likes>()
            .add_trait::<flecs::Relationship>();

        // Even though Likes is marked as relationship and used as target here, this
        // won't panic as With is marked as trait.
        world
            .component::<Loves>()
            .add_trait::<(flecs::With, Likes)>();
    }

    #[derive(Component)]
    struct Likes;
    #[derive(Component)]
    struct Apples;

    world.component::<Apples>().add_trait::<flecs::Target>();

    let e = world
        .entity()
        .add(Apples::id()) // Panic, 'Apples' is not used as target
        .add((Apples::id(), Likes::id())) // Panic, 'Apples' is not used as target, but as relationship
        .add((Likes::id(), Apples::id())); // OK

    #[derive(Component)]
    struct Serializable; // Tag, contains no data

    #[derive(Component)]
    struct Position {
        x: f32,
        y: f32,
    }

    let e = world
        .entity()
        .set(Position { x: 10.0, y: 20.9 })
        .add_trait::<(Serializable, Position)>(); // Because Serializable is a tag, the pair
    // has a value of type Position

    // Gets value from Position component
    e.get::<&Position>(|pos| {
        println!("Position: ({}, {})", pos.x, pos.y);
    });
    // Gets (unintended) value from (Serializable, Position) pair
    e.get::<&(Serializable, Position)>(|pos| {
        println!("Serializable Position: ({}, {})", pos.x, pos.y);
    });

    // This is currently not supported in Rust due to safety concerns.

    let e = world.entity().add_trait::<flecs::Final>();

    let i = world.entity().is_a(e); // not allowed

    // Register component with trait. Optional, since this is the default behavior.
    world
        .component::<Mass>()
        .add_trait::<(flecs::OnInstantiate, flecs::Override)>();

    let base = world.entity().set(Mass { value: 100.0 });
    let inst = world.entity().is_a(base); // Mass is copied to inst

    assert!(inst.owns(Mass::id()));
    assert!(base.cloned::<&Mass>() != inst.cloned::<&Mass>());

    // Register component with trait
    world
        .component::<Mass>()
        .add_trait::<(flecs::OnInstantiate, flecs::Inherit)>();

    let base = world.entity().set(Mass { value: 100.0 });
    let inst = world.entity().is_a(base);

    assert!(inst.has(Mass::id()));
    assert!(!inst.owns(Mass::id()));
    assert!(base.cloned::<&Mass>() != inst.cloned::<&Mass>());

    // Register component with trait
    world
        .component::<Mass>()
        .add_trait::<(flecs::OnInstantiate, flecs::DontInherit)>();

    let base = world.entity().set(Mass { value: 100.0 });
    let inst = world.entity().is_a(base);

    assert!(!inst.has(Mass::id()));
    assert!(!inst.owns(Mass::id()));
    assert!(inst.try_get::<&Mass>(|mass| {}).is_none());

    let locatedin = world.entity();
    let manhattan = world.entity();
    let newyork = world.entity();
    let usa = world.entity();

    manhattan.add((locatedin, newyork));
    newyork.add((locatedin, usa));

    locatedin.add_trait::<flecs::Transitive>();

    let parent_a = world.entity();
    let parent_b = world.entity();
    e.child_of(parent_a);
    e.child_of(parent_b); // replaces (ChildOf, parent_a)

    let married_to = world.entity().add_trait::<flecs::Exclusive>();

    world
        .component::<Position>()
        .add_trait::<flecs::CanToggle>();

    let e = world.entity().set(Position { x: 10.0, y: 20.0 });

    e.disable(Position::id()); // Disable component
    assert!(!e.is_enabled(Position::id()));

    e.enable(Position::id()); // Enable component
    assert!(e.is_enabled(Position::id())); // Updated to use Position::id()

    let walking = world.entity();
    let running = world.entity();

    world.component::<Position>().add_trait::<flecs::Sparse>();

    let married_to = world.entity().add_trait::<flecs::Symmetric>();
    let bob = world.entity();
    let alice = world.entity();
    bob.add((married_to, alice)); // Also adds (MarriedTo, Bob) to Alice

    let responsibility = world.entity();
    let power = world.entity().add((id::<flecs::With>(), responsibility));

    // Create new entity that has both Power and Responsibility
    let e = world.entity().add(power);

    let likes = world.entity();
    let loves = world.entity().add_trait::<(flecs::With, Likes)>();
    let pears = world.entity();

    // Create new entity with both (Loves, Pears) and (Likes, Pears)
    let e = world.entity().add((loves, pears));

    // Enforce that target of relationship is child of Food
    let food = world.entity().add_trait::<flecs::OneOf>();
    let apples = world.entity().child_of(food);
    let fork = world.entity();

    // This is ok, Apples is a child of Food
    let a = world.entity().add((food, apples));

    // This is not ok, Fork is not a child of Food
    let b = world.entity().add((food, fork));

    // Enforce that target of relationship is child of Food
    let food = world.entity();
    let eats = world.entity().add((id::<flecs::OneOf>(), food));
    let apples = world.entity().child_of(food);
    let fork = world.entity();

    // This is ok, Apples is a child of Food
    let a = world.entity().add((eats, apples));

    // This is not ok, Fork is not a child of Food
    let b = world.entity().add((eats, fork));
}

// app.world.set(flecs::rest::Rest::default());
// // enable stats for flecs (system, pipeline, etc)
// app.world.import::<stats::Stats>();
fn flecs_docs_remote_api_compile_test() {
    let world = World::new();

    // Optional, gather statistics for explorer
    world.import::<stats::Stats>();
    // Creates REST server on default port (27750)
    world.set(flecs::rest::Rest::default());
    // Runs the system serving up REST requests
    while world.progress() {}

    world
        .app()
        // Optional, gather statistics for explorer
        .enable_stats(true)
        .enable_rest(0)
        .run();

    // Optional, gather statistics for explorer
    world.import::<stats::Stats>();
    // Creates REST server on default port (27750)
    world.set(flecs::rest::Rest::default());
    // Runs the system serving up REST requests
    while world.progress() {}
}