Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ray Casting for Primitive Shapes #15724

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3269,6 +3269,28 @@ description = "Exhibits different modes of constructing cubic curves using splin
category = "Math"
wasm = true

[[example]]
name = "ray_cast_2d"
path = "examples/math/ray_cast_2d.rs"
doc-scrape-examples = true

[package.metadata.example.ray_cast_2d]
name = "2D Ray Casting for Primitives"
description = "Shows off ray casting for primitive shapes in 2D"
category = "Math"
wasm = true

[[example]]
name = "ray_cast_3d"
path = "examples/math/ray_cast_3d.rs"
doc-scrape-examples = true

[package.metadata.example.ray_cast_3d]
name = "3D Ray Casting for Primitives"
description = "Shows off ray casting for primitive shapes in 3D"
category = "Math"
wasm = true

[[example]]
name = "render_primitives"
path = "examples/math/render_primitives.rs"
Expand Down
10 changes: 10 additions & 0 deletions benches/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ name = "bezier"
path = "benches/bevy_math/bezier.rs"
harness = false

[[bench]]
name = "ray_cast_2d"
path = "benches/bevy_math/ray_cast_2d.rs"
harness = false

[[bench]]
name = "ray_cast_3d"
path = "benches/bevy_math/ray_cast_3d.rs"
harness = false

[[bench]]
name = "torus"
path = "benches/bevy_render/torus.rs"
Expand Down
101 changes: 101 additions & 0 deletions benches/benches/bevy_math/ray_cast_2d.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use std::time::Duration;

use bevy_math::{prelude::*, FromRng, ShapeSample};
use criterion::{
black_box, criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion,
};
use rand::{rngs::StdRng, Rng, SeedableRng};

const SAMPLES: usize = 100_000;

fn bench_shape<S: PrimitiveRayCast2d>(
group: &mut BenchmarkGroup<'_, WallTime>,
rng: &mut StdRng,
name: &str,
shape_constructor: impl Fn(&mut StdRng) -> S,
) {
group.bench_function(format!("{name}_ray_cast"), |b| {
// Generate random shapes and rays.
let shapes = (0..SAMPLES)
.map(|_| shape_constructor(rng))
.collect::<Vec<_>>();
let rays = (0..SAMPLES)
.map(|_| Ray2d {
origin: Circle::new(10.0).sample_interior(rng),
direction: Dir2::from_rng(rng),
})
.collect::<Vec<_>>();
let items = shapes.into_iter().zip(rays).collect::<Vec<_>>();

// Cast rays against the shapes.
b.iter(|| {
items.iter().for_each(|(shape, ray)| {
black_box(shape.local_ray_cast(*ray, f32::MAX, false));
});
});
});
}

fn ray_cast_2d(c: &mut Criterion) {
let mut group = c.benchmark_group("ray_cast_2d_100k");
group.warm_up_time(Duration::from_millis(500));

let mut rng = StdRng::seed_from_u64(46);

bench_shape(&mut group, &mut rng, "circle", |rng| {
Circle::new(rng.gen_range(0.1..2.5))
});
bench_shape(&mut group, &mut rng, "arc", |rng| {
Arc2d::new(
rng.gen_range(0.1..2.5),
rng.gen_range(0.1..std::f32::consts::PI),
)
});
bench_shape(&mut group, &mut rng, "circular_sector", |rng| {
CircularSector::new(
rng.gen_range(0.1..2.5),
rng.gen_range(0.1..std::f32::consts::PI),
)
});
bench_shape(&mut group, &mut rng, "circular_segment", |rng| {
CircularSegment::new(
rng.gen_range(0.1..2.5),
rng.gen_range(0.1..std::f32::consts::PI),
)
});
bench_shape(&mut group, &mut rng, "ellipse", |rng| {
Ellipse::new(rng.gen_range(0.1..2.5), rng.gen_range(0.1..2.5))
});
bench_shape(&mut group, &mut rng, "annulus", |rng| {
Annulus::new(rng.gen_range(0.1..1.25), rng.gen_range(1.26..2.5))
});
bench_shape(&mut group, &mut rng, "capsule2d", |rng| {
Capsule2d::new(rng.gen_range(0.1..1.25), rng.gen_range(0.1..5.0))
});
bench_shape(&mut group, &mut rng, "rectangle", |rng| {
Rectangle::new(rng.gen_range(0.1..5.0), rng.gen_range(0.1..5.0))
});
bench_shape(&mut group, &mut rng, "rhombus", |rng| {
Rhombus::new(rng.gen_range(0.1..5.0), rng.gen_range(0.1..5.0))
});
bench_shape(&mut group, &mut rng, "line2d", |rng| Line2d {
direction: Dir2::from_rng(rng),
});
bench_shape(&mut group, &mut rng, "segment2d", |rng| Segment2d {
direction: Dir2::from_rng(rng),
half_length: rng.gen_range(0.1..5.0),
});
bench_shape(&mut group, &mut rng, "regular_polygon", |rng| {
RegularPolygon::new(rng.gen_range(0.1..2.5), rng.gen_range(3..6))
});
bench_shape(&mut group, &mut rng, "triangle2d", |rng| {
Triangle2d::new(
Vec2::new(rng.gen_range(-7.5..7.5), rng.gen_range(-7.5..7.5)),
Vec2::new(rng.gen_range(-7.5..7.5), rng.gen_range(-7.5..7.5)),
Vec2::new(rng.gen_range(-7.5..7.5), rng.gen_range(-7.5..7.5)),
)
});
}

criterion_group!(benches, ray_cast_2d);
criterion_main!(benches);
120 changes: 120 additions & 0 deletions benches/benches/bevy_math/ray_cast_3d.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
use std::time::Duration;

use bevy_math::{prelude::*, FromRng, ShapeSample};
use criterion::{
black_box, criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion,
};
use rand::{rngs::StdRng, Rng, SeedableRng};

const SAMPLES: usize = 100_000;

fn bench_shape<S: PrimitiveRayCast3d>(
group: &mut BenchmarkGroup<'_, WallTime>,
rng: &mut StdRng,
name: &str,
shape_constructor: impl Fn(&mut StdRng) -> S,
) {
group.bench_function(format!("{name}_ray_cast"), |b| {
// Generate random shapes and rays.
let shapes = (0..SAMPLES)
.map(|_| shape_constructor(rng))
.collect::<Vec<_>>();
let rays = (0..SAMPLES)
.map(|_| Ray3d {
origin: Sphere::new(10.0).sample_interior(rng),
direction: Dir3::from_rng(rng),
})
.collect::<Vec<_>>();
let items = shapes.into_iter().zip(rays).collect::<Vec<_>>();

// Cast rays against the shapes.
b.iter(|| {
items.iter().for_each(|(shape, ray)| {
black_box(shape.local_ray_cast(*ray, f32::MAX, false));
});
});
});
}

fn ray_cast_3d(c: &mut Criterion) {
let mut group = c.benchmark_group("ray_cast_3d_100k");
group.warm_up_time(Duration::from_millis(500));

let mut rng = StdRng::seed_from_u64(46);

bench_shape(&mut group, &mut rng, "sphere", |rng| {
Sphere::new(rng.gen_range(0.1..2.5))
});
bench_shape(&mut group, &mut rng, "cuboid", |rng| {
Cuboid::new(
rng.gen_range(0.1..5.0),
rng.gen_range(0.1..5.0),
rng.gen_range(0.1..5.0),
)
});
bench_shape(&mut group, &mut rng, "cylinder", |rng| {
Cylinder::new(rng.gen_range(0.1..2.5), rng.gen_range(0.1..5.0))
});
bench_shape(&mut group, &mut rng, "cone", |rng| {
Cone::new(rng.gen_range(0.1..2.5), rng.gen_range(0.1..5.0))
});
bench_shape(&mut group, &mut rng, "conical_frustum", |rng| {
ConicalFrustum {
radius_top: rng.gen_range(0.1..2.5),
radius_bottom: rng.gen_range(0.1..2.5),
height: rng.gen_range(0.1..5.0),
}
});
bench_shape(&mut group, &mut rng, "capsule3d", |rng| {
Capsule3d::new(rng.gen_range(0.1..2.5), rng.gen_range(0.1..5.0))
});
bench_shape(&mut group, &mut rng, "triangle3d", |rng| {
Triangle3d::new(
Vec3::new(
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
),
Vec3::new(
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
),
Vec3::new(
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
),
)
});
bench_shape(&mut group, &mut rng, "tetrahedron", |rng| {
Tetrahedron::new(
Vec3::new(
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
),
Vec3::new(
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
),
Vec3::new(
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
),
Vec3::new(
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
rng.gen_range(-7.5..7.5),
),
)
});
bench_shape(&mut group, &mut rng, "torus", |rng| {
Torus::new(rng.gen_range(0.1..1.25), rng.gen_range(1.26..2.5))
});
}

criterion_group!(benches, ray_cast_3d);
criterion_main!(benches);
2 changes: 2 additions & 0 deletions crates/bevy_math/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ mod isometry;
pub mod ops;
pub mod primitives;
mod ray;
pub mod ray_cast;
mod rects;
mod rotation2d;
#[cfg(feature = "rand")]
Expand Down Expand Up @@ -60,6 +61,7 @@ pub mod prelude {
direction::{Dir2, Dir3, Dir3A},
ops,
primitives::*,
ray_cast::{PrimitiveRayCast2d, PrimitiveRayCast3d, RayHit2d, RayHit3d},
BVec2, BVec3, BVec4, EulerRot, FloatExt, IRect, IVec2, IVec3, IVec4, Isometry2d,
Isometry3d, Mat2, Mat3, Mat4, Quat, Ray2d, Ray3d, Rect, Rot2, StableInterpolate, URect,
UVec2, UVec3, UVec4, Vec2, Vec2Swizzles, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles,
Expand Down
46 changes: 45 additions & 1 deletion crates/bevy_math/src/ray.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
primitives::{InfinitePlane3d, Plane2d},
Dir2, Dir3, Vec2, Vec3,
Dir2, Dir3, Isometry2d, Isometry3d, Vec2, Vec3,
};

#[cfg(feature = "bevy_reflect")]
Expand Down Expand Up @@ -55,6 +55,28 @@ impl Ray2d {
}
None
}

/// Returns `self` transformed by the given [isometry].
///
/// [isometry]: crate::Isometry2d
#[inline]
pub fn transformed_by(&self, isometry: Isometry2d) -> Self {
Self {
origin: isometry.transform_point(self.origin),
direction: isometry.rotation * self.direction,
}
}

/// Returns `self` transformed by the inverse of the given [isometry].
///
/// [isometry]: crate::Isometry2d
#[inline]
pub fn inverse_transformed_by(&self, isometry: Isometry2d) -> Self {
Self {
origin: isometry.inverse_transform_point(self.origin),
direction: isometry.rotation.inverse() * self.direction,
}
}
}

/// An infinite half-line starting at `origin` and going in `direction` in 3D space.
Expand Down Expand Up @@ -104,6 +126,28 @@ impl Ray3d {
}
None
}

/// Returns `self` transformed by the given [isometry].
///
/// [isometry]: crate::Isometry3d
#[inline]
pub fn transformed_by(&self, isometry: Isometry3d) -> Self {
Self {
origin: isometry.transform_point(self.origin).into(),
direction: isometry.rotation * self.direction,
}
}

/// Returns `self` transformed by the inverse of the given [isometry].
///
/// [isometry]: crate::Isometry3d
#[inline]
pub fn inverse_transformed_by(&self, isometry: Isometry3d) -> Self {
Self {
origin: isometry.inverse_transform_point(self.origin).into(),
direction: isometry.rotation.inverse() * self.direction,
}
}
}

#[cfg(test)]
Expand Down
Loading
Loading