From e1db693525c66d559fba6eeb623044794d1aa9ec Mon Sep 17 00:00:00 2001 From: Xein Date: Sun, 22 Nov 2026 12:07:00 +0100 Subject: [PATCH] Levitation Joint --- engine/src/toast/physics/joint.hpp | 23 +++- engine/src/toast/physics/joint_solver.cpp | 104 +++++++++++++++++- .../toast/physics/nodes/levitation_joint.cpp | 75 +++++++++++++ .../toast/physics/nodes/levitation_joint.hpp | 66 +++++++++++ engine/src/toast/physics/simulator.cpp | 7 +- engine/src/toast/physics/simulator.hpp | 1 + engine/src/toast/physics/simulator_joints.cpp | 27 +++++ 7 files changed, 293 insertions(+), 10 deletions(-) create mode 100644 engine/src/toast/physics/nodes/levitation_joint.cpp create mode 100644 engine/src/toast/physics/nodes/levitation_joint.hpp diff --git a/engine/src/toast/physics/joint.hpp b/engine/src/toast/physics/joint.hpp index f2db6c8c9..8c61cf4b6 100644 --- a/engine/src/toast/physics/joint.hpp +++ b/engine/src/toast/physics/joint.hpp @@ -31,7 +31,8 @@ enum class JointType : uint8_t { pin, hinge, slider, - fixed + fixed, + levitation, }; // Material friction times pin radius in metres as torque per newton carried @@ -77,7 +78,19 @@ struct FixedParams { auto operator==(const FixedParams&) const -> bool = default; }; -using JointParams = std::variant; +struct LevitationParams { + float stiffness_hz = 2.0f; + float damping_ratio = 0.7f; + float max_force = 100.0f; + float catch_radius = 0.5f; + float release_radius = 1.0f; + glm::bvec3 rotation_free = glm::bvec3(true); + float angular_damping = 1.0f; + + auto operator==(const LevitationParams&) const -> bool = default; +}; + +using JointParams = std::variant; struct JointFrame { glm::vec3 position = {}; @@ -137,6 +150,10 @@ struct Joint { JointVoxelEnd voxel_end_b; float last_force = 0.0f; float last_torque = 0.0f; + bool levitating = true; + float levitation_offset = 0.0f; + float levitation_force = 0.0f; + bool exclusion_active = false; }; struct JointState { @@ -144,6 +161,8 @@ struct JointState { float position = 0.0f; float force = 0.0f; float torque = 0.0f; + bool levitating = true; + float offset = 0.0f; }; struct JointSlot { diff --git a/engine/src/toast/physics/joint_solver.cpp b/engine/src/toast/physics/joint_solver.cpp index 0aae211e5..68b0ce077 100644 --- a/engine/src/toast/physics/joint_solver.cpp +++ b/engine/src/toast/physics/joint_solver.cpp @@ -13,6 +13,11 @@ auto skew(const glm::vec3& v) -> glm::mat3 { return glm::mat3 {0.0f, v.z, -v.y, -v.z, 0.0f, v.x, v.y, -v.x, 0.0f}; } +auto clampLength(const glm::vec3& value, float limit) -> glm::vec3 { + const float length = glm::length(value); + return length > limit ? value * (limit / length) : value; +} + auto inverseMass(const Body& body) -> float { return movable(body) ? body.inverse_mass : 0.0f; } @@ -247,6 +252,53 @@ void solveSlider(const JointRow& row, Joint& joint, const SliderParams& params, ); } +void solveHover(const JointRow& row, Joint& joint, const LevitationParams& params, Body& a, Body& b) { + const float step = 1.0f / row.inverse_dt; + const float omega = glm::two_pi() * std::max(params.stiffness_hz, 0.0f); + const float a1 = (2.0f * std::max(params.damping_ratio, 0.0f)) + (step * omega); + const float a2 = step * omega * a1; + const float a3 = 1.0f / (1.0f + a2); + const float bias_rate = a1 > 1.0e-8f ? omega / a1 : 0.0f; + + const glm::vec3 relative = velocityAt(b, row.r_b) - velocityAt(a, row.r_a); + glm::vec3& accumulated = joint.impulses.point; + glm::vec3 next = + accumulated + (row.inverse_point_mass * (-(a2 * a3) * (relative + (bias_rate * row.error)))) - (a3 * accumulated); + next = clampLength(next, std::max(params.max_force, 0.0f) * step); + applyLinear(a, b, row.r_a, row.r_b, next - accumulated); + accumulated = next; + joint.levitation_force = glm::length(next) / step; +} + +void solveLevitationRotation(const JointRow& row, Joint& joint, const LevitationParams& params, Body& a, Body& b) { + const float share = 1.0f - std::exp(-std::max(params.angular_damping, 0.0f) / row.inverse_dt); + for (int index = 0; index < 3; ++index) { + const glm::vec3 axis = row.axes_a[index]; + if (not params.rotation_free[index]) { + solveAngular(a, b, axis, 0.0f, joint.impulses.angular_lock[index], -k_infinity, k_infinity); + continue; + } + + const float mass = angularMass(a, b, axis); + if (mass <= 0.0f) { + continue; + } + const float speed = glm::dot(b.angular_velocity - a.angular_velocity, axis); + float& accumulated = joint.impulses.friction[index]; + const float next = accumulated - (share * mass * speed) - ((1.0f - share) * accumulated); + applyAngular(a, b, axis * (next - accumulated)); + accumulated = next; + } +} + +void solveLevitation(const JointRow& row, Joint& joint, const LevitationParams& params, Body& a, Body& b) { + if (not joint.levitating) { + return; + } + solveHover(row, joint, params, a, b); + solveLevitationRotation(row, joint, params, a, b); +} + void solveFixed(const JointRow& row, Joint& joint, Body& a, Body& b) { // Neither body turns relative to the other const glm::vec3 angular_impulse = row.inverse_angular_mass * -(b.angular_velocity - a.angular_velocity); @@ -281,7 +333,8 @@ auto measure(const Joint& joint, const Body& body_a, const Body& body_b) -> Join } if (std::holds_alternative(joint.descriptor.params) || - std::holds_alternative(joint.descriptor.params)) { + std::holds_alternative(joint.descriptor.params) || + std::holds_alternative(joint.descriptor.params)) { row.position = glm::dot(row.error, row.axes_a[0]); glm::quat difference = frame_b * glm::conjugate(frame_a); @@ -341,11 +394,6 @@ void shiftAngular(Body& a, Body& b, const glm::vec3& push) { } } -auto clampLength(const glm::vec3& value, float limit) -> glm::vec3 { - const float length = glm::length(value); - return length > limit ? value * (limit / length) : value; -} - auto clampValue(float value) -> float { return std::clamp(value, -k_max_position_correction, k_max_position_correction); } @@ -399,6 +447,11 @@ auto makeJoint(const JointDescriptor& descriptor, const Body& body_a, const Body joint.frame_a = frame_in(body_a); joint.frame_b = frame_in(body_b); + if (const auto* levitation = std::get_if(&descriptor.params); levitation != nullptr) { + joint.frame_b.position = body_b.local_center_of_mass; + joint.levitating = glm::length(body_b.worldCenterOfMass() - descriptor.anchor) < levitation->catch_radius; + } + // Angle of b around the axis from the frame x like the limits and zero for a body centred on the axis if (const auto* hinge = std::get_if(&descriptor.params); hinge != nullptr) { const glm::mat3 axes = glm::mat3_cast(descriptor.frame); @@ -442,6 +495,21 @@ auto prepareJoint(Joint& joint, const Body& body_a, const Body& body_b, float dt const float speed = glm::dot(velocityAt(body_b, row.r_b) - velocityAt(body_a, row.r_a), row.axes_a[0]); row.bounce_lower = bounce(row.position - slider->linear_limit_lower, speed, slider->limit_restitution, dt); row.bounce_upper = bounce(slider->linear_limit_upper - row.position, -speed, slider->limit_restitution, dt); + } else if (const auto* levitation = std::get_if(&joint.descriptor.params); levitation != nullptr) { + const float distance = glm::length(row.error); + const float release_radius = std::max(levitation->release_radius, levitation->catch_radius); + joint.levitation_offset = distance; + if (joint.levitating ? distance > release_radius : distance < levitation->catch_radius) { + joint.levitating = not joint.levitating; + joint.impulses = {}; + } + for (int index = 0; index < 3; ++index) { + if (levitation->rotation_free[index]) { + joint.impulses.angular_lock[index] = 0.0f; + } + } + joint.impulses.point = glm::vec3 {0.0f}; + joint.impulses.friction = glm::vec3 {0.0f}; } return row; } @@ -462,6 +530,10 @@ void warmStartJoint(const JointRow& row, const Joint& joint, Body& body_a, Body& } else if (std::holds_alternative(joint.descriptor.params)) { applyAngular(body_a, body_b, impulses.angular_lock); applyLinear(body_a, body_b, row.r_a, row.r_b, impulses.point); + } else if (std::holds_alternative(joint.descriptor.params)) { + if (joint.levitating) { + applyAngular(body_a, body_b, row.axes_a * impulses.angular_lock); + } } else { applyAngular(body_a, body_b, impulses.angular_lock); applyLinear( @@ -484,6 +556,8 @@ void solveJoint(const JointRow& row, Joint& joint, Body& body_a, Body& body_b) { solveSlider(row, joint, *slider, body_a, body_b); } else if (std::holds_alternative(joint.descriptor.params)) { solveFixed(row, joint, body_a, body_b); + } else if (const auto* levitation = std::get_if(&joint.descriptor.params); levitation != nullptr) { + solveLevitation(row, joint, *levitation, body_a, body_b); } } @@ -513,6 +587,12 @@ auto jointReaction(const Joint& joint) -> JointReaction { if (std::holds_alternative(joint.descriptor.params)) { return {.linear = glm::length(impulses.point), .angular = glm::length(impulses.angular_lock)}; } + if (std::holds_alternative(joint.descriptor.params)) { + if (not joint.levitating) { + return {}; + } + return {.linear = glm::length(impulses.point), .angular = glm::length(impulses.angular_lock)}; + } return {.linear = glm::length(impulses.point), .angular = glm::length(impulses.friction)}; } @@ -579,6 +659,18 @@ void correctJointPositions(Joint& joint, Body& body_a, Body& body_b) { before.inverse_angular_mass * (clampLength(before.angular_error, k_max_position_correction) * -fixed->bias) ); close_ends(fixed->bias); + } else if (const auto* levitation = std::get_if(&joint.descriptor.params); levitation != nullptr) { + if (not joint.levitating) { + return; + } + constexpr float k_lock_bias = 0.3f; + for (int index = 0; index < 3; ++index) { + if (not levitation->rotation_free[index]) { + const JointRow row = measure(joint, body_a, body_b); + const glm::vec3 axis = row.axes_a[index]; + correctAngular(body_a, body_b, axis, glm::dot(row.angular_error, axis), k_lock_bias); + } + } } } diff --git a/engine/src/toast/physics/nodes/levitation_joint.cpp b/engine/src/toast/physics/nodes/levitation_joint.cpp new file mode 100644 index 000000000..1b17d8ce4 --- /dev/null +++ b/engine/src/toast/physics/nodes/levitation_joint.cpp @@ -0,0 +1,75 @@ +#include "levitation_joint.hpp" + +#include +#include +#include + +namespace physics { + +namespace { + +void drawCircle(const glm::vec3& origin, const glm::vec3& first, const glm::vec3& second, float radius, const glm::vec4& color) { + constexpr int k_segments = 24; + glm::vec3 previous = origin + (first * radius); + for (int segment = 1; segment <= k_segments; ++segment) { + const float angle = glm::two_pi() * static_cast(segment) / static_cast(k_segments); + const glm::vec3 point = origin + (((first * std::cos(angle)) + (second * std::sin(angle))) * radius); + debug::drawLine(previous, point, color); + previous = point; + } +} + +} + +auto LevitationJoint::makeParams() const -> JointParams { + return LevitationParams { + .stiffness_hz = stiffness_hz, + .damping_ratio = damping_ratio, + .max_force = std::max(max_force, 0.0f), + .catch_radius = catch_radius, + .release_radius = std::max(release_radius, catch_radius), + .rotation_free = glm::bvec3(rotation_free_x, rotation_free_y, rotation_free_z), + .angular_damping = angular_damping, + }; +} + +void LevitationJoint::applyState(const JointState& state) { + current_offset = state.offset; + if (levitating == state.levitating) { + return; + } + levitating = state.levitating; + if (levitating) { + captured.fire(); + } else { + released.fire(); + } +} + +void LevitationJoint::updateInspectorMessages() { + Joint3D::updateInspectorMessages(); + + static const toast::NodeMessage radii_message { + .severity = toast::NodeMessage::warning, + .id = 16, + .text = "The catch radius is bigger than the release radius, the release radius is used as big as the catch radius", + }; + if (catch_radius > release_radius) { + addInspectorMessage(radii_message); + } else { + removeInspectorMessage(radii_message); + } +} + +void LevitationJoint::drawGizmo(const glm::vec3& origin, const glm::mat3& axes, const glm::vec4& color) const { + const glm::vec4 inner {color.r, color.g, color.b, 0.35f}; + const float outer_radius = std::max(release_radius, catch_radius); + for (int index = 0; index < 3; ++index) { + const glm::vec3& first = axes[index]; + const glm::vec3& second = axes[(index + 1) % 3]; + drawCircle(origin, first, second, catch_radius, inner); + drawCircle(origin, first, second, outer_radius, color); + } +} + +} diff --git a/engine/src/toast/physics/nodes/levitation_joint.hpp b/engine/src/toast/physics/nodes/levitation_joint.hpp new file mode 100644 index 000000000..d30507a2d --- /dev/null +++ b/engine/src/toast/physics/nodes/levitation_joint.hpp @@ -0,0 +1,66 @@ +/** + * @file levitation_joint.hpp + * @author Xein + * @date 21 Nov 2026 + * @brief Holds a body floating around a point like a magnet + */ + +#pragma once +#include "joint3d.hpp" + +namespace physics { + +class [[ToastNode, Icon("SliderJoint"), Color("Green")]] TOAST_API LevitationJoint : public physics::Joint3D { +public: + signals::Signal<> released; + signals::Signal<> captured; + + /// How fast the hover settles + [[Reflect, Group("Hover"), Unit("Hz"), Range(0.0, 20.0)]] + float stiffness_hz = 2.0f; + + [[Reflect, Group("Hover"), Range(0.0, 2.0)]] + float damping_ratio = 0.7f; + + /// The strongest pull of the hover + [[Reflect, Group("Hover"), Unit("N")]] + float max_force = 100.0f; + + /// A body this close to the point is picked up again + [[Reflect, Group("Zone"), Unit("m")]] + float catch_radius = 0.5f; + + /// A body this far from the point is let go + [[Reflect, Group("Zone"), Unit("m")]] + float release_radius = 1.0f; + + [[Reflect, Group("Rotation")]] + bool rotation_free_x = true; + + [[Reflect, Group("Rotation")]] + bool rotation_free_y = true; + + [[Reflect, Group("Rotation")]] + bool rotation_free_z = true; + + /// How fast the free axes lose their spin + [[Reflect, Group("Rotation"), Unit("1/s")]] + float angular_damping = 1.0f; + + [[Reflect, Group("State"), ReadOnly]] + bool levitating = true; + + [[Reflect, Group("State"), ReadOnly, Unit("m")]] + float current_offset = 0.0f; + + [[nodiscard]] + auto makeParams() const -> JointParams override; + +protected: + void drawGizmo(const glm::vec3& origin, const glm::mat3& axes, const glm::vec4& color) const override; + + void applyState(const JointState& state) override; + void updateInspectorMessages() override; +}; + +} diff --git a/engine/src/toast/physics/simulator.cpp b/engine/src/toast/physics/simulator.cpp index 290386c48..982689a3c 100644 --- a/engine/src/toast/physics/simulator.cpp +++ b/engine/src/toast/physics/simulator.cpp @@ -833,6 +833,7 @@ void Simulator::tick() { solveIslands(islands); breakOverloadedJoints(dt); + syncLevitationExclusions(); const auto after_solve = std::chrono::steady_clock::now(); m_profile.island_solve_ms = elapsed_ms(after_islands, after_solve); @@ -3914,6 +3915,7 @@ auto Simulator::createJoint(const JointDescriptor& descriptor) -> JointID { made_joint.voxel_end_a = voxelEndOf(made.body_a, made_joint.frame_a, made.voxel_anchor); } made_joint.voxel_end_b = voxelEndOf(made.body_b, made_joint.frame_b, made.voxel_anchor); + made_joint.exclusion_active = made.exclude_collision && not holds_world && made_joint.levitating; JointSlot joint_slot {.joint = made_joint, .occupied = true}; JointID id; if (not m_free_joint_slots.empty()) { @@ -3928,7 +3930,7 @@ auto Simulator::createJoint(const JointDescriptor& descriptor) -> JointID { id.generation = m_joints[id.slot].generation; ++m_joint_count; - if (made.exclude_collision && not holds_world) { + if (made_joint.exclusion_active) { addExclusion(made.body_a, made.body_b); } wakeBody(made.body_a); @@ -3944,6 +3946,7 @@ void Simulator::destroyJoint(JointID joint) { JointSlot& slot = m_joints[joint.slot]; const JointDescriptor descriptor = slot.joint.descriptor; + const bool held_exclusion = slot.joint.exclusion_active; slot.occupied = false; slot.joint = {}; ++slot.generation; @@ -3953,7 +3956,7 @@ void Simulator::destroyJoint(JointID joint) { m_free_joint_slots.emplace_back(joint.slot); --m_joint_count; - if (descriptor.exclude_collision && valid(descriptor.body_a) && valid(descriptor.body_b)) { + if (held_exclusion && valid(descriptor.body_a) && valid(descriptor.body_b)) { removeExclusion(descriptor.body_a, descriptor.body_b); } // What hung from it falls diff --git a/engine/src/toast/physics/simulator.hpp b/engine/src/toast/physics/simulator.hpp index 33474d9a6..0d979d0f0 100644 --- a/engine/src/toast/physics/simulator.hpp +++ b/engine/src/toast/physics/simulator.hpp @@ -573,6 +573,7 @@ class TOAST_API Simulator { void syncJointNodes(); void checkJointAnchors(); void breakOverloadedJoints(float dt); + void syncLevitationExclusions(); void breakJoint(JointID joint, JointBreakReason reason); void publishJoints(); [[nodiscard]] diff --git a/engine/src/toast/physics/simulator_joints.cpp b/engine/src/toast/physics/simulator_joints.cpp index 3a20fe186..87d07ea19 100644 --- a/engine/src/toast/physics/simulator_joints.cpp +++ b/engine/src/toast/physics/simulator_joints.cpp @@ -170,6 +170,8 @@ void Simulator::publishJoints() { .position = joint.slider_position, .force = joint.last_force, .torque = joint.last_torque, + .levitating = joint.levitating, + .offset = joint.levitation_offset, } ); } @@ -217,6 +219,9 @@ void Simulator::breakOverloadedJoints(float dt) { const _detail::JointReaction reaction = _detail::jointReaction(joint); joint.last_force = reaction.linear / dt; joint.last_torque = reaction.angular / dt; + if (std::holds_alternative(joint.descriptor.params)) { + joint.last_force = joint.levitating ? joint.levitation_force : 0.0f; + } const JointID id {.slot = index, .generation = m_joints[index].generation}; if (joint.descriptor.break_force > 0.0f && joint.last_force > joint.descriptor.break_force) { @@ -227,6 +232,28 @@ void Simulator::breakOverloadedJoints(float dt) { } } +void Simulator::syncLevitationExclusions() { + if (m_joint_count == 0) { + return; + } + + for (JointSlot& slot : m_joints) { + Joint& joint = slot.joint; + if (not slot.occupied || not std::holds_alternative(joint.descriptor.params) || + not joint.descriptor.exclude_collision || not valid(joint.descriptor.body_a) || not valid(joint.descriptor.body_b)) { + continue; + } + + if (joint.levitating && not joint.exclusion_active) { + addExclusion(joint.descriptor.body_a, joint.descriptor.body_b); + joint.exclusion_active = true; + } else if (not joint.levitating && joint.exclusion_active) { + removeExclusion(joint.descriptor.body_a, joint.descriptor.body_b); + joint.exclusion_active = false; + } + } +} + auto Simulator::findVoxelShape(BodyID body) const -> ShapeID { for (uint32_t index = 0; index < m_shapes.size(); ++index) { const ShapeSlot& slot = m_shapes[index];