Commit graph

1080 commits

Author SHA1 Message Date
Ixentus
80bd378aa0 Fix tiny state docs inconsistency (#1764)
@TheRawMeatball
2021-03-26 18:30:28 +00:00
Carter Anderson
7a511394ac Add register_component to AppBuilder and improve error message (#1750) 2021-03-26 04:15:07 +00:00
Alexander Sepity
500d7469e7 Fixed criteria-less systems being re-ran unnecessarily (#1754)
Fixes #1753.

The problem was introduced while reworking the logic around stages' own criteria. Before #1675 they used to be stored and processed inline with the systems' criteria, and systems without criteria used that of their stage. After, criteria-less systems think they should run, always. This PR more or less restores previous behavior; a less cludge solution can wait until after 0.5 - ideally, until stageless.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-26 00:31:58 +00:00
Carter Anderson
bf053218bf Disable frustum culling and add warning (#1761)
Frustum culling has some pretty major gaps right now (such as not supporting sprite transform scaling and not taking into account projections). It should be disabled by default until it provides a solid experience across all bevy use cases.
2021-03-25 22:05:28 +00:00
Jakob Hellermann
ad60046982 fix clippy lints (#1756) 2021-03-25 20:48:18 +00:00
Carter Anderson
1d7196da4f Add state app builder docs (#1746)
This is intended to help protect users against #1671. It doesn't resolve the issue, but I think its a good stop-gap solution for 0.5. A "full" fix would be very involved (and maybe not worth the added complexity).
2021-03-25 06:12:14 +00:00
Carter Anderson
80961d1bd0 Fix sparse insert (#1748)
Removing the checks on this line https://github.com/bevyengine/bevy/blob/main/crates/bevy_sprite/src/frustum_culling.rs#L64 and running the "many_sprites" example revealed two corner case bugs in bevy_ecs. The first, a simple and honest missed line introduced in #1471. The other, an insidious monster that has been there since the ECS v2 rewrite, just waiting for the time to strike:

1. #1471 accidentally removed the "insert" line for sparse set components with the "mutated" bundle state. Re-adding it fixes the problem. I did a slight refactor here to make the implementation simpler and remove a branch.
2. The other issue is nastier. ECS v2 added an "archetype graph". When determining what components were added/mutated during an archetype change, we read the FromBundle edge (which encodes this state) on the "new" archetype.  The problem is that unlike "add edges" which are guaranteed to be unique for a given ("graph node", "bundle id") pair, FromBundle edges are not necessarily unique:

```rust
// OLD_ARCHETYPE -> NEW_ARCHETYPE

// [] -> [usize]
e.insert(2usize);
// [usize] -> [usize, i32]
e.insert(1i32);
// [usize, i32] -> [usize, i32]
e.insert(1i32);
// [usize, i32] -> [usize]
e.remove::<i32>();
// [usize] -> [usize, i32]
e.insert(1i32);
```

Note that the second `e.insert(1i32)` command has a different "archetype graph edge" than the first, but they both lead to the same "new archetype".

The fix here is simple: just remove FromBundle edges because they are broken and store the information in the "add edges", which are guaranteed to be unique.

FromBundle edges were added to cut down on the number of archetype accesses / make the archetype access patterns nicer. But benching this change resulted in no significant perf changes and the addition of get_2_mut() for archetypes resolves the access pattern issue.
2021-03-25 05:56:00 +00:00
TheRawMeatball
78edec2e45 Change State::*_next to *_replace, add proper next (#1676)
In the current impl, next clears out the entire stack and replaces it with a new state. This PR moves this functionality into a replace method, and changes the behavior of next to only change the top state.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-25 03:28:40 +00:00
Aaron Winter
b65ec82d46 Frustum Culling (for Sprites) (#1492)
This PR adds two systems to the sprite module that culls Sprites and AtlasSprites that are not within the camera's view.
This is achieved by removing / adding a new  `Viewable` Component dynamically.

Some of the render queries now use a `With<Viewable>` filter to only process the sprites that are actually on screen, which improves performance drastically for scene swith a large amount of sprites off-screen.

https://streamable.com/vvzh2u

This scene shows a map with a 320x320 tiles, with a grid size of 64p.
This is exactly 102400 Sprites in the entire scene.

Without this PR, this scene runs with 1 to 4 FPS.

With this PR..
.. at 720p, there are around 600 visible sprites and runs at ~215 FPS
.. at 1440p there are around 2000 visible sprites and runs at ~135 FPS

The Systems this PR adds take around 1.2ms (with 100K+ sprites in the scene)

Note:
This is only implemented for Sprites and AtlasTextureSprites.
There is no culling for 3D in this PR.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-24 21:29:53 +00:00
Alexander Sepity
d3e020a1e7 System sets and run criteria v2 (#1675)
I'm opening this prematurely; consider this an RFC that predates RFCs and therefore not super-RFC-like.

This PR does two "big" things: decouple run criteria from system sets, reimagine system sets as weapons of mass system description.

### What it lets us do:

* Reuse run criteria within a stage.
* Pipe output of one run criteria as input to another.
* Assign labels, dependencies, run criteria, and ambiguity sets to many systems at the same time.

### Things already done:
* Decoupled run criteria from system sets.
* Mass system description superpowers to `SystemSet`.
* Implemented `RunCriteriaDescriptor`.
* Removed `VirtualSystemSet`.
* Centralized all run criteria of `SystemStage`.
* Extended system descriptors with per-system run criteria.
* `.before()` and `.after()` for run criteria.
* Explicit order between state driver and related run criteria. Fixes #1672.
* Opt-in run criteria deduplication; default behavior is to panic.
* Labels (not exposed) for state run criteria; state run criteria are deduplicated.

### API issues that need discussion:

* [`FixedTimestep::step(1.0).label("my label")`](eaccf857cd/crates/bevy_ecs/src/schedule/run_criteria.rs (L120-L122)) and [`FixedTimestep::step(1.0).with_label("my label")`](eaccf857cd/crates/bevy_core/src/time/fixed_timestep.rs (L86-L89)) are both valid but do very different things.

---

I will try to maintain this post up-to-date as things change. Do check the diffs in "edited" thingy from time to time.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-24 20:11:55 +00:00
TheRawMeatball
10ef750899 Expose resource change detection on World (#1715) 2021-03-24 01:00:13 +00:00
François
248ec1ed95 update rectangle-pack to latest release (#1742)
update to release of rectangle-pack  0.3.0 after #1741
2021-03-24 00:21:37 +00:00
François
9ae56e8604 update for rectangle-pack 0.2.1 (fix CI) (#1741)
crate `rectangle-pack` just published version 0.2.1 with a breaking change: c9ecd58f7a

I also opened an issue on their repo so that they are aware of it: https://github.com/chinedufn/rectangle-pack/issues/3
2021-03-23 19:07:33 +00:00
TheRawMeatball
47004dfcb4 Added remove_non_send to World (#1716)
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-23 00:41:54 +00:00
Carter Anderson
81b53d15d4 Make Commands and World apis consistent (#1703)
Resolves #1253 #1562

This makes the Commands apis consistent with World apis. This moves to a "type state" pattern (like World) where the "current entity" is stored in an `EntityCommands` builder.

In general this tends to cuts down on indentation and line count. It comes at the cost of needing to type `commands` more and adding more semicolons to terminate expressions.

I also added `spawn_bundle` to Commands because this is a common enough operation that I think its worth providing a shorthand.
2021-03-23 00:23:40 +00:00
Jakob Hellermann
2dd2e5e9fe make ComponentTicks::set_changed public (#1711)
fixes #1710
2021-03-22 18:49:26 +00:00
Jonas Matser
cd8025d0a7 Remove remaining camerapos bindings (#1708)
Fixes #1706

@JeanMertz already solved it. I just ran all examples and tests.
2021-03-22 18:10:35 +00:00
dependabot[bot]
42924d2227 Update fixedbitset requirement from 0.3 to 0.4 (#1726)
Updates the requirements on [fixedbitset](https://github.com/bluss/fixedbitset) to permit the latest version.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a href="https://github.com/bluss/fixedbitset/commits">compare view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)


</details>
2021-03-22 07:06:04 +00:00
Jonas Matser
45b2db7070 Rebase of existing PBR work (#1554)
This is a rebase of StarArawns PBR work from #261 with IngmarBitters work from #1160 cherry-picked on top.

I had to make a few minor changes to make some intermediate commits compile and the end result is not yet 100% what I expected, so there's a bit more work to do.

Co-authored-by: John Mitchell <toasterthegamer@gmail.com>
Co-authored-by: Ingmar Bitter <ingmar.bitter@gmail.com>
2021-03-20 03:22:33 +00:00
Carter Anderson
b6be8a5314 Fix table reserve logic (#1698)
Fixes #1692
Alternative to #1696

This ensures that the capacity actually grows in increments of grow_amount, and also ensures that Table capacity is always <= column and entity vec capacity.

Debug logs that describe the new logic (running the example in #1692)
[out.txt](https://github.com/bevyengine/bevy/files/6173808/out.txt)
2021-03-19 23:32:31 +00:00
MinerSebas
c78b76bba8 Provide better size_hint for QueryIter (#1697)
This PR overrides the default size_hint for QueryIter.
This is mainly done to provide inline documentation of Issue #1686.
2021-03-19 20:52:44 +00:00
Carter Anderson
dd4a196329 Flexible camera bindings (#1689)
Alternative to #1203 and #1611

Camera bindings have historically been "hacked in". They were _required_ in all shaders and only supported a single Mat4. PBR (#1554) requires the CameraView matrix, but adding this using the "hacked" method forced users to either include all possible camera data in a single binding (#1203) or include all possible bindings (#1611).

This approach instead assigns each "active camera" its own RenderResourceBindings, which are populated by CameraNode. The PassNode then retrieves (and initializes) the relevant bind groups for all render pipelines used by visible entities. 

* Enables any number of camera bindings , including zero (with any set or binding number ... set 0 should still be used to avoid rebinds).
* Renames Camera binding to CameraViewProj
* Adds CameraView binding
2021-03-19 20:36:40 +00:00
Alice Cecile
6121e5f933 Reliable change detection (#1471)
# Problem Definition

The current change tracking (via flags for both components and resources) fails to detect changes made by systems that are scheduled to run earlier in the frame than they are.

This issue is discussed at length in [#68](https://github.com/bevyengine/bevy/issues/68) and [#54](https://github.com/bevyengine/bevy/issues/54).

This is very much a draft PR, and contributions are welcome and needed.

# Criteria
1. Each change is detected at least once, no matter the ordering.
2. Each change is detected at most once, no matter the ordering.
3. Changes should be detected the same frame that they are made.
4. Competitive ergonomics. Ideally does not require opting-in.
5. Low CPU overhead of computation.
6. Memory efficient. This must not increase over time, except where the number of entities / resources does.
7. Changes should not be lost for systems that don't run.
8. A frame needs to act as a pure function. Given the same set of entities / components it needs to produce the same end state without side-effects.

**Exact** change-tracking proposals satisfy criteria 1 and 2.
**Conservative** change-tracking proposals satisfy criteria 1 but not 2.
**Flaky** change tracking proposals satisfy criteria 2 but not 1.

# Code Base Navigation

There are three types of flags: 
- `Added`: A piece of data was added to an entity / `Resources`.
- `Mutated`: A piece of data was able to be modified, because its `DerefMut` was accessed
- `Changed`: The bitwise OR of `Added` and `Changed`

The special behavior of `ChangedRes`, with respect to the scheduler is being removed in [#1313](https://github.com/bevyengine/bevy/pull/1313) and does not need to be reproduced.

`ChangedRes` and friends can be found in "bevy_ecs/core/resources/resource_query.rs".

The `Flags` trait for Components can be found in "bevy_ecs/core/query.rs".

`ComponentFlags` are stored in "bevy_ecs/core/archetypes.rs", defined on line 446.

# Proposals

**Proposal 5 was selected for implementation.**

## Proposal 0: No Change Detection

The baseline, where computations are performed on everything regardless of whether it changed.

**Type:** Conservative

**Pros:**
- already implemented
- will never miss events
- no overhead

**Cons:**
- tons of repeated work
- doesn't allow users to avoid repeating work (or monitoring for other changes)

## Proposal 1: Earlier-This-Tick Change Detection

The current approach as of Bevy 0.4. Flags are set, and then flushed at the end of each frame.

**Type:** Flaky

**Pros:**
- already implemented
- simple to understand
- low memory overhead (2 bits per component)
- low time overhead (clear every flag once per frame)

**Cons:**
- misses systems based on ordering
- systems that don't run every frame miss changes
- duplicates detection when looping
- can lead to unresolvable circular dependencies

## Proposal 2: Two-Tick Change Detection

Flags persist for two frames, using a double-buffer system identical to that used in events.

A change is observed if it is found in either the current frame's list of changes or the previous frame's.

**Type:** Conservative

**Pros:**
- easy to understand
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)

**Cons:**
- can result in a great deal of duplicated work
- systems that don't run every frame miss changes
- duplicates detection when looping

## Proposal 3: Last-Tick Change Detection

Flags persist for two frames, using a double-buffer system identical to that used in events.

A change is observed if it is found in the previous frame's list of changes.

**Type:** Exact

**Pros:**
- exact
- easy to understand
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)

**Cons:**
- change detection is always delayed, possibly causing painful chained delays
- systems that don't run every frame miss changes
- duplicates detection when looping

## Proposal 4: Flag-Doubling Change Detection

Combine Proposal 2 and Proposal 3. Differentiate between `JustChanged` (current behavior) and `Changed` (Proposal 3).

Pack this data into the flags according to [this implementation proposal](https://github.com/bevyengine/bevy/issues/68#issuecomment-769174804).

**Type:** Flaky + Exact

**Pros:**
- allows users to acc
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)

**Cons:**
- users must specify the type of change detection required
- still quite fragile to system ordering effects when using the flaky `JustChanged` form
- cannot get immediate + exact results
- systems that don't run every frame miss changes
- duplicates detection when looping

## [SELECTED] Proposal 5: Generation-Counter Change Detection

A global counter is increased after each system is run. Each component saves the time of last mutation, and each system saves the time of last execution. Mutation is detected when the component's counter is greater than the system's counter. Discussed [here](https://github.com/bevyengine/bevy/issues/68#issuecomment-769174804). How to handle addition detection is unsolved; the current proposal is to use the highest bit of the counter as in proposal 1.

**Type:** Exact (for mutations), flaky (for additions)

**Pros:**
- low time overhead (set component counter on access, set system counter after execution)
- robust to systems that don't run every frame
- robust to systems that loop

**Cons:**
- moderately complex implementation
- must be modified as systems are inserted dynamically
- medium memory overhead (4 bytes per component + system)
- unsolved addition detection

## Proposal 6: System-Data Change Detection

For each system, track which system's changes it has seen. This approach is only worth fully designing and implementing if Proposal 5 fails in some way.  

**Type:** Exact

**Pros:**
- exact
- conceptually simple

**Cons:**
- requires storing data on each system
- implementation is complex
- must be modified as systems are inserted dynamically

## Proposal 7: Total-Order Change Detection

Discussed [here](https://github.com/bevyengine/bevy/issues/68#issuecomment-754326523). This proposal is somewhat complicated by the new scheduler, but I believe it should still be conceptually feasible. This approach is only worth fully designing and implementing if Proposal 5 fails in some way.  

**Type:** Exact

**Pros:**
- exact
- efficient data storage relative to other exact proposals

**Cons:**
- requires access to the scheduler
- complex implementation and difficulty grokking
- must be modified as systems are inserted dynamically

# Tests

- We will need to verify properties 1, 2, 3, 7 and 8. Priority: 1 > 2 = 3 > 8 > 7
- Ideally we can use identical user-facing syntax for all proposals, allowing us to re-use the same syntax for each.
- When writing tests, we need to carefully specify order using explicit dependencies.
- These tests will need to be duplicated for both components and resources.
- We need to be sure to handle cases where ambiguous system orders exist.

`changing_system` is always the system that makes the changes, and `detecting_system` always detects the changes.

The component / resource changed will be simple boolean wrapper structs.

## Basic Added / Mutated / Changed

2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs before `detecting_system`
- verify at the end of tick 2

## At Least Once

2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs after `detecting_system`
- verify at the end of tick 2

## At Most Once

2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs once before `detecting_system`
- increment a counter based on the number of changes detected
- verify at the end of tick 2

## Fast Detection
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs before `detecting_system`
- verify at the end of tick 1

## Ambiguous System Ordering Robustness
2 x 3 x 2 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs [before/after] `detecting_system` in tick 1
- `changing_system` runs [after/before] `detecting_system` in tick 2

## System Pausing
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs in tick 1, then is disabled by run criteria
- `detecting_system` is disabled by run criteria until it is run once during tick 3
- verify at the end of tick 3

## Addition Causes Mutation

2 design:
- Resources vs. Components
- `adding_system_1` adds a component / resource
- `adding system_2` adds the same component / resource
- verify the `Mutated` flag at the end of the tick
- verify the `Added` flag at the end of the tick

First check tests for: https://github.com/bevyengine/bevy/issues/333
Second check tests for: https://github.com/bevyengine/bevy/issues/1443

## Changes Made By Commands

- `adding_system` runs in Update in tick 1, and sends a command to add a component 
- `detecting_system` runs in Update in tick 1 and 2, after `adding_system`
- We can't detect the changes in tick 1, since they haven't been processed yet
- If we were to track these changes as being emitted by `adding_system`, we can't detect the changes in tick 2 either, since `detecting_system` has already run once after `adding_system` :( 

# Benchmarks

See: [general advice](https://github.com/bevyengine/bevy/blob/master/docs/profiling.md), [Criterion crate](https://github.com/bheisler/criterion.rs)

There are several critical parameters to vary: 
1. entity count (1 to 10^9)
2. fraction of entities that are changed (0% to 100%)
3. cost to perform work on changed entities, i.e. workload (1 ns to 1s)

1 and 2 should be varied between benchmark runs. 3 can be added on computationally.

We want to measure:
- memory cost
- run time

We should collect these measurements across several frames (100?) to reduce bootup effects and accurately measure the mean, variance and drift.

Entity-component change detection is much more important to benchmark than resource change detection, due to the orders of magnitude higher number of pieces of data.

No change detection at all should be included in benchmarks as a second control for cases where missing changes is unacceptable.

## Graphs
1. y: performance, x: log_10(entity count), color: proposal, facet: performance metric. Set cost to perform work to 0. 
2. y: run time, x: cost to perform work, color: proposal, facet: fraction changed. Set number of entities to 10^6
3. y: memory, x: frames, color: proposal

# Conclusions
1. Is the theoretical categorization of the proposals correct according to our tests?
2. How does the performance of the proposals compare without any load?
3. How does the performance of the proposals compare with realistic loads?
4. At what workload does more exact change tracking become worth the (presumably) higher overhead?
5. When does adding change-detection to save on work become worthwhile?
6. Is there enough divergence in performance between the best solutions in each class to ship more than one change-tracking solution?

# Implementation Plan

1. Write a test suite.
2. Verify that tests fail for existing approach.
3. Write a benchmark suite.
4. Get performance numbers for existing approach.
5. Implement, test and benchmark various solutions using a Git branch per proposal.
6. Create a draft PR with all solutions and present results to team.
7. Select a solution and replace existing change detection.

Co-authored-by: Brice DAVIER <bricedavier@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-19 17:53:26 +00:00
François
348e2a3d40 documentation on Transform and GlobalTransform (#1687)
fixes #1599 

* Added doc on `Transform` and `GlobalTransform` to describe usage and how `GlobalTransform` is updated
* Documented all methods on `Transform`
* `#[doc(hidden)]` most constructors and methods mutating `GlobalTransform`, documented the other
* Mentioned z-ordering for `Transform` in 2d
2021-03-19 03:54:53 +00:00
Carter Anderson
8d1e52be31 fix dyn warning (#1690)
This is now a warning on nightly.
2021-03-19 02:53:26 +00:00
Zaszi
0a875f647d Derive PartialEq for WindowMode (#1688)
Many a game will provide some sort of video settings where a window mode option is a common inclusion. I ran into problems, however, with [egui's](https://github.com/emilk/egui) `combo_box` that imposes a `PartialEq` necessity. Deriving the trait would fix this problem, and as this does not break any existing API it should be a non-controversial change.
2021-03-18 23:47:34 +00:00
Alec Deason
cd4c684ad5 Fix tiny typo in ambiguity checker message (#1682)
Add one missing word
2021-03-18 01:28:21 +00:00
François
bcd5318247 color spaces and representation (#1572)
`Color` can now be from different color spaces or representation:
- sRGB
- linear RGB
- HSL

This fixes #1193 by allowing the creation of const colors of all types, and writing it to the linear RGB color space for rendering.

I went with an enum after trying with two different types (`Color` and `LinearColor`) to be able to use the different variants in all place where a `Color` is expected.

I also added the HLS representation because:
- I like it
- it's useful for some case, see example `contributors`: I can just change the saturation and lightness while keeping the hue of the color
- I think adding another variant not using `red`, `green`, `blue` makes it clearer there are differences

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-17 23:59:51 +00:00
Alice Cecile
ab0165d20d Improved documentation for Events (#1669)
Explains subtle behavior more explicitly, documents `add_event`, mentions `EventWriter`.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-17 23:42:19 +00:00
Carter Anderson
5fedb6029a Make Reflect impls unsafe (Reflect::any must return self) (#1679)
Fixes #1100 

Implementors must make sure that `Reflect::any` and `Reflect::any_mut` both return the `self` reference passed in (both for logical correctness and downcast safety).
2021-03-17 22:46:46 +00:00
François
107dd73687 update ColorMaterial when Texture changed (#1461)
fixes #1161, fixes #1243

this adds two systems:
- first is keeping an hashmap of textures and their containing color materials, then listening to events on textures to select color materials that should be updated
- second is chained to send a modified event for all color materials that need updating
2021-03-17 19:53:24 +00:00
TheRawMeatball
284889c64b Redo State architecture (#1424)
An alternative to StateStages that uses SystemSets. Also includes pop and push operations since this was originally developed for my personal project which needed them.
2021-03-15 22:12:04 +00:00
Jakob Hellermann
48ee167531 expose stages and system containers (#1647)
This allows third-party plugins to analyze the schedule, e.g. `bevy_mod_picking` can [display a schedule graph](https://github.com/jakobhellermann/bevy_mod_debugdump/tree/schedule-graph#schedule-graph):

![schedule graph](https://raw.githubusercontent.com/jakobhellermann/bevy_mod_debugdump/schedule-graph/docs/schedule_graph.svg)
2021-03-14 20:44:51 +00:00
davier
de55e05669 Fix error in DynamicScene (#1651)
The wrong error was returned when using an unregistered type in a scene, leading to a confusing error message.
2021-03-14 20:02:10 +00:00
Jakob Hellermann
f6ff80c5b1
add Debug, Copy, Clone for all shapes (#1653) 2021-03-14 12:45:00 -07:00
Jakob Hellermann
ac661188c8 better error message: specify which resource is missing (#1648) 2021-03-14 00:36:16 +00:00
François
86e2fc53d0 improve error message when asset type hasn't beed added to app (#1487)
Error message noticed in #1475 

When an asset type hasn't been added to the app but a load was attempted, the error message wasn't helpful:
```
thread 'IO Task Pool (0)' panicked at 'Failed to find AssetLifecycle for label Some("Mesh0/Primitive0"), which has an asset type 8ecbac0f-f545-4473-ad43-e1f4243af51e. Are you sure that is a registered asset type?', /.cargo/git/checkouts/bevy-f7ffde730c324c74/89a41bc/crates/bevy_asset/src/asset_server.rs:435:17
```
means that 
```rust
.add_asset::<bevy::render::prelude::Mesh>()
```
needs to be added.

* type name was not given, only UUID, which may make it hard to identify type across bevy/plugins
* instruction were not helpful as the `register_asset_type` method is not public

new error message:
```
thread 'IO Task Pool (1)' panicked at 'Failed to find AssetLifecycle for label 'Some("Mesh0/Primitive0")', which has an asset type "bevy_render::mesh::mesh::Mesh" (UUID 8ecbac0f-f545-4473-ad43-e1f4243af51e). Are you sure this asset type has been added to your app builder?', /bevy/crates/bevy_asset/src/asset_server.rs:435:17
```
2021-03-14 00:36:15 +00:00
Simon Guillot
aa81aaf3fa Small improvement of code quality of Assets::set* methods (#1649)
As mentioned in #1609.

I'm not sure if this is desirable, but on top of factoring the `set` and `set_untracked` methods I added a warning when the return value of `set` isn't used to mitigate similar issues.

I silenced it for the only occurence where it's currently done  68606934e3/crates/bevy_asset/src/asset_server.rs (L468)
2021-03-14 00:19:44 +00:00
Jasen Borisov
2e72755b8a GLTF loader: support mipmap filters (#1639)
This removes the `GltfError::UnsupportedMinFilter` error.

I don't think this error should have existed in the first place, because it prevents users from using assets that bevy could totally render (without mipmap support as of yet).

It's much better to load the asset properly and then render it (even if it looks a little ugly), than to refuse to load the asset at all, giving users a confusing error.
2021-03-13 18:44:26 +00:00
François
bbb9849506 Replace default method calls from Glam types with explicit const (#1645)
it's a followup of #1550 

I think calling explicit methods/values instead of default makes the code easier to read: "what is `Quat::default()`" vs "Oh, it's `Quat::IDENTITY`"

`Transform::identity()` and `GlobalTransform::identity()` can also be consts and I replaced the calls to their `default()` impl with `identity()`
2021-03-13 18:23:39 +00:00
davier
8acb0d2012 Fix cargo doc warnings (#1640)
Fixes all warnings from `cargo doc --all`.
Those related to code blocks were introduced in #1612, but re-formatting using the experimental features in `rustfmt.toml` doesn't seem to reintroduce them.
2021-03-13 18:23:38 +00:00
François
75ae20dc4a use std clamp instead of Bevy's (#1644)
Rust std's `clamp` has been stabilised in 1.50: https://github.com/rust-lang/rust/issues/44095

This is already the minimum supported version, so no change there 👍
2021-03-13 18:07:14 +00:00
Simon Guillot
785aad92f4 Fix pipeline initialisation of wireframe mode (fixes #1609) (#1623)
More details are in the associated issue #1609.

While looking for the source of this issue, I've noticed that the `set` and `set_untracked` methods aren't really DRY:
68606934e3/crates/bevy_asset/src/assets.rs (L76-L85)

68606934e3/crates/bevy_asset/src/assets.rs (L91-L99)

Shouldn't `set` call `set_untracked`? Also, given the bug that arose from a misusage of these functions, maybe some refactoring is needed?
2021-03-12 22:12:07 +00:00
Alice Cecile
03601db51c Basic documentation for Entities, Components and Systems (#1578)
These are largely targeted at beginners, as `Entity`, `Component` and `System` are the most obvious terms to search when first getting introduced to Bevy.
2021-03-12 19:59:55 +00:00
Jonas Matser
32af4b7dc3 Add separate brightness field to AmbientLight (#1605)
Idea being this would be easier to grasp for end-users. Problem with the logical defaults is this breaks current setups, because light will become 20 times less bright. But most folks won't have customized this resource or will not have used `..Default::default()` due to lack of other fields.
2021-03-12 18:59:24 +00:00
MinerSebas
8a9f475edb Remove the Clippy "-A clippy::manual-strip" override (#1619)
That override was added to support pre 1.45 Versions of Rust, but Bevy requires currently the latest stable rust release.
This means that the reason for the override doesn't apply anymore.
2021-03-12 03:05:14 +00:00
Carter Anderson
68606934e3 remove unsafe get_unchecked (and mut variant) from Tables and Archetypes (#1614)
Removes `get_unchecked` and `get_unchecked_mut` from `Tables` and `Archetypes` collections in favor of safe Index implementations. This fixes a safety error in `Archetypes::get_id_or_insert()` (which previously relied on TableId being valid to be safe ... the alternative was to make that method unsafe too). It also cuts down on a lot of unsafe and makes the code easier to look at. I'm not sure what changed since the last benchmark, but these numbers are more favorable than my last tests of similar changes. I didn't include the Components collection as those severely killed perf last time I tried. But this does inspire me to try again (just in a separate pr)! 

Note that the `simple_insert/bevy_unbatched` benchmark fluctuates a lot on both branches (this was also true for prior versions of bevy). It seems like the allocator has more variance for many small allocations. And `sparse_frag_iter/bevy` operates on such a small scale that 10% fluctuations are common.

Some benches do take a small hit here, but I personally think its worth it.

This also fixes a safety error in Query::for_each_mut, which needed to mutably borrow Query (aaahh!).  

![image](https://user-images.githubusercontent.com/2694663/110726926-2b52eb80-81cf-11eb-9ea3-bff951060c7c.png)
![image](https://user-images.githubusercontent.com/2694663/110726991-4c1b4100-81cf-11eb-9199-ca79bef0b9bd.png)
2021-03-11 18:38:22 +00:00
Carter Anderson
b17f8a4bce format comments (#1612)
Uses the new unstable comment formatting features added to rustfmt.toml.
2021-03-11 00:27:30 +00:00
Carter Anderson
be1c317d4e Resolve (most) internal system ambiguities (#1606)
* Adds labels and orderings to systems that need them (uses the new many-to-many labels for InputSystem)
* Removes the Event, PreEvent, Scene, and Ui stages in favor of First, PreUpdate, and PostUpdate (there is more collapsing potential, such as the Asset stages and _maybe_ removing First, but those have more nuance so they should be handled separately)
* Ambiguity detection now prints component conflicts
* Removed broken change filters from flex calculation (which implicitly relied on the z-update system always modifying translation.z). This will require more work to make it behave as expected so i just removed it (and it was already doing this work every frame).
2021-03-10 22:37:02 +00:00
Martín Maita
e9a501e6b8 Fixes potential panic when unwrapping touch event on Moved phase (#1591)
Should fix https://github.com/bevyengine/bevy/issues/1516.

I don't have any devices available to test this tbh but I feel like this was the only spot that could be causing a panic.

@ptircylinder since you posted this issue, could you please try to run the example on this branch and check if you get the same behavior while using your device? Thank you!
2021-03-10 00:44:45 +00:00
Nathan Stocks
faeccd7a09 Reflection cleanup (#1536)
This is an effort to provide the correct `#[reflect_value(...)]` attributes where they are needed.  

Supersedes #1533 and resolves #1528.

---

I am working under the following assumptions (thanks to @bjorn3 and @Davier for advice here):

- Any `enum` that derives `Reflect` and one or more of { `Serialize`, `Deserialize`, `PartialEq`, `Hash` } needs a `#[reflect_value(...)]` attribute containing the same subset of { `Serialize`, `Deserialize`, `PartialEq`, `Hash` } that is present on the derive.
- Same as above for `struct` and `#[reflect(...)]`, respectively.
- If a `struct` is used as a component, it should also have `#[reflect(Component)]`
- All reflected types should be registered in their plugins

I treated the following as components (added `#[reflect(Component)]` if necessary):
- `bevy_render`
  - `struct RenderLayers`
- `bevy_transform`
  - `struct GlobalTransform`
  - `struct Parent`
  - `struct Transform`
- `bevy_ui`
  - `struct Style`

Not treated as components:
- `bevy_math`
  - `struct Size<T>`
  - `struct Rect<T>`
  - Note: The updates for `Size<T>` and `Rect<T>` in `bevy::math::geometry` required using @Davier's suggestion to add `+ PartialEq` to the trait bound. I then registered the specific types used over in `bevy_ui` such as `Size<Val>`, etc. in `bevy_ui`'s plugin, since `bevy::math` does not contain a plugin.
- `bevy_render`
  - `struct Color`
  - `struct PipelineSpecialization`
  - `struct ShaderSpecialization`
  - `enum PrimitiveTopology`
  - `enum IndexFormat`

Not Addressed:
- I am not searching for components in Bevy that are _not_ reflected. So if there are components that are not reflected that should be reflected, that will need to be figured out in another PR.
- I only added `#[reflect(...)]` or `#[reflect_value(...)]` entries for the set of four traits { `Serialize`, `Deserialize`, `PartialEq`, `Hash` } _if they were derived via `#[derive(...)]`_. I did not look for manual trait implementations of the same set of four, nor did I consider any traits outside the four.  Are those other possibilities something that needs to be looked into?
2021-03-09 23:39:41 +00:00
Alexander Sepity
d51130d4ab Many-to-many system labels (#1576)
* Systems can now have more than one label attached to them.
* System labels no longer have to be unique in the stage.

Code like this is now possible:
```rust
SystemStage::parallel()
    .with_system(system_0.system().label("group one").label("first"))
    .with_system(system_1.system().label("group one").after("first"))
    .with_system(system_2.system().after("group one"))
```

I've opted to use only the system name in ambiguity reporting, which previously was only a fallback; this, obviously, is because labels aren't one-to-one with systems anymore. We could allow users to name systems to improve this; we'll then have to think about whether or not we want to allow using the name as a label (this would, effectively, introduce implicit labelling, not all implications of which are clear to me yet wrt many-to-many labels).

Dependency cycle errors are reported using the system names and only the labels that form the cycle, with each system-system "edge" in the cycle represented as one or several labels.

Slightly unrelated: `.before()` and `.after()` with a label not attached to any system no longer crashes, and logs a warning instead. This is necessary to, for example, allow plugins to specify execution order with systems of potentially missing other plugins.
2021-03-09 23:08:34 +00:00
TheRawMeatball
ea9c7d58ff Fix label macro for types with generics (#1498)
Fixes #1497

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-09 03:49:48 +00:00
TheRawMeatball
9d60563adf Query::get_unique (#1263)
Adds `get_unique` and `get_unique_mut` to extend the query api and cover a common use case. Also establishes a second impl block where non-core APIs that don't access the internal fields of queries can live.
2021-03-08 21:21:47 +00:00
Jasen Borisov
13aef05038 impl SystemParam for Option<Res<T>> / Option<ResMut<T>> (#1494)
This allows users to write systems that do not panic if a resource does not exist at runtime (such as if it has not been inserted yet).

This is a copy-paste of the impls for `Res` and `ResMut`, with an extra check to see if the resource exists.

There might be a cleaner way to do it than this check. I don't know.
2021-03-08 20:12:22 +00:00
TheRawMeatball
d9b8b3e618 Add EventWriter (#1575)
This adds a `EventWriter<T>` `SystemParam` that is just a thin wrapper around `ResMut<Events<T>>`. This is primarily to have API symmetry between the reader and writer, and has the added benefit of easily improving the API later with no breaking changes.
2021-03-07 20:42:04 +00:00
Joshua J. Bouw
2b0a48d945 feat: clone indices (#1574)
Super simple and straight forward. I need this for the tilemap because if I need to update all chunk indices, then I can calculate it once and clone it. Of course, for now I'm just returning the Vec itself then wrapping it but would be nice if I didn't have to do that.
2021-03-07 19:50:20 +00:00
François
58d687b86d fix flip of contributor bird (#1573)
Since 89217171b4, some birds in example `contributors` where not colored.

Fix is to use `flip_x` of `Sprite` instead of setting `transform.scale.x` to `-1` as described in #1407.


It may be an unintended side effect, as now we can't easily display a colored sprite while changing it's scale from `1` to `-1`, we would have to change it's scale from `1` to `0`, then flip it, then change scale from `0` to `1`.
2021-03-07 19:50:19 +00:00
Jonas Matser
a7308155ee Make TypeRegistration::get_short_name() pub (#1571)
This would allow for example `bevy_mod_debugdump` to use it, instead of custom typename shortening.
2021-03-07 19:50:18 +00:00
François
dabf419095 update archetypes if needed before running system in SingleThreadedExecutor (#1586)
fixes #1585 

I copied most of the logic from the `ParallelSystemExecutor` impl, simplifying it a little as systems can't run in parallel
2021-03-07 19:32:19 +00:00
Cameron Hart
f61e44db28 Update glam to 0.13.0. (#1550)
See https://github.com/bitshifter/glam-rs/blob/master/CHANGELOG.md for details on changes.

Co-authored-by: Cameron Hart <c_hart@wargaming.net>
2021-03-06 19:39:16 +00:00
Carter Anderson
0eba5f38b9 update hexasphere to 3.2 (#1577) 2021-03-06 19:23:04 +00:00
Alice Cecile
03e0a9f23e Docs for Bundle showing how to nest bundles (#1570)
I've also added a clearer description of what bundles are used for, and explained that you can't query for bundles (a very common beginner confusion).

Co-authored-by: MinerSebas <scherthan_sebastian@web.de>
Co-authored-by: Renato Caldas <renato@calgera.com>
2021-03-06 01:57:03 +00:00
sdfgeoff
006848311c Documented some of the Mesh properties (#1566)
I was fiddling with creating a mesh importer today, and decided to write some more docs. 

A lot of this is describing general renderer/GL stuff, so you'll probably find most of it self explanatory anyway, but perhaps it will be useful for someone.
2021-03-06 01:57:02 +00:00
sdfgeoff
64b29617d6 Added documentation on the query filters (#1553)
This documents both the non-obvious interaction with non-explicit system ordering
and adds examples for Changed and Added. This likely closes #1551
2021-03-06 01:57:01 +00:00
Renato Caldas
87399c3560 Fix staging buffer required size calculation (fixes #1056) (#1509)
Fix staging buffer required size calculation (fixes #1056)

The `required_staging_buffer_size` is currently calculated differently in two places, each will be correct in different situations:

* `prepare_staging_buffers()` based on actual `buffer_byte_len()`
* `set_required_staging_buffer_size_to_max()` based on item_size

In the case of render assets, `prepare_staging_buffers()` would only operate over changed assets. If some of the assets didn't change, their size wouldn't be taken into account for the `required_staging_buffer_size`. In some cases, this meant the buffers wouldn't be resized when they should. Now `prepare_staging_buffers()` is called over all assets, which may hit performance but at least gets the size right.

Shortly after `prepare_staging_buffers()`,  `set_required_staging_buffer_size_to_max()` would unconditionally overwrite the previously computed value, even if using `item_size` made no sense. Now it only overwrites the value if bigger.

This can be considered a short term hack, but should prevent a few hard to debug panics.
2021-03-06 01:42:57 +00:00
MinerSebas
b2d654cbf6 Use rand 0.8 again (#1567)
#1525 accidentally moved back to rand 0.7
2021-03-06 00:53:42 +00:00
Chris Janaqi
ab407aa697 ♻️ Timer refactor to duration. Add Stopwatch struct. (#1151)
This pull request is following the discussion on the issue #1127. Additionally, it integrates the change proposed by #1112.

The list of change of this pull request:

*  Add `Timer::times_finished` method that counts the number of wraps for repeating timers.
* ♻️ Refactored `Timer`
* 🐛 Fix a bug where 2 successive calls to `Timer::tick` which makes a repeating timer to finish makes `Timer::just_finished` to return `false` where it should return `true`. Minimal failing example:
```rust
use bevy::prelude::*;
let mut timer: Timer<()> = Timer::from_seconds(1.0, true);
timer.tick(1.5);
assert!(timer.finished());
assert!(timer.just_finished());
timer.tick(1.5);
assert!(timer.finished());
assert!(timer.just_finished()); // <- This fails where it should not
```
* 📚 Add extensive documentation for Timer with doc examples.
*  Add a `Stopwatch` struct similar to `Timer` with extensive doc and tests.

Even if the type specialization is not retained for bevy, the doc, bugfix and added method are worth salvaging 😅.
This is my first PR for bevy, please be kind to me ❤️ .

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-05 19:59:14 +00:00
Jakob Hellermann
4686437d7a add Or back to prelude (#1564)
The bevy ecs v2 rewrite seems to have removed the `Or` query filter from the prelude, which I assume was done on accident, since `With` and `Without` are still there.
2021-03-05 18:33:20 +00:00
Carter Anderson
3a2a68852c Bevy ECS V2 (#1525)
# Bevy ECS V2

This is a rewrite of Bevy ECS (basically everything but the new executor/schedule, which are already awesome). The overall goal was to improve the performance and versatility of Bevy ECS. Here is a quick bulleted list of changes before we dive into the details:

* Complete World rewrite
* Multiple component storage types:
    * Tables: fast cache friendly iteration, slower add/removes (previously called Archetypes)
    * Sparse Sets: fast add/remove, slower iteration
* Stateful Queries (caches query results for faster iteration. fragmented iteration is _fast_ now)
* Stateful System Params (caches expensive operations. inspired by @DJMcNab's work in #1364)
* Configurable System Params (users can set configuration when they construct their systems. once again inspired by @DJMcNab's work)
* Archetypes are now "just metadata", component storage is separate
* Archetype Graph (for faster archetype changes)
* Component Metadata
    * Configure component storage type
    * Retrieve information about component size/type/name/layout/send-ness/etc
    * Components are uniquely identified by a densely packed ComponentId
    * TypeIds are now totally optional (which should make implementing scripting easier)
* Super fast "for_each" query iterators
* Merged Resources into World. Resources are now just a special type of component
* EntityRef/EntityMut builder apis (more efficient and more ergonomic)
* Fast bitset-backed `Access<T>` replaces old hashmap-based approach everywhere
* Query conflicts are determined by component access instead of archetype component access (to avoid random failures at runtime)
    * With/Without are still taken into account for conflicts, so this should still be comfy to use
* Much simpler `IntoSystem` impl
* Significantly reduced the amount of hashing throughout the ecs in favor of Sparse Sets (indexed by densely packed ArchetypeId, ComponentId, BundleId, and TableId)
* Safety Improvements
    * Entity reservation uses a normal world reference instead of unsafe transmute
    * QuerySets no longer transmute lifetimes
    * Made traits "unsafe" where relevant
    * More thorough safety docs
* WorldCell
    * Exposes safe mutable access to multiple resources at a time in a World 
* Replaced "catch all" `System::update_archetypes(world: &World)` with `System::new_archetype(archetype: &Archetype)`
* Simpler Bundle implementation
* Replaced slow "remove_bundle_one_by_one" used as fallback for Commands::remove_bundle with fast "remove_bundle_intersection"
* Removed `Mut<T>` query impl. it is better to only support one way: `&mut T` 
* Removed with() from `Flags<T>` in favor of `Option<Flags<T>>`, which allows querying for flags to be "filtered" by default 
* Components now have is_send property (currently only resources support non-send)
* More granular module organization
* New `RemovedComponents<T>` SystemParam that replaces `query.removed::<T>()`
* `world.resource_scope()` for mutable access to resources and world at the same time
* WorldQuery and QueryFilter traits unified. FilterFetch trait added to enable "short circuit" filtering. Auto impled for cases that don't need it
* Significantly slimmed down SystemState in favor of individual SystemParam state
* System Commands changed from `commands: &mut Commands` back to `mut commands: Commands` (to allow Commands to have a World reference)

Fixes #1320

## `World` Rewrite

This is a from-scratch rewrite of `World` that fills the niche that `hecs` used to. Yes, this means Bevy ECS is no longer a "fork" of hecs. We're going out our own!

(the only shared code between the projects is the entity id allocator, which is already basically ideal)

A huge shout out to @SanderMertens (author of [flecs](https://github.com/SanderMertens/flecs)) for sharing some great ideas with me (specifically hybrid ecs storage and archetype graphs). He also helped advise on a number of implementation details.

## Component Storage (The Problem)

Two ECS storage paradigms have gained a lot of traction over the years:

* **Archetypal ECS**: 
    * Stores components in "tables" with static schemas. Each "column" stores components of a given type. Each "row" is an entity.
    * Each "archetype" has its own table. Adding/removing an entity's component changes the archetype.
    * Enables super-fast Query iteration due to its cache-friendly data layout
    * Comes at the cost of more expensive add/remove operations for an Entity's components, because all components need to be copied to the new archetype's "table"
* **Sparse Set ECS**:
    * Stores components of the same type in densely packed arrays, which are sparsely indexed by densely packed unsigned integers (Entity ids)
    * Query iteration is slower than Archetypal ECS because each entity's component could be at any position in the sparse set. This "random access" pattern isn't cache friendly. Additionally, there is an extra layer of indirection because you must first map the entity id to an index in the component array.
    * Adding/removing components is a cheap, constant time operation 

Bevy ECS V1, hecs, legion, flec, and Unity DOTS are all "archetypal ecs-es". I personally think "archetypal" storage is a good default for game engines. An entity's archetype doesn't need to change frequently in general, and it creates "fast by default" query iteration (which is a much more common operation). It is also "self optimizing". Users don't need to think about optimizing component layouts for iteration performance. It "just works" without any extra boilerplate.

Shipyard and EnTT are "sparse set ecs-es". They employ "packing" as a way to work around the "suboptimal by default" iteration performance for specific sets of components. This helps, but I didn't think this was a good choice for a general purpose engine like Bevy because:

1. "packs" conflict with each other. If bevy decides to internally pack the Transform and GlobalTransform components, users are then blocked if they want to pack some custom component with Transform.
2. users need to take manual action to optimize

Developers selecting an ECS framework are stuck with a hard choice. Select an "archetypal" framework with "fast iteration everywhere" but without the ability to cheaply add/remove components, or select a "sparse set" framework to cheaply add/remove components but with slower iteration performance.

## Hybrid Component Storage (The Solution)

In Bevy ECS V2, we get to have our cake and eat it too. It now has _both_ of the component storage types above (and more can be added later if needed):

* **Tables** (aka "archetypal" storage)
    * The default storage. If you don't configure anything, this is what you get
    * Fast iteration by default
    * Slower add/remove operations
* **Sparse Sets**
    * Opt-in
    * Slower iteration
    * Faster add/remove operations

These storage types complement each other perfectly. By default Query iteration is fast. If developers know that they want to add/remove a component at high frequencies, they can set the storage to "sparse set":

```rust
world.register_component(
    ComponentDescriptor:🆕:<MyComponent>(StorageType::SparseSet)
).unwrap();
```

## Archetypes

Archetypes are now "just metadata" ... they no longer store components directly. They do store:

* The `ComponentId`s of each of the Archetype's components (and that component's storage type)
    * Archetypes are uniquely defined by their component layouts
    * For example: entities with "table" components `[A, B, C]` _and_ "sparse set" components `[D, E]` will always be in the same archetype.
* The `TableId` associated with the archetype
    * For now each archetype has exactly one table (which can have no components),
    * There is a 1->Many relationship from Tables->Archetypes. A given table could have any number of archetype components stored in it:
        * Ex: an entity with "table storage" components `[A, B, C]` and "sparse set" components `[D, E]` will share the same `[A, B, C]` table as an entity with `[A, B, C]` table component and `[F]` sparse set components.
        * This 1->Many relationship is how we preserve fast "cache friendly" iteration performance when possible (more on this later)
* A list of entities that are in the archetype and the row id of the table they are in
* ArchetypeComponentIds
    * unique densely packed identifiers for (ArchetypeId, ComponentId) pairs
    * used by the schedule executor for cheap system access control
* "Archetype Graph Edges" (see the next section)  

## The "Archetype Graph"

Archetype changes in Bevy (and a number of other archetypal ecs-es) have historically been expensive to compute. First, you need to allocate a new vector of the entity's current component ids, add or remove components based on the operation performed, sort it (to ensure it is order-independent), then hash it to find the archetype (if it exists). And thats all before we get to the _already_ expensive full copy of all components to the new table storage.

The solution is to build a "graph" of archetypes to cache these results. @SanderMertens first exposed me to the idea (and he got it from @gjroelofs, who came up with it). They propose adding directed edges between archetypes for add/remove component operations. If `ComponentId`s are densely packed, you can use sparse sets to cheaply jump between archetypes.

Bevy takes this one step further by using add/remove `Bundle` edges instead of `Component` edges. Bevy encourages the use of `Bundles` to group add/remove operations. This is largely for "clearer game logic" reasons, but it also helps cut down on the number of archetype changes required. `Bundles` now also have densely-packed `BundleId`s. This allows us to use a _single_ edge for each bundle operation (rather than needing to traverse N edges ... one for each component). Single component operations are also bundles, so this is strictly an improvement over a "component only" graph.

As a result, an operation that used to be _heavy_ (both for allocations and compute) is now two dirt-cheap array lookups and zero allocations.

## Stateful Queries

World queries are now stateful. This allows us to:

1. Cache archetype (and table) matches
    * This resolves another issue with (naive) archetypal ECS: query performance getting worse as the number of archetypes goes up (and fragmentation occurs).
2. Cache Fetch and Filter state
    * The expensive parts of fetch/filter operations (such as hashing the TypeId to find the ComponentId) now only happen once when the Query is first constructed
3. Incrementally build up state
    * When new archetypes are added, we only process the new archetypes (no need to rebuild state for old archetypes)

As a result, the direct `World` query api now looks like this:

```rust
let mut query = world.query::<(&A, &mut B)>();
for (a, mut b) in query.iter_mut(&mut world) {
}
```

Requiring `World` to generate stateful queries (rather than letting the `QueryState` type be constructed separately) allows us to ensure that _all_ queries are properly initialized (and the relevant world state, such as ComponentIds). This enables QueryState to remove branches from its operations that check for initialization status (and also enables query.iter() to take an immutable world reference because it doesn't need to initialize anything in world).

However in systems, this is a non-breaking change. State management is done internally by the relevant SystemParam.

## Stateful SystemParams

Like Queries, `SystemParams` now also cache state. For example, `Query` system params store the "stateful query" state mentioned above. Commands store their internal `CommandQueue`. This means you can now safely use as many separate `Commands` parameters in your system as you want. `Local<T>` system params store their `T` value in their state (instead of in Resources). 

SystemParam state also enabled a significant slim-down of SystemState. It is much nicer to look at now.

Per-SystemParam state naturally insulates us from an "aliased mut" class of errors we have hit in the past (ex: using multiple `Commands` system params).

(credit goes to @DJMcNab for the initial idea and draft pr here #1364)

## Configurable SystemParams

@DJMcNab also had the great idea to make SystemParams configurable. This allows users to provide some initial configuration / values for system parameters (when possible). Most SystemParams have no config (the config type is `()`), but the `Local<T>` param now supports user-provided parameters:

```rust

fn foo(value: Local<usize>) {    
}

app.add_system(foo.system().config(|c| c.0 = Some(10)));
```

## Uber Fast "for_each" Query Iterators

Developers now have the choice to use a fast "for_each" iterator, which yields ~1.5-3x iteration speed improvements for "fragmented iteration", and minor ~1.2x iteration speed improvements for unfragmented iteration. 

```rust
fn system(query: Query<(&A, &mut B)>) {
    // you now have the option to do this for a speed boost
    query.for_each_mut(|(a, mut b)| {
    });

    // however normal iterators are still available
    for (a, mut b) in query.iter_mut() {
    }
}
```

I think in most cases we should continue to encourage "normal" iterators as they are more flexible and more "rust idiomatic". But when that extra "oomf" is needed, it makes sense to use `for_each`.

We should also consider using `for_each` for internal bevy systems to give our users a nice speed boost (but that should be a separate pr).

## Component Metadata

`World` now has a `Components` collection, which is accessible via `world.components()`. This stores mappings from `ComponentId` to `ComponentInfo`, as well as `TypeId` to `ComponentId` mappings (where relevant). `ComponentInfo` stores information about the component, such as ComponentId, TypeId, memory layout, send-ness (currently limited to resources), and storage type.

## Significantly Cheaper `Access<T>`

We used to use `TypeAccess<TypeId>` to manage read/write component/archetype-component access. This was expensive because TypeIds must be hashed and compared individually. The parallel executor got around this by "condensing" type ids into bitset-backed access types. This worked, but it had to be re-generated from the `TypeAccess<TypeId>`sources every time archetypes changed.

This pr removes TypeAccess in favor of faster bitset access everywhere. We can do this thanks to the move to densely packed `ComponentId`s and `ArchetypeComponentId`s.

## Merged Resources into World

Resources had a lot of redundant functionality with Components. They stored typed data, they had access control, they had unique ids, they were queryable via SystemParams, etc. In fact the _only_ major difference between them was that they were unique (and didn't correlate to an entity).

Separate resources also had the downside of requiring a separate set of access controls, which meant the parallel executor needed to compare more bitsets per system and manage more state.

I initially got the "separate resources" idea from `legion`. I think that design was motivated by the fact that it made the direct world query/resource lifetime interactions more manageable. It certainly made our lives easier when using Resources alongside hecs/bevy_ecs. However we already have a construct for safely and ergonomically managing in-world lifetimes: systems (which use `Access<T>` internally).

This pr merges Resources into World:

```rust
world.insert_resource(1);
world.insert_resource(2.0);
let a = world.get_resource::<i32>().unwrap();
let mut b = world.get_resource_mut::<f64>().unwrap();
*b = 3.0;
```

Resources are now just a special kind of component. They have their own ComponentIds (and their own resource TypeId->ComponentId scope, so they don't conflict wit components of the same type). They are stored in a special "resource archetype", which stores components inside the archetype using a new `unique_components` sparse set (note that this sparse set could later be used to implement Tags). This allows us to keep the code size small by reusing existing datastructures (namely Column, Archetype, ComponentFlags, and ComponentInfo). This allows us the executor to use a single `Access<ArchetypeComponentId>` per system. It should also make scripting language integration easier.

_But_ this merge did create problems for people directly interacting with `World`. What if you need mutable access to multiple resources at the same time? `world.get_resource_mut()` borrows World mutably!

## WorldCell

WorldCell applies the `Access<ArchetypeComponentId>` concept to direct world access:

```rust
let world_cell = world.cell();
let a = world_cell.get_resource_mut::<i32>().unwrap();
let b = world_cell.get_resource_mut::<f64>().unwrap();
```

This adds cheap runtime checks (a sparse set lookup of `ArchetypeComponentId` and a counter) to ensure that world accesses do not conflict with each other. Each operation returns a `WorldBorrow<'w, T>` or `WorldBorrowMut<'w, T>` wrapper type, which will release the relevant ArchetypeComponentId resources when dropped.

World caches the access sparse set (and only one cell can exist at a time), so `world.cell()` is a cheap operation. 

WorldCell does _not_ use atomic operations. It is non-send, does a mutable borrow of world to prevent other accesses, and uses a simple `Rc<RefCell<ArchetypeComponentAccess>>` wrapper in each WorldBorrow pointer. 

The api is currently limited to resource access, but it can and should be extended to queries / entity component access.

## Resource Scopes

WorldCell does not yet support component queries, and even when it does there are sometimes legitimate reasons to want a mutable world ref _and_ a mutable resource ref (ex: bevy_render and bevy_scene both need this). In these cases we could always drop down to the unsafe `world.get_resource_unchecked_mut()`, but that is not ideal!

Instead developers can use a "resource scope"

```rust
world.resource_scope(|world: &mut World, a: &mut A| {
})
```

This temporarily removes the `A` resource from `World`, provides mutable pointers to both, and re-adds A to World when finished. Thanks to the move to ComponentIds/sparse sets, this is a cheap operation.

If multiple resources are required, scopes can be nested. We could also consider adding a "resource tuple" to the api if this pattern becomes common and the boilerplate gets nasty.

## Query Conflicts Use ComponentId Instead of ArchetypeComponentId

For safety reasons, systems cannot contain queries that conflict with each other without wrapping them in a QuerySet. On bevy `main`, we use ArchetypeComponentIds to determine conflicts. This is nice because it can take into account filters:

```rust
// these queries will never conflict due to their filters
fn filter_system(a: Query<&mut A, With<B>>, b: Query<&mut B, Without<B>>) {
}
```

But it also has a significant downside:
```rust
// these queries will not conflict _until_ an entity with A, B, and C is spawned
fn maybe_conflicts_system(a: Query<(&mut A, &C)>, b: Query<(&mut A, &B)>) {
}
```

The system above will panic at runtime if an entity with A, B, and C is spawned. This makes it hard to trust that your game logic will run without crashing.

In this pr, I switched to using `ComponentId` instead. This _is_ more constraining. `maybe_conflicts_system` will now always fail, but it will do it consistently at startup. Naively, it would also _disallow_ `filter_system`, which would be a significant downgrade in usability. Bevy has a number of internal systems that rely on disjoint queries and I expect it to be a common pattern in userspace.

To resolve this, I added a new `FilteredAccess<T>` type, which wraps `Access<T>` and adds with/without filters. If two `FilteredAccess` have with/without values that prove they are disjoint, they will no longer conflict.

## EntityRef / EntityMut

World entity operations on `main` require that the user passes in an `entity` id to each operation:

```rust
let entity = world.spawn((A, )); // create a new entity with A
world.get::<A>(entity);
world.insert(entity, (B, C));
world.insert_one(entity, D);
```

This means that each operation needs to look up the entity location / verify its validity. The initial spawn operation also requires a Bundle as input. This can be awkward when no components are required (or one component is required).

These operations have been replaced by `EntityRef` and `EntityMut`, which are "builder-style" wrappers around world that provide read and read/write operations on a single, pre-validated entity:

```rust
// spawn now takes no inputs and returns an EntityMut
let entity = world.spawn()
    .insert(A) // insert a single component into the entity
    .insert_bundle((B, C)) // insert a bundle of components into the entity
    .id() // id returns the Entity id

// Returns EntityMut (or panics if the entity does not exist)
world.entity_mut(entity)
    .insert(D)
    .insert_bundle(SomeBundle::default());
{
    // returns EntityRef (or panics if the entity does not exist)
    let d = world.entity(entity)
        .get::<D>() // gets the D component
        .unwrap();
    // world.get still exists for ergonomics
    let d = world.get::<D>(entity).unwrap();
}

// These variants return Options if you want to check existence instead of panicing 
world.get_entity_mut(entity)
    .unwrap()
    .insert(E);

if let Some(entity_ref) = world.get_entity(entity) {
    let d = entity_ref.get::<D>().unwrap();
}
```

This _does not_ affect the current Commands api or terminology. I think that should be a separate conversation as that is a much larger breaking change.

## Safety Improvements

* Entity reservation in Commands uses a normal world borrow instead of an unsafe transmute
* QuerySets no longer transmutes lifetimes
* Made traits "unsafe" when implementing a trait incorrectly could cause unsafety
* More thorough safety docs

## RemovedComponents SystemParam

The old approach to querying removed components: `query.removed:<T>()` was confusing because it had no connection to the query itself. I replaced it with the following, which is both clearer and allows us to cache the ComponentId mapping in the SystemParamState:

```rust
fn system(removed: RemovedComponents<T>) {
    for entity in removed.iter() {
    }
} 
```

## Simpler Bundle implementation

Bundles are no longer responsible for sorting (or deduping) TypeInfo. They are just a simple ordered list of component types / data. This makes the implementation smaller and opens the door to an easy "nested bundle" implementation in the future (which i might even add in this pr). Duplicate detection is now done once per bundle type by World the first time a bundle is used.

## Unified WorldQuery and QueryFilter types

(don't worry they are still separate type _parameters_ in Queries .. this is a non-breaking change)

WorldQuery and QueryFilter were already basically identical apis. With the addition of `FetchState` and more storage-specific fetch methods, the overlap was even clearer (and the redundancy more painful).

QueryFilters are now just `F: WorldQuery where F::Fetch: FilterFetch`. FilterFetch requires `Fetch<Item = bool>` and adds new "short circuit" variants of fetch methods. This enables a filter tuple like `(With<A>, Without<B>, Changed<C>)` to stop evaluating the filter after the first mismatch is encountered. FilterFetch is automatically implemented for `Fetch` implementations that return bool.

This forces fetch implementations that return things like `(bool, bool, bool)` (such as the filter above) to manually implement FilterFetch and decide whether or not to short-circuit.

## More Granular Modules

World no longer globs all of the internal modules together. It now exports `core`, `system`, and `schedule` separately. I'm also considering exporting `core` submodules directly as that is still pretty "glob-ey" and unorganized (feedback welcome here).

## Remaining Draft Work (to be done in this pr)

* ~~panic on conflicting WorldQuery fetches (&A, &mut A)~~
    * ~~bevy `main` and hecs both currently allow this, but we should protect against it if possible~~
* ~~batch_iter / par_iter (currently stubbed out)~~
* ~~ChangedRes~~
    * ~~I skipped this while we sort out #1313. This pr should be adapted to account for whatever we land on there~~.
* ~~The `Archetypes` and `Tables` collections use hashes of sorted lists of component ids to uniquely identify each archetype/table. This hash is then used as the key in a HashMap to look up the relevant ArchetypeId or TableId. (which doesn't handle hash collisions properly)~~
* ~~It is currently unsafe to generate a Query from "World A", then use it on "World B" (despite the api claiming it is safe). We should probably close this gap. This could be done by adding a randomly generated WorldId to each world, then storing that id in each Query. They could then be compared to each other on each `query.do_thing(&world)` operation. This _does_ add an extra branch to each query operation, so I'm open to other suggestions if people have them.~~
* ~~Nested Bundles (if i find time)~~

## Potential Future Work

* Expand WorldCell to support queries.
* Consider not allocating in the empty archetype on `world.spawn()`
    * ex: return something like EntityMutUninit, which turns into EntityMut after an `insert` or `insert_bundle` op
    * this actually regressed performance last time i tried it, but in theory it should be faster
* Optimize SparseSet::insert (see `PERF` comment on insert)
* Replace SparseArray `Option<T>` with T::MAX to cut down on branching
    * would enable cheaper get_unchecked() operations
* upstream fixedbitset optimizations
    * fixedbitset could be allocation free for small block counts (store blocks in a SmallVec)
    * fixedbitset could have a const constructor 
* Consider implementing Tags (archetype-specific by-value data that affects archetype identity) 
    * ex: ArchetypeA could have `[A, B, C]` table components and `[D(1)]` "tag" component. ArchetypeB could have `[A, B, C]` table components and a `[D(2)]` tag component. The archetypes are different, despite both having D tags because the value inside D is different.
    * this could potentially build on top of the `archetype.unique_components` added in this pr for resource storage.
* Consider reverting `all_tuples` proc macro in favor of the old `macro_rules` implementation
    * all_tuples is more flexible and produces cleaner documentation (the macro_rules version produces weird type parameter orders due to parser constraints)
    * but unfortunately all_tuples also appears to make Rust Analyzer sad/slow when working inside of `bevy_ecs` (does not affect user code)
* Consider "resource queries" and/or "mixed resource and entity component queries" as an alternative to WorldCell
    * this is basically just "systems" so maybe it's not worth it
* Add more world ops
    * `world.clear()`
    * `world.reserve<T: Bundle>(count: usize)`
 * Try using the old archetype allocation strategy (allocate new memory on resize and copy everything over). I expect this to improve batch insertion performance at the cost of unbatched performance. But thats just a guess. I'm not an allocation perf pro :)
 * Adapt Commands apis for consistency with new World apis 

## Benchmarks

key:

* `bevy_old`: bevy `main` branch
* `bevy`: this branch
* `_foreach`: uses an optimized for_each iterator
* ` _sparse`: uses sparse set storage (if unspecified assume table storage)
* `_system`: runs inside a system (if unspecified assume test happens via direct world ops)

### Simple Insert (from ecs_bench_suite)

![image](https://user-images.githubusercontent.com/2694663/109245573-9c3ce100-7795-11eb-9003-bfd41cd5c51f.png)

### Simpler Iter (from ecs_bench_suite)

![image](https://user-images.githubusercontent.com/2694663/109245795-ffc70e80-7795-11eb-92fb-3ffad09aabf7.png)

### Fragment Iter (from ecs_bench_suite)

![image](https://user-images.githubusercontent.com/2694663/109245849-0fdeee00-7796-11eb-8d25-eb6b7a682c48.png)

### Sparse Fragmented Iter

Iterate a query that matches 5 entities from a single matching archetype, but there are 100 unmatching archetypes

![image](https://user-images.githubusercontent.com/2694663/109245916-2b49f900-7796-11eb-9a8f-ed89c203f940.png)
 
### Schedule (from ecs_bench_suite)

![image](https://user-images.githubusercontent.com/2694663/109246428-1fab0200-7797-11eb-8841-1b2161e90fa4.png)

### Add Remove Component (from ecs_bench_suite)

![image](https://user-images.githubusercontent.com/2694663/109246492-39e4e000-7797-11eb-8985-2706bd0495ab.png)


### Add Remove Component Big

Same as the test above, but each entity has 5 "large" matrix components and 1 "large" matrix component is added and removed

![image](https://user-images.githubusercontent.com/2694663/109246517-449f7500-7797-11eb-835e-28b6790daeaa.png)


### Get Component

Looks up a single component value a large number of times

![image](https://user-images.githubusercontent.com/2694663/109246129-87ad1880-7796-11eb-9fcb-c38012aa7c70.png)
2021-03-05 07:54:35 +00:00
Zhixing Zhang
d9fb61d474 Wireframe Rendering Pipeline (#562)
This PR implements wireframe rendering.

Usage:

This is now ready as soon as #1401 gets merged.


Usage:

```rust
    app
        .insert_resource(WgpuOptions {
            name: Some("3d_scene"),
            features: WgpuFeatures::NON_FILL_POLYGON_MODE,
            ..Default::default()
        }) // To enable the NON_FILL_POLYGON_MODE feature
        .add_plugin(WireframePlugin)
        .run();

```

Now we just need to add the Wireframe component on an entity, and it'll draw. its wireframe.


We can also enable wireframe drawing globally by setting the global property in the `WireframeConfig` resource to `true`.



Co-authored-by: Zhixing Zhang <me@neoto.xin>
2021-03-04 01:23:24 +00:00
Alexander Sepity
4f1a65113d Fixed commands for coerced exclusive systems (#1531)
Fixes #1530.
2021-03-03 23:36:01 +00:00
François
1fcafc4210 Glb textures should use bevy_render to load images (#1454)
Fixes #1396 

<img width="1392" alt="Screenshot 2021-02-16 at 02 24 01" src="https://user-images.githubusercontent.com/8672791/108011774-1b991a80-7008-11eb-979e-6ebfc51fba3c.png">

Issue was that, when loading an image directly from its bytes in the binary glb file, it didn't follow the same flow as when loaded as a texture file. This PR removes the dependency to `image` from `bevy_gltf`, and load the image using `bevy_render` in all cases. I also added support for more mime types while there.

<img width="1392" alt="Screenshot 2021-02-16 at 02 44 56" src="https://user-images.githubusercontent.com/8672791/108011915-674bc400-7008-11eb-83d4-ded96a38919b.png">
2021-03-03 21:36:16 +00:00
Zhixing Zhang
6e14ed23bc Enable wgpu device limits (#1544)
Follow up on #547 and #1401 

Co-authored-by: Zhixing Zhang <me@neoto.xin>
2021-03-03 21:20:46 +00:00
François
6a0968b2ea convert grayscale images to rgb (#1524)
Fixes #1518 

Issue was that images loaded as [`ImageLumaA8`](https://docs.rs/image/0.23.13/image/enum.DynamicImage.html#variant.ImageLumaA8) (grayscale with alpha channel) from `image` were considered as [`Rg8Unorm`](https://docs.rs/wgpu/0.7.0/wgpu/enum.TextureFormat.html#variant.Rg8Unorm) (red green channels) from `wgpu`.
Same for `ImageLuma8` (grayscale) that was converted to `R8Unorm` (only red channel).

As `wgpu` doesn't seem to have grayscale texture formats, I converted the grayscale textures to rgba.
2021-03-03 21:20:45 +00:00
dependabot[bot]
319e75c7aa Update tracing-wasm requirement from 0.1 to 0.2 (#1539)
Updates the requirements on [tracing-wasm](https://github.com/storyscript/tracing-wasm) to permit the latest version.
<details>
<summary>Commits</summary>
<ul>
<li><a href="09a0d75c45"><code>09a0d75</code></a> Disable default features for dependencies and release 0.2.0</li>
<li><a href="bbeca396ed"><code>bbeca39</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/storyscript/tracing-wasm/issues/12">#12</a> from storyscript/readme-clarification</li>
<li><a href="e35b182232"><code>e35b182</code></a> add clarifying note to README.</li>
<li><a href="259e118e7f"><code>259e118</code></a> rustfmt</li>
<li><a href="f2099cfe5e"><code>f2099cf</code></a> Apply clippy suggestions</li>
<li><a href="fde480fa11"><code>fde480f</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/storyscript/tracing-wasm/issues/6">#6</a> from storyscript/config-builder</li>
<li><a href="ad9d4b1903"><code>ad9d4b1</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/storyscript/tracing-wasm/issues/7">#7</a> from storyscript/feat/default-level</li>
<li><a href="64fedbd267"><code>64fedbd</code></a> chore(config): change level to max_level</li>
<li><a href="7cb160a7a9"><code>7cb160a</code></a> feat(level): add default level in config from the builder</li>
<li><a href="a9e7f2a4b8"><code>a9e7f2a</code></a> WIP: Builder pattern for WASMLayerConfig</li>
<li>Additional commits viewable in <a href="https://github.com/storyscript/tracing-wasm/compare/0.1.0...v0.2.0">compare view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)


</details>
2021-03-03 21:01:41 +00:00
verzuz
b8961a957e enable wgpu device features (#547)
Should wait for https://github.com/bevyengine/bevy/pull/542 and new wgpu_rs release.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-03 20:07:26 +00:00
Zicklag
89217171b4 Add Sprite Flipping (#1407)
OK, here's my attempt at sprite flipping. There are a couple of points that I need review/help on, but I think the UX is about ideal:

```rust
        .spawn(SpriteBundle {
            material: materials.add(texture_handle.into()),
            sprite: Sprite {
                // Flip the sprite along the x axis
                flip: SpriteFlip { x: true, y: false },
                ..Default::default()
            },
            ..Default::default()
        });
```

Now for the issues. The big issue is that for some reason, when flipping the UVs on the sprite, there is a light "bleeding" or whatever you call it where the UV tries to sample past the texture boundry and ends up clipping. This is only noticed when resizing the window, though. You can see a screenshot below.

![image](https://user-images.githubusercontent.com/25393315/107098172-397aaa00-67d4-11eb-8e02-c90c820cd70e.png)

I am quite baffled why the texture sampling is overrunning like it is and could use some guidance if anybody knows what might be wrong.

The other issue, which I just worked around, is that I had to remove the `#[render_resources(from_self)]` annotation from the Spritesheet because the `SpriteFlip` render resource wasn't being picked up properly in the shader when using it. I'm not sure what the cause of that was, but by removing the annotation and re-organizing the shader inputs accordingly the problem was fixed.

I'm not sure if this is the most efficient way to do this or if there is a better way, but I wanted to try it out if only for the learning experience. Let me know what you think!
2021-03-03 19:26:45 +00:00
Daniel McNab
e61d7920e3 Add suffixes to diagnostics and other cleanup (#1505)
Also a few related clean ups to diagnostics
Old look (from the log_diagnostics_example):
<details>
<summary>Old look hidden to avoid clutter </summary>

![image](https://user-images.githubusercontent.com/36049421/108776774-bc349080-755a-11eb-8569-d4832abf6bc3.png)

</details>
New look: 

![image](https://user-images.githubusercontent.com/36049421/108776587-82638a00-755a-11eb-96eb-539026d59bcb.png)

In particular, notice that the width of the diagnostics has been significantly reduced - within vscode the value no longer wraps on my 1920 width monitor. The value is still 105 columns wide, so there is room for improvement however.
2021-03-03 03:43:15 +00:00
Carter Anderson
74cb13aa70 update libloading (#1543)
Alternative to #1418
2021-03-03 03:11:12 +00:00
Wouter Buckens
000dd4c1c2 Add docs & example for SystemParam (#1435)
It took me a little while to figure out how to use the `SystemParam` derive macro to easily create my own params. So I figured I'd add some docs and an example with what I learned.

- Fixed a bug in the `SystemParam` derive macro where it didn't detect the correct crate name when used in an example (no longer relevant, replaced by #1426 - see further)
- Added some doc comments and a short example code block in the docs for the `SystemParam` trait
- Added a more complete example with explanatory comments in examples
2021-03-03 03:11:11 +00:00
Archina
b8a0ab01ba add to lower case to make asset loading case insensitive (#1427)
This should fix bug #1425
2021-03-03 03:11:10 +00:00
Digital Seven
8dcba7f4a1 Add Window Resize Constraints (#1409)
You should be able to set the minimum and maximum desired resolution of a system window.
This also fixes a bug on Windows operating system: When you try to resize to 0 on the height it crashes.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-03 02:56:50 +00:00
TheRawMeatball
87ada5b589 Get rid of ChangedRes (#1313)
This replaces `ChangedRes` with simple associated methods that return the same info, but don't block execution. Also, since ChangedRes was infectious and was the only reason `FetchSystemParam::get_params` and `System::run_unsafe` returned `Option`s, their implementation could be simplified after this PR is merged, or as part of it with a future commit.
2021-03-03 01:59:40 +00:00
Carter Anderson
e035ce1f2a remove dev-dependencies from bevy_ecs (#1542)
These are no longer used, increase build times, and currently break builds due to a broken criterion dependency on nightly.
2021-03-03 01:39:02 +00:00
Jakob Hellermann
bc4fe9b186 keep track of type name in NodeState (#1444)
Adds the original type_name to `NodeState`, enabling plugins like [this](https://github.com/jakobhellermann/bevy_mod_debugdump).
This does increase the `NodeState` type by 16 bytes, but it is already 176 so it's not that big of an increase.
2021-02-22 09:15:29 +00:00
Jakob Hellermann
a1ec684131 fix bevy_ecs macro path handling (#1426)
- It now doesn't search in the dev-dependencies anymore
- and the behaviour is consistent for derive_bundle and derive_system_param
2021-02-22 09:15:27 +00:00
Jonas Matser
72f2a7b581 Add getter for RenderGraph Node uuid (#1499)
`RenderGraph` errors only give the `Uuid` of the node. So for my graphviz dot based visualization of the `RenderGraph` I really wanted to show it to the user. I think it makes sense to have it accessible for at least debugging purposes.
2021-02-22 08:59:14 +00:00
Nathan Stocks
13b602ee3f Xtask CI (#1387)
This PR is easiest to review commit by commit.

Followup on https://github.com/bevyengine/bevy/pull/1309#issuecomment-767310084

- [x] Switch from a bash script to an xtask rust workspace member.
  - Results in ~30s longer CI due to compilation of the xtask itself
  - Enables Bevy contributors on any platform to run `cargo ci` to run linting -- if the default available Rust is the same version as on CI, then the command should give an identical result.
- [x] Use the xtask from official CI so there's only one place to update.
- [x] Bonus: Run clippy on the _entire_ workspace (existing CI setup was missing the `--workspace` flag
  - [x] Clean up newly-exposed clippy errors 

~#1388 builds on this to clean up newly discovered clippy errors -- I thought it might be nicer as a separate PR.~  Nope, merged it into this one so CI would pass.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-02-22 08:42:19 +00:00
MinerSebas
c9f19d8663 Cleanup of Markdown Files and add CI Checking (#1463)
I have run the VSCode Extension [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) on all Markdown Files in the Repo.
The provided Rules are documented here: https://github.com/DavidAnson/markdownlint/blob/v0.23.1/doc/Rules.md

Rules I didn't follow/fix:
* MD024/no-duplicate-heading
  * Changelog: Here Heading will always repeat.
  * Examples Readme: Platform-specific documentation should be symmetrical.
* MD025/single-title
* MD026/no-trailing-punctuation
  * Caused by the ! in "Hello, World!".
* MD033/no-inline-html
  * The plugins_guidlines file does need HTML, so the shown badges aren't downscaled too much.
* ~~MD036/no-emphasis-as-heading:~~
  * ~~This Warning only Appears in the Github Issue Templates and can be ignored.~~
* ~~MD041/first-line-heading~~
  * ~~Only appears in the Readme for the AlienCake example Assets, which is unimportant.~~

---

I also sorted the Examples in the Readme and Cargo.toml in this order/Priority:
* Topic/Folder
* Introductionary Examples
* Alphabetical Order

The explanation for each case, where it isn't Alphabetical :
* Diagnostics
  * log_diagnostics: The usage of inbuild Diagnostics is more important than creating your own.
* ECS (Entity Component System)
  * ecs_guide: The guide should be read, before diving into other Features.
* Reflection
  * reflection: Basic Explanation should be read, before more advanced Topics.
* WASM Examples
  * hello_wasm: It's "Hello, World!".
2021-02-22 04:50:05 +00:00
Jakob Hellermann
e5b0c65c86 rename bevy_ui::node module so that bevy_ui::render::node isn't shadowed (#1464)
Previously the `mod node` shadowed the `pub use render::node`, and `CAMERA_UI`, `NODE` and `UI_PASS` constants couldn't be used.
2021-02-22 04:33:33 +00:00
Alexander Krivács Schrøder
e76d6566d7 Add backend feature metadata to make bevy_winit build on docs.rs again (#1430)
The `bevy_winit` crate hasn't been able to build on docs.rs [since 0.2.1](https://docs.rs/crate/bevy_winit/0.4.0). This PR restores the ability of docs.rs to build `bevy_winit` again.

(The choice of backend is essentially arbitrary, but choosing one *is required* for the crate to build)
2021-02-22 04:15:50 +00:00
maxwellodri
ba2226a487 Added Hash and Deserialize/Serialize traits to ElementState (#1447)
This adds traits that are already implemented for KeyCodes/Mouse Button etc.
2021-02-22 03:59:37 +00:00
Jakob Hellermann
cd688d7a41 fix rustdoc warnings (#1437)
Every warning is fixed except for 
b39df9a8d2/crates/bevy_render/src/texture/texture_descriptor.rs (L61)
because I didn't know what the required feature is.
I opened https://github.com/gfx-rs/wgpu/issues/1213 for that.
2021-02-22 03:59:35 +00:00
Alec Deason
97a78c3698 Make vertex buffers optional (#1485)
For some cases, like driving a full screen fragment shader, it is sometimes convenient to not have to create and upload a mesh because the necessary vertices are simple to synthesize in the vertex shader. Bevy's existing pipeline compiler assumes that there will always be a vertex buffer. This PR changes that such that vertex buffer descriptor is only added to the pipeline layout if there are vertex attributes in the shader.
2021-02-22 03:43:27 +00:00
Niklas Eicker
2e3af84590 Add remove resource to commands (#1478)
resolves #1468 

Co-authored-by: Niklas Eicker <git@nikl.me>
2021-02-22 03:43:26 +00:00
Jakob Hellermann
f73c6d18ef better error message on failed derive (#1491)
Before, when deriving `SystemLabel` for a type without `Clone`, the error message was:
```
the trait `SystemLabel` is not implemented for `&TransformSystem`
```
Now it is
```
the trait `Clone` is not implemented for `TransformSystem`
```
which directly shows what's needed to fix the problem.
2021-02-22 03:23:57 +00:00
Renato Caldas
3319195f90 Implement Reflect for integer glam vectors. (#1455)
This is a very simple change that allows the (reflected) use of integer glam vectors (UVec2 for instance) in components.
2021-02-19 22:25:07 +00:00
Yoh Deadfall
578a5b1b88 Moved benchmarks to a single place (#1477)
Closes #1472.
2021-02-19 22:11:00 +00:00
TheRawMeatball
fa73036f9d
Extend AppBuilder api with add_system_set and similar methods (#1453)
Extend AppBuilder api with `add_system_set` and similar methods
2021-02-19 11:36:34 -08:00
Niklas Eicker
884dc46ffe
Replace right/up/forward and counter parts with local_x/local_y and local_z (#1476) 2021-02-19 10:51:26 -08:00
Alexander Sepity
c2a427f1a3
Non-string labels (#1423 continued) (#1473)
Non-string labels
2021-02-18 13:20:37 -08:00
Alexander Sepity
82d0e84a5c
Explicit execution order ambiguities API (#1469)
Explicit execution order ambiguities API.
2021-02-18 11:30:13 -08:00
François
a5d2501b75
add labels and ordering for transform and parent systems in POST_UPDATE stage (#1456) 2021-02-16 18:00:12 -08:00
Alice Cecile
a895256925
Better documentation for explicit dependencies (#1428)
* More in-depth ambiguity checker docs
* Updated ecs_guide example with explicit dependencies
2021-02-16 11:18:08 -08:00
Alexander Sepity
d021a3c374
Relaxed bounds on NonSend. (#1448) 2021-02-14 16:20:16 -08:00
Hans W. Uhlig
f8292ccf7e
Simple Implementation to address #1327 by adding a focused field to the window and related system (#1386)
* Simple Implementation to address #1327 by adding a focused field to the window and related system

* Changing Window update function from bevy_window to bevy_winit.

* Removing unused imports.
2021-02-12 21:32:32 -08:00
Wouter Buckens
b39df9a8d2
Fix missing paths in ECS SystemParam derive macro (#1434) 2021-02-11 15:59:11 -08:00
Daniel McNab
3a32a21fe9
Fix clippy stuff (#1433)
* Fix clippy stuff

* Add comments explaining inconsistency

Also explains that the code is unused
2021-02-11 14:09:01 -08:00
Alexander Sepity
d5a7330431
System sets and parallel executor v2 (#1144)
System sets and parallel executor v2
2021-02-09 12:14:10 -08:00
Carter Anderson
b71ada0346
revert default vsync mode to Fifo (#1416)
the mailbox option doesn't do framelimiting on some devices. we need to rely on vsync for framelimiting until bevy supports framelimiting internally. #1343
2021-02-08 18:13:37 -08:00
MinerSebas
3475a64a2c
More Doctest changes (#1405)
* Add system() to DocTests

* Hide use statements
2021-02-05 17:44:34 -08:00
szunami
c87d4c110f
Update example system in documentation (#1403)
The existing snippet fails to compile with:

```
no method named `system` found for fn item `fn(bevy::prelude::Commands) {example_system}` in the current scope
```
2021-02-05 12:57:47 -08:00
Rob Parrett
110ff77db9
Fix regression causing "flipped" sprites to be invisible (#1399)
Regressed in 81809c71ce
2021-02-04 20:17:11 -08:00
davier
5b115397ba
Fix Reflect serialization of tuple structs (#1366)
* Fix  DynamicTupleStruct::type_name()

* Fix type_name() for DynamicList, DynamicMap  and DynamicTuple
2021-02-02 13:57:26 -08:00
Jakob Hellermann
4796ea8d22
move texture_to_image and image_to_texture into new module (#1381)
The `Texture::convert` function previously was only compiled when
one of the image format features (`png`, `jpeg` etc.) were enabled.
The `bevy_sprite` crate needs this function though, which led
to compilation errors when using `cargo check --no-default-features
--features render`.

Now the `convert` function has no features and the `texture_to_image`
and `image_to_texture` utilites functions are in an unconditionally
compiled module.
2021-02-02 13:25:16 -08:00
dependabot[bot]
1ca8ce4a79
Update crossbeam-utils requirement from 0.7.2 to 0.8.1 (#959)
Updates the requirements on [crossbeam-utils](https://github.com/crossbeam-rs/crossbeam) to permit the latest version.
- [Release notes](https://github.com/crossbeam-rs/crossbeam/releases)
- [Changelog](https://github.com/crossbeam-rs/crossbeam/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crossbeam-rs/crossbeam/compare/crossbeam-0.7.2...crossbeam-utils-0.8.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-02-01 13:51:44 -08:00
dependabot[bot]
05b8b5c8c2
Update crossbeam-channel requirement from 0.4.4 to 0.5.0 (#668)
Updates the requirements on [crossbeam-channel](https://github.com/crossbeam-rs/crossbeam) to permit the latest version.
- [Release notes](https://github.com/crossbeam-rs/crossbeam/releases)
- [Changelog](https://github.com/crossbeam-rs/crossbeam/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crossbeam-rs/crossbeam/compare/crossbeam-channel-0.4.4...crossbeam-channel-0.5.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-02-01 13:30:38 -08:00
dependabot[bot]
89df94e690
Update ahash requirement from 0.6.1 to 0.7.0 (#1370)
Updates the requirements on [ahash](https://github.com/tkaitchuck/ahash) to permit the latest version.
- [Release notes](https://github.com/tkaitchuck/ahash/releases)
- [Commits](https://github.com/tkaitchuck/ahash/commits)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-02-01 13:29:54 -08:00
François
6b8f8a7ed0
Texture atlas format and conversion (#1365)
* can specify texture format for a texture atlas
* add automatic conversion
2021-02-01 11:30:11 -08:00
Zhixing Zhang
81809c71ce
Update to wgpu-rs 0.7 (#542)
Update to wgpu-rs 0.7
2021-01-31 20:06:42 -08:00
Will Crichton
e6e23fdfa9
Add support for gltf::Material::unlit (#1341)
* Add support for gltf::Material::unlit
2021-01-31 17:13:16 -08:00
davier
1d3dfd3938
Fix Interaction not resetting to None sometimes (#1315)
* Fix Interaction getting stuck when pressing and releasing mouse button in one frame

* Fix Interaction not resetting in some cases with FocusPolicy::Pass
2021-01-31 17:03:25 -08:00
Nathan Stocks
0867dc76a3
Use Cow<'static, str> in Name (#1308)
* Implement Name { name } as Cow<'static, str>
* Attempt impl Reflect for Cow<'static, str.>
2021-01-31 16:35:23 -08:00
Jasen Borisov
7d065eeb71
3D OrthographicProjection improvements + new example (#1361)
* use `length_squared` for visible entities

* ortho projection 2d/3d different depth calculation

* use ScalingMode::FixedVertical for 3d ortho

* new example: 3d orthographic
2021-01-31 16:22:06 -08:00
François
83e30a841a
bind the labeled asset type to the actual loaded asset (#1363)
bind the labeled asset type to the actual loaded asset
2021-01-31 13:54:15 -08:00
Zicklag
bff44f76ec
Fix Un-Renamed add_resource Compile Error (#1357) 2021-01-30 13:32:46 -08:00
Alice Cecile
6f5a4d9deb
Rename add_resource to insert_resource (#1356)
* Renamed add_resource to insert_resource

* Changed usage of add_resource to insert_resource

* Renamed add_thread_local_resource
2021-01-30 12:55:13 -08:00
Daniel McNab
b922a3ec60
Update init_resource to not overwrite (#1349)
Update init_resource to not overwrite
2021-01-30 12:48:11 -08:00
Renato Caldas
8e0e4223e5
Improve clarity of WindowTextureNode and WindowSwapchainNode error messages (#1355)
Improve clarity of WindowTextureNode and WindowSwapchainNode error messages
2021-01-30 12:47:27 -08:00
Telzhaak
61c9a40fde
[Bugfix] add_stage now checks Stage existence (#1346)
add_stage now checks stage existence
2021-01-30 12:10:14 -08:00
Jasen Borisov
57f9ac18d7
OrthographicProjection scaling mode + camera bundle refactoring (#400)
* add normalized orthographic projection

* custom scale for ScaledOrthographicProjection

* allow choosing base axis for ScaledOrthographicProjection

* cargo fmt

* add general (scaled) orthographic camera bundle

FIXME: does the same "far" trick from Camera2DBundle make any sense here?

* fixes

* camera bundles: rename and new ortho constructors

* unify orthographic projections

* give PerspectiveCameraBundle constructors like those of OrthographicCameraBundle

* update examples with new camera bundle syntax

* rename CameraUiBundle to UiCameraBundle

* update examples

* ScalingMode::None

* remove extra blank lines

* sane default bounds for orthographic projection

* fix alien_cake_addict example

* reorder ScalingMode enum variants

* ios example fix
2021-01-30 02:31:03 -08:00
Zicklag
af67231567
Fix Bug in Asset Server Error Message Formatter (#1340) 2021-01-29 13:26:21 -08:00
Zicklag
cc9ed52ea7
Update Scene Example to Use scn.ron File (#1339) 2021-01-28 14:14:50 -08:00
Jakob Hellermann
f3306e5490
implement Debug for Flags regardless of underlying type (#1323) 2021-01-26 11:58:46 -08:00
davier
528c2858e0
Expose more info in PositionedGlyph (#1319) 2021-01-26 11:53:55 -08:00
Zicklag
b6485ccf29
Process Asset File Extensions With Multiple Dots (#1277)
Process Asset File Extensions With Multiple Dots
Fixes #1276
2021-01-25 12:37:23 -08:00
davier
5edf2d2395
Prevent ImageBundles from causing constant layout recalculations (#1299)
Prevent ImageBundles from causing constant layout recalculations
2021-01-24 21:00:20 -08:00
Toniman20
32acbfb632
Added set_minimized and set_position to Window (#1292)
Added `set_minimized` and `set_position` to `Window`
2021-01-24 20:06:06 -08:00
RedlineTriad
7e368e0b78
Add more transform relative vectors (#1300)
* Add more transform relative vectors (#1298)

* Add inverse of relative directions (#1298)
2021-01-24 20:05:30 -08:00
tigregalis
40b5bbd028
Rich text (#1245)
Rich text support (different fonts / styles within the same text section)
2021-01-24 17:07:43 -08:00
Will Crichton
3d0c4e380c
Don't panic on error when loading assets (#1286)
* Don't panic on IO errors
* Better formatting for asset server errors
2021-01-23 13:23:16 -08:00
Tomasz Sterna
f2b73eaa8a
Fix documentation comment for State::overwrite_next (#1291) 2021-01-23 13:18:28 -08:00
Will Crichton
7166a28baf
Enable dynamic mutable access to component data (#1284)
* Enable dynamic mutable access to component data

* Add clippy allowance, more documentation
2021-01-22 15:15:08 -08:00
Will Crichton
ebcab3638a
Change Name to take Into<String> instead of String (#1283) 2021-01-22 14:13:26 -08:00
Daniel McNab
6bd5ec8404
Change to using add_run_criteria (#1282) 2021-01-22 14:09:14 -08:00
Renato Caldas
0a39c81be6
Add support for reading from mapped buffers (#1274)
* Add support for mapping buffers for reading.

* Add support for reading from a mapped buffer.
2021-01-21 17:53:43 -08:00
Aevyrie
18e4fa8cdf
world coords to screen space (#1258)
Add Camera::world_to_screen to convert world coordinates to screen space
2021-01-21 17:49:29 -08:00
TheRawMeatball
f15d62c0f1
More types (#1267) 2021-01-21 16:05:23 -08:00
bjorn3
7aefd727f6
Use valid keys to initialize AHasher in FixedState (#1268)
Using 0 as keys causes the hasher to get stuck
2021-01-20 14:24:57 -08:00