bevy/examples/3d/3d_viewport_to_world.rs

73 lines
2 KiB
Rust
Raw Normal View History

//! This example demonstrates how to use the `Camera::viewport_to_world` method.
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, draw_cursor)
.run();
}
fn draw_cursor(
camera_query: Query<(&Camera, &GlobalTransform)>,
ground_query: Query<&GlobalTransform, With<Ground>>,
windows: Query<&Window>,
mut gizmos: Gizmos,
) {
let (camera, camera_transform) = camera_query.single();
let ground = ground_query.single();
let Some(cursor_position) = windows.single().cursor_position() else {
return;
};
// Calculate a ray pointing from the camera into the world based on the cursor's position.
let Some(ray) = camera.viewport_to_world(camera_transform, cursor_position) else {
return;
};
// Calculate if and where the ray is hitting the ground plane.
Split `Ray` into `Ray2d` and `Ray3d` and simplify plane construction (#10856) # Objective A better alternative version of #10843. Currently, Bevy has a single `Ray` struct for 3D. To allow better interoperability with Bevy's primitive shapes (#10572) and some third party crates (that handle e.g. spatial queries), it would be very useful to have separate versions for 2D and 3D respectively. ## Solution Separate `Ray` into `Ray2d` and `Ray3d`. These new structs also take advantage of the new primitives by using `Direction2d`/`Direction3d` for the direction: ```rust pub struct Ray2d { pub origin: Vec2, pub direction: Direction2d, } pub struct Ray3d { pub origin: Vec3, pub direction: Direction3d, } ``` and by using `Plane2d`/`Plane3d` in `intersect_plane`: ```rust impl Ray2d { // ... pub fn intersect_plane(&self, plane_origin: Vec2, plane: Plane2d) -> Option<f32> { // ... } } ``` --- ## Changelog ### Added - `Ray2d` and `Ray3d` - `Ray2d::new` and `Ray3d::new` constructors - `Plane2d::new` and `Plane3d::new` constructors ### Removed - Removed `Ray` in favor of `Ray3d` ### Changed - `direction` is now a `Direction2d`/`Direction3d` instead of a vector, which provides guaranteed normalization - `intersect_plane` now takes a `Plane2d`/`Plane3d` instead of just a vector for the plane normal - `Direction2d` and `Direction3d` now derive `Serialize` and `Deserialize` to preserve ray (de)serialization ## Migration Guide `Ray` has been renamed to `Ray3d`. ### Ray creation Before: ```rust Ray { origin: Vec3::ZERO, direction: Vec3::new(0.5, 0.6, 0.2).normalize(), } ``` After: ```rust // Option 1: Ray3d { origin: Vec3::ZERO, direction: Direction3d::new(Vec3::new(0.5, 0.6, 0.2)).unwrap(), } // Option 2: Ray3d::new(Vec3::ZERO, Vec3::new(0.5, 0.6, 0.2)) ``` ### Plane intersections Before: ```rust let result = ray.intersect_plane(Vec2::X, Vec2::Y); ``` After: ```rust let result = ray.intersect_plane(Vec2::X, Plane2d::new(Vec2::Y)); ```
2023-12-06 14:09:04 +00:00
let Some(distance) =
ray.intersect_plane(ground.translation(), primitives::Plane3d::new(ground.up()))
else {
return;
};
let point = ray.get_point(distance);
// Draw a circle just above the ground plane at that position.
gizmos.circle(point + ground.up() * 0.01, ground.up(), 0.2, Color::WHITE);
}
#[derive(Component)]
struct Ground;
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// plane
commands.spawn((
PbrBundle {
Use `impl Into<A>` for `Assets::add` (#10878) # Motivation When spawning entities into a scene, it is very common to create assets like meshes and materials and to add them via asset handles. A common setup might look like this: ```rust fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands.spawn(PbrBundle { mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), material: materials.add(StandardMaterial::from(Color::RED)), ..default() }); } ``` Let's take a closer look at the part that adds the assets using `add`. ```rust mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), material: materials.add(StandardMaterial::from(Color::RED)), ``` Here, "mesh" and "material" are both repeated three times. It's very explicit, but I find it to be a bit verbose. In addition to being more code to read and write, the extra characters can sometimes also lead to the code being formatted to span multiple lines even though the core task, adding e.g. a primitive mesh, is extremely simple. A way to address this is by using `.into()`: ```rust mesh: meshes.add(shape::Cube { size: 1.0 }.into()), material: materials.add(Color::RED.into()), ``` This is fine, but from the names and the type of `meshes`, we already know what the type should be. It's very clear that `Cube` should be turned into a `Mesh` because of the context it's used in. `.into()` is just seven characters, but it's so common that it quickly adds up and gets annoying. It would be nice if you could skip all of the conversion and let Bevy handle it for you: ```rust mesh: meshes.add(shape::Cube { size: 1.0 }), material: materials.add(Color::RED), ``` # Objective Make adding assets more ergonomic by making `Assets::add` take an `impl Into<A>` instead of `A`. ## Solution `Assets::add` now takes an `impl Into<A>` instead of `A`, so e.g. this works: ```rust commands.spawn(PbrBundle { mesh: meshes.add(shape::Cube { size: 1.0 }), material: materials.add(Color::RED), ..default() }); ``` I also changed all examples to use this API, which increases consistency as well because `Mesh::from` and `into` were being used arbitrarily even in the same file. This also gets rid of some lines of code because formatting is nicer. --- ## Changelog - `Assets::add` now takes an `impl Into<A>` instead of `A` - Examples don't use `T::from(K)` or `K.into()` when adding assets ## Migration Guide Some `into` calls that worked previously might now be broken because of the new trait bounds. You need to either remove `into` or perform the conversion explicitly with `from`: ```rust // Doesn't compile let mesh_handle = meshes.add(shape::Cube { size: 1.0 }.into()), // These compile let mesh_handle = meshes.add(shape::Cube { size: 1.0 }), let mesh_handle = meshes.add(Mesh::from(shape::Cube { size: 1.0 })), ``` ## Concerns I believe the primary concerns might be: 1. Is this too implicit? 2. Does this increase codegen bloat? Previously, the two APIs were using `into` or `from`, and now it's "nothing" or `from`. You could argue that `into` is slightly more explicit than "nothing" in cases like the earlier examples where a `Color` gets converted to e.g. a `StandardMaterial`, but I personally don't think `into` adds much value even in this case, and you could still see the actual type from the asset type. As for codegen bloat, I doubt it adds that much, but I'm not very familiar with the details of codegen. I personally value the user-facing code reduction and ergonomics improvements that these changes would provide, but it might be worth checking the other effects in more detail. Another slight concern is migration pain; apps might have a ton of `into` calls that would need to be removed, and it did take me a while to do so for Bevy itself (maybe around 20-40 minutes). However, I think the fact that there *are* so many `into` calls just highlights that the API could be made nicer, and I'd gladly migrate my own projects for it.
2024-01-08 22:14:43 +00:00
mesh: meshes.add(shape::Plane::from_size(20.)),
material: materials.add(Color::rgb(0.3, 0.5, 0.3)),
..default()
},
Ground,
));
// light
commands.spawn(DirectionalLightBundle {
transform: Transform::from_translation(Vec3::ONE).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(15.0, 5.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}