Path: blob/master/modules/godot_physics_2d/godot_body_pair_2d.cpp
21344 views
/**************************************************************************/1/* godot_body_pair_2d.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "godot_body_pair_2d.h"3132#include "godot_collision_solver_2d.h"33#include "godot_space_2d.h"3435#define ACCUMULATE_IMPULSES3637#define MIN_VELOCITY 0.00138#define MAX_BIAS_ROTATION (Math::PI / 8)3940void GodotBodyPair2D::_add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self) {41GodotBodyPair2D *self = static_cast<GodotBodyPair2D *>(p_self);4243self->_contact_added_callback(p_point_A, p_point_B);44}4546void GodotBodyPair2D::_contact_added_callback(const Vector2 &p_point_A, const Vector2 &p_point_B) {47Vector2 local_A = A->get_inv_transform().basis_xform(p_point_A);48Vector2 local_B = B->get_inv_transform().basis_xform(p_point_B - offset_B);4950int new_index = contact_count;5152ERR_FAIL_COND(new_index >= (MAX_CONTACTS + 1));5354Contact contact;55contact.local_A = local_A;56contact.local_B = local_B;57contact.normal = (p_point_A - p_point_B).normalized();58contact.used = true;5960// Attempt to determine if the contact will be reused.61real_t recycle_radius_2 = space->get_contact_recycle_radius() * space->get_contact_recycle_radius();6263for (int i = 0; i < contact_count; i++) {64Contact &c = contacts[i];65if (c.local_A.distance_squared_to(local_A) < (recycle_radius_2) &&66c.local_B.distance_squared_to(local_B) < (recycle_radius_2)) {67contact.acc_normal_impulse = c.acc_normal_impulse;68contact.acc_tangent_impulse = c.acc_tangent_impulse;69contact.acc_bias_impulse = c.acc_bias_impulse;70contact.acc_bias_impulse_center_of_mass = c.acc_bias_impulse_center_of_mass;71c = contact;72return;73}74}7576// Figure out if the contact amount must be reduced to fit the new contact.77if (new_index == MAX_CONTACTS) {78// Remove the contact with the minimum depth.7980const Transform2D &transform_A = A->get_transform();81const Transform2D &transform_B = B->get_transform();8283int least_deep = -1;84real_t min_depth;8586// Start with depth for new contact.87{88Vector2 global_A = transform_A.basis_xform(contact.local_A);89Vector2 global_B = transform_B.basis_xform(contact.local_B) + offset_B;9091Vector2 axis = global_A - global_B;92min_depth = axis.dot(contact.normal);93}9495for (int i = 0; i < contact_count; i++) {96const Contact &c = contacts[i];97Vector2 global_A = transform_A.basis_xform(c.local_A);98Vector2 global_B = transform_B.basis_xform(c.local_B) + offset_B;99100Vector2 axis = global_A - global_B;101real_t depth = axis.dot(c.normal);102103if (depth < min_depth) {104min_depth = depth;105least_deep = i;106}107}108109if (least_deep > -1) {110// Replace the least deep contact by the new one.111contacts[least_deep] = contact;112}113114return;115}116117contacts[new_index] = contact;118contact_count++;119}120121void GodotBodyPair2D::_validate_contacts() {122// Make sure to erase contacts that are no longer valid.123real_t max_separation = space->get_contact_max_separation();124real_t max_separation2 = max_separation * max_separation;125126const Transform2D &transform_A = A->get_transform();127const Transform2D &transform_B = B->get_transform();128129for (int i = 0; i < contact_count; i++) {130Contact &c = contacts[i];131132bool erase = false;133if (!c.used) {134// Was left behind in previous frame.135erase = true;136} else {137c.used = false;138139Vector2 global_A = transform_A.basis_xform(c.local_A);140Vector2 global_B = transform_B.basis_xform(c.local_B) + offset_B;141Vector2 axis = global_A - global_B;142real_t depth = axis.dot(c.normal);143144if (depth < -max_separation || (global_B + c.normal * depth - global_A).length_squared() > max_separation2) {145erase = true;146}147}148149if (erase) {150// Contact no longer needed, remove.151152if ((i + 1) < contact_count) {153// Swap with the last one.154SWAP(contacts[i], contacts[contact_count - 1]);155}156157i--;158contact_count--;159}160}161}162163// `_test_ccd` prevents tunneling by slowing down a high velocity body that is about to collide so164// that next frame it will be at an appropriate location to collide (i.e. slight overlap).165// WARNING: The way velocity is adjusted down to cause a collision means the momentum will be166// weaker than it should for a bounce!167// Process: Only proceed if body A's motion is high relative to its size.168// Cast forward along motion vector to see if A is going to enter/pass B's collider next frame, only proceed if it does.169// Adjust the velocity of A down so that it will just slightly intersect the collider instead of blowing right past it.170bool GodotBodyPair2D::_test_ccd(real_t p_step, GodotBody2D *p_A, int p_shape_A, const Transform2D &p_xform_A, GodotBody2D *p_B, int p_shape_B, const Transform2D &p_xform_B) {171Vector2 motion = p_A->get_linear_velocity() * p_step;172real_t mlen = motion.length();173if (mlen < CMP_EPSILON) {174return false;175}176177Vector2 mnormal = motion / mlen;178179real_t min = 0.0, max = 0.0;180p_A->get_shape(p_shape_A)->project_rangev(mnormal, p_xform_A, min, max);181182// Did it move enough in this direction to even attempt raycast?183// Let's say it should move more than 1/3 the size of the object in that axis.184bool fast_object = mlen > (max - min) * 0.3;185if (!fast_object) {186return false;187}188189// A is moving fast enough that tunneling might occur. See if it's really about to collide.190191// Roughly predict body B's position in the next frame (ignoring collisions).192Transform2D predicted_xform_B = p_xform_B.translated(p_B->get_linear_velocity() * p_step);193194// Cast a segment from support in motion normal, in the same direction of motion by motion length.195// Support point will the farthest forward collision point along the movement vector.196// i.e. the point that should hit B first if any collision does occur.197198// convert mnormal into body A's local xform because get_support requires (and returns) local coordinates.199int a;200Vector2 s[2];201p_A->get_shape(p_shape_A)->get_supports(p_xform_A.basis_xform_inv(mnormal).normalized(), s, a);202Vector2 from = p_xform_A.xform(s[0]);203// Back up 10% of the per-frame motion behind the support point and use that as the beginning of our cast.204// This should ensure the calculated new velocity will really cause a bit of overlap instead of just getting us very close.205Vector2 to = from + motion;206207Transform2D from_inv = predicted_xform_B.affine_inverse();208209// Back up 10% of the per-frame motion behind the support point and use that as the beginning of our cast.210// At high speeds, this may mean we're actually casting from well behind the body instead of inside it, which is odd. But it still works out.211Vector2 local_from = from_inv.xform(from - motion * 0.1);212Vector2 local_to = from_inv.xform(to);213214Vector2 rpos, rnorm;215if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from, local_to, rpos, rnorm)) {216// there was no hit. Since the segment is the length of per-frame motion, this means the bodies will not217// actually collide yet on next frame. We'll probably check again next frame once they're closer.218return false;219}220221// Check one-way collision based on motion direction.222if (p_A->get_shape(p_shape_A)->allows_one_way_collision() && p_B->is_shape_set_as_one_way_collision(p_shape_B)) {223Vector2 direction = predicted_xform_B.basis_xform(p_B->get_shape_one_way_collision_direction(p_shape_B)).normalized();224225if (direction.dot(mnormal) < CMP_EPSILON) {226collided = false;227oneway_disabled = true;228return false;229}230}231232// Shorten the linear velocity so it does not hit, but gets close enough,233// next frame will hit softly or soft enough.234Vector2 hitpos = predicted_xform_B.xform(rpos);235236real_t newlen = hitpos.distance_to(from) + (max - min) * 0.01; // adding 1% of body length to the distance between collision and support point should cause body A's support point to arrive just within B's collider next frame.237p_A->set_linear_velocity(mnormal * (newlen / p_step));238239return true;240}241242real_t combine_bounce(GodotBody2D *A, GodotBody2D *B) {243return CLAMP(A->get_bounce() + B->get_bounce(), 0, 1);244}245246real_t combine_friction(GodotBody2D *A, GodotBody2D *B) {247return Math::abs(MIN(A->get_friction(), B->get_friction()));248}249250bool GodotBodyPair2D::setup(real_t p_step) {251check_ccd = false;252253if (!A->interacts_with(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self())) {254collided = false;255return false;256}257258collide_A = (A->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC) && A->collides_with(B);259collide_B = (B->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC) && B->collides_with(A);260261report_contacts_only = false;262if (!collide_A && !collide_B) {263if ((A->get_max_contacts_reported() > 0) || (B->get_max_contacts_reported() > 0)) {264report_contacts_only = true;265} else {266collided = false;267return false;268}269}270271//use local A coordinates to avoid numerical issues on collision detection272offset_B = B->get_transform().get_origin() - A->get_transform().get_origin();273274_validate_contacts();275276const Vector2 &offset_A = A->get_transform().get_origin();277Transform2D xform_Au = A->get_transform().untranslated();278Transform2D xform_A = xform_Au * A->get_shape_transform(shape_A);279280Transform2D xform_Bu = B->get_transform();281xform_Bu.columns[2] -= offset_A;282Transform2D xform_B = xform_Bu * B->get_shape_transform(shape_B);283284GodotShape2D *shape_A_ptr = A->get_shape(shape_A);285GodotShape2D *shape_B_ptr = B->get_shape(shape_B);286287Vector2 motion_A, motion_B;288289if (A->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_SHAPE) {290motion_A = A->get_motion();291}292if (B->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_SHAPE) {293motion_B = B->get_motion();294}295296bool prev_collided = collided;297298collided = GodotCollisionSolver2D::solve(shape_A_ptr, xform_A, motion_A, shape_B_ptr, xform_B, motion_B, _add_contact, this, &sep_axis);299if (!collided) {300oneway_disabled = false;301302if (A->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_A) {303check_ccd = true;304return true;305}306307if (B->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_B) {308check_ccd = true;309return true;310}311312return false;313}314315if (oneway_disabled) {316return false;317}318319if (!prev_collided) {320if (shape_B_ptr->allows_one_way_collision() && A->is_shape_set_as_one_way_collision(shape_A)) {321Vector2 direction = xform_A.basis_xform(A->get_shape_one_way_collision_direction(shape_A)).normalized();322323bool valid = false;324for (int i = 0; i < contact_count; i++) {325Contact &c = contacts[i];326if (c.normal.dot(direction) > -CMP_EPSILON) { // Greater (normal inverted).327continue;328}329valid = true;330break;331}332if (!valid) {333collided = false;334oneway_disabled = true;335return false;336}337}338339if (shape_A_ptr->allows_one_way_collision() && B->is_shape_set_as_one_way_collision(shape_B)) {340Vector2 direction = xform_B.basis_xform(B->get_shape_one_way_collision_direction(shape_B)).normalized();341342bool valid = false;343for (int i = 0; i < contact_count; i++) {344Contact &c = contacts[i];345if (c.normal.dot(direction) < CMP_EPSILON) { // Less (normal ok).346continue;347}348valid = true;349break;350}351if (!valid) {352collided = false;353oneway_disabled = true;354return false;355}356}357}358359return true;360}361362bool GodotBodyPair2D::pre_solve(real_t p_step) {363if (oneway_disabled) {364return false;365}366367if (!collided) {368if (check_ccd) {369const Vector2 &offset_A = A->get_transform().get_origin();370Transform2D xform_Au = A->get_transform().untranslated();371Transform2D xform_A = xform_Au * A->get_shape_transform(shape_A);372373Transform2D xform_Bu = B->get_transform();374xform_Bu.columns[2] -= offset_A;375Transform2D xform_B = xform_Bu * B->get_shape_transform(shape_B);376377if (A->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_A) {378_test_ccd(p_step, A, shape_A, xform_A, B, shape_B, xform_B);379}380381if (B->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_B) {382_test_ccd(p_step, B, shape_B, xform_B, A, shape_A, xform_A);383}384}385386return false;387}388389real_t max_penetration = space->get_contact_max_allowed_penetration();390391real_t bias = space->get_contact_bias();392393GodotShape2D *shape_A_ptr = A->get_shape(shape_A);394GodotShape2D *shape_B_ptr = B->get_shape(shape_B);395396if (shape_A_ptr->get_custom_bias() || shape_B_ptr->get_custom_bias()) {397if (shape_A_ptr->get_custom_bias() == 0) {398bias = shape_B_ptr->get_custom_bias();399} else if (shape_B_ptr->get_custom_bias() == 0) {400bias = shape_A_ptr->get_custom_bias();401} else {402bias = (shape_B_ptr->get_custom_bias() + shape_A_ptr->get_custom_bias()) * 0.5;403}404}405406real_t inv_dt = 1.0 / p_step;407408bool do_process = false;409410const Vector2 &offset_A = A->get_transform().get_origin();411const Transform2D &transform_A = A->get_transform();412const Transform2D &transform_B = B->get_transform();413414real_t inv_inertia_A = collide_A ? A->get_inv_inertia() : 0.0;415real_t inv_inertia_B = collide_B ? B->get_inv_inertia() : 0.0;416417real_t inv_mass_A = collide_A ? A->get_inv_mass() : 0.0;418real_t inv_mass_B = collide_B ? B->get_inv_mass() : 0.0;419420for (int i = 0; i < contact_count; i++) {421Contact &c = contacts[i];422c.active = false;423424Vector2 global_A = transform_A.basis_xform(c.local_A);425Vector2 global_B = transform_B.basis_xform(c.local_B) + offset_B;426427Vector2 axis = global_A - global_B;428real_t depth = axis.dot(c.normal);429430if (depth <= 0.0) {431continue;432}433434#ifdef DEBUG_ENABLED435if (space->is_debugging_contacts()) {436space->add_debug_contact(global_A + offset_A);437space->add_debug_contact(global_B + offset_A);438}439#endif440441c.rA = global_A - A->get_center_of_mass();442c.rB = global_B - B->get_center_of_mass() - offset_B;443444// Precompute normal mass, tangent mass, and bias.445real_t rnA = c.rA.dot(c.normal);446real_t rnB = c.rB.dot(c.normal);447real_t kNormal = inv_mass_A + inv_mass_B;448kNormal += inv_inertia_A * (c.rA.dot(c.rA) - rnA * rnA) + inv_inertia_B * (c.rB.dot(c.rB) - rnB * rnB);449c.mass_normal = 1.0f / kNormal;450451Vector2 tangent = c.normal.orthogonal();452real_t rtA = c.rA.dot(tangent);453real_t rtB = c.rB.dot(tangent);454real_t kTangent = inv_mass_A + inv_mass_B;455kTangent += inv_inertia_A * (c.rA.dot(c.rA) - rtA * rtA) + inv_inertia_B * (c.rB.dot(c.rB) - rtB * rtB);456c.mass_tangent = 1.0f / kTangent;457458c.bias = -bias * inv_dt * MIN(0.0f, -depth + max_penetration);459c.depth = depth;460461Vector2 P = c.acc_normal_impulse * c.normal + c.acc_tangent_impulse * tangent;462463c.acc_impulse -= P;464465if (A->can_report_contacts() || B->can_report_contacts()) {466Vector2 crB = Vector2(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x) + B->get_linear_velocity();467Vector2 crA = Vector2(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x) + A->get_linear_velocity();468if (A->can_report_contacts()) {469A->add_contact(global_A + offset_A, -c.normal, depth, shape_A, crA, global_B + offset_A, shape_B, B->get_instance_id(), B->get_self(), crB, c.acc_impulse);470}471if (B->can_report_contacts()) {472B->add_contact(global_B + offset_A, c.normal, depth, shape_B, crB, global_A + offset_A, shape_A, A->get_instance_id(), A->get_self(), crA, c.acc_impulse);473}474}475476if (report_contacts_only) {477collided = false;478continue;479}480481#ifdef ACCUMULATE_IMPULSES482{483// Apply normal + friction impulse484if (collide_A) {485A->apply_impulse(-P, c.rA + A->get_center_of_mass());486}487if (collide_B) {488B->apply_impulse(P, c.rB + B->get_center_of_mass());489}490}491#endif492493c.bounce = combine_bounce(A, B);494if (c.bounce) {495Vector2 crA(-A->get_prev_angular_velocity() * c.rA.y, A->get_prev_angular_velocity() * c.rA.x);496Vector2 crB(-B->get_prev_angular_velocity() * c.rB.y, B->get_prev_angular_velocity() * c.rB.x);497Vector2 dv = B->get_prev_linear_velocity() + crB - A->get_prev_linear_velocity() - crA;498c.bounce = c.bounce * dv.dot(c.normal);499}500501c.active = true;502do_process = true;503}504505return do_process;506}507508void GodotBodyPair2D::solve(real_t p_step) {509if (!collided || oneway_disabled) {510return;511}512513const real_t max_bias_av = MAX_BIAS_ROTATION / p_step;514515real_t inv_mass_A = collide_A ? A->get_inv_mass() : 0.0;516real_t inv_mass_B = collide_B ? B->get_inv_mass() : 0.0;517518for (int i = 0; i < contact_count; ++i) {519Contact &c = contacts[i];520521if (!c.active) {522continue;523}524525// Relative velocity at contact526527Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);528Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);529Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;530531Vector2 crbA(-A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x);532Vector2 crbB(-B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x);533Vector2 dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA;534535real_t vn = dv.dot(c.normal);536real_t vbn = dbv.dot(c.normal);537538Vector2 tangent = c.normal.orthogonal();539real_t vt = dv.dot(tangent);540541real_t jbn = (c.bias - vbn) * c.mass_normal;542real_t jbnOld = c.acc_bias_impulse;543c.acc_bias_impulse = MAX(jbnOld + jbn, 0.0f);544545Vector2 jb = c.normal * (c.acc_bias_impulse - jbnOld);546547if (collide_A) {548A->apply_bias_impulse(-jb, c.rA + A->get_center_of_mass(), max_bias_av);549}550if (collide_B) {551B->apply_bias_impulse(jb, c.rB + B->get_center_of_mass(), max_bias_av);552}553554crbA = Vector2(-A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x);555crbB = Vector2(-B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x);556dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA;557558vbn = dbv.dot(c.normal);559560if (Math::abs(-vbn + c.bias) > MIN_VELOCITY) {561real_t jbn_com = (-vbn + c.bias) / (inv_mass_A + inv_mass_B);562real_t jbnOld_com = c.acc_bias_impulse_center_of_mass;563c.acc_bias_impulse_center_of_mass = MAX(jbnOld_com + jbn_com, 0.0f);564565Vector2 jb_com = c.normal * (c.acc_bias_impulse_center_of_mass - jbnOld_com);566567if (collide_A) {568A->apply_bias_impulse(-jb_com, A->get_center_of_mass(), 0.0f);569}570if (collide_B) {571B->apply_bias_impulse(jb_com, B->get_center_of_mass(), 0.0f);572}573}574575real_t jn = -(c.bounce + vn) * c.mass_normal;576real_t jnOld = c.acc_normal_impulse;577c.acc_normal_impulse = MAX(jnOld + jn, 0.0f);578579real_t friction = combine_friction(A, B);580581real_t jtMax = friction * c.acc_normal_impulse;582real_t jt = -vt * c.mass_tangent;583real_t jtOld = c.acc_tangent_impulse;584c.acc_tangent_impulse = CLAMP(jtOld + jt, -jtMax, jtMax);585586Vector2 j = c.normal * (c.acc_normal_impulse - jnOld) + tangent * (c.acc_tangent_impulse - jtOld);587588if (collide_A) {589A->apply_impulse(-j, c.rA + A->get_center_of_mass());590}591if (collide_B) {592B->apply_impulse(j, c.rB + B->get_center_of_mass());593}594c.acc_impulse -= j;595}596}597598GodotBodyPair2D::GodotBodyPair2D(GodotBody2D *p_A, int p_shape_A, GodotBody2D *p_B, int p_shape_B) :599GodotConstraint2D(_arr, 2) {600A = p_A;601B = p_B;602shape_A = p_shape_A;603shape_B = p_shape_B;604space = A->get_space();605A->add_constraint(this, 0);606B->add_constraint(this, 1);607}608609GodotBodyPair2D::~GodotBodyPair2D() {610A->remove_constraint(this, 0);611B->remove_constraint(this, 1);612}613614615