Fix crash Cycles rendering with --debug-value 256.
[blender.git] / source / blender / blenkernel / intern / rigidbody.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2013 Blender Foundation
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joshua Leung, Sergej Reich
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file rigidbody.c
29  *  \ingroup blenkernel
30  *  \brief Blender-side interface and methods for dealing with Rigid Body simulations
31  */
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stddef.h>
36 #include <float.h>
37 #include <math.h>
38 #include <limits.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "BLI_blenlib.h"
43 #include "BLI_math.h"
44
45 #ifdef WITH_BULLET
46 #  include "RBI_api.h"
47 #endif
48
49 #include "DNA_ID.h"
50 #include "DNA_group_types.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_object_types.h"
54 #include "DNA_object_force_types.h"
55 #include "DNA_rigidbody_types.h"
56 #include "DNA_scene_types.h"
57
58 #include "BKE_collection.h"
59 #include "BKE_effect.h"
60 #include "BKE_global.h"
61 #include "BKE_layer.h"
62 #include "BKE_library.h"
63 #include "BKE_library_query.h"
64 #include "BKE_mesh.h"
65 #include "BKE_mesh_runtime.h"
66 #include "BKE_object.h"
67 #include "BKE_pointcache.h"
68 #include "BKE_rigidbody.h"
69 #include "BKE_scene.h"
70
71 #include "DEG_depsgraph.h"
72 #include "DEG_depsgraph_query.h"
73
74 /* ************************************** */
75 /* Memory Management */
76
77 /* Freeing Methods --------------------- */
78
79 #ifdef WITH_BULLET
80 static void rigidbody_update_ob_array(RigidBodyWorld *rbw);
81
82 #else
83 static void RB_dworld_remove_constraint(void *UNUSED(world), void *UNUSED(con)) {}
84 static void RB_dworld_remove_body(void *UNUSED(world), void *UNUSED(body)) {}
85 static void RB_dworld_delete(void *UNUSED(world)) {}
86 static void RB_body_delete(void *UNUSED(body)) {}
87 static void RB_shape_delete(void *UNUSED(shape)) {}
88 static void RB_constraint_delete(void *UNUSED(con)) {}
89
90 #endif
91
92 /* Free rigidbody world */
93 void BKE_rigidbody_free_world(Scene *scene)
94 {
95         bool is_orig = (scene->id.tag & LIB_TAG_COPIED_ON_WRITE) == 0;
96         RigidBodyWorld *rbw = scene->rigidbody_world;
97         scene->rigidbody_world = NULL;
98
99         /* sanity check */
100         if (!rbw)
101                 return;
102
103         if (is_orig && rbw->shared->physics_world) {
104                 /* free physics references, we assume that all physics objects in will have been added to the world */
105                 if (rbw->constraints) {
106                         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, object)
107                         {
108                                 if (object->rigidbody_constraint) {
109                                         RigidBodyCon *rbc = object->rigidbody_constraint;
110                                         if (rbc->physics_constraint) {
111                                                 RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
112                                         }
113                                 }
114                         }
115                         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
116                 }
117
118                 if (rbw->group) {
119                         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
120                         {
121                                 BKE_rigidbody_free_object(object, rbw);
122                         }
123                         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
124                 }
125                 /* free dynamics world */
126                 RB_dworld_delete(rbw->shared->physics_world);
127         }
128         if (rbw->objects)
129                 free(rbw->objects);
130
131         if (is_orig) {
132                 /* free cache */
133                 BKE_ptcache_free_list(&(rbw->shared->ptcaches));
134                 rbw->shared->pointcache = NULL;
135
136                 MEM_freeN(rbw->shared);
137         }
138
139         /* free effector weights */
140         if (rbw->effector_weights)
141                 MEM_freeN(rbw->effector_weights);
142
143         /* free rigidbody world itself */
144         MEM_freeN(rbw);
145 }
146
147 /* Free RigidBody settings and sim instances */
148 void BKE_rigidbody_free_object(Object *ob, RigidBodyWorld *rbw)
149 {
150         bool is_orig = (ob->id.tag & LIB_TAG_COPIED_ON_WRITE) == 0;
151         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
152
153         /* sanity check */
154         if (rbo == NULL)
155                 return;
156
157         /* free physics references */
158         if (is_orig) {
159                 if (rbo->shared->physics_object) {
160                         BLI_assert(rbw);
161                         if (rbw) {
162                                 /* We can only remove the body from the world if the world is known.
163                                  * The world is generally only unknown if it's an evaluated copy of
164                                  * an object that's being freed, in which case this code isn't run anyway. */
165                                 RB_dworld_remove_body(rbw->shared->physics_world, rbo->shared->physics_object);
166                         }
167
168                         RB_body_delete(rbo->shared->physics_object);
169                         rbo->shared->physics_object = NULL;
170                 }
171
172                 if (rbo->shared->physics_shape) {
173                         RB_shape_delete(rbo->shared->physics_shape);
174                         rbo->shared->physics_shape = NULL;
175                 }
176
177                 MEM_freeN(rbo->shared);
178         }
179
180         /* free data itself */
181         MEM_freeN(rbo);
182         ob->rigidbody_object = NULL;
183 }
184
185 /* Free RigidBody constraint and sim instance */
186 void BKE_rigidbody_free_constraint(Object *ob)
187 {
188         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
189
190         /* sanity check */
191         if (rbc == NULL)
192                 return;
193
194         /* free physics reference */
195         if (rbc->physics_constraint) {
196                 RB_constraint_delete(rbc->physics_constraint);
197                 rbc->physics_constraint = NULL;
198         }
199
200         /* free data itself */
201         MEM_freeN(rbc);
202         ob->rigidbody_constraint = NULL;
203 }
204
205 #ifdef WITH_BULLET
206
207 /* Copying Methods --------------------- */
208
209 /* These just copy the data, clearing out references to physics objects.
210  * Anything that uses them MUST verify that the copied object will
211  * be added to relevant groups later...
212  */
213
214 RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob, const int flag)
215 {
216         RigidBodyOb *rboN = NULL;
217
218         if (ob->rigidbody_object) {
219                 /* just duplicate the whole struct first (to catch all the settings) */
220                 rboN = MEM_dupallocN(ob->rigidbody_object);
221
222                 if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
223                         /* This is a regular copy, and not a CoW copy for depsgraph evaluation */
224                         rboN->shared = MEM_callocN(sizeof(*rboN->shared), "RigidBodyOb_Shared");
225                 }
226
227                 /* tag object as needing to be verified */
228                 rboN->flag |= RBO_FLAG_NEEDS_VALIDATE;
229         }
230
231         /* return new copy of settings */
232         return rboN;
233 }
234
235 RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int UNUSED(flag))
236 {
237         RigidBodyCon *rbcN = NULL;
238
239         if (ob->rigidbody_constraint) {
240                 /* just duplicate the whole struct first (to catch all the settings) */
241                 rbcN = MEM_dupallocN(ob->rigidbody_constraint);
242
243                 /* tag object as needing to be verified */
244                 rbcN->flag |= RBC_FLAG_NEEDS_VALIDATE;
245
246                 /* clear out all the fields which need to be revalidated later */
247                 rbcN->physics_constraint = NULL;
248         }
249
250         /* return new copy of settings */
251         return rbcN;
252 }
253
254 /* ************************************** */
255 /* Setup Utilities - Validate Sim Instances */
256
257 /* get the appropriate evaluated mesh based on rigid body mesh source */
258 static Mesh *rigidbody_get_mesh(Object *ob)
259 {
260         switch (ob->rigidbody_object->mesh_source) {
261                 case RBO_MESH_DEFORM:
262                         return ob->runtime.mesh_deform_eval;
263                 case RBO_MESH_FINAL:
264                         return ob->runtime.mesh_eval;
265                 case RBO_MESH_BASE:
266                         /* This mesh may be used for computing looptris, which should be done
267                          * on the original; otherwise every time the CoW is recreated it will
268                          * have to be recomputed. */
269                         BLI_assert(ob->rigidbody_object->mesh_source == RBO_MESH_BASE);
270                         return ob->runtime.mesh_orig;
271         }
272
273         /* Just return something sensible so that at least Blender won't crash. */
274         BLI_assert(!"Unknown mesh source");
275         return ob->runtime.mesh_eval;
276 }
277
278 /* create collision shape of mesh - convex hull */
279 static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, float margin, bool *can_embed)
280 {
281         rbCollisionShape *shape = NULL;
282         Mesh *mesh = NULL;
283         MVert *mvert = NULL;
284         int totvert = 0;
285
286         if (ob->type == OB_MESH && ob->data) {
287                 mesh = rigidbody_get_mesh(ob);
288                 mvert   = (mesh) ? mesh->mvert : NULL;
289                 totvert = (mesh) ? mesh->totvert : 0;
290         }
291         else {
292                 printf("ERROR: cannot make Convex Hull collision shape for non-Mesh object\n");
293         }
294
295         if (totvert) {
296                 shape = RB_shape_new_convex_hull((float *)mvert, sizeof(MVert), totvert, margin, can_embed);
297         }
298         else {
299                 printf("ERROR: no vertices to define Convex Hull collision shape with\n");
300         }
301
302         return shape;
303 }
304
305 /* create collision shape of mesh - triangulated mesh
306  * returns NULL if creation fails.
307  */
308 static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob)
309 {
310         rbCollisionShape *shape = NULL;
311
312         if (ob->type == OB_MESH) {
313                 Mesh *mesh = NULL;
314                 MVert *mvert;
315                 const MLoopTri *looptri;
316                 int totvert;
317                 int tottri;
318                 const MLoop *mloop;
319
320                 mesh = rigidbody_get_mesh(ob);
321
322                 /* ensure mesh validity, then grab data */
323                 if (mesh == NULL)
324                         return NULL;
325
326                 mvert   = mesh->mvert;
327                 totvert = mesh->totvert;
328                 looptri = BKE_mesh_runtime_looptri_ensure(mesh);
329                 tottri = mesh->runtime.looptris.len;
330                 mloop = mesh->mloop;
331
332                 /* sanity checking - potential case when no data will be present */
333                 if ((totvert == 0) || (tottri == 0)) {
334                         printf("WARNING: no geometry data converted for Mesh Collision Shape (ob = %s)\n", ob->id.name + 2);
335                 }
336                 else {
337                         rbMeshData *mdata;
338                         int i;
339
340                         /* init mesh data for collision shape */
341                         mdata = RB_trimesh_data_new(tottri, totvert);
342
343                         RB_trimesh_add_vertices(mdata, (float *)mvert, totvert, sizeof(MVert));
344
345                         /* loop over all faces, adding them as triangles to the collision shape
346                          * (so for some faces, more than triangle will get added)
347                          */
348                         if (mvert && looptri) {
349                                 for (i = 0; i < tottri; i++) {
350                                         /* add first triangle - verts 1,2,3 */
351                                         const MLoopTri *lt = &looptri[i];
352                                         int vtri[3];
353
354                                         vtri[0] = mloop[lt->tri[0]].v;
355                                         vtri[1] = mloop[lt->tri[1]].v;
356                                         vtri[2] = mloop[lt->tri[2]].v;
357
358                                         RB_trimesh_add_triangle_indices(mdata, i, UNPACK3(vtri));
359                                 }
360                         }
361
362                         RB_trimesh_finish(mdata);
363
364                         /* construct collision shape
365                          *
366                          * These have been chosen to get better speed/accuracy tradeoffs with regards
367                          * to limitations of each:
368                          *    - BVH-Triangle Mesh: for passive objects only. Despite having greater
369                          *                         speed/accuracy, they cannot be used for moving objects.
370                          *    - GImpact Mesh:      for active objects. These are slower and less stable,
371                          *                         but are more flexible for general usage.
372                          */
373                         if (ob->rigidbody_object->type == RBO_TYPE_PASSIVE) {
374                                 shape = RB_shape_new_trimesh(mdata);
375                         }
376                         else {
377                                 shape = RB_shape_new_gimpact_mesh(mdata);
378                         }
379                 }
380         }
381         else {
382                 printf("ERROR: cannot make Triangular Mesh collision shape for non-Mesh object\n");
383         }
384
385         return shape;
386 }
387
388 /* Create new physics sim collision shape for object and store it,
389  * or remove the existing one first and replace...
390  */
391 static void rigidbody_validate_sim_shape(Object *ob, bool rebuild)
392 {
393         RigidBodyOb *rbo = ob->rigidbody_object;
394         rbCollisionShape *new_shape = NULL;
395         BoundBox *bb = NULL;
396         float size[3] = {1.0f, 1.0f, 1.0f};
397         float radius = 1.0f;
398         float height = 1.0f;
399         float capsule_height;
400         float hull_margin = 0.0f;
401         bool can_embed = true;
402         bool has_volume;
403
404         /* sanity check */
405         if (rbo == NULL)
406                 return;
407
408         /* don't create a new shape if we already have one and don't want to rebuild it */
409         if (rbo->shared->physics_shape && !rebuild)
410                 return;
411
412         /* if automatically determining dimensions, use the Object's boundbox
413          *      - assume that all quadrics are standing upright on local z-axis
414          *      - assume even distribution of mass around the Object's pivot
415          *        (i.e. Object pivot is centralized in boundbox)
416          */
417         // XXX: all dimensions are auto-determined now... later can add stored settings for this
418         /* get object dimensions without scaling */
419         bb = BKE_object_boundbox_get(ob);
420         if (bb) {
421                 size[0] = (bb->vec[4][0] - bb->vec[0][0]);
422                 size[1] = (bb->vec[2][1] - bb->vec[0][1]);
423                 size[2] = (bb->vec[1][2] - bb->vec[0][2]);
424         }
425         mul_v3_fl(size, 0.5f);
426
427         if (ELEM(rbo->shape, RB_SHAPE_CAPSULE, RB_SHAPE_CYLINDER, RB_SHAPE_CONE)) {
428                 /* take radius as largest x/y dimension, and height as z-dimension */
429                 radius = MAX2(size[0], size[1]);
430                 height = size[2];
431         }
432         else if (rbo->shape == RB_SHAPE_SPHERE) {
433                 /* take radius to the largest dimension to try and encompass everything */
434                 radius = MAX3(size[0], size[1], size[2]);
435         }
436
437         /* create new shape */
438         switch (rbo->shape) {
439                 case RB_SHAPE_BOX:
440                         new_shape = RB_shape_new_box(size[0], size[1], size[2]);
441                         break;
442
443                 case RB_SHAPE_SPHERE:
444                         new_shape = RB_shape_new_sphere(radius);
445                         break;
446
447                 case RB_SHAPE_CAPSULE:
448                         capsule_height = (height - radius) * 2.0f;
449                         new_shape = RB_shape_new_capsule(radius, (capsule_height > 0.0f) ? capsule_height : 0.0f);
450                         break;
451                 case RB_SHAPE_CYLINDER:
452                         new_shape = RB_shape_new_cylinder(radius, height);
453                         break;
454                 case RB_SHAPE_CONE:
455                         new_shape = RB_shape_new_cone(radius, height * 2.0f);
456                         break;
457
458                 case RB_SHAPE_CONVEXH:
459                         /* try to emged collision margin */
460                         has_volume = (MIN3(size[0], size[1], size[2]) > 0.0f);
461
462                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && has_volume)
463                                 hull_margin = 0.04f;
464                         new_shape = rigidbody_get_shape_convexhull_from_mesh(ob, hull_margin, &can_embed);
465                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN))
466                                 rbo->margin = (can_embed && has_volume) ? 0.04f : 0.0f;  /* RB_TODO ideally we shouldn't directly change the margin here */
467                         break;
468                 case RB_SHAPE_TRIMESH:
469                         new_shape = rigidbody_get_shape_trimesh_from_mesh(ob);
470                         break;
471         }
472         /* use box shape if we can't fall back to old shape */
473         if (new_shape == NULL && rbo->shared->physics_shape == NULL) {
474                 new_shape = RB_shape_new_box(size[0], size[1], size[2]);
475         }
476         /* assign new collision shape if creation was successful */
477         if (new_shape) {
478                 if (rbo->shared->physics_shape) {
479                         RB_shape_delete(rbo->shared->physics_shape);
480                 }
481                 rbo->shared->physics_shape = new_shape;
482                 RB_shape_set_margin(rbo->shared->physics_shape, RBO_GET_MARGIN(rbo));
483         }
484 }
485
486 /* --------------------- */
487
488 /* helper function to calculate volume of rigidbody object */
489 // TODO: allow a parameter to specify method used to calculate this?
490 void BKE_rigidbody_calc_volume(Object *ob, float *r_vol)
491 {
492         RigidBodyOb *rbo = ob->rigidbody_object;
493
494         float size[3]  = {1.0f, 1.0f, 1.0f};
495         float radius = 1.0f;
496         float height = 1.0f;
497
498         float volume = 0.0f;
499
500         /* if automatically determining dimensions, use the Object's boundbox
501          *      - assume that all quadrics are standing upright on local z-axis
502          *      - assume even distribution of mass around the Object's pivot
503          *        (i.e. Object pivot is centralized in boundbox)
504          *      - boundbox gives full width
505          */
506         // XXX: all dimensions are auto-determined now... later can add stored settings for this
507         BKE_object_dimensions_get(ob, size);
508
509         if (ELEM(rbo->shape, RB_SHAPE_CAPSULE, RB_SHAPE_CYLINDER, RB_SHAPE_CONE)) {
510                 /* take radius as largest x/y dimension, and height as z-dimension */
511                 radius = MAX2(size[0], size[1]) * 0.5f;
512                 height = size[2];
513         }
514         else if (rbo->shape == RB_SHAPE_SPHERE) {
515                 /* take radius to the largest dimension to try and encompass everything */
516                 radius = max_fff(size[0], size[1], size[2]) * 0.5f;
517         }
518
519         /* calculate volume as appropriate  */
520         switch (rbo->shape) {
521                 case RB_SHAPE_BOX:
522                         volume = size[0] * size[1] * size[2];
523                         break;
524
525                 case RB_SHAPE_SPHERE:
526                         volume = 4.0f / 3.0f * (float)M_PI * radius * radius * radius;
527                         break;
528
529                 /* for now, assume that capsule is close enough to a cylinder... */
530                 case RB_SHAPE_CAPSULE:
531                 case RB_SHAPE_CYLINDER:
532                         volume = (float)M_PI * radius * radius * height;
533                         break;
534
535                 case RB_SHAPE_CONE:
536                         volume = (float)M_PI / 3.0f * radius * radius * height;
537                         break;
538
539                 case RB_SHAPE_CONVEXH:
540                 case RB_SHAPE_TRIMESH:
541                 {
542                         if (ob->type == OB_MESH) {
543                                 Mesh *mesh = rigidbody_get_mesh(ob);
544                                 MVert *mvert;
545                                 const MLoopTri *lt = NULL;
546                                 int totvert, tottri = 0;
547                                 const MLoop *mloop = NULL;
548
549                                 /* ensure mesh validity, then grab data */
550                                 if (mesh == NULL)
551                                         return;
552
553                                 mvert   = mesh->mvert;
554                                 totvert = mesh->totvert;
555                                 lt = BKE_mesh_runtime_looptri_ensure(mesh);
556                                 tottri = mesh->runtime.looptris.len;
557                                 mloop = mesh->mloop;
558
559                                 if (totvert > 0 && tottri > 0) {
560                                         BKE_mesh_calc_volume(mvert, totvert, lt, tottri, mloop, &volume, NULL);
561                                 }
562                         }
563                         else {
564                                 /* rough estimate from boundbox as fallback */
565                                 /* XXX could implement other types of geometry here (curves, etc.) */
566                                 volume = size[0] * size[1] * size[2];
567                         }
568                         break;
569                 }
570
571 #if 0 // XXX: not defined yet
572                 case RB_SHAPE_COMPOUND:
573                         volume = 0.0f;
574                         break;
575 #endif
576         }
577
578         /* return the volume calculated */
579         if (r_vol) *r_vol = volume;
580 }
581
582 void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3])
583 {
584         RigidBodyOb *rbo = ob->rigidbody_object;
585
586         float size[3]  = {1.0f, 1.0f, 1.0f};
587         float height = 1.0f;
588
589         zero_v3(r_center);
590
591         /* if automatically determining dimensions, use the Object's boundbox
592          *      - assume that all quadrics are standing upright on local z-axis
593          *      - assume even distribution of mass around the Object's pivot
594          *        (i.e. Object pivot is centralized in boundbox)
595          *      - boundbox gives full width
596          */
597         // XXX: all dimensions are auto-determined now... later can add stored settings for this
598         BKE_object_dimensions_get(ob, size);
599
600         /* calculate volume as appropriate  */
601         switch (rbo->shape) {
602                 case RB_SHAPE_BOX:
603                 case RB_SHAPE_SPHERE:
604                 case RB_SHAPE_CAPSULE:
605                 case RB_SHAPE_CYLINDER:
606                         break;
607
608                 case RB_SHAPE_CONE:
609                         /* take radius as largest x/y dimension, and height as z-dimension */
610                         height = size[2];
611                         /* cone is geometrically centered on the median,
612                          * center of mass is 1/4 up from the base
613                          */
614                         r_center[2] = -0.25f * height;
615                         break;
616
617                 case RB_SHAPE_CONVEXH:
618                 case RB_SHAPE_TRIMESH:
619                 {
620                         if (ob->type == OB_MESH) {
621                                 Mesh *mesh = rigidbody_get_mesh(ob);
622                                 MVert *mvert;
623                                 const MLoopTri *looptri;
624                                 int totvert, tottri;
625                                 const MLoop *mloop;
626
627                                 /* ensure mesh validity, then grab data */
628                                 if (mesh == NULL)
629                                         return;
630
631                                 mvert   = mesh->mvert;
632                                 totvert = mesh->totvert;
633                                 looptri = BKE_mesh_runtime_looptri_ensure(mesh);
634                                 tottri = mesh->runtime.looptris.len;
635                                 mloop = mesh->mloop;
636
637                                 if (totvert > 0 && tottri > 0) {
638                                         BKE_mesh_calc_volume(mvert, totvert, looptri, tottri, mloop, NULL, r_center);
639                                 }
640                         }
641                         break;
642                 }
643
644 #if 0 // XXX: not defined yet
645                 case RB_SHAPE_COMPOUND:
646                         volume = 0.0f;
647                         break;
648 #endif
649         }
650 }
651
652 /* --------------------- */
653
654 /**
655  * Create physics sim representation of object given RigidBody settings
656  *
657  * \param rebuild Even if an instance already exists, replace it
658  */
659 static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool rebuild)
660 {
661         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
662         float loc[3];
663         float rot[4];
664
665         /* sanity checks:
666          *      - object doesn't have RigidBody info already: then why is it here?
667          */
668         if (rbo == NULL)
669                 return;
670
671         /* make sure collision shape exists */
672         /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects, but it's needed for constraints to update correctly */
673         if (rbo->shared->physics_shape == NULL || rebuild)
674                 rigidbody_validate_sim_shape(ob, true);
675
676         if (rbo->shared->physics_object) {
677                 RB_dworld_remove_body(rbw->shared->physics_world, rbo->shared->physics_object);
678         }
679         if (!rbo->shared->physics_object || rebuild) {
680                 /* remove rigid body if it already exists before creating a new one */
681                 if (rbo->shared->physics_object) {
682                         RB_body_delete(rbo->shared->physics_object);
683                 }
684
685                 mat4_to_loc_quat(loc, rot, ob->obmat);
686
687                 rbo->shared->physics_object = RB_body_new(rbo->shared->physics_shape, loc, rot);
688
689                 RB_body_set_friction(rbo->shared->physics_object, rbo->friction);
690                 RB_body_set_restitution(rbo->shared->physics_object, rbo->restitution);
691
692                 RB_body_set_damping(rbo->shared->physics_object, rbo->lin_damping, rbo->ang_damping);
693                 RB_body_set_sleep_thresh(rbo->shared->physics_object, rbo->lin_sleep_thresh, rbo->ang_sleep_thresh);
694                 RB_body_set_activation_state(rbo->shared->physics_object, rbo->flag & RBO_FLAG_USE_DEACTIVATION);
695
696                 if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED)
697                         RB_body_deactivate(rbo->shared->physics_object);
698
699
700                 RB_body_set_linear_factor(rbo->shared->physics_object,
701                                           (ob->protectflag & OB_LOCK_LOCX) == 0,
702                                           (ob->protectflag & OB_LOCK_LOCY) == 0,
703                                           (ob->protectflag & OB_LOCK_LOCZ) == 0);
704                 RB_body_set_angular_factor(rbo->shared->physics_object,
705                                            (ob->protectflag & OB_LOCK_ROTX) == 0,
706                                            (ob->protectflag & OB_LOCK_ROTY) == 0,
707                                            (ob->protectflag & OB_LOCK_ROTZ) == 0);
708
709                 RB_body_set_mass(rbo->shared->physics_object, RBO_GET_MASS(rbo));
710                 RB_body_set_kinematic_state(rbo->shared->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
711         }
712
713         if (rbw && rbw->shared->physics_world)
714                 RB_dworld_add_body(rbw->shared->physics_world, rbo->shared->physics_object, rbo->col_groups);
715 }
716
717 /* --------------------- */
718
719 static void rigidbody_constraint_set_limits(
720         RigidBodyCon *rbc, void (*set_limits)(rbConstraint *, int, float, float))
721 {
722         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
723                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
724         else
725                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
726
727         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
728                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
729         else
730                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
731
732         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
733                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
734         else
735                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
736
737         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
738                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
739         else
740                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
741
742         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
743                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
744         else
745                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
746
747         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
748                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
749         else
750                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
751 }
752
753 /**
754  * Create physics sim representation of constraint given rigid body constraint settings
755  *
756  * \param rebuild Even if an instance already exists, replace it
757  */
758 static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, bool rebuild)
759 {
760         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
761         float loc[3];
762         float rot[4];
763         float lin_lower;
764         float lin_upper;
765         float ang_lower;
766         float ang_upper;
767
768         /* sanity checks:
769          *      - object should have a rigid body constraint
770          *  - rigid body constraint should have at least one constrained object
771          */
772         if (rbc == NULL) {
773                 return;
774         }
775
776         if (ELEM(NULL, rbc->ob1, rbc->ob1->rigidbody_object, rbc->ob2, rbc->ob2->rigidbody_object)) {
777                 if (rbc->physics_constraint) {
778                         RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
779                         RB_constraint_delete(rbc->physics_constraint);
780                         rbc->physics_constraint = NULL;
781                 }
782                 return;
783         }
784
785         if (rbc->physics_constraint && rebuild == false) {
786                 RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
787         }
788         if (rbc->physics_constraint == NULL || rebuild) {
789                 rbRigidBody *rb1 = rbc->ob1->rigidbody_object->shared->physics_object;
790                 rbRigidBody *rb2 = rbc->ob2->rigidbody_object->shared->physics_object;
791
792                 /* remove constraint if it already exists before creating a new one */
793                 if (rbc->physics_constraint) {
794                         RB_constraint_delete(rbc->physics_constraint);
795                         rbc->physics_constraint = NULL;
796                 }
797
798                 mat4_to_loc_quat(loc, rot, ob->obmat);
799
800                 if (rb1 && rb2) {
801                         switch (rbc->type) {
802                                 case RBC_TYPE_POINT:
803                                         rbc->physics_constraint = RB_constraint_new_point(loc, rb1, rb2);
804                                         break;
805                                 case RBC_TYPE_FIXED:
806                                         rbc->physics_constraint = RB_constraint_new_fixed(loc, rot, rb1, rb2);
807                                         break;
808                                 case RBC_TYPE_HINGE:
809                                         rbc->physics_constraint = RB_constraint_new_hinge(loc, rot, rb1, rb2);
810                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
811                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
812                                         }
813                                         else
814                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, 0.0f, -1.0f);
815                                         break;
816                                 case RBC_TYPE_SLIDER:
817                                         rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2);
818                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
819                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
820                                         else
821                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, 0.0f, -1.0f);
822                                         break;
823                                 case RBC_TYPE_PISTON:
824                                         rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2);
825                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
826                                                 lin_lower = rbc->limit_lin_x_lower;
827                                                 lin_upper = rbc->limit_lin_x_upper;
828                                         }
829                                         else {
830                                                 lin_lower = 0.0f;
831                                                 lin_upper = -1.0f;
832                                         }
833                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
834                                                 ang_lower = rbc->limit_ang_x_lower;
835                                                 ang_upper = rbc->limit_ang_x_upper;
836                                         }
837                                         else {
838                                                 ang_lower = 0.0f;
839                                                 ang_upper = -1.0f;
840                                         }
841                                         RB_constraint_set_limits_piston(rbc->physics_constraint, lin_lower, lin_upper, ang_lower, ang_upper);
842                                         break;
843                                 case RBC_TYPE_6DOF_SPRING:
844                                         rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2);
845
846                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->flag & RBC_FLAG_USE_SPRING_X);
847                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_stiffness_x);
848                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_damping_x);
849
850                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->flag & RBC_FLAG_USE_SPRING_Y);
851                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_stiffness_y);
852                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_damping_y);
853
854                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->flag & RBC_FLAG_USE_SPRING_Z);
855                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_stiffness_z);
856                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_damping_z);
857
858                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->flag & RBC_FLAG_USE_SPRING_ANG_X);
859                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_stiffness_ang_x);
860                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_damping_ang_x);
861
862                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y);
863                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_stiffness_ang_y);
864                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_damping_ang_y);
865
866                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z);
867                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_stiffness_ang_z);
868                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_damping_ang_z);
869
870                                         RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint);
871
872                                         rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof_spring);
873                                         break;
874                                 case RBC_TYPE_6DOF:
875                                         rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
876
877                                         rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof);
878                                         break;
879                                 case RBC_TYPE_MOTOR:
880                                         rbc->physics_constraint = RB_constraint_new_motor(loc, rot, rb1, rb2);
881
882                                         RB_constraint_set_enable_motor(rbc->physics_constraint, rbc->flag & RBC_FLAG_USE_MOTOR_LIN, rbc->flag & RBC_FLAG_USE_MOTOR_ANG);
883                                         RB_constraint_set_max_impulse_motor(rbc->physics_constraint, rbc->motor_lin_max_impulse, rbc->motor_ang_max_impulse);
884                                         RB_constraint_set_target_velocity_motor(rbc->physics_constraint, rbc->motor_lin_target_velocity, rbc->motor_ang_target_velocity);
885                                         break;
886                         }
887                 }
888                 else { /* can't create constraint without both rigid bodies */
889                         return;
890                 }
891
892                 RB_constraint_set_enabled(rbc->physics_constraint, rbc->flag & RBC_FLAG_ENABLED);
893
894                 if (rbc->flag & RBC_FLAG_USE_BREAKING)
895                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, rbc->breaking_threshold);
896                 else
897                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, FLT_MAX);
898
899                 if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS)
900                         RB_constraint_set_solver_iterations(rbc->physics_constraint, rbc->num_solver_iterations);
901                 else
902                         RB_constraint_set_solver_iterations(rbc->physics_constraint, -1);
903         }
904
905         if (rbw && rbw->shared->physics_world && rbc->physics_constraint) {
906                 RB_dworld_add_constraint(rbw->shared->physics_world, rbc->physics_constraint, rbc->flag & RBC_FLAG_DISABLE_COLLISIONS);
907         }
908 }
909
910 /* --------------------- */
911
912 /* Create physics sim world given RigidBody world settings */
913 // NOTE: this does NOT update object references that the scene uses, in case those aren't ready yet!
914 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild)
915 {
916         /* sanity checks */
917         if (rbw == NULL)
918                 return;
919
920         /* create new sim world */
921         if (rebuild || rbw->shared->physics_world == NULL) {
922                 if (rbw->shared->physics_world)
923                         RB_dworld_delete(rbw->shared->physics_world);
924                 rbw->shared->physics_world = RB_dworld_new(scene->physics_settings.gravity);
925         }
926
927         RB_dworld_set_solver_iterations(rbw->shared->physics_world, rbw->num_solver_iterations);
928         RB_dworld_set_split_impulse(rbw->shared->physics_world, rbw->flag & RBW_FLAG_USE_SPLIT_IMPULSE);
929 }
930
931 /* ************************************** */
932 /* Setup Utilities - Create Settings Blocks */
933
934 /* Set up RigidBody world */
935 RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
936 {
937         /* try to get whatever RigidBody world that might be representing this already */
938         RigidBodyWorld *rbw;
939
940         /* sanity checks
941          *      - there must be a valid scene to add world to
942          *      - there mustn't be a sim world using this group already
943          */
944         if (scene == NULL)
945                 return NULL;
946
947         /* create a new sim world */
948         rbw = MEM_callocN(sizeof(RigidBodyWorld), "RigidBodyWorld");
949         rbw->shared = MEM_callocN(sizeof(*rbw->shared), "RigidBodyWorld_Shared");
950
951         /* set default settings */
952         rbw->effector_weights = BKE_add_effector_weights(NULL);
953
954         rbw->ltime = PSFRA;
955
956         rbw->time_scale = 1.0f;
957
958         rbw->steps_per_second = 60; /* Bullet default (60 Hz) */
959         rbw->num_solver_iterations = 10; /* 10 is bullet default */
960
961         rbw->shared->pointcache = BKE_ptcache_add(&(rbw->shared->ptcaches));
962         rbw->shared->pointcache->step = 1;
963
964         /* return this sim world */
965         return rbw;
966 }
967
968 RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag)
969 {
970         RigidBodyWorld *rbw_copy = MEM_dupallocN(rbw);
971
972         if (rbw->effector_weights) {
973                 rbw_copy->effector_weights = MEM_dupallocN(rbw->effector_weights);
974         }
975         if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
976                 id_us_plus((ID *)rbw_copy->group);
977                 id_us_plus((ID *)rbw_copy->constraints);
978         }
979
980         if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
981                 /* This is a regular copy, and not a CoW copy for depsgraph evaluation */
982                 rbw_copy->shared = MEM_callocN(sizeof(*rbw_copy->shared), "RigidBodyWorld_Shared");
983                 BKE_ptcache_copy_list(&rbw_copy->shared->ptcaches, &rbw->shared->ptcaches, LIB_ID_COPY_CACHES);
984                 rbw_copy->shared->pointcache = rbw_copy->shared->ptcaches.first;
985         }
986
987         rbw_copy->objects = NULL;
988         rbw_copy->numbodies = 0;
989         rigidbody_update_ob_array(rbw_copy);
990
991         return rbw_copy;
992 }
993
994 void BKE_rigidbody_world_groups_relink(RigidBodyWorld *rbw)
995 {
996         ID_NEW_REMAP(rbw->group);
997         ID_NEW_REMAP(rbw->constraints);
998         ID_NEW_REMAP(rbw->effector_weights->group);
999 }
1000
1001 void BKE_rigidbody_world_id_loop(RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata)
1002 {
1003         func(rbw, (ID **)&rbw->group, userdata, IDWALK_CB_NOP);
1004         func(rbw, (ID **)&rbw->constraints, userdata, IDWALK_CB_NOP);
1005         func(rbw, (ID **)&rbw->effector_weights->group, userdata, IDWALK_CB_NOP);
1006
1007         if (rbw->objects) {
1008                 int i;
1009                 for (i = 0; i < rbw->numbodies; i++) {
1010                         func(rbw, (ID **)&rbw->objects[i], userdata, IDWALK_CB_NOP);
1011                 }
1012         }
1013 }
1014
1015 /* Add rigid body settings to the specified object */
1016 RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type)
1017 {
1018         RigidBodyOb *rbo;
1019         RigidBodyWorld *rbw = scene->rigidbody_world;
1020
1021         /* sanity checks
1022          *      - rigidbody world must exist
1023          *      - object must exist
1024          *      - cannot add rigid body if it already exists
1025          */
1026         if (ob == NULL || (ob->rigidbody_object != NULL))
1027                 return NULL;
1028
1029         /* create new settings data, and link it up */
1030         rbo = MEM_callocN(sizeof(RigidBodyOb), "RigidBodyOb");
1031         rbo->shared = MEM_callocN(sizeof(*rbo->shared), "RigidBodyOb_Shared");
1032
1033         /* set default settings */
1034         rbo->type = type;
1035
1036         rbo->mass = 1.0f;
1037
1038         rbo->friction = 0.5f; /* best when non-zero. 0.5 is Bullet default */
1039         rbo->restitution = 0.0f; /* best when zero. 0.0 is Bullet default */
1040
1041         rbo->margin = 0.04f; /* 0.04 (in meters) is Bullet default */
1042
1043         rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */
1044         rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */
1045
1046         rbo->lin_damping = 0.04f;
1047         rbo->ang_damping = 0.1f;
1048
1049         rbo->col_groups = 1;
1050
1051         /* use triangle meshes for passive objects
1052          * use convex hulls for active objects since dynamic triangle meshes are very unstable
1053          */
1054         if (type == RBO_TYPE_ACTIVE)
1055                 rbo->shape = RB_SHAPE_CONVEXH;
1056         else
1057                 rbo->shape = RB_SHAPE_TRIMESH;
1058
1059         rbo->mesh_source = RBO_MESH_DEFORM;
1060
1061         /* set initial transform */
1062         mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1063
1064         /* flag cache as outdated */
1065         BKE_rigidbody_cache_reset(rbw);
1066
1067         /* return this object */
1068         return rbo;
1069 }
1070
1071 /* Add rigid body constraint to the specified object */
1072 RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type)
1073 {
1074         RigidBodyCon *rbc;
1075         RigidBodyWorld *rbw = scene->rigidbody_world;
1076
1077         /* sanity checks
1078          *      - rigidbody world must exist
1079          *      - object must exist
1080          *      - cannot add constraint if it already exists
1081          */
1082         if (ob == NULL || (ob->rigidbody_constraint != NULL))
1083                 return NULL;
1084
1085         /* create new settings data, and link it up */
1086         rbc = MEM_callocN(sizeof(RigidBodyCon), "RigidBodyCon");
1087
1088         /* set default settings */
1089         rbc->type = type;
1090
1091         rbc->ob1 = NULL;
1092         rbc->ob2 = NULL;
1093
1094         rbc->flag |= RBC_FLAG_ENABLED;
1095         rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS;
1096
1097         rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */
1098         rbc->num_solver_iterations = 10; /* 10 is Bullet default */
1099
1100         rbc->limit_lin_x_lower = -1.0f;
1101         rbc->limit_lin_x_upper = 1.0f;
1102         rbc->limit_lin_y_lower = -1.0f;
1103         rbc->limit_lin_y_upper = 1.0f;
1104         rbc->limit_lin_z_lower = -1.0f;
1105         rbc->limit_lin_z_upper = 1.0f;
1106         rbc->limit_ang_x_lower = -M_PI_4;
1107         rbc->limit_ang_x_upper = M_PI_4;
1108         rbc->limit_ang_y_lower = -M_PI_4;
1109         rbc->limit_ang_y_upper = M_PI_4;
1110         rbc->limit_ang_z_lower = -M_PI_4;
1111         rbc->limit_ang_z_upper = M_PI_4;
1112
1113         rbc->spring_damping_x = 0.5f;
1114         rbc->spring_damping_y = 0.5f;
1115         rbc->spring_damping_z = 0.5f;
1116         rbc->spring_damping_ang_x = 0.5f;
1117         rbc->spring_damping_ang_y = 0.5f;
1118         rbc->spring_damping_ang_z = 0.5f;
1119         rbc->spring_stiffness_x = 10.0f;
1120         rbc->spring_stiffness_y = 10.0f;
1121         rbc->spring_stiffness_z = 10.0f;
1122         rbc->spring_stiffness_ang_x = 10.0f;
1123         rbc->spring_stiffness_ang_y = 10.0f;
1124         rbc->spring_stiffness_ang_z = 10.0f;
1125
1126         rbc->motor_lin_max_impulse = 1.0f;
1127         rbc->motor_lin_target_velocity = 1.0f;
1128         rbc->motor_ang_max_impulse = 1.0f;
1129         rbc->motor_ang_target_velocity = 1.0f;
1130
1131         /* flag cache as outdated */
1132         BKE_rigidbody_cache_reset(rbw);
1133
1134         /* return this object */
1135         return rbc;
1136 }
1137
1138 /* ************************************** */
1139 /* Utilities API */
1140
1141 /* Get RigidBody world for the given scene, creating one if needed
1142  *
1143  * \param scene Scene to find active Rigid Body world for
1144  */
1145 RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene)
1146 {
1147         /* sanity check */
1148         if (scene == NULL)
1149                 return NULL;
1150
1151         return scene->rigidbody_world;
1152 }
1153
1154 void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob)
1155 {
1156         RigidBodyWorld *rbw = scene->rigidbody_world;
1157         RigidBodyCon *rbc;
1158         int i;
1159
1160         if (rbw) {
1161
1162                 /* remove object from array */
1163                 if (rbw && rbw->objects) {
1164                         for (i = 0; i < rbw->numbodies; i++) {
1165                                 if (rbw->objects[i] == ob) {
1166                                         rbw->objects[i] = NULL;
1167                                         break;
1168                                 }
1169                         }
1170                 }
1171
1172                 /* remove object from rigid body constraints */
1173                 if (rbw->constraints) {
1174                         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, obt)
1175                         {
1176                                 if (obt && obt->rigidbody_constraint) {
1177                                         rbc = obt->rigidbody_constraint;
1178                                         if (ELEM(ob, rbc->ob1, rbc->ob2)) {
1179                                                 BKE_rigidbody_remove_constraint(scene, obt);
1180                                         }
1181                                 }
1182                         }
1183                         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1184                 }
1185                 BKE_collection_object_remove(bmain, rbw->group, ob, false);
1186         }
1187
1188         /* remove object's settings */
1189         BKE_rigidbody_free_object(ob, rbw);
1190
1191         /* flag cache as outdated */
1192         BKE_rigidbody_cache_reset(rbw);
1193 }
1194
1195 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob)
1196 {
1197         RigidBodyWorld *rbw = scene->rigidbody_world;
1198         RigidBodyCon *rbc = ob->rigidbody_constraint;
1199
1200         /* remove from rigidbody world, free object won't do this */
1201         if (rbw && rbw->shared->physics_world && rbc->physics_constraint) {
1202                 RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
1203         }
1204         /* remove object's settings */
1205         BKE_rigidbody_free_constraint(ob);
1206
1207         /* flag cache as outdated */
1208         BKE_rigidbody_cache_reset(rbw);
1209 }
1210
1211
1212 /* ************************************** */
1213 /* Simulation Interface - Bullet */
1214
1215 /* Update object array and rigid body count so they're in sync with the rigid body group */
1216 static void rigidbody_update_ob_array(RigidBodyWorld *rbw)
1217 {
1218         if (rbw->group == NULL) {
1219                 rbw->numbodies = 0;
1220                 rbw->objects = realloc(rbw->objects, 0);
1221                 return;
1222         }
1223
1224         int n = 0;
1225         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1226         {
1227                 (void)object;
1228                 n++;
1229         }
1230         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1231
1232         if (rbw->numbodies != n) {
1233                 rbw->numbodies = n;
1234                 rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies);
1235         }
1236
1237         int i = 0;
1238         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1239         {
1240                 rbw->objects[i] = object;
1241                 i++;
1242         }
1243         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1244 }
1245
1246 static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
1247 {
1248         float adj_gravity[3];
1249
1250         /* adjust gravity to take effector weights into account */
1251         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
1252                 copy_v3_v3(adj_gravity, scene->physics_settings.gravity);
1253                 mul_v3_fl(adj_gravity, rbw->effector_weights->global_gravity * rbw->effector_weights->weight[0]);
1254         }
1255         else {
1256                 zero_v3(adj_gravity);
1257         }
1258
1259         /* update gravity, since this RNA setting is not part of RigidBody settings */
1260         RB_dworld_set_gravity(rbw->shared->physics_world, adj_gravity);
1261
1262         /* update object array in case there are changes */
1263         rigidbody_update_ob_array(rbw);
1264 }
1265
1266 static void rigidbody_update_sim_ob(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo)
1267 {
1268         float loc[3];
1269         float rot[4];
1270         float scale[3];
1271
1272         /* only update if rigid body exists */
1273         if (rbo->shared->physics_object == NULL)
1274                 return;
1275
1276         if (rbo->shape == RB_SHAPE_TRIMESH && rbo->flag & RBO_FLAG_USE_DEFORM) {
1277                 Mesh *mesh = ob->runtime.mesh_deform_eval;
1278                 if (mesh) {
1279                         MVert *mvert = mesh->mvert;
1280                         int totvert = mesh->totvert;
1281                         BoundBox *bb = BKE_object_boundbox_get(ob);
1282
1283                         RB_shape_trimesh_update(rbo->shared->physics_shape, (float *)mvert, totvert, sizeof(MVert), bb->vec[0], bb->vec[6]);
1284                 }
1285         }
1286
1287         mat4_decompose(loc, rot, scale, ob->obmat);
1288
1289         /* update scale for all objects */
1290         RB_body_set_scale(rbo->shared->physics_object, scale);
1291         /* compensate for embedded convex hull collision margin */
1292         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH)
1293                 RB_shape_set_margin(rbo->shared->physics_shape, RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
1294
1295         /* make transformed objects temporarily kinmatic so that they can be moved by the user during simulation */
1296         if (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ) {
1297                 RB_body_set_kinematic_state(rbo->shared->physics_object, true);
1298                 RB_body_set_mass(rbo->shared->physics_object, 0.0f);
1299         }
1300
1301         /* update rigid body location and rotation for kinematic bodies */
1302         if (rbo->flag & RBO_FLAG_KINEMATIC || (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1303                 RB_body_activate(rbo->shared->physics_object);
1304                 RB_body_set_loc_rot(rbo->shared->physics_object, loc, rot);
1305         }
1306         /* update influence of effectors - but don't do it on an effector */
1307         /* only dynamic bodies need effector update */
1308         else if (rbo->type == RBO_TYPE_ACTIVE && ((ob->pd == NULL) || (ob->pd->forcefield == PFIELD_NULL))) {
1309                 EffectorWeights *effector_weights = rbw->effector_weights;
1310                 EffectedPoint epoint;
1311                 ListBase *effectors;
1312
1313                 /* get effectors present in the group specified by effector_weights */
1314                 effectors = BKE_effectors_create(depsgraph, ob, NULL, effector_weights);
1315                 if (effectors) {
1316                         float eff_force[3] = {0.0f, 0.0f, 0.0f};
1317                         float eff_loc[3], eff_vel[3];
1318
1319                         /* create dummy 'point' which represents last known position of object as result of sim */
1320                         // XXX: this can create some inaccuracies with sim position, but is probably better than using unsimulated vals?
1321                         RB_body_get_position(rbo->shared->physics_object, eff_loc);
1322                         RB_body_get_linear_velocity(rbo->shared->physics_object, eff_vel);
1323
1324                         pd_point_from_loc(scene, eff_loc, eff_vel, 0, &epoint);
1325
1326                         /* calculate net force of effectors, and apply to sim object
1327                          *      - we use 'central force' since apply force requires a "relative position" which we don't have...
1328                          */
1329                         BKE_effectors_apply(effectors, NULL, effector_weights, &epoint, eff_force, NULL);
1330                         if (G.f & G_DEBUG)
1331                                 printf("\tapplying force (%f,%f,%f) to '%s'\n", eff_force[0], eff_force[1], eff_force[2], ob->id.name + 2);
1332                         /* activate object in case it is deactivated */
1333                         if (!is_zero_v3(eff_force))
1334                                 RB_body_activate(rbo->shared->physics_object);
1335                         RB_body_apply_central_force(rbo->shared->physics_object, eff_force);
1336                 }
1337                 else if (G.f & G_DEBUG)
1338                         printf("\tno forces to apply to '%s'\n", ob->id.name + 2);
1339
1340                 /* cleanup */
1341                 BKE_effectors_free(effectors);
1342         }
1343         /* NOTE: passive objects don't need to be updated since they don't move */
1344
1345         /* NOTE: no other settings need to be explicitly updated here,
1346          * since RNA setters take care of the rest :)
1347          */
1348 }
1349
1350 /**
1351  * Updates and validates world, bodies and shapes.
1352  *
1353  * \param rebuild Rebuild entire simulation
1354  */
1355 static void rigidbody_update_simulation(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, bool rebuild)
1356 {
1357         /* update world */
1358         if (rebuild)
1359                 BKE_rigidbody_validate_sim_world(scene, rbw, true);
1360         rigidbody_update_sim_world(scene, rbw);
1361
1362         /* XXX TODO For rebuild: remove all constraints first.
1363          * Otherwise we can end up deleting objects that are still
1364          * referenced by constraints, corrupting bullet's internal list.
1365          *
1366          * Memory management needs redesign here, this is just a dirty workaround.
1367          */
1368         if (rebuild && rbw->constraints) {
1369                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, ob)
1370                 {
1371                         RigidBodyCon *rbc = ob->rigidbody_constraint;
1372                         if (rbc && rbc->physics_constraint) {
1373                                 RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
1374                                 RB_constraint_delete(rbc->physics_constraint);
1375                                 rbc->physics_constraint = NULL;
1376                         }
1377                 }
1378                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1379         }
1380
1381         /* update objects */
1382         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, ob)
1383         {
1384                 if (ob->type == OB_MESH) {
1385                         /* validate that we've got valid object set up here... */
1386                         RigidBodyOb *rbo = ob->rigidbody_object;
1387                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1388                         BKE_object_where_is_calc(depsgraph, scene, ob);
1389
1390                         if (rbo == NULL) {
1391                                 /* Since this object is included in the sim group but doesn't have
1392                                  * rigid body settings (perhaps it was added manually), add!
1393                                  *      - assume object to be active? That is the default for newly added settings...
1394                                  */
1395                                 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, RBO_TYPE_ACTIVE);
1396                                 rigidbody_validate_sim_object(rbw, ob, true);
1397
1398                                 rbo = ob->rigidbody_object;
1399                         }
1400                         else {
1401                                 /* perform simulation data updates as tagged */
1402                                 /* refresh object... */
1403                                 if (rebuild) {
1404                                         /* World has been rebuilt so rebuild object */
1405                                         /* TODO(Sybren): rigidbody_validate_sim_object() can call rigidbody_validate_sim_shape(),
1406                                          * but neither resets the RBO_FLAG_NEEDS_RESHAPE flag nor calls RB_body_set_collision_shape().
1407                                          * This results in the collision shape being created twice, which is unnecessary. */
1408                                         rigidbody_validate_sim_object(rbw, ob, true);
1409                                 }
1410                                 else if (rbo->flag & RBO_FLAG_NEEDS_VALIDATE) {
1411                                         rigidbody_validate_sim_object(rbw, ob, false);
1412                                 }
1413                                 /* refresh shape... */
1414                                 if (rbo->flag & RBO_FLAG_NEEDS_RESHAPE) {
1415                                         /* mesh/shape data changed, so force shape refresh */
1416                                         rigidbody_validate_sim_shape(ob, true);
1417                                         /* now tell RB sim about it */
1418                                         // XXX: we assume that this can only get applied for active/passive shapes that will be included as rigidbodies
1419                                         RB_body_set_collision_shape(rbo->shared->physics_object, rbo->shared->physics_shape);
1420                                 }
1421                                 rbo->flag &= ~(RBO_FLAG_NEEDS_VALIDATE | RBO_FLAG_NEEDS_RESHAPE);
1422                         }
1423
1424                         /* update simulation object... */
1425                         rigidbody_update_sim_ob(depsgraph, scene, rbw, ob, rbo);
1426                 }
1427         }
1428         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1429
1430         /* update constraints */
1431         if (rbw->constraints == NULL) /* no constraints, move on */
1432                 return;
1433
1434         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, ob)
1435         {
1436                 /* validate that we've got valid object set up here... */
1437                 RigidBodyCon *rbc = ob->rigidbody_constraint;
1438                 /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1439                 BKE_object_where_is_calc(depsgraph, scene, ob);
1440
1441                 if (rbc == NULL) {
1442                         /* Since this object is included in the group but doesn't have
1443                          * constraint settings (perhaps it was added manually), add!
1444                          */
1445                         ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, RBC_TYPE_FIXED);
1446                         rigidbody_validate_sim_constraint(rbw, ob, true);
1447
1448                         rbc = ob->rigidbody_constraint;
1449                 }
1450                 else {
1451                         /* perform simulation data updates as tagged */
1452                         if (rebuild) {
1453                                 /* World has been rebuilt so rebuild constraint */
1454                                 rigidbody_validate_sim_constraint(rbw, ob, true);
1455                         }
1456                         else if (rbc->flag & RBC_FLAG_NEEDS_VALIDATE) {
1457                                 rigidbody_validate_sim_constraint(rbw, ob, false);
1458                         }
1459                         rbc->flag &= ~RBC_FLAG_NEEDS_VALIDATE;
1460                 }
1461         }
1462         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1463 }
1464
1465 static void rigidbody_update_simulation_post_step(Depsgraph *depsgraph, RigidBodyWorld *rbw)
1466 {
1467         ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1468
1469         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, ob)
1470         {
1471                 Base *base = BKE_view_layer_base_find(view_layer, ob);
1472                 RigidBodyOb *rbo = ob->rigidbody_object;
1473                 /* Reset kinematic state for transformed objects. */
1474                 if (rbo && base && (base->flag & BASE_SELECTED) && (G.moving & G_TRANSFORM_OBJ)) {
1475                         RB_body_set_kinematic_state(rbo->shared->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
1476                         RB_body_set_mass(rbo->shared->physics_object, RBO_GET_MASS(rbo));
1477                         /* Deactivate passive objects so they don't interfere with deactivation of active objects. */
1478                         if (rbo->type == RBO_TYPE_PASSIVE)
1479                                 RB_body_deactivate(rbo->shared->physics_object);
1480                 }
1481         }
1482         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1483 }
1484
1485 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime)
1486 {
1487         return (rbw && (rbw->flag & RBW_FLAG_MUTED) == 0 && ctime > rbw->shared->pointcache->startframe);
1488 }
1489
1490 /* Sync rigid body and object transformations */
1491 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime)
1492 {
1493         RigidBodyOb *rbo = ob->rigidbody_object;
1494
1495         /* keep original transform for kinematic and passive objects */
1496         if (ELEM(NULL, rbw, rbo) || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE)
1497                 return;
1498
1499         /* use rigid body transform after cache start frame if objects is not being transformed */
1500         if (BKE_rigidbody_check_sim_running(rbw, ctime) && !(ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1501                 float mat[4][4], size_mat[4][4], size[3];
1502
1503                 normalize_qt(rbo->orn); // RB_TODO investigate why quaternion isn't normalized at this point
1504                 quat_to_mat4(mat, rbo->orn);
1505                 copy_v3_v3(mat[3], rbo->pos);
1506
1507                 mat4_to_size(size, ob->obmat);
1508                 size_to_mat4(size_mat, size);
1509                 mul_m4_m4m4(mat, mat, size_mat);
1510
1511                 copy_m4_m4(ob->obmat, mat);
1512         }
1513         /* otherwise set rigid body transform to current obmat */
1514         else {
1515                 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1516         }
1517 }
1518
1519 /* Used when canceling transforms - return rigidbody and object to initial states */
1520 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
1521 {
1522         RigidBodyOb *rbo = ob->rigidbody_object;
1523         bool correct_delta = !(rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE);
1524
1525         /* return rigid body and object to their initial states */
1526         copy_v3_v3(rbo->pos, ob->loc);
1527         copy_v3_v3(ob->loc, loc);
1528
1529         if (correct_delta) {
1530                 add_v3_v3(rbo->pos, ob->dloc);
1531         }
1532
1533         if (ob->rotmode > 0) {
1534                 float qt[4];
1535                 eulO_to_quat(qt, ob->rot, ob->rotmode);
1536
1537                 if (correct_delta) {
1538                         float dquat[4];
1539                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1540
1541                         mul_qt_qtqt(rbo->orn, dquat, qt);
1542                 }
1543                 else {
1544                         copy_qt_qt(rbo->orn, qt);
1545                 }
1546
1547                 copy_v3_v3(ob->rot, rot);
1548         }
1549         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1550                 float qt[4];
1551                 axis_angle_to_quat(qt, ob->rotAxis, ob->rotAngle);
1552
1553                 if (correct_delta) {
1554                         float dquat[4];
1555                         axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
1556
1557                         mul_qt_qtqt(rbo->orn, dquat, qt);
1558                 }
1559                 else {
1560                         copy_qt_qt(rbo->orn, qt);
1561                 }
1562
1563                 copy_v3_v3(ob->rotAxis, rotAxis);
1564                 ob->rotAngle = rotAngle;
1565         }
1566         else {
1567                 if (correct_delta) {
1568                         mul_qt_qtqt(rbo->orn, ob->dquat, ob->quat);
1569                 }
1570                 else {
1571                         copy_qt_qt(rbo->orn, ob->quat);
1572                 }
1573
1574                 copy_qt_qt(ob->quat, quat);
1575         }
1576
1577         if (rbo->shared->physics_object) {
1578                 /* allow passive objects to return to original transform */
1579                 if (rbo->type == RBO_TYPE_PASSIVE)
1580                         RB_body_set_kinematic_state(rbo->shared->physics_object, true);
1581                 RB_body_set_loc_rot(rbo->shared->physics_object, rbo->pos, rbo->orn);
1582         }
1583         // RB_TODO update rigid body physics object's loc/rot for dynamic objects here as well (needs to be done outside bullet's update loop)
1584 }
1585
1586 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw)
1587 {
1588         if (rbw) {
1589                 rbw->shared->pointcache->flag |= PTCACHE_OUTDATED;
1590         }
1591 }
1592
1593 /* ------------------ */
1594
1595 /* Rebuild rigid body world */
1596 /* NOTE: this needs to be called before frame update to work correctly */
1597 void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime)
1598 {
1599         RigidBodyWorld *rbw = scene->rigidbody_world;
1600         PointCache *cache;
1601         PTCacheID pid;
1602         int startframe, endframe;
1603
1604         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1605         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1606         cache = rbw->shared->pointcache;
1607
1608         /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */
1609         int n = 0;
1610         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1611         {
1612                 (void)object;
1613                 n++;
1614         }
1615         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1616
1617         if (rbw->shared->physics_world == NULL || rbw->numbodies != n) {
1618                 cache->flag |= PTCACHE_OUTDATED;
1619         }
1620
1621         if (ctime == startframe + 1 && rbw->ltime == startframe) {
1622                 if (cache->flag & PTCACHE_OUTDATED) {
1623                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1624                         rigidbody_update_simulation(depsgraph, scene, rbw, true);
1625                         BKE_ptcache_validate(cache, (int)ctime);
1626                         cache->last_exact = 0;
1627                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1628                 }
1629         }
1630 }
1631
1632 /* Run RigidBody simulation for the specified physics world */
1633 void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime)
1634 {
1635         float timestep;
1636         RigidBodyWorld *rbw = scene->rigidbody_world;
1637         PointCache *cache;
1638         PTCacheID pid;
1639         int startframe, endframe;
1640
1641         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1642         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1643         cache = rbw->shared->pointcache;
1644
1645         if (ctime <= startframe) {
1646                 rbw->ltime = startframe;
1647                 return;
1648         }
1649         /* make sure we don't go out of cache frame range */
1650         else if (ctime > endframe) {
1651                 ctime = endframe;
1652         }
1653
1654         /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */
1655         if (rbw->shared->physics_world == NULL && !(cache->flag & PTCACHE_BAKED))
1656                 return;
1657         else if (rbw->objects == NULL)
1658                 rigidbody_update_ob_array(rbw);
1659
1660         /* try to read from cache */
1661         // RB_TODO deal with interpolated, old and baked results
1662         bool can_simulate = (ctime == rbw->ltime + 1) && !(cache->flag & PTCACHE_BAKED);
1663
1664         if (BKE_ptcache_read(&pid, ctime, can_simulate) == PTCACHE_READ_EXACT) {
1665                 BKE_ptcache_validate(cache, (int)ctime);
1666                 rbw->ltime = ctime;
1667                 return;
1668         }
1669
1670         if (!DEG_is_active(depsgraph)) {
1671                 /* When the depsgraph is inactive we should neither write to the cache
1672                  * nor run the simulation. */
1673                 return;
1674         }
1675
1676         /* advance simulation, we can only step one frame forward */
1677         if (compare_ff_relative(ctime, rbw->ltime + 1, FLT_EPSILON, 64)) {
1678                 /* write cache for first frame when on second frame */
1679                 if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
1680                         BKE_ptcache_write(&pid, startframe);
1681                 }
1682
1683                 /* update and validate simulation */
1684                 rigidbody_update_simulation(depsgraph, scene, rbw, false);
1685
1686                 /* calculate how much time elapsed since last step in seconds */
1687                 timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale;
1688                 /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */
1689                 RB_dworld_step_simulation(rbw->shared->physics_world, timestep, INT_MAX, 1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f));
1690
1691                 rigidbody_update_simulation_post_step(depsgraph, rbw);
1692
1693                 /* write cache for current frame */
1694                 BKE_ptcache_validate(cache, (int)ctime);
1695                 BKE_ptcache_write(&pid, (unsigned int)ctime);
1696
1697                 rbw->ltime = ctime;
1698         }
1699 }
1700 /* ************************************** */
1701
1702 #else  /* WITH_BULLET */
1703
1704 /* stubs */
1705 #if defined(__GNUC__) || defined(__clang__)
1706 #  pragma GCC diagnostic push
1707 #  pragma GCC diagnostic ignored "-Wunused-parameter"
1708 #endif
1709
1710 struct RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob, const int flag) { return NULL; }
1711 struct RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int flag) { return NULL; }
1712 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild) {}
1713 void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) { if (r_vol) *r_vol = 0.0f; }
1714 void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) { zero_v3(r_center); }
1715 struct RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) { return NULL; }
1716 struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag) { return NULL; }
1717 void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw) {}
1718 void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata) {}
1719 struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; }
1720 struct RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type) { return NULL; }
1721 struct RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { return NULL; }
1722 void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob) {}
1723 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) {}
1724 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) {}
1725 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) {}
1726 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime) { return false; }
1727 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) {}
1728 void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime) {}
1729 void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime) {}
1730
1731 #if defined(__GNUC__) || defined(__clang__)
1732 #  pragma GCC diagnostic pop
1733 #endif
1734
1735 #endif  /* WITH_BULLET */
1736
1737
1738
1739 /* -------------------- */
1740 /* Depsgraph evaluation */
1741
1742 void BKE_rigidbody_rebuild_sim(Depsgraph *depsgraph,
1743                                Scene *scene)
1744 {
1745         float ctime = DEG_get_ctime(depsgraph);
1746         DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime);
1747         /* rebuild sim data (i.e. after resetting to start of timeline) */
1748         if (BKE_scene_check_rigidbody_active(scene)) {
1749                 BKE_rigidbody_rebuild_world(depsgraph, scene, ctime);
1750         }
1751 }
1752
1753 void BKE_rigidbody_eval_simulation(Depsgraph *depsgraph,
1754                                    Scene *scene)
1755 {
1756         float ctime = DEG_get_ctime(depsgraph);
1757         DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime);
1758
1759         /* evaluate rigidbody sim */
1760         if (!BKE_scene_check_rigidbody_active(scene)) {
1761                 return;
1762         }
1763         BKE_rigidbody_do_simulation(depsgraph, scene, ctime);
1764 }
1765
1766 void BKE_rigidbody_object_sync_transforms(Depsgraph *depsgraph,
1767                                           Scene *scene,
1768                                           Object *ob)
1769 {
1770         RigidBodyWorld *rbw = scene->rigidbody_world;
1771         float ctime = DEG_get_ctime(depsgraph);
1772         DEG_debug_print_eval_time(depsgraph, __func__, ob->id.name, ob, ctime);
1773         /* read values pushed into RBO from sim/cache... */
1774         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
1775 }