Make rigidbody simulation handle animated objects gracefully

The animated objects was not updated for each internal substep for the rigidbody sim.
This would lead to unstable simulations or very annoying clipping artifacts.

Updated the code to use explicit substeps and tie it to the scene frame rate.

Fix T47402: Properly updating the animated objects fixes the reported issue.

Reviewed By: Brecht, Jacques

Differential Revision: http://developer.blender.org/D8762
This commit is contained in:
Sebastian Parborg 2020-09-02 14:14:47 +02:00
parent feb4b645d7
commit 1aa54d4921
Notes: blender-bot 2023-10-04 11:00:31 +02:00
Referenced by commit f4d8382c86, Rigid body physics: Move effector force update into substep loop.
Referenced by issue #98272, Regression: Physics force field strength affect varies inversely proportion to physics substeps per frame
Referenced by issue #47402, A Rigid Body does not keep the initial velocity after the animated checkbox is disabled
Referenced by issue #113234, motor constraint isn't working
18 changed files with 358 additions and 50 deletions

View File

@ -18,6 +18,19 @@
# All rights reserved.
# ***** END GPL LICENSE BLOCK *****
# avoid noisy warnings
if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang")
add_c_flag(
"-Wno-unused-result -Wno-unused-variable -Wno-unused-but-set-variable -Wno-reorder"
)
remove_cc_flag(
"-Wmissing-declarations"
)
endif()
# Use double precision to make simulations of small objects stable.
add_definitions(-DBT_USE_DOUBLE_PRECISION)
set(INC
.
src

View File

@ -18,6 +18,8 @@
# All rights reserved.
# ***** END GPL LICENSE BLOCK *****
add_definitions(-DBT_USE_DOUBLE_PRECISION)
set(INC
.
)
@ -28,7 +30,9 @@ set(INC_SYS
set(SRC
rb_bullet_api.cpp
rb_convex_hull_api.cpp
RBI_hull_api.h
RBI_api.h
)

View File

@ -200,10 +200,12 @@ void RB_body_set_scale(rbRigidBody *body, const float scale[3]);
/* ............ */
/* Get RigidBody's position as vector */
/* Get RigidBody's position as a vector */
void RB_body_get_position(rbRigidBody *body, float v_out[3]);
/* Get RigidBody's orientation as quaternion */
/* Get RigidBody's orientation as a quaternion */
void RB_body_get_orientation(rbRigidBody *body, float v_out[4]);
/* Get RigidBody's local scale as a vector */
void RB_body_get_scale(rbRigidBody *object, float v_out[3]);
/* ............ */

View File

@ -0,0 +1,43 @@
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2020 Blender Foundation,
* All rights reserved.
*/
#ifndef __RB_HULL_API_H__
#define __RB_HULL_API_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef struct plConvexHull__ {
int unused;
} * plConvexHull;
plConvexHull plConvexHullCompute(float (*coords)[3], int count);
void plConvexHullDelete(plConvexHull hull);
int plConvexHullNumVertices(plConvexHull hull);
int plConvexHullNumFaces(plConvexHull hull);
void plConvexHullGetVertex(plConvexHull hull, int n, float coords[3], int *original_index);
int plConvexHullGetFaceSize(plConvexHull hull, int n);
void plConvexHullGetFaceVertices(plConvexHull hull, int n, int *vertices);
#ifdef __cplusplus
}
#endif
#endif /* __RB_HULL_API_H__ */

View File

@ -649,6 +649,16 @@ void RB_body_get_orientation(rbRigidBody *object, float v_out[4])
copy_quat_btquat(v_out, body->getWorldTransform().getRotation());
}
void RB_body_get_scale(rbRigidBody *object, float v_out[3])
{
btRigidBody *body = object->body;
btCollisionShape *cshape = body->getCollisionShape();
/* The body should have a collision shape when we try to set the scale. */
btAssert(cshape);
copy_v3_btvec3(v_out, cshape->getLocalScaling());
}
/* ............ */
/* Overrides for simulation */

View File

@ -0,0 +1,83 @@
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2020 Blender Foundation,
* All rights reserved.
*/
#include "LinearMath/btConvexHullComputer.h"
#include "RBI_hull_api.h"
plConvexHull plConvexHullCompute(float (*coords)[3], int count)
{
btConvexHullComputer *computer = new btConvexHullComputer;
computer->compute(reinterpret_cast<float *>(coords), sizeof(*coords), count, 0, 0);
return reinterpret_cast<plConvexHull>(computer);
}
void plConvexHullDelete(plConvexHull hull)
{
btConvexHullComputer *computer(reinterpret_cast<btConvexHullComputer *>(hull));
delete computer;
}
int plConvexHullNumVertices(plConvexHull hull)
{
btConvexHullComputer *computer(reinterpret_cast<btConvexHullComputer *>(hull));
return computer->vertices.size();
}
int plConvexHullNumFaces(plConvexHull hull)
{
btConvexHullComputer *computer(reinterpret_cast<btConvexHullComputer *>(hull));
return computer->faces.size();
}
void plConvexHullGetVertex(plConvexHull hull, int n, float coords[3], int *original_index)
{
btConvexHullComputer *computer(reinterpret_cast<btConvexHullComputer *>(hull));
const btVector3 &v(computer->vertices[n]);
coords[0] = v[0];
coords[1] = v[1];
coords[2] = v[2];
(*original_index) = computer->original_vertex_index[n];
}
int plConvexHullGetFaceSize(plConvexHull hull, int n)
{
btConvexHullComputer *computer(reinterpret_cast<btConvexHullComputer *>(hull));
const btConvexHullComputer::Edge *e_orig, *e;
int count;
for (e_orig = &computer->edges[computer->faces[n]], e = e_orig, count = 0;
count == 0 || e != e_orig;
e = e->getNextEdgeOfFace(), count++) {
;
}
return count;
}
void plConvexHullGetFaceVertices(plConvexHull hull, int n, int *vertices)
{
btConvexHullComputer *computer(reinterpret_cast<btConvexHullComputer *>(hull));
const btConvexHullComputer::Edge *e_orig, *e;
int count;
for (e_orig = &computer->edges[computer->faces[n]], e = e_orig, count = 0;
count == 0 || e != e_orig;
e = e->getNextEdgeOfFace(), count++) {
vertices[count] = e->getTargetVertex();
}
}

View File

@ -385,8 +385,8 @@ class SCENE_PT_rigid_body_world_settings(RigidBodySubPanel, Panel):
col.prop(rbw, "use_split_impulse")
col = col.column()
col.prop(rbw, "steps_per_second", text="Steps Per Second")
col.prop(rbw, "solver_iterations", text="Solver Iterations")
col.prop(rbw, "substeps_per_frame")
col.prop(rbw, "solver_iterations")
class SCENE_PT_rigid_body_cache(RigidBodySubPanel, Panel):

View File

@ -482,9 +482,15 @@ if(WITH_BULLET)
list(APPEND INC
../../../intern/rigidbody
)
if(NOT WITH_SYSTEM_BULLET)
list(APPEND LIB
extern_bullet
)
endif()
list(APPEND LIB
bf_intern_rigidbody
extern_bullet
${BULLET_LIBRARIES}
)

View File

@ -1180,7 +1180,10 @@ RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
rbw->time_scale = 1.0f;
rbw->steps_per_second = 60; /* Bullet default (60 Hz) */
/* Most high quality Bullet example files has an internal framerate of 240hz.
* The blender default scene has a frame rate of 24, so take 10 substeps (24fps * 10).
*/
rbw->substeps_per_frame = 10;
rbw->num_solver_iterations = 10; /* 10 is bullet default */
rbw->shared->pointcache = BKE_ptcache_add(&(rbw->shared->ptcaches));
@ -1651,10 +1654,6 @@ static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
static void rigidbody_update_sim_ob(
Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo)
{
float loc[3];
float rot[4];
float scale[3];
/* only update if rigid body exists */
if (rbo->shared->physics_object == NULL) {
return;
@ -1680,14 +1679,21 @@ static void rigidbody_update_sim_ob(
}
}
mat4_decompose(loc, rot, scale, ob->obmat);
if (!(rbo->flag & RBO_FLAG_KINEMATIC)) {
/* update scale for all non kinematic objects */
float new_scale[3], old_scale[3];
mat4_to_size(new_scale, ob->obmat);
RB_body_get_scale(rbo->shared->physics_object, old_scale);
/* update scale for all objects */
RB_body_set_scale(rbo->shared->physics_object, scale);
/* compensate for embedded convex hull collision margin */
if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH) {
RB_shape_set_margin(rbo->shared->physics_shape,
RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
/* Avoid updating collision shape AABBs if scale didn't change. */
if (!compare_size_v3v3(old_scale, new_scale, 0.001f)) {
RB_body_set_scale(rbo->shared->physics_object, new_scale);
/* compensate for embedded convex hull collision margin */
if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH) {
RB_shape_set_margin(rbo->shared->physics_shape,
RBO_GET_MARGIN(rbo) * MIN3(new_scale[0], new_scale[1], new_scale[2]));
}
}
}
/* Make transformed objects temporarily kinmatic
@ -1697,11 +1703,6 @@ static void rigidbody_update_sim_ob(
RB_body_set_mass(rbo->shared->physics_object, 0.0f);
}
/* update rigid body location and rotation for kinematic bodies */
if (rbo->flag & RBO_FLAG_KINEMATIC || (is_selected && (G.moving & G_TRANSFORM_OBJ))) {
RB_body_activate(rbo->shared->physics_object);
RB_body_set_loc_rot(rbo->shared->physics_object, loc, rot);
}
/* update influence of effectors - but don't do it on an effector */
/* only dynamic bodies need effector update */
else if (rbo->type == RBO_TYPE_ACTIVE &&
@ -1765,8 +1766,6 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph,
RigidBodyWorld *rbw,
bool rebuild)
{
float ctime = DEG_get_ctime(depsgraph);
/* update world */
/* Note physics_world can get NULL when undoing the deletion of the last object in it (see
* T70667). */
@ -1799,9 +1798,6 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph,
if (ob->type == OB_MESH) {
/* validate that we've got valid object set up here... */
RigidBodyOb *rbo = ob->rigidbody_object;
/* Update transformation matrix of the object
* so we don't get a frame of lag for simple animations. */
BKE_object_where_is_calc_time(depsgraph, scene, ob, ctime);
/* TODO remove this whole block once we are sure we never get NULL rbo here anymore. */
/* This cannot be done in CoW evaluation context anymore... */
@ -1859,9 +1855,6 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph,
FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->constraints, ob) {
/* validate that we've got valid object set up here... */
RigidBodyCon *rbc = ob->rigidbody_constraint;
/* Update transformation matrix of the object
* so we don't get a frame of lag for simple animations. */
BKE_object_where_is_calc_time(depsgraph, scene, ob, ctime);
/* TODO remove this whole block once we are sure we never get NULL rbo here anymore. */
/* This cannot be done in CoW evaluation context anymore... */
@ -1891,6 +1884,104 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph,
FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
}
typedef struct KinematicSubstepData {
RigidBodyOb *rbo;
float old_pos[3];
float new_pos[3];
float old_rot[4];
float new_rot[4];
bool scale_changed;
float old_scale[3];
float new_scale[3];
} KinematicSubstepData;
static ListBase rigidbody_create_substep_data(RigidBodyWorld *rbw)
{
/* Objects that we want to update substep location/rotation for. */
ListBase substep_targets = {NULL, NULL};
FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->group, ob) {
RigidBodyOb *rbo = ob->rigidbody_object;
/* only update if rigid body exists */
if (!rbo || rbo->shared->physics_object == NULL) {
continue;
}
if (rbo->flag & RBO_FLAG_KINEMATIC) {
float loc[3], rot[4], scale[3];
KinematicSubstepData *data = MEM_callocN(sizeof(KinematicSubstepData),
"RigidBody Substep data");
data->rbo = rbo;
RB_body_get_position(rbo->shared->physics_object, loc);
RB_body_get_orientation(rbo->shared->physics_object, rot);
RB_body_get_scale(rbo->shared->physics_object, scale);
copy_v3_v3(data->old_pos, loc);
copy_v4_v4(data->old_rot, rot);
copy_v3_v3(data->old_scale, scale);
mat4_decompose(loc, rot, scale, ob->obmat);
copy_v3_v3(data->new_pos, loc);
copy_v4_v4(data->new_rot, rot);
copy_v3_v3(data->new_scale, scale);
data->scale_changed = !compare_size_v3v3(data->old_scale, data->new_scale, 0.001f);
LinkData *ob_link = BLI_genericNodeN(data);
BLI_addtail(&substep_targets, ob_link);
}
}
FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
return substep_targets;
}
static void rigidbody_update_kinematic_obj_substep(ListBase *substep_targets, float interp_fac)
{
LISTBASE_FOREACH (LinkData *, link, substep_targets) {
KinematicSubstepData *data = link->data;
RigidBodyOb *rbo = data->rbo;
float loc[3], rot[4];
interp_v3_v3v3(loc, data->old_pos, data->new_pos, interp_fac);
interp_qt_qtqt(rot, data->old_rot, data->new_rot, interp_fac);
RB_body_activate(rbo->shared->physics_object);
RB_body_set_loc_rot(rbo->shared->physics_object, loc, rot);
if (!data->scale_changed) {
/* Avoid having to rebuild the collision shape AABBs if scale didn't change. */
continue;
}
float scale[3];
interp_v3_v3v3(scale, data->old_scale, data->new_scale, interp_fac);
RB_body_set_scale(rbo->shared->physics_object, scale);
/* compensate for embedded convex hull collision margin */
if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH) {
RB_shape_set_margin(rbo->shared->physics_shape,
RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
}
}
}
static void rigidbody_free_substep_data(ListBase *substep_targets)
{
LISTBASE_FOREACH (LinkData *, link, substep_targets) {
KinematicSubstepData *data = link->data;
MEM_freeN(data);
}
BLI_freelistN(substep_targets);
}
static void rigidbody_update_simulation_post_step(Depsgraph *depsgraph, RigidBodyWorld *rbw)
{
ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
@ -2072,7 +2163,6 @@ void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime
/* Run RigidBody simulation for the specified physics world */
void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime)
{
float timestep;
RigidBodyWorld *rbw = scene->rigidbody_world;
PointCache *cache;
PTCacheID pid;
@ -2125,14 +2215,23 @@ void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime
/* update and validate simulation */
rigidbody_update_simulation(depsgraph, scene, rbw, false);
const float frame_diff = ctime - rbw->ltime;
/* calculate how much time elapsed since last step in seconds */
timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale;
/* Step simulation by the requested timestep,
* steps per second are adjusted to take time scale into account. */
RB_dworld_step_simulation(rbw->shared->physics_world,
timestep,
INT_MAX,
1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f));
const float timestep = 1.0f / (float)FPS * frame_diff * rbw->time_scale;
const float substep = timestep / rbw->substeps_per_frame;
ListBase substep_targets = rigidbody_create_substep_data(rbw);
const float interp_step = 1.0f / rbw->substeps_per_frame;
float cur_interp_val = interp_step;
for (int i = 0; i < rbw->substeps_per_frame; i++) {
rigidbody_update_kinematic_obj_substep(&substep_targets, cur_interp_val);
RB_dworld_step_simulation(rbw->shared->physics_world, substep, 0, substep);
cur_interp_val += interp_step;
}
rigidbody_free_substep_data(&substep_targets);
rigidbody_update_simulation_post_step(depsgraph, rbw);

View File

@ -367,6 +367,10 @@ MINLINE bool compare_len_v3v3(const float a[3],
const float b[3],
const float limit) ATTR_WARN_UNUSED_RESULT;
MINLINE bool compare_size_v3v3(const float a[3],
const float b[3],
const float limit) ATTR_WARN_UNUSED_RESULT;
MINLINE float line_point_side_v2(const float l1[2],
const float l2[2],
const float pt[2]) ATTR_WARN_UNUSED_RESULT;

View File

@ -1372,6 +1372,24 @@ MINLINE bool compare_len_v3v3(const float v1[3], const float v2[3], const float
return (dot_v3v3(d, d) <= (limit * limit));
}
MINLINE bool compare_size_v3v3(const float v1[3], const float v2[3], const float limit)
{
for (int i = 0; i < 3; i++) {
if (v2[i] == 0.0f) {
/* Catch division by zero. */
if (v1[i] != v2[i]) {
return false;
}
}
else {
if (fabsf(v1[i] / v2[i] - 1.0f) > limit) {
return false;
}
}
}
return true;
}
/** \name Vector Clamping
* \{ */

View File

@ -33,6 +33,7 @@
#include "DNA_gpencil_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
#include "DNA_rigidbody_types.h"
#include "DNA_screen_types.h"
#include "DNA_shader_fx_types.h"
@ -518,6 +519,23 @@ void blo_do_versions_290(FileData *fd, Library *UNUSED(lib), Main *bmain)
}
}
for (Scene *scene = bmain->scenes.first; scene; scene = scene->id.next) {
RigidBodyWorld *rbw = scene->rigidbody_world;
if (rbw == NULL) {
continue;
}
/* The substep method changed from "per second" to "per frame".
* To get the new value simply divide the old bullet sim fps with the scene fps.
*/
rbw->substeps_per_frame /= FPS;
if (rbw->substeps_per_frame <= 0) {
rbw->substeps_per_frame = 1;
}
}
/**
* Versioning code until next subversion bump goes here.
*

View File

@ -189,10 +189,15 @@ endif()
if(WITH_BULLET)
list(APPEND INC_SYS
${BULLET_INCLUDE_DIRS}
"../../../intern/rigidbody/"
)
if(NOT WITH_SYSTEM_BULLET)
list(APPEND LIB
extern_bullet
)
endif()
list(APPEND LIB
${BULLET_LIBRARIES}
)
add_definitions(-DWITH_BULLET)

View File

@ -28,7 +28,7 @@
# include "BLI_listbase.h"
# include "BLI_math.h"
# include "Bullet-C-Api.h"
# include "RBI_hull_api.h"
/* XXX: using 128 for totelem and pchunk of mempool, no idea what good
* values would be though */

View File

@ -75,8 +75,8 @@ typedef struct RigidBodyWorld {
/** Number of objects in rigid body group. */
int numbodies;
/** Number of simulation steps thaken per second. */
short steps_per_second;
/** Number of simulation substeps steps taken per frame. */
short substeps_per_frame;
/** Number of constraint solver iterations made per simulation step. */
short num_solver_iterations;

View File

@ -125,3 +125,4 @@ DNA_STRUCT_RENAME_ELEM(bTheme, tstatusbar, space_statusbar)
DNA_STRUCT_RENAME_ELEM(bTheme, ttopbar, space_topbar)
DNA_STRUCT_RENAME_ELEM(bTheme, tuserpref, space_preferences)
DNA_STRUCT_RENAME_ELEM(bTheme, tv3d, space_view3d)
DNA_STRUCT_RENAME_ELEM(RigidBodyWorld, steps_per_second, substeps_per_frame)

View File

@ -906,15 +906,15 @@ static void rna_def_rigidbody_world(BlenderRNA *brna)
RNA_def_property_update(prop, NC_SCENE, "rna_RigidBodyWorld_reset");
/* timestep */
prop = RNA_def_property(srna, "steps_per_second", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "steps_per_second");
prop = RNA_def_property(srna, "substeps_per_frame", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "substeps_per_frame");
RNA_def_property_range(prop, 1, SHRT_MAX);
RNA_def_property_ui_range(prop, 60, 1000, 1, -1);
RNA_def_property_int_default(prop, 60);
RNA_def_property_ui_range(prop, 1, 1000, 1, -1);
RNA_def_property_int_default(prop, 10);
RNA_def_property_ui_text(
prop,
"Steps Per Second",
"Number of simulation steps taken per second (higher values are more accurate "
"Substeps Per Frame",
"Number of simulation steps taken per frame (higher values are more accurate "
"but slower)");
RNA_def_property_update(prop, NC_SCENE, "rna_RigidBodyWorld_reset");

View File

@ -156,9 +156,11 @@ if(WITH_OPENSUBDIV)
endif()
if(WITH_BULLET)
list(APPEND LIB
extern_bullet
)
if(NOT WITH_SYSTEM_BULLET)
list(APPEND LIB
extern_bullet
)
endif()
add_definitions(-DWITH_BULLET)
endif()