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