Blender V5.3
rigidbody.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2013 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
9
10#include <algorithm>
11#include <cfloat>
12#include <cmath>
13#include <cstdio>
14#include <cstring>
15
16#include "CLG_log.h"
17
18#include "MEM_guardedalloc.h"
19
20#include "BLI_listbase.hh"
21#include "BLI_math_matrix_c.hh"
23#include "BLI_math_vector_c.hh"
24#include "BLI_mutex.hh"
25
26#ifdef WITH_BULLET
27# include "RBI_api.h"
28#endif
29
30#include "DNA_ID.h"
32#include "DNA_mesh_types.h"
34#include "DNA_object_types.h"
35#include "DNA_rigidbody_types.h"
36#include "DNA_scene_types.h"
37
38#include "BKE_collection.hh"
39#include "BKE_effect.h"
40#include "BKE_global.hh"
41#include "BKE_layer.hh"
42#include "BKE_lib_id.hh"
43#include "BKE_lib_query.hh"
44#include "BKE_main.hh"
45#include "BKE_mesh.hh"
46#include "BKE_mesh_runtime.hh"
47#include "BKE_object.hh"
48#include "BKE_pointcache.h"
49#include "BKE_report.hh"
50#include "BKE_rigidbody.h"
51#include "BKE_scene.hh"
52
53#include "DEG_depsgraph.hh"
55
56#ifndef WITH_BULLET
57/* #RBI_api.h is not included, some types still need to be declared. */
58struct rbCollisionShape;
59struct rbConstraint;
60struct rbDynamicsWorld;
61struct rbRigidBody;
62#endif /* !WITH_BULLET */
63
64namespace blender {
65
66#ifdef WITH_BULLET
67static CLG_LogRef LOG = {"physics.rigidbody"};
68#endif
69
70/* ************************************** */
71/* Memory Management */
72
73/* Freeing Methods --------------------- */
74
75#ifdef WITH_BULLET
76static void rigidbody_update_ob_array(RigidBodyWorld *rbw);
77#else
78static void RB_dworld_remove_constraint(void * /*world*/, void * /*con*/) {}
79static void RB_dworld_remove_body(void * /*world*/, void * /*body*/) {}
80static void RB_dworld_delete(void * /*world*/) {}
81static void RB_body_delete(void * /*body*/) {}
82static void RB_shape_delete(void * /*shape*/) {}
83static void RB_constraint_delete(void * /*con*/) {}
84#endif
85
97
99{
100 if (rbw->shared) {
101 rbw->shared->runtime = MEM_new<RigidBodyWorld_Runtime>(__func__);
102 }
103}
104
106{
107 return (rbw->shared) ? rbw->shared->runtime->physics_world : nullptr;
108}
109
111{
112 bool is_orig = (scene->id.tag & ID_TAG_COPIED_ON_EVAL) == 0;
113 RigidBodyWorld *rbw = scene->rigidbody_world;
114 scene->rigidbody_world = nullptr;
115
116 /* sanity check */
117 if (!rbw) {
118 return;
119 }
120
121 if (is_orig && rbw->shared->runtime->physics_world) {
122 /* Free physics references,
123 * we assume that all physics objects in will have been added to the world. */
124 if (rbw->constraints) {
126 if (object->rigidbody_constraint) {
127 RigidBodyCon *rbc = object->rigidbody_constraint;
128 if (rbc->physics_constraint) {
130 static_cast<rbConstraint *>(rbc->physics_constraint));
131 }
132 }
133 }
135 }
136
137 if (rbw->group) {
139 BKE_rigidbody_free_object(object, rbw);
140 }
142 }
143 }
144 if (rbw->objects) {
145 free(rbw->objects);
146 }
147
148 if (is_orig) {
149 /* free cache */
151 rbw->shared->pointcache = nullptr;
152
153 MEM_delete(rbw->shared->runtime);
154 MEM_delete(rbw->shared);
155 }
156
157 /* free effector weights */
158 if (rbw->effector_weights) {
159 MEM_delete(rbw->effector_weights);
160 }
161
162 /* free rigidbody world itself */
163 MEM_delete(rbw);
164}
165
167{
168 bool is_orig = (ob->id.tag & ID_TAG_COPIED_ON_EVAL) == 0;
169 RigidBodyOb *rbo = ob->rigidbody_object;
170
171 /* sanity check */
172 if (rbo == nullptr) {
173 return;
174 }
175
176 /* free physics references */
177 if (is_orig) {
178 if (rbo->shared->physics_object) {
179 if (rbw != nullptr && rbw->shared->runtime->physics_world != nullptr) {
180 /* We can only remove the body from the world if the world is known.
181 * The world is generally only unknown if it's an evaluated copy of
182 * an object that's being freed, in which case this code isn't run anyway. */
184 static_cast<rbRigidBody *>(rbo->shared->physics_object));
185 }
186 else {
187 /* We have no access to 'owner' RBW when deleting the object ID itself... No choice bu to
188 * loop over all scenes then. */
189 for (Scene *scene = G_MAIN->scenes.first(); scene != nullptr;
190 scene = static_cast<Scene *>(scene->id.next))
191 {
192 RigidBodyWorld *scene_rbw = scene->rigidbody_world;
193 if (scene_rbw != nullptr && scene_rbw->shared->runtime->physics_world != nullptr) {
195 static_cast<rbRigidBody *>(rbo->shared->physics_object));
196 }
197 }
198 }
199
200 RB_body_delete(static_cast<rbRigidBody *>(rbo->shared->physics_object));
201 rbo->shared->physics_object = nullptr;
202 }
203
204 if (rbo->shared->physics_shape) {
206 rbo->shared->physics_shape = nullptr;
207 }
208
209 MEM_delete(rbo->shared);
210 }
211
212 /* free data itself */
213 MEM_delete(rbo);
214 ob->rigidbody_object = nullptr;
215}
216
218{
219 RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : nullptr;
220
221 /* sanity check */
222 if (rbc == nullptr) {
223 return;
224 }
225
226 /* free physics reference */
227 if (rbc->physics_constraint) {
229 rbc->physics_constraint = nullptr;
230 }
231
232 /* free data itself */
233 MEM_delete(rbc);
234 ob->rigidbody_constraint = nullptr;
235}
236
238{
239 /* Check if the object will have its transform changed by the rigidbody simulation. */
240
241 /* True if the shape of this object's parent is of type compound */
242 bool obCompoundParent = (ob->parent != nullptr && ob->parent->rigidbody_object != nullptr &&
244
245 RigidBodyOb *rbo = ob->rigidbody_object;
246 if (rbo == nullptr || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE ||
247 obCompoundParent)
248 {
249 return false;
250 }
251
252 return true;
253}
254
255#ifdef WITH_BULLET
256
257/* ************************************** */
258/* Setup Utilities - Validate Sim Instances */
259
260/* get the appropriate evaluated mesh based on rigid body mesh source */
261static const Mesh *rigidbody_get_mesh(Object *ob)
262{
263 BLI_assert(ob->type == OB_MESH);
264
265 switch (ob->rigidbody_object->mesh_source) {
266 case RBO_MESH_DEFORM:
268 case RBO_MESH_FINAL:
270 case RBO_MESH_BASE:
271 /* This mesh may be used for computing corner_tris, which should be done
272 * on the original; otherwise every time the evaluated copy is recreated it will
273 * have to be recomputed. */
274 BLI_assert(ob->rigidbody_object->mesh_source == RBO_MESH_BASE);
275 return (Mesh *)ob->runtime->data_orig;
276 }
277
278 /* Just return something sensible so that at least Blender won't crash. */
279 BLI_assert_msg(0, "Unknown mesh source");
281}
282
283/* create collision shape of mesh - convex hull */
284static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob,
285 float margin,
286 bool *can_embed)
287{
288 rbCollisionShape *shape = nullptr;
289 const Mesh *mesh = nullptr;
290 const float (*positions)[3] = nullptr;
291 int totvert = 0;
292
293 if (ob->type == OB_MESH && ob->data) {
294 mesh = rigidbody_get_mesh(ob);
295 positions = (mesh) ? reinterpret_cast<const float (*)[3]>(mesh->vert_positions().data()) :
296 nullptr;
297 totvert = (mesh) ? mesh->verts_num : 0;
298 }
299 else {
300 CLOG_ERROR(&LOG, "cannot make Convex Hull collision shape for non-Mesh object");
301 }
302
303 if (totvert) {
305 (float *)positions, sizeof(float[3]), totvert, margin, can_embed);
306 }
307 else {
308 CLOG_ERROR(&LOG, "no vertices to define Convex Hull collision shape with");
309 }
310
311 return shape;
312}
313
314/* create collision shape of mesh - triangulated mesh
315 * returns nullptr if creation fails.
316 */
317static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob)
318{
319 rbCollisionShape *shape = nullptr;
320
321 if (ob->type == OB_MESH) {
322 const Mesh *mesh = rigidbody_get_mesh(ob);
323 if (mesh == nullptr) {
324 return nullptr;
325 }
326
327 const Span<float3> positions = mesh->vert_positions();
328 const int totvert = mesh->verts_num;
329 const Span<int3> corner_tris = mesh->corner_tris();
330 const int tottri = corner_tris.size();
331 const Span<int> corner_verts = mesh->corner_verts();
332
333 /* sanity checking - potential case when no data will be present */
334 if ((totvert == 0) || (tottri == 0)) {
335 CLOG_WARN(
336 &LOG, "no geometry data converted for Mesh Collision Shape (ob = %s)", ob->id.name + 2);
337 }
338 else {
339 rbMeshData *mdata;
340 int i;
341
342 /* init mesh data for collision shape */
343 mdata = RB_trimesh_data_new(tottri, totvert);
344
345 RB_trimesh_add_vertices(mdata, (float *)positions.data(), totvert, sizeof(float[3]));
346
347 /* loop over all faces, adding them as triangles to the collision shape
348 * (so for some faces, more than triangle will get added)
349 */
350 if (positions.data()) {
351 for (i = 0; i < tottri; i++) {
352 /* add first triangle - verts 1,2,3 */
353 const int3 &tri = corner_tris[i];
354 int vtri[3];
355
356 vtri[0] = corner_verts[tri[0]];
357 vtri[1] = corner_verts[tri[1]];
358 vtri[2] = corner_verts[tri[2]];
359
361 }
362 }
363
364 RB_trimesh_finish(mdata);
365
366 /* construct collision shape
367 *
368 * These have been chosen to get better speed/accuracy tradeoffs with regards
369 * to limitations of each:
370 * - BVH-Triangle Mesh: for passive objects only. Despite having greater
371 * speed/accuracy, they cannot be used for moving objects.
372 * - GImpact Mesh: for active objects. These are slower and less stable,
373 * but are more flexible for general usage.
374 */
375 if (ob->rigidbody_object->type == RBO_TYPE_PASSIVE) {
376 shape = RB_shape_new_trimesh(mdata);
377 }
378 else {
379 shape = RB_shape_new_gimpact_mesh(mdata);
380 }
381 }
382 }
383 else {
384 CLOG_ERROR(&LOG, "cannot make Triangular Mesh collision shape for non-Mesh object");
385 }
386
387 return shape;
388}
389
390/* Helper function to create physics collision shape for object.
391 * Returns a new collision shape.
392 */
393static rbCollisionShape *rigidbody_validate_sim_shape_helper(RigidBodyWorld *rbw, Object *ob)
394{
395 RigidBodyOb *rbo = ob->rigidbody_object;
396 rbCollisionShape *new_shape = nullptr;
397 float size[3] = {1.0f, 1.0f, 1.0f};
398 float radius = 1.0f;
399 float height = 1.0f;
400 float capsule_height;
401 float hull_margin = 0.0f;
402 bool can_embed = true;
403 bool has_volume;
404
405 /* sanity check */
406 if (rbo == nullptr) {
407 return nullptr;
408 }
409
410 /* if automatically determining dimensions, use the Object's boundbox
411 * - assume that all quadrics are standing upright on local z-axis
412 * - assume even distribution of mass around the Object's pivot
413 * (i.e. Object pivot is centralized in boundbox)
414 */
415 /* XXX: all dimensions are auto-determined now... later can add stored settings for this */
416 /* get object dimensions without scaling */
417 if (const std::optional<Bounds<float3>> bounds = BKE_object_boundbox_get(ob)) {
418 copy_v3_v3(size, bounds->max - bounds->min);
419 }
420 mul_v3_fl(size, 0.5f);
421
423 /* take radius as largest x/y dimension, and height as z-dimension */
424 radius = std::max(size[0], size[1]);
425 height = size[2];
426 }
427 else if (rbo->shape == RB_SHAPE_SPHERE) {
428 /* take radius to the largest dimension to try and encompass everything */
429 radius = std::max({size[0], size[1], size[2]});
430 }
431
432 /* create new shape */
433 switch (rbo->shape) {
434 case RB_SHAPE_BOX:
435 new_shape = RB_shape_new_box(size[0], size[1], size[2]);
436 break;
437
438 case RB_SHAPE_SPHERE:
439 new_shape = RB_shape_new_sphere(radius);
440 break;
441
442 case RB_SHAPE_CAPSULE:
443 capsule_height = (height - radius) * 2.0f;
444 new_shape = RB_shape_new_capsule(radius, (capsule_height > 0.0f) ? capsule_height : 0.0f);
445 break;
447 new_shape = RB_shape_new_cylinder(radius, height);
448 break;
449 case RB_SHAPE_CONE:
450 new_shape = RB_shape_new_cone(radius, height * 2.0f);
451 break;
452
453 case RB_SHAPE_CONVEXH:
454 /* try to embed collision margin */
455 has_volume = (std::min({size[0], size[1], size[2]}) > 0.0f);
456
457 if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && has_volume) {
458 hull_margin = 0.04f;
459 }
460 new_shape = rigidbody_get_shape_convexhull_from_mesh(ob, hull_margin, &can_embed);
461 if (!(rbo->flag & RBO_FLAG_USE_MARGIN)) {
462 rbo->margin = (can_embed && has_volume) ?
463 0.04f :
464 0.0f; /* RB_TODO ideally we shouldn't directly change the margin here */
465 }
466 break;
467 case RB_SHAPE_TRIMESH:
468 new_shape = rigidbody_get_shape_trimesh_from_mesh(ob);
469 break;
471 new_shape = RB_shape_new_compound();
472 rbCollisionShape *childShape = nullptr;
473 float loc[3], rot[4];
474 float mat[4][4];
475 /* Add children to the compound shape */
476 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->group, childObject) {
477 if (childObject->parent == ob) {
478 childShape = rigidbody_validate_sim_shape_helper(rbw, childObject);
479 if (childShape) {
480 BKE_object_matrix_local_get(childObject, mat);
481 mat4_to_loc_quat(loc, rot, mat);
482 RB_compound_add_child_shape(new_shape, childShape, loc, rot);
483 }
484 }
485 }
487
488 break;
489 }
490 /* use box shape if it failed to create new shape */
491 if (new_shape == nullptr) {
492 new_shape = RB_shape_new_box(size[0], size[1], size[2]);
493 }
494 if (new_shape) {
495 RB_shape_set_margin(new_shape, RBO_GET_MARGIN(rbo));
496 }
497
498 return new_shape;
499}
500
501/* Create new physics sim collision shape for object and store it,
502 * or remove the existing one first and replace...
503 */
504static void rigidbody_validate_sim_shape(RigidBodyWorld *rbw, Object *ob, bool rebuild)
505{
506 RigidBodyOb *rbo = ob->rigidbody_object;
507 rbCollisionShape *new_shape = nullptr;
508
509 /* sanity check */
510 if (rbo == nullptr) {
511 return;
512 }
513
514 /* don't create a new shape if we already have one and don't want to rebuild it */
515 if (rbo->shared->physics_shape && !rebuild) {
516 return;
517 }
518
519 /* Also don't create a shape if this object is parent of a compound shape */
520 if (ob->parent != nullptr && ob->parent->rigidbody_object != nullptr &&
521 ob->parent->rigidbody_object->shape == RB_SHAPE_COMPOUND)
522 {
523 return;
524 }
525
526 new_shape = rigidbody_validate_sim_shape_helper(rbw, ob);
527
528 /* assign new collision shape if creation was successful */
529 if (new_shape) {
530 if (rbo->shared->physics_shape) {
531 RB_shape_delete(static_cast<rbCollisionShape *>(rbo->shared->physics_shape));
532 }
533 rbo->shared->physics_shape = new_shape;
534 if (rbo->shared->physics_object) {
535 RB_body_set_collision_shape(static_cast<rbRigidBody *>(rbo->shared->physics_object),
536 static_cast<rbCollisionShape *>(rbo->shared->physics_shape));
537 }
538 }
539}
540
541/* --------------------- */
542
543void BKE_rigidbody_calc_volume(Object *ob, float *r_vol)
544{
545 RigidBodyOb *rbo = ob->rigidbody_object;
546
547 float size[3] = {1.0f, 1.0f, 1.0f};
548 float radius = 1.0f;
549 float height = 1.0f;
550
551 float volume = 0.0f;
552
553 /* if automatically determining dimensions, use the Object's boundbox
554 * - assume that all quadrics are standing upright on local z-axis
555 * - assume even distribution of mass around the Object's pivot
556 * (i.e. Object pivot is centralized in boundbox)
557 * - boundbox gives full width
558 */
559 /* XXX: all dimensions are auto-determined now... later can add stored settings for this */
561
563 /* take radius as largest x/y dimension, and height as z-dimension */
564 radius = std::max(size[0], size[1]) * 0.5f;
565 height = size[2];
566 }
567 else if (rbo->shape == RB_SHAPE_SPHERE) {
568 /* take radius to the largest dimension to try and encompass everything */
569 radius = std::max({size[0], size[1], size[2]}) * 0.5f;
570 }
571
572 /* Calculate volume as appropriate. */
573 switch (rbo->shape) {
575 break;
576 case RB_SHAPE_BOX:
577 volume = size[0] * size[1] * size[2];
578 break;
579
580 case RB_SHAPE_SPHERE:
581 volume = 4.0f / 3.0f * float(M_PI) * radius * radius * radius;
582 break;
583
584 /* for now, assume that capsule is close enough to a cylinder... */
585 case RB_SHAPE_CAPSULE:
587 volume = float(M_PI) * radius * radius * height;
588 break;
589
590 case RB_SHAPE_CONE:
591 volume = float(M_PI) / 3.0f * radius * radius * height;
592 break;
593
594 case RB_SHAPE_CONVEXH:
595 case RB_SHAPE_TRIMESH: {
596 if (ob->type == OB_MESH) {
597 const Mesh *mesh = rigidbody_get_mesh(ob);
598 if (mesh == nullptr) {
599 return;
600 }
601
602 const Span<float3> positions = mesh->vert_positions();
603 const Span<int3> corner_tris = mesh->corner_tris();
604 const Span<int> corner_verts = mesh->corner_verts();
605
606 if (!positions.is_empty() && !corner_tris.is_empty()) {
607 BKE_mesh_calc_volume(reinterpret_cast<const float (*)[3]>(positions.data()),
608 positions.size(),
609 corner_tris.data(),
610 corner_tris.size(),
611 corner_verts.data(),
612 &volume,
613 nullptr);
614 const float volume_scale = mat4_to_volume_scale(ob->object_to_world().ptr());
615 volume *= fabsf(volume_scale);
616 }
617 }
618 else {
619 /* rough estimate from boundbox as a fallback */
620 /* XXX could implement other types of geometry here (curves, etc.) */
621 volume = size[0] * size[1] * size[2];
622 }
623 break;
624 }
625 }
626
627 /* return the volume calculated */
628 if (r_vol) {
629 *r_vol = volume;
630 }
631}
632
633void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3])
634{
635 RigidBodyOb *rbo = ob->rigidbody_object;
636
637 float size[3] = {1.0f, 1.0f, 1.0f};
638 float height = 1.0f;
639
640 zero_v3(r_center);
641
642 /* if automatically determining dimensions, use the Object's boundbox
643 * - assume that all quadrics are standing upright on local z-axis
644 * - assume even distribution of mass around the Object's pivot
645 * (i.e. Object pivot is centralized in boundbox)
646 * - boundbox gives full width
647 */
648 /* XXX: all dimensions are auto-determined now... later can add stored settings for this. */
650
651 /* Calculate volume as appropriate. */
652 switch (rbo->shape) {
654 case RB_SHAPE_BOX:
655 case RB_SHAPE_SPHERE:
656 case RB_SHAPE_CAPSULE:
658 break;
659
660 case RB_SHAPE_CONE:
661 /* take radius as largest x/y dimension, and height as z-dimension */
662 height = size[2];
663 /* cone is geometrically centered on the median,
664 * center of mass is 1/4 up from the base
665 */
666 r_center[2] = -0.25f * height;
667 break;
668
669 case RB_SHAPE_CONVEXH:
670 case RB_SHAPE_TRIMESH: {
671 if (ob->type == OB_MESH) {
672 const Mesh *mesh = rigidbody_get_mesh(ob);
673 if (mesh == nullptr) {
674 return;
675 }
676
677 const Span<float3> positions = mesh->vert_positions();
678 const Span<int3> corner_tris = mesh->corner_tris();
679
680 if (!positions.is_empty() && !corner_tris.is_empty()) {
681 BKE_mesh_calc_volume(reinterpret_cast<const float (*)[3]>(positions.data()),
682 positions.size(),
683 corner_tris.data(),
684 corner_tris.size(),
685 mesh->corner_verts().data(),
686 nullptr,
687 r_center);
688 }
689 }
690 break;
691 }
692 }
693}
694
695/* --------------------- */
696
702static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool rebuild)
703{
704 RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : nullptr;
705 float loc[3];
706 float rot[4];
707
708 /* sanity checks:
709 * - object doesn't have RigidBody info already: then why is it here?
710 */
711 if (rbo == nullptr) {
712 return;
713 }
714
715 /* make sure collision shape exists */
716 /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects,
717 * but it's needed for constraints to update correctly. */
718 if (rbo->shared->physics_shape == nullptr || rebuild) {
719 rigidbody_validate_sim_shape(rbw, ob, true);
720 }
721
722 if (rbo->shared->physics_object && !rebuild) {
723 /* Don't remove body on rebuild as it has already been removed when deleting and rebuilding the
724 * world. */
725 RB_dworld_remove_body(rbw->shared->runtime->physics_world,
726 static_cast<rbRigidBody *>(rbo->shared->physics_object));
727 }
728 if (!rbo->shared->physics_object || rebuild) {
729 /* remove rigid body if it already exists before creating a new one */
730 if (rbo->shared->physics_object) {
731 RB_body_delete(static_cast<rbRigidBody *>(rbo->shared->physics_object));
732 rbo->shared->physics_object = nullptr;
733 }
734 /* Don't create rigid body object if the parent is a compound shape */
735 if (ob->parent != nullptr && ob->parent->rigidbody_object != nullptr &&
736 ob->parent->rigidbody_object->shape == RB_SHAPE_COMPOUND)
737 {
738 return;
739 }
740
741 mat4_to_loc_quat(loc, rot, ob->object_to_world().ptr());
742
743 rbo->shared->physics_object = RB_body_new(
744 static_cast<rbCollisionShape *>(rbo->shared->physics_shape), loc, rot);
745
746 RB_body_set_friction(static_cast<rbRigidBody *>(rbo->shared->physics_object), rbo->friction);
747 RB_body_set_restitution(static_cast<rbRigidBody *>(rbo->shared->physics_object),
748 rbo->restitution);
749
750 RB_body_set_damping(static_cast<rbRigidBody *>(rbo->shared->physics_object),
751 rbo->lin_damping,
752 rbo->ang_damping);
753 RB_body_set_sleep_thresh(static_cast<rbRigidBody *>(rbo->shared->physics_object),
754 rbo->lin_sleep_thresh,
755 rbo->ang_sleep_thresh);
756 RB_body_set_activation_state(static_cast<rbRigidBody *>(rbo->shared->physics_object),
757 rbo->flag & RBO_FLAG_USE_DEACTIVATION);
758
759 if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED) {
760 RB_body_deactivate(static_cast<rbRigidBody *>(rbo->shared->physics_object));
761 }
762
763 RB_body_set_linear_factor(static_cast<rbRigidBody *>(rbo->shared->physics_object),
764 (ob->protectflag & OB_LOCK_LOCX) == 0,
765 (ob->protectflag & OB_LOCK_LOCY) == 0,
766 (ob->protectflag & OB_LOCK_LOCZ) == 0);
767 RB_body_set_angular_factor(static_cast<rbRigidBody *>(rbo->shared->physics_object),
768 (ob->protectflag & OB_LOCK_ROTX) == 0,
769 (ob->protectflag & OB_LOCK_ROTY) == 0,
770 (ob->protectflag & OB_LOCK_ROTZ) == 0);
771
772 RB_body_set_mass(static_cast<rbRigidBody *>(rbo->shared->physics_object), RBO_GET_MASS(rbo));
773 RB_body_set_kinematic_state(static_cast<rbRigidBody *>(rbo->shared->physics_object),
774 rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
775 }
776
777 if (rbw && rbw->shared->runtime->physics_world && rbo->shared->physics_object) {
778 RB_dworld_add_body(rbw->shared->runtime->physics_world,
779 static_cast<rbRigidBody *>(rbo->shared->physics_object),
780 rbo->col_groups);
781 }
782}
783
784/* --------------------- */
785
786static void rigidbody_constraint_init_spring(RigidBodyCon *rbc,
787 void (*set_spring)(rbConstraint *, int, int),
788 void (*set_stiffness)(rbConstraint *, int, float),
789 void (*set_damping)(rbConstraint *, int, float))
790{
791 set_spring(static_cast<rbConstraint *>(rbc->physics_constraint),
793 rbc->flag & RBC_FLAG_USE_SPRING_X);
794 set_stiffness(static_cast<rbConstraint *>(rbc->physics_constraint),
796 rbc->spring_stiffness_x);
797 set_damping(
798 static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_LIN_X, rbc->spring_damping_x);
799
800 set_spring(static_cast<rbConstraint *>(rbc->physics_constraint),
802 rbc->flag & RBC_FLAG_USE_SPRING_Y);
803 set_stiffness(static_cast<rbConstraint *>(rbc->physics_constraint),
805 rbc->spring_stiffness_y);
806 set_damping(
807 static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_LIN_Y, rbc->spring_damping_y);
808
809 set_spring(static_cast<rbConstraint *>(rbc->physics_constraint),
811 rbc->flag & RBC_FLAG_USE_SPRING_Z);
812 set_stiffness(static_cast<rbConstraint *>(rbc->physics_constraint),
814 rbc->spring_stiffness_z);
815 set_damping(
816 static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_LIN_Z, rbc->spring_damping_z);
817
818 set_spring(static_cast<rbConstraint *>(rbc->physics_constraint),
820 rbc->flag & RBC_FLAG_USE_SPRING_ANG_X);
821 set_stiffness(static_cast<rbConstraint *>(rbc->physics_constraint),
823 rbc->spring_stiffness_ang_x);
824 set_damping(static_cast<rbConstraint *>(rbc->physics_constraint),
826 rbc->spring_damping_ang_x);
827
828 set_spring(static_cast<rbConstraint *>(rbc->physics_constraint),
830 rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y);
831 set_stiffness(static_cast<rbConstraint *>(rbc->physics_constraint),
833 rbc->spring_stiffness_ang_y);
834 set_damping(static_cast<rbConstraint *>(rbc->physics_constraint),
836 rbc->spring_damping_ang_y);
837
838 set_spring(static_cast<rbConstraint *>(rbc->physics_constraint),
840 rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z);
841 set_stiffness(static_cast<rbConstraint *>(rbc->physics_constraint),
843 rbc->spring_stiffness_ang_z);
844 set_damping(static_cast<rbConstraint *>(rbc->physics_constraint),
846 rbc->spring_damping_ang_z);
847}
848
849static void rigidbody_constraint_set_limits(RigidBodyCon *rbc,
850 void (*set_limits)(rbConstraint *, int, float, float))
851{
852 if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
853 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint),
855 rbc->limit_lin_x_lower,
856 rbc->limit_lin_x_upper);
857 }
858 else {
859 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_LIN_X, 0.0f, -1.0f);
860 }
861
862 if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y) {
863 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint),
865 rbc->limit_lin_y_lower,
866 rbc->limit_lin_y_upper);
867 }
868 else {
869 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_LIN_Y, 0.0f, -1.0f);
870 }
871
872 if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z) {
873 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint),
875 rbc->limit_lin_z_lower,
876 rbc->limit_lin_z_upper);
877 }
878 else {
879 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_LIN_Z, 0.0f, -1.0f);
880 }
881
882 if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
883 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint),
885 rbc->limit_ang_x_lower,
886 rbc->limit_ang_x_upper);
887 }
888 else {
889 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_ANG_X, 0.0f, -1.0f);
890 }
891
892 if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y) {
893 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint),
895 rbc->limit_ang_y_lower,
896 rbc->limit_ang_y_upper);
897 }
898 else {
899 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_ANG_Y, 0.0f, -1.0f);
900 }
901
902 if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
903 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint),
905 rbc->limit_ang_z_lower,
906 rbc->limit_ang_z_upper);
907 }
908 else {
909 set_limits(static_cast<rbConstraint *>(rbc->physics_constraint), RB_LIMIT_ANG_Z, 0.0f, -1.0f);
910 }
911}
912
918static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, bool rebuild)
919{
920 RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : nullptr;
921 float loc[3];
922 float rot[4];
923 float lin_lower;
924 float lin_upper;
925 float ang_lower;
926 float ang_upper;
927
928 /* sanity checks:
929 * - object should have a rigid body constraint
930 * - rigid body constraint should have at least one constrained object
931 */
932 if (rbc == nullptr) {
933 return;
934 }
935
936 if (ELEM(nullptr, rbc->ob1, rbc->ob1->rigidbody_object, rbc->ob2, rbc->ob2->rigidbody_object)) {
937 if (rbc->physics_constraint) {
938 RB_dworld_remove_constraint(rbw->shared->runtime->physics_world,
939 static_cast<rbConstraint *>(rbc->physics_constraint));
940 RB_constraint_delete(static_cast<rbConstraint *>(rbc->physics_constraint));
941 rbc->physics_constraint = nullptr;
942 }
943 return;
944 }
945
946 if (rbc->physics_constraint && rebuild == false) {
947 RB_dworld_remove_constraint(rbw->shared->runtime->physics_world,
948 static_cast<rbConstraint *>(rbc->physics_constraint));
949 }
950 if (rbc->physics_constraint == nullptr || rebuild) {
951 rbRigidBody *rb1 = static_cast<rbRigidBody *>(
952 rbc->ob1->rigidbody_object->shared->physics_object);
953 rbRigidBody *rb2 = static_cast<rbRigidBody *>(
954 rbc->ob2->rigidbody_object->shared->physics_object);
955
956 /* remove constraint if it already exists before creating a new one */
957 if (rbc->physics_constraint) {
958 RB_constraint_delete(static_cast<rbConstraint *>(rbc->physics_constraint));
959 rbc->physics_constraint = nullptr;
960 }
961
962 mat4_to_loc_quat(loc, rot, ob->object_to_world().ptr());
963
964 if (rb1 && rb2) {
965 switch (rbc->type) {
966 case RBC_TYPE_POINT:
967 rbc->physics_constraint = RB_constraint_new_point(loc, rb1, rb2);
968 break;
969 case RBC_TYPE_FIXED:
970 rbc->physics_constraint = RB_constraint_new_fixed(loc, rot, rb1, rb2);
971 break;
972 case RBC_TYPE_HINGE:
973 rbc->physics_constraint = RB_constraint_new_hinge(loc, rot, rb1, rb2);
974 if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
975 RB_constraint_set_limits_hinge(static_cast<rbConstraint *>(rbc->physics_constraint),
976 rbc->limit_ang_z_lower,
977 rbc->limit_ang_z_upper);
978 }
979 else {
981 static_cast<rbConstraint *>(rbc->physics_constraint), 0.0f, -1.0f);
982 }
983 break;
984 case RBC_TYPE_SLIDER:
985 rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2);
986 if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
987 RB_constraint_set_limits_slider(static_cast<rbConstraint *>(rbc->physics_constraint),
988 rbc->limit_lin_x_lower,
989 rbc->limit_lin_x_upper);
990 }
991 else {
993 static_cast<rbConstraint *>(rbc->physics_constraint), 0.0f, -1.0f);
994 }
995 break;
996 case RBC_TYPE_PISTON:
997 rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2);
998 if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
999 lin_lower = rbc->limit_lin_x_lower;
1000 lin_upper = rbc->limit_lin_x_upper;
1001 }
1002 else {
1003 lin_lower = 0.0f;
1004 lin_upper = -1.0f;
1005 }
1006 if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
1007 ang_lower = rbc->limit_ang_x_lower;
1008 ang_upper = rbc->limit_ang_x_upper;
1009 }
1010 else {
1011 ang_lower = 0.0f;
1012 ang_upper = -1.0f;
1013 }
1014 RB_constraint_set_limits_piston(static_cast<rbConstraint *>(rbc->physics_constraint),
1015 lin_lower,
1016 lin_upper,
1017 ang_lower,
1018 ang_upper);
1019 break;
1021 if (rbc->spring_type == RBC_SPRING_TYPE2) {
1022 rbc->physics_constraint = RB_constraint_new_6dof_spring2(loc, rot, rb1, rb2);
1023
1024 rigidbody_constraint_init_spring(rbc,
1028
1030 static_cast<rbConstraint *>(rbc->physics_constraint));
1031
1032 rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof_spring2);
1033 }
1034 else {
1035 rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2);
1036
1037 rigidbody_constraint_init_spring(rbc,
1041
1043 static_cast<rbConstraint *>(rbc->physics_constraint));
1044
1045 rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof);
1046 }
1047 break;
1048 case RBC_TYPE_6DOF:
1049 rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
1050
1051 rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof);
1052 break;
1053 case RBC_TYPE_MOTOR:
1054 rbc->physics_constraint = RB_constraint_new_motor(loc, rot, rb1, rb2);
1055
1056 RB_constraint_set_enable_motor(static_cast<rbConstraint *>(rbc->physics_constraint),
1057 rbc->flag & RBC_FLAG_USE_MOTOR_LIN,
1058 rbc->flag & RBC_FLAG_USE_MOTOR_ANG);
1059 RB_constraint_set_max_impulse_motor(static_cast<rbConstraint *>(rbc->physics_constraint),
1060 rbc->motor_lin_max_impulse,
1061 rbc->motor_ang_max_impulse);
1063 static_cast<rbConstraint *>(rbc->physics_constraint),
1064 rbc->motor_lin_target_velocity,
1065 rbc->motor_ang_target_velocity);
1066 break;
1067 }
1068 }
1069 else { /* can't create constraint without both rigid bodies */
1070 return;
1071 }
1072
1073 /* When 'rbc->type' is unknown. */
1074 if (rbc->physics_constraint == nullptr) {
1075 return;
1076 }
1077
1078 RB_constraint_set_enabled(static_cast<rbConstraint *>(rbc->physics_constraint),
1079 rbc->flag & RBC_FLAG_ENABLED);
1080
1081 if (rbc->flag & RBC_FLAG_USE_BREAKING) {
1082 RB_constraint_set_breaking_threshold(static_cast<rbConstraint *>(rbc->physics_constraint),
1083 rbc->breaking_threshold);
1084 }
1085 else {
1086 RB_constraint_set_breaking_threshold(static_cast<rbConstraint *>(rbc->physics_constraint),
1087 FLT_MAX);
1088 }
1089
1090 if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS) {
1091 RB_constraint_set_solver_iterations(static_cast<rbConstraint *>(rbc->physics_constraint),
1092 rbc->num_solver_iterations);
1093 }
1094 else {
1095 RB_constraint_set_solver_iterations(static_cast<rbConstraint *>(rbc->physics_constraint),
1096 -1);
1097 }
1098 }
1099
1100 if (rbw && rbw->shared->runtime->physics_world && rbc->physics_constraint) {
1101 RB_dworld_add_constraint(rbw->shared->runtime->physics_world,
1102 static_cast<rbConstraint *>(rbc->physics_constraint),
1103 rbc->flag & RBC_FLAG_DISABLE_COLLISIONS);
1104 }
1105}
1106
1107/* --------------------- */
1108
1109void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild)
1110{
1111 /* sanity checks */
1112 if (rbw == nullptr) {
1113 return;
1114 }
1115
1116 /* create new sim world */
1117 if (rebuild || rbw->shared->runtime->physics_world == nullptr) {
1118 if (rbw->shared->runtime->physics_world) {
1119 RB_dworld_delete(rbw->shared->runtime->physics_world);
1120 }
1121 rbw->shared->runtime->physics_world = RB_dworld_new(scene->physics_settings.gravity);
1122 }
1123
1124 RB_dworld_set_solver_iterations(rbw->shared->runtime->physics_world, rbw->num_solver_iterations);
1125 RB_dworld_set_split_impulse(rbw->shared->runtime->physics_world,
1126 rbw->flag & RBW_FLAG_USE_SPLIT_IMPULSE);
1127}
1128
1129/* ************************************** */
1130/* Setup Utilities - Create Settings Blocks */
1131
1133{
1134 /* try to get whatever RigidBody world that might be representing this already */
1135 RigidBodyWorld *rbw;
1136
1137 /* sanity checks
1138 * - there must be a valid scene to add world to
1139 * - there mustn't be a sim world using this group already
1140 */
1141 if (scene == nullptr) {
1142 return nullptr;
1143 }
1144
1145 /* create a new sim world */
1146 rbw = MEM_new<RigidBodyWorld>("RigidBodyWorld");
1147 rbw->shared = MEM_new<RigidBodyWorld_Shared>("RigidBodyWorld_Shared");
1148
1149 /* set default settings */
1150 rbw->effector_weights = BKE_effector_add_weights(nullptr);
1151
1152 rbw->ltime = scene->playback_start();
1153
1154 rbw->time_scale = 1.0f;
1155
1156 /* Most high quality Bullet example files has an internal frame-rate of 240hz.
1157 * The blender default scene has a frame rate of 24, so take 10 sub-steps (24fps * 10). */
1158 rbw->substeps_per_frame = 10;
1159 rbw->num_solver_iterations = 10; /* 10 is bullet default */
1160
1161 rbw->shared->pointcache = BKE_ptcache_add(&(rbw->shared->ptcaches));
1162 rbw->shared->pointcache->step = 1;
1163
1165
1166 /* return this sim world */
1167 return rbw;
1168}
1169
1171{
1172 RigidBodyWorld *rbw_copy = MEM_dupalloc(rbw);
1173
1174 if (rbw->effector_weights) {
1175 rbw_copy->effector_weights = static_cast<EffectorWeights *>(
1176 MEM_dupalloc(rbw->effector_weights));
1177 if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
1178 id_us_plus((ID *)rbw->effector_weights->group);
1179 }
1180 }
1181 if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
1182 id_us_plus((ID *)rbw_copy->group);
1183 id_us_plus((ID *)rbw_copy->constraints);
1184 }
1185
1186 if ((flag & LIB_ID_COPY_SET_COPIED_ON_WRITE) == 0) {
1187 /* This is a regular copy, and not an evaluated copy for depsgraph evaluation. */
1188 rbw_copy->shared = MEM_new<RigidBodyWorld_Shared>("RigidBodyWorld_Shared");
1189 BKE_ptcache_copy_list(&rbw_copy->shared->ptcaches, &rbw->shared->ptcaches, LIB_ID_COPY_CACHES);
1190 rbw_copy->shared->pointcache = rbw_copy->shared->ptcaches.first();
1192 }
1193
1194 rbw_copy->objects = nullptr;
1195 rbw_copy->numbodies = 0;
1196 rigidbody_update_ob_array(rbw_copy);
1197
1198 return rbw_copy;
1199}
1200
1202{
1203 ID_NEW_REMAP(rbw->group);
1204 ID_NEW_REMAP(rbw->constraints);
1205 ID_NEW_REMAP(rbw->effector_weights->group);
1206}
1207
1209{
1210 RigidBodyOb *rbo;
1211 RigidBodyWorld *rbw = scene->rigidbody_world;
1212
1213 /* sanity checks
1214 * - rigidbody world must exist
1215 * - object must exist
1216 * - cannot add rigid body if it already exists
1217 */
1218 if (ob == nullptr) {
1219 return nullptr;
1220 }
1221 if (ob->rigidbody_object != nullptr) {
1222 return ob->rigidbody_object;
1223 }
1224
1225 /* create new settings data, and link it up */
1226 rbo = MEM_new<RigidBodyOb>("RigidBodyOb");
1227 rbo->shared = MEM_new<RigidBodyOb_Shared>("RigidBodyOb_Shared");
1228
1229 /* set default settings */
1230 rbo->type = type;
1231
1232 rbo->mass = 1.0f;
1233
1234 rbo->friction = 0.5f; /* best when non-zero. 0.5 is Bullet default */
1235 rbo->restitution = 0.0f; /* best when zero. 0.0 is Bullet default */
1236
1237 rbo->margin = 0.04f; /* 0.04 (in meters) is Bullet default */
1238
1239 rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */
1240 rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */
1241
1242 rbo->lin_damping = 0.04f;
1243 rbo->ang_damping = 0.1f;
1244
1245 rbo->col_groups = 1;
1246
1247 /* use triangle meshes for passive objects
1248 * use convex hulls for active objects since dynamic triangle meshes are very unstable
1249 */
1250 if (type == RBO_TYPE_ACTIVE) {
1251 rbo->shape = RB_SHAPE_CONVEXH;
1252 }
1253 else {
1254 rbo->shape = RB_SHAPE_TRIMESH;
1255 }
1256
1257 rbo->mesh_source = RBO_MESH_DEFORM;
1258
1259 /* set initial transform */
1260 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->object_to_world().ptr());
1261
1262 /* flag cache as outdated */
1265
1266 /* return this object */
1267 return rbo;
1268}
1269
1271{
1272 RigidBodyCon *rbc;
1273 RigidBodyWorld *rbw = scene->rigidbody_world;
1274
1275 /* sanity checks
1276 * - rigidbody world must exist
1277 * - object must exist
1278 * - cannot add constraint if it already exists
1279 */
1280 if (ob == nullptr || (ob->rigidbody_constraint != nullptr)) {
1281 return nullptr;
1282 }
1283
1284 /* create new settings data, and link it up */
1285 rbc = MEM_new<RigidBodyCon>("RigidBodyCon");
1286
1287 /* set default settings */
1288 rbc->type = type;
1289
1290 rbc->ob1 = nullptr;
1291 rbc->ob2 = nullptr;
1292
1293 rbc->flag |= RBC_FLAG_ENABLED;
1294 rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS;
1295 rbc->flag |= RBC_FLAG_NEEDS_VALIDATE;
1296
1297 rbc->spring_type = RBC_SPRING_TYPE2;
1298
1299 rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */
1300 rbc->num_solver_iterations = 10; /* 10 is Bullet default */
1301
1302 rbc->limit_lin_x_lower = -1.0f;
1303 rbc->limit_lin_x_upper = 1.0f;
1304 rbc->limit_lin_y_lower = -1.0f;
1305 rbc->limit_lin_y_upper = 1.0f;
1306 rbc->limit_lin_z_lower = -1.0f;
1307 rbc->limit_lin_z_upper = 1.0f;
1308 rbc->limit_ang_x_lower = -M_PI_4;
1309 rbc->limit_ang_x_upper = M_PI_4;
1310 rbc->limit_ang_y_lower = -M_PI_4;
1311 rbc->limit_ang_y_upper = M_PI_4;
1312 rbc->limit_ang_z_lower = -M_PI_4;
1313 rbc->limit_ang_z_upper = M_PI_4;
1314
1315 rbc->spring_damping_x = 0.5f;
1316 rbc->spring_damping_y = 0.5f;
1317 rbc->spring_damping_z = 0.5f;
1318 rbc->spring_damping_ang_x = 0.5f;
1319 rbc->spring_damping_ang_y = 0.5f;
1320 rbc->spring_damping_ang_z = 0.5f;
1321 rbc->spring_stiffness_x = 10.0f;
1322 rbc->spring_stiffness_y = 10.0f;
1323 rbc->spring_stiffness_z = 10.0f;
1324 rbc->spring_stiffness_ang_x = 10.0f;
1325 rbc->spring_stiffness_ang_y = 10.0f;
1326 rbc->spring_stiffness_ang_z = 10.0f;
1327
1328 rbc->motor_lin_max_impulse = 1.0f;
1329 rbc->motor_lin_target_velocity = 1.0f;
1330 rbc->motor_ang_max_impulse = 1.0f;
1331 rbc->motor_ang_target_velocity = 1.0f;
1332
1333 /* flag cache as outdated */
1335
1336 /* return this object */
1337 return rbc;
1338}
1339
1341{
1342 if (rbw->group != nullptr) {
1343 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->group, object) {
1344 if (object->type != OB_MESH || object->rigidbody_object != nullptr) {
1345 continue;
1346 }
1347 object->rigidbody_object = BKE_rigidbody_create_object(scene, object, RBO_TYPE_ACTIVE);
1349 }
1352 }
1353}
1354
1356{
1357 if (rbw->constraints != nullptr) {
1358 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->constraints, object) {
1359 if (object->rigidbody_constraint != nullptr) {
1360 continue;
1361 }
1362 object->rigidbody_constraint = BKE_rigidbody_create_constraint(
1363 scene, object, RBC_TYPE_FIXED);
1364 }
1366 }
1367}
1368
1369void BKE_rigidbody_main_collection_object_add(Main *bmain, Collection *collection, Object *object)
1370{
1371 for (Scene *scene = bmain->scenes.first(); scene; scene = static_cast<Scene *>(scene->id.next)) {
1372 RigidBodyWorld *rbw = scene->rigidbody_world;
1373
1374 if (rbw == nullptr) {
1375 continue;
1376 }
1377
1378 if (rbw->group == collection && object->type == OB_MESH && object->rigidbody_object == nullptr)
1379 {
1380 object->rigidbody_object = BKE_rigidbody_create_object(scene, object, RBO_TYPE_ACTIVE);
1381 }
1382 if (rbw->constraints == collection && object->rigidbody_constraint == nullptr) {
1383 object->rigidbody_constraint = BKE_rigidbody_create_constraint(
1384 scene, object, RBC_TYPE_FIXED);
1385 }
1386 }
1387}
1388
1389/* ************************************** */
1390/* Utilities API */
1391
1393{
1394 /* sanity check */
1395 if (scene == nullptr) {
1396 return nullptr;
1397 }
1398
1399 return scene->rigidbody_world;
1400}
1401
1402static bool rigidbody_add_object_to_scene(Main *bmain, Scene *scene, Object *ob)
1403{
1404 /* Add rigid body world and group if they don't exist for convenience */
1406 if (rbw == nullptr) {
1407 rbw = BKE_rigidbody_create_world(scene);
1408 if (rbw == nullptr) {
1409 return false;
1410 }
1411
1412 BKE_rigidbody_validate_sim_world(scene, rbw, false);
1413 scene->rigidbody_world = rbw;
1414 }
1415
1416 if (rbw->group == nullptr) {
1417 rbw->group = BKE_collection_add(bmain, nullptr, "RigidBodyWorld");
1418 id_us_plus(&rbw->group->id);
1419 }
1420
1421 /* Add object to rigid body group. */
1422 BKE_collection_object_add(bmain, rbw->group, ob);
1424
1426 DEG_id_tag_update(&rbw->group->id, ID_RECALC_SYNC_TO_EVAL);
1427
1428 return true;
1429}
1430
1431static bool rigidbody_add_constraint_to_scene(Main *bmain, Scene *scene, Object *ob)
1432{
1433 /* Add rigid body world and group if they don't exist for convenience */
1435 if (rbw == nullptr) {
1436 rbw = BKE_rigidbody_create_world(scene);
1437 if (rbw == nullptr) {
1438 return false;
1439 }
1440
1441 BKE_rigidbody_validate_sim_world(scene, rbw, false);
1442 scene->rigidbody_world = rbw;
1443 }
1444
1445 if (rbw->constraints == nullptr) {
1446 rbw->constraints = BKE_collection_add(bmain, nullptr, "RigidBodyConstraints");
1447 id_us_plus(&rbw->constraints->id);
1448 }
1449
1450 /* Add object to rigid body group. */
1451 BKE_collection_object_add(bmain, rbw->constraints, ob);
1453
1455 DEG_id_tag_update(&rbw->constraints->id, ID_RECALC_SYNC_TO_EVAL);
1456
1457 return true;
1458}
1459
1461{
1462 if (ob->rigidbody_object != nullptr) {
1463 /* Add newly local object to scene. */
1464 for (Scene *scene = bmain->scenes.first(); scene; scene = static_cast<Scene *>(scene->id.next))
1465 {
1466 if (BKE_scene_object_find(*bmain, scene, ob)) {
1467 rigidbody_add_object_to_scene(bmain, scene, ob);
1468 }
1469 }
1470 }
1471 if (ob->rigidbody_constraint != nullptr) {
1472 /* Add newly local object to scene. */
1473 for (Scene *scene = bmain->scenes.first(); scene; scene = static_cast<Scene *>(scene->id.next))
1474 {
1475 if (BKE_scene_object_find(*bmain, scene, ob)) {
1476 rigidbody_add_constraint_to_scene(bmain, scene, ob);
1477 }
1478 }
1479 }
1480}
1481
1483 Main *bmain, Scene *scene, Object *ob, eRigidBodyOb_Type type, ReportList *reports)
1484{
1485 if (ob->type != OB_MESH) {
1486 BKE_report(reports, RPT_ERROR, "Cannot add Rigid Body to non mesh object");
1487 return false;
1488 }
1489
1490 /* Add object to rigid body world in scene. */
1491 if (!rigidbody_add_object_to_scene(bmain, scene, ob)) {
1492 BKE_report(reports, RPT_ERROR, "Cannot create Rigid Body world");
1493 return false;
1494 }
1495
1496 /* make rigidbody object settings */
1497 if (ob->rigidbody_object == nullptr) {
1498 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, type);
1499 }
1500 ob->rigidbody_object->type = type;
1501 ob->rigidbody_object->flag |= RBO_FLAG_NEEDS_VALIDATE;
1502
1505
1506 return true;
1507}
1508
1509void BKE_rigidbody_remove_object(Main *bmain, Scene *scene, Object *ob, const bool free_us)
1510{
1511 RigidBodyWorld *rbw = scene->rigidbody_world;
1512 RigidBodyCon *rbc;
1513 int i;
1514
1515 if (rbw) {
1516
1517 /* remove object from array */
1518 if (rbw->objects) {
1519 for (i = 0; i < rbw->numbodies; i++) {
1520 if (rbw->objects[i] == ob) {
1521 rbw->objects[i] = nullptr;
1522 break;
1523 }
1524 }
1525 }
1526
1527 /* remove object from rigid body constraints */
1528 if (rbw->constraints) {
1529 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->constraints, obt) {
1530 if (obt && obt->rigidbody_constraint) {
1531 rbc = obt->rigidbody_constraint;
1532 if (rbc->ob1 == ob) {
1533 rbc->ob1 = nullptr;
1535 rigidbody_validate_sim_constraint(rbw, obt, false);
1536 }
1537 if (rbc->ob2 == ob) {
1538 rbc->ob2 = nullptr;
1540 rigidbody_validate_sim_constraint(rbw, obt, false);
1541 }
1542 }
1543 }
1545 }
1546
1547 /* Relying on user-count of the object should be OK, and it is much cheaper than looping in all
1548 * collections to check whether the object is already in another one... */
1549 if (ID_REAL_USERS(&ob->id) == 1) {
1550 /* Some users seems to find it funny to use a view-layer instancing collection
1551 * as RBW collection... Despite this being a bad (ab)use of the system, avoid losing objects
1552 * when we remove them from RB simulation. */
1553 BKE_collection_object_add(bmain, scene->master_collection, ob);
1554 }
1555 if (rbw->group) {
1556 BKE_collection_object_remove(bmain, rbw->group, ob, free_us);
1557 DEG_id_tag_update(&rbw->group->id, ID_RECALC_SYNC_TO_EVAL);
1558 }
1559
1560 /* flag cache as outdated */
1562 /* Reset cache as the object order probably changed after freeing the object. */
1563 PTCacheID pid;
1564 BKE_ptcache_id_from_rigidbody(&pid, nullptr, rbw);
1566 }
1567
1568 /* remove object's settings */
1570
1571 /* Dependency graph update */
1574}
1575
1576void BKE_rigidbody_remove_constraint(Main *bmain, Scene *scene, Object *ob, const bool free_us)
1577{
1578 RigidBodyWorld *rbw = scene->rigidbody_world;
1579 RigidBodyCon *rbc = ob->rigidbody_constraint;
1580
1581 if (rbw != nullptr) {
1582 /* Remove from RBW constraints collection. */
1583 if (rbw->constraints != nullptr) {
1584 BKE_collection_object_remove(bmain, rbw->constraints, ob, free_us);
1585 DEG_id_tag_update(&rbw->constraints->id, ID_RECALC_SYNC_TO_EVAL);
1586 }
1587
1588 /* remove from rigidbody world, free object won't do this */
1589 if (rbw->shared->runtime->physics_world && rbc->physics_constraint) {
1590 RB_dworld_remove_constraint(rbw->shared->runtime->physics_world,
1591 static_cast<rbConstraint *>(rbc->physics_constraint));
1592 }
1593 }
1594
1595 /* remove object's settings */
1597
1598 /* flag cache as outdated */
1600}
1601
1602/* ************************************** */
1603/* Simulation Interface - Bullet */
1604
1605/* Update object array and rigid body count so they're in sync with the rigid body group */
1606static void rigidbody_update_ob_array(RigidBodyWorld *rbw)
1607{
1608 if (rbw->group == nullptr) {
1609 rbw->numbodies = 0;
1610 rbw->objects = static_cast<Object **>(realloc(rbw->objects, 0));
1611 return;
1612 }
1613
1614 int n = 0;
1615 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->group, object) {
1616 (void)object;
1617 /* Ignore if this object is the direct child of an object with a compound shape */
1618 if (object->parent == nullptr || object->parent->rigidbody_object == nullptr ||
1619 object->parent->rigidbody_object->shape != RB_SHAPE_COMPOUND)
1620 {
1621 n++;
1622 }
1623 }
1625
1626 if (rbw->numbodies != n) {
1627 rbw->numbodies = n;
1628 rbw->objects = static_cast<Object **>(
1629 realloc(rbw->objects, sizeof(Object *) * rbw->numbodies));
1630 }
1631
1632 int i = 0;
1633 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->group, object) {
1634 /* Ignore if this object is the direct child of an object with a compound shape */
1635 if (object->parent == nullptr || object->parent->rigidbody_object == nullptr ||
1636 object->parent->rigidbody_object->shape != RB_SHAPE_COMPOUND)
1637 {
1638 rbw->objects[i] = object;
1639 i++;
1640 }
1641 }
1643}
1644
1645static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
1646{
1647 float adj_gravity[3];
1648
1649 /* adjust gravity to take effector weights into account */
1650 if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
1651 copy_v3_v3(adj_gravity, scene->physics_settings.gravity);
1652 mul_v3_fl(adj_gravity,
1653 rbw->effector_weights->global_gravity * rbw->effector_weights->weight[0]);
1654 }
1655 else {
1656 zero_v3(adj_gravity);
1657 }
1658
1659 /* update gravity, since this RNA setting is not part of RigidBody settings */
1660 RB_dworld_set_gravity(rbw->shared->runtime->physics_world, adj_gravity);
1661
1662 /* update object array in case there are changes */
1663 rigidbody_update_ob_array(rbw);
1664}
1665
1666static void rigidbody_update_sim_ob(Depsgraph *depsgraph, Object *ob, RigidBodyOb *rbo)
1667{
1668 /* only update if rigid body exists */
1669 if (rbo->shared->physics_object == nullptr) {
1670 return;
1671 }
1672
1673 const Scene *scene = DEG_get_input_scene(depsgraph);
1674 ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1675 BKE_view_layer_synced_ensure(*DEG_get_bmain(depsgraph), scene, view_layer);
1676 Base *base = BKE_view_layer_base_find(view_layer, ob);
1677 const bool is_selected = base ? (base->flag & BASE_SELECTED) != 0 : false;
1678
1679 if (rbo->shape == RB_SHAPE_TRIMESH && rbo->flag & RBO_FLAG_USE_DEFORM) {
1681 if (mesh) {
1682 const float (*positions)[3] = reinterpret_cast<const float (*)[3]>(
1683 mesh->vert_positions().data());
1684 int totvert = mesh->verts_num;
1685 const std::optional<Bounds<float3>> bounds = BKE_object_boundbox_get(ob);
1686
1687 RB_shape_trimesh_update(static_cast<rbCollisionShape *>(rbo->shared->physics_shape),
1688 (float *)positions,
1689 totvert,
1690 sizeof(float[3]),
1691 bounds->min,
1692 bounds->max);
1693 }
1694 }
1695
1696 if (!(rbo->flag & RBO_FLAG_KINEMATIC)) {
1697 /* update scale for all non kinematic objects */
1698 float new_scale[3], old_scale[3];
1699 mat4_to_size(new_scale, ob->object_to_world().ptr());
1700 RB_body_get_scale(static_cast<rbRigidBody *>(rbo->shared->physics_object), old_scale);
1701
1702 /* Avoid updating collision shape AABBs if scale didn't change. */
1703 if (!compare_size_v3v3(old_scale, new_scale, 0.001f)) {
1704 RB_body_set_scale(static_cast<rbRigidBody *>(rbo->shared->physics_object), new_scale);
1705 /* compensate for embedded convex hull collision margin */
1706 if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH) {
1707 RB_shape_set_margin(static_cast<rbCollisionShape *>(rbo->shared->physics_shape),
1708 RBO_GET_MARGIN(rbo) *
1709 std::min({new_scale[0], new_scale[1], new_scale[2]}));
1710 }
1711 }
1712 }
1713
1714 /* Make transformed objects temporarily kinematic
1715 * so that they can be moved by the user during simulation. */
1716 if (is_selected && (G.moving & G_TRANSFORM_OBJ)) {
1717 RB_body_set_kinematic_state(static_cast<rbRigidBody *>(rbo->shared->physics_object), true);
1718 RB_body_set_mass(static_cast<rbRigidBody *>(rbo->shared->physics_object), 0.0f);
1719 }
1720
1721 /* NOTE: no other settings need to be explicitly updated here,
1722 * since RNA setters take care of the rest :)
1723 */
1724}
1725
1731static void rigidbody_update_simulation(Depsgraph *depsgraph,
1732 Scene *scene,
1733 RigidBodyWorld *rbw,
1734 bool rebuild)
1735{
1736 /* update world */
1737 /* Note physics_world can get nullptr when undoing the deletion of the last object in it (see
1738 * #70667). */
1739 if (rebuild || rbw->shared->runtime->physics_world == nullptr) {
1740 BKE_rigidbody_validate_sim_world(scene, rbw, rebuild);
1741 /* We have rebuilt the world so we need to make sure the rest is rebuilt as well. */
1742 rebuild = true;
1743 }
1744
1745 rigidbody_update_sim_world(scene, rbw);
1746
1747 /* XXX TODO: For rebuild: remove all constraints first.
1748 * Otherwise we can end up deleting objects that are still
1749 * referenced by constraints, corrupting bullet's internal list.
1750 *
1751 * Memory management needs redesign here, this is just a dirty workaround.
1752 */
1753 if (rebuild && rbw->constraints) {
1754 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->constraints, ob) {
1755 RigidBodyCon *rbc = ob->rigidbody_constraint;
1756 if (rbc && rbc->physics_constraint) {
1757 RB_dworld_remove_constraint(rbw->shared->runtime->physics_world,
1758 static_cast<rbConstraint *>(rbc->physics_constraint));
1759 RB_constraint_delete(static_cast<rbConstraint *>(rbc->physics_constraint));
1760 rbc->physics_constraint = nullptr;
1761 }
1762 }
1764 }
1765
1766 /* update objects */
1768 if (ob->type == OB_MESH) {
1769 /* validate that we've got valid object set up here... */
1770 RigidBodyOb *rbo = ob->rigidbody_object;
1771
1772 /* TODO: remove this whole block once we are sure we never get nullptr rbo here anymore. */
1773 /* This cannot be done in copy-on-eval evaluation context anymore... */
1774 if (rbo == nullptr) {
1776 "Evaluated object part of RBW object collection without RB object data, "
1777 "should not happen.\n");
1778 /* Since this object is included in the sim group but doesn't have
1779 * rigid body settings (perhaps it was added manually), add!
1780 * - assume object to be active? That is the default for newly added settings...
1781 */
1782 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, RBO_TYPE_ACTIVE);
1783 rigidbody_validate_sim_object(rbw, ob, true);
1784
1785 rbo = ob->rigidbody_object;
1786 }
1787 else {
1788 /* perform simulation data updates as tagged */
1789 /* refresh object... */
1790 if (rebuild) {
1791 /* World has been rebuilt so rebuild object */
1792 /* TODO(Sybren): rigidbody_validate_sim_object() can call rigidbody_validate_sim_shape(),
1793 * but neither resets the RBO_FLAG_NEEDS_RESHAPE flag nor
1794 * calls RB_body_set_collision_shape().
1795 * This results in the collision shape being created twice, which is unnecessary. */
1796 rigidbody_validate_sim_object(rbw, ob, true);
1797 }
1798 else if (rbo->flag & RBO_FLAG_NEEDS_VALIDATE) {
1799 rigidbody_validate_sim_object(rbw, ob, false);
1800 }
1801 /* refresh shape... */
1802 if (rbo->flag & RBO_FLAG_NEEDS_RESHAPE) {
1803 /* mesh/shape data changed, so force shape refresh */
1804 rigidbody_validate_sim_shape(rbw, ob, true);
1805 /* now tell RB sim about it */
1806 /* XXX: we assume that this can only get applied for active/passive shapes
1807 * that will be included as rigid-bodies. */
1808 if (rbo->shared->physics_object != nullptr && rbo->shared->physics_shape != nullptr) {
1810 static_cast<rbRigidBody *>(rbo->shared->physics_object),
1811 static_cast<rbCollisionShape *>(rbo->shared->physics_shape));
1812 }
1813 }
1814 }
1816
1817 /* update simulation object... */
1818 rigidbody_update_sim_ob(depsgraph, ob, rbo);
1819 }
1820 }
1822
1823 /* update constraints */
1824 if (rbw->constraints == nullptr) { /* no constraints, move on */
1825 return;
1826 }
1827
1828 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->constraints, ob) {
1829 /* validate that we've got valid object set up here... */
1830 RigidBodyCon *rbc = ob->rigidbody_constraint;
1831
1832 /* TODO: remove this whole block once we are sure we never get nullptr rbo here anymore. */
1833 /* This cannot be done in copy-on-eval evaluation context anymore... */
1834 if (rbc == nullptr) {
1836 0,
1837 "Evaluated object part of RBW constraints collection without RB constraint data, "
1838 "should not happen.\n");
1839 /* Since this object is included in the group but doesn't have
1840 * constraint settings (perhaps it was added manually), add!
1841 */
1842 ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, RBC_TYPE_FIXED);
1843 rigidbody_validate_sim_constraint(rbw, ob, true);
1844
1845 rbc = ob->rigidbody_constraint;
1846 }
1847 else {
1848 /* perform simulation data updates as tagged */
1849 if (rebuild) {
1850 /* World has been rebuilt so rebuild constraint */
1851 rigidbody_validate_sim_constraint(rbw, ob, true);
1852 }
1853 else if (rbc->flag & RBC_FLAG_NEEDS_VALIDATE) {
1854 rigidbody_validate_sim_constraint(rbw, ob, false);
1855 }
1856 }
1857 rbc->flag &= ~RBC_FLAG_NEEDS_VALIDATE;
1858 }
1860}
1861
1862struct KinematicSubstepData {
1863 RigidBodyOb *rbo;
1864 float old_pos[3];
1865 float new_pos[3];
1866 float old_rot[4];
1867 float new_rot[4];
1868 bool scale_changed;
1869 float old_scale[3];
1870 float new_scale[3];
1871};
1872
1873static ListBaseT<LinkData> rigidbody_create_substep_data(RigidBodyWorld *rbw)
1874{
1875 /* Objects that we want to update substep location/rotation for. */
1876 ListBaseT<LinkData> substep_targets = {nullptr, nullptr};
1877
1879 RigidBodyOb *rbo = ob->rigidbody_object;
1880 /* only update if rigid body exists */
1881 if (!rbo || rbo->shared->physics_object == nullptr) {
1882 continue;
1883 }
1884
1885 if (rbo->flag & RBO_FLAG_KINEMATIC) {
1886 float loc[3], rot[4], scale[3];
1887
1888 KinematicSubstepData *data = MEM_new_zeroed<KinematicSubstepData>("RigidBody Substep data");
1889
1890 data->rbo = rbo;
1891
1892 RB_body_get_position(static_cast<rbRigidBody *>(rbo->shared->physics_object), loc);
1893 RB_body_get_orientation(static_cast<rbRigidBody *>(rbo->shared->physics_object), rot);
1894 RB_body_get_scale(static_cast<rbRigidBody *>(rbo->shared->physics_object), scale);
1895
1896 copy_v3_v3(data->old_pos, loc);
1897 copy_v4_v4(data->old_rot, rot);
1898 copy_v3_v3(data->old_scale, scale);
1899
1900 mat4_decompose(loc, rot, scale, ob->object_to_world().ptr());
1901
1902 copy_v3_v3(data->new_pos, loc);
1903 copy_v4_v4(data->new_rot, rot);
1904 copy_v3_v3(data->new_scale, scale);
1905
1906 data->scale_changed = !compare_size_v3v3(data->old_scale, data->new_scale, 0.001f);
1907
1908 LinkData *ob_link = BLI_genericNodeN(data);
1909 BLI_addtail(&substep_targets, ob_link);
1910 }
1911 }
1913
1914 return substep_targets;
1915}
1916
1917static void rigidbody_update_kinematic_obj_substep(ListBaseT<LinkData> *substep_targets,
1918 float interp_fac)
1919{
1920 for (LinkData &link : *substep_targets) {
1921 KinematicSubstepData *data = static_cast<KinematicSubstepData *>(link.data);
1922 RigidBodyOb *rbo = data->rbo;
1923
1924 float loc[3], rot[4];
1925
1926 interp_v3_v3v3(loc, data->old_pos, data->new_pos, interp_fac);
1927 interp_qt_qtqt(rot, data->old_rot, data->new_rot, interp_fac);
1928
1929 RB_body_activate(static_cast<rbRigidBody *>(rbo->shared->physics_object));
1930 RB_body_set_loc_rot(static_cast<rbRigidBody *>(rbo->shared->physics_object), loc, rot);
1931
1932 if (!data->scale_changed) {
1933 /* Avoid having to rebuild the collision shape AABBs if scale didn't change. */
1934 continue;
1935 }
1936
1937 float scale[3];
1938
1939 interp_v3_v3v3(scale, data->old_scale, data->new_scale, interp_fac);
1940
1941 RB_body_set_scale(static_cast<rbRigidBody *>(rbo->shared->physics_object), scale);
1942
1943 /* compensate for embedded convex hull collision margin */
1944 if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH) {
1945 RB_shape_set_margin(static_cast<rbCollisionShape *>(rbo->shared->physics_shape),
1946 RBO_GET_MARGIN(rbo) * std::min({scale[0], scale[1], scale[2]}));
1947 }
1948 }
1949}
1950
1951static void rigidbody_update_external_forces(Depsgraph *depsgraph,
1952 Scene *scene,
1953 RigidBodyWorld *rbw)
1954{
1956 /* only update if rigid body exists */
1957 RigidBodyOb *rbo = ob->rigidbody_object;
1958 if (ob->type != OB_MESH || rbo->shared->physics_object == nullptr) {
1959 continue;
1960 }
1961
1962 /* update influence of effectors - but don't do it on an effector */
1963 /* only dynamic bodies need effector update */
1964 if (rbo->type == RBO_TYPE_ACTIVE &&
1965 ((ob->pd == nullptr) || (ob->pd->forcefield == PFIELD_NULL)))
1966 {
1967 EffectorWeights *effector_weights = rbw->effector_weights;
1968 EffectedPoint epoint;
1969 ListBaseT<EffectorCache> *effectors;
1970
1971 /* get effectors present in the group specified by effector_weights */
1972 effectors = BKE_effectors_create(depsgraph, ob, nullptr, effector_weights, false);
1973 if (effectors) {
1974 float eff_force[3] = {0.0f, 0.0f, 0.0f};
1975 float eff_loc[3], eff_vel[3];
1976
1977 /* create dummy 'point' which represents last known position of object as result of sim
1978 */
1979 /* XXX: this can create some inaccuracies with sim position,
1980 * but is probably better than using un-simulated values? */
1981 RB_body_get_position(static_cast<rbRigidBody *>(rbo->shared->physics_object), eff_loc);
1982 RB_body_get_linear_velocity(static_cast<rbRigidBody *>(rbo->shared->physics_object),
1983 eff_vel);
1984
1985 pd_point_from_loc(scene, eff_loc, eff_vel, 0, &epoint);
1986
1987 /* Calculate net force of effectors, and apply to sim object:
1988 * - we use 'central force' since apply force requires a "relative position"
1989 * which we don't have... */
1991 effectors, nullptr, effector_weights, &epoint, eff_force, nullptr, nullptr);
1992 if (G.f & G_DEBUG) {
1993 printf("\tapplying force (%f,%f,%f) to '%s'\n",
1994 eff_force[0],
1995 eff_force[1],
1996 eff_force[2],
1997 ob->id.name + 2);
1998 }
1999 /* activate object in case it is deactivated */
2000 if (!is_zero_v3(eff_force)) {
2001 RB_body_activate(static_cast<rbRigidBody *>(rbo->shared->physics_object));
2002 }
2003 if ((rbo->flag & RBO_FLAG_DISABLED) == 0) {
2004 RB_body_apply_central_force(static_cast<rbRigidBody *>(rbo->shared->physics_object),
2005 eff_force);
2006 }
2007 }
2008 else if (G.f & G_DEBUG) {
2009 printf("\tno forces to apply to '%s'\n", ob->id.name + 2);
2010 }
2011
2012 /* cleanup */
2013 BKE_effectors_free(effectors);
2014 }
2015 /* NOTE: passive objects don't need to be updated since they don't move */
2016 }
2018}
2019
2020static void rigidbody_free_substep_data(ListBaseT<LinkData> *substep_targets)
2021{
2022 for (LinkData &link : *substep_targets) {
2023 KinematicSubstepData *data = static_cast<KinematicSubstepData *>(link.data);
2024 MEM_delete(data);
2025 }
2026
2027 substep_targets->free_no_destruct();
2028}
2029static void rigidbody_update_simulation_post_step(Depsgraph *depsgraph, RigidBodyWorld *rbw)
2030{
2031 const Scene *scene = DEG_get_input_scene(depsgraph);
2032 ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
2033 BKE_view_layer_synced_ensure(*DEG_get_bmain(depsgraph), scene, view_layer);
2034
2036 Base *base = BKE_view_layer_base_find(view_layer, ob);
2037 RigidBodyOb *rbo = ob->rigidbody_object;
2038 /* Reset kinematic state for transformed objects. */
2039 if (rbo && base && (base->flag & BASE_SELECTED) && (G.moving & G_TRANSFORM_OBJ) &&
2040 rbo->shared->physics_object)
2041 {
2042 RB_body_set_kinematic_state(static_cast<rbRigidBody *>(rbo->shared->physics_object),
2043 rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
2044 RB_body_set_mass(static_cast<rbRigidBody *>(rbo->shared->physics_object), RBO_GET_MASS(rbo));
2045 /* Deactivate passive objects so they don't interfere with deactivation of active objects. */
2046 if (rbo->type == RBO_TYPE_PASSIVE) {
2047 RB_body_deactivate(static_cast<rbRigidBody *>(rbo->shared->physics_object));
2048 }
2049 }
2050 }
2052}
2053
2054bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime)
2055{
2056 return (rbw && (rbw->flag & RBW_FLAG_MUTED) == 0 && ctime > rbw->shared->pointcache->startframe);
2057}
2058
2059void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime)
2060{
2062 /* Don't sync transforms for objects that are not affected/changed by the simulation. */
2063 return;
2064 }
2065
2066 RigidBodyOb *rbo = ob->rigidbody_object;
2067
2068 /* use rigid body transform after cache start frame if objects is not being transformed */
2069 if (BKE_rigidbody_check_sim_running(rbw, ctime) &&
2070 !(ob->base_flag & BASE_SELECTED && G.moving & G_TRANSFORM_OBJ))
2071 {
2072 float mat[4][4], size_mat[4][4], size[3];
2073
2074 normalize_qt(rbo->orn); /* RB_TODO investigate why quaternion isn't normalized at this point */
2075 quat_to_mat4(mat, rbo->orn);
2076 copy_v3_v3(mat[3], rbo->pos);
2077
2078 mat4_to_size(size, ob->object_to_world().ptr());
2079 size_to_mat4(size_mat, size);
2080 mul_m4_m4m4(mat, mat, size_mat);
2081
2082 copy_m4_m4(ob->runtime->object_to_world.ptr(), mat);
2083 }
2084 /* otherwise set rigid body transform to current obmat */
2085 else {
2086 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->object_to_world().ptr());
2087 }
2088}
2089
2091 Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
2092{
2093 bool correct_delta = BKE_rigidbody_is_affected_by_simulation(ob);
2094 RigidBodyOb *rbo = ob->rigidbody_object;
2095
2096 /* return rigid body and object to their initial states */
2097 copy_v3_v3(rbo->pos, ob->loc);
2098 copy_v3_v3(ob->loc, loc);
2099
2100 if (correct_delta) {
2101 add_v3_v3(rbo->pos, ob->dloc);
2102 }
2103
2104 if (ob->rotmode > 0) {
2105 float qt[4];
2106 eulO_to_quat(qt, ob->rot, ob->rotmode);
2107
2108 if (correct_delta) {
2109 float dquat[4];
2110 eulO_to_quat(dquat, ob->drot, ob->rotmode);
2111
2112 mul_qt_qtqt(rbo->orn, dquat, qt);
2113 }
2114 else {
2115 copy_qt_qt(rbo->orn, qt);
2116 }
2117
2118 copy_v3_v3(ob->rot, rot);
2119 }
2120 else if (ob->rotmode == ROT_MODE_AXISANGLE) {
2121 float qt[4];
2122 axis_angle_to_quat(qt, ob->rotAxis, ob->rotAngle);
2123
2124 if (correct_delta) {
2125 float dquat[4];
2126 axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
2127
2128 mul_qt_qtqt(rbo->orn, dquat, qt);
2129 }
2130 else {
2131 copy_qt_qt(rbo->orn, qt);
2132 }
2133
2134 copy_v3_v3(ob->rotAxis, rotAxis);
2135 ob->rotAngle = rotAngle;
2136 }
2137 else {
2138 if (correct_delta) {
2139 mul_qt_qtqt(rbo->orn, ob->dquat, ob->quat);
2140 }
2141 else {
2142 copy_qt_qt(rbo->orn, ob->quat);
2143 }
2144
2145 copy_qt_qt(ob->quat, quat);
2146 }
2147
2148 if (rbo->shared->physics_object) {
2149 /* allow passive objects to return to original transform */
2150 if (rbo->type == RBO_TYPE_PASSIVE) {
2151 RB_body_set_kinematic_state(static_cast<rbRigidBody *>(rbo->shared->physics_object), true);
2152 }
2154 static_cast<rbRigidBody *>(rbo->shared->physics_object), rbo->pos, rbo->orn);
2155 }
2156 /* RB_TODO update rigid body physics object's loc/rot for dynamic objects here as well
2157 * (needs to be done outside bullet's update loop). */
2158}
2159
2161{
2162 if (rbw) {
2163 rbw->shared->pointcache->flag |= PTCACHE_OUTDATED;
2164 }
2165}
2166
2167/* ------------------ */
2168
2169void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime)
2170{
2171 RigidBodyWorld *rbw = scene->rigidbody_world;
2172 PointCache *cache;
2173 PTCacheID pid;
2174 int startframe, endframe;
2175
2176 /* Avoid multiple depsgraph evaluations accessing the same shared data. */
2177 std::unique_lock lock(rbw->shared->runtime->mutex);
2178
2179 BKE_ptcache_id_from_rigidbody(&pid, nullptr, rbw);
2180 BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, nullptr);
2181 cache = rbw->shared->pointcache;
2182
2183 /* Flag cache as outdated if we don't have a world or number of objects
2184 * in the simulation has changed. */
2185 int n = 0;
2186 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->group, object) {
2187 (void)object;
2188 /* Ignore if this object is the direct child of an object with a compound shape */
2189 if (object->parent == nullptr || object->parent->rigidbody_object == nullptr ||
2190 object->parent->rigidbody_object->shape != RB_SHAPE_COMPOUND)
2191 {
2192 n++;
2193 }
2194 }
2196
2197 if (rbw->shared->runtime->physics_world == nullptr || rbw->numbodies != n) {
2198 cache->flag |= PTCACHE_OUTDATED;
2199 }
2200
2201 if (ctime == startframe + 1 && rbw->ltime == startframe) {
2202 if (cache->flag & PTCACHE_OUTDATED) {
2204 rigidbody_update_simulation(depsgraph, scene, rbw, true);
2205 BKE_ptcache_validate(cache, int(ctime));
2206 cache->last_exact = 0;
2207 cache->flag &= ~PTCACHE_REDO_NEEDED;
2208 }
2209 }
2210}
2211
2212void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime)
2213{
2214 RigidBodyWorld *rbw = scene->rigidbody_world;
2215 PointCache *cache;
2216 PTCacheID pid;
2217 int startframe, endframe;
2218
2219 BKE_ptcache_id_from_rigidbody(&pid, nullptr, rbw);
2220 BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, nullptr);
2221 cache = rbw->shared->pointcache;
2222
2223 if (ctime <= startframe) {
2224 rbw->ltime = startframe;
2225 return;
2226 }
2227 /* make sure we don't go out of cache frame range */
2228 ctime = std::min<float>(ctime, endframe);
2229
2230 /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */
2231 if (rbw->shared->runtime->physics_world == nullptr && !(cache->flag & PTCACHE_BAKED)) {
2232 return;
2233 }
2234 if (rbw->objects == nullptr) {
2235 rigidbody_update_ob_array(rbw);
2236 }
2237
2238 /* try to read from cache */
2239 /* RB_TODO deal with interpolated, old and baked results */
2240 bool can_simulate = (ctime == rbw->ltime + 1) && !(cache->flag & PTCACHE_BAKED);
2241
2242 if (BKE_ptcache_read(&pid, ctime, can_simulate) == PTCACHE_READ_EXACT) {
2243 BKE_ptcache_validate(cache, int(ctime));
2244 rbw->ltime = ctime;
2245 return;
2246 }
2247
2248 if (!DEG_is_active(depsgraph)) {
2249 /* When the depsgraph is inactive we should neither write to the cache
2250 * nor run the simulation. */
2251 return;
2252 }
2253
2254 /* advance simulation, we can only step one frame forward */
2255 if (compare_ff_relative(ctime, rbw->ltime + 1, FLT_EPSILON, 64)) {
2256 /* write cache for first frame when on second frame */
2257 if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
2258 BKE_ptcache_write(&pid, startframe);
2259 }
2260
2261 const float frame_diff = ctime - rbw->ltime;
2262 /* calculate how much time elapsed since last step in seconds */
2263 const float timestep = 1.0f / float(scene->frames_per_second()) * frame_diff * rbw->time_scale;
2264
2265 const float substep = timestep / rbw->substeps_per_frame;
2266
2267 ListBaseT<LinkData> kinematic_substep_targets = rigidbody_create_substep_data(rbw);
2268
2269 const float interp_step = 1.0f / rbw->substeps_per_frame;
2270 float cur_interp_val = interp_step;
2271
2272 /* update and validate simulation */
2273 rigidbody_update_simulation(depsgraph, scene, rbw, false);
2274
2275 for (int i = 0; i < rbw->substeps_per_frame; i++) {
2276 rigidbody_update_external_forces(depsgraph, scene, rbw);
2277 rigidbody_update_kinematic_obj_substep(&kinematic_substep_targets, cur_interp_val);
2278 RB_dworld_step_simulation(rbw->shared->runtime->physics_world, substep, 0, substep);
2279 cur_interp_val += interp_step;
2280 }
2281 rigidbody_free_substep_data(&kinematic_substep_targets);
2282
2283 rigidbody_update_simulation_post_step(depsgraph, rbw);
2284
2285 /* write cache for current frame */
2286 BKE_ptcache_validate(cache, int(ctime));
2287 BKE_ptcache_write(&pid, uint(ctime));
2288
2289 rbw->ltime = ctime;
2290 }
2291}
2292/* ************************************** */
2293
2294#else /* WITH_BULLET */
2295
2296/* stubs */
2297# if defined(__GNUC__) || defined(__clang__)
2298# pragma GCC diagnostic push
2299# pragma GCC diagnostic ignored "-Wunused-parameter"
2300# elif defined(_MSC_VER)
2301/* Suppress unreferenced formal parameter warning. */
2302# pragma warning(disable : 4100)
2303# endif
2304
2305void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild) {}
2306
2307void BKE_rigidbody_calc_volume(Object *ob, float *r_vol)
2308{
2309 if (r_vol) {
2310 *r_vol = 0.0f;
2311 }
2312}
2313void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3])
2314{
2315 zero_v3(r_center);
2316}
2318{
2319 return nullptr;
2320}
2322{
2323 return nullptr;
2324}
2327{
2328 return nullptr;
2329}
2331{
2332 return nullptr;
2333}
2335{
2336 return nullptr;
2337}
2338
2340
2342 Main *bmain, Scene *scene, Object *ob, eRigidBodyOb_Type type, ReportList *reports)
2343{
2344 BKE_report(reports, RPT_ERROR, "Compiled without Bullet physics engine");
2345 return false;
2346}
2347
2348void BKE_rigidbody_remove_object(Main *bmain, Scene *scene, Object *ob, const bool free_us) {}
2349void BKE_rigidbody_remove_constraint(Main *bmain, Scene *scene, Object *ob, const bool free_us) {}
2352 Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
2353{
2354}
2356{
2357 return false;
2358}
2360void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime) {}
2361void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime) {}
2365{
2366}
2367
2368# if defined(__GNUC__) || defined(__clang__)
2369# pragma GCC diagnostic pop
2370# endif
2371
2372#endif /* WITH_BULLET */
2373
2374/* -------------------- */
2375/* Depsgraph evaluation */
2376
2377void BKE_rigidbody_rebuild_sim(Depsgraph *depsgraph, Scene *scene)
2378{
2379 float ctime = DEG_get_ctime(depsgraph);
2380 DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime);
2381 /* rebuild sim data (i.e. after resetting to start of timeline) */
2383 BKE_rigidbody_rebuild_world(depsgraph, scene, ctime);
2384 }
2385}
2386
2387void BKE_rigidbody_eval_simulation(Depsgraph *depsgraph, Scene *scene)
2388{
2389 float ctime = DEG_get_ctime(depsgraph);
2390 DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime);
2391
2392 /* evaluate rigidbody sim */
2394 return;
2395 }
2396 BKE_rigidbody_do_simulation(depsgraph, scene, ctime);
2397}
2398
2399void BKE_rigidbody_object_sync_transforms(Depsgraph *depsgraph, Scene *scene, Object *ob)
2400{
2401 RigidBodyWorld *rbw = scene->rigidbody_world;
2402 float ctime = DEG_get_ctime(depsgraph);
2403 DEG_debug_print_eval_time(depsgraph, __func__, ob->id.name, ob, ctime);
2404 /* read values pushed into RBO from sim/cache... */
2405 BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2406}
2407
2409{
2410 func(rbw, reinterpret_cast<ID **>(&rbw->group), userdata, IDWALK_CB_USER);
2411 func(rbw, reinterpret_cast<ID **>(&rbw->constraints), userdata, IDWALK_CB_USER);
2412 func(rbw, reinterpret_cast<ID **>(&rbw->effector_weights->group), userdata, IDWALK_CB_USER);
2413
2414 if (rbw->objects) {
2415 int i;
2416 for (i = 0; i < rbw->numbodies; i++) {
2417 func(rbw, reinterpret_cast<ID **>(&rbw->objects[i]), userdata, IDWALK_CB_NOP);
2418 }
2419 }
2420}
2421
2422/* Copying Methods --------------------- */
2423
2424/* These just copy the data, clearing out references to physics objects.
2425 * Anything that uses them MUST verify that the copied object will
2426 * be added to relevant groups later...
2427 */
2428
2429static RigidBodyOb *rigidbody_copy_object(const Object *ob, const int flag)
2430{
2431 RigidBodyOb *rboN = nullptr;
2432
2433 if (ob->rigidbody_object) {
2434 const bool is_orig = (flag & LIB_ID_COPY_SET_COPIED_ON_WRITE) == 0;
2435
2436 /* just duplicate the whole struct first (to catch all the settings) */
2437 rboN = MEM_dupalloc(ob->rigidbody_object);
2438
2439 if (is_orig) {
2440 /* This is a regular copy, and not an evaluated copy for depsgraph evaluation */
2441 rboN->shared = MEM_new<RigidBodyOb_Shared>("RigidBodyOb_Shared");
2442 }
2443
2444 /* tag object as needing to be verified */
2446 }
2447
2448 /* return new copy of settings */
2449 return rboN;
2450}
2451
2452static RigidBodyCon *rigidbody_copy_constraint(const Object *ob, const int /*flag*/)
2453{
2454 RigidBodyCon *rbcN = nullptr;
2455
2456 if (ob->rigidbody_constraint) {
2457 /* Just duplicate the whole struct first (to catch all the settings). */
2458 rbcN = MEM_dupalloc(ob->rigidbody_constraint);
2459
2460 /* Tag object as needing to be verified. */
2462
2463 /* Clear out all the fields which need to be re-validated later. */
2464 rbcN->physics_constraint = nullptr;
2465 }
2466
2467 /* return new copy of settings */
2468 return rbcN;
2469}
2470
2471void BKE_rigidbody_object_copy(Main *bmain, Object *ob_dst, const Object *ob_src, const int flag)
2472{
2473 ob_dst->rigidbody_object = rigidbody_copy_object(ob_src, flag);
2474 ob_dst->rigidbody_constraint = rigidbody_copy_constraint(ob_src, flag);
2475
2477 return;
2478 }
2479
2480 /* We have to ensure that duplicated object ends up in relevant rigidbody collections...
2481 * Otherwise duplicating the RB data itself is meaningless. */
2482 for (Scene &scene : bmain->scenes) {
2483 RigidBodyWorld *rigidbody_world = scene.rigidbody_world;
2484
2485 if (rigidbody_world != nullptr) {
2486 bool need_objects_update = false;
2487 bool need_constraints_update = false;
2488
2489 if (ob_dst->rigidbody_object) {
2490 if (BKE_collection_has_object(rigidbody_world->group, ob_src)) {
2491 BKE_collection_object_add(bmain, rigidbody_world->group, ob_dst);
2492 need_objects_update = true;
2493 }
2494 }
2495 if (ob_dst->rigidbody_constraint) {
2496 if (BKE_collection_has_object(rigidbody_world->constraints, ob_src)) {
2497 BKE_collection_object_add(bmain, rigidbody_world->constraints, ob_dst);
2498 need_constraints_update = true;
2499 }
2500 }
2501
2502 if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0 &&
2503 (need_objects_update || need_constraints_update))
2504 {
2505 BKE_rigidbody_cache_reset(rigidbody_world);
2506
2508 if (need_objects_update) {
2509 DEG_id_tag_update(&rigidbody_world->group->id, ID_RECALC_SYNC_TO_EVAL);
2510 }
2511 if (need_constraints_update) {
2513 }
2515 }
2516 }
2517 }
2518}
2519
2520} // namespace blender
#define FOREACH_COLLECTION_OBJECT_RECURSIVE_END
#define FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(_collection, _object)
#define G_MAIN
General operations, lookup, etc. for blender objects.
#define PTCACHE_RESET_OUTDATED
#define PTCACHE_READ_EXACT
API for Blender-side Rigid Body stuff.
#define RBO_GET_MASS(rbo)
#define RBO_GET_MARGIN(rbo)
#define M_PI
#define M_PI_4
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
ID and Library types, which are fundamental for SDNA.
#define ID_NEW_REMAP(a)
Definition DNA_ID.h:761
#define ID_REAL_USERS(id)
Definition DNA_ID.h:679
Object groups, one object can be in many groups at once.
Object is a sort of wrapper for general info.
Types and defines for representing Rigid Body entities.
Read Blender memory allocation and freeing.
Rigid Body API for interfacing with external Physics Engines.
#define RB_LIMIT_LIN_Y
Definition RBI_api.h:317
struct rbCollisionShape rbCollisionShape
Definition RBI_api.h:38
#define RB_LIMIT_LIN_X
Definition RBI_api.h:316
struct rbMeshData rbMeshData
Definition RBI_api.h:41
#define RB_LIMIT_LIN_Z
Definition RBI_api.h:318
struct rbRigidBody rbRigidBody
Definition RBI_api.h:35
#define RB_LIMIT_ANG_X
Definition RBI_api.h:319
#define RB_LIMIT_ANG_Z
Definition RBI_api.h:321
#define RB_LIMIT_ANG_Y
Definition RBI_api.h:320
struct rbConstraint rbConstraint
Definition RBI_api.h:44
volatile int lock
#define BLI_assert(a)
#define UNPACK3(a)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
constexpr const T * data() const
Definition BLI_span.hh:219
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr bool is_empty() const
Definition BLI_span.hh:264
#define rot(x, k)
#define FLT_MAX
#define FLT_EPSILON
float3x3 scale(float3x3 mat, float2 scale)
#define LOG(level)
Definition log.h:97
void free(Subdiv *subdiv)
Definition subdiv.cc:192
int size(const AssetLibraryReference *library_reference)
BMesh Iterators.
static void RB_dworld_remove_constraint(void *, void *)
Definition rigidbody.cc:78
int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old)
void mat4_to_loc_quat(float loc[3], float quat[4], const float wmat[4][4])
void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, struct Scene *scene, float ctime)
void BKE_rigidbody_calc_volume(struct Object *ob, float *r_vol)
MINLINE int compare_ff_relative(float a, float b, float max_diff, int max_ulps)
void BKE_rigidbody_aftertrans_update(struct Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
void BKE_rigidbody_validate_sim_world(struct Scene *scene, struct RigidBodyWorld *rbw, bool rebuild)
bool DEG_is_active(const Depsgraph *depsgraph)
Definition depsgraph.cc:324
static void RB_body_delete(void *)
Definition rigidbody.cc:81
void id_us_plus(ID *id)
Definition lib_id.cc:433
void BKE_rigidbody_calc_center_of_mass(struct Object *ob, float r_center[3])
void BKE_rigidbody_world_init_runtime(struct RigidBodyWorld *rbw)
Definition rigidbody.cc:98
rbDynamicsWorld * BKE_rigidbody_world_physics(struct RigidBodyWorld *rbw)
Definition rigidbody.cc:105
bool BKE_rigidbody_check_sim_running(struct RigidBodyWorld *rbw, float ctime)
int BKE_ptcache_id_reset(struct Scene *scene, PTCacheID *pid, int mode)
void(*) RigidbodyWorldIDFunc(struct RigidBodyWorld *rbw, struct ID **idpoin, void *userdata, LibraryForeachIDCallbackFlag cb_flag)
float normalize_qt(float q[4])
void DEG_debug_print_eval_time(Depsgraph *depsgraph, const char *function_name, const char *object_name, const void *object_address, float time)
static void RB_dworld_remove_body(void *, void *)
Definition rigidbody.cc:79
void axis_angle_to_quat(float r[4], const float axis[3], float angle)
struct RigidBodyOb * BKE_rigidbody_create_object(struct Scene *scene, struct Object *ob, eRigidBodyOb_Type type)
void BKE_effectors_apply(ListBaseT< EffectorCache > *effectors, ListBaseT< ColliderCache > *colliders, struct EffectorWeights *weights, struct EffectedPoint *point, float *force, float *wind_force, float *impulse)
Definition effect.cc:1134
void mul_m4_m4m4(float R[4][4], const float A[4][4], const float B[4][4])
void mul_qt_qtqt(float q[4], const float a[4], const float b[4])
@ LIB_ID_CREATE_NO_USER_REFCOUNT
@ LIB_ID_COPY_RIGID_BODY_NO_COLLECTION_HANDLING
@ LIB_ID_COPY_SET_COPIED_ON_WRITE
@ LIB_ID_CREATE_NO_DEG_TAG
@ LIB_ID_COPY_CACHES
@ LIB_ID_CREATE_NO_MAIN
void BKE_ptcache_id_from_rigidbody(PTCacheID *pid, struct Object *ob, struct RigidBodyWorld *rbw)
MINLINE void mul_v3_fl(float r[3], float f)
bool BKE_collection_has_object(Collection *collection, const Object *ob)
static void RB_shape_delete(void *)
Definition rigidbody.cc:82
static RigidBodyOb * rigidbody_copy_object(const Object *ob, const int flag)
Global G
Definition blender.cc:57
void size_to_mat4(float R[4][4], const float size[3])
ViewLayer * DEG_get_input_view_layer(const Depsgraph *graph)
VecBase< int32_t, 3 > int3
struct RigidBodyCon * BKE_rigidbody_create_constraint(struct Scene *scene, struct Object *ob, eRigidBodyCon_Type type)
void * MEM_new_zeroed(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
void BKE_rigidbody_object_copy(struct Main *bmain, struct Object *ob_dst, const struct Object *ob_src, int flag)
void BKE_rigidbody_ensure_local_object(struct Main *bmain, struct Object *ob)
int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra)
void BKE_rigidbody_cache_reset(struct RigidBodyWorld *rbw)
void copy_qt_qt(float q[4], const float a[4])
Main * DEG_get_bmain(const Depsgraph *graph)
void DEG_id_tag_update(ID *id, unsigned int flags)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
BMesh const char void * data
void interp_qt_qtqt(float q[4], const float a[4], const float b[4], float t)
void BKE_rigidbody_object_sync_transforms(struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob)
static void RB_constraint_delete(void *)
Definition rigidbody.cc:83
void BKE_object_matrix_local_get(Object *ob, float r_mat[4][4])
Definition object.cc:3136
void BKE_rigidbody_objects_collection_validate(struct Main *bmain, struct Scene *scene, struct RigidBodyWorld *rbw)
void BKE_object_dimensions_get(const Object *ob, float r_vec[3])
Definition object.cc:3799
bool BKE_view_layer_synced_ensure(const Main &bmain, const Scene *scene, ViewLayer *view_layer)
LinkData * BLI_genericNodeN(void *data)
Definition listbase.cc:936
void BKE_ptcache_id_time(PTCacheID *pid, struct Scene *scene, float cfra, int *startframe, int *endframe, float *timescale)
bool BKE_collection_object_add(Main *bmain, Collection *collection, Object *ob)
void interp_v3_v3v3(float r[3], const float a[3], const float b[3], float t)
bool BKE_rigidbody_add_object(struct Main *bmain, struct Scene *scene, struct Object *ob, eRigidBodyOb_Type type, struct ReportList *reports)
void BKE_rigidbody_free_object(struct Object *ob, struct RigidBodyWorld *rbw)
Definition rigidbody.cc:166
struct RigidBodyWorld * BKE_rigidbody_world_copy(struct RigidBodyWorld *rbw, int flag)
void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, struct Scene *scene, float ctime)
MINLINE void zero_v3(float r[3])
struct RigidBodyWorld * BKE_rigidbody_create_world(struct Scene *scene)
void BKE_rigidbody_main_collection_object_add(struct Main *bmain, struct Collection *collection, struct Object *object)
static void RB_dworld_delete(void *)
Definition rigidbody.cc:80
void BKE_mesh_calc_volume(const float(*vert_positions)[3], int mverts_num, const int3 *corner_tris, int corner_tris_num, const int *corner_verts, float *r_volume, float r_center[3])
void mat4_to_size(float size[3], const float M[4][4])
static RigidBodyCon * rigidbody_copy_constraint(const Object *ob, const int)
void BKE_ptcache_validate(struct PointCache *cache, int framenr)
MINLINE void add_v3_v3(float r[3], const float a[3])
void BKE_rigidbody_remove_object(struct Main *bmain, struct Scene *scene, struct Object *ob, bool free_us)
void pd_point_from_loc(struct Scene *scene, float *loc, float *vel, int index, struct EffectedPoint *point)
Definition effect.cc:424
void BKE_ptcache_free_list(ListBaseT< PointCache > *ptcaches)
void BKE_rigidbody_free_world(struct Scene *scene)
Definition rigidbody.cc:110
bool BKE_collection_object_remove(Main *bmain, Collection *collection, Object *ob, bool free_us)
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
MINLINE bool compare_size_v3v3(const float v1[3], const float v2[3], float limit) ATTR_WARN_UNUSED_RESULT
void eulO_to_quat(float q[4], const float e[3], short order)
std::mutex Mutex
Definition BLI_mutex.hh:51
ListBaseT< EffectorCache > * BKE_effectors_create(struct Depsgraph *depsgraph, struct Object *ob_src, struct ParticleSystem *psys_src, struct EffectorWeights *weights, bool use_rotation)
Definition effect.cc:316
@ ID_RECALC_TRANSFORM
Definition DNA_ID.h:1054
@ ID_RECALC_SYNC_TO_EVAL
Definition DNA_ID.h:1118
@ RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS
bool BKE_scene_object_find(const Main &bmain, Scene *scene, Object *ob)
Definition scene.cc:2209
Scene * DEG_get_input_scene(const Depsgraph *graph)
void BKE_rigidbody_remove_constraint(struct Main *bmain, struct Scene *scene, struct Object *ob, bool free_us)
Base * BKE_view_layer_base_find(ViewLayer *view_layer, Object *ob)
@ ID_TAG_COPIED_ON_EVAL
Definition DNA_ID.h:1000
void BKE_rigidbody_constraints_collection_validate(struct Scene *scene, struct RigidBodyWorld *rbw)
struct PointCache * BKE_ptcache_add(ListBaseT< PointCache > *ptcaches)
struct PointCache * BKE_ptcache_copy_list(ListBaseT< PointCache > *ptcaches_new, const ListBaseT< PointCache > *ptcaches_old, int flag)
@ G_TRANSFORM_OBJ
void DEG_relations_tag_update(Main *bmain)
void BKE_rigidbody_eval_simulation(struct Depsgraph *depsgraph, struct Scene *scene)
void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw)
std::optional< Bounds< float3 > > BKE_object_boundbox_get(const Object *ob)
Definition object.cc:3726
MINLINE void copy_v4_v4(float r[4], const float a[4])
void BKE_rigidbody_sync_transforms(struct RigidBodyWorld *rbw, struct Object *ob, float ctime)
bool BKE_rigidbody_is_affected_by_simulation(struct Object *ob)
Definition rigidbody.cc:237
void copy_m4_m4(float m1[4][4], const float m2[4][4])
float mat4_to_volume_scale(const float mat[4][4])
struct RigidBodyWorld * BKE_rigidbody_get_world(struct Scene *scene)
struct EffectorWeights * BKE_effector_add_weights(struct Collection *collection)
Definition effect.cc:63
float DEG_get_ctime(const Depsgraph *graph)
bool BKE_scene_check_rigidbody_active(const Scene *scene)
Definition scene.cc:3135
void mat4_decompose(float loc[3], float quat[4], float size[3], const float wmat[4][4])
MINLINE bool is_zero_v3(const float v[3]) ATTR_WARN_UNUSED_RESULT
void BKE_rigidbody_rebuild_sim(struct Depsgraph *depsgraph, struct Scene *scene)
void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata)
void BKE_effectors_free(ListBaseT< EffectorCache > *lb)
Definition effect.cc:371
const Mesh * BKE_object_get_mesh_deform_eval(const Object *object)
Definition object.cc:4519
void BKE_rigidbody_free_constraint(struct Object *ob)
Definition rigidbody.cc:217
void quat_to_mat4(float m[4][4], const float q[4])
Mesh * BKE_object_get_evaluated_mesh(const Object *object_eval)
Definition object.cc:4436
Collection * BKE_collection_add(Main *bmain, Collection *collection_parent, const char *name_custom)
#define fabsf
void RB_constraint_set_max_impulse_motor(rbConstraint *con, float max_impulse_lin, float max_impulse_ang)
void RB_dworld_set_solver_iterations(rbDynamicsWorld *world, int num_solver_iterations)
void RB_dworld_add_body(rbDynamicsWorld *world, rbRigidBody *object, int col_groups)
void RB_dworld_set_split_impulse(rbDynamicsWorld *world, int split_impulse)
rbCollisionShape * RB_shape_new_compound()
void RB_constraint_set_stiffness_6dof_spring(rbConstraint *con, int axis, float stiffness)
void RB_body_set_restitution(rbRigidBody *object, float value)
rbCollisionShape * RB_shape_new_box(float x, float y, float z)
void RB_body_set_friction(rbRigidBody *object, float value)
void RB_body_set_mass(rbRigidBody *object, float value)
rbConstraint * RB_constraint_new_fixed(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
void RB_body_set_activation_state(rbRigidBody *object, int use_deactivation)
rbConstraint * RB_constraint_new_6dof_spring(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
void RB_dworld_add_constraint(rbDynamicsWorld *world, rbConstraint *con, int disable_collisions)
void RB_constraint_set_damping_6dof_spring(rbConstraint *con, int axis, float damping)
rbCollisionShape * RB_shape_new_gimpact_mesh(rbMeshData *mesh)
rbCollisionShape * RB_shape_new_trimesh(rbMeshData *mesh)
rbConstraint * RB_constraint_new_slider(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
void RB_body_get_linear_velocity(rbRigidBody *object, float v_out[3])
void RB_constraint_set_enabled(rbConstraint *con, int enabled)
void RB_constraint_set_stiffness_6dof_spring2(rbConstraint *con, int axis, float stiffness)
void RB_constraint_set_equilibrium_6dof_spring(rbConstraint *con)
void RB_body_apply_central_force(rbRigidBody *object, const float v_in[3])
void RB_constraint_set_limits_slider(rbConstraint *con, float lower, float upper)
rbConstraint * RB_constraint_new_piston(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
void RB_constraint_set_breaking_threshold(rbConstraint *con, float threshold)
void RB_constraint_set_enable_motor(rbConstraint *con, int enable_lin, int enable_ang)
void RB_body_get_orientation(rbRigidBody *object, float v_out[4])
void RB_dworld_set_gravity(rbDynamicsWorld *world, const float g_in[3])
void RB_compound_add_child_shape(rbCollisionShape *parentShape, rbCollisionShape *shape, const float loc[3], const float rot[4])
rbDynamicsWorld * RB_dworld_new(const float gravity[3])
void RB_trimesh_add_triangle_indices(rbMeshData *mesh, int num, int index0, int index1, int index2)
rbMeshData * RB_trimesh_data_new(int num_tris, int num_verts)
void RB_trimesh_add_vertices(rbMeshData *mesh, float *vertices, int num_verts, int vert_stride)
void RB_constraint_set_limits_6dof_spring2(rbConstraint *con, int axis, float lower, float upper)
rbConstraint * RB_constraint_new_6dof(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
void RB_constraint_set_solver_iterations(rbConstraint *con, int num_solver_iterations)
rbCollisionShape * RB_shape_new_cylinder(float radius, float height)
void RB_constraint_set_damping_6dof_spring2(rbConstraint *con, int axis, float damping)
void RB_body_set_collision_shape(rbRigidBody *object, rbCollisionShape *shape)
void RB_body_set_scale(rbRigidBody *object, const float scale[3])
void RB_body_set_damping(rbRigidBody *object, float linear, float angular)
void RB_shape_trimesh_update(rbCollisionShape *shape, const float *vertices, int num_verts, int vert_stride, const float min[3], const float max[3])
void RB_constraint_set_spring_6dof_spring(rbConstraint *con, int axis, int enable)
void RB_shape_set_margin(rbCollisionShape *shape, float value)
rbRigidBody * RB_body_new(rbCollisionShape *shape, const float loc[3], const float rot[4])
void RB_body_deactivate(rbRigidBody *object)
void RB_body_set_kinematic_state(rbRigidBody *object, int kinematic)
rbConstraint * RB_constraint_new_6dof_spring2(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
rbConstraint * RB_constraint_new_hinge(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
void RB_trimesh_finish(rbMeshData *mesh)
void RB_body_get_position(rbRigidBody *object, float v_out[3])
rbCollisionShape * RB_shape_new_convex_hull(const float *verts, int stride, int count, float margin, bool *can_embed)
rbConstraint * RB_constraint_new_point(const float pivot[3], rbRigidBody *rb1, rbRigidBody *rb2)
rbCollisionShape * RB_shape_new_cone(float radius, float height)
void RB_constraint_set_limits_piston(rbConstraint *con, float lin_lower, float lin_upper, float ang_lower, float ang_upper)
void RB_constraint_set_limits_6dof(rbConstraint *con, int axis, float lower, float upper)
void RB_body_set_loc_rot(rbRigidBody *object, const float loc[3], const float rot[4])
void RB_constraint_set_limits_hinge(rbConstraint *con, float lower, float upper)
void RB_constraint_set_target_velocity_motor(rbConstraint *con, float velocity_lin, float velocity_ang)
rbCollisionShape * RB_shape_new_sphere(float radius)
void RB_body_activate(rbRigidBody *object)
void RB_body_set_linear_factor(rbRigidBody *object, float x, float y, float z)
void RB_body_set_sleep_thresh(rbRigidBody *object, float linear, float angular)
void RB_dworld_step_simulation(rbDynamicsWorld *world, float timeStep, int maxSubSteps, float timeSubStep)
void RB_constraint_set_equilibrium_6dof_spring2(rbConstraint *con)
rbCollisionShape * RB_shape_new_capsule(float radius, float height)
rbConstraint * RB_constraint_new_motor(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2)
void RB_body_get_scale(rbRigidBody *object, float v_out[3])
void RB_constraint_set_spring_6dof_spring2(rbConstraint *con, int axis, int enable)
void RB_body_set_angular_factor(rbRigidBody *object, float x, float y, float z)
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
const NodeType * type
Definition graph/node.h:179
ustring name
Definition graph/node.h:178
char name[258]
Definition DNA_ID.h:433
ListBaseT< Scene > scenes
Definition BKE_main.hh:386
struct Object * parent
struct RigidBodyOb * rigidbody_object
struct RigidBodyCon * rigidbody_constraint
struct RigidBodyOb_Shared * shared
rbDynamicsWorld * physics_world
Definition rigidbody.cc:87
struct RigidBodyWorld_Runtime * runtime
struct Collection * constraints
struct EffectorWeights * effector_weights
struct RigidBodyWorld_Shared * shared
struct RigidBodyWorld * rigidbody_world