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