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
use crate::{
archetype::{Archetype, ArchetypeComponentId, ArchetypeGeneration, ArchetypeId},
change_detection::Mut,
component::{ComponentId, Tick},
entity::Entity,
prelude::{Component, FromWorld},
query::{
Access, BatchingStrategy, DebugCheckedUnwrap, FilteredAccess, QueryCombinationIter,
QueryIter, QueryParIter,
},
storage::{SparseSetIndex, TableId},
world::{unsafe_world_cell::UnsafeWorldCell, World, WorldId},
};
#[cfg(feature = "trace")]
use bevy_utils::tracing::Span;
use fixedbitset::FixedBitSet;
use std::{any::TypeId, borrow::Borrow, fmt, mem::MaybeUninit, ptr};
use super::{
NopWorldQuery, QueryBuilder, QueryData, QueryEntityError, QueryFilter, QueryManyIter,
QuerySingleError, ROQueryItem,
};
/// Provides scoped access to a [`World`] state according to a given [`QueryData`] and [`QueryFilter`].
#[repr(C)]
// SAFETY NOTE:
// Do not add any new fields that use the `D` or `F` generic parameters as this may
// make `QueryState::as_transmuted_state` unsound if not done with care.
pub struct QueryState<D: QueryData, F: QueryFilter = ()> {
world_id: WorldId,
pub(crate) archetype_generation: ArchetypeGeneration,
pub(crate) matched_tables: FixedBitSet,
pub(crate) matched_archetypes: FixedBitSet,
pub(crate) archetype_component_access: Access<ArchetypeComponentId>,
pub(crate) component_access: FilteredAccess<ComponentId>,
// NOTE: we maintain both a TableId bitset and a vec because iterating the vec is faster
pub(crate) matched_table_ids: Vec<TableId>,
// NOTE: we maintain both a ArchetypeId bitset and a vec because iterating the vec is faster
pub(crate) matched_archetype_ids: Vec<ArchetypeId>,
pub(crate) fetch_state: D::State,
pub(crate) filter_state: F::State,
#[cfg(feature = "trace")]
par_iter_span: Span,
}
impl<D: QueryData, F: QueryFilter> fmt::Debug for QueryState<D, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueryState")
.field("world_id", &self.world_id)
.field("matched_table_count", &self.matched_table_ids.len())
.field("matched_archetype_count", &self.matched_archetype_ids.len())
.finish_non_exhaustive()
}
}
impl<D: QueryData, F: QueryFilter> FromWorld for QueryState<D, F> {
fn from_world(world: &mut World) -> Self {
world.query_filtered()
}
}
impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
/// Converts this `QueryState` reference to a `QueryState` that does not access anything mutably.
pub fn as_readonly(&self) -> &QueryState<D::ReadOnly, F> {
// SAFETY: invariant on `WorldQuery` trait upholds that `D::ReadOnly` and `F::ReadOnly`
// have a subset of the access, and match the exact same archetypes/tables as `D`/`F` respectively.
unsafe { self.as_transmuted_state::<D::ReadOnly, F>() }
}
/// Converts this `QueryState` reference to a `QueryState` that does not return any data
/// which can be faster.
///
/// This doesn't use `NopWorldQuery` as it loses filter functionality, for example
/// `NopWorldQuery<Changed<T>>` is functionally equivalent to `With<T>`.
pub fn as_nop(&self) -> &QueryState<NopWorldQuery<D>, F> {
// SAFETY: `NopWorldQuery` doesn't have any accesses and defers to
// `D` for table/archetype matching
unsafe { self.as_transmuted_state::<NopWorldQuery<D>, F>() }
}
/// Converts this `QueryState` reference to any other `QueryState` with
/// the same `WorldQuery::State` associated types.
///
/// Consider using `as_readonly` or `as_nop` instead which are safe functions.
///
/// # SAFETY
///
/// `NewD` must have a subset of the access that `D` does and match the exact same archetypes/tables
/// `NewF` must have a subset of the access that `F` does and match the exact same archetypes/tables
pub(crate) unsafe fn as_transmuted_state<
NewD: QueryData<State = D::State>,
NewF: QueryFilter<State = F::State>,
>(
&self,
) -> &QueryState<NewD, NewF> {
&*ptr::from_ref(self).cast::<QueryState<NewD, NewF>>()
}
/// Returns the archetype components accessed by this query.
pub fn archetype_component_access(&self) -> &Access<ArchetypeComponentId> {
&self.archetype_component_access
}
/// Returns the components accessed by this query.
pub fn component_access(&self) -> &FilteredAccess<ComponentId> {
&self.component_access
}
/// Returns the tables matched by this query.
pub fn matched_tables(&self) -> &[TableId] {
&self.matched_table_ids
}
/// Returns the archetypes matched by this query.
pub fn matched_archetypes(&self) -> &[ArchetypeId] {
&self.matched_archetype_ids
}
}
impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
/// Creates a new [`QueryState`] from a given [`World`] and inherits the result of `world.id()`.
pub fn new(world: &mut World) -> Self {
let fetch_state = D::init_state(world);
let filter_state = F::init_state(world);
let mut component_access = FilteredAccess::default();
D::update_component_access(&fetch_state, &mut component_access);
// Use a temporary empty FilteredAccess for filters. This prevents them from conflicting with the
// main Query's `fetch_state` access. Filters are allowed to conflict with the main query fetch
// because they are evaluated *before* a specific reference is constructed.
let mut filter_component_access = FilteredAccess::default();
F::update_component_access(&filter_state, &mut filter_component_access);
// Merge the temporary filter access with the main access. This ensures that filter access is
// properly considered in a global "cross-query" context (both within systems and across systems).
component_access.extend(&filter_component_access);
let mut state = Self {
world_id: world.id(),
archetype_generation: ArchetypeGeneration::initial(),
matched_table_ids: Vec::new(),
matched_archetype_ids: Vec::new(),
fetch_state,
filter_state,
component_access,
matched_tables: Default::default(),
matched_archetypes: Default::default(),
archetype_component_access: Default::default(),
#[cfg(feature = "trace")]
par_iter_span: bevy_utils::tracing::info_span!(
"par_for_each",
query = std::any::type_name::<D>(),
filter = std::any::type_name::<F>(),
),
};
state.update_archetypes(world);
state
}
/// Creates a new [`QueryState`] from a given [`QueryBuilder`] and inherits it's [`FilteredAccess`].
pub fn from_builder(builder: &mut QueryBuilder<D, F>) -> Self {
let mut fetch_state = D::init_state(builder.world_mut());
let filter_state = F::init_state(builder.world_mut());
D::set_access(&mut fetch_state, builder.access());
let mut state = Self {
world_id: builder.world().id(),
archetype_generation: ArchetypeGeneration::initial(),
matched_table_ids: Vec::new(),
matched_archetype_ids: Vec::new(),
fetch_state,
filter_state,
component_access: builder.access().clone(),
matched_tables: Default::default(),
matched_archetypes: Default::default(),
archetype_component_access: Default::default(),
#[cfg(feature = "trace")]
par_iter_span: bevy_utils::tracing::info_span!(
"par_for_each",
data = std::any::type_name::<D>(),
filter = std::any::type_name::<F>(),
),
};
state.update_archetypes(builder.world());
state
}
/// Checks if the query is empty for the given [`World`], where the last change and current tick are given.
///
/// # Panics
///
/// If `world` does not match the one used to call `QueryState::new` for this instance.
#[inline]
pub fn is_empty(&self, world: &World, last_run: Tick, this_run: Tick) -> bool {
self.validate_world(world.id());
// SAFETY:
// - We have read-only access to the entire world.
// - The world has been validated.
unsafe {
self.is_empty_unsafe_world_cell(
world.as_unsafe_world_cell_readonly(),
last_run,
this_run,
)
}
}
/// Checks if the query is empty for the given [`UnsafeWorldCell`].
///
/// # Safety
///
/// - `world` must have permission to read any components required by this instance's `F` [`QueryFilter`].
/// - `world` must match the one used to create this [`QueryState`].
#[inline]
pub(crate) unsafe fn is_empty_unsafe_world_cell(
&self,
world: UnsafeWorldCell,
last_run: Tick,
this_run: Tick,
) -> bool {
// SAFETY:
// - The caller ensures that `world` has permission to access any data used by the filter.
// - The caller ensures that the world matches.
unsafe {
self.as_nop()
.iter_unchecked_manual(world, last_run, this_run)
.next()
.is_none()
}
}
/// Updates the state's internal view of the [`World`]'s archetypes. If this is not called before querying data,
/// the results may not accurately reflect what is in the `world`.
///
/// This is only required if a `manual` method (such as [`Self::get_manual`]) is being called, and it only needs to
/// be called if the `world` has been structurally mutated (i.e. added/removed a component or resource). Users using
/// non-`manual` methods such as [`QueryState::get`] do not need to call this as it will be automatically called for them.
///
/// If you have an [`UnsafeWorldCell`] instead of `&World`, consider using [`QueryState::update_archetypes_unsafe_world_cell`].
///
/// # Panics
///
/// If `world` does not match the one used to call `QueryState::new` for this instance.
#[inline]
pub fn update_archetypes(&mut self, world: &World) {
self.update_archetypes_unsafe_world_cell(world.as_unsafe_world_cell_readonly());
}
/// Updates the state's internal view of the `world`'s archetypes. If this is not called before querying data,
/// the results may not accurately reflect what is in the `world`.
///
/// This is only required if a `manual` method (such as [`Self::get_manual`]) is being called, and it only needs to
/// be called if the `world` has been structurally mutated (i.e. added/removed a component or resource). Users using
/// non-`manual` methods such as [`QueryState::get`] do not need to call this as it will be automatically called for them.
///
/// # Note
///
/// This method only accesses world metadata.
///
/// # Panics
///
/// If `world` does not match the one used to call `QueryState::new` for this instance.
pub fn update_archetypes_unsafe_world_cell(&mut self, world: UnsafeWorldCell) {
self.validate_world(world.id());
let archetypes = world.archetypes();
let old_generation =
std::mem::replace(&mut self.archetype_generation, archetypes.generation());
for archetype in &archetypes[old_generation..] {
self.new_archetype(archetype);
}
}
/// # Panics
///
/// If `world_id` does not match the [`World`] used to call `QueryState::new` for this instance.
///
/// Many unsafe query methods require the world to match for soundness. This function is the easiest
/// way of ensuring that it matches.
#[inline]
#[track_caller]
pub fn validate_world(&self, world_id: WorldId) {
#[inline(never)]
#[track_caller]
#[cold]
fn panic_mismatched(this: WorldId, other: WorldId) -> ! {
panic!("Encountered a mismatched World. This QueryState was created from {this:?}, but a method was called using {other:?}.");
}
if self.world_id != world_id {
panic_mismatched(self.world_id, world_id);
}
}
/// Update the current [`QueryState`] with information from the provided [`Archetype`]
/// (if applicable, i.e. if the archetype has any intersecting [`ComponentId`] with the current [`QueryState`]).
pub fn new_archetype(&mut self, archetype: &Archetype) {
if D::matches_component_set(&self.fetch_state, &|id| archetype.contains(id))
&& F::matches_component_set(&self.filter_state, &|id| archetype.contains(id))
&& self.matches_component_set(&|id| archetype.contains(id))
{
self.update_archetype_component_access(archetype);
let archetype_index = archetype.id().index();
if !self.matched_archetypes.contains(archetype_index) {
self.matched_archetypes.grow(archetype_index + 1);
self.matched_archetypes.set(archetype_index, true);
self.matched_archetype_ids.push(archetype.id());
}
let table_index = archetype.table_id().as_usize();
if !self.matched_tables.contains(table_index) {
self.matched_tables.grow(table_index + 1);
self.matched_tables.set(table_index, true);
self.matched_table_ids.push(archetype.table_id());
}
}
}
/// Returns `true` if this query matches a set of components. Otherwise, returns `false`.
pub fn matches_component_set(&self, set_contains_id: &impl Fn(ComponentId) -> bool) -> bool {
self.component_access.filter_sets.iter().any(|set| {
set.with
.ones()
.all(|index| set_contains_id(ComponentId::get_sparse_set_index(index)))
&& set
.without
.ones()
.all(|index| !set_contains_id(ComponentId::get_sparse_set_index(index)))
})
}
/// For the given `archetype`, adds any component accessed used by this query's underlying [`FilteredAccess`] to `access`.
pub fn update_archetype_component_access(&mut self, archetype: &Archetype) {
self.component_access.access.reads().for_each(|id| {
if let Some(id) = archetype.get_archetype_component_id(id) {
self.archetype_component_access.add_read(id);
}
});
self.component_access.access.writes().for_each(|id| {
if let Some(id) = archetype.get_archetype_component_id(id) {
self.archetype_component_access.add_write(id);
}
});
}
/// Use this to transform a [`QueryState`] into a more generic [`QueryState`].
/// This can be useful for passing to another function that might take the more general form.
/// See [`Query::transmute_lens`](crate::system::Query::transmute_lens) for more details.
///
/// You should not call [`update_archetypes`](Self::update_archetypes) on the returned [`QueryState`] as the result will be unpredictable.
/// You might end up with a mix of archetypes that only matched the original query + archetypes that only match
/// the new [`QueryState`]. Most of the safe methods on [`QueryState`] call [`QueryState::update_archetypes`] internally, so this
/// best used through a [`Query`](crate::system::Query).
pub fn transmute<NewD: QueryData>(&self, world: &World) -> QueryState<NewD> {
self.transmute_filtered::<NewD, ()>(world)
}
/// Creates a new [`QueryState`] with the same underlying [`FilteredAccess`], matched tables and archetypes
/// as self but with a new type signature.
///
/// Panics if `NewD` or `NewF` require accesses that this query does not have.
pub fn transmute_filtered<NewD: QueryData, NewF: QueryFilter>(
&self,
world: &World,
) -> QueryState<NewD, NewF> {
let mut component_access = FilteredAccess::default();
let mut fetch_state = NewD::get_state(world).expect("Could not create fetch_state, Please initialize all referenced components before transmuting.");
let filter_state = NewF::get_state(world).expect("Could not create filter_state, Please initialize all referenced components before transmuting.");
NewD::set_access(&mut fetch_state, &self.component_access);
NewD::update_component_access(&fetch_state, &mut component_access);
let mut filter_component_access = FilteredAccess::default();
NewF::update_component_access(&filter_state, &mut filter_component_access);
component_access.extend(&filter_component_access);
assert!(component_access.is_subset(&self.component_access), "Transmuted state for {} attempts to access terms that are not allowed by original state {}.", std::any::type_name::<(NewD, NewF)>(), std::any::type_name::<(D, F)>() );
QueryState {
world_id: self.world_id,
archetype_generation: self.archetype_generation,
matched_table_ids: self.matched_table_ids.clone(),
matched_archetype_ids: self.matched_archetype_ids.clone(),
fetch_state,
filter_state,
component_access: self.component_access.clone(),
matched_tables: self.matched_tables.clone(),
matched_archetypes: self.matched_archetypes.clone(),
archetype_component_access: self.archetype_component_access.clone(),
#[cfg(feature = "trace")]
par_iter_span: bevy_utils::tracing::info_span!(
"par_for_each",
query = std::any::type_name::<NewD>(),
filter = std::any::type_name::<NewF>(),
),
}
}
/// Gets the query result for the given [`World`] and [`Entity`].
///
/// This can only be called for read-only queries, see [`Self::get_mut`] for write-queries.
#[inline]
pub fn get<'w>(
&mut self,
world: &'w World,
entity: Entity,
) -> Result<ROQueryItem<'w, D>, QueryEntityError> {
self.update_archetypes(world);
// SAFETY: query is read only
unsafe {
self.as_readonly().get_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
entity,
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Returns the read-only query results for the given array of [`Entity`].
///
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is
/// returned instead.
///
/// Note that the unlike [`QueryState::get_many_mut`], the entities passed in do not need to be unique.
///
/// # Examples
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::query::QueryEntityError;
///
/// #[derive(Component, PartialEq, Debug)]
/// struct A(usize);
///
/// let mut world = World::new();
/// let entity_vec: Vec<Entity> = (0..3).map(|i|world.spawn(A(i)).id()).collect();
/// let entities: [Entity; 3] = entity_vec.try_into().unwrap();
///
/// world.spawn(A(73));
///
/// let mut query_state = world.query::<&A>();
///
/// let component_values = query_state.get_many(&world, entities).unwrap();
///
/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
///
/// let wrong_entity = Entity::from_raw(365);
///
/// assert_eq!(query_state.get_many(&world, [wrong_entity]), Err(QueryEntityError::NoSuchEntity(wrong_entity)));
/// ```
#[inline]
pub fn get_many<'w, const N: usize>(
&mut self,
world: &'w World,
entities: [Entity; N],
) -> Result<[ROQueryItem<'w, D>; N], QueryEntityError> {
self.update_archetypes(world);
// SAFETY:
// - We have read-only access to the entire world.
// - `update_archetypes` validates that the `World` matches.
unsafe {
self.get_many_read_only_manual(
world.as_unsafe_world_cell_readonly(),
entities,
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Gets the query result for the given [`World`] and [`Entity`].
#[inline]
pub fn get_mut<'w>(
&mut self,
world: &'w mut World,
entity: Entity,
) -> Result<D::Item<'w>, QueryEntityError> {
self.update_archetypes(world);
let change_tick = world.change_tick();
let last_change_tick = world.last_change_tick();
// SAFETY: query has unique world access
unsafe {
self.get_unchecked_manual(
world.as_unsafe_world_cell(),
entity,
last_change_tick,
change_tick,
)
}
}
/// Returns the query results for the given array of [`Entity`].
///
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is
/// returned instead.
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::query::QueryEntityError;
///
/// #[derive(Component, PartialEq, Debug)]
/// struct A(usize);
///
/// let mut world = World::new();
///
/// let entities: Vec<Entity> = (0..3).map(|i|world.spawn(A(i)).id()).collect();
/// let entities: [Entity; 3] = entities.try_into().unwrap();
///
/// world.spawn(A(73));
///
/// let mut query_state = world.query::<&mut A>();
///
/// let mut mutable_component_values = query_state.get_many_mut(&mut world, entities).unwrap();
///
/// for mut a in &mut mutable_component_values {
/// a.0 += 5;
/// }
///
/// let component_values = query_state.get_many(&world, entities).unwrap();
///
/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
///
/// let wrong_entity = Entity::from_raw(57);
/// let invalid_entity = world.spawn_empty().id();
///
/// assert_eq!(query_state.get_many_mut(&mut world, [wrong_entity]).unwrap_err(), QueryEntityError::NoSuchEntity(wrong_entity));
/// assert_eq!(query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err(), QueryEntityError::QueryDoesNotMatch(invalid_entity));
/// assert_eq!(query_state.get_many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));
/// ```
#[inline]
pub fn get_many_mut<'w, const N: usize>(
&mut self,
world: &'w mut World,
entities: [Entity; N],
) -> Result<[D::Item<'w>; N], QueryEntityError> {
self.update_archetypes(world);
let change_tick = world.change_tick();
let last_change_tick = world.last_change_tick();
// SAFETY: method requires exclusive world access
// and world has been validated via update_archetypes
unsafe {
self.get_many_unchecked_manual(
world.as_unsafe_world_cell(),
entities,
last_change_tick,
change_tick,
)
}
}
/// Gets the query result for the given [`World`] and [`Entity`].
///
/// This method is slightly more efficient than [`QueryState::get`] in some situations, since
/// it does not update this instance's internal cache. This method will return an error if `entity`
/// belongs to an archetype that has not been cached.
///
/// To ensure that the cache is up to date, call [`QueryState::update_archetypes`] before this method.
/// The cache is also updated in [`QueryState::new`], `QueryState::get`, or any method with mutable
/// access to `self`.
///
/// This can only be called for read-only queries, see [`Self::get_mut`] for mutable queries.
#[inline]
pub fn get_manual<'w>(
&self,
world: &'w World,
entity: Entity,
) -> Result<ROQueryItem<'w, D>, QueryEntityError> {
self.validate_world(world.id());
// SAFETY: query is read only and world is validated
unsafe {
self.as_readonly().get_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
entity,
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Gets the query result for the given [`World`] and [`Entity`].
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
#[inline]
pub unsafe fn get_unchecked<'w>(
&mut self,
world: UnsafeWorldCell<'w>,
entity: Entity,
) -> Result<D::Item<'w>, QueryEntityError> {
self.update_archetypes_unsafe_world_cell(world);
self.get_unchecked_manual(world, entity, world.last_change_tick(), world.change_tick())
}
/// Gets the query result for the given [`World`] and [`Entity`], where the last change and
/// the current change tick are given.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
///
/// This must be called on the same `World` that the `Query` was generated from:
/// use `QueryState::validate_world` to verify this.
pub(crate) unsafe fn get_unchecked_manual<'w>(
&self,
world: UnsafeWorldCell<'w>,
entity: Entity,
last_run: Tick,
this_run: Tick,
) -> Result<D::Item<'w>, QueryEntityError> {
let location = world
.entities()
.get(entity)
.ok_or(QueryEntityError::NoSuchEntity(entity))?;
if !self
.matched_archetypes
.contains(location.archetype_id.index())
{
return Err(QueryEntityError::QueryDoesNotMatch(entity));
}
let archetype = world
.archetypes()
.get(location.archetype_id)
.debug_checked_unwrap();
let mut fetch = D::init_fetch(world, &self.fetch_state, last_run, this_run);
let mut filter = F::init_fetch(world, &self.filter_state, last_run, this_run);
let table = world
.storages()
.tables
.get(location.table_id)
.debug_checked_unwrap();
D::set_archetype(&mut fetch, &self.fetch_state, archetype, table);
F::set_archetype(&mut filter, &self.filter_state, archetype, table);
if F::filter_fetch(&mut filter, entity, location.table_row) {
Ok(D::fetch(&mut fetch, entity, location.table_row))
} else {
Err(QueryEntityError::QueryDoesNotMatch(entity))
}
}
/// Returns a shared reference to the component `T` of the given [`Entity`].
///
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
#[deprecated(
since = "0.13.0",
note = "Please use `get` and select for the exact component based on the structure of the exact query as required."
)]
#[allow(deprecated)]
#[inline]
pub(crate) fn get_component<'w, T: Component>(
&self,
world: UnsafeWorldCell<'w>,
entity: Entity,
) -> Result<&'w T, super::QueryComponentError> {
let entity_ref = world
.get_entity(entity)
.ok_or(super::QueryComponentError::NoSuchEntity)?;
let component_id = world
.components()
.get_id(TypeId::of::<T>())
.ok_or(super::QueryComponentError::MissingComponent)?;
let archetype_component = entity_ref
.archetype()
.get_archetype_component_id(component_id)
.ok_or(super::QueryComponentError::MissingComponent)?;
if self
.archetype_component_access
.has_read(archetype_component)
{
// SAFETY: `world` must have access to the component `T` for this entity,
// since it was registered in `self`'s archetype component access set.
unsafe { entity_ref.get::<T>() }.ok_or(super::QueryComponentError::MissingComponent)
} else {
Err(super::QueryComponentError::MissingReadAccess)
}
}
/// Returns a shared reference to the component `T` of the given [`Entity`].
///
/// # Panics
///
/// If given a nonexisting entity or mismatched component, this will panic.
#[deprecated(
since = "0.13.0",
note = "Please use `get` and select for the exact component based on the structure of the exact query as required."
)]
#[allow(deprecated)]
#[inline]
pub(crate) fn component<'w, T: Component>(
&self,
world: UnsafeWorldCell<'w>,
entity: Entity,
) -> &'w T {
match self.get_component(world, entity) {
Ok(component) => component,
Err(error) => {
panic!(
"Cannot get component `{:?}` from {entity:?}: {error}",
TypeId::of::<T>()
)
}
}
}
/// Returns a mutable reference to the component `T` of the given entity.
///
/// In case of a nonexisting entity or mismatched component, a [`QueryComponentError`] is returned instead.
///
/// # Safety
///
/// This function makes it possible to violate Rust's aliasing guarantees.
/// You must make sure this call does not result in multiple mutable references to the same component.
///
/// [`QueryComponentError`]: super::QueryComponentError
#[deprecated(
since = "0.13.0",
note = "Please use QueryState::get_unchecked_manual and select for the exact component based on the structure of the exact query as required."
)]
#[allow(deprecated)]
#[inline]
pub unsafe fn get_component_unchecked_mut<'w, T: Component>(
&self,
world: UnsafeWorldCell<'w>,
entity: Entity,
last_run: Tick,
this_run: Tick,
) -> Result<Mut<'w, T>, super::QueryComponentError> {
let entity_ref = world
.get_entity(entity)
.ok_or(super::QueryComponentError::NoSuchEntity)?;
let component_id = world
.components()
.get_id(TypeId::of::<T>())
.ok_or(super::QueryComponentError::MissingComponent)?;
let archetype_component = entity_ref
.archetype()
.get_archetype_component_id(component_id)
.ok_or(super::QueryComponentError::MissingComponent)?;
if self
.archetype_component_access
.has_write(archetype_component)
{
// SAFETY: It is the responsibility of the caller to ensure it is sound to get a
// mutable reference to this entity's component `T`.
let result = unsafe { entity_ref.get_mut_using_ticks::<T>(last_run, this_run) };
result.ok_or(super::QueryComponentError::MissingComponent)
} else {
Err(super::QueryComponentError::MissingWriteAccess)
}
}
/// Gets the read-only query results for the given [`World`] and array of [`Entity`], where the last change and
/// the current change tick are given.
///
/// # Safety
///
/// * `world` must have permission to read all of the components returned from this call.
/// No mutable references may coexist with any of the returned references.
/// * This must be called on the same `World` that the `Query` was generated from:
/// use `QueryState::validate_world` to verify this.
pub(crate) unsafe fn get_many_read_only_manual<'w, const N: usize>(
&self,
world: UnsafeWorldCell<'w>,
entities: [Entity; N],
last_run: Tick,
this_run: Tick,
) -> Result<[ROQueryItem<'w, D>; N], QueryEntityError> {
let mut values = [(); N].map(|_| MaybeUninit::uninit());
for (value, entity) in std::iter::zip(&mut values, entities) {
// SAFETY: fetch is read-only
// and world must be validated
let item = self
.as_readonly()
.get_unchecked_manual(world, entity, last_run, this_run)?;
*value = MaybeUninit::new(item);
}
// SAFETY: Each value has been fully initialized.
Ok(values.map(|x| x.assume_init()))
}
/// Gets the query results for the given [`World`] and array of [`Entity`], where the last change and
/// the current change tick are given.
///
/// # Safety
///
/// This does not check for unique access to subsets of the entity-component data.
/// To be safe, make sure mutable queries have unique access to the components they query.
///
/// This must be called on the same `World` that the `Query` was generated from:
/// use `QueryState::validate_world` to verify this.
pub(crate) unsafe fn get_many_unchecked_manual<'w, const N: usize>(
&self,
world: UnsafeWorldCell<'w>,
entities: [Entity; N],
last_run: Tick,
this_run: Tick,
) -> Result<[D::Item<'w>; N], QueryEntityError> {
// Verify that all entities are unique
for i in 0..N {
for j in 0..i {
if entities[i] == entities[j] {
return Err(QueryEntityError::AliasedMutability(entities[i]));
}
}
}
let mut values = [(); N].map(|_| MaybeUninit::uninit());
for (value, entity) in std::iter::zip(&mut values, entities) {
let item = self.get_unchecked_manual(world, entity, last_run, this_run)?;
*value = MaybeUninit::new(item);
}
// SAFETY: Each value has been fully initialized.
Ok(values.map(|x| x.assume_init()))
}
/// Returns an [`Iterator`] over the query results for the given [`World`].
///
/// This can only be called for read-only queries, see [`Self::iter_mut`] for write-queries.
#[inline]
pub fn iter<'w, 's>(&'s mut self, world: &'w World) -> QueryIter<'w, 's, D::ReadOnly, F> {
self.update_archetypes(world);
// SAFETY: query is read only
unsafe {
self.as_readonly().iter_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Returns an [`Iterator`] over the query results for the given [`World`].
#[inline]
pub fn iter_mut<'w, 's>(&'s mut self, world: &'w mut World) -> QueryIter<'w, 's, D, F> {
self.update_archetypes(world);
let change_tick = world.change_tick();
let last_change_tick = world.last_change_tick();
// SAFETY: query has unique world access
unsafe {
self.iter_unchecked_manual(world.as_unsafe_world_cell(), last_change_tick, change_tick)
}
}
/// Returns an [`Iterator`] over the query results for the given [`World`] without updating the query's archetypes.
/// Archetypes must be manually updated before by using [`Self::update_archetypes`].
///
/// This can only be called for read-only queries.
#[inline]
pub fn iter_manual<'w, 's>(&'s self, world: &'w World) -> QueryIter<'w, 's, D::ReadOnly, F> {
self.validate_world(world.id());
// SAFETY: query is read only and world is validated
unsafe {
self.as_readonly().iter_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Returns an [`Iterator`] over all possible combinations of `K` query results without repetition.
/// This can only be called for read-only queries.
///
/// A combination is an arrangement of a collection of items where order does not matter.
///
/// `K` is the number of items that make up each subset, and the number of items returned by the iterator.
/// `N` is the number of total entities output by query.
///
/// For example, given the list [1, 2, 3, 4], where `K` is 2, the combinations without repeats are
/// [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4].
/// And in this case, `N` would be defined as 4 since the size of the input list is 4.
///
/// For combinations of size `K` of query taking `N` inputs, you will get:
/// - if `K == N`: one combination of all query results
/// - if `K < N`: all possible `K`-sized combinations of query results, without repetition
/// - if `K > N`: empty set (no `K`-sized combinations exist)
///
/// The `iter_combinations` method does not guarantee order of iteration.
///
/// This can only be called for read-only queries, see [`Self::iter_combinations_mut`] for
/// write-queries.
#[inline]
pub fn iter_combinations<'w, 's, const K: usize>(
&'s mut self,
world: &'w World,
) -> QueryCombinationIter<'w, 's, D::ReadOnly, F, K> {
self.update_archetypes(world);
// SAFETY: query is read only
unsafe {
self.as_readonly().iter_combinations_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Returns an [`Iterator`] over all possible combinations of `K` query results without repetition.
///
/// A combination is an arrangement of a collection of items where order does not matter.
///
/// `K` is the number of items that make up each subset, and the number of items returned by the iterator.
/// `N` is the number of total entities output by query.
///
/// For example, given the list [1, 2, 3, 4], where `K` is 2, the combinations without repeats are
/// [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4].
/// And in this case, `N` would be defined as 4 since the size of the input list is 4.
///
/// For combinations of size `K` of query taking `N` inputs, you will get:
/// - if `K == N`: one combination of all query results
/// - if `K < N`: all possible `K`-sized combinations of query results, without repetition
/// - if `K > N`: empty set (no `K`-sized combinations exist)
///
/// The `iter_combinations_mut` method does not guarantee order of iteration.
#[inline]
pub fn iter_combinations_mut<'w, 's, const K: usize>(
&'s mut self,
world: &'w mut World,
) -> QueryCombinationIter<'w, 's, D, F, K> {
self.update_archetypes(world);
let change_tick = world.change_tick();
let last_change_tick = world.last_change_tick();
// SAFETY: query has unique world access
unsafe {
self.iter_combinations_unchecked_manual(
world.as_unsafe_world_cell(),
last_change_tick,
change_tick,
)
}
}
/// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
///
/// Items are returned in the order of the list of entities.
/// Entities that don't match the query are skipped.
///
/// # See also
///
/// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
#[inline]
pub fn iter_many<'w, 's, EntityList: IntoIterator>(
&'s mut self,
world: &'w World,
entities: EntityList,
) -> QueryManyIter<'w, 's, D::ReadOnly, F, EntityList::IntoIter>
where
EntityList::Item: Borrow<Entity>,
{
self.update_archetypes(world);
// SAFETY: query is read only
unsafe {
self.as_readonly().iter_many_unchecked_manual(
entities,
world.as_unsafe_world_cell_readonly(),
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
///
/// Items are returned in the order of the list of entities.
/// Entities that don't match the query are skipped.
///
/// If `world` archetypes changed since [`Self::update_archetypes`] was last called,
/// this will skip entities contained in new archetypes.
///
/// This can only be called for read-only queries.
///
/// # See also
///
/// - [`iter_many`](Self::iter_many) to update archetypes.
/// - [`iter_manual`](Self::iter_manual) to iterate over all query items.
#[inline]
pub fn iter_many_manual<'w, 's, EntityList: IntoIterator>(
&'s self,
world: &'w World,
entities: EntityList,
) -> QueryManyIter<'w, 's, D::ReadOnly, F, EntityList::IntoIter>
where
EntityList::Item: Borrow<Entity>,
{
self.validate_world(world.id());
// SAFETY: query is read only, world id is validated
unsafe {
self.as_readonly().iter_many_unchecked_manual(
entities,
world.as_unsafe_world_cell_readonly(),
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Returns an iterator over the query items generated from an [`Entity`] list.
///
/// Items are returned in the order of the list of entities.
/// Entities that don't match the query are skipped.
#[inline]
pub fn iter_many_mut<'w, 's, EntityList: IntoIterator>(
&'s mut self,
world: &'w mut World,
entities: EntityList,
) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter>
where
EntityList::Item: Borrow<Entity>,
{
self.update_archetypes(world);
let change_tick = world.change_tick();
let last_change_tick = world.last_change_tick();
// SAFETY: Query has unique world access.
unsafe {
self.iter_many_unchecked_manual(
entities,
world.as_unsafe_world_cell(),
last_change_tick,
change_tick,
)
}
}
/// Returns an [`Iterator`] over the query results for the given [`World`].
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
#[inline]
pub unsafe fn iter_unchecked<'w, 's>(
&'s mut self,
world: UnsafeWorldCell<'w>,
) -> QueryIter<'w, 's, D, F> {
self.update_archetypes_unsafe_world_cell(world);
self.iter_unchecked_manual(world, world.last_change_tick(), world.change_tick())
}
/// Returns an [`Iterator`] over all possible combinations of `K` query results for the
/// given [`World`] without repetition.
/// This can only be called for read-only queries.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
#[inline]
pub unsafe fn iter_combinations_unchecked<'w, 's, const K: usize>(
&'s mut self,
world: UnsafeWorldCell<'w>,
) -> QueryCombinationIter<'w, 's, D, F, K> {
self.update_archetypes_unsafe_world_cell(world);
self.iter_combinations_unchecked_manual(
world,
world.last_change_tick(),
world.change_tick(),
)
}
/// Returns an [`Iterator`] for the given [`World`], where the last change and
/// the current change tick are given.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
/// This does not validate that `world.id()` matches `self.world_id`. Calling this on a `world`
/// with a mismatched [`WorldId`] is unsound.
#[inline]
pub(crate) unsafe fn iter_unchecked_manual<'w, 's>(
&'s self,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> QueryIter<'w, 's, D, F> {
QueryIter::new(world, self, last_run, this_run)
}
/// Returns an [`Iterator`] for the given [`World`] and list of [`Entity`]'s, where the last change and
/// the current change tick are given.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
/// This does not check for entity uniqueness
/// This does not validate that `world.id()` matches `self.world_id`. Calling this on a `world`
/// with a mismatched [`WorldId`] is unsound.
#[inline]
pub(crate) unsafe fn iter_many_unchecked_manual<'w, 's, EntityList: IntoIterator>(
&'s self,
entities: EntityList,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter>
where
EntityList::Item: Borrow<Entity>,
{
QueryManyIter::new(world, self, entities, last_run, this_run)
}
/// Returns an [`Iterator`] over all possible combinations of `K` query results for the
/// given [`World`] without repetition.
/// This can only be called for read-only queries.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
/// This does not validate that `world.id()` matches `self.world_id`. Calling this on a `world`
/// with a mismatched [`WorldId`] is unsound.
#[inline]
pub(crate) unsafe fn iter_combinations_unchecked_manual<'w, 's, const K: usize>(
&'s self,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> QueryCombinationIter<'w, 's, D, F, K> {
QueryCombinationIter::new(world, self, last_run, this_run)
}
/// Runs `func` on each query result for the given [`World`]. This is faster than the equivalent
/// `iter()` method, but cannot be chained like a normal [`Iterator`].
///
/// This can only be called for read-only queries, see [`Self::for_each_mut`] for write-queries.
///
/// Shorthand for `query.iter(world).for_each(..)`.
#[inline]
#[deprecated(
since = "0.13.0",
note = "QueryState::for_each was not idiomatic Rust and has been moved to query.iter().for_each()"
)]
pub fn for_each<'w, FN: FnMut(ROQueryItem<'w, D>)>(&mut self, world: &'w World, func: FN) {
self.iter(world).for_each(func);
}
/// Runs `func` on each query result for the given [`World`]. This is faster than the equivalent
/// `iter_mut()` method, but cannot be chained like a normal [`Iterator`].
///
/// Shorthand for `query.iter_mut(world).for_each(..)`.
#[inline]
#[deprecated(
since = "0.13.0",
note = "QueryState::for_each_mut was not idiomatic Rust and has been moved to query.iter_mut().for_each()"
)]
pub fn for_each_mut<'w, FN: FnMut(D::Item<'w>)>(&mut self, world: &'w mut World, func: FN) {
self.iter_mut(world).for_each(func);
}
/// Runs `func` on each query result for the given [`World`]. This is faster than the equivalent
/// `iter()` method, but cannot be chained like a normal [`Iterator`].
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
#[inline]
#[deprecated(
since = "0.13.0",
note = "QueryState::for_each_unchecked was not idiomatic Rust and has been moved to query.iter_unchecked_manual().for_each()"
)]
pub unsafe fn for_each_unchecked<'w, FN: FnMut(D::Item<'w>)>(
&mut self,
world: UnsafeWorldCell<'w>,
func: FN,
) {
self.update_archetypes_unsafe_world_cell(world);
self.iter_unchecked_manual(world, world.last_change_tick(), world.change_tick())
.for_each(func);
}
/// Returns a parallel iterator over the query results for the given [`World`].
///
/// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.
///
/// Note that you must use the `for_each` method to iterate over the
/// results, see [`par_iter_mut`] for an example.
///
/// [`par_iter_mut`]: Self::par_iter_mut
#[inline]
pub fn par_iter<'w, 's>(
&'s mut self,
world: &'w World,
) -> QueryParIter<'w, 's, D::ReadOnly, F> {
self.update_archetypes(world);
QueryParIter {
world: world.as_unsafe_world_cell_readonly(),
state: self.as_readonly(),
last_run: world.last_change_tick(),
this_run: world.read_change_tick(),
batching_strategy: BatchingStrategy::new(),
}
}
/// Returns a parallel iterator over the query results for the given [`World`].
///
/// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.
///
/// # Examples
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::query::QueryEntityError;
///
/// #[derive(Component, PartialEq, Debug)]
/// struct A(usize);
///
/// # bevy_tasks::ComputeTaskPool::get_or_init(|| bevy_tasks::TaskPool::new());
///
/// let mut world = World::new();
///
/// # let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
/// # let entities: [Entity; 3] = entities.try_into().unwrap();
///
/// let mut query_state = world.query::<&mut A>();
///
/// query_state.par_iter_mut(&mut world).for_each(|mut a| {
/// a.0 += 5;
/// });
///
/// # let component_values = query_state.get_many(&world, entities).unwrap();
///
/// # assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
///
/// # let wrong_entity = Entity::from_raw(57);
/// # let invalid_entity = world.spawn_empty().id();
///
/// # assert_eq!(query_state.get_many_mut(&mut world, [wrong_entity]).unwrap_err(), QueryEntityError::NoSuchEntity(wrong_entity));
/// # assert_eq!(query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err(), QueryEntityError::QueryDoesNotMatch(invalid_entity));
/// # assert_eq!(query_state.get_many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));
/// ```
///
/// # Panics
/// The [`ComputeTaskPool`] is not initialized. If using this from a query that is being
/// initialized and run from the ECS scheduler, this should never panic.
///
/// [`par_iter`]: Self::par_iter
/// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
#[inline]
pub fn par_iter_mut<'w, 's>(&'s mut self, world: &'w mut World) -> QueryParIter<'w, 's, D, F> {
self.update_archetypes(world);
let this_run = world.change_tick();
let last_run = world.last_change_tick();
QueryParIter {
world: world.as_unsafe_world_cell(),
state: self,
last_run,
this_run,
batching_strategy: BatchingStrategy::new(),
}
}
/// Runs `func` on each query result in parallel for the given [`World`], where the last change and
/// the current change tick are given. This is faster than the equivalent
/// `iter()` method, but cannot be chained like a normal [`Iterator`].
///
/// # Panics
/// The [`ComputeTaskPool`] is not initialized. If using this from a query that is being
/// initialized and run from the ECS scheduler, this should never panic.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
/// This does not validate that `world.id()` matches `self.world_id`. Calling this on a `world`
/// with a mismatched [`WorldId`] is unsound.
///
/// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
#[cfg(all(not(target = "wasm32"), feature = "multi-threaded"))]
pub(crate) unsafe fn par_for_each_unchecked_manual<
'w,
FN: Fn(D::Item<'w>) + Send + Sync + Clone,
>(
&self,
world: UnsafeWorldCell<'w>,
batch_size: usize,
func: FN,
last_run: Tick,
this_run: Tick,
) {
// NOTE: If you are changing query iteration code, remember to update the following places, where relevant:
// QueryIter, QueryIterationCursor, QueryManyIter, QueryCombinationIter, QueryState::for_each_unchecked_manual, QueryState::par_for_each_unchecked_manual
bevy_tasks::ComputeTaskPool::get().scope(|scope| {
if D::IS_DENSE && F::IS_DENSE {
// SAFETY: We only access table data that has been registered in `self.archetype_component_access`.
let tables = &world.storages().tables;
for table_id in &self.matched_table_ids {
let table = &tables[*table_id];
if table.is_empty() {
continue;
}
let mut offset = 0;
while offset < table.entity_count() {
let mut func = func.clone();
let len = batch_size.min(table.entity_count() - offset);
scope.spawn(async move {
#[cfg(feature = "trace")]
let _span = self.par_iter_span.enter();
let table = &world
.storages()
.tables
.get(*table_id)
.debug_checked_unwrap();
let batch = offset..offset + len;
self.iter_unchecked_manual(world, last_run, this_run)
.for_each_in_table_range(&mut func, table, batch);
});
offset += batch_size;
}
}
} else {
let archetypes = world.archetypes();
for archetype_id in &self.matched_archetype_ids {
let mut offset = 0;
let archetype = &archetypes[*archetype_id];
if archetype.is_empty() {
continue;
}
while offset < archetype.len() {
let mut func = func.clone();
let len = batch_size.min(archetype.len() - offset);
scope.spawn(async move {
#[cfg(feature = "trace")]
let _span = self.par_iter_span.enter();
let archetype =
world.archetypes().get(*archetype_id).debug_checked_unwrap();
let batch = offset..offset + len;
self.iter_unchecked_manual(world, last_run, this_run)
.for_each_in_archetype_range(&mut func, archetype, batch);
});
offset += batch_size;
}
}
}
});
}
/// Returns a single immutable query result when there is exactly one entity matching
/// the query.
///
/// This can only be called for read-only queries,
/// see [`single_mut`](Self::single_mut) for write-queries.
///
/// # Panics
///
/// Panics if the number of query results is not exactly one. Use
/// [`get_single`](Self::get_single) to return a `Result` instead of panicking.
#[track_caller]
#[inline]
pub fn single<'w>(&mut self, world: &'w World) -> ROQueryItem<'w, D> {
match self.get_single(world) {
Ok(items) => items,
Err(error) => panic!("Cannot get single mutable query result: {error}"),
}
}
/// Returns a single immutable query result when there is exactly one entity matching
/// the query.
///
/// This can only be called for read-only queries,
/// see [`get_single_mut`](Self::get_single_mut) for write-queries.
///
/// If the number of query results is not exactly one, a [`QuerySingleError`] is returned
/// instead.
#[inline]
pub fn get_single<'w>(
&mut self,
world: &'w World,
) -> Result<ROQueryItem<'w, D>, QuerySingleError> {
self.update_archetypes(world);
// SAFETY: query is read only
unsafe {
self.as_readonly().get_single_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
world.last_change_tick(),
world.read_change_tick(),
)
}
}
/// Returns a single mutable query result when there is exactly one entity matching
/// the query.
///
/// # Panics
///
/// Panics if the number of query results is not exactly one. Use
/// [`get_single_mut`](Self::get_single_mut) to return a `Result` instead of panicking.
#[track_caller]
#[inline]
pub fn single_mut<'w>(&mut self, world: &'w mut World) -> D::Item<'w> {
// SAFETY: query has unique world access
match self.get_single_mut(world) {
Ok(items) => items,
Err(error) => panic!("Cannot get single query result: {error}"),
}
}
/// Returns a single mutable query result when there is exactly one entity matching
/// the query.
///
/// If the number of query results is not exactly one, a [`QuerySingleError`] is returned
/// instead.
#[inline]
pub fn get_single_mut<'w>(
&mut self,
world: &'w mut World,
) -> Result<D::Item<'w>, QuerySingleError> {
self.update_archetypes(world);
let change_tick = world.change_tick();
let last_change_tick = world.last_change_tick();
// SAFETY: query has unique world access
unsafe {
self.get_single_unchecked_manual(
world.as_unsafe_world_cell(),
last_change_tick,
change_tick,
)
}
}
/// Returns a query result when there is exactly one entity matching the query.
///
/// If the number of query results is not exactly one, a [`QuerySingleError`] is returned
/// instead.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
#[inline]
pub unsafe fn get_single_unchecked<'w>(
&mut self,
world: UnsafeWorldCell<'w>,
) -> Result<D::Item<'w>, QuerySingleError> {
self.update_archetypes_unsafe_world_cell(world);
self.get_single_unchecked_manual(world, world.last_change_tick(), world.change_tick())
}
/// Returns a query result when there is exactly one entity matching the query,
/// where the last change and the current change tick are given.
///
/// If the number of query results is not exactly one, a [`QuerySingleError`] is returned
/// instead.
///
/// # Safety
///
/// This does not check for mutable query correctness. To be safe, make sure mutable queries
/// have unique access to the components they query.
#[inline]
pub unsafe fn get_single_unchecked_manual<'w>(
&self,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> Result<D::Item<'w>, QuerySingleError> {
let mut query = self.iter_unchecked_manual(world, last_run, this_run);
let first = query.next();
let extra = query.next().is_some();
match (first, extra) {
(Some(r), false) => Ok(r),
(None, _) => Err(QuerySingleError::NoEntities(std::any::type_name::<Self>())),
(Some(_), _) => Err(QuerySingleError::MultipleEntities(std::any::type_name::<
Self,
>())),
}
}
}
impl<D: QueryData, F: QueryFilter> From<QueryBuilder<'_, D, F>> for QueryState<D, F> {
fn from(mut value: QueryBuilder<D, F>) -> Self {
QueryState::from_builder(&mut value)
}
}
#[cfg(test)]
mod tests {
use crate as bevy_ecs;
use crate::world::FilteredEntityRef;
use crate::{component::Component, prelude::*, query::QueryEntityError};
#[test]
fn get_many_unchecked_manual_uniqueness() {
let mut world = World::new();
let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();
let query_state = world.query::<Entity>();
// These don't matter for the test
let last_change_tick = world.last_change_tick();
let change_tick = world.change_tick();
// It's best to test get_many_unchecked_manual directly,
// as it is shared and unsafe
// We don't care about aliased mutability for the read-only equivalent
// SAFETY: Query does not access world data.
assert!(unsafe {
query_state
.get_many_unchecked_manual::<10>(
world.as_unsafe_world_cell_readonly(),
entities.clone().try_into().unwrap(),
last_change_tick,
change_tick,
)
.is_ok()
});
assert_eq!(
// SAFETY: Query does not access world data.
unsafe {
query_state
.get_many_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
[entities[0], entities[0]],
last_change_tick,
change_tick,
)
.unwrap_err()
},
QueryEntityError::AliasedMutability(entities[0])
);
assert_eq!(
// SAFETY: Query does not access world data.
unsafe {
query_state
.get_many_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
[entities[0], entities[1], entities[0]],
last_change_tick,
change_tick,
)
.unwrap_err()
},
QueryEntityError::AliasedMutability(entities[0])
);
assert_eq!(
// SAFETY: Query does not access world data.
unsafe {
query_state
.get_many_unchecked_manual(
world.as_unsafe_world_cell_readonly(),
[entities[9], entities[9]],
last_change_tick,
change_tick,
)
.unwrap_err()
},
QueryEntityError::AliasedMutability(entities[9])
);
}
#[test]
#[should_panic]
fn right_world_get() {
let mut world_1 = World::new();
let world_2 = World::new();
let mut query_state = world_1.query::<Entity>();
let _panics = query_state.get(&world_2, Entity::from_raw(0));
}
#[test]
#[should_panic]
fn right_world_get_many() {
let mut world_1 = World::new();
let world_2 = World::new();
let mut query_state = world_1.query::<Entity>();
let _panics = query_state.get_many(&world_2, []);
}
#[test]
#[should_panic]
fn right_world_get_many_mut() {
let mut world_1 = World::new();
let mut world_2 = World::new();
let mut query_state = world_1.query::<Entity>();
let _panics = query_state.get_many_mut(&mut world_2, []);
}
#[derive(Component, PartialEq, Debug)]
struct A(usize);
#[derive(Component, PartialEq, Debug)]
struct B(usize);
#[derive(Component, PartialEq, Debug)]
struct C(usize);
#[test]
fn can_transmute_to_more_general() {
let mut world = World::new();
world.spawn((A(1), B(0)));
let query_state = world.query::<(&A, &B)>();
let mut new_query_state = query_state.transmute::<&A>(&world);
assert_eq!(new_query_state.iter(&world).len(), 1);
let a = new_query_state.single(&world);
assert_eq!(a.0, 1);
}
#[test]
fn cannot_get_data_not_in_original_query() {
let mut world = World::new();
world.spawn((A(0), B(0)));
world.spawn((A(1), B(0), C(0)));
let query_state = world.query_filtered::<(&A, &B), Without<C>>();
let mut new_query_state = query_state.transmute::<&A>(&world);
// even though we change the query to not have Without<C>, we do not get the component with C.
let a = new_query_state.single(&world);
assert_eq!(a.0, 0);
}
#[test]
fn can_transmute_empty_tuple() {
let mut world = World::new();
world.init_component::<A>();
let entity = world.spawn(A(10)).id();
let q = world.query::<()>();
let mut q = q.transmute::<Entity>(&world);
assert_eq!(q.single(&world), entity);
}
#[test]
fn can_transmute_immut_fetch() {
let mut world = World::new();
world.spawn(A(10));
let q = world.query::<&A>();
let mut new_q = q.transmute::<Ref<A>>(&world);
assert!(new_q.single(&world).is_added());
let q = world.query::<Ref<A>>();
let _ = q.transmute::<&A>(&world);
}
#[test]
fn can_transmute_mut_fetch() {
let mut world = World::new();
world.spawn(A(0));
let q = world.query::<&mut A>();
let _ = q.transmute::<Ref<A>>(&world);
let _ = q.transmute::<&A>(&world);
}
#[test]
fn can_transmute_entity_mut() {
let mut world = World::new();
world.spawn(A(0));
let q: QueryState<EntityMut<'_>> = world.query::<EntityMut>();
let _ = q.transmute::<EntityRef>(&world);
}
#[test]
fn can_generalize_with_option() {
let mut world = World::new();
world.spawn((A(0), B(0)));
let query_state = world.query::<(Option<&A>, &B)>();
let _ = query_state.transmute::<Option<&A>>(&world);
let _ = query_state.transmute::<&B>(&world);
}
#[test]
#[should_panic(
expected = "Transmuted state for ((&bevy_ecs::query::state::tests::A, &bevy_ecs::query::state::tests::B), ()) attempts to access terms that are not allowed by original state (&bevy_ecs::query::state::tests::A, ())."
)]
fn cannot_transmute_to_include_data_not_in_original_query() {
let mut world = World::new();
world.init_component::<A>();
world.init_component::<B>();
world.spawn(A(0));
let query_state = world.query::<&A>();
let mut _new_query_state = query_state.transmute::<(&A, &B)>(&world);
}
#[test]
#[should_panic(
expected = "Transmuted state for (&mut bevy_ecs::query::state::tests::A, ()) attempts to access terms that are not allowed by original state (&bevy_ecs::query::state::tests::A, ())."
)]
fn cannot_transmute_immut_to_mut() {
let mut world = World::new();
world.spawn(A(0));
let query_state = world.query::<&A>();
let mut _new_query_state = query_state.transmute::<&mut A>(&world);
}
#[test]
#[should_panic(
expected = "Transmuted state for (&bevy_ecs::query::state::tests::A, ()) attempts to access terms that are not allowed by original state (core::option::Option<&bevy_ecs::query::state::tests::A>, ())."
)]
fn cannot_transmute_option_to_immut() {
let mut world = World::new();
world.spawn(C(0));
let query_state = world.query::<Option<&A>>();
let mut new_query_state = query_state.transmute::<&A>(&world);
let x = new_query_state.single(&world);
assert_eq!(x.0, 1234);
}
#[test]
#[should_panic(
expected = "Transmuted state for (&bevy_ecs::query::state::tests::A, ()) attempts to access terms that are not allowed by original state (bevy_ecs::world::entity_ref::EntityRef, ())."
)]
fn cannot_transmute_entity_ref() {
let mut world = World::new();
world.init_component::<A>();
let q = world.query::<EntityRef>();
let _ = q.transmute::<&A>(&world);
}
#[test]
fn can_transmute_filtered_entity() {
let mut world = World::new();
let entity = world.spawn((A(0), B(1))).id();
let query =
QueryState::<(Entity, &A, &B)>::new(&mut world).transmute::<FilteredEntityRef>(&world);
let mut query = query;
// Our result is completely untyped
let entity_ref = query.single(&world);
assert_eq!(entity, entity_ref.id());
assert_eq!(0, entity_ref.get::<A>().unwrap().0);
assert_eq!(1, entity_ref.get::<B>().unwrap().0);
}
#[test]
fn can_transmute_added() {
let mut world = World::new();
let entity_a = world.spawn(A(0)).id();
let mut query = QueryState::<(Entity, &A, Has<B>)>::new(&mut world)
.transmute_filtered::<(Entity, Has<B>), Added<A>>(&world);
assert_eq!((entity_a, false), query.single(&world));
world.clear_trackers();
let entity_b = world.spawn((A(0), B(0))).id();
assert_eq!((entity_b, true), query.single(&world));
world.clear_trackers();
assert!(query.get_single(&world).is_err());
}
#[test]
fn can_transmute_changed() {
let mut world = World::new();
let entity_a = world.spawn(A(0)).id();
let mut detection_query = QueryState::<(Entity, &A)>::new(&mut world)
.transmute_filtered::<Entity, Changed<A>>(&world);
let mut change_query = QueryState::<&mut A>::new(&mut world);
assert_eq!(entity_a, detection_query.single(&world));
world.clear_trackers();
assert!(detection_query.get_single(&world).is_err());
change_query.single_mut(&mut world).0 = 1;
assert_eq!(entity_a, detection_query.single(&world));
}
}