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

Refine physics #2

Merged
merged 5 commits into from
Dec 9, 2023
Merged
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
11 changes: 0 additions & 11 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ edition = "2021"
[dependencies]
blade = { path = "../blade" }
egui = "0.23"
egui-gizmo = "0.12"
egui-winit = "0.23"
env_logger = "0.10"
nalgebra = { version = "0.32", features = ["mint"] }
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# RayCraft

A simple vehicle simulator based on [Blade engine](https://github.com/kvark/blade).

![colliders](etc/collider-boxes.jpg)
2 changes: 2 additions & 0 deletions data/config.ron
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
colliders: [
(
mass: 100000.0,
friction: 1.0,
pos: (0, -1, 0),
shape: Cuboid(
half: (100000, 1, 100000),
Expand All @@ -29,6 +30,7 @@
distance: 5,
azimuth: 0,
altitude: 0.5,
speed: 0.0,
target: (0, 1, 0),
fov: 1.0,
),
Expand Down
5 changes: 3 additions & 2 deletions data/vehicles/raceFuture.ron
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
),
collider: (
mass: 1.0,
friction: 2.0,
pos: (0, 0, 0),
rot: (0, 0, 90),
shape: Cylinder(
Expand All @@ -34,8 +35,8 @@
z: 0.5,
steer: (
max_angle: 30,
stiffness: 100,
damping: 0,
stiffness: 1000,
damping: 1,
),
),
(
Expand Down
Binary file added etc/collider-boxes.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
155 changes: 66 additions & 89 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ struct CameraConfig {
azimuth: f32,
altitude: f32,
distance: f32,
speed: f32,
target: [f32; 3],
fov: f32,
}
Expand All @@ -56,8 +57,9 @@ struct GameConfig {
}

struct Wheel {
_object: blade::ObjectHandle,
object: blade::ObjectHandle,
joint: blade::JointHandle,
local_rotation: nalgebra::UnitQuaternion<f32>,
}

struct WheelAxle {
Expand All @@ -76,7 +78,8 @@ struct Game {
// engine stuff
engine: blade::Engine,
last_physics_update: time::Instant,
is_paused: Option<egui_gizmo::GizmoMode>,
last_camera_base_quat: nalgebra::UnitQuaternion<f32>,
is_paused: bool,
// windowing
window: winit::window::Window,
egui_state: egui_winit::State,
Expand Down Expand Up @@ -125,7 +128,7 @@ impl Game {
let mut vehicle = Vehicle {
body_handle: engine.add_object(
&body_config,
nalgebra::Isometry3::translation(init_pos.x, init_pos.y, init_pos.z),
nalgebra::Isometry3::new(init_pos, nalgebra::Vector3::zeros()),
blade::BodyType::Dynamic,
),
drive_factor: veh_config.drive_factor,
Expand All @@ -136,6 +139,7 @@ impl Game {
visuals: vec![veh_config.wheel.visual],
colliders: vec![veh_config.wheel.collider],
};
//Note: in the vehicle coordinate system X=left, Y=up, Z=forward
for ac in veh_config.axles {
let offset_left = nalgebra::Vector3::new(ac.x, 0.0, ac.z);
let offset_right = nalgebra::Vector3::new(-ac.x, 0.0, ac.z);
Expand All @@ -154,6 +158,7 @@ impl Game {
blade::BodyType::Dynamic,
);

let joint_kind = blade::JointKind::Soft;
let has_steer = ac.steer.max_angle > 0.0;
let max_angle = ac.steer.max_angle.to_radians();
let locked_axes = if has_steer {
Expand All @@ -162,15 +167,16 @@ impl Game {
} else {
rapier3d::dynamics::JointAxesMask::LOCKED_REVOLUTE_AXES
};

let left_frame =
nalgebra::Isometry3::rotation(nalgebra::Vector3::y_axis().scale(consts::PI));
let joint_left = engine.add_joint(
vehicle.body_handle,
wheel_left,
rapier3d::dynamics::GenericJointBuilder::new(locked_axes)
.contacts_enabled(false)
.local_anchor1(offset_left.into())
.local_frame2(nalgebra::Isometry3::rotation(
nalgebra::Vector3::y_axis().scale(consts::PI),
))
.local_frame2(left_frame)
.limits(rapier3d::dynamics::JointAxis::AngY, [-max_angle, max_angle])
.motor_position(rapier3d::dynamics::JointAxis::AngX, 0.0, 1.0, 1.0)
.motor_position(
Expand All @@ -180,6 +186,7 @@ impl Game {
ac.steer.damping,
)
.build(),
joint_kind,
);
let joint_right = engine.add_joint(
vehicle.body_handle,
Expand All @@ -196,16 +203,19 @@ impl Game {
ac.steer.damping,
)
.build(),
joint_kind,
);

vehicle.wheel_axles.push(WheelAxle {
left: Wheel {
_object: wheel_left,
object: wheel_left,
joint: joint_left,
local_rotation: left_frame.rotation,
},
right: Wheel {
_object: wheel_right,
object: wheel_right,
joint: joint_right,
local_rotation: nalgebra::UnitQuaternion::default(),
},
steer: if has_steer { Some(ac.steer) } else { None },
});
Expand All @@ -214,7 +224,8 @@ impl Game {
Self {
engine,
last_physics_update: time::Instant::now(),
is_paused: None,
last_camera_base_quat: Default::default(),
is_paused: false,
window,
egui_state: egui_winit::State::new(event_loop),
egui_context: egui::Context::default(),
Expand All @@ -229,10 +240,10 @@ impl Game {
}

fn set_velocity(&mut self, velocity: f32) {
self.engine.wake_up(self.vehicle.body_handle);
for wax in self.vehicle.wheel_axles.iter() {
for &joint_handle in &[wax.left.joint, wax.right.joint] {
let joint = self.engine.get_joint_mut(joint_handle);
joint.data.set_motor_velocity(
self.engine[joint_handle].set_motor_velocity(
rapier3d::dynamics::JointAxis::AngX,
velocity,
self.vehicle.drive_factor,
Expand All @@ -248,8 +259,7 @@ impl Game {
None => continue,
};
for &joint_handle in &[wax.left.joint, wax.right.joint] {
let joint = self.engine.get_joint_mut(joint_handle);
joint.data.set_motor_position(
self.engine[joint_handle].set_motor_position(
rapier3d::dynamics::JointAxis::AngY,
angle_rad,
steer.stiffness,
Expand All @@ -259,6 +269,34 @@ impl Game {
}
}

/// When front wheels are steered, their axis changes.
/// This routine re-aligns the axis of rotation every frame.
fn align_wheels(&mut self) {
let veh_isometry = self.engine.get_object_isometry(self.vehicle.body_handle);
let veh_y_axis = veh_isometry.transform_vector(&nalgebra::Vector3::y_axis());
for wax in self.vehicle.wheel_axles.iter() {
if wax.steer.is_none() {
continue;
}
for &wheel in &[&wax.left, &wax.right] {
let w_isometry = *self.engine.get_object_isometry(wheel.object);
let mut joint = &mut self.engine[wheel.joint];
let veh_y_in_wheel_frame = w_isometry.inverse().transform_vector(&veh_y_axis);
let x_angle = veh_y_in_wheel_frame.z.atan2(veh_y_in_wheel_frame.y);
let sign = wheel
.local_rotation
.transform_vector(&nalgebra::Vector3::x_axis())
.x
.signum();
let local_rot = nalgebra::UnitQuaternion::from_axis_angle(
&nalgebra::Vector3::x_axis(),
sign * x_angle,
);
joint.local_frame2.rotation = wheel.local_rotation * local_rot;
}
}
}

fn on_event(&mut self, event: &winit::event::WindowEvent) -> bool {
let response = self.egui_state.on_event(&self.egui_context, event);
if response.consumed {
Expand Down Expand Up @@ -324,64 +362,6 @@ impl Game {
false
}

fn add_camera_manipulation(&mut self, ui: &mut egui::Ui) {
let mode = match self.is_paused {
Some(mode) => mode,
None => return,
};

let cc = &self.cam_config;
let eye_dir = nalgebra::Vector3::new(
-cc.azimuth.sin() * cc.altitude.cos(),
cc.altitude.sin(),
-cc.azimuth.cos() * cc.altitude.cos(),
);

let rotation = {
let z = eye_dir;
//let x = z.cross(&nalgebra::Vector3::y_axis()).normalize();
let x = nalgebra::Vector3::new(cc.azimuth.cos(), 0.0, -cc.azimuth.sin());
//let y = z.cross(&x);
let y = nalgebra::Vector3::new(
cc.altitude.sin() * -cc.azimuth.sin(),
-cc.altitude.cos(),
cc.altitude.sin() * -cc.azimuth.cos(),
);
nalgebra::geometry::UnitQuaternion::from_rotation_matrix(
&nalgebra::geometry::Rotation3::from_basis_unchecked(&[x, y, z]).transpose(),
)
};
let view = {
let t = rotation * (nalgebra::Vector3::from(cc.target) - eye_dir.scale(cc.distance));
nalgebra::geometry::Isometry3::from_parts(t.into(), rotation)
};

let aspect = self.engine.screen_aspect();
let depth_range = 1.0f32..10000.0; //TODO?
let projection_matrix =
nalgebra::Matrix4::new_perspective(aspect, cc.fov, depth_range.start, depth_range.end);

let gizmo = egui_gizmo::Gizmo::new("Object")
.model_matrix(view.to_homogeneous())
.projection_matrix(projection_matrix)
.mode(mode)
.orientation(egui_gizmo::GizmoOrientation::Global)
.snapping(true);

if let Some(result) = gizmo.interact(ui) {
let q = nalgebra::Unit::new_normalize(nalgebra::Quaternion::from(
result.rotation.to_array(),
));
let m = q.inverse().to_rotation_matrix();
self.cam_config.azimuth = -m[(2, 0)].atan2(m[(0, 0)]);
self.cam_config.altitude = (-m[(1, 1)]).acos();
let t_local = q
.inverse()
.transform_vector(&nalgebra::Vector3::from(result.translation.to_array()));
self.cam_config.target = (t_local + eye_dir.scale(self.cam_config.distance)).into();
}
}

fn populate_hud(&mut self, ui: &mut egui::Ui) {
egui::CollapsingHeader::new("Camera")
.default_open(true)
Expand All @@ -392,21 +372,13 @@ impl Game {
.clamp_range(1.0..=100.0),
);
ui.horizontal(|ui| {
ui.selectable_value(
&mut self.is_paused,
Some(egui_gizmo::GizmoMode::Translate),
"Target",
);
ui.label("Target");
ui.add(egui::DragValue::new(&mut self.cam_config.target[1]));
ui.add(egui::DragValue::new(&mut self.cam_config.target[2]));
});
ui.horizontal(|ui| {
let eps = 0.01;
ui.selectable_value(
&mut self.is_paused,
Some(egui_gizmo::GizmoMode::Rotate),
"Angle",
);
ui.label("Angle");
ui.add(
egui::DragValue::new(&mut self.cam_config.azimuth)
.clamp_range(-consts::FRAC_PI_2..=consts::FRAC_PI_2)
Expand All @@ -419,12 +391,9 @@ impl Game {
);
});
ui.add(egui::Slider::new(&mut self.cam_config.fov, 0.5f32..=2.0f32).text("FOV"));
if self.is_paused.is_some() && ui.button("Unpause").clicked() {
self.is_paused = None;
}
ui.toggle_value(&mut self.is_paused, "Pause");
});

self.add_camera_manipulation(ui);
self.engine.populate_hud(ui);
}

Expand Down Expand Up @@ -455,7 +424,8 @@ impl Game {
);
let engine_dt = self.last_physics_update.elapsed().as_secs_f32();
self.last_physics_update = time::Instant::now();
if self.is_paused.is_none() {
if !self.is_paused {
self.align_wheels();
self.engine.update(engine_dt);
}

Expand All @@ -470,12 +440,19 @@ impl Game {
let base_quat =
nalgebra::UnitQuaternion::new_normalize(nalgebra::Quaternion::from_parts(
veh_isometry.rotation.quaternion().w,
nalgebra::Vector3::y_axis().scale(projection.abs()),
nalgebra::Vector3::y_axis().scale(projection),
));

let cc = &self.cam_config;
let smooth_t = (-engine_dt * cc.speed).exp();
let smooth_quat = nalgebra::UnitQuaternion::new_normalize(
base_quat.lerp(&self.last_camera_base_quat, smooth_t),
);
let base =
nalgebra::geometry::Isometry3::from_parts(veh_isometry.translation, base_quat);
nalgebra::geometry::Isometry3::from_parts(veh_isometry.translation, smooth_quat);
self.last_camera_base_quat = smooth_quat;

//TODO: `nalgebra::Point3::from(mint::Vector3)` doesn't exist?
let cc = &self.cam_config;
let source = nalgebra::Vector3::from(cc.target)
+ nalgebra::Vector3::new(
-cc.azimuth.sin() * cc.altitude.cos(),
Expand Down