Compare commits

..

No commits in common. "main" and "shapecast" have entirely different histories.

6 changed files with 1208 additions and 846 deletions

1590
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -4,14 +4,12 @@ version = "0.1.0"
edition = "2024"
[dependencies]
bevy = { version = "0.16", features = ["bevy_dev_tools", "configurable_error_handler"] }
bevy = { version = "0.15", features = ["bevy_dev_tools"] }
bevy-inspector-egui = "0.29"
[dependencies.avian3d]
default-features = false
#version = "0.2"
git = "https://github.com/Jondolf/avian"
branch = "main"
version = "0.2"
features = ["3d", "f32", "parry-f32", "debug-plugin", "default-collider", "collider-from-mesh"]

View file

@ -1,24 +1,12 @@
use avian3d::{
math::{Scalar, FRAC_PI_2},
prelude::{
AngularDamping, Collider, ColliderDensity, CollisionLayers, ExternalForce, ExternalTorque,
LinearDamping, RayCaster, RigidBody, SleepingDisabled, SpatialQueryFilter,
TransformInterpolation,
},
};
use bevy::{
asset::Handle,
ecs::{bundle::Bundle, entity::Entity},
prelude::{
children, AlphaMode, App, Assets, Capsule3d, Color, Commands, Component, Dir3, Mesh,
Mesh3d, MeshMaterial3d, Name, Plugin, Reflect, ResMut, SpawnRelated, Sphere,
StandardMaterial, Startup, Transform, Vec3, Visibility,
},
prelude::*,
};
use bevy::prelude::*;
use crate::physics::CatControllerState;
pub const SPRING_CONSTANT: Scalar = 40.0;
pub const SPRING_CONSTANT: Scalar = 60.0;
pub const DAMPING_CONSTANT: Scalar = 10.0;
pub const WHEEL_RADIUS: Scalar = 0.4;
pub const REST_DISTANCE: Scalar = 1.5 + WHEEL_RADIUS;
@ -36,6 +24,7 @@ pub enum CyberWheel {
}
#[derive(Component, Clone, Copy, Debug, Reflect, Default)]
#[reflect(Component)]
pub struct WheelState {
pub displacement: Scalar,
pub force_normal: Scalar,
@ -51,6 +40,7 @@ impl WheelState {
}
#[derive(Component, Clone, Copy, Debug, Reflect)]
#[reflect(Component)]
#[require(WheelState)]
pub struct WheelConfig {
pub attach: Vec3,
@ -92,21 +82,9 @@ fn spawn_bike(
let body_collider =
Collider::capsule_endpoints(0.5, Vec3::new(0.0, 0.0, -0.65), Vec3::new(0.0, 0.0, 0.8));
let pbr_bundle = {
let color = Color::srgb(0.7, 0.05, 0.7);
let mut xform = Transform::default();
xform.rotate_x(FRAC_PI_2);
(
Mesh3d(meshes.add(Capsule3d::new(0.5, 1.45))),
xform,
Visibility::Visible,
MeshMaterial3d(materials.add(color)),
TransformInterpolation,
)
};
let mut body = commands.spawn((xform, Visibility::default()));
body.insert((
commands
.spawn((xform, Visibility::default()))
.insert((
Name::new("body"),
RigidBody::Dynamic,
body_collider,
@ -114,91 +92,127 @@ fn spawn_bike(
SleepingDisabled,
CyberBikeBody,
CatControllerState::default(),
ColliderDensity(1.6),
ColliderDensity(1.2),
AngularDamping(0.2),
LinearDamping(0.1),
ExternalForce::ZERO.with_persistence(false),
ExternalTorque::ZERO.with_persistence(false),
));
body.insert(spawn_children(body.id(), meshes, materials))
.with_child(pbr_bundle);
))
.with_children(|builder| {
let color = Color::srgb(0.7, 0.05, 0.7);
let mut xform = Transform::default();
xform.rotate_x(FRAC_PI_2);
let pbr_bundle = (
Mesh3d(meshes.add(Capsule3d::new(0.5, 1.45))),
xform,
MeshMaterial3d(materials.add(color)),
);
builder.spawn(pbr_bundle);
spawn_wheels(builder, meshes, materials, builder.parent_entity());
});
}
fn spawn_children(
parent: Entity,
fn spawn_wheels(
commands: &mut ChildBuilder,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) -> impl Bundle {
body: Entity,
) {
let mesh: Mesh = Sphere::new(WHEEL_RADIUS).into();
let wheel_material = StandardMaterial {
let front_rake = Vec3::new(0.0, -1.0, -0.9).normalize(); // about 30 degrees
let front_wheel_pos = FRONT_ATTACH + (front_rake * REST_DISTANCE);
wheel_caster(
commands,
FRONT_ATTACH,
Dir3::new_unchecked(front_rake),
body,
REST_DISTANCE,
CyberWheel::Front,
);
wheel_mesh(
commands,
&mut meshes,
&mut materials,
front_wheel_pos,
mesh.clone(),
WheelConfig::new(
FRONT_ATTACH,
REST_DISTANCE,
SPRING_CONSTANT,
DAMPING_CONSTANT,
FRICTION_COEFF,
WHEEL_RADIUS,
),
CyberWheel::Front,
);
let rear_rake = Vec3::new(0.0, -1.0, 0.9).normalize();
let rear_wheel_pos = REAR_ATTACH + (rear_rake * REST_DISTANCE);
wheel_caster(
commands,
REAR_ATTACH,
Dir3::new_unchecked(rear_rake),
body,
REST_DISTANCE,
CyberWheel::Rear,
);
wheel_mesh(
commands,
&mut meshes,
&mut materials,
rear_wheel_pos,
mesh,
WheelConfig::new(
REAR_ATTACH,
REST_DISTANCE,
SPRING_CONSTANT,
DAMPING_CONSTANT,
FRICTION_COEFF,
WHEEL_RADIUS,
),
CyberWheel::Rear,
);
}
//-************************************************************************
// helper fns for the wheels
//-************************************************************************
fn wheel_caster(
commands: &mut ChildBuilder,
origin: Vec3,
direction: Dir3,
parent: Entity,
rest_dist: Scalar,
wheel: CyberWheel,
) {
let caster = RayCaster::new(origin, direction)
.with_max_distance(rest_dist)
.with_max_hits(1)
.with_query_filter(SpatialQueryFilter::from_excluded_entities([parent]));
commands.spawn((caster, wheel));
}
fn wheel_mesh(
commands: &mut ChildBuilder,
meshes: &mut ResMut<Assets<Mesh>>,
materials: &mut ResMut<Assets<StandardMaterial>>,
position: Vec3,
tire_mesh: Mesh,
config: WheelConfig,
wheel: CyberWheel,
) {
let wheel_material = &StandardMaterial {
base_color: Color::srgb(0.01, 0.01, 0.01),
alpha_mode: AlphaMode::Opaque,
perceptual_roughness: 0.5,
..Default::default()
};
let mesh = meshes.add(mesh);
let material = materials.add(wheel_material);
let front_rake = Vec3::new(0.0, -1.0, -0.9).normalize(); // about 30 degrees
let front_wheel_pos = FRONT_ATTACH + (front_rake * REST_DISTANCE);
let rear_rake = Vec3::new(0.0, -1.0, 0.9).normalize();
let rear_wheel_pos = REAR_ATTACH + (rear_rake * REST_DISTANCE);
children![
(
RayCaster::new(FRONT_ATTACH, Dir3::new_unchecked(front_rake))
.with_max_hits(1)
.with_max_distance(REST_DISTANCE)
.with_query_filter(SpatialQueryFilter::from_excluded_entities([parent])),
CyberWheel::Front
),
wheel_bundle(
mesh.clone(),
material.clone(),
front_wheel_pos,
WheelConfig::new(
FRONT_ATTACH,
REST_DISTANCE,
SPRING_CONSTANT - 5.0,
DAMPING_CONSTANT,
FRICTION_COEFF,
WHEEL_RADIUS,
),
CyberWheel::Front,
),
(
RayCaster::new(REAR_ATTACH, Dir3::new_unchecked(rear_rake))
.with_max_hits(1)
.with_max_distance(REST_DISTANCE)
.with_query_filter(SpatialQueryFilter::from_excluded_entities([parent])),
CyberWheel::Rear,
),
wheel_bundle(
mesh,
material,
rear_wheel_pos,
WheelConfig::new(
REAR_ATTACH,
REST_DISTANCE,
SPRING_CONSTANT + 10.0,
DAMPING_CONSTANT,
FRICTION_COEFF,
WHEEL_RADIUS,
),
CyberWheel::Rear,
),
]
}
fn wheel_bundle(
mesh: Handle<Mesh>,
material: Handle<StandardMaterial>,
position: Vec3,
config: WheelConfig,
wheel: CyberWheel,
) -> impl Bundle {
let xform = Transform::from_translation(position);
let name = match wheel {
@ -206,18 +220,15 @@ fn wheel_bundle(
CyberWheel::Rear => "rear tire",
};
(
commands.spawn((
Name::new(name),
config,
Mesh3d(mesh),
MeshMaterial3d(material),
Mesh3d(meshes.add(tire_mesh)),
MeshMaterial3d(materials.add(wheel_material.clone())),
xform,
Collider::sphere(WHEEL_RADIUS),
ColliderDensity(0.5),
CollisionLayers::NONE,
TransformInterpolation,
wheel,
)
));
}
pub struct CyberBikePlugin;

View file

@ -1,10 +1,4 @@
use bevy::{
platform::collections::HashSet,
prelude::{
App, ButtonInput, Camera3d, Commands, Component, KeyCode, Plugin, Quat, Query, Res, ResMut,
Resource, Result, Startup, Transform, Update, Vec, Vec3, With, Without,
},
};
use bevy::{prelude::*, utils::HashSet};
use crate::bike::CyberBikeBody;
@ -71,8 +65,8 @@ fn follow_bike(
mut camera: Query<&mut Transform, (With<CyberCameras>, Without<CyberBikeBody>)>,
bike: Query<&Transform, (With<CyberBikeBody>, Without<CyberCameras>)>,
offset: Res<DebugCamOffset>,
) -> Result {
let bike_xform = *bike.single()?;
) {
let bike_xform = *bike.single();
let up = Vec3::Y;
let mut ncx = Transform::from_translation(bike_xform.translation);
@ -81,10 +75,8 @@ fn follow_bike(
ncx.translation += ncx.up() * offset.alt;
ncx.look_at(bike_xform.translation, up);
let mut cam_xform = camera.single_mut()?;
let mut cam_xform = camera.single_mut();
*cam_xform = ncx;
Ok(())
}
pub struct CamPlug;

View file

@ -5,12 +5,13 @@ use bevy::{
color::{palettes::css::SILVER, Alpha},
pbr::MeshMaterial3d,
prelude::{
children, default, App, AppGizmoBuilder, Assets, ButtonInput, Color, Commands,
DefaultPlugins, Entity, GizmoConfig, KeyCode, Mesh, Mesh3d, Meshable, Plane3d, PointLight,
Query, Res, ResMut, SpawnRelated, Srgba, StandardMaterial, Startup, Transform, Update,
Vec3, Visibility, Window,
default, App, AppGizmoBuilder, Assets, BuildChildren, ButtonInput, ChildBuild, Color,
Commands, DefaultPlugins, Entity, GizmoConfig, KeyCode, Mesh, Mesh3d, Meshable, Plane3d,
PointLight, Query, Res, ResMut, Srgba, StandardMaterial, Startup, Transform, Update, Vec3,
Visibility, Window,
},
};
use bevy_inspector_egui::quick::WorldInspectorPlugin;
mod bike;
mod camera;
@ -30,6 +31,7 @@ fn main() {
CyberBikePlugin,
CyberInputPlugin,
CyberPhysicsPlugin,
WorldInspectorPlugin::new(),
))
.insert_gizmo_config(
PhysicsGizmos {
@ -54,7 +56,8 @@ fn ground_and_light(
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let spatial_bundle = (Transform::default(), Visibility::default());
commands.spawn((
commands
.spawn((
spatial_bundle,
RigidBody::Static,
Collider::cuboid(500.0, 5., 500.0),
@ -62,13 +65,16 @@ fn ground_and_light(
ColliderDensity(1000.0),
CollisionLayers::ALL,
Friction::new(0.9),
children![(
))
.with_children(|p| {
let bundle = (
Mesh3d(meshes.add(Plane3d::default().mesh().size(500.0, 500.0))),
MeshMaterial3d(materials.add(Color::from(SILVER).with_alpha(0.7))),
Transform::from_xyz(0.0, 2.5, 0.0),
Visibility::Visible,
)],
));
);
p.spawn(bundle);
});
commands.spawn((
PointLight {

View file

@ -1,16 +1,16 @@
use avian3d::{math::Scalar, prelude::*};
use bevy::prelude::{
App, Component, FixedUpdate, IntoScheduleConfigs, Plugin, ResMut, Resource, Startup, Update,
};
use bevy::prelude::*;
const DRAG_COEFF: Scalar = 0.00001;
const DRAG_COEFF: Scalar = 0.1;
#[derive(Resource, Default, Debug)]
#[derive(Resource, Default, Debug, Reflect)]
#[reflect(Resource)]
struct CyberLean {
pub lean: f32,
}
#[derive(Debug, Resource)]
#[derive(Debug, Resource, Reflect)]
#[reflect(Resource)]
pub struct CatControllerSettings {
pub kp: f32,
pub kd: f32,
@ -20,14 +20,14 @@ pub struct CatControllerSettings {
impl Default for CatControllerSettings {
fn default() -> Self {
Self {
kp: 60.0,
kd: 30.0,
ki: 0.0,
kp: 16.0,
kd: 2.0,
ki: 0.9,
}
}
}
#[derive(Component, Debug, Clone, Copy)]
#[derive(Component, Debug, Clone, Copy, Reflect)]
pub struct CatControllerState {
pub roll_integral: f32,
pub roll_prev: f32,
@ -57,17 +57,8 @@ impl CatControllerState {
mod systems {
use std::f32::consts::{FRAC_PI_3, FRAC_PI_4};
use avian3d::prelude::{
ComputedCenterOfMass, ExternalForce, ExternalTorque, Gravity, LinearVelocity, RayCaster,
RayHits, RigidBodyQueryReadOnly,
};
use bevy::{
ecs::system::{Populated, Single},
prelude::{
ButtonInput, Color, Gizmos, GlobalTransform, KeyCode, Quat, Res, ResMut, Time,
Transform, Vec, Vec3, With, Without,
},
};
use avian3d::prelude::*;
use bevy::prelude::*;
use super::{CatControllerSettings, CatControllerState, CyberLean, DRAG_COEFF};
use crate::{
@ -87,8 +78,8 @@ mod systems {
}
pub(super) fn calculate_lean(
bike_state: Single<(&LinearVelocity, &Transform), With<CyberBikeBody>>,
wheels: Populated<&GlobalTransform, With<CyberWheel>>,
bike_state: Query<(&LinearVelocity, &Transform), With<CyberBikeBody>>,
wheels: Query<&GlobalTransform, With<CyberWheel>>,
input: Res<InputState>,
gravity: Res<Gravity>,
mut lean: ResMut<CyberLean>,
@ -97,7 +88,7 @@ mod systems {
let w1 = wheels.next().unwrap();
let w2 = wheels.next().unwrap();
let base = (w1.translation() - w2.translation()).length().abs();
let (velocity, xform) = bike_state.into_inner();
let (velocity, xform) = bike_state.single();
let vel = velocity.dot(*xform.forward());
let v_squared = vel.powi(2);
let steering_angle = yaw_to_angle(input.yaw);
@ -114,33 +105,21 @@ mod systems {
}
pub(super) fn apply_lean(
bike_query: Single<(&Transform, &mut ExternalTorque, &mut CatControllerState)>,
wheels: Populated<(&WheelState, &GlobalTransform, &CyberWheel)>,
mut bike_query: Query<(&Transform, &mut ExternalForce, &mut CatControllerState)>,
wheels: Query<&WheelState>,
time: Res<Time>,
settings: Res<CatControllerSettings>,
lean: Res<CyberLean>,
mut gizmos: Gizmos,
) {
let (xform, mut torque, mut control_vars) = bike_query.into_inner();
let (xform, mut force, mut control_vars) = bike_query.single_mut();
let mut factor = 1.0;
let mut rxform = GlobalTransform::default();
let mut fxform = GlobalTransform::default();
for (wheel_state, xform, cwheel) in wheels.iter() {
if wheel_state.contact_point.is_none() {
for wheel in wheels.iter() {
if wheel.contact_point.is_none() {
factor -= 0.25;
}
match cwheel {
CyberWheel::Front => {
fxform = *xform;
}
CyberWheel::Rear => {
rxform = *xform;
}
}
}
let tork_axis = (rxform.translation() - fxform.translation()).normalize();
let world_up = Vec3::Y; //xform.translation.normalize();
let rot = Quat::from_axis_angle(*xform.back(), lean.lean);
@ -171,14 +150,15 @@ mod systems {
let mag =
(settings.kp * roll_error) + (settings.ki * integral) + (settings.kd * derivative);
if mag.is_finite() {
//let lean_force = factor * mag * *xform.left();
let tork = factor * mag * tork_axis;
torque.apply_torque(tork);
let lean_force = factor * mag * *xform.left();
force.apply_force_at_point(
lean_force,
xform.translation + *xform.up(),
xform.translation,
);
gizmos.arrow(
xform.translation + *xform.up(),
xform.translation + *xform.up() + mag * xform.left(),
xform.translation + *xform.up() + lean_force,
Color::WHITE,
);
}
@ -195,15 +175,12 @@ mod systems {
}
pub(super) fn suspension(
bike_body_query: Single<
(&Transform, &ComputedCenterOfMass, &mut ExternalForce),
With<CyberBikeBody>,
>,
mut wheel_mesh_query: Populated<
mut bike_body_query: Query<(&Transform, &mut ExternalForce), With<CyberBikeBody>>,
mut wheel_mesh_query: Query<
(&mut Transform, &mut WheelState, &WheelConfig, &CyberWheel),
Without<CyberBikeBody>,
>,
caster_query: Populated<(&RayCaster, &RayHits, &CyberWheel)>,
caster_query: Query<(&RayCaster, &RayHits, &CyberWheel)>,
time: Res<Time>,
mut gizmos: Gizmos,
) {
@ -228,7 +205,7 @@ mod systems {
}
}
let (bike_xform, com, mut bike_forces) = bike_body_query.into_inner();
let (bike_xform, mut bike_forces) = bike_body_query.single_mut();
for (mut xform, mut state, config, wheel) in wheel_mesh_query.iter_mut() {
let (caster, hits) = match wheel {
@ -260,7 +237,11 @@ mod systems {
hit_point + force,
Color::linear_rgb(1., 0.5, 0.2),
);
bike_forces.apply_force_at_point(force, hit_point, bike_xform.translation + com.0);
bike_forces.apply_force_at_point(
force,
caster.global_origin(),
bike_xform.translation,
);
} else {
xform.translation = config.attach + (caster.direction.as_vec3() * config.rest_dist);
state.reset();
@ -268,8 +249,8 @@ mod systems {
}
}
pub(super) fn wheel_action(
bike_query: Single<
pub(super) fn steering(
mut bike_query: Query<
(
&Transform,
&LinearVelocity,
@ -278,16 +259,20 @@ mod systems {
),
With<CyberBikeBody>,
>,
mut wheels: Populated<(&mut WheelState, &WheelConfig, &CyberWheel)>,
mut wheels: Query<(&mut WheelState, &WheelConfig, &CyberWheel)>,
time: Res<Time>,
input: Res<InputState>,
mut gizmos: Gizmos,
) {
let (bike_xform, bike_vel, mut bike_force, bike_body) = bike_query.into_inner();
let Ok((bike_xform, bike_vel, mut bike_force, bike_body)) = bike_query.get_single_mut()
else {
bevy::log::warn!("No entity for bike_query.");
return;
};
let bike_vel = bike_vel.0;
let dt = time.delta().as_secs_f32();
let max_thrust = 500.0;
let max_thrust = 2000.0;
let yaw_angle = -yaw_to_angle(input.yaw);
for (mut state, config, wheel) in wheels.iter_mut() {
@ -300,8 +285,8 @@ mod systems {
let forward = normal.cross(*bike_xform.right());
let thrust_mag = input.throttle * max_thrust * dt;
let (thrust_dir, thrust_force) = match wheel {
CyberWheel::Rear => (forward, thrust_mag),
CyberWheel::Front => (rot * forward, thrust_mag * 0.1),
CyberWheel::Rear => (forward, thrust_mag * 0.1),
CyberWheel::Front => (rot * forward, thrust_mag),
};
let thrust = thrust_force * thrust_dir;
@ -328,11 +313,7 @@ mod systems {
state.sliding = false;
}
bike_force.apply_force_at_point(
force,
contact_point,
bike_xform.translation + bike_body.center_of_mass.0,
);
bike_force.apply_force_at_point(force, contact_point, bike_xform.translation);
gizmos.arrow(
contact_point,
contact_point + friction,
@ -348,35 +329,26 @@ mod systems {
}
pub(super) fn drag(
bike_query: Single<
(
&Transform,
&LinearVelocity,
&ComputedCenterOfMass,
&mut ExternalForce,
),
mut bike_query: Query<
(&Transform, &LinearVelocity, &mut ExternalForce),
With<CyberBikeBody>,
>,
mut gizmos: Gizmos,
time: Res<Time>,
) {
let (xform, vel, com, mut force) = bike_query.into_inner();
let (xform, vel, mut force) = bike_query.single_mut();
let dt = time.delta_secs();
let speed = vel.length_squared();
let dspeed = speed * 0.0000001;
let speed = vel.length();
let dspeed = speed.powf(1.2) * 0.1;
let dir = vel.normalize_or_zero();
let drag = -dspeed * dt * DRAG_COEFF * dir;
if speed > 0.1 {
force.apply_force_at_point(
drag,
xform.translation - (0.2 * *xform.down()),
xform.translation + com.0,
);
if speed > 1.0 {
force.apply_force_at_point(drag, xform.translation, xform.translation);
}
bevy::log::debug!("speed: {}, drag force: {}", vel.length(), drag.length());
bevy::log::debug!("speed: {}, drag force: {}", speed, drag.length());
gizmos.arrow(
xform.translation,
@ -386,7 +358,7 @@ mod systems {
}
pub(super) fn tweak(
mut config: Populated<&mut WheelConfig>,
mut config: Query<&mut WheelConfig>,
mut keys: ResMut<ButtonInput<KeyCode>>,
) {
let keyset: std::collections::HashSet<_> = keys.get_pressed().collect();
@ -423,14 +395,17 @@ mod systems {
}
}
use systems::{apply_lean, calculate_lean, drag, suspension, tweak, wheel_action};
use systems::{apply_lean, calculate_lean, drag, steering, suspension, tweak};
pub struct CyberPhysicsPlugin;
impl Plugin for CyberPhysicsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<CatControllerSettings>()
.register_type::<CatControllerSettings>()
.register_type::<CatControllerState>()
.init_resource::<CyberLean>()
.register_type::<CyberLean>()
.add_plugins((PhysicsPlugins::default(), PhysicsDebugPlugin::default()))
.insert_resource(SubstepCount(12))
.add_systems(Startup, |mut gravity: ResMut<Gravity>| {
@ -438,7 +413,7 @@ impl Plugin for CyberPhysicsPlugin {
})
.add_systems(
FixedUpdate,
(calculate_lean, apply_lean, suspension, wheel_action, drag).chain(),
(calculate_lean, apply_lean, suspension, steering, drag).chain(),
)
.add_systems(Update, tweak);
}