1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
//! A small `bevy` plugin for raycasting against [`Mesh`]es.
//!
//! The plugin provides two ways of raycasting:
//! - An "immediate-mode" API, which allows you to raycast into the scene on-demand in any system.
//! - A "retained-mode" API, where raycasts are performed once every frame based on entities tagged
//! with specific components.
//!
//! # Immediate Mode API
//!
//! See the `immediate` example for reference.
//!
//! This is the simplest way to get started. Add the [`Raycast`]
//! [`SystemParam`](bevy::ecs::system::SystemParam) to your system, and call [`Raycast::cast_ray`],
//! to get a list of intersections. Raycasts are performed immediately when you call the `cast_ray`
//! method. See the [`Raycast`] documentation for more details. You don't even need to add a plugin
//! to your application.
//!
//! # Retained Mode API
//!
//! See the `minimal` example for reference.
//!
//! This API requires you add a [`RaycastSource`] to the entity that will be generating rays, and a
//! [`RaycastMesh`] to all meshes that you want to raycast against. The [`RaycastSource`] has some
//! built in modes for common use cases. You can set this entity to cast based on where it is
//! pointing, using [`RaycastMethod::Transform`], or you can use [`RaycastMethod::Screenspace`]
//! along with a screenspace coordinate if the entity is a camera.
//!
//! These components are both generic, and raycasts will only happen between entities with the same
//! generic parameter. For example, [`RaycastSource<Foo>`] can cast rays against meshes with
//! [`RaycastMesh<Foo>`], but not against meshes that instead only have a [`RaycastMesh<Bar>`]
//! component.
//!
//! ## Comparison to Immediate Mode
//!
//! While the retained mode API requires adding components on entities, in return it's generally
//! more "hands-off". Once you add the components to entities, the plugin will run raycasts for you
//! every frame, and you can query your [`RaycastSource`]s to see what they have intersected that
//! frame.
//!
//! You can also think of this as being the "declarative" API. Instead of defining how the raycast
//! happens, you instead describe what you want. For example, "this entity should cast rays in the
//! direction it faces", and you can then query that entity to find out what it hit.
//!
//! By comparison, the immediate mode API is more imperative. You must define the raycast directly,
//! but in return you are immediately given the results of the raycast without needing to wait for
//! the scheduled raycasting system to run and query the results.
//!
//! # Use Cases
//!
//! This plugin is well suited for use cases where you don't want to use a full physics engine, you
//! are putting together a simple prototype, or you just want the simplest-possible API. Using the
//! [`Raycast`] system param requires no added components or plugins. You can just start raycasting
//! in your systems.
//!
//! ## Limitations
//!
//! This plugin runs entirely on the CPU, with minimal acceleration structures, and without support
//! for skinned meshes. However, there is a good chance that this simply won't be an issue for your
//! application. The provided `stress_test` example is a worst-case scenario that can help you judge
//! if the plugin will meet your performance needs. Using a laptop with an i7-11800H, I am able to
//! reach 110-530 fps in the stress test, raycasting against 1,000 monkey meshes.
#![allow(clippy::type_complexity)]
#[cfg(feature = "debug")]
pub mod debug;
mod primitives;
mod raycast;
pub mod system_param;
use std::{
fmt::Debug,
hash::{Hash, Hasher},
marker::PhantomData,
};
use bevy::{
math::Vec3A,
prelude::*,
reflect::TypePath,
render::{
camera::Camera,
mesh::{Indices, Mesh, VertexAttributeValues},
render_resource::PrimitiveTopology,
},
window::PrimaryWindow,
};
pub use crate::{primitives::*, raycast::*};
#[cfg(feature = "debug")]
pub use debug::*;
pub mod prelude {
pub use crate::{
low_latency_window_plugin,
system_param::{Raycast, RaycastSettings, RaycastVisibility},
DefaultRaycastingPlugin, Ray3d, RaycastMesh, RaycastMethod, RaycastPluginState,
RaycastSource, RaycastSystem, SimplifiedMesh,
};
}
use prelude::*;
pub struct DefaultRaycastingPlugin<T>(pub PhantomData<fn() -> T>);
impl<T: TypePath + Send + Sync> Plugin for DefaultRaycastingPlugin<T> {
fn build(&self, app: &mut App) {
app.init_resource::<RaycastPluginState<T>>().add_systems(
First,
(
build_rays::<T>
.in_set(RaycastSystem::BuildRays::<T>)
.run_if(|state: Res<RaycastPluginState<T>>| state.build_rays),
update_raycast::<T>
.in_set(RaycastSystem::UpdateRaycast::<T>)
.run_if(|state: Res<RaycastPluginState<T>>| state.update_raycast),
update_target_intersections::<T>
.in_set(RaycastSystem::UpdateIntersections::<T>)
.run_if(|state: Res<RaycastPluginState<T>>| state.update_raycast),
)
.chain(),
);
app.register_type::<RaycastMesh<T>>()
.register_type::<RaycastSource<T>>();
#[cfg(feature = "debug")]
app.add_systems(
First,
update_debug_cursor::<T>
.in_set(RaycastSystem::UpdateDebugCursor::<T>)
.run_if(|state: Res<RaycastPluginState<T>>| state.update_debug_cursor)
.after(RaycastSystem::UpdateIntersections::<T>),
);
}
}
impl<T> Default for DefaultRaycastingPlugin<T> {
fn default() -> Self {
DefaultRaycastingPlugin(PhantomData)
}
}
#[derive(SystemSet)]
pub enum RaycastSystem<T> {
BuildRays,
UpdateRaycast,
UpdateIntersections,
#[cfg(feature = "debug")]
UpdateDebugCursor,
_Phantom(PhantomData<fn() -> T>),
}
impl<T> PartialEq for RaycastSystem<T> {
fn eq(&self, other: &Self) -> bool {
core::mem::discriminant(self) == core::mem::discriminant(other)
}
}
impl<T> Eq for RaycastSystem<T> {}
impl<T> Debug for RaycastSystem<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let set = std::any::type_name::<T>();
match self {
Self::BuildRays => write!(f, "BuildRays ({})", set),
Self::UpdateRaycast => write!(f, "UpdateRaycast ({})", set),
Self::UpdateIntersections => write!(f, "UpdateIntersections ({})", set),
#[cfg(feature = "debug")]
Self::UpdateDebugCursor => write!(f, "UpdateDebugCursor ({})", set),
Self::_Phantom(_) => write!(f, "PhantomData<{}>", set),
}
}
}
impl<T> Hash for RaycastSystem<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
let set = std::any::type_name::<T>();
(core::mem::discriminant(self), set).hash(state);
}
}
impl<T> Clone for RaycastSystem<T> {
fn clone(&self) -> Self {
match self {
Self::BuildRays => Self::BuildRays,
Self::UpdateRaycast => Self::UpdateRaycast,
Self::UpdateIntersections => Self::UpdateIntersections,
#[cfg(feature = "debug")]
Self::UpdateDebugCursor => Self::UpdateDebugCursor,
Self::_Phantom(_) => Self::_Phantom(PhantomData),
}
}
}
/// Global plugin state used to enable or disable all ray casting for a given type T.
#[derive(Component, Resource)]
pub struct RaycastPluginState<T> {
pub build_rays: bool,
pub update_raycast: bool,
#[cfg(feature = "debug")]
pub update_debug_cursor: bool,
_marker: PhantomData<fn() -> T>,
}
impl<T> Default for RaycastPluginState<T> {
fn default() -> Self {
RaycastPluginState {
build_rays: true,
update_raycast: true,
#[cfg(feature = "debug")]
update_debug_cursor: false,
_marker: PhantomData,
}
}
}
#[cfg(feature = "debug")]
impl<T> RaycastPluginState<T> {
pub fn with_debug_cursor(self) -> Self {
RaycastPluginState {
update_debug_cursor: true,
..self
}
}
}
/// Marks an entity as pickable, with type T.
///
/// # Requirements
///
/// The marked entity must also have a [Mesh] component.
#[derive(Component, Debug, Reflect)]
#[reflect(Component)]
pub struct RaycastMesh<T: TypePath> {
#[reflect(ignore)]
pub intersections: Vec<(Entity, IntersectionData)>,
#[reflect(ignore)]
_marker: PhantomData<T>,
}
impl<T: TypePath> RaycastMesh<T> {
/// Get a reference to the ray cast source's intersections. Returns an empty list if there are
/// no intersections.
pub fn intersections(&self) -> &[(Entity, IntersectionData)] {
&self.intersections
}
}
impl<T: TypePath> Default for RaycastMesh<T> {
fn default() -> Self {
RaycastMesh {
intersections: Vec::new(),
_marker: PhantomData,
}
}
}
impl<T: TypePath> Clone for RaycastMesh<T> {
fn clone(&self) -> Self {
RaycastMesh {
intersections: self.intersections.clone(),
_marker: PhantomData,
}
}
}
/// The `RaycastSource` component is used to generate rays with the specified `cast_method`. A `ray`
/// is generated when the RaycastSource is initialized, either by waiting for update_raycast system
/// to process the ray, or by using a `with_ray` function.`
#[derive(Component, Reflect)]
#[reflect(Component)]
pub struct RaycastSource<T: TypePath> {
/// The method used to generate rays for this raycast.
pub cast_method: RaycastMethod,
/// When `true`, raycasting will only hit the nearest entity, skipping any entities that are
/// further away. This can significantly improve performance in cases where a ray intersects
/// many AABBs.
pub should_early_exit: bool,
/// Determines how raycasting should consider entity visibility.
pub visibility: RaycastVisibility,
#[reflect(skip_serializing)]
pub ray: Option<Ray3d>,
#[reflect(ignore)]
intersections: Vec<(Entity, IntersectionData)>,
#[reflect(ignore)]
_marker: PhantomData<fn() -> T>,
}
impl<T: TypePath> Default for RaycastSource<T> {
fn default() -> Self {
RaycastSource {
cast_method: RaycastMethod::Screenspace(Vec2::ZERO),
should_early_exit: true,
visibility: RaycastVisibility::MustBeVisibleAndInView,
ray: None,
intersections: Vec::new(),
_marker: PhantomData,
}
}
}
impl<T: TypePath> Clone for RaycastSource<T> {
fn clone(&self) -> Self {
Self {
cast_method: self.cast_method.clone(),
should_early_exit: self.should_early_exit,
visibility: self.visibility,
ray: self.ray,
intersections: self.intersections.clone(),
_marker: PhantomData,
}
}
}
impl<T: TypePath> RaycastSource<T> {
/// Instantiates a [RaycastSource]. It will not be initialized until the update_raycast system
/// runs, or one of the `with_ray` functions is run.
pub fn new() -> RaycastSource<T> {
RaycastSource::default()
}
/// Initializes a [RaycastSource] with a valid screenspace ray.
pub fn with_ray_screenspace(
self,
cursor_pos_screen: Vec2,
camera: &Camera,
camera_transform: &GlobalTransform,
window: &Window,
) -> Self {
RaycastSource {
cast_method: RaycastMethod::Screenspace(cursor_pos_screen),
ray: Ray3d::from_screenspace(cursor_pos_screen, camera, camera_transform, window),
..self
}
}
/// Initializes a [RaycastSource] with a valid ray derived from a transform.
pub fn with_ray_transform(self, transform: Mat4) -> Self {
RaycastSource {
cast_method: RaycastMethod::Transform,
ray: Some(Ray3d::from_transform(transform)),
..self
}
}
/// Set the `should_early_exit` field of this raycast source.
pub fn with_early_exit(self, should_early_exit: bool) -> Self {
Self {
should_early_exit,
..self
}
}
/// Set the `visibility` field of this raycast source.
pub fn with_visibility(self, visibility: RaycastVisibility) -> Self {
Self { visibility, ..self }
}
/// Instantiates and initializes a [RaycastSource] with a valid screenspace ray.
pub fn new_screenspace(
cursor_pos_screen: Vec2,
camera: &Camera,
camera_transform: &GlobalTransform,
window: &Window,
) -> Self {
RaycastSource::new().with_ray_screenspace(
cursor_pos_screen,
camera,
camera_transform,
window,
)
}
/// Initializes a [RaycastSource] with a valid ray derived from a transform.
pub fn new_transform(transform: Mat4) -> Self {
RaycastSource::new().with_ray_transform(transform)
}
/// Instantiates a [RaycastSource] with [RaycastMethod::Transform], and an empty ray. It will
/// not be initialized until the [update_raycast] system is run and a [GlobalTransform] is
/// present on this entity.
///
/// # Warning
/// Only use this if the entity this is associated with will have its [Transform] or
/// [GlobalTransform] specified elsewhere. If the [GlobalTransform] is not set, this ray casting
/// source will never be able to generate a raycast.
pub fn new_transform_empty() -> Self {
RaycastSource {
cast_method: RaycastMethod::Transform,
..Default::default()
}
}
/// Get a reference to the ray cast source's intersections, if one exists.
pub fn get_intersections(&self) -> Option<&[(Entity, IntersectionData)]> {
if self.intersections.is_empty() {
None
} else {
Some(&self.intersections)
}
}
/// Get a reference to the ray cast source's intersections. Returns an empty list if there are
/// no intersections.
pub fn intersections(&self) -> &[(Entity, IntersectionData)] {
&self.intersections
}
/// Get a reference to the nearest intersection point, if there is one.
pub fn get_nearest_intersection(&self) -> Option<(Entity, &IntersectionData)> {
if self.intersections.is_empty() {
None
} else {
self.intersections.first().map(|(e, i)| (*e, i))
}
}
/// Run an intersection check between this [`RaycastSource`] and a 3D primitive [`Primitive3d`].
pub fn intersect_primitive(&self, shape: Primitive3d) -> Option<IntersectionData> {
Some(self.ray?.intersects_primitive(shape)?.into())
}
/// Get a copy of the ray cast source's ray.
pub fn get_ray(&self) -> Option<Ray3d> {
self.ray
}
/// Get a mutable reference to the ray cast source's intersections.
pub fn intersections_mut(&mut self) -> &mut Vec<(Entity, IntersectionData)> {
&mut self.intersections
}
/// Returns `true` if this is using [`RaycastMethod::Screenspace`].
pub fn is_screenspace(&self) -> bool {
matches!(self.cast_method, RaycastMethod::Screenspace(_))
}
}
/// Specifies the method used to generate rays.
#[derive(Clone, Debug, Reflect)]
pub enum RaycastMethod {
/// Specify screen coordinates relative to the camera component associated with this entity.
///
/// # Component Requirements
///
/// This requires a [Camera] component on this [RaycastSource]'s entity, to determine where the
/// screenspace ray is firing from in the world.
Screenspace(Vec2),
/// Use a transform in world space to define a pick ray. This transform is applied to a vector
/// at the origin pointing up to generate a ray.
///
/// # Component Requirements
///
/// Requires a [GlobalTransform] component associated with this [RaycastSource]'s entity.
Transform,
}
pub fn build_rays<T: TypePath>(
mut pick_source_query: Query<(
&mut RaycastSource<T>,
Option<&GlobalTransform>,
Option<&Camera>,
)>,
window: Query<&Window, With<PrimaryWindow>>,
) {
for (mut pick_source, transform, camera) in &mut pick_source_query {
pick_source.ray = match &mut pick_source.cast_method {
RaycastMethod::Screenspace(cursor_pos_screen) => {
// Get all the info we need from the camera and window
let window = match window.get_single() {
Ok(window) => window,
Err(_) => {
error!("No primary window found, cannot cast ray");
return;
}
};
let camera = match camera {
Some(camera) => camera,
None => {
error!(
"The PickingSource is a CameraScreenSpace but has no associated Camera component"
);
return;
}
};
let camera_transform = match transform {
Some(transform) => transform,
None => {
error!(
"The PickingSource is a CameraScreenSpace but has no associated GlobalTransform component"
);
return;
}
};
Ray3d::from_screenspace(*cursor_pos_screen, camera, camera_transform, window)
}
// Use the specified transform as the origin and direction of the ray
RaycastMethod::Transform => {
let transform = match transform {
Some(matrix) => matrix,
None => {
error!(
"The PickingSource is a Transform but has no associated GlobalTransform component"
);
return
}
}
.compute_matrix();
Some(Ray3d::from_transform(transform))
}
};
}
}
/// Iterates through all entities with the [RaycastMesh] component, checking for
/// intersections. If these entities have bounding volumes, these will be checked first, greatly
/// accelerating the process.
pub fn update_raycast<T: TypePath + Send + Sync + 'static>(
mut raycast: system_param::Raycast,
mut pick_source_query: Query<&mut RaycastSource<T>>,
targets: Query<&RaycastMesh<T>>,
) {
for mut pick_source in &mut pick_source_query {
if let Some(ray) = pick_source.ray {
pick_source.intersections.clear();
let filter = |entity| targets.contains(entity);
let test = |_| pick_source.should_early_exit;
let settings = RaycastSettings::default()
.with_filter(&filter)
.with_early_exit_test(&test)
.with_visibility(pick_source.visibility);
pick_source.intersections = raycast.cast_ray(ray, &settings).to_vec();
}
}
}
pub fn update_target_intersections<T: TypePath + Send + Sync>(
sources: Query<(Entity, &RaycastSource<T>)>,
mut meshes: Query<&mut RaycastMesh<T>>,
mut previously_updated_raycast_meshes: Local<Vec<Entity>>,
) {
// Clear any entities with intersections last frame
for entity in previously_updated_raycast_meshes.drain(..) {
if let Ok(mesh) = meshes.get_mut(entity).as_mut() {
mesh.intersections.clear();
}
}
for (source_entity, source) in sources.iter() {
for (mesh_entity, intersection) in source.intersections().iter() {
if let Ok(mut mesh) = meshes.get_mut(*mesh_entity) {
mesh.intersections
.push((source_entity, intersection.to_owned()));
previously_updated_raycast_meshes.push(*mesh_entity);
}
}
}
}
/// Cast a ray on a mesh, and returns the intersection
pub fn ray_intersection_over_mesh(
mesh: &Mesh,
mesh_transform: &Mat4,
ray: &Ray3d,
backface_culling: Backfaces,
) -> Option<IntersectionData> {
if mesh.primitive_topology() != PrimitiveTopology::TriangleList {
error!(
"Invalid intersection check: `TriangleList` is the only supported `PrimitiveTopology`"
);
return None;
}
// Get the vertex positions from the mesh reference resolved from the mesh handle
let vertex_positions: &Vec<[f32; 3]> = match mesh.attribute(Mesh::ATTRIBUTE_POSITION) {
None => panic!("Mesh does not contain vertex positions"),
Some(vertex_values) => match &vertex_values {
VertexAttributeValues::Float32x3(positions) => positions,
_ => panic!("Unexpected types in {:?}", Mesh::ATTRIBUTE_POSITION),
},
};
let vertex_normals: Option<&[[f32; 3]]> =
if let Some(normal_values) = mesh.attribute(Mesh::ATTRIBUTE_NORMAL) {
match &normal_values {
VertexAttributeValues::Float32x3(normals) => Some(normals),
_ => None,
}
} else {
None
};
if let Some(indices) = &mesh.indices() {
// Iterate over the list of pick rays that belong to the same group as this mesh
match indices {
Indices::U16(vertex_indices) => ray_mesh_intersection(
mesh_transform,
vertex_positions,
vertex_normals,
ray,
Some(vertex_indices),
backface_culling,
),
Indices::U32(vertex_indices) => ray_mesh_intersection(
mesh_transform,
vertex_positions,
vertex_normals,
ray,
Some(vertex_indices),
backface_culling,
),
}
} else {
ray_mesh_intersection(
mesh_transform,
vertex_positions,
vertex_normals,
ray,
None::<&Vec<u32>>,
backface_culling,
)
}
}
pub trait IntoUsize: Copy {
fn into_usize(self) -> usize;
}
impl IntoUsize for u16 {
fn into_usize(self) -> usize {
self as usize
}
}
impl IntoUsize for u32 {
fn into_usize(self) -> usize {
self as usize
}
}
/// Checks if a ray intersects a mesh, and returns the nearest intersection if one exists.
pub fn ray_mesh_intersection(
mesh_transform: &Mat4,
vertex_positions: &[[f32; 3]],
vertex_normals: Option<&[[f32; 3]]>,
ray: &Ray3d,
indices: Option<&Vec<impl IntoUsize>>,
backface_culling: Backfaces,
) -> Option<IntersectionData> {
// The ray cast can hit the same mesh many times, so we need to track which hit is
// closest to the camera, and record that.
let mut min_pick_distance = f32::MAX;
let mut pick_intersection = None;
let world_to_mesh = mesh_transform.inverse();
let mesh_space_ray = Ray3d::new(
world_to_mesh.transform_point3(ray.origin()),
world_to_mesh.transform_vector3(ray.direction()),
);
if let Some(indices) = indices {
// Make sure this chunk has 3 vertices to avoid a panic.
if indices.len() % 3 != 0 {
warn!("Index list not a multiple of 3");
return None;
}
// Now that we're in the vector of vertex indices, we want to look at the vertex
// positions for each triangle, so we'll take indices in chunks of three, where each
// chunk of three indices are references to the three vertices of a triangle.
for index in indices.chunks(3) {
let tri_vertex_positions = [
Vec3A::from(vertex_positions[index[0].into_usize()]),
Vec3A::from(vertex_positions[index[1].into_usize()]),
Vec3A::from(vertex_positions[index[2].into_usize()]),
];
let tri_normals = vertex_normals.map(|normals| {
[
Vec3A::from(normals[index[0].into_usize()]),
Vec3A::from(normals[index[1].into_usize()]),
Vec3A::from(normals[index[2].into_usize()]),
]
});
let intersection = triangle_intersection(
tri_vertex_positions,
tri_normals,
min_pick_distance,
mesh_space_ray,
backface_culling,
);
if let Some(i) = intersection {
pick_intersection = Some(IntersectionData::new(
mesh_transform.transform_point3(i.position()),
mesh_transform.transform_vector3(i.normal()),
mesh_transform
.transform_vector3(mesh_space_ray.direction() * i.distance())
.length(),
i.triangle().map(|tri| {
Triangle::from([
mesh_transform.transform_point3a(tri.v0),
mesh_transform.transform_point3a(tri.v1),
mesh_transform.transform_point3a(tri.v2),
])
}),
));
min_pick_distance = i.distance();
}
}
} else {
for i in (0..vertex_positions.len()).step_by(3) {
let tri_vertex_positions = [
Vec3A::from(vertex_positions[i]),
Vec3A::from(vertex_positions[i + 1]),
Vec3A::from(vertex_positions[i + 2]),
];
let tri_normals = vertex_normals.map(|normals| {
[
Vec3A::from(normals[i]),
Vec3A::from(normals[i + 1]),
Vec3A::from(normals[i + 2]),
]
});
let intersection = triangle_intersection(
tri_vertex_positions,
tri_normals,
min_pick_distance,
mesh_space_ray,
backface_culling,
);
if let Some(i) = intersection {
pick_intersection = Some(IntersectionData::new(
mesh_transform.transform_point3(i.position()),
mesh_transform.transform_vector3(i.normal()),
mesh_transform
.transform_vector3(mesh_space_ray.direction() * i.distance())
.length(),
i.triangle().map(|tri| {
Triangle::from([
mesh_transform.transform_point3a(tri.v0),
mesh_transform.transform_point3a(tri.v1),
mesh_transform.transform_point3a(tri.v2),
])
}),
));
min_pick_distance = i.distance();
}
}
}
pick_intersection
}
fn triangle_intersection(
tri_vertices: [Vec3A; 3],
tri_normals: Option<[Vec3A; 3]>,
max_distance: f32,
ray: Ray3d,
backface_culling: Backfaces,
) -> Option<IntersectionData> {
if tri_vertices
.iter()
.any(|&vertex| (vertex - ray.origin).length_squared() < max_distance.powi(2))
{
// Run the raycast on the ray and triangle
if let Some(ray_hit) = ray_triangle_intersection(&ray, &tri_vertices, backface_culling) {
let distance = *ray_hit.distance();
if distance > 0.0 && distance < max_distance {
let position = ray.position(distance);
let normal = if let Some(normals) = tri_normals {
let u = ray_hit.uv_coords().0;
let v = ray_hit.uv_coords().1;
let w = 1.0 - u - v;
normals[1] * u + normals[2] * v + normals[0] * w
} else {
(tri_vertices.v1() - tri_vertices.v0())
.cross(tri_vertices.v2() - tri_vertices.v0())
.normalize()
};
let intersection = IntersectionData::new(
position,
normal.into(),
distance,
Some(tri_vertices.to_triangle()),
);
return Some(intersection);
}
}
}
None
}
pub trait TriangleTrait {
fn v0(&self) -> Vec3A;
fn v1(&self) -> Vec3A;
fn v2(&self) -> Vec3A;
fn to_triangle(self) -> Triangle;
}
impl TriangleTrait for [Vec3A; 3] {
fn v0(&self) -> Vec3A {
self[0]
}
fn v1(&self) -> Vec3A {
self[1]
}
fn v2(&self) -> Vec3A {
self[2]
}
fn to_triangle(self) -> Triangle {
Triangle::from(self)
}
}
impl TriangleTrait for Triangle {
fn v0(&self) -> Vec3A {
self.v0
}
fn v1(&self) -> Vec3A {
self.v1
}
fn v2(&self) -> Vec3A {
self.v2
}
fn to_triangle(self) -> Triangle {
self
}
}
#[derive(Component)]
pub struct SimplifiedMesh {
pub mesh: Handle<Mesh>,
}
#[derive(Component)]
pub struct NoBackfaceCulling;
/// Used for examples to reduce picking latency. Not relevant code for the examples.
#[doc(hidden)]
#[allow(dead_code)]
pub fn low_latency_window_plugin() -> bevy::window::WindowPlugin {
bevy::window::WindowPlugin {
primary_window: Some(bevy::window::Window {
present_mode: bevy::window::PresentMode::AutoNoVsync,
..Default::default()
}),
..Default::default()
}
}