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