
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):  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.
400 lines
13 KiB
Rust
400 lines
13 KiB
Rust
//! Eat the cakes. Eat them all. An example 3D game.
|
|
|
|
use bevy::{ecs::schedule::SystemSet, prelude::*, time::FixedTimestep};
|
|
use rand::Rng;
|
|
|
|
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
|
|
enum GameState {
|
|
Playing,
|
|
GameOver,
|
|
}
|
|
|
|
fn main() {
|
|
App::new()
|
|
.init_resource::<Game>()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_state(GameState::Playing)
|
|
.add_startup_system(setup_cameras)
|
|
.add_system_set(SystemSet::on_enter(GameState::Playing).with_system(setup))
|
|
.add_system_set(
|
|
SystemSet::on_update(GameState::Playing)
|
|
.with_system(move_player)
|
|
.with_system(focus_camera)
|
|
.with_system(rotate_bonus)
|
|
.with_system(scoreboard_system),
|
|
)
|
|
.add_system_set(SystemSet::on_exit(GameState::Playing).with_system(teardown))
|
|
.add_system_set(SystemSet::on_enter(GameState::GameOver).with_system(display_score))
|
|
.add_system_set(SystemSet::on_update(GameState::GameOver).with_system(gameover_keyboard))
|
|
.add_system_set(SystemSet::on_exit(GameState::GameOver).with_system(teardown))
|
|
.add_system_set(
|
|
SystemSet::new()
|
|
.with_run_criteria(FixedTimestep::step(5.0))
|
|
.with_system(spawn_bonus),
|
|
)
|
|
.add_system(bevy::window::close_on_esc)
|
|
.run();
|
|
}
|
|
|
|
struct Cell {
|
|
height: f32,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Player {
|
|
entity: Option<Entity>,
|
|
i: usize,
|
|
j: usize,
|
|
move_cooldown: Timer,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Bonus {
|
|
entity: Option<Entity>,
|
|
i: usize,
|
|
j: usize,
|
|
handle: Handle<Scene>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Game {
|
|
board: Vec<Vec<Cell>>,
|
|
player: Player,
|
|
bonus: Bonus,
|
|
score: i32,
|
|
cake_eaten: u32,
|
|
camera_should_focus: Vec3,
|
|
camera_is_focus: Vec3,
|
|
}
|
|
|
|
const BOARD_SIZE_I: usize = 14;
|
|
const BOARD_SIZE_J: usize = 21;
|
|
|
|
const RESET_FOCUS: [f32; 3] = [
|
|
BOARD_SIZE_I as f32 / 2.0,
|
|
0.0,
|
|
BOARD_SIZE_J as f32 / 2.0 - 0.5,
|
|
];
|
|
|
|
fn setup_cameras(mut commands: Commands, mut game: ResMut<Game>) {
|
|
game.camera_should_focus = Vec3::from(RESET_FOCUS);
|
|
game.camera_is_focus = game.camera_should_focus;
|
|
commands.spawn_bundle(Camera3dBundle {
|
|
transform: Transform::from_xyz(
|
|
-(BOARD_SIZE_I as f32 / 2.0),
|
|
2.0 * BOARD_SIZE_J as f32 / 3.0,
|
|
BOARD_SIZE_J as f32 / 2.0 - 0.5,
|
|
)
|
|
.looking_at(game.camera_is_focus, Vec3::Y),
|
|
..default()
|
|
});
|
|
}
|
|
|
|
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMut<Game>) {
|
|
// reset the game state
|
|
game.cake_eaten = 0;
|
|
game.score = 0;
|
|
game.player.i = BOARD_SIZE_I / 2;
|
|
game.player.j = BOARD_SIZE_J / 2;
|
|
game.player.move_cooldown = Timer::from_seconds(0.3, false);
|
|
|
|
commands.spawn_bundle(PointLightBundle {
|
|
transform: Transform::from_xyz(4.0, 10.0, 4.0),
|
|
point_light: PointLight {
|
|
intensity: 3000.0,
|
|
shadows_enabled: true,
|
|
range: 30.0,
|
|
..default()
|
|
},
|
|
..default()
|
|
});
|
|
|
|
// spawn the game board
|
|
let cell_scene = asset_server.load("models/AlienCake/tile.glb#Scene0");
|
|
game.board = (0..BOARD_SIZE_J)
|
|
.map(|j| {
|
|
(0..BOARD_SIZE_I)
|
|
.map(|i| {
|
|
let height = rand::thread_rng().gen_range(-0.1..0.1);
|
|
commands
|
|
.spawn_bundle(TransformBundle::from(Transform::from_xyz(
|
|
i as f32,
|
|
height - 0.2,
|
|
j as f32,
|
|
)))
|
|
.with_children(|cell| {
|
|
cell.spawn_scene(cell_scene.clone());
|
|
});
|
|
Cell { height }
|
|
})
|
|
.collect()
|
|
})
|
|
.collect();
|
|
|
|
// spawn the game character
|
|
game.player.entity = Some(
|
|
commands
|
|
.spawn_bundle(TransformBundle::from(Transform {
|
|
translation: Vec3::new(
|
|
game.player.i as f32,
|
|
game.board[game.player.j][game.player.i].height,
|
|
game.player.j as f32,
|
|
),
|
|
rotation: Quat::from_rotation_y(-std::f32::consts::FRAC_PI_2),
|
|
..default()
|
|
}))
|
|
.with_children(|cell| {
|
|
cell.spawn_scene(asset_server.load("models/AlienCake/alien.glb#Scene0"));
|
|
})
|
|
.id(),
|
|
);
|
|
|
|
// load the scene for the cake
|
|
game.bonus.handle = asset_server.load("models/AlienCake/cakeBirthday.glb#Scene0");
|
|
|
|
// scoreboard
|
|
commands.spawn_bundle(TextBundle {
|
|
text: Text::with_section(
|
|
"Score:",
|
|
TextStyle {
|
|
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
|
|
font_size: 40.0,
|
|
color: Color::rgb(0.5, 0.5, 1.0),
|
|
},
|
|
Default::default(),
|
|
),
|
|
style: Style {
|
|
position_type: PositionType::Absolute,
|
|
position: UiRect {
|
|
top: Val::Px(5.0),
|
|
left: Val::Px(5.0),
|
|
..default()
|
|
},
|
|
..default()
|
|
},
|
|
..default()
|
|
});
|
|
}
|
|
|
|
// remove all entities that are not a camera
|
|
fn teardown(mut commands: Commands, entities: Query<Entity, Without<Camera>>) {
|
|
for entity in entities.iter() {
|
|
commands.entity(entity).despawn_recursive();
|
|
}
|
|
}
|
|
|
|
// control the game character
|
|
fn move_player(
|
|
mut commands: Commands,
|
|
keyboard_input: Res<Input<KeyCode>>,
|
|
mut game: ResMut<Game>,
|
|
mut transforms: Query<&mut Transform>,
|
|
time: Res<Time>,
|
|
) {
|
|
if game.player.move_cooldown.tick(time.delta()).finished() {
|
|
let mut moved = false;
|
|
let mut rotation = 0.0;
|
|
|
|
if keyboard_input.pressed(KeyCode::Up) {
|
|
if game.player.i < BOARD_SIZE_I - 1 {
|
|
game.player.i += 1;
|
|
}
|
|
rotation = -std::f32::consts::FRAC_PI_2;
|
|
moved = true;
|
|
}
|
|
if keyboard_input.pressed(KeyCode::Down) {
|
|
if game.player.i > 0 {
|
|
game.player.i -= 1;
|
|
}
|
|
rotation = std::f32::consts::FRAC_PI_2;
|
|
moved = true;
|
|
}
|
|
if keyboard_input.pressed(KeyCode::Right) {
|
|
if game.player.j < BOARD_SIZE_J - 1 {
|
|
game.player.j += 1;
|
|
}
|
|
rotation = std::f32::consts::PI;
|
|
moved = true;
|
|
}
|
|
if keyboard_input.pressed(KeyCode::Left) {
|
|
if game.player.j > 0 {
|
|
game.player.j -= 1;
|
|
}
|
|
rotation = 0.0;
|
|
moved = true;
|
|
}
|
|
|
|
// move on the board
|
|
if moved {
|
|
game.player.move_cooldown.reset();
|
|
*transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform {
|
|
translation: Vec3::new(
|
|
game.player.i as f32,
|
|
game.board[game.player.j][game.player.i].height,
|
|
game.player.j as f32,
|
|
),
|
|
rotation: Quat::from_rotation_y(rotation),
|
|
..default()
|
|
};
|
|
}
|
|
}
|
|
|
|
// eat the cake!
|
|
if let Some(entity) = game.bonus.entity {
|
|
if game.player.i == game.bonus.i && game.player.j == game.bonus.j {
|
|
game.score += 2;
|
|
game.cake_eaten += 1;
|
|
commands.entity(entity).despawn_recursive();
|
|
game.bonus.entity = None;
|
|
}
|
|
}
|
|
}
|
|
|
|
// change the focus of the camera
|
|
fn focus_camera(
|
|
time: Res<Time>,
|
|
mut game: ResMut<Game>,
|
|
mut transforms: ParamSet<(Query<&mut Transform, With<Camera3d>>, Query<&Transform>)>,
|
|
) {
|
|
const SPEED: f32 = 2.0;
|
|
// if there is both a player and a bonus, target the mid-point of them
|
|
if let (Some(player_entity), Some(bonus_entity)) = (game.player.entity, game.bonus.entity) {
|
|
let transform_query = transforms.p1();
|
|
if let (Ok(player_transform), Ok(bonus_transform)) = (
|
|
transform_query.get(player_entity),
|
|
transform_query.get(bonus_entity),
|
|
) {
|
|
game.camera_should_focus = player_transform
|
|
.translation
|
|
.lerp(bonus_transform.translation, 0.5);
|
|
}
|
|
// otherwise, if there is only a player, target the player
|
|
} else if let Some(player_entity) = game.player.entity {
|
|
if let Ok(player_transform) = transforms.p1().get(player_entity) {
|
|
game.camera_should_focus = player_transform.translation;
|
|
}
|
|
// otherwise, target the middle
|
|
} else {
|
|
game.camera_should_focus = Vec3::from(RESET_FOCUS);
|
|
}
|
|
// calculate the camera motion based on the difference between where the camera is looking
|
|
// and where it should be looking; the greater the distance, the faster the motion;
|
|
// smooth out the camera movement using the frame time
|
|
let mut camera_motion = game.camera_should_focus - game.camera_is_focus;
|
|
if camera_motion.length() > 0.2 {
|
|
camera_motion *= SPEED * time.delta_seconds();
|
|
// set the new camera's actual focus
|
|
game.camera_is_focus += camera_motion;
|
|
}
|
|
// look at that new camera's actual focus
|
|
for mut transform in transforms.p0().iter_mut() {
|
|
*transform = transform.looking_at(game.camera_is_focus, Vec3::Y);
|
|
}
|
|
}
|
|
|
|
// despawn the bonus if there is one, then spawn a new one at a random location
|
|
fn spawn_bonus(
|
|
mut state: ResMut<State<GameState>>,
|
|
mut commands: Commands,
|
|
mut game: ResMut<Game>,
|
|
) {
|
|
if *state.current() != GameState::Playing {
|
|
return;
|
|
}
|
|
if let Some(entity) = game.bonus.entity {
|
|
game.score -= 3;
|
|
commands.entity(entity).despawn_recursive();
|
|
game.bonus.entity = None;
|
|
if game.score <= -5 {
|
|
// We don't particularly care if this operation fails
|
|
let _ = state.overwrite_set(GameState::GameOver);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// ensure bonus doesn't spawn on the player
|
|
loop {
|
|
game.bonus.i = rand::thread_rng().gen_range(0..BOARD_SIZE_I);
|
|
game.bonus.j = rand::thread_rng().gen_range(0..BOARD_SIZE_J);
|
|
if game.bonus.i != game.player.i || game.bonus.j != game.player.j {
|
|
break;
|
|
}
|
|
}
|
|
game.bonus.entity = Some(
|
|
commands
|
|
.spawn_bundle(TransformBundle::from(Transform::from_xyz(
|
|
game.bonus.i as f32,
|
|
game.board[game.bonus.j][game.bonus.i].height + 0.2,
|
|
game.bonus.j as f32,
|
|
)))
|
|
.with_children(|children| {
|
|
children.spawn_bundle(PointLightBundle {
|
|
point_light: PointLight {
|
|
color: Color::rgb(1.0, 1.0, 0.0),
|
|
intensity: 1000.0,
|
|
range: 10.0,
|
|
..default()
|
|
},
|
|
transform: Transform::from_xyz(0.0, 2.0, 0.0),
|
|
..default()
|
|
});
|
|
children.spawn_scene(game.bonus.handle.clone());
|
|
})
|
|
.id(),
|
|
);
|
|
}
|
|
|
|
// let the cake turn on itself
|
|
fn rotate_bonus(game: Res<Game>, time: Res<Time>, mut transforms: Query<&mut Transform>) {
|
|
if let Some(entity) = game.bonus.entity {
|
|
if let Ok(mut cake_transform) = transforms.get_mut(entity) {
|
|
cake_transform.rotate(Quat::from_rotation_y(time.delta_seconds()));
|
|
cake_transform.scale = Vec3::splat(
|
|
1.0 + (game.score as f32 / 10.0 * time.seconds_since_startup().sin() as f32).abs(),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
// update the score displayed during the game
|
|
fn scoreboard_system(game: Res<Game>, mut query: Query<&mut Text>) {
|
|
let mut text = query.single_mut();
|
|
text.sections[0].value = format!("Sugar Rush: {}", game.score);
|
|
}
|
|
|
|
// restart the game when pressing spacebar
|
|
fn gameover_keyboard(mut state: ResMut<State<GameState>>, keyboard_input: Res<Input<KeyCode>>) {
|
|
if keyboard_input.just_pressed(KeyCode::Space) {
|
|
state.set(GameState::Playing).unwrap();
|
|
}
|
|
}
|
|
|
|
// display the number of cake eaten before losing
|
|
fn display_score(mut commands: Commands, asset_server: Res<AssetServer>, game: Res<Game>) {
|
|
commands
|
|
.spawn_bundle(NodeBundle {
|
|
style: Style {
|
|
margin: UiRect::all(Val::Auto),
|
|
justify_content: JustifyContent::Center,
|
|
align_items: AlignItems::Center,
|
|
..default()
|
|
},
|
|
color: Color::NONE.into(),
|
|
..default()
|
|
})
|
|
.with_children(|parent| {
|
|
parent.spawn_bundle(TextBundle {
|
|
text: Text::with_section(
|
|
format!("Cake eaten: {}", game.cake_eaten),
|
|
TextStyle {
|
|
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
|
|
font_size: 80.0,
|
|
color: Color::rgb(0.5, 0.5, 1.0),
|
|
},
|
|
Default::default(),
|
|
),
|
|
..default()
|
|
});
|
|
});
|
|
}
|