Compare commits

...

2 commits

Author SHA1 Message Date
Joe Ardent
b54e0a637f works 2025-04-26 16:32:31 -07:00
Joe Ardent
3777f120e7 bike hierarchy is boned 2025-04-26 15:18:18 -07:00
6 changed files with 781 additions and 1140 deletions

1576
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

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

View file

@ -1,12 +1,24 @@
use avian3d::{
math::{Scalar, FRAC_PI_2},
prelude::*,
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,
},
};
use bevy::prelude::*;
use crate::physics::CatControllerState;
pub const SPRING_CONSTANT: Scalar = 60.0;
pub const SPRING_CONSTANT: Scalar = 50.0;
pub const DAMPING_CONSTANT: Scalar = 10.0;
pub const WHEEL_RADIUS: Scalar = 0.4;
pub const REST_DISTANCE: Scalar = 1.5 + WHEEL_RADIUS;
@ -24,7 +36,6 @@ pub enum CyberWheel {
}
#[derive(Component, Clone, Copy, Debug, Reflect, Default)]
#[reflect(Component)]
pub struct WheelState {
pub displacement: Scalar,
pub force_normal: Scalar,
@ -40,7 +51,6 @@ impl WheelState {
}
#[derive(Component, Clone, Copy, Debug, Reflect)]
#[reflect(Component)]
#[require(WheelState)]
pub struct WheelConfig {
pub attach: Vec3,
@ -82,99 +92,105 @@ 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));
commands
.spawn((xform, Visibility::default()))
.insert((
Name::new("body"),
RigidBody::Dynamic,
body_collider,
CollisionLayers::from_bits(1, 1),
SleepingDisabled,
CyberBikeBody,
CatControllerState::default(),
ColliderDensity(1.2),
AngularDamping(0.2),
LinearDamping(0.1),
ExternalForce::ZERO.with_persistence(false),
ExternalTorque::ZERO.with_persistence(false),
))
.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());
});
let mut body = commands.spawn((xform, Visibility::default()));
body.insert((
Name::new("body"),
RigidBody::Dynamic,
body_collider,
CollisionLayers::from_bits(1, 1),
SleepingDisabled,
CyberBikeBody,
CatControllerState::default(),
ColliderDensity(1.4),
AngularDamping(0.2),
LinearDamping(0.1),
ExternalForce::ZERO.with_persistence(false),
ExternalTorque::ZERO.with_persistence(false),
));
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 parent = body.id();
body.insert(spawn_children(parent, pbr_bundle, meshes, materials));
}
fn spawn_wheels(
commands: &mut ChildBuilder,
fn spawn_children(
parent: Entity,
body: impl Bundle,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
body: Entity,
) {
) -> impl Bundle {
let mesh: Mesh = Sphere::new(WHEEL_RADIUS).into();
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);
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),
children!(
body,
REST_DISTANCE,
CyberWheel::Rear,
);
wheel_mesh(
commands,
&mut meshes,
&mut materials,
rear_wheel_pos,
mesh,
WheelConfig::new(
REAR_ATTACH,
wheel_caster(
parent,
FRONT_ATTACH,
Dir3::new_unchecked(front_rake),
REST_DISTANCE,
SPRING_CONSTANT,
DAMPING_CONSTANT,
FRICTION_COEFF,
WHEEL_RADIUS,
CyberWheel::Front,
),
CyberWheel::Rear,
);
wheel_mesh(
mesh.clone(),
material.clone(),
front_wheel_pos,
WheelConfig::new(
FRONT_ATTACH,
REST_DISTANCE,
SPRING_CONSTANT,
DAMPING_CONSTANT,
FRICTION_COEFF,
WHEEL_RADIUS,
),
CyberWheel::Front,
),
wheel_caster(
parent,
REAR_ATTACH,
Dir3::new_unchecked(rear_rake),
REST_DISTANCE,
CyberWheel::Rear,
),
wheel_mesh(
mesh,
material,
rear_wheel_pos,
WheelConfig::new(
REAR_ATTACH,
REST_DISTANCE,
SPRING_CONSTANT,
DAMPING_CONSTANT,
FRICTION_COEFF,
WHEEL_RADIUS,
),
CyberWheel::Rear,
),
)
}
//-************************************************************************
@ -182,37 +198,27 @@ fn spawn_wheels(
//-************************************************************************
fn wheel_caster(
commands: &mut ChildBuilder,
parent: Entity,
origin: Vec3,
direction: Dir3,
parent: Entity,
rest_dist: Scalar,
wheel: CyberWheel,
) {
) -> impl Bundle {
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));
(caster, wheel)
}
fn wheel_mesh(
commands: &mut ChildBuilder,
meshes: &mut ResMut<Assets<Mesh>>,
materials: &mut ResMut<Assets<StandardMaterial>>,
mesh: Handle<Mesh>,
material: Handle<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()
};
) -> impl Bundle {
let xform = Transform::from_translation(position);
let name = match wheel {
@ -220,18 +226,18 @@ fn wheel_mesh(
CyberWheel::Rear => "rear tire",
};
commands.spawn((
(
Name::new(name),
config,
Mesh3d(meshes.add(tire_mesh)),
MeshMaterial3d(materials.add(wheel_material.clone())),
Mesh3d(mesh),
MeshMaterial3d(material),
xform,
Collider::sphere(WHEEL_RADIUS),
ColliderDensity(0.5),
CollisionLayers::NONE,
TransformInterpolation,
wheel,
));
)
}
pub struct CyberBikePlugin;

View file

@ -1,4 +1,10 @@
use bevy::{prelude::*, utils::HashSet};
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 crate::bike::CyberBikeBody;
@ -65,8 +71,8 @@ fn follow_bike(
mut camera: Query<&mut Transform, (With<CyberCameras>, Without<CyberBikeBody>)>,
bike: Query<&Transform, (With<CyberBikeBody>, Without<CyberCameras>)>,
offset: Res<DebugCamOffset>,
) {
let bike_xform = *bike.single();
) -> Result {
let bike_xform = *bike.single()?;
let up = Vec3::Y;
let mut ncx = Transform::from_translation(bike_xform.translation);
@ -75,8 +81,10 @@ 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

@ -3,15 +3,15 @@ use avian3d::prelude::{
};
use bevy::{
color::{palettes::css::SILVER, Alpha},
ecs::error::{warn, GLOBAL_ERROR_HANDLER},
pbr::MeshMaterial3d,
prelude::{
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,
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,
},
};
use bevy_inspector_egui::quick::WorldInspectorPlugin;
mod bike;
mod camera;
@ -24,6 +24,10 @@ use input::CyberInputPlugin;
use physics::CyberPhysicsPlugin;
fn main() {
GLOBAL_ERROR_HANDLER
.set(warn)
.expect("The error handler can only be set once, globally.");
// initialize Bevy App here
let mut app = App::new();
app.add_plugins((
DefaultPlugins,
@ -31,7 +35,6 @@ fn main() {
CyberBikePlugin,
CyberInputPlugin,
CyberPhysicsPlugin,
WorldInspectorPlugin::new(),
))
.insert_gizmo_config(
PhysicsGizmos {
@ -56,25 +59,21 @@ fn ground_and_light(
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let spatial_bundle = (Transform::default(), Visibility::default());
commands
.spawn((
spatial_bundle,
RigidBody::Static,
Collider::cuboid(500.0, 5., 500.0),
CollisionMargin(0.1),
ColliderDensity(1000.0),
CollisionLayers::ALL,
Friction::new(0.9),
))
.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((
spatial_bundle,
RigidBody::Static,
Collider::cuboid(500.0, 5., 500.0),
CollisionMargin(0.1),
ColliderDensity(1000.0),
CollisionLayers::ALL,
Friction::new(0.9),
children![(
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,
)],
));
commands.spawn((
PointLight {

View file

@ -1,16 +1,16 @@
use avian3d::{math::Scalar, prelude::*};
use bevy::prelude::*;
use bevy::prelude::{
App, Component, FixedUpdate, IntoScheduleConfigs, Plugin, ResMut, Resource, Startup, Update,
};
const DRAG_COEFF: Scalar = 0.00001;
#[derive(Resource, Default, Debug, Reflect)]
#[reflect(Resource)]
#[derive(Resource, Default, Debug)]
struct CyberLean {
pub lean: f32,
}
#[derive(Debug, Resource, Reflect)]
#[reflect(Resource)]
#[derive(Debug, Resource)]
pub struct CatControllerSettings {
pub kp: f32,
pub kd: f32,
@ -27,7 +27,7 @@ impl Default for CatControllerSettings {
}
}
#[derive(Component, Debug, Clone, Copy, Reflect)]
#[derive(Component, Debug, Clone, Copy)]
pub struct CatControllerState {
pub roll_integral: f32,
pub roll_prev: f32,
@ -58,7 +58,13 @@ mod systems {
use std::f32::consts::{FRAC_PI_3, FRAC_PI_4};
use avian3d::prelude::*;
use bevy::prelude::*;
use bevy::{
ecs::error::BevyError,
prelude::{
ButtonInput, Color, Gizmos, GlobalTransform, KeyCode, Quat, Query, Res, ResMut, Result,
Time, Transform, Vec, Vec3, With, Without,
},
};
use super::{CatControllerSettings, CatControllerState, CyberLean, DRAG_COEFF};
use crate::{
@ -83,12 +89,12 @@ mod systems {
input: Res<InputState>,
gravity: Res<Gravity>,
mut lean: ResMut<CyberLean>,
) {
) -> Result {
let mut wheels = wheels.iter();
let w1 = wheels.next().unwrap();
let w2 = wheels.next().unwrap();
let w1 = wheels.next().ok_or(BevyError::from("oops"))?;
let w2 = wheels.next().ok_or(BevyError::from("oops"))?;
let base = (w1.translation() - w2.translation()).length().abs();
let (velocity, xform) = bike_state.single();
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);
@ -102,6 +108,7 @@ mod systems {
} else {
//lean.lean = 0.0;
}
Ok(())
}
pub(super) fn apply_lean(
@ -111,8 +118,8 @@ mod systems {
settings: Res<CatControllerSettings>,
lean: Res<CyberLean>,
mut gizmos: Gizmos,
) {
let (xform, mut force, mut control_vars) = bike_query.single_mut();
) -> Result {
let (xform, mut force, mut control_vars) = bike_query.single_mut()?;
let mut factor = 1.0;
for wheel in wheels.iter() {
@ -163,6 +170,7 @@ mod systems {
);
}
}
Ok(())
}
fn yaw_to_angle(yaw: f32) -> f32 {
@ -183,7 +191,7 @@ mod systems {
caster_query: Query<(&RayCaster, &RayHits, &CyberWheel)>,
time: Res<Time>,
mut gizmos: Gizmos,
) {
) -> Result {
let dt = time.delta().as_secs_f32();
let mut front_caster = &RayCaster::default();
@ -205,7 +213,7 @@ mod systems {
}
}
let (bike_xform, mut bike_forces) = bike_body_query.single_mut();
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 {
@ -247,6 +255,7 @@ mod systems {
state.reset();
}
}
Ok(())
}
pub(super) fn steering(
@ -263,12 +272,8 @@ mod systems {
time: Res<Time>,
input: Res<InputState>,
mut gizmos: Gizmos,
) {
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;
};
) -> Result {
let (bike_xform, bike_vel, mut bike_force, bike_body) = bike_query.single_mut()?;
let bike_vel = bike_vel.0;
let dt = time.delta().as_secs_f32();
@ -326,6 +331,8 @@ mod systems {
);
}
}
Ok(())
}
pub(super) fn drag(
@ -335,8 +342,8 @@ mod systems {
>,
mut gizmos: Gizmos,
time: Res<Time>,
) {
let (xform, vel, mut force) = bike_query.single_mut();
) -> Result {
let (xform, vel, mut force) = bike_query.single_mut()?;
let dt = time.delta_secs();
@ -359,6 +366,8 @@ mod systems {
xform.translation + drag * 10.,
Color::linear_rgb(1.0, 0.0, 0.0),
);
Ok(())
}
pub(super) fn tweak(
@ -406,10 +415,7 @@ 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>| {