Skip to content

Commit

Permalink
Merge branch 'main' into feature/reflect-command-bundle-docs-remove
Browse files Browse the repository at this point in the history
  • Loading branch information
Niashi24 committed Sep 11, 2024
2 parents 52fec32 + 8e7ef64 commit 551e24d
Show file tree
Hide file tree
Showing 9 changed files with 301 additions and 84 deletions.
13 changes: 12 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3251,7 +3251,18 @@ doc-scrape-examples = true

[package.metadata.example.projection_zoom]
name = "Projection Zoom"
description = "Shows how to zoom and orbit orthographic and perspective projection cameras."
description = "Shows how to zoom orthographic and perspective projection cameras."
category = "Camera"
wasm = true

[[example]]
name = "camera_orbit"
path = "examples/camera/camera_orbit.rs"
doc-scrape-examples = true

[package.metadata.example.camera_orbit]
name = "Camera Orbit"
description = "Shows how to orbit a static scene using pitch, yaw, and roll."
category = "Camera"
wasm = true

Expand Down
31 changes: 30 additions & 1 deletion crates/bevy_reflect/src/func/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
//! Closures, on the other hand, are special functions that do capture their environment.
//! These are always defined with anonymous function syntax.
//!
//! ```rust
//! ```
//! // A closure that captures an immutable reference to a variable
//! let c = 123;
//! let add = |a: i32, b: i32| a + b + c;
Expand Down Expand Up @@ -94,6 +94,35 @@
//! For other functions that don't conform to one of the above signatures,
//! [`DynamicFunction`] and [`DynamicFunctionMut`] can instead be created manually.
//!
//! # Function Registration
//!
//! This module also provides a [`FunctionRegistry`] that can be used to register functions and closures
//! by name so that they may be retrieved and called dynamically.
//!
//! ```
//! # use bevy_reflect::func::{ArgList, FunctionRegistry};
//! fn add(a: i32, b: i32) -> i32 {
//! a + b
//! }
//!
//! let mut registry = FunctionRegistry::default();
//!
//! // You can register functions and methods by their `std::any::type_name`:
//! registry.register(add).unwrap();
//!
//! // Or you can register them by a custom name:
//! registry.register_with_name("mul", |a: i32, b: i32| a * b).unwrap();
//!
//! // You can then retrieve and call these functions by name:
//! let reflect_add = registry.get(std::any::type_name_of_val(&add)).unwrap();
//! let value = reflect_add.call(ArgList::default().push_owned(10_i32).push_owned(5_i32)).unwrap();
//! assert_eq!(value.unwrap_owned().try_downcast_ref::<i32>(), Some(&15));
//!
//! let reflect_mul = registry.get("mul").unwrap();
//! let value = reflect_mul.call(ArgList::default().push_owned(10_i32).push_owned(5_i32)).unwrap();
//! assert_eq!(value.unwrap_owned().try_downcast_ref::<i32>(), Some(&50));
//! ```
//!
//! [`PartialReflect`]: crate::PartialReflect
//! [`Reflect`]: crate::Reflect
//! [lack of variadic generics]: https://poignardazur.github.io/2024/05/25/report-on-rustnl-variadics/
Expand Down
3 changes: 2 additions & 1 deletion crates/bevy_text/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ impl Plugin for TextPlugin {
.ambiguous_with(CameraUpdateSystem),
remove_dropped_font_atlas_sets,
),
);
)
.add_systems(Last, trim_cosmic_cache);

if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.add_systems(
Expand Down
17 changes: 16 additions & 1 deletion crates/bevy_text/src/pipeline.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
use std::sync::Arc;

use bevy_asset::{AssetId, Assets};
use bevy_ecs::{component::Component, entity::Entity, reflect::ReflectComponent, system::Resource};
use bevy_ecs::{
component::Component,
entity::Entity,
reflect::ReflectComponent,
system::{ResMut, Resource},
};
use bevy_math::{UVec2, Vec2};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::texture::Image;
Expand Down Expand Up @@ -407,3 +412,13 @@ fn buffer_dimensions(buffer: &Buffer) -> Vec2 {

Vec2::new(width.ceil(), height).ceil()
}

/// Discards stale data cached in `FontSystem`.
pub(crate) fn trim_cosmic_cache(mut pipeline: ResMut<TextPipeline>) {
// A trim age of 2 was found to reduce frame time variance vs age of 1 when tested with dynamic text.
// See https://github.com/bevyengine/bevy/pull/15037
//
// We assume only text updated frequently benefits from the shape cache (e.g. animated text, or
// text that is dynamically measured for UI).
pipeline.font_system_mut().shape_run_cache.trim(2);
}
8 changes: 4 additions & 4 deletions crates/bevy_ui/src/layout/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub struct UiLayoutSystemRemovedComponentParam<'w, 's> {
#[doc(hidden)]
#[derive(Default)]
pub struct UiLayoutSystemBuffers {
interned_root_notes: Vec<Vec<Entity>>,
interned_root_nodes: Vec<Vec<Entity>>,
resized_windows: EntityHashSet,
camera_layout_info: EntityHashMap<CameraLayoutInfo>,
}
Expand Down Expand Up @@ -122,7 +122,7 @@ pub fn ui_layout_system(
#[cfg(feature = "bevy_text")] mut text_pipeline: ResMut<TextPipeline>,
) {
let UiLayoutSystemBuffers {
interned_root_notes,
interned_root_nodes,
resized_windows,
camera_layout_info,
} = &mut *buffers;
Expand All @@ -147,7 +147,7 @@ pub fn ui_layout_system(
size,
resized,
scale_factor: scale_factor * ui_scale.0,
root_nodes: interned_root_notes.pop().unwrap_or_default(),
root_nodes: interned_root_nodes.pop().unwrap_or_default(),
}
};

Expand Down Expand Up @@ -280,7 +280,7 @@ pub fn ui_layout_system(
}

camera.root_nodes.clear();
interned_root_notes.push(camera.root_nodes);
interned_root_nodes.push(camera.root_nodes);
}

fn update_uinode_geometry_recursive(
Expand Down
3 changes: 2 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,9 @@ Example | Description
Example | Description
--- | ---
[2D top-down camera](../examples/camera/2d_top_down_camera.rs) | A 2D top-down camera smoothly following player movements
[Camera Orbit](../examples/camera/camera_orbit.rs) | Shows how to orbit a static scene using pitch, yaw, and roll.
[First person view model](../examples/camera/first_person_view_model.rs) | A first-person camera that uses a world model and a view model with different field of views (FOV)
[Projection Zoom](../examples/camera/projection_zoom.rs) | Shows how to zoom and orbit orthographic and perspective projection cameras.
[Projection Zoom](../examples/camera/projection_zoom.rs) | Shows how to zoom orthographic and perspective projection cameras.

## Dev tools

Expand Down
163 changes: 163 additions & 0 deletions examples/camera/camera_orbit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
//! Shows how to orbit camera around a static scene using pitch, yaw, and roll.

use std::{f32::consts::FRAC_PI_2, ops::Range};

use bevy::prelude::*;

#[derive(Debug, Default, Resource)]
struct CameraSettings {
pub orbit_distance: f32,
// Multiply keyboard inputs by this factor
pub orbit_speed: f32,
// Clamp pitch to this range
pub pitch_range: Range<f32>,
}

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<CameraSettings>()
.add_systems(Startup, (setup, instructions))
.add_systems(Update, orbit)
.run();
}

/// Set up a simple 3D scene
fn setup(
mut camera_settings: ResMut<CameraSettings>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Limiting pitch stops some unexpected rotation past 90° up or down.
let pitch_limit = FRAC_PI_2 - 0.01;

camera_settings.orbit_distance = 10.0;
camera_settings.orbit_speed = 1.0;
camera_settings.pitch_range = -pitch_limit..pitch_limit;

commands.spawn((
Name::new("Camera"),
Camera3dBundle {
transform: Transform::from_xyz(5.0, 5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
},
));

commands.spawn((
Name::new("Plane"),
PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(5.0, 5.0)),
material: materials.add(StandardMaterial {
base_color: Color::srgb(0.3, 0.5, 0.3),
// Turning off culling keeps the plane visible when viewed from beneath.
cull_mode: None,
..default()
}),
..default()
},
));

commands.spawn((
Name::new("Cube"),
PbrBundle {
mesh: meshes.add(Cuboid::default()),
material: materials.add(Color::srgb(0.8, 0.7, 0.6)),
transform: Transform::from_xyz(1.5, 0.51, 1.5),
..default()
},
));

commands.spawn((
Name::new("Light"),
PointLightBundle {
transform: Transform::from_xyz(3.0, 8.0, 5.0),
..default()
},
));
}

fn instructions(mut commands: Commands) {
commands
.spawn((
Name::new("Instructions"),
NodeBundle {
style: Style {
align_items: AlignItems::Start,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Start,
width: Val::Percent(100.),
..default()
},
..default()
},
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"W or S: pitch",
TextStyle::default(),
));
parent.spawn(TextBundle::from_section(
"A or D: yaw",
TextStyle::default(),
));
parent.spawn(TextBundle::from_section(
"Q or E: roll",
TextStyle::default(),
));
});
}

fn orbit(
mut camera: Query<&mut Transform, With<Camera>>,
camera_settings: Res<CameraSettings>,
keyboard_input: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
) {
let mut transform = camera.single_mut();

let mut delta_pitch = 0.0;
let mut delta_roll = 0.0;
let mut delta_yaw = 0.0;

if keyboard_input.pressed(KeyCode::KeyW) {
delta_pitch += camera_settings.orbit_speed;
}
if keyboard_input.pressed(KeyCode::KeyS) {
delta_pitch -= camera_settings.orbit_speed;
}

if keyboard_input.pressed(KeyCode::KeyQ) {
delta_roll -= camera_settings.orbit_speed;
}
if keyboard_input.pressed(KeyCode::KeyE) {
delta_roll += camera_settings.orbit_speed;
}

if keyboard_input.pressed(KeyCode::KeyA) {
delta_yaw -= camera_settings.orbit_speed;
}
if keyboard_input.pressed(KeyCode::KeyD) {
delta_yaw += camera_settings.orbit_speed;
}

// Incorporating the delta time between calls prevents this from being framerate-bound.
delta_pitch *= time.delta_seconds();
delta_roll *= time.delta_seconds();
delta_yaw *= time.delta_seconds();

// Obtain the existing pitch, yaw, and roll values from the transform.
let (yaw, pitch, roll) = transform.rotation.to_euler(EulerRot::YXZ);

// Establish the new yaw and pitch, preventing the pitch value from exceeding our limits.
let pitch = (pitch + delta_pitch).clamp(
camera_settings.pitch_range.start,
camera_settings.pitch_range.end,
);
let roll = roll + delta_roll;
let yaw = yaw + delta_yaw;
transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);

// Adjust the translation to maintain the correct orientation toward the orbit target.
transform.translation = Vec3::ZERO - transform.forward() * camera_settings.orbit_distance;
}
Loading

0 comments on commit 551e24d

Please sign in to comment.