3f9f6f15892bd9b151d30aa678f3d44de1aa486c
[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_collection_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_init_spring(
720         RigidBodyCon *rbc, void (*set_spring)(rbConstraint *, int, int),
721         void (*set_stiffness)(rbConstraint *, int, float), void (*set_damping)(rbConstraint *, int, float))
722 {
723         set_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->flag & RBC_FLAG_USE_SPRING_X);
724         set_stiffness(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_stiffness_x);
725         set_damping(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_damping_x);
726
727         set_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->flag & RBC_FLAG_USE_SPRING_Y);
728         set_stiffness(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_stiffness_y);
729         set_damping(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_damping_y);
730
731         set_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->flag & RBC_FLAG_USE_SPRING_Z);
732         set_stiffness(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_stiffness_z);
733         set_damping(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_damping_z);
734
735         set_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->flag & RBC_FLAG_USE_SPRING_ANG_X);
736         set_stiffness(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_stiffness_ang_x);
737         set_damping(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_damping_ang_x);
738
739         set_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y);
740         set_stiffness(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_stiffness_ang_y);
741         set_damping(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_damping_ang_y);
742
743         set_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z);
744         set_stiffness(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_stiffness_ang_z);
745         set_damping(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_damping_ang_z);
746 }
747
748 static void rigidbody_constraint_set_limits(
749         RigidBodyCon *rbc, void (*set_limits)(rbConstraint *, int, float, float))
750 {
751         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
752                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
753         else
754                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
755
756         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
757                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
758         else
759                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
760
761         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
762                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
763         else
764                 set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
765
766         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
767                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
768         else
769                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
770
771         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
772                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
773         else
774                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
775
776         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
777                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
778         else
779                 set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
780 }
781
782 /**
783  * Create physics sim representation of constraint given rigid body constraint settings
784  *
785  * \param rebuild Even if an instance already exists, replace it
786  */
787 static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, bool rebuild)
788 {
789         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
790         float loc[3];
791         float rot[4];
792         float lin_lower;
793         float lin_upper;
794         float ang_lower;
795         float ang_upper;
796
797         /* sanity checks:
798          *      - object should have a rigid body constraint
799          *  - rigid body constraint should have at least one constrained object
800          */
801         if (rbc == NULL) {
802                 return;
803         }
804
805         if (ELEM(NULL, rbc->ob1, rbc->ob1->rigidbody_object, rbc->ob2, rbc->ob2->rigidbody_object)) {
806                 if (rbc->physics_constraint) {
807                         RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
808                         RB_constraint_delete(rbc->physics_constraint);
809                         rbc->physics_constraint = NULL;
810                 }
811                 return;
812         }
813
814         if (rbc->physics_constraint && rebuild == false) {
815                 RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
816         }
817         if (rbc->physics_constraint == NULL || rebuild) {
818                 rbRigidBody *rb1 = rbc->ob1->rigidbody_object->shared->physics_object;
819                 rbRigidBody *rb2 = rbc->ob2->rigidbody_object->shared->physics_object;
820
821                 /* remove constraint if it already exists before creating a new one */
822                 if (rbc->physics_constraint) {
823                         RB_constraint_delete(rbc->physics_constraint);
824                         rbc->physics_constraint = NULL;
825                 }
826
827                 mat4_to_loc_quat(loc, rot, ob->obmat);
828
829                 if (rb1 && rb2) {
830                         switch (rbc->type) {
831                                 case RBC_TYPE_POINT:
832                                         rbc->physics_constraint = RB_constraint_new_point(loc, rb1, rb2);
833                                         break;
834                                 case RBC_TYPE_FIXED:
835                                         rbc->physics_constraint = RB_constraint_new_fixed(loc, rot, rb1, rb2);
836                                         break;
837                                 case RBC_TYPE_HINGE:
838                                         rbc->physics_constraint = RB_constraint_new_hinge(loc, rot, rb1, rb2);
839                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
840                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
841                                         }
842                                         else
843                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, 0.0f, -1.0f);
844                                         break;
845                                 case RBC_TYPE_SLIDER:
846                                         rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2);
847                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
848                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
849                                         else
850                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, 0.0f, -1.0f);
851                                         break;
852                                 case RBC_TYPE_PISTON:
853                                         rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2);
854                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
855                                                 lin_lower = rbc->limit_lin_x_lower;
856                                                 lin_upper = rbc->limit_lin_x_upper;
857                                         }
858                                         else {
859                                                 lin_lower = 0.0f;
860                                                 lin_upper = -1.0f;
861                                         }
862                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
863                                                 ang_lower = rbc->limit_ang_x_lower;
864                                                 ang_upper = rbc->limit_ang_x_upper;
865                                         }
866                                         else {
867                                                 ang_lower = 0.0f;
868                                                 ang_upper = -1.0f;
869                                         }
870                                         RB_constraint_set_limits_piston(rbc->physics_constraint, lin_lower, lin_upper, ang_lower, ang_upper);
871                                         break;
872                                 case RBC_TYPE_6DOF_SPRING:
873                                         if (rbc->spring_type == RBC_SPRING_TYPE2) {
874                                                 rbc->physics_constraint = RB_constraint_new_6dof_spring2(loc, rot, rb1, rb2);
875
876                                                 rigidbody_constraint_init_spring(rbc, RB_constraint_set_spring_6dof_spring2, RB_constraint_set_stiffness_6dof_spring2, RB_constraint_set_damping_6dof_spring2);
877
878                                                 RB_constraint_set_equilibrium_6dof_spring2(rbc->physics_constraint);
879
880                                                 rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof_spring2);
881                                         }
882                                         else {
883                                                 rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2);
884
885                                                 rigidbody_constraint_init_spring(rbc, RB_constraint_set_spring_6dof_spring, RB_constraint_set_stiffness_6dof_spring, RB_constraint_set_damping_6dof_spring);
886
887                                                 RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint);
888
889                                                 rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof);
890                                         }
891                                         break;
892                                 case RBC_TYPE_6DOF:
893                                         rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
894
895                                         rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof);
896                                         break;
897                                 case RBC_TYPE_MOTOR:
898                                         rbc->physics_constraint = RB_constraint_new_motor(loc, rot, rb1, rb2);
899
900                                         RB_constraint_set_enable_motor(rbc->physics_constraint, rbc->flag & RBC_FLAG_USE_MOTOR_LIN, rbc->flag & RBC_FLAG_USE_MOTOR_ANG);
901                                         RB_constraint_set_max_impulse_motor(rbc->physics_constraint, rbc->motor_lin_max_impulse, rbc->motor_ang_max_impulse);
902                                         RB_constraint_set_target_velocity_motor(rbc->physics_constraint, rbc->motor_lin_target_velocity, rbc->motor_ang_target_velocity);
903                                         break;
904                         }
905                 }
906                 else { /* can't create constraint without both rigid bodies */
907                         return;
908                 }
909
910                 RB_constraint_set_enabled(rbc->physics_constraint, rbc->flag & RBC_FLAG_ENABLED);
911
912                 if (rbc->flag & RBC_FLAG_USE_BREAKING)
913                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, rbc->breaking_threshold);
914                 else
915                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, FLT_MAX);
916
917                 if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS)
918                         RB_constraint_set_solver_iterations(rbc->physics_constraint, rbc->num_solver_iterations);
919                 else
920                         RB_constraint_set_solver_iterations(rbc->physics_constraint, -1);
921         }
922
923         if (rbw && rbw->shared->physics_world && rbc->physics_constraint) {
924                 RB_dworld_add_constraint(rbw->shared->physics_world, rbc->physics_constraint, rbc->flag & RBC_FLAG_DISABLE_COLLISIONS);
925         }
926 }
927
928 /* --------------------- */
929
930 /* Create physics sim world given RigidBody world settings */
931 // NOTE: this does NOT update object references that the scene uses, in case those aren't ready yet!
932 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild)
933 {
934         /* sanity checks */
935         if (rbw == NULL)
936                 return;
937
938         /* create new sim world */
939         if (rebuild || rbw->shared->physics_world == NULL) {
940                 if (rbw->shared->physics_world)
941                         RB_dworld_delete(rbw->shared->physics_world);
942                 rbw->shared->physics_world = RB_dworld_new(scene->physics_settings.gravity);
943         }
944
945         RB_dworld_set_solver_iterations(rbw->shared->physics_world, rbw->num_solver_iterations);
946         RB_dworld_set_split_impulse(rbw->shared->physics_world, rbw->flag & RBW_FLAG_USE_SPLIT_IMPULSE);
947 }
948
949 /* ************************************** */
950 /* Setup Utilities - Create Settings Blocks */
951
952 /* Set up RigidBody world */
953 RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
954 {
955         /* try to get whatever RigidBody world that might be representing this already */
956         RigidBodyWorld *rbw;
957
958         /* sanity checks
959          *      - there must be a valid scene to add world to
960          *      - there mustn't be a sim world using this group already
961          */
962         if (scene == NULL)
963                 return NULL;
964
965         /* create a new sim world */
966         rbw = MEM_callocN(sizeof(RigidBodyWorld), "RigidBodyWorld");
967         rbw->shared = MEM_callocN(sizeof(*rbw->shared), "RigidBodyWorld_Shared");
968
969         /* set default settings */
970         rbw->effector_weights = BKE_add_effector_weights(NULL);
971
972         rbw->ltime = PSFRA;
973
974         rbw->time_scale = 1.0f;
975
976         rbw->steps_per_second = 60; /* Bullet default (60 Hz) */
977         rbw->num_solver_iterations = 10; /* 10 is bullet default */
978
979         rbw->shared->pointcache = BKE_ptcache_add(&(rbw->shared->ptcaches));
980         rbw->shared->pointcache->step = 1;
981
982         /* return this sim world */
983         return rbw;
984 }
985
986 RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag)
987 {
988         RigidBodyWorld *rbw_copy = MEM_dupallocN(rbw);
989
990         if (rbw->effector_weights) {
991                 rbw_copy->effector_weights = MEM_dupallocN(rbw->effector_weights);
992         }
993         if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
994                 id_us_plus((ID *)rbw_copy->group);
995                 id_us_plus((ID *)rbw_copy->constraints);
996         }
997
998         if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
999                 /* This is a regular copy, and not a CoW copy for depsgraph evaluation */
1000                 rbw_copy->shared = MEM_callocN(sizeof(*rbw_copy->shared), "RigidBodyWorld_Shared");
1001                 BKE_ptcache_copy_list(&rbw_copy->shared->ptcaches, &rbw->shared->ptcaches, LIB_ID_COPY_CACHES);
1002                 rbw_copy->shared->pointcache = rbw_copy->shared->ptcaches.first;
1003         }
1004
1005         rbw_copy->objects = NULL;
1006         rbw_copy->numbodies = 0;
1007         rigidbody_update_ob_array(rbw_copy);
1008
1009         return rbw_copy;
1010 }
1011
1012 void BKE_rigidbody_world_groups_relink(RigidBodyWorld *rbw)
1013 {
1014         ID_NEW_REMAP(rbw->group);
1015         ID_NEW_REMAP(rbw->constraints);
1016         ID_NEW_REMAP(rbw->effector_weights->group);
1017 }
1018
1019 void BKE_rigidbody_world_id_loop(RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata)
1020 {
1021         func(rbw, (ID **)&rbw->group, userdata, IDWALK_CB_NOP);
1022         func(rbw, (ID **)&rbw->constraints, userdata, IDWALK_CB_NOP);
1023         func(rbw, (ID **)&rbw->effector_weights->group, userdata, IDWALK_CB_NOP);
1024
1025         if (rbw->objects) {
1026                 int i;
1027                 for (i = 0; i < rbw->numbodies; i++) {
1028                         func(rbw, (ID **)&rbw->objects[i], userdata, IDWALK_CB_NOP);
1029                 }
1030         }
1031 }
1032
1033 /* Add rigid body settings to the specified object */
1034 RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type)
1035 {
1036         RigidBodyOb *rbo;
1037         RigidBodyWorld *rbw = scene->rigidbody_world;
1038
1039         /* sanity checks
1040          *      - rigidbody world must exist
1041          *      - object must exist
1042          *      - cannot add rigid body if it already exists
1043          */
1044         if (ob == NULL || (ob->rigidbody_object != NULL))
1045                 return NULL;
1046
1047         /* create new settings data, and link it up */
1048         rbo = MEM_callocN(sizeof(RigidBodyOb), "RigidBodyOb");
1049         rbo->shared = MEM_callocN(sizeof(*rbo->shared), "RigidBodyOb_Shared");
1050
1051         /* set default settings */
1052         rbo->type = type;
1053
1054         rbo->mass = 1.0f;
1055
1056         rbo->friction = 0.5f; /* best when non-zero. 0.5 is Bullet default */
1057         rbo->restitution = 0.0f; /* best when zero. 0.0 is Bullet default */
1058
1059         rbo->margin = 0.04f; /* 0.04 (in meters) is Bullet default */
1060
1061         rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */
1062         rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */
1063
1064         rbo->lin_damping = 0.04f;
1065         rbo->ang_damping = 0.1f;
1066
1067         rbo->col_groups = 1;
1068
1069         /* use triangle meshes for passive objects
1070          * use convex hulls for active objects since dynamic triangle meshes are very unstable
1071          */
1072         if (type == RBO_TYPE_ACTIVE)
1073                 rbo->shape = RB_SHAPE_CONVEXH;
1074         else
1075                 rbo->shape = RB_SHAPE_TRIMESH;
1076
1077         rbo->mesh_source = RBO_MESH_DEFORM;
1078
1079         /* set initial transform */
1080         mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1081
1082         /* flag cache as outdated */
1083         BKE_rigidbody_cache_reset(rbw);
1084
1085         /* return this object */
1086         return rbo;
1087 }
1088
1089 /* Add rigid body constraint to the specified object */
1090 RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type)
1091 {
1092         RigidBodyCon *rbc;
1093         RigidBodyWorld *rbw = scene->rigidbody_world;
1094
1095         /* sanity checks
1096          *      - rigidbody world must exist
1097          *      - object must exist
1098          *      - cannot add constraint if it already exists
1099          */
1100         if (ob == NULL || (ob->rigidbody_constraint != NULL))
1101                 return NULL;
1102
1103         /* create new settings data, and link it up */
1104         rbc = MEM_callocN(sizeof(RigidBodyCon), "RigidBodyCon");
1105
1106         /* set default settings */
1107         rbc->type = type;
1108
1109         rbc->ob1 = NULL;
1110         rbc->ob2 = NULL;
1111
1112         rbc->flag |= RBC_FLAG_ENABLED;
1113         rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS;
1114
1115         rbc->spring_type = RBC_SPRING_TYPE2;
1116
1117         rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */
1118         rbc->num_solver_iterations = 10; /* 10 is Bullet default */
1119
1120         rbc->limit_lin_x_lower = -1.0f;
1121         rbc->limit_lin_x_upper = 1.0f;
1122         rbc->limit_lin_y_lower = -1.0f;
1123         rbc->limit_lin_y_upper = 1.0f;
1124         rbc->limit_lin_z_lower = -1.0f;
1125         rbc->limit_lin_z_upper = 1.0f;
1126         rbc->limit_ang_x_lower = -M_PI_4;
1127         rbc->limit_ang_x_upper = M_PI_4;
1128         rbc->limit_ang_y_lower = -M_PI_4;
1129         rbc->limit_ang_y_upper = M_PI_4;
1130         rbc->limit_ang_z_lower = -M_PI_4;
1131         rbc->limit_ang_z_upper = M_PI_4;
1132
1133         rbc->spring_damping_x = 0.5f;
1134         rbc->spring_damping_y = 0.5f;
1135         rbc->spring_damping_z = 0.5f;
1136         rbc->spring_damping_ang_x = 0.5f;
1137         rbc->spring_damping_ang_y = 0.5f;
1138         rbc->spring_damping_ang_z = 0.5f;
1139         rbc->spring_stiffness_x = 10.0f;
1140         rbc->spring_stiffness_y = 10.0f;
1141         rbc->spring_stiffness_z = 10.0f;
1142         rbc->spring_stiffness_ang_x = 10.0f;
1143         rbc->spring_stiffness_ang_y = 10.0f;
1144         rbc->spring_stiffness_ang_z = 10.0f;
1145
1146         rbc->motor_lin_max_impulse = 1.0f;
1147         rbc->motor_lin_target_velocity = 1.0f;
1148         rbc->motor_ang_max_impulse = 1.0f;
1149         rbc->motor_ang_target_velocity = 1.0f;
1150
1151         /* flag cache as outdated */
1152         BKE_rigidbody_cache_reset(rbw);
1153
1154         /* return this object */
1155         return rbc;
1156 }
1157
1158 /* ************************************** */
1159 /* Utilities API */
1160
1161 /* Get RigidBody world for the given scene, creating one if needed
1162  *
1163  * \param scene Scene to find active Rigid Body world for
1164  */
1165 RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene)
1166 {
1167         /* sanity check */
1168         if (scene == NULL)
1169                 return NULL;
1170
1171         return scene->rigidbody_world;
1172 }
1173
1174 void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob)
1175 {
1176         RigidBodyWorld *rbw = scene->rigidbody_world;
1177         RigidBodyCon *rbc;
1178         int i;
1179
1180         if (rbw) {
1181
1182                 /* remove object from array */
1183                 if (rbw && rbw->objects) {
1184                         for (i = 0; i < rbw->numbodies; i++) {
1185                                 if (rbw->objects[i] == ob) {
1186                                         rbw->objects[i] = NULL;
1187                                         break;
1188                                 }
1189                         }
1190                 }
1191
1192                 /* remove object from rigid body constraints */
1193                 if (rbw->constraints) {
1194                         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, obt)
1195                         {
1196                                 if (obt && obt->rigidbody_constraint) {
1197                                         rbc = obt->rigidbody_constraint;
1198                                         if (ELEM(ob, rbc->ob1, rbc->ob2)) {
1199                                                 BKE_rigidbody_remove_constraint(scene, obt);
1200                                         }
1201                                 }
1202                         }
1203                         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1204                 }
1205                 BKE_collection_object_remove(bmain, rbw->group, ob, false);
1206         }
1207
1208         /* remove object's settings */
1209         BKE_rigidbody_free_object(ob, rbw);
1210
1211         /* flag cache as outdated */
1212         BKE_rigidbody_cache_reset(rbw);
1213 }
1214
1215 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob)
1216 {
1217         RigidBodyWorld *rbw = scene->rigidbody_world;
1218         RigidBodyCon *rbc = ob->rigidbody_constraint;
1219
1220         /* remove from rigidbody world, free object won't do this */
1221         if (rbw && rbw->shared->physics_world && rbc->physics_constraint) {
1222                 RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
1223         }
1224         /* remove object's settings */
1225         BKE_rigidbody_free_constraint(ob);
1226
1227         /* flag cache as outdated */
1228         BKE_rigidbody_cache_reset(rbw);
1229 }
1230
1231
1232 /* ************************************** */
1233 /* Simulation Interface - Bullet */
1234
1235 /* Update object array and rigid body count so they're in sync with the rigid body group */
1236 static void rigidbody_update_ob_array(RigidBodyWorld *rbw)
1237 {
1238         if (rbw->group == NULL) {
1239                 rbw->numbodies = 0;
1240                 rbw->objects = realloc(rbw->objects, 0);
1241                 return;
1242         }
1243
1244         int n = 0;
1245         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1246         {
1247                 (void)object;
1248                 n++;
1249         }
1250         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1251
1252         if (rbw->numbodies != n) {
1253                 rbw->numbodies = n;
1254                 rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies);
1255         }
1256
1257         int i = 0;
1258         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1259         {
1260                 rbw->objects[i] = object;
1261                 i++;
1262         }
1263         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1264 }
1265
1266 static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
1267 {
1268         float adj_gravity[3];
1269
1270         /* adjust gravity to take effector weights into account */
1271         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
1272                 copy_v3_v3(adj_gravity, scene->physics_settings.gravity);
1273                 mul_v3_fl(adj_gravity, rbw->effector_weights->global_gravity * rbw->effector_weights->weight[0]);
1274         }
1275         else {
1276                 zero_v3(adj_gravity);
1277         }
1278
1279         /* update gravity, since this RNA setting is not part of RigidBody settings */
1280         RB_dworld_set_gravity(rbw->shared->physics_world, adj_gravity);
1281
1282         /* update object array in case there are changes */
1283         rigidbody_update_ob_array(rbw);
1284 }
1285
1286 static void rigidbody_update_sim_ob(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo)
1287 {
1288         float loc[3];
1289         float rot[4];
1290         float scale[3];
1291
1292         /* only update if rigid body exists */
1293         if (rbo->shared->physics_object == NULL)
1294                 return;
1295
1296         if (rbo->shape == RB_SHAPE_TRIMESH && rbo->flag & RBO_FLAG_USE_DEFORM) {
1297                 Mesh *mesh = ob->runtime.mesh_deform_eval;
1298                 if (mesh) {
1299                         MVert *mvert = mesh->mvert;
1300                         int totvert = mesh->totvert;
1301                         BoundBox *bb = BKE_object_boundbox_get(ob);
1302
1303                         RB_shape_trimesh_update(rbo->shared->physics_shape, (float *)mvert, totvert, sizeof(MVert), bb->vec[0], bb->vec[6]);
1304                 }
1305         }
1306
1307         mat4_decompose(loc, rot, scale, ob->obmat);
1308
1309         /* update scale for all objects */
1310         RB_body_set_scale(rbo->shared->physics_object, scale);
1311         /* compensate for embedded convex hull collision margin */
1312         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH)
1313                 RB_shape_set_margin(rbo->shared->physics_shape, RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
1314
1315         /* make transformed objects temporarily kinmatic so that they can be moved by the user during simulation */
1316         if (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ) {
1317                 RB_body_set_kinematic_state(rbo->shared->physics_object, true);
1318                 RB_body_set_mass(rbo->shared->physics_object, 0.0f);
1319         }
1320
1321         /* update rigid body location and rotation for kinematic bodies */
1322         if (rbo->flag & RBO_FLAG_KINEMATIC || (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1323                 RB_body_activate(rbo->shared->physics_object);
1324                 RB_body_set_loc_rot(rbo->shared->physics_object, loc, rot);
1325         }
1326         /* update influence of effectors - but don't do it on an effector */
1327         /* only dynamic bodies need effector update */
1328         else if (rbo->type == RBO_TYPE_ACTIVE && ((ob->pd == NULL) || (ob->pd->forcefield == PFIELD_NULL))) {
1329                 EffectorWeights *effector_weights = rbw->effector_weights;
1330                 EffectedPoint epoint;
1331                 ListBase *effectors;
1332
1333                 /* get effectors present in the group specified by effector_weights */
1334                 effectors = BKE_effectors_create(depsgraph, ob, NULL, effector_weights);
1335                 if (effectors) {
1336                         float eff_force[3] = {0.0f, 0.0f, 0.0f};
1337                         float eff_loc[3], eff_vel[3];
1338
1339                         /* create dummy 'point' which represents last known position of object as result of sim */
1340                         // XXX: this can create some inaccuracies with sim position, but is probably better than using unsimulated vals?
1341                         RB_body_get_position(rbo->shared->physics_object, eff_loc);
1342                         RB_body_get_linear_velocity(rbo->shared->physics_object, eff_vel);
1343
1344                         pd_point_from_loc(scene, eff_loc, eff_vel, 0, &epoint);
1345
1346                         /* calculate net force of effectors, and apply to sim object
1347                          *      - we use 'central force' since apply force requires a "relative position" which we don't have...
1348                          */
1349                         BKE_effectors_apply(effectors, NULL, effector_weights, &epoint, eff_force, NULL);
1350                         if (G.f & G_DEBUG)
1351                                 printf("\tapplying force (%f,%f,%f) to '%s'\n", eff_force[0], eff_force[1], eff_force[2], ob->id.name + 2);
1352                         /* activate object in case it is deactivated */
1353                         if (!is_zero_v3(eff_force))
1354                                 RB_body_activate(rbo->shared->physics_object);
1355                         RB_body_apply_central_force(rbo->shared->physics_object, eff_force);
1356                 }
1357                 else if (G.f & G_DEBUG)
1358                         printf("\tno forces to apply to '%s'\n", ob->id.name + 2);
1359
1360                 /* cleanup */
1361                 BKE_effectors_free(effectors);
1362         }
1363         /* NOTE: passive objects don't need to be updated since they don't move */
1364
1365         /* NOTE: no other settings need to be explicitly updated here,
1366          * since RNA setters take care of the rest :)
1367          */
1368 }
1369
1370 /**
1371  * Updates and validates world, bodies and shapes.
1372  *
1373  * \param rebuild Rebuild entire simulation
1374  */
1375 static void rigidbody_update_simulation(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, bool rebuild)
1376 {
1377         /* update world */
1378         if (rebuild)
1379                 BKE_rigidbody_validate_sim_world(scene, rbw, true);
1380         rigidbody_update_sim_world(scene, rbw);
1381
1382         /* XXX TODO For rebuild: remove all constraints first.
1383          * Otherwise we can end up deleting objects that are still
1384          * referenced by constraints, corrupting bullet's internal list.
1385          *
1386          * Memory management needs redesign here, this is just a dirty workaround.
1387          */
1388         if (rebuild && rbw->constraints) {
1389                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, ob)
1390                 {
1391                         RigidBodyCon *rbc = ob->rigidbody_constraint;
1392                         if (rbc && rbc->physics_constraint) {
1393                                 RB_dworld_remove_constraint(rbw->shared->physics_world, rbc->physics_constraint);
1394                                 RB_constraint_delete(rbc->physics_constraint);
1395                                 rbc->physics_constraint = NULL;
1396                         }
1397                 }
1398                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1399         }
1400
1401         /* update objects */
1402         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, ob)
1403         {
1404                 if (ob->type == OB_MESH) {
1405                         /* validate that we've got valid object set up here... */
1406                         RigidBodyOb *rbo = ob->rigidbody_object;
1407                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1408                         BKE_object_where_is_calc(depsgraph, scene, ob);
1409
1410                         if (rbo == NULL) {
1411                                 /* Since this object is included in the sim group but doesn't have
1412                                  * rigid body settings (perhaps it was added manually), add!
1413                                  *      - assume object to be active? That is the default for newly added settings...
1414                                  */
1415                                 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, RBO_TYPE_ACTIVE);
1416                                 rigidbody_validate_sim_object(rbw, ob, true);
1417
1418                                 rbo = ob->rigidbody_object;
1419                         }
1420                         else {
1421                                 /* perform simulation data updates as tagged */
1422                                 /* refresh object... */
1423                                 if (rebuild) {
1424                                         /* World has been rebuilt so rebuild object */
1425                                         /* TODO(Sybren): rigidbody_validate_sim_object() can call rigidbody_validate_sim_shape(),
1426                                          * but neither resets the RBO_FLAG_NEEDS_RESHAPE flag nor calls RB_body_set_collision_shape().
1427                                          * This results in the collision shape being created twice, which is unnecessary. */
1428                                         rigidbody_validate_sim_object(rbw, ob, true);
1429                                 }
1430                                 else if (rbo->flag & RBO_FLAG_NEEDS_VALIDATE) {
1431                                         rigidbody_validate_sim_object(rbw, ob, false);
1432                                 }
1433                                 /* refresh shape... */
1434                                 if (rbo->flag & RBO_FLAG_NEEDS_RESHAPE) {
1435                                         /* mesh/shape data changed, so force shape refresh */
1436                                         rigidbody_validate_sim_shape(ob, true);
1437                                         /* now tell RB sim about it */
1438                                         // XXX: we assume that this can only get applied for active/passive shapes that will be included as rigidbodies
1439                                         RB_body_set_collision_shape(rbo->shared->physics_object, rbo->shared->physics_shape);
1440                                 }
1441                                 rbo->flag &= ~(RBO_FLAG_NEEDS_VALIDATE | RBO_FLAG_NEEDS_RESHAPE);
1442                         }
1443
1444                         /* update simulation object... */
1445                         rigidbody_update_sim_ob(depsgraph, scene, rbw, ob, rbo);
1446                 }
1447         }
1448         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1449
1450         /* update constraints */
1451         if (rbw->constraints == NULL) /* no constraints, move on */
1452                 return;
1453
1454         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, ob)
1455         {
1456                 /* validate that we've got valid object set up here... */
1457                 RigidBodyCon *rbc = ob->rigidbody_constraint;
1458                 /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1459                 BKE_object_where_is_calc(depsgraph, scene, ob);
1460
1461                 if (rbc == NULL) {
1462                         /* Since this object is included in the group but doesn't have
1463                          * constraint settings (perhaps it was added manually), add!
1464                          */
1465                         ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, RBC_TYPE_FIXED);
1466                         rigidbody_validate_sim_constraint(rbw, ob, true);
1467
1468                         rbc = ob->rigidbody_constraint;
1469                 }
1470                 else {
1471                         /* perform simulation data updates as tagged */
1472                         if (rebuild) {
1473                                 /* World has been rebuilt so rebuild constraint */
1474                                 rigidbody_validate_sim_constraint(rbw, ob, true);
1475                         }
1476                         else if (rbc->flag & RBC_FLAG_NEEDS_VALIDATE) {
1477                                 rigidbody_validate_sim_constraint(rbw, ob, false);
1478                         }
1479                         rbc->flag &= ~RBC_FLAG_NEEDS_VALIDATE;
1480                 }
1481         }
1482         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1483 }
1484
1485 static void rigidbody_update_simulation_post_step(Depsgraph *depsgraph, RigidBodyWorld *rbw)
1486 {
1487         ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1488
1489         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, ob)
1490         {
1491                 Base *base = BKE_view_layer_base_find(view_layer, ob);
1492                 RigidBodyOb *rbo = ob->rigidbody_object;
1493                 /* Reset kinematic state for transformed objects. */
1494                 if (rbo && base && (base->flag & BASE_SELECTED) && (G.moving & G_TRANSFORM_OBJ)) {
1495                         RB_body_set_kinematic_state(rbo->shared->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
1496                         RB_body_set_mass(rbo->shared->physics_object, RBO_GET_MASS(rbo));
1497                         /* Deactivate passive objects so they don't interfere with deactivation of active objects. */
1498                         if (rbo->type == RBO_TYPE_PASSIVE)
1499                                 RB_body_deactivate(rbo->shared->physics_object);
1500                 }
1501         }
1502         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1503 }
1504
1505 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime)
1506 {
1507         return (rbw && (rbw->flag & RBW_FLAG_MUTED) == 0 && ctime > rbw->shared->pointcache->startframe);
1508 }
1509
1510 /* Sync rigid body and object transformations */
1511 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime)
1512 {
1513         RigidBodyOb *rbo = ob->rigidbody_object;
1514
1515         /* keep original transform for kinematic and passive objects */
1516         if (ELEM(NULL, rbw, rbo) || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE)
1517                 return;
1518
1519         /* use rigid body transform after cache start frame if objects is not being transformed */
1520         if (BKE_rigidbody_check_sim_running(rbw, ctime) && !(ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1521                 float mat[4][4], size_mat[4][4], size[3];
1522
1523                 normalize_qt(rbo->orn); // RB_TODO investigate why quaternion isn't normalized at this point
1524                 quat_to_mat4(mat, rbo->orn);
1525                 copy_v3_v3(mat[3], rbo->pos);
1526
1527                 mat4_to_size(size, ob->obmat);
1528                 size_to_mat4(size_mat, size);
1529                 mul_m4_m4m4(mat, mat, size_mat);
1530
1531                 copy_m4_m4(ob->obmat, mat);
1532         }
1533         /* otherwise set rigid body transform to current obmat */
1534         else {
1535                 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1536         }
1537 }
1538
1539 /* Used when canceling transforms - return rigidbody and object to initial states */
1540 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
1541 {
1542         RigidBodyOb *rbo = ob->rigidbody_object;
1543         bool correct_delta = !(rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE);
1544
1545         /* return rigid body and object to their initial states */
1546         copy_v3_v3(rbo->pos, ob->loc);
1547         copy_v3_v3(ob->loc, loc);
1548
1549         if (correct_delta) {
1550                 add_v3_v3(rbo->pos, ob->dloc);
1551         }
1552
1553         if (ob->rotmode > 0) {
1554                 float qt[4];
1555                 eulO_to_quat(qt, ob->rot, ob->rotmode);
1556
1557                 if (correct_delta) {
1558                         float dquat[4];
1559                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1560
1561                         mul_qt_qtqt(rbo->orn, dquat, qt);
1562                 }
1563                 else {
1564                         copy_qt_qt(rbo->orn, qt);
1565                 }
1566
1567                 copy_v3_v3(ob->rot, rot);
1568         }
1569         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1570                 float qt[4];
1571                 axis_angle_to_quat(qt, ob->rotAxis, ob->rotAngle);
1572
1573                 if (correct_delta) {
1574                         float dquat[4];
1575                         axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
1576
1577                         mul_qt_qtqt(rbo->orn, dquat, qt);
1578                 }
1579                 else {
1580                         copy_qt_qt(rbo->orn, qt);
1581                 }
1582
1583                 copy_v3_v3(ob->rotAxis, rotAxis);
1584                 ob->rotAngle = rotAngle;
1585         }
1586         else {
1587                 if (correct_delta) {
1588                         mul_qt_qtqt(rbo->orn, ob->dquat, ob->quat);
1589                 }
1590                 else {
1591                         copy_qt_qt(rbo->orn, ob->quat);
1592                 }
1593
1594                 copy_qt_qt(ob->quat, quat);
1595         }
1596
1597         if (rbo->shared->physics_object) {
1598                 /* allow passive objects to return to original transform */
1599                 if (rbo->type == RBO_TYPE_PASSIVE)
1600                         RB_body_set_kinematic_state(rbo->shared->physics_object, true);
1601                 RB_body_set_loc_rot(rbo->shared->physics_object, rbo->pos, rbo->orn);
1602         }
1603         // 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)
1604 }
1605
1606 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw)
1607 {
1608         if (rbw) {
1609                 rbw->shared->pointcache->flag |= PTCACHE_OUTDATED;
1610         }
1611 }
1612
1613 /* ------------------ */
1614
1615 /* Rebuild rigid body world */
1616 /* NOTE: this needs to be called before frame update to work correctly */
1617 void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime)
1618 {
1619         RigidBodyWorld *rbw = scene->rigidbody_world;
1620         PointCache *cache;
1621         PTCacheID pid;
1622         int startframe, endframe;
1623
1624         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1625         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1626         cache = rbw->shared->pointcache;
1627
1628         /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */
1629         int n = 0;
1630         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1631         {
1632                 (void)object;
1633                 n++;
1634         }
1635         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1636
1637         if (rbw->shared->physics_world == NULL || rbw->numbodies != n) {
1638                 cache->flag |= PTCACHE_OUTDATED;
1639         }
1640
1641         if (ctime == startframe + 1 && rbw->ltime == startframe) {
1642                 if (cache->flag & PTCACHE_OUTDATED) {
1643                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1644                         rigidbody_update_simulation(depsgraph, scene, rbw, true);
1645                         BKE_ptcache_validate(cache, (int)ctime);
1646                         cache->last_exact = 0;
1647                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1648                 }
1649         }
1650 }
1651
1652 /* Run RigidBody simulation for the specified physics world */
1653 void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime)
1654 {
1655         float timestep;
1656         RigidBodyWorld *rbw = scene->rigidbody_world;
1657         PointCache *cache;
1658         PTCacheID pid;
1659         int startframe, endframe;
1660
1661         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1662         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1663         cache = rbw->shared->pointcache;
1664
1665         if (ctime <= startframe) {
1666                 rbw->ltime = startframe;
1667                 return;
1668         }
1669         /* make sure we don't go out of cache frame range */
1670         else if (ctime > endframe) {
1671                 ctime = endframe;
1672         }
1673
1674         /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */
1675         if (rbw->shared->physics_world == NULL && !(cache->flag & PTCACHE_BAKED))
1676                 return;
1677         else if (rbw->objects == NULL)
1678                 rigidbody_update_ob_array(rbw);
1679
1680         /* try to read from cache */
1681         // RB_TODO deal with interpolated, old and baked results
1682         bool can_simulate = (ctime == rbw->ltime + 1) && !(cache->flag & PTCACHE_BAKED);
1683
1684         if (BKE_ptcache_read(&pid, ctime, can_simulate) == PTCACHE_READ_EXACT) {
1685                 BKE_ptcache_validate(cache, (int)ctime);
1686                 rbw->ltime = ctime;
1687                 return;
1688         }
1689
1690         if (!DEG_is_active(depsgraph)) {
1691                 /* When the depsgraph is inactive we should neither write to the cache
1692                  * nor run the simulation. */
1693                 return;
1694         }
1695
1696         /* advance simulation, we can only step one frame forward */
1697         if (compare_ff_relative(ctime, rbw->ltime + 1, FLT_EPSILON, 64)) {
1698                 /* write cache for first frame when on second frame */
1699                 if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
1700                         BKE_ptcache_write(&pid, startframe);
1701                 }
1702
1703                 /* update and validate simulation */
1704                 rigidbody_update_simulation(depsgraph, scene, rbw, false);
1705
1706                 /* calculate how much time elapsed since last step in seconds */
1707                 timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale;
1708                 /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */
1709                 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));
1710
1711                 rigidbody_update_simulation_post_step(depsgraph, rbw);
1712
1713                 /* write cache for current frame */
1714                 BKE_ptcache_validate(cache, (int)ctime);
1715                 BKE_ptcache_write(&pid, (unsigned int)ctime);
1716
1717                 rbw->ltime = ctime;
1718         }
1719 }
1720 /* ************************************** */
1721
1722 #else  /* WITH_BULLET */
1723
1724 /* stubs */
1725 #if defined(__GNUC__) || defined(__clang__)
1726 #  pragma GCC diagnostic push
1727 #  pragma GCC diagnostic ignored "-Wunused-parameter"
1728 #endif
1729
1730 struct RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob, const int flag) { return NULL; }
1731 struct RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int flag) { return NULL; }
1732 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild) {}
1733 void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) { if (r_vol) *r_vol = 0.0f; }
1734 void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) { zero_v3(r_center); }
1735 struct RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) { return NULL; }
1736 struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag) { return NULL; }
1737 void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw) {}
1738 void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata) {}
1739 struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; }
1740 struct RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type) { return NULL; }
1741 struct RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { return NULL; }
1742 void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob) {}
1743 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) {}
1744 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) {}
1745 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) {}
1746 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime) { return false; }
1747 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) {}
1748 void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime) {}
1749 void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime) {}
1750
1751 #if defined(__GNUC__) || defined(__clang__)
1752 #  pragma GCC diagnostic pop
1753 #endif
1754
1755 #endif  /* WITH_BULLET */
1756
1757
1758
1759 /* -------------------- */
1760 /* Depsgraph evaluation */
1761
1762 void BKE_rigidbody_rebuild_sim(Depsgraph *depsgraph,
1763                                Scene *scene)
1764 {
1765         float ctime = DEG_get_ctime(depsgraph);
1766         DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime);
1767         /* rebuild sim data (i.e. after resetting to start of timeline) */
1768         if (BKE_scene_check_rigidbody_active(scene)) {
1769                 BKE_rigidbody_rebuild_world(depsgraph, scene, ctime);
1770         }
1771 }
1772
1773 void BKE_rigidbody_eval_simulation(Depsgraph *depsgraph,
1774                                    Scene *scene)
1775 {
1776         float ctime = DEG_get_ctime(depsgraph);
1777         DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime);
1778
1779         /* evaluate rigidbody sim */
1780         if (!BKE_scene_check_rigidbody_active(scene)) {
1781                 return;
1782         }
1783         BKE_rigidbody_do_simulation(depsgraph, scene, ctime);
1784 }
1785
1786 void BKE_rigidbody_object_sync_transforms(Depsgraph *depsgraph,
1787                                           Scene *scene,
1788                                           Object *ob)
1789 {
1790         RigidBodyWorld *rbw = scene->rigidbody_world;
1791         float ctime = DEG_get_ctime(depsgraph);
1792         DEG_debug_print_eval_time(depsgraph, __func__, ob->id.name, ob, ctime);
1793         /* read values pushed into RBO from sim/cache... */
1794         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
1795 }