flecs_ecs 0.2.0

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
use core::ffi::c_void;

use super::*;

use flecs_ecs_derive::extern_abi;

#[extern_abi]
unsafe fn c_run_post_frame(world: *mut sys::ecs_world_t, ctx: *mut ::core::ffi::c_void) {
    let action: fn(WorldRef) = unsafe { core::mem::transmute(ctx as *const ()) };
    let world = unsafe { WorldRef::from_ptr(world) };
    (action)(world);
}

#[extern_abi]
unsafe fn c_on_destroyed(world: *mut sys::ecs_world_t, ctx: *mut ::core::ffi::c_void) {
    let action: fn(WorldRef) = unsafe { core::mem::transmute(ctx as *const ()) };
    let world = unsafe { WorldRef::from_ptr(world) };
    (action)(world);
}

impl World {
    /// deletes and recreates the world
    ///
    /// # Panics
    /// This function panics if lingering references to `Query` and `World` objects are still present.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// let e = world.entity().id();
    ///
    /// assert!(world.exists(e));
    /// let new_world = world.reset();
    /// assert!(!new_world.exists(e));
    /// ```
    pub fn reset(self) -> Self {
        if unsafe { sys::flecs_poly_refcount(self.raw_world.as_ptr() as *mut c_void) } > 1 {
            panic!("Reset would invalidate other world handles that are still lingering in the user's code base. 
            This is a bug in the user code. Please ensure that all world handles are out of scope before calling `reset`.");
        }
        drop(self);
        World::new()
    }

    /// obtain pointer to C world object.
    ///
    /// # Returns
    ///
    /// Returns a pointer to the C world object.
    #[inline(always)]
    #[doc(hidden)]
    pub fn ptr_mut(&self) -> *mut sys::ecs_world_t {
        self.raw_world.as_ptr()
    }

    /// Get the world's info. See [`sys::WorldInfo`] for what information you can retrieve.
    ///
    /// # Example
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// world.progress();
    ///
    /// let world_info = world.info();
    ///
    /// assert!(world_info.delta_time > 0.0);
    /// //assert!(world_info.world_time_total_raw > 0.0); //BUG TODO
    /// //assert!(world_info.systems_ran_frame == 0);
    /// ```
    pub fn info(&self) -> sys::WorldInfo {
        // SAFETY: The pointer is valid for the lifetime of the world.
        unsafe { *sys::ecs_get_world_info(self.raw_world.as_ptr()) }
    }

    /// Signals the application to quit.
    ///
    /// After calling this function, the next call to [`World::progress()`] returns false.
    ///
    /// # Example
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// let mut count = 0;
    /// while world.progress() {
    ///     count += 1;
    ///     if count == 5 {
    ///         world.quit();
    ///     }
    /// }
    /// assert!(count == 5);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::should_quit()`]
    pub fn quit(&self) {
        unsafe {
            sys::ecs_quit(self.raw_world.as_ptr());
        }
    }

    /// Tests if [`World::quit()`] has been called.
    ///
    /// # Returns
    ///
    /// True if quit has been called, false otherwise.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// assert!(!world.should_quit());
    /// world.quit();
    /// assert!(world.should_quit());
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::quit()`]
    pub fn should_quit(&self) -> bool {
        unsafe { sys::ecs_should_quit(self.raw_world.as_ptr()) }
    }

    /// Registers an action to be executed when the world is destroyed.
    ///
    /// This provides a safe, ergonomic way to register cleanup callbacks that will
    /// be invoked when the world is dropped. The callback receives a [`WorldRef`]
    /// that can be used to access world state during cleanup.
    ///
    /// # Arguments
    ///
    /// * `action` - The function to call when the world is destroyed.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    /// world.on_destroyed(|world| {
    ///     println!("World is being destroyed!");
    /// });
    /// // World will be destroyed when it goes out of scope
    /// ```
    ///
    /// # See also
    ///
    /// * C++ API: `world::atfini`
    #[doc(alias = "ecs_atfini")]
    pub fn on_destroyed(&self, action: fn(WorldRef)) {
        let ctx: *mut ::core::ffi::c_void = action as *const () as *mut ::core::ffi::c_void;
        unsafe {
            sys::ecs_atfini(self.raw_world.as_ptr(), Some(c_on_destroyed), ctx);
        }
    }

    /// Begins a frame.
    ///
    /// When an application does not use [`World::progress()`] to control the main loop, it
    /// can still use Flecs features such as FPS limiting and time measurements processed.
    ///
    /// Calls to [`World::frame_begin`] must always be followed by [`World::frame_end`].
    ///
    /// The function accepts a `delta_time` parameter, which will get passed to
    /// systems. This value is also used to compute the amount of time the
    /// function needs to sleep to ensure it does not exceed the `target_fps`, when
    /// it is set. When 0 is provided for `delta_time`, the time will be measured.
    ///
    /// # Safety
    /// This function should only be ran from the main thread.
    ///
    /// # Arguments
    /// * `delta_time`: Time elapsed since the last frame.
    ///
    /// # Returns
    /// The provided `delta_time`, or the measured time if 0 was provided.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// #[derive(Component)]
    /// struct Position {
    ///     x: f32,
    ///     y: f32,
    /// }
    ///
    /// let world = World::new();
    ///
    /// let entity = world.entity().set(Position { x: 5.0, y: 0.0 });
    ///
    /// let sys = world.system::<&Position>().each(|pos| {});
    ///
    /// let world_info = world.info();
    ///
    /// assert_eq!(world_info.systems_ran_frame, 0);
    ///
    /// let dt = world.frame_begin(0.0);
    ///
    /// world.frame_end();
    ///
    /// let world_info = world.info();
    ///
    /// //TODO
    /// //assert_eq!(world_info.systems_ran_frame, 1);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::frame_end()`]
    pub fn frame_begin(&self, delta_time: f32) -> f32 {
        unsafe { sys::ecs_frame_begin(self.raw_world.as_ptr(), delta_time) }
    }

    /// Ends a frame.
    ///
    /// This operation must be called at the end of the frame, and always after
    /// [`World::frame_begin()`].
    ///
    /// # Safety
    /// The function should only be run from the main thread.
    ///
    /// # See also
    ///
    /// * [`World::frame_begin()`]
    pub fn frame_end(&self) {
        unsafe {
            sys::ecs_frame_end(self.raw_world.as_ptr());
        }
    }

    /// Begin readonly mode.
    ///
    /// When an application does not use [`World::progress()`] to control the main loop,
    /// it can still use Flecs features such as the defer queue. To stage changes, this function
    /// must be called after [`World::frame_begin()`].
    ///
    /// A call to [`World::readonly_begin()`] must be followed by a call to
    /// [`World::readonly_end()`].
    ///
    /// When staging is enabled, modifications to entities are stored to a stage.
    /// This ensures that arrays are not modified while iterating. Modifications are
    /// merged back to the "main stage" when [`World::readonly_end()`] is invoked.
    ///
    /// While the world is in staging mode, no structural changes (add/remove/...) can
    /// be made to the world itself. Operations must be executed on a stage instead
    /// (see [`World::stage()`]).
    ///
    /// Readonly mode is a stronger version of deferred mode. In deferred mode,
    /// ECS operations such as add/remove/set/delete etc. are added to a command
    /// queue to be executed later. In readonly mode, operations that could break
    /// scheduler logic (such as creating systems, queries) are also disallowed.
    ///
    /// Readonly mode itself has a single-threaded and a multi-threaded mode. In
    /// single-threaded mode certain mutations on the world are still allowed, for example:
    /// - Entity liveliness operations (such as new, `make_alive`), so that systems are
    ///   able to create new entities.
    /// - Implicit component registration, so that this works from systems.
    /// - Mutations to supporting data structures for the evaluation of uncached
    ///   queries, so that these can be created on the fly.
    ///
    /// These mutations are safe in single-threaded applications, but for
    /// multi-threaded applications, the world needs to be entirely immutable. For this
    /// purpose, multi-threaded readonly mode exists, which disallows all mutations on
    /// the world.
    ///
    /// While in readonly mode, applications can still enqueue ECS operations on a
    /// stage. Stages are managed automatically when using the pipeline addon and
    /// [`World::progress()`], but they can also be configured manually.
    ///
    /// Number of stages typically corresponds with number of threads
    ///
    /// When an attempt is made to perform an operation on a world in readonly mode,
    /// the code will throw an assert saying that the world is in readonly mode.
    ///
    /// A call to `readonly_begin` must be followed up with `readonly_end()`.
    /// When `readonly_end()` is called, all enqueued commands from configured
    /// stages are merged back into the world. Calls to `readonly_begin()` and
    /// `readonly_end()` should always happen from a context where the code has
    /// exclusive access to the world. The functions themselves are not thread safe.
    ///
    /// # Safety
    /// This function should only be run from the main thread.
    ///
    /// # Returns
    /// Whether the world is currently staged and whether it is in readonly mode.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// #[derive(Component)]
    /// struct Position {
    ///     x: i32,
    ///     y: i32,
    /// }
    ///
    /// let world = World::new();
    ///
    /// let stage = world.stage(0);
    ///
    /// world.readonly_begin(false);
    ///
    /// assert_eq!(stage.count(Position::id()), 0);
    ///
    /// world.readonly_end();
    ///
    /// world.readonly_begin(false);
    ///
    /// stage.entity().set(Position { x: 10, y: 20 });
    /// stage.entity().set(Position { x: 10, y: 20 });
    ///
    /// assert_eq!(stage.count(Position::id()), 0);
    ///
    /// world.readonly_end();
    ///
    /// assert_eq!(stage.count(Position::id()), 2);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::is_readonly()`]
    /// * [`World::readonly_end()`]
    pub fn readonly_begin(&self, multi_threaded: bool) -> bool {
        unsafe { sys::ecs_readonly_begin(self.raw_world.as_ptr(), multi_threaded) }
    }

    /// End readonly mode.
    ///
    /// Leaves staging mode. After this operation, the world may be directly mutated again.
    /// By default, this operation also merges data back into the world, unless auto-merging
    /// was disabled explicitly.
    ///
    /// # Safety
    /// This function should only be run from the main thread.
    ///
    /// # Returns
    ///
    /// Whether the world is currently staged.
    ///
    /// # Example
    ///
    /// see [`World::readonly_begin()`].
    ///
    /// # See also
    ///
    /// * [`World::is_readonly()`]
    /// * [`World::readonly_begin()`]
    pub fn readonly_end(&self) {
        unsafe {
            sys::ecs_readonly_end(self.raw_world.as_ptr());
        }
    }

    /// Test whether the current world object is readonly.
    ///
    /// This function allows the code to test whether the currently used world
    /// object is readonly or whether it allows for writing.
    ///
    /// # Returns
    ///
    /// True if the world or stage is readonly.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// assert!(!world.is_readonly());
    ///
    /// world.readonly_begin(false);
    ///
    /// assert!(world.is_readonly());
    ///
    /// world.readonly_end();
    ///
    /// assert!(!world.is_readonly());
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::readonly_begin()`]
    /// * [`World::readonly_end()`]
    pub fn is_readonly(&self) -> bool {
        unsafe { sys::ecs_stage_is_readonly(self.raw_world.as_ptr()) }
    }

    /// Defers operations until the end of the frame.
    ///
    /// When this operation is invoked while iterating, the operations between
    /// [`World::defer_begin()`] and [`World::defer_end()`] are executed at the
    /// end of the frame.
    ///
    /// # Safety
    /// This operation is thread safe.
    ///
    /// # Returns
    /// Whether the operation was successful.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// #[derive(Component)]
    /// struct Position {
    ///     x: i32,
    ///     y: i32,
    /// }
    ///
    /// let world = World::new();
    ///
    /// world.defer_begin();
    ///
    /// let e = world.entity().set(Position { x: 10, y: 20 });
    ///
    /// assert!(!e.has(Position::id()));
    ///
    /// world.defer_end();
    ///
    /// assert!(e.has(Position::id()));
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::defer()`]
    /// * [`World::defer_end()`]
    /// * [`World::defer_suspend()`]
    /// * [`World::defer_resume()`]
    /// * [`World::is_deferred()`]
    pub fn defer_begin(&self) -> bool {
        unsafe { sys::ecs_defer_begin(self.raw_world.as_ptr()) }
    }

    /// Ends a block of operations to defer.
    ///
    /// This should follow a [`World::defer_begin()`] call.
    ///
    /// # Safety
    /// This operation is thread safe.
    ///
    /// # Returns
    /// Whether the operation was successful.
    ///
    /// # Example
    ///
    /// see [`World::defer_begin`]
    ///
    /// # See also
    ///
    /// * [`World::defer()`]
    /// * [`World::defer_begin()`]
    /// * [`World::defer_suspend()`]
    /// * [`World::defer_resume()`]
    /// * [`World::is_deferred()`]
    pub fn defer_end(&self) -> bool {
        unsafe { sys::ecs_defer_end(self.raw_world.as_ptr()) }
    }

    /// Test whether deferring is enabled.
    ///
    /// # Returns
    ///
    /// Whether deferring is enabled.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// assert!(!world.is_deferred());
    ///
    /// world.defer_begin();
    ///
    /// assert!(world.is_deferred());
    ///
    /// world.defer_end();
    ///
    /// assert!(!world.is_deferred());
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::defer()`]
    /// * [`World::defer_begin()`]
    /// * [`World::defer_end()`]
    /// * [`World::defer_suspend()`]
    /// * [`World::defer_resume()`]
    pub fn is_deferred(&self) -> bool {
        unsafe { sys::ecs_is_deferred(self.raw_world.as_ptr()) }
    }

    /// Defers all operations executed in the passed-in closure.
    ///
    /// # Arguments
    ///
    /// * `func` - The closure to execute.
    ///
    /// # Examples
    /// ```
    /// # use flecs_ecs::core::World;
    /// # let world = World::new();
    /// let return_something_if_wanted = world.defer(|| {
    ///     // deferred operations here
    /// });
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::defer_begin()`]
    /// * [`World::defer_end()`]
    /// * [`World::defer_suspend()`]
    /// * [`World::defer_resume()`]
    /// * [`World::is_deferred()`]
    pub fn defer<T>(&self, func: impl FnOnce() -> T) -> T {
        unsafe {
            sys::ecs_defer_begin(self.raw_world.as_ptr());
        }
        let result = func();
        unsafe {
            sys::ecs_defer_end(self.raw_world.as_ptr());
        }
        result
    }

    /// Suspends deferring of operations but do flush the queue.
    ///
    /// This operation can be used to do an undeferred operation
    /// while not flushing the operations in the queue.
    ///
    /// An application should invoke [`World::defer_resume()`] before
    /// [`World::defer_end()`] is called. The operation may only be called
    /// when deferring is enabled.
    ///
    /// # See also
    ///
    /// * [`World::defer()`]
    /// * [`World::defer_begin()`]
    /// * [`World::defer_end()`]
    /// * [`World::defer_resume()`]
    /// * [`World::is_deferred()`]
    pub fn defer_suspend(&self) {
        unsafe {
            sys::ecs_defer_suspend(self.raw_world.as_ptr());
        }
    }

    /// Resumes deferring of operations.
    ///
    /// # See also
    ///
    /// * [`World::defer()`]
    /// * [`World::defer_begin()`]
    /// * [`World::defer_end()`]
    /// * [`World::defer_suspend()`]
    /// * [`World::is_deferred()`]
    pub fn defer_resume(&self) {
        unsafe {
            sys::ecs_defer_resume(self.raw_world.as_ptr());
        }
    }

    /// Configure world to have N stages.
    ///
    /// This initializes N stages, which allows applications to defer operations to
    /// multiple isolated defer queues. This is typically used for applications with
    /// multiple threads, where each thread gets its own queue, and commands are
    /// merged when threads are synchronized.
    ///
    /// Note that [`World::set_threads()`] already creates the appropriate number of stages.
    /// The [`World::set_stage_count()`] operation is useful for applications that want to manage
    /// their own stages and/or threads.
    ///
    /// # Arguments
    ///
    /// * `stages`: The number of stages.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// world.set_stage_count(2);
    ///
    /// world.readonly_begin(false);
    ///
    /// let stage1 = world.stage(0);
    ///
    /// let e1 = stage1.entity_named("e1");
    ///
    /// world.readonly_end();
    ///
    /// assert!(e1.id() != 0);
    /// assert_eq!(e1.name(), "e1");
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::get_stage_count()`]
    /// * [`World::is_stage()`]
    /// * [`World::merge()`]
    /// * [`World::stage()`]
    /// * [`World::stage_id()`]
    pub fn set_stage_count(&self, stages: i32) {
        unsafe {
            sys::ecs_set_stage_count(self.raw_world.as_ptr(), stages);
        }
    }

    /// Get number of configured stages.
    ///
    /// Return number of stages set by [`World::set_stage_count()`].
    ///
    /// # Returns
    ///
    /// The number of stages used for threading.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// assert_eq!(world.get_stage_count(), 1);
    ///
    /// world.set_stage_count(4);
    ///
    /// assert_eq!(world.get_stage_count(), 4);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::is_stage()`]
    /// * [`World::merge()`]
    /// * [`World::set_stage_count()`]
    /// * [`World::stage()`]
    /// * [`World::stage_id()`]
    pub fn get_stage_count(&self) -> i32 {
        unsafe { sys::ecs_get_stage_count(self.raw_world.as_ptr()) }
    }

    /// Get current stage id.
    ///
    /// The stage id can be used by an application to learn about which stage it
    /// is using, which typically corresponds with the worker thread id.
    ///
    /// # Returns
    ///
    /// The stage id.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// assert_eq!(world.stage_id(), 0);
    ///
    /// world.set_stage_count(4);
    ///
    /// assert_eq!(world.stage_id(), 0);
    ///
    /// let stage = world.stage(3);
    ///
    /// assert_eq!(stage.stage_id(), 3);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::get_stage_count()`]
    /// * [`World::is_stage()`]
    /// * [`World::merge()`]
    /// * [`World::set_stage_count()`]
    /// * [`World::stage()`]
    pub fn stage_id(&self) -> i32 {
        unsafe { sys::ecs_stage_get_id(self.raw_world.as_ptr()) }
    }

    /// Test if is a stage.
    ///
    /// If this function returns `false`, it is guaranteed that this is a valid
    /// world object.
    ///
    /// # Returns
    ///
    /// True if the world is a stage, false if not.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// assert!(!world.is_stage());
    ///
    /// let stage = world.stage(0);
    ///
    /// assert!(stage.is_stage());
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::get_stage_count()`]
    /// * [`World::merge()`]
    /// * [`World::set_stage_count()`]
    /// * [`World::stage()`]
    /// * [`World::stage_id()`]
    pub fn is_stage(&self) -> bool {
        unsafe {
            ecs_assert!(
                sys::flecs_poly_is_(
                    self.raw_world.as_ptr() as *const c_void,
                    sys::ecs_world_t_magic as i32
                ) || sys::flecs_poly_is_(
                    self.raw_world.as_ptr() as *const c_void,
                    sys::ecs_stage_t_magic as i32
                ),
                FlecsErrorCode::InvalidParameter,
                "flecs::world instance contains invalid reference to world or stage"
            );
            sys::flecs_poly_is_(
                self.raw_world.as_ptr() as *const c_void,
                sys::ecs_stage_t_magic as i32,
            )
        }
    }

    /// Merge world or stage.
    ///
    /// When automatic merging is disabled, an application can call this
    /// operation on either an individual stage, or on the world which will merge
    /// all stages. This operation may only be called when staging is not enabled
    /// (either after [`World::progress()`] or after [`World::readonly_end()`]).
    ///
    /// This operation may be called on an already merged stage or world.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// #[derive(Component)]
    /// struct Position {
    ///     x: i32,
    ///     y: i32,
    /// }
    ///
    /// let world = World::new();
    ///
    /// let e = world.entity();
    ///
    /// let stage = world.create_async_stage();
    ///
    /// e.mut_current_stage(stage).set(Position { x: 10, y: 20 });
    ///
    /// assert!(!e.has(Position::id()));
    ///
    /// stage.merge();
    ///
    /// assert!(e.has(Position::id()));
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::get_stage_count()`]
    /// * [`World::is_stage()`]
    /// * [`World::set_stage_count()`]
    /// * [`World::stage()`]
    /// * [`World::stage_id()`]
    pub fn merge(&self) {
        unsafe { sys::ecs_merge(self.raw_world.as_ptr()) };
    }

    /// Get stage-specific world pointer.
    ///
    /// Flecs threads can safely invoke the API as long as they have a private
    /// context to write to, also referred to as the stage. This function returns a
    /// pointer to a stage, disguised as a world pointer.
    ///
    /// Note that this function does not(!) create a new world. It simply wraps the
    /// existing world in a thread-specific context, which the API knows how to
    /// unwrap. The reason the stage is returned as an [`sys::ecs_world_t`] is so that
    /// it can be passed transparently to the existing API functions, vs. having to
    /// create a dedicated API for threading.
    ///
    /// # Arguments
    ///
    /// * `stage_id` - The index of the stage to retrieve.
    ///
    /// # Returns
    ///
    /// A thread-specific pointer to the world.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// assert_eq!(world.stage_id(), 0);
    ///
    /// world.set_stage_count(4);
    ///
    /// assert_eq!(world.stage_id(), 0);
    ///
    /// let stage = world.stage(3);
    ///
    /// assert_eq!(stage.stage_id(), 3);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::get_stage_count()`]
    /// * [`World::is_stage()`]
    /// * [`World::merge()`]
    /// * [`World::set_stage_count()`]
    /// * [`World::stage_id()`]
    pub fn stage(&self, stage_id: i32) -> WorldRef<'_> {
        unsafe { WorldRef::from_ptr(sys::ecs_get_stage(self.raw_world.as_ptr(), stage_id)) }
    }

    /// Create asynchronous stage.
    ///
    /// An asynchronous stage can be used to asynchronously queue operations for
    /// later merging with the world. An asynchronous stage is similar to a regular
    /// stage, except that it does not allow reading from the world.
    ///
    /// Asynchronous stages are never merged automatically, and must therefore be
    /// manually merged with the [`World::merge()`] function. It is not necessary to call
    /// [`World::defer_begin()`] or [`World::defer_end()`] before and after enqueuing commands,
    /// as an asynchronous stage unconditionally defers operations.
    ///
    /// The application must ensure that no commands are added to the stage while the
    /// stage is being merged.
    ///
    /// An asynchronous stage will be cleaned up when it is dropped.
    ///
    /// # Returns
    ///
    /// The stage.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// #[derive(Component)]
    /// struct Position {
    ///     x: i32,
    ///     y: i32,
    /// }
    ///
    /// let world = World::new();
    ///
    /// let e = world.entity();
    ///
    /// let stage = world.create_async_stage();
    ///
    /// e.mut_current_stage(stage).set(Position { x: 10, y: 20 });
    ///
    /// assert!(!e.has(Position::id()));
    ///
    /// stage.merge();
    ///
    /// assert!(e.has(Position::id()));
    /// ```
    pub fn create_async_stage(&self) -> WorldRef<'_> {
        unsafe { WorldRef::from_ptr(sys::ecs_stage_new(self.raw_world.as_ptr())) }
    }

    /// Get actual world.
    ///
    /// If the current object points to a stage, this operation will return the
    /// actual world.
    ///
    /// # Returns
    ///
    /// The actual world.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// let stage = world.stage(0);
    ///
    /// let world_ref = stage.real_world();
    ///
    /// assert!(!world_ref.is_stage());
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::is_stage()`]
    /// * [`World::stage()`]
    /// * [`WorldRef`]
    pub fn real_world(&self) -> WorldRef<'_> {
        self.world().real_world()
    }

    /// Set world context.
    ///
    /// Set a context value that can be accessed by anyone that has a reference
    /// to the world.
    ///
    /// # Arguments
    ///
    /// * `ctx` - The world context.
    /// * `ctx_free` - The free function for the context. Can pass `None` if no free function is needed.
    ///
    /// # Example
    ///
    /// ```
    /// use core::ffi::c_void;
    /// use flecs_ecs::prelude::*;
    ///
    /// #[extern_abi]
    /// fn free_ctx(ctx: *mut c_void) {
    ///     unsafe {
    ///         Box::from_raw(ctx as *mut i32);
    ///     }
    /// }
    ///
    /// let world = World::new();
    ///
    /// let ctx = Box::leak(Box::new(42));
    ///
    /// world.set_context(ctx as *mut i32 as *mut c_void, Some(free_ctx));
    ///
    /// assert_eq!(world.context() as *const i32, ctx);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::context()`]
    #[expect(
        clippy::not_unsafe_ptr_arg_deref,
        reason = "this doesn't actually deref the pointer and controls lifetime"
    )]
    pub fn set_context(&self, ctx: *mut c_void, ctx_free: sys::ecs_ctx_free_t) {
        unsafe { sys::ecs_set_ctx(self.raw_world.as_ptr(), ctx, ctx_free) }
    }

    /// Get world context.
    ///
    /// # Returns
    ///
    /// The configured world context.
    ///
    /// # Example
    ///
    /// See [`World::set_context`].
    ///
    /// # See also
    ///
    /// * [`World::set_context()`]
    pub fn context(&self) -> *mut c_void {
        unsafe { sys::ecs_get_ctx(self.raw_world.as_ptr()) }
    }

    #[expect(dead_code, reason = "possibly used in the future")]
    pub(crate) fn get_context(world: *mut sys::ecs_world_t) -> *mut WorldCtx {
        unsafe { sys::ecs_get_binding_ctx(world) as *mut WorldCtx }
    }

    #[expect(dead_code, reason = "possibly used in the future")]
    pub(crate) fn get_components_map(world: *mut sys::ecs_world_t) -> &'static mut FlecsIdMap {
        unsafe { &mut (*(sys::ecs_get_binding_ctx(world) as *mut WorldCtx)).components }
    }

    pub(crate) fn get_components_map_ptr(world: *mut sys::ecs_world_t) -> *mut FlecsIdMap {
        unsafe { &mut (*(sys::ecs_get_binding_ctx(world) as *mut WorldCtx)).components }
    }

    #[doc(hidden)]
    pub fn components_map(&self) -> &'static mut FlecsIdMap {
        unsafe { &mut (*(self.components.as_ptr())) }
    }

    #[expect(dead_code, reason = "possibly used in the future")]
    pub(crate) fn get_components_array(world: *mut sys::ecs_world_t) -> &'static mut FlecsArray {
        unsafe { &mut (*(sys::ecs_get_binding_ctx(world) as *mut WorldCtx)).components_array }
    }

    pub(crate) fn get_components_array_ptr(world: *mut sys::ecs_world_t) -> *mut FlecsArray {
        unsafe { &mut (*(sys::ecs_get_binding_ctx(world) as *mut WorldCtx)).components_array }
    }

    #[doc(hidden)]
    pub fn components_array(&self) -> &'static mut FlecsArray {
        unsafe { &mut (*(self.components_array.as_ptr())) }
    }

    /// Set world binding context
    /// Set a context value that can be accessed by anyone that has a reference to the world.
    ///
    /// # Arguments
    ///
    /// * `ctx` - The world context.
    /// * `ctx_free` - The free function for the context. Can pass `None` if no free function is needed.
    ///
    /// # See also
    ///
    /// * [`World::get_binding_context()`]
    #[expect(dead_code, reason = "possibly used in the future")]
    pub(crate) fn set_binding_context(&self, ctx: *mut c_void, ctx_free: sys::ecs_ctx_free_t) {
        unsafe { sys::ecs_set_binding_ctx(self.raw_world.as_ptr(), ctx, ctx_free) }
    }

    /// Get world binding context.
    ///
    /// # Returns
    ///
    /// The configured world context.
    ///
    /// # See also
    ///
    /// * [`World::set_binding_context()`]
    #[expect(dead_code, reason = "possibly used in the future")]
    pub(crate) fn get_binding_context(&self) -> *mut c_void {
        unsafe { sys::ecs_get_binding_ctx(self.raw_world.as_ptr()) }
    }

    /// Preallocate memory for a number of entities.
    ///
    /// This function preallocates memory for the entity index.
    ///
    /// # Arguments
    ///
    /// * `entity_count` - Number of entities to preallocate memory for.
    pub fn preallocate_entity_count(&self, entity_count: i32) {
        unsafe { sys::ecs_dim(self.raw_world.as_ptr(), entity_count) };
    }

    /// Free unused memory.
    ///
    /// This operation frees allocated memory that is no longer in use by the world.
    /// Examples of allocations that get cleaned up are:
    /// - Unused pages in the entity index
    /// - Component columns
    /// - Empty tables
    ///
    /// Flecs uses allocators internally for speeding up allocations. Allocators are
    /// not evaluated by this function, which means that the memory reported by the
    /// OS may not go down. For this reason, this function is most effective when
    /// combined with `FLECS_USE_OS_ALLOC`, which disables internal allocators.
    pub fn shrink_memory(&self) {
        unsafe { sys::ecs_shrink(self.raw_world.as_ptr()) };
    }

    /// Set the entity range.
    ///
    /// This function limits the range of issued entity IDs between `min` and `max`.
    ///
    /// # Arguments
    ///
    /// * `min` - Minimum entity ID issued.
    /// * `max` - Maximum entity ID issued.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// world.set_entity_range(5000, 0);
    ///
    /// let e = world.entity();
    ///
    /// assert_eq!(e.id(), 5000);
    ///
    /// let e = world.entity();
    ///
    /// assert_eq!(e.id(), 5001);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::enable_range_check()`]
    /// * [`World::preallocate_entity_count()`]
    pub fn set_entity_range(&self, min: impl Into<Entity>, max: impl Into<Entity>) {
        unsafe { sys::ecs_set_entity_range(self.raw_world.as_ptr(), *min.into(), *max.into()) };
    }

    /// Enforce that operations cannot modify entities outside of the specified range.
    ///
    /// This function ensures that only entities within the specified range can
    /// be modified. Use this function if specific parts of the code are only allowed
    /// to modify a certain set of entities, as could be the case for networked applications.
    ///
    /// # Arguments
    ///
    /// * `enabled` - True if the range check should be enabled, false otherwise.
    ///
    /// # Example
    ///
    /// ```should_panic
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// let e = world.entity();
    /// let e2 = world.entity();
    ///
    /// world.set_entity_range(5000, 0);
    /// world.enable_range_check(true);
    ///
    /// e.add(e2); // panics in debug mode! because e and e2 are outside the range
    /// panic!("in release mode, this does not panic, this is to prevent the test from failing")
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::set_entity_range()`]
    pub fn enable_range_check(&self, enabled: bool) {
        unsafe { sys::ecs_enable_range_check(self.raw_world.as_ptr(), enabled) };
    }

    /// Get the current scope. Get the scope set by `set_scope`.
    /// If no scope is set, this operation will return `None`.
    ///
    /// # Returns
    ///
    /// Returns an `EntityView` representing the current scope.
    /// If no scope is set, this operation will return `None`.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// let e = world.entity_named("scope");
    ///
    /// world.set_scope(e);
    ///
    /// let s = world.get_scope();
    ///
    /// assert_eq!(s.unwrap(), e);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::set_scope()`]
    #[inline(always)]
    pub fn get_scope(&self) -> Option<EntityView<'_>> {
        let scope = unsafe { sys::ecs_get_scope(self.raw_world.as_ptr()) };

        if scope == 0 {
            None
        } else {
            Some(EntityView::new_from(self, scope))
        }
    }

    /// Set the current scope. This operation sets the scope of the current stage to the provided entity.
    /// As a result new entities will be created in this scope, and lookups will be relative to the provided scope.
    /// It is considered good practice to restore the scope to the old value.
    ///
    /// This method changes the current scope to the entity represented by the provided `id`.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the scope entity to set.
    ///
    /// # Returns
    ///
    /// Returns an `EntityView` representing the previous set scope.
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// let world = World::new();
    ///
    /// let e = world.entity_named("scope");
    ///
    /// // previous scope can be used to set the scope back to the original.
    /// let previous_scope = world.set_scope(e);
    ///
    /// let s = world.get_scope();
    ///
    /// assert_eq!(s.unwrap(), e);
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::get_scope()`]
    /// * [`World::set_scope()`]
    #[inline(always)]
    pub fn set_scope(&self, id: impl IntoId) -> EntityView<'_> {
        EntityView::new_from(self, unsafe {
            sys::ecs_set_scope(self.raw_world.as_ptr(), *id.into_id(self))
        })
    }

    /// Sets the search path for entity lookup operations.
    ///
    /// This function configures the search path used for looking up an entity.
    ///
    /// # Best Practices
    ///
    /// * It's advisable to restore the previous search path after making temporary changes.
    ///
    /// # Default Behavior
    ///
    /// * The default search path includes `flecs.core`.
    ///
    /// # Overwriting
    ///
    /// * Providing a custom search path will overwrite the existing search path.
    ///
    /// # Considerations
    ///
    /// * If the custom search path doesn't include `flecs.core`, operations that rely on looking up names from `flecs.core` may fail.
    ///
    /// # Arguments
    ///
    /// * `search_path` - The entity to set as the search path.
    ///
    /// # Returns
    ///
    /// Returns the current search path after the operation.
    ///
    /// # See also
    ///
    /// * [`World::lookup()`]
    /// * [`World::lookup_recursive()`]
    /// * [`World::try_lookup()`]
    /// * [`World::try_lookup_recursive()`]
    /// * C API: `sys::ecs_set_lookup_path`
    // TODO we need to improve this function somehow, it's not very ergonomic
    pub fn set_lookup_path(&self, search_path: impl IntoEntity) -> *mut sys::ecs_entity_t {
        unsafe {
            sys::ecs_set_lookup_path(self.raw_world.as_ptr(), &*search_path.into_entity(self))
        }
    }

    /// Lookup an entity by name.
    /// The entity is searched recursively recursively traversing
    /// up the tree until found.
    ///
    /// # Panics
    ///
    /// Ensure that the entity exists before using it.
    /// Use the [`World::try_lookup_recursive()`] variant otherwise.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the entity to lookup.
    ///
    /// # Returns
    ///
    /// The entity
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// #[derive(Component)]
    /// struct Position {
    ///     x: i32,
    ///     y: i32,
    /// }
    ///
    /// let world = World::new();
    /// let a = world.entity().set(Position { x: 10, y: 20 }).with(|| {
    ///     world.entity_named("X");
    /// });
    ///
    /// let x = world.lookup_recursive("X");
    /// assert!(x.has(a));
    /// ```
    ///
    /// # See also
    ///
    /// * [`World::lookup()`]
    /// * [`World::set_lookup_path()`]
    /// * [`World::try_lookup()`]
    /// * [`World::try_lookup_recursive()`]
    #[inline(always)]
    pub fn lookup_recursive(&self, name: &str) -> EntityView<'_> {
        self.try_lookup_recursive(name).unwrap_or_else(|| {
            panic!("Entity {name} not found, when unsure, use try_lookup_recursive")
        })
    }

    /// Lookup entity by name, only the current scope is searched
    ///
    /// # Panics
    ///
    /// Ensure that the entity exists before using it.
    /// Use the [`World::try_lookup()`] variant otherwise.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the entity to lookup.
    ///
    /// # Returns
    ///
    /// The entity
    ///
    /// # See also
    ///
    /// * [`World::lookup_recursive()`]
    /// * [`World::set_lookup_path()`]
    /// * [`World::try_lookup()`]
    /// * [`World::try_lookup_recursive()`]
    #[inline(always)]
    pub fn lookup(&self, name: &str) -> EntityView<'_> {
        self.try_lookup(name)
            .unwrap_or_else(|| panic!("Entity {name} not found, when unsure, use try_lookup"))
    }

    /// Helper function for [`World::try_lookup()`] and [`World::try_lookup_recursive()`].
    fn try_lookup_impl(&self, name: &str, recursively: bool) -> Option<EntityView<'_>> {
        let name = compact_str::format_compact!("{}\0", name);

        let entity_id = unsafe {
            sys::ecs_lookup_path_w_sep(
                self.raw_world.as_ptr(),
                0,
                name.as_ptr() as *const _,
                SEPARATOR.as_ptr(),
                SEPARATOR.as_ptr(),
                recursively,
            )
        };
        if entity_id == 0 {
            None
        } else {
            Some(EntityView::new_from(self, entity_id))
        }
    }

    /// Lookup an entity by name.
    /// The entity is searched recursively recursively traversing
    /// up the tree until found.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the entity to lookup.
    ///
    /// # Returns
    ///
    /// The entity if found, otherwise `None`.
    ///
    /// # See also
    ///
    /// * [`World::lookup()`]
    /// * [`World::lookup_recursive()`]
    /// * [`World::set_lookup_path()`]
    /// * [`World::try_lookup()`]
    #[inline(always)]
    pub fn try_lookup_recursive(&self, name: &str) -> Option<EntityView<'_>> {
        self.try_lookup_impl(name, true)
    }

    /// Lookup entity by name, only the current scope is searched
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the entity to lookup.
    ///
    /// # Returns
    ///
    /// The entity if found, otherwise `None`.
    ///
    /// # See also
    ///
    /// * [`World::lookup()`]
    /// * [`World::lookup_recursive()`]
    /// * [`World::set_lookup_path()`]
    /// * [`World::try_lookup_recursive()`]
    #[inline(always)]
    pub fn try_lookup(&self, name: &str) -> Option<EntityView<'_>> {
        self.try_lookup_impl(name, false)
    }

    /// Sets a singleton component of type `T` on the world.
    ///
    /// # Arguments
    ///
    /// * `component` - The singleton component to set on the world.
    pub fn set<T: ComponentId + DataComponent + ComponentType<Struct>>(&self, component: T) {
        let id = T::entity_id(self);
        set_helper(self.raw_world.as_ptr(), id, component, id);
    }

    /// Set a singleton pair using the second element type and a first id.
    ///
    /// # Safety
    ///
    /// Caller must ensure that `First` and `second` pair id data type is the one provided.
    pub fn set_first<First>(&self, second: impl Into<Entity>, first: First)
    where
        First: ComponentId + ComponentType<Struct> + DataComponent,
    {
        let entity = EntityView::new_from(self, First::entity_id(self));
        entity.set_first::<First>(first, second);
    }

    /// Set a singleton pair using the second element type and a first id.
    ///
    /// # Safety
    ///
    /// Caller must ensure that `first` and `Second` pair id data type is the one provided.
    pub fn set_second<Second>(&self, first: impl Into<Entity>, second: Second)
    where
        Second: ComponentId + ComponentType<Struct> + DataComponent,
    {
        let entity = EntityView::new_from(self, Second::entity_id(self));
        entity.set_second::<Second>(first, second);
    }

    /// Set singleton pair.
    /// This operation sets the pair value, and uses the first non tag / ZST as type. If the
    /// entity did not yet have the pair, it will be added, otherwise overridden.
    pub fn set_pair<First, Second>(&self, data: <(First, Second) as ComponentOrPairId>::CastType)
    where
        First: ComponentId,
        Second: ComponentId,
        (First, Second): ComponentOrPairId,
    {
        const {
            assert!(
                !<(First, Second) as ComponentOrPairId>::IS_TAGS,
                "setting tag relationships is not possible with `set_pair`. use `add_pair` instead."
            );
        };

        let entity = EntityView::new_from(
            self,
            <<(First, Second) as ComponentOrPairId>::First as ComponentId>::entity_id(self),
        );
        entity.set_pair::<First, Second>(data);
    }

    /// assign a component for an entity.
    /// This operation sets the component value. If the entity did not yet have
    /// the component the operation will panic.
    pub fn assign<T: ComponentId + DataComponent>(&self, value: T) {
        let id = T::entity_id(self);
        assign_helper(self.ptr_mut(), id, value, id);
    }

    /// assign a component for an entity.
    /// This operation sets the component value. If the entity did not yet have
    /// the component the operation will panic.
    pub fn assign_id<T: ComponentId + DataComponent>(&self, value: T, id: impl IntoId) {
        let id = *id.into_id(self);
        assign_helper(self.ptr_mut(), id, value, id);
    }

    /// assign a component for an entity.
    /// This operation sets the component value. If the entity did not yet have
    /// the component the operation will panic.
    pub fn assign_pair<First, Second>(
        &self,
        value: <(First, Second) as ComponentOrPairId>::CastType,
    ) where
        First: ComponentId,
        Second: ComponentId,
        (First, Second): ComponentOrPairId,
    {
        let entity = EntityView::new_from(
            self,
            <<(First, Second) as ComponentOrPairId>::CastType as ComponentId>::entity_id(self),
        );

        entity.assign_pair::<First, Second>(value);
    }

    /// assign a component for an entity.
    /// This operation sets the component value. If the entity did not yet have
    /// the component the operation will panic.
    pub fn assign_first<First>(&self, first: First, second: impl Into<Entity>)
    where
        First: ComponentId + DataComponent,
    {
        let entity = EntityView::new_from(self, First::entity_id(self));
        entity.assign_first::<First>(first, second);
    }

    /// assign a component for an entity.
    /// This operation sets the component value. If the entity did not yet have
    /// the component the operation will panic.
    pub fn assign_second<Second>(&self, first: impl Into<Entity>, second: Second)
    where
        Second: ComponentId + DataComponent,
    {
        let entity = EntityView::new_from(self, Second::entity_id(self));
        entity.assign_second::<Second>(first, second);
    }

    /// signal that singleton component was modified.
    ///
    /// # Arguments
    ///
    /// * `id` - The id of the component that was modified.
    ///
    /// # See also
    ///
    /// * [`EntityView::modified()`]
    /// * [`World::modified()`]
    #[inline(always)]
    pub fn modified(&self, id: impl Into<Entity>) {
        let id = id.into();
        EntityView::new_from(self, id).modified(id);
    }

    /// set the version of the provided entity.
    pub fn set_version(&self, entity: impl Into<Entity>) {
        unsafe { sys::ecs_set_version(self.raw_world.as_ptr(), *entity.into()) };
    }

    /// returns true if the world is currently multithreaded, such as when a system that is multithreaded is running.
    #[inline(always)]
    pub fn is_currently_multithreaded(&self) -> bool {
        unsafe {
            sys::ecs_world_get_flags(self.raw_world.as_ptr()) & sys::EcsWorldMultiThreaded != 0
        }
    }

    /// Return component id if it has been registered.
    ///
    /// This is similar to `component_id::<T>()` but will never register the
    /// component with the world. If `T` is not registered in this world, returns `None`.
    #[inline(always)]
    pub fn get_component_id<T: ComponentId>(&self) -> Option<Entity> {
        if <T as ComponentId>::is_registered_with_world(self) {
            Some(Entity(T::entity_id(self)))
        } else {
            None
        }
    }

    /// Return raw type info for an id (component, tag, or pair).
    ///
    /// Returns `None` when no type info is available for the provided id.
    #[inline(always)]
    pub fn type_info_from(&self, id: impl IntoId) -> Option<*const sys::ecs_type_info_t> {
        let ptr = unsafe { sys::ecs_get_type_info(self.raw_world.as_ptr(), *id.into_entity(self)) };
        if ptr.is_null() { None } else { Some(ptr) }
    }

    /// Iterate entities in root of world
    ///
    /// # Arguments
    ///
    /// * `func` - The function invoked for each child. Must match the signature `FnMut(EntityView)`.
    #[inline(always)]
    pub fn each_child(&self, callback: impl FnMut(EntityView)) {
        EntityView::new(self).each_child(callback);
    }

    /// create alias for component
    ///
    /// # Type Parameters
    ///
    /// * `T` - The component type to create an alias for.
    ///
    /// # Arguments
    ///
    /// * `alias` - The alias to create.
    ///
    /// # Returns
    ///
    /// The entity representing the component.
    #[inline(always)]
    pub fn set_alias_component<T: ComponentId>(&self, alias: &str) -> EntityView<'_> {
        let alias = compact_str::format_compact!("{}\0", alias);

        let id = T::entity_id(self);
        if alias.is_empty() {
            unsafe {
                sys::ecs_set_alias(
                    self.raw_world.as_ptr(),
                    id,
                    sys::ecs_get_name(self.raw_world.as_ptr(), id),
                );
            };
        } else {
            unsafe { sys::ecs_set_alias(self.raw_world.as_ptr(), id, alias.as_ptr() as *const _) };
        }
        EntityView::new_from(self, id)
    }

    /// create alias for entity by name
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the entity to create an alias for.
    /// * `alias` - The alias to create.
    ///
    /// # Returns
    ///
    /// The entity found by name.
    #[inline(always)]
    pub fn set_alias_entity_by_name(&self, name: &str, alias: &str) -> EntityView<'_> {
        let name = compact_str::format_compact!("{}\0", name);
        let alias = compact_str::format_compact!("{}\0", alias);

        let id = unsafe {
            sys::ecs_lookup_path_w_sep(
                self.raw_world.as_ptr(),
                0,
                name.as_ptr() as *const _,
                SEPARATOR.as_ptr(),
                SEPARATOR.as_ptr(),
                true,
            )
        };
        ecs_assert!(id != 0, FlecsErrorCode::InvalidParameter);
        unsafe { sys::ecs_set_alias(self.raw_world.as_ptr(), id, alias.as_ptr() as *const _) };
        EntityView::new_from(self, id)
    }

    /// create alias for entity
    ///
    /// # Arguments
    ///
    /// * `entity` - The entity to create an alias for.
    /// * `alias` - The alias to create.
    #[inline(always)]
    pub fn set_alias_entity(&self, entity: impl Into<Entity>, alias: &str) {
        let alias = compact_str::format_compact!("{}\0", alias);

        let entity = *entity.into();
        if alias.is_empty() {
            unsafe {
                sys::ecs_set_alias(
                    self.raw_world.as_ptr(),
                    entity,
                    sys::ecs_get_name(self.raw_world.as_ptr(), entity),
                );
            };
        } else {
            unsafe {
                sys::ecs_set_alias(self.raw_world.as_ptr(), entity, alias.as_ptr() as *const _);
            };
        }
    }

    /// Count entities with the provided id.
    ///
    /// # Arguments
    ///
    /// * `id` - The id to count.
    ///
    /// # Returns
    ///
    /// The number of entities with the provided id.
    pub fn count(&self, id: impl IntoId) -> i32 {
        unsafe { sys::ecs_count_id(self.raw_world.as_ptr(), *id.into_id(self)) }
    }

    /// Count entities with the provided enum constant.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The enum type.
    ///
    /// # Arguments
    ///
    /// * `constant` - The enum constant to count.
    ///
    /// # Returns
    ///
    /// The number of entities with the provided enum constant.
    pub fn count_enum<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &self,
        enum_value: T,
    ) -> i32 {
        unsafe { sys::ecs_count_id(self.raw_world.as_ptr(), *(enum_value.id_variant(self).id)) }
    }

    /// Count entities with the provided pair enum tag.
    ///
    /// # Type Parameters
    ///
    /// * `First` - The first element of the pair.
    /// * `Second` - The second element of the pair.
    ///
    /// # Arguments
    ///
    /// * `enum_value` - The enum value to count.
    ///
    /// # Returns
    ///
    /// The number of entities with the provided pair enum tag.
    pub fn count_enum_tag_pair<First, Second>(&self, enum_value: Second) -> i32
    where
        First: ComponentId,
        Second: ComponentId + ComponentType<Enum> + EnumComponentInfo,
    {
        unsafe {
            sys::ecs_count_id(
                self.raw_world.as_ptr(),
                ecs_pair(First::entity_id(self), *(enum_value.id_variant(self)).id),
            )
        }
    }

    /// All entities created in function are created in scope. All operations
    /// called in function (such as lookup) are relative to scope.
    ///
    /// # Arguments
    ///
    /// * `parent_id` - The id of the scope to use.
    /// * `func` - The function to run.
    pub fn run_in_scope_with(&self, parent_id: impl IntoEntity, mut func: impl FnMut()) {
        let world = self.world();
        let prev: sys::ecs_id_t =
            unsafe { sys::ecs_set_scope(self.raw_world.as_ptr(), *parent_id.into_entity(world)) };
        func();
        unsafe {
            sys::ecs_set_scope(self.raw_world.as_ptr(), prev);
        }
    }

    /// Use provided scope for operations ran on returned world.
    /// Operations need to be ran in a single statement
    ///
    /// # Arguments
    ///
    /// * `parent_id` - The id of the scope to use.
    ///
    /// # Returns
    ///
    /// A scoped world.
    pub fn scope(&self, parent_id: impl IntoId, mut f: impl FnMut(&World)) {
        let previous_scope = self.set_scope(parent_id);
        f(self);
        self.set_scope(previous_scope);
    }

    /// Use provided scope of name for operations ran on returned world.
    /// Operations need to be ran in a single statement
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the scope to use.
    ///
    /// # Returns
    ///
    /// A scoped world.
    pub fn scope_name(&self, name: &str, f: impl FnMut(&World)) {
        self.scope(EntityView::new_named(self, name).id, f);
    }

    /// all entities created in function are created with id
    ///
    /// # Arguments
    ///
    /// * `id`: The id to create entities with.
    /// * `func`: The function to run.
    pub fn with(&self, id: impl IntoId, mut func: impl FnMut()) {
        let prev: sys::ecs_id_t =
            unsafe { sys::ecs_set_with(self.raw_world.as_ptr(), *id.into_id(self)) };
        func();
        unsafe {
            sys::ecs_set_with(self.raw_world.as_ptr(), prev);
        }
    }

    /// Entities created in function are created with enum constant
    ///
    /// # Type Parameters
    ///
    /// * `T`: The enum type.
    ///
    /// # Arguments
    ///
    /// * `enum_value`: The enum value to give the entity.
    /// * `func`: The function to run.
    pub fn with_enum<T>(&self, enum_value: T, func: impl FnMut())
    where
        T: ComponentId + ComponentType<Enum> + EnumComponentInfo,
    {
        self.with(enum_value.id_variant(self), func);
    }

    /// Entities created in function are created with enum tag pair
    ///
    /// # Type Parameters
    ///
    /// * `First`: The first element of the pair.
    /// * `Second`: The enum component type.
    ///
    /// # Arguments
    ///
    /// * `enum_value`: The enum value to give the entity.
    /// * `func`: The function to run.
    pub fn with_enum_pair<First, Second>(&self, enum_value: Second, func: impl FnMut())
    where
        First: ComponentId,
        Second: ComponentId + ComponentType<Enum> + EnumComponentInfo,
    {
        self.with(
            ecs_pair(First::entity_id(self), **(enum_value.id_variant(self))),
            func,
        );
    }

    /// Delete all entities with the given id
    ///
    /// # Arguments
    ///
    /// * `id`: The id to delete.
    pub fn delete_entities_with(&self, id: impl IntoId) {
        unsafe {
            sys::ecs_delete_with(self.raw_world.as_ptr(), *id.into_id(self));
        }
    }

    /// Delete all entities with the given enum constant
    ///
    /// # Type Parameters
    ///
    /// * `T`: The enum type.
    ///
    /// # Arguments
    ///
    /// * `enum_value`: The enum value to query against for deletion.
    pub fn delete_with_enum<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &self,
        enum_value: T,
    ) {
        self.delete_entities_with(enum_value.id_variant(self));
    }

    /// Delete all entities with the given enum tag pair / relationship
    ///
    /// # Type Parameters
    ///
    /// * `First`: The first element of the pair.
    /// * `Second`: The enum component type.
    ///
    /// # Arguments
    ///
    /// * `enum_value`: The enum value to query against for deletion.
    ///
    /// # See also
    ///
    /// * `world::delete_with`
    pub fn delete_with_enum_pair<First, Second>(&self, enum_value: Second)
    where
        First: ComponentId,
        Second: ComponentId + ComponentType<Enum> + EnumComponentInfo,
    {
        self.delete_entities_with(ecs_pair(
            First::entity_id(self),
            **enum_value.id_variant(self),
        ));
    }

    /// Remove all instances of the given id from entities
    ///
    /// # Arguments
    ///
    /// * `id`: The id to remove.
    pub fn remove_all(&self, id: impl IntoId) {
        unsafe {
            sys::ecs_remove_all(self.raw_world.as_ptr(), *id.into_id(self));
        }
    }

    /// Remove all instances with the given enum constant from entities
    ///
    /// # Type Parameters
    ///
    /// * `T`: The enum type.
    ///
    /// # Arguments
    ///
    /// * `enum_value`: The enum value to query against for removal.
    pub fn remove_all_enum<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &self,
        enum_value: T,
    ) {
        self.remove_all(enum_value.id_variant(self));
    }

    /// Remove all instances with the given enum tag pair / relationship from entities
    ///
    /// # Type Parameters
    ///
    /// * `First`: The first element of the pair.
    /// * `Second`: The enum component type.
    ///
    /// # Arguments
    ///
    /// * `enum_value`: The enum value to query against for removal.
    pub fn remove_all_enum_pair<First, Second>(&self, enum_value: Second)
    where
        First: ComponentId,
        Second: ComponentId + ComponentType<Enum> + EnumComponentInfo,
    {
        self.remove_all((First::entity_id(self), enum_value.id_variant(self)));
    }

    /// Checks if the given entity ID exists in the world.
    ///
    /// # Arguments
    ///
    /// * `entity` - The entity to check.
    ///
    /// # Returns
    ///
    /// True if the entity exists, false otherwise.
    pub fn exists(&self, entity: impl Into<Entity>) -> bool {
        unsafe { sys::ecs_exists(self.raw_world.as_ptr(), *entity.into()) }
    }

    /// Checks if the given entity ID is alive in the world.
    pub fn is_alive(&self, entity: impl Into<Entity>) -> bool {
        unsafe { sys::ecs_is_alive(self.raw_world.as_ptr(), *entity.into()) }
    }

    /// Checks if the given entity ID is valid.
    /// Invalid entities cannot be used with API functions.
    pub fn is_valid(&self, entity: impl Into<Entity>) -> bool {
        unsafe { sys::ecs_is_valid(self.raw_world.as_ptr(), *entity.into()) }
    }

    /// Get alive entity for id.
    ///
    /// # Arguments
    ///
    /// * `entity` - The entity to check
    ///
    /// # Returns
    ///
    /// The entity with the current generation. If the entity is not alive, this
    /// function will return an Entity of 0. Use `try_get_alive` if you want to
    /// return an `Option<EntityView>`.
    pub fn get_alive(&self, entity: impl Into<Entity>) -> EntityView<'_> {
        let entity = unsafe { sys::ecs_get_alive(self.raw_world.as_ptr(), *entity.into()) };

        EntityView::new_from(self, entity)
    }

    /// Get alive entity for id.
    ///
    /// # Arguments
    ///
    /// * `entity` - The entity to check
    ///
    /// # Returns
    ///
    /// The entity with the current generation.
    /// If the entity is not alive, this function will return `None`.
    pub fn try_get_alive(&self, entity: impl Into<Entity>) -> Option<EntityView<'_>> {
        let entity = unsafe { sys::ecs_get_alive(self.raw_world.as_ptr(), *entity.into()) };
        if entity == 0 {
            None
        } else {
            Some(EntityView::new_from(self, entity))
        }
    }

    /// Ensures that entity with provided generation is alive.
    /// This operation will fail if an entity exists with the same id and a
    /// different, non-zero generation.
    ///
    /// # Arguments
    ///
    /// * `entity` - The entity to ensure is alive.
    ///
    /// # Returns
    ///
    /// The entity with the provided generation.
    pub fn make_alive(&self, entity: impl Into<Entity>) -> EntityView<'_> {
        let entity = *entity.into();
        unsafe { sys::ecs_make_alive(self.raw_world.as_ptr(), entity) };
        EntityView::new_from(self, entity)
    }

    /// Run callback after completing frame
    ///
    /// # Arguments
    ///
    /// * `action` - The action to run.
    /// * `ctx` - The context to pass to the action.
    pub fn run_post_frame(&self, action: fn(WorldRef)) {
        let ctx: *mut ::core::ffi::c_void = action as *const () as *mut ::core::ffi::c_void;
        unsafe {
            sys::ecs_run_post_frame(self.raw_world.as_ptr(), Some(c_run_post_frame), ctx);
        }
    }
}