2022-05-16 13:53:20 +00:00
|
|
|
//! Shows multiple transformations of objects.
|
|
|
|
|
2022-03-15 05:49:49 +00:00
|
|
|
use bevy::prelude::*;
|
|
|
|
|
|
|
|
use std::f32::consts::PI;
|
|
|
|
|
|
|
|
// A struct for additional data of for a moving cube.
|
|
|
|
#[derive(Component)]
|
|
|
|
struct CubeState {
|
|
|
|
start_pos: Vec3,
|
|
|
|
move_speed: f32,
|
|
|
|
turn_speed: f32,
|
|
|
|
}
|
|
|
|
|
|
|
|
// A struct adding information to a scalable entity,
|
|
|
|
// that will be stationary at the center of the scene.
|
|
|
|
#[derive(Component)]
|
|
|
|
struct Center {
|
|
|
|
max_size: f32,
|
|
|
|
min_size: f32,
|
|
|
|
scale_factor: f32,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
App::new()
|
|
|
|
.add_plugins(DefaultPlugins)
|
|
|
|
.add_startup_system(setup)
|
|
|
|
.add_system(move_cube)
|
|
|
|
.add_system(rotate_cube)
|
|
|
|
.add_system(scale_down_sphere_proportional_to_cube_travel_distance)
|
|
|
|
.run();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Startup system to setup the scene and spawn all relevant entities.
|
|
|
|
fn setup(
|
|
|
|
mut commands: Commands,
|
|
|
|
mut meshes: ResMut<Assets<Mesh>>,
|
|
|
|
mut materials: ResMut<Assets<StandardMaterial>>,
|
|
|
|
) {
|
|
|
|
// Add an object (sphere) for visualizing scaling.
|
|
|
|
commands
|
|
|
|
.spawn_bundle(PbrBundle {
|
|
|
|
mesh: meshes.add(Mesh::from(shape::Icosphere {
|
|
|
|
radius: 3.0,
|
|
|
|
subdivisions: 32,
|
|
|
|
})),
|
|
|
|
material: materials.add(Color::YELLOW.into()),
|
|
|
|
transform: Transform::from_translation(Vec3::ZERO),
|
2022-06-07 02:16:47 +00:00
|
|
|
..default()
|
2022-03-15 05:49:49 +00:00
|
|
|
})
|
|
|
|
.insert(Center {
|
|
|
|
max_size: 1.0,
|
|
|
|
min_size: 0.1,
|
|
|
|
scale_factor: 0.05,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Add the cube to visualize rotation and translation.
|
|
|
|
// This cube will circle around the center_sphere
|
|
|
|
// by changing its rotation each frame and moving forward.
|
|
|
|
// Define a start transform for an orbiting cube, that's away from our central object (sphere)
|
|
|
|
// and rotate it so it will be able to move around the sphere and not towards it.
|
|
|
|
let angle_90 = PI / 2.0;
|
2022-07-01 03:58:54 +00:00
|
|
|
let cube_spawn =
|
|
|
|
Transform::from_translation(Vec3::Z * -10.0).with_rotation(Quat::from_rotation_y(angle_90));
|
2022-03-15 05:49:49 +00:00
|
|
|
commands
|
|
|
|
.spawn_bundle(PbrBundle {
|
|
|
|
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
|
|
|
|
material: materials.add(Color::WHITE.into()),
|
|
|
|
transform: cube_spawn,
|
2022-06-07 02:16:47 +00:00
|
|
|
..default()
|
2022-03-15 05:49:49 +00:00
|
|
|
})
|
|
|
|
.insert(CubeState {
|
|
|
|
start_pos: cube_spawn.translation,
|
|
|
|
move_speed: 2.0,
|
|
|
|
turn_speed: 0.2,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Spawn a camera looking at the entities to show what's happening in this example.
|
Camera Driven Rendering (#4745)
This adds "high level camera driven rendering" to Bevy. The goal is to give users more control over what gets rendered (and where) without needing to deal with render logic. This will make scenarios like "render to texture", "multiple windows", "split screen", "2d on 3d", "3d on 2d", "pass layering", and more significantly easier.
Here is an [example of a 2d render sandwiched between two 3d renders (each from a different perspective)](https://gist.github.com/cart/4fe56874b2e53bc5594a182fc76f4915):
![image](https://user-images.githubusercontent.com/2694663/168411086-af13dec8-0093-4a84-bdd4-d4362d850ffa.png)
Users can now spawn a camera, point it at a RenderTarget (a texture or a window), and it will "just work".
Rendering to a second window is as simple as spawning a second camera and assigning it to a specific window id:
```rust
// main camera (main window)
commands.spawn_bundle(Camera2dBundle::default());
// second camera (other window)
commands.spawn_bundle(Camera2dBundle {
camera: Camera {
target: RenderTarget::Window(window_id),
..default()
},
..default()
});
```
Rendering to a texture is as simple as pointing the camera at a texture:
```rust
commands.spawn_bundle(Camera2dBundle {
camera: Camera {
target: RenderTarget::Texture(image_handle),
..default()
},
..default()
});
```
Cameras now have a "render priority", which controls the order they are drawn in. If you want to use a camera's output texture as a texture in the main pass, just set the priority to a number lower than the main pass camera (which defaults to `0`).
```rust
// main pass camera with a default priority of 0
commands.spawn_bundle(Camera2dBundle::default());
commands.spawn_bundle(Camera2dBundle {
camera: Camera {
target: RenderTarget::Texture(image_handle.clone()),
priority: -1,
..default()
},
..default()
});
commands.spawn_bundle(SpriteBundle {
texture: image_handle,
..default()
})
```
Priority can also be used to layer to cameras on top of each other for the same RenderTarget. This is what "2d on top of 3d" looks like in the new system:
```rust
commands.spawn_bundle(Camera3dBundle::default());
commands.spawn_bundle(Camera2dBundle {
camera: Camera {
// this will render 2d entities "on top" of the default 3d camera's render
priority: 1,
..default()
},
..default()
});
```
There is no longer the concept of a global "active camera". Resources like `ActiveCamera<Camera2d>` and `ActiveCamera<Camera3d>` have been replaced with the camera-specific `Camera::is_active` field. This does put the onus on users to manage which cameras should be active.
Cameras are now assigned a single render graph as an "entry point", which is configured on each camera entity using the new `CameraRenderGraph` component. The old `PerspectiveCameraBundle` and `OrthographicCameraBundle` (generic on camera marker components like Camera2d and Camera3d) have been replaced by `Camera3dBundle` and `Camera2dBundle`, which set 3d and 2d default values for the `CameraRenderGraph` and projections.
```rust
// old 3d perspective camera
commands.spawn_bundle(PerspectiveCameraBundle::default())
// new 3d perspective camera
commands.spawn_bundle(Camera3dBundle::default())
```
```rust
// old 2d orthographic camera
commands.spawn_bundle(OrthographicCameraBundle::new_2d())
// new 2d orthographic camera
commands.spawn_bundle(Camera2dBundle::default())
```
```rust
// old 3d orthographic camera
commands.spawn_bundle(OrthographicCameraBundle::new_3d())
// new 3d orthographic camera
commands.spawn_bundle(Camera3dBundle {
projection: OrthographicProjection {
scale: 3.0,
scaling_mode: ScalingMode::FixedVertical,
..default()
}.into(),
..default()
})
```
Note that `Camera3dBundle` now uses a new `Projection` enum instead of hard coding the projection into the type. There are a number of motivators for this change: the render graph is now a part of the bundle, the way "generic bundles" work in the rust type system prevents nice `..default()` syntax, and changing projections at runtime is much easier with an enum (ex for editor scenarios). I'm open to discussing this choice, but I'm relatively certain we will all come to the same conclusion here. Camera2dBundle and Camera3dBundle are much clearer than being generic on marker components / using non-default constructors.
If you want to run a custom render graph on a camera, just set the `CameraRenderGraph` component:
```rust
commands.spawn_bundle(Camera3dBundle {
camera_render_graph: CameraRenderGraph::new(some_render_graph_name),
..default()
})
```
Just note that if the graph requires data from specific components to work (such as `Camera3d` config, which is provided in the `Camera3dBundle`), make sure the relevant components have been added.
Speaking of using components to configure graphs / passes, there are a number of new configuration options:
```rust
commands.spawn_bundle(Camera3dBundle {
camera_3d: Camera3d {
// overrides the default global clear color
clear_color: ClearColorConfig::Custom(Color::RED),
..default()
},
..default()
})
commands.spawn_bundle(Camera3dBundle {
camera_3d: Camera3d {
// disables clearing
clear_color: ClearColorConfig::None,
..default()
},
..default()
})
```
Expect to see more of the "graph configuration Components on Cameras" pattern in the future.
By popular demand, UI no longer requires a dedicated camera. `UiCameraBundle` has been removed. `Camera2dBundle` and `Camera3dBundle` now both default to rendering UI as part of their own render graphs. To disable UI rendering for a camera, disable it using the CameraUi component:
```rust
commands
.spawn_bundle(Camera3dBundle::default())
.insert(CameraUi {
is_enabled: false,
..default()
})
```
## Other Changes
* The separate clear pass has been removed. We should revisit this for things like sky rendering, but I think this PR should "keep it simple" until we're ready to properly support that (for code complexity and performance reasons). We can come up with the right design for a modular clear pass in a followup pr.
* I reorganized bevy_core_pipeline into Core2dPlugin and Core3dPlugin (and core_2d / core_3d modules). Everything is pretty much the same as before, just logically separate. I've moved relevant types (like Camera2d, Camera3d, Camera3dBundle, Camera2dBundle) into their relevant modules, which is what motivated this reorganization.
* I adapted the `scene_viewer` example (which relied on the ActiveCameras behavior) to the new system. I also refactored bits and pieces to be a bit simpler.
* All of the examples have been ported to the new camera approach. `render_to_texture` and `multiple_windows` are now _much_ simpler. I removed `two_passes` because it is less relevant with the new approach. If someone wants to add a new "layered custom pass with CameraRenderGraph" example, that might fill a similar niche. But I don't feel much pressure to add that in this pr.
* Cameras now have `target_logical_size` and `target_physical_size` fields, which makes finding the size of a camera's render target _much_ simpler. As a result, the `Assets<Image>` and `Windows` parameters were removed from `Camera::world_to_screen`, making that operation much more ergonomic.
* Render order ambiguities between cameras with the same target and the same priority now produce a warning. This accomplishes two goals:
1. Now that there is no "global" active camera, by default spawning two cameras will result in two renders (one covering the other). This would be a silent performance killer that would be hard to detect after the fact. By detecting ambiguities, we can provide a helpful warning when this occurs.
2. Render order ambiguities could result in unexpected / unpredictable render results. Resolving them makes sense.
## Follow Up Work
* Per-Camera viewports, which will make it possible to render to a smaller area inside of a RenderTarget (great for something like splitscreen)
* Camera-specific MSAA config (should use the same "overriding" pattern used for ClearColor)
* Graph Based Camera Ordering: priorities are simple, but they make complicated ordering constraints harder to express. We should consider adopting a "graph based" camera ordering model with "before" and "after" relationships to other cameras (or build it "on top" of the priority system).
* Consider allowing graphs to run subgraphs from any nest level (aka a global namespace for graphs). Right now the 2d and 3d graphs each need their own UI subgraph, which feels "fine" in the short term. But being able to share subgraphs between other subgraphs seems valuable.
* Consider splitting `bevy_core_pipeline` into `bevy_core_2d` and `bevy_core_3d` packages. Theres a shared "clear color" dependency here, which would need a new home.
2022-06-02 00:12:17 +00:00
|
|
|
commands.spawn_bundle(Camera3dBundle {
|
2022-03-15 05:49:49 +00:00
|
|
|
transform: Transform::from_xyz(0.0, 10.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
|
2022-06-07 02:16:47 +00:00
|
|
|
..default()
|
2022-03-15 05:49:49 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// Add a light source for better 3d visibility.
|
|
|
|
commands.spawn_bundle(PointLightBundle {
|
|
|
|
transform: Transform::from_translation(Vec3::ONE * 3.0),
|
2022-06-07 02:16:47 +00:00
|
|
|
..default()
|
2022-03-15 05:49:49 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// This system will move the cube forward.
|
|
|
|
fn move_cube(mut cubes: Query<(&mut Transform, &mut CubeState)>, timer: Res<Time>) {
|
2022-07-11 15:28:50 +00:00
|
|
|
for (mut transform, cube) in &mut cubes {
|
2022-03-15 05:49:49 +00:00
|
|
|
// Move the cube forward smoothly at a given move_speed.
|
|
|
|
let forward = transform.forward();
|
|
|
|
transform.translation += forward * cube.move_speed * timer.delta_seconds();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// This system will rotate the cube slightly towards the center_sphere.
|
|
|
|
// Due to the forward movement the resulting movement
|
|
|
|
// will be a circular motion around the center_sphere.
|
|
|
|
fn rotate_cube(
|
|
|
|
mut cubes: Query<(&mut Transform, &mut CubeState), Without<Center>>,
|
|
|
|
center_spheres: Query<&Transform, With<Center>>,
|
|
|
|
timer: Res<Time>,
|
|
|
|
) {
|
|
|
|
// Calculate the point to circle around. (The position of the center_sphere)
|
|
|
|
let mut center: Vec3 = Vec3::ZERO;
|
2022-07-11 15:28:50 +00:00
|
|
|
for sphere in ¢er_spheres {
|
2022-03-15 05:49:49 +00:00
|
|
|
center += sphere.translation;
|
|
|
|
}
|
|
|
|
// Update the rotation of the cube(s).
|
2022-07-11 15:28:50 +00:00
|
|
|
for (mut transform, cube) in &mut cubes {
|
2022-03-15 05:49:49 +00:00
|
|
|
// Calculate the rotation of the cube if it would be looking at the sphere in the center.
|
|
|
|
let look_at_sphere = transform.looking_at(center, transform.local_y());
|
|
|
|
// Interpolate between the current rotation and the fully turned rotation
|
|
|
|
// when looking a the sphere, with a given turn speed to get a smooth motion.
|
|
|
|
// With higher speed the curvature of the orbit would be smaller.
|
|
|
|
let incremental_turn_weight = cube.turn_speed * timer.delta_seconds();
|
|
|
|
let old_rotation = transform.rotation;
|
|
|
|
transform.rotation = old_rotation.lerp(look_at_sphere.rotation, incremental_turn_weight);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// This system will scale down the sphere in the center of the scene
|
|
|
|
// according to the traveling distance of the orbiting cube(s) from their start position(s).
|
|
|
|
fn scale_down_sphere_proportional_to_cube_travel_distance(
|
|
|
|
cubes: Query<(&Transform, &CubeState), Without<Center>>,
|
|
|
|
mut centers: Query<(&mut Transform, &Center)>,
|
|
|
|
) {
|
|
|
|
// First we need to calculate the length of between
|
|
|
|
// the current position of the orbiting cube and the spawn position.
|
|
|
|
let mut distances = 0.0;
|
2022-07-11 15:28:50 +00:00
|
|
|
for (cube_transform, cube_state) in &cubes {
|
2022-03-15 05:49:49 +00:00
|
|
|
distances += (cube_state.start_pos - cube_transform.translation).length();
|
|
|
|
}
|
|
|
|
// Now we use the calculated value to scale the sphere in the center accordingly.
|
2022-07-11 15:28:50 +00:00
|
|
|
for (mut transform, center) in &mut centers {
|
2022-03-15 05:49:49 +00:00
|
|
|
// Calculate the new size from the calculated distances and the centers scale_factor.
|
|
|
|
// Since we want to have the sphere at its max_size at the cubes spawn location we start by
|
|
|
|
// using the max_size as start value and subtract the distances scaled by a scaling factor.
|
|
|
|
let mut new_size: f32 = center.max_size - center.scale_factor * distances;
|
|
|
|
|
|
|
|
// The new size should also not be smaller than the centers min_size.
|
|
|
|
// Therefore the max value out of (new_size, center.min_size) is used.
|
|
|
|
new_size = new_size.max(center.min_size);
|
|
|
|
|
|
|
|
// Now scale the sphere uniformly in all directions using new_size.
|
|
|
|
// Here Vec3:splat is used to create a vector with new_size in x, y and z direction.
|
|
|
|
transform.scale = Vec3::splat(new_size);
|
|
|
|
}
|
|
|
|
}
|