Rigidbody: Add option to choose mesh source for collision shapes
[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_anim_types.h"
50 #include "DNA_group_types.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_object_types.h"
54 #include "DNA_object_force.h"
55 #include "DNA_rigidbody_types.h"
56 #include "DNA_scene_types.h"
57
58 #include "BKE_animsys.h"
59 #include "BKE_cdderivedmesh.h"
60 #include "BKE_effect.h"
61 #include "BKE_global.h"
62 #include "BKE_group.h"
63 #include "BKE_library.h"
64 #include "BKE_mesh.h"
65 #include "BKE_object.h"
66 #include "BKE_pointcache.h"
67 #include "BKE_rigidbody.h"
68 #include "BKE_utildefines.h"
69
70 #include "RNA_access.h"
71
72 #ifdef WITH_BULLET
73
74 /* ************************************** */
75 /* Memory Management */
76
77 /* Freeing Methods --------------------- */
78
79 /* Free rigidbody world */
80 void BKE_rigidbody_free_world(RigidBodyWorld *rbw)
81 {
82         /* sanity check */
83         if (!rbw)
84                 return;
85
86         if (rbw->physics_world) {
87                 /* free physics references, we assume that all physics objects in will have been added to the world */
88                 GroupObject *go;
89                 if (rbw->constraints) {
90                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
91                                 if (go->ob && go->ob->rigidbody_constraint) {
92                                         RigidBodyCon *rbc = go->ob->rigidbody_constraint;
93
94                                         if (rbc->physics_constraint)
95                                                 RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
96                                 }
97                         }
98                 }
99                 if (rbw->group) {
100                         for (go = rbw->group->gobject.first; go; go = go->next) {
101                                 if (go->ob && go->ob->rigidbody_object) {
102                                         RigidBodyOb *rbo = go->ob->rigidbody_object;
103
104                                         if (rbo->physics_object)
105                                                 RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
106                                 }
107                         }
108                 }
109                 /* free dynamics world */
110                 RB_dworld_delete(rbw->physics_world);
111         }
112         if (rbw->objects)
113                 free(rbw->objects);
114
115         /* free cache */
116         BKE_ptcache_free_list(&(rbw->ptcaches));
117         rbw->pointcache = NULL;
118
119         /* free effector weights */
120         if (rbw->effector_weights)
121                 MEM_freeN(rbw->effector_weights);
122
123         /* free rigidbody world itself */
124         MEM_freeN(rbw);
125 }
126
127 /* Free RigidBody settings and sim instances */
128 void BKE_rigidbody_free_object(Object *ob)
129 {
130         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
131
132         /* sanity check */
133         if (rbo == NULL)
134                 return;
135
136         /* free physics references */
137         if (rbo->physics_object) {
138                 RB_body_delete(rbo->physics_object);
139                 rbo->physics_object = NULL;
140         }
141
142         if (rbo->physics_shape) {
143                 RB_shape_delete(rbo->physics_shape);
144                 rbo->physics_shape = NULL;
145         }
146
147         /* free data itself */
148         MEM_freeN(rbo);
149         ob->rigidbody_object = NULL;
150 }
151
152 /* Free RigidBody constraint and sim instance */
153 void BKE_rigidbody_free_constraint(Object *ob)
154 {
155         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
156
157         /* sanity check */
158         if (rbc == NULL)
159                 return;
160
161         /* free physics reference */
162         if (rbc->physics_constraint) {
163                 RB_constraint_delete(rbc->physics_constraint);
164                 rbc->physics_constraint = NULL;
165         }
166
167         /* free data itself */
168         MEM_freeN(rbc);
169         ob->rigidbody_constraint = NULL;
170 }
171
172 /* Copying Methods --------------------- */
173
174 /* These just copy the data, clearing out references to physics objects.
175  * Anything that uses them MUST verify that the copied object will
176  * be added to relevant groups later...
177  */
178
179 RigidBodyOb *BKE_rigidbody_copy_object(Object *ob)
180 {
181         RigidBodyOb *rboN = NULL;
182
183         if (ob->rigidbody_object) {
184                 /* just duplicate the whole struct first (to catch all the settings) */
185                 rboN = MEM_dupallocN(ob->rigidbody_object);
186
187                 /* tag object as needing to be verified */
188                 rboN->flag |= RBO_FLAG_NEEDS_VALIDATE;
189
190                 /* clear out all the fields which need to be revalidated later */
191                 rboN->physics_object = NULL;
192                 rboN->physics_shape = NULL;
193         }
194
195         /* return new copy of settings */
196         return rboN;
197 }
198
199 RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob)
200 {
201         RigidBodyCon *rbcN = NULL;
202
203         if (ob->rigidbody_constraint) {
204                 /* just duplicate the whole struct first (to catch all the settings) */
205                 rbcN = MEM_dupallocN(ob->rigidbody_constraint);
206
207                 /* tag object as needing to be verified */
208                 rbcN->flag |= RBC_FLAG_NEEDS_VALIDATE;
209
210                 /* clear out all the fields which need to be revalidated later */
211                 rbcN->physics_constraint = NULL;
212         }
213
214         /* return new copy of settings */
215         return rbcN;
216 }
217
218 /* preserve relationships between constraints and rigid bodies after duplication */
219 void BKE_rigidbody_relink_constraint(RigidBodyCon *rbc)
220 {
221         ID_NEW(rbc->ob1);
222         ID_NEW(rbc->ob2);
223 }
224
225 /* ************************************** */
226 /* Setup Utilities - Validate Sim Instances */
227
228 /* get the appropriate DerivedMesh based on rigid body mesh source */
229 static DerivedMesh *rigidbody_get_mesh(Object *ob)
230 {
231         if (ob->rigidbody_object->mesh_source == RBO_MESH_DEFORM) {
232                 return ob->derivedDeform;
233         }
234         else if (ob->rigidbody_object->mesh_source == RBO_MESH_FINAL) {
235                 return ob->derivedFinal;
236         }
237         else {
238                 return CDDM_from_mesh(ob->data);
239         }
240 }
241
242 /* create collision shape of mesh - convex hull */
243 static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, float margin, bool *can_embed)
244 {
245         rbCollisionShape *shape = NULL;
246         DerivedMesh *dm = NULL;
247         MVert *mvert = NULL;
248         int totvert = 0;
249
250         if (ob->type == OB_MESH && ob->data) {
251                 dm = rigidbody_get_mesh(ob);
252                 mvert   = (dm) ? dm->getVertArray(dm) : NULL;
253                 totvert = (dm) ? dm->getNumVerts(dm) : 0;
254         }
255         else {
256                 printf("ERROR: cannot make Convex Hull collision shape for non-Mesh object\n");
257         }
258
259         if (totvert) {
260                 shape = RB_shape_new_convex_hull((float *)mvert, sizeof(MVert), totvert, margin, can_embed);
261         }
262         else {
263                 printf("ERROR: no vertices to define Convex Hull collision shape with\n");
264         }
265
266         if (dm && ob->rigidbody_object->mesh_source == RBO_MESH_BASE)
267                 dm->release(dm);
268
269         return shape;
270 }
271
272 /* create collision shape of mesh - triangulated mesh
273  * returns NULL if creation fails.
274  */
275 static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob)
276 {
277         rbCollisionShape *shape = NULL;
278
279         if (ob->type == OB_MESH) {
280                 DerivedMesh *dm = NULL;
281                 MVert *mvert;
282                 MFace *mface;
283                 int totvert;
284                 int totface;
285
286                 dm = rigidbody_get_mesh(ob);
287
288                 /* ensure mesh validity, then grab data */
289                 if (dm == NULL)
290                         return NULL;
291
292                 DM_ensure_tessface(dm);
293
294                 mvert   = (dm) ? dm->getVertArray(dm) : NULL;
295                 totvert = (dm) ? dm->getNumVerts(dm) : 0;
296                 mface   = (dm) ? dm->getTessFaceArray(dm) : NULL;
297                 totface = (dm) ? dm->getNumTessFaces(dm) : 0;
298
299                 /* sanity checking - potential case when no data will be present */
300                 if ((totvert == 0) || (totface == 0)) {
301                         printf("WARNING: no geometry data converted for Mesh Collision Shape (ob = %s)\n", ob->id.name + 2);
302                 }
303                 else {
304                         rbMeshData *mdata;
305                         int i;
306
307                         /* init mesh data for collision shape */
308                         mdata = RB_trimesh_data_new();
309
310                         /* loop over all faces, adding them as triangles to the collision shape
311                          * (so for some faces, more than triangle will get added)
312                          */
313                         for (i = 0; (i < totface) && (mface) && (mvert); i++, mface++) {
314                                 /* add first triangle - verts 1,2,3 */
315                                 {
316                                         MVert *va = (mface->v1 < totvert) ? (mvert + mface->v1) : (mvert);
317                                         MVert *vb = (mface->v2 < totvert) ? (mvert + mface->v2) : (mvert);
318                                         MVert *vc = (mface->v3 < totvert) ? (mvert + mface->v3) : (mvert);
319
320                                         RB_trimesh_add_triangle(mdata, va->co, vb->co, vc->co);
321                                 }
322
323                                 /* add second triangle if needed - verts 1,3,4 */
324                                 if (mface->v4) {
325                                         MVert *va = (mface->v1 < totvert) ? (mvert + mface->v1) : (mvert);
326                                         MVert *vb = (mface->v3 < totvert) ? (mvert + mface->v3) : (mvert);
327                                         MVert *vc = (mface->v4 < totvert) ? (mvert + mface->v4) : (mvert);
328
329                                         RB_trimesh_add_triangle(mdata, va->co, vb->co, vc->co);
330                                 }
331                         }
332
333                         /* construct collision shape
334                          *
335                          * These have been chosen to get better speed/accuracy tradeoffs with regards
336                          * to limitations of each:
337                          *    - BVH-Triangle Mesh: for passive objects only. Despite having greater
338                          *                         speed/accuracy, they cannot be used for moving objects.
339                          *    - GImpact Mesh:      for active objects. These are slower and less stable,
340                          *                         but are more flexible for general usage.
341                          */
342                         if (ob->rigidbody_object->type == RBO_TYPE_PASSIVE) {
343                                 shape = RB_shape_new_trimesh(mdata);
344                         }
345                         else {
346                                 shape = RB_shape_new_gimpact_mesh(mdata);
347                         }
348                 }
349
350                 /* cleanup temp data */
351                 if (dm && ob->rigidbody_object->mesh_source == RBO_MESH_BASE) {
352                         dm->release(dm);
353                 }
354         }
355         else {
356                 printf("ERROR: cannot make Triangular Mesh collision shape for non-Mesh object\n");
357         }
358
359         return shape;
360 }
361
362 /* Create new physics sim collision shape for object and store it,
363  * or remove the existing one first and replace...
364  */
365 void BKE_rigidbody_validate_sim_shape(Object *ob, short rebuild)
366 {
367         RigidBodyOb *rbo = ob->rigidbody_object;
368         rbCollisionShape *new_shape = NULL;
369         BoundBox *bb = NULL;
370         float size[3] = {1.0f, 1.0f, 1.0f};
371         float radius = 1.0f;
372         float height = 1.0f;
373         float capsule_height;
374         float hull_margin = 0.0f;
375         bool can_embed = true;
376         bool has_volume;
377
378         /* sanity check */
379         if (rbo == NULL)
380                 return;
381
382         /* don't create a new shape if we already have one and don't want to rebuild it */
383         if (rbo->physics_shape && !rebuild)
384                 return;
385
386         /* if automatically determining dimensions, use the Object's boundbox
387          *      - assume that all quadrics are standing upright on local z-axis
388          *      - assume even distribution of mass around the Object's pivot
389          *        (i.e. Object pivot is centralized in boundbox)
390          */
391         // XXX: all dimensions are auto-determined now... later can add stored settings for this
392         /* get object dimensions without scaling */
393         bb = BKE_object_boundbox_get(ob);
394         if (bb) {
395                 size[0] = (bb->vec[4][0] - bb->vec[0][0]);
396                 size[1] = (bb->vec[2][1] - bb->vec[0][1]);
397                 size[2] = (bb->vec[1][2] - bb->vec[0][2]);
398         }
399         mul_v3_fl(size, 0.5f);
400
401         if (ELEM3(rbo->shape, RB_SHAPE_CAPSULE, RB_SHAPE_CYLINDER, RB_SHAPE_CONE)) {
402                 /* take radius as largest x/y dimension, and height as z-dimension */
403                 radius = MAX2(size[0], size[1]);
404                 height = size[2];
405         }
406         else if (rbo->shape == RB_SHAPE_SPHERE) {
407                 /* take radius to the the largest dimension to try and encompass everything */
408                 radius = MAX3(size[0], size[1], size[2]);
409         }
410
411         /* create new shape */
412         switch (rbo->shape) {
413                 case RB_SHAPE_BOX:
414                         new_shape = RB_shape_new_box(size[0], size[1], size[2]);
415                         break;
416
417                 case RB_SHAPE_SPHERE:
418                         new_shape = RB_shape_new_sphere(radius);
419                         break;
420
421                 case RB_SHAPE_CAPSULE:
422                         capsule_height = (height - radius) * 2.0f;
423                         new_shape = RB_shape_new_capsule(radius, (capsule_height > 0.0f) ? capsule_height : 0.0f);
424                         break;
425                 case RB_SHAPE_CYLINDER:
426                         new_shape = RB_shape_new_cylinder(radius, height);
427                         break;
428                 case RB_SHAPE_CONE:
429                         new_shape = RB_shape_new_cone(radius, height * 2.0f);
430                         break;
431
432                 case RB_SHAPE_CONVEXH:
433                         /* try to emged collision margin */
434                         has_volume = (MIN3(size[0], size[1], size[2]) > 0.0f);
435
436                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && has_volume)
437                                 hull_margin = 0.04f;
438                         new_shape = rigidbody_get_shape_convexhull_from_mesh(ob, hull_margin, &can_embed);
439                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN))
440                                 rbo->margin = (can_embed && has_volume) ? 0.04f : 0.0f;  /* RB_TODO ideally we shouldn't directly change the margin here */
441                         break;
442                 case RB_SHAPE_TRIMESH:
443                         new_shape = rigidbody_get_shape_trimesh_from_mesh(ob);
444                         break;
445         }
446         /* assign new collision shape if creation was successful */
447         if (new_shape) {
448                 if (rbo->physics_shape)
449                         RB_shape_delete(rbo->physics_shape);
450                 rbo->physics_shape = new_shape;
451                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo));
452         }
453         /* use box shape if we can't fall back to old shape */
454         else if (rbo->physics_shape == NULL) {
455                 rbo->shape = RB_SHAPE_BOX;
456                 BKE_rigidbody_validate_sim_shape(ob, true);
457         }
458 }
459
460 /* --------------------- */
461
462 /* Create physics sim representation of object given RigidBody settings
463  * < rebuild: even if an instance already exists, replace it
464  */
465 void BKE_rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, short rebuild)
466 {
467         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
468         float loc[3];
469         float rot[4];
470
471         /* sanity checks:
472          *      - object doesn't have RigidBody info already: then why is it here?
473          */
474         if (rbo == NULL)
475                 return;
476
477         /* make sure collision shape exists */
478         /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects, but it's needed for constraints to update correctly */
479         if (rbo->physics_shape == NULL || rebuild)
480                 BKE_rigidbody_validate_sim_shape(ob, true);
481
482         if (rbo->physics_object) {
483                 if (rebuild == false)
484                         RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
485         }
486         if (!rbo->physics_object || rebuild) {
487                 /* remove rigid body if it already exists before creating a new one */
488                 if (rbo->physics_object) {
489                         RB_body_delete(rbo->physics_object);
490                 }
491
492                 mat4_to_loc_quat(loc, rot, ob->obmat);
493
494                 rbo->physics_object = RB_body_new(rbo->physics_shape, loc, rot);
495
496                 RB_body_set_friction(rbo->physics_object, rbo->friction);
497                 RB_body_set_restitution(rbo->physics_object, rbo->restitution);
498
499                 RB_body_set_damping(rbo->physics_object, rbo->lin_damping, rbo->ang_damping);
500                 RB_body_set_sleep_thresh(rbo->physics_object, rbo->lin_sleep_thresh, rbo->ang_sleep_thresh);
501                 RB_body_set_activation_state(rbo->physics_object, rbo->flag & RBO_FLAG_USE_DEACTIVATION);
502
503                 if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED)
504                         RB_body_deactivate(rbo->physics_object);
505
506
507                 RB_body_set_linear_factor(rbo->physics_object,
508                                           (ob->protectflag & OB_LOCK_LOCX) == 0,
509                                           (ob->protectflag & OB_LOCK_LOCY) == 0,
510                                           (ob->protectflag & OB_LOCK_LOCZ) == 0);
511                 RB_body_set_angular_factor(rbo->physics_object,
512                                            (ob->protectflag & OB_LOCK_ROTX) == 0,
513                                            (ob->protectflag & OB_LOCK_ROTY) == 0,
514                                            (ob->protectflag & OB_LOCK_ROTZ) == 0);
515
516                 RB_body_set_mass(rbo->physics_object, RBO_GET_MASS(rbo));
517                 RB_body_set_kinematic_state(rbo->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
518         }
519
520         if (rbw && rbw->physics_world)
521                 RB_dworld_add_body(rbw->physics_world, rbo->physics_object, rbo->col_groups);
522 }
523
524 /* --------------------- */
525
526 /* Create physics sim representation of constraint given rigid body constraint settings
527  * < rebuild: even if an instance already exists, replace it
528  */
529 void BKE_rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, short rebuild)
530 {
531         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
532         float loc[3];
533         float rot[4];
534         float lin_lower;
535         float lin_upper;
536         float ang_lower;
537         float ang_upper;
538
539         /* sanity checks:
540          *      - object should have a rigid body constraint
541          *  - rigid body constraint should have at least one constrained object
542          */
543         if (rbc == NULL) {
544                 return;
545         }
546
547         if (ELEM4(NULL, rbc->ob1, rbc->ob1->rigidbody_object, rbc->ob2, rbc->ob2->rigidbody_object)) {
548                 if (rbc->physics_constraint) {
549                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
550                         RB_constraint_delete(rbc->physics_constraint);
551                         rbc->physics_constraint = NULL;
552                 }
553                 return;
554         }
555
556         if (rbc->physics_constraint) {
557                 if (rebuild == false)
558                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
559         }
560         if (rbc->physics_constraint == NULL || rebuild) {
561                 rbRigidBody *rb1 = rbc->ob1->rigidbody_object->physics_object;
562                 rbRigidBody *rb2 = rbc->ob2->rigidbody_object->physics_object;
563
564                 /* remove constraint if it already exists before creating a new one */
565                 if (rbc->physics_constraint) {
566                         RB_constraint_delete(rbc->physics_constraint);
567                         rbc->physics_constraint = NULL;
568                 }
569
570                 mat4_to_loc_quat(loc, rot, ob->obmat);
571
572                 if (rb1 && rb2) {
573                         switch (rbc->type) {
574                                 case RBC_TYPE_POINT:
575                                         rbc->physics_constraint = RB_constraint_new_point(loc, rb1, rb2);
576                                         break;
577                                 case RBC_TYPE_FIXED:
578                                         rbc->physics_constraint = RB_constraint_new_fixed(loc, rot, rb1, rb2);
579                                         break;
580                                 case RBC_TYPE_HINGE:
581                                         rbc->physics_constraint = RB_constraint_new_hinge(loc, rot, rb1, rb2);
582                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
583                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
584                                         }
585                                         else
586                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, 0.0f, -1.0f);
587                                         break;
588                                 case RBC_TYPE_SLIDER:
589                                         rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2);
590                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
591                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
592                                         else
593                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, 0.0f, -1.0f);
594                                         break;
595                                 case RBC_TYPE_PISTON:
596                                         rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2);
597                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
598                                                 lin_lower = rbc->limit_lin_x_lower;
599                                                 lin_upper = rbc->limit_lin_x_upper;
600                                         }
601                                         else {
602                                                 lin_lower = 0.0f;
603                                                 lin_upper = -1.0f;
604                                         }
605                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
606                                                 ang_lower = rbc->limit_ang_x_lower;
607                                                 ang_upper = rbc->limit_ang_x_upper;
608                                         }
609                                         else {
610                                                 ang_lower = 0.0f;
611                                                 ang_upper = -1.0f;
612                                         }
613                                         RB_constraint_set_limits_piston(rbc->physics_constraint, lin_lower, lin_upper, ang_lower, ang_upper);
614                                         break;
615                                 case RBC_TYPE_6DOF_SPRING:
616                                         rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2);
617
618                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->flag & RBC_FLAG_USE_SPRING_X);
619                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_stiffness_x);
620                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_damping_x);
621
622                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->flag & RBC_FLAG_USE_SPRING_Y);
623                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_stiffness_y);
624                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_damping_y);
625
626                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->flag & RBC_FLAG_USE_SPRING_Z);
627                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_stiffness_z);
628                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_damping_z);
629
630                                         RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint);
631                                         /* fall-through */
632                                 case RBC_TYPE_6DOF:
633                                         if (rbc->type == RBC_TYPE_6DOF) /* a litte awkward but avoids duplicate code for limits */
634                                                 rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
635
636                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
637                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
638                                         else
639                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
640
641                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
642                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
643                                         else
644                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
645
646                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
647                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
648                                         else
649                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
650
651                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
652                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
653                                         else
654                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
655
656                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
657                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
658                                         else
659                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
660
661                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
662                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
663                                         else
664                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
665                                         break;
666                                 case RBC_TYPE_MOTOR:
667                                         rbc->physics_constraint = RB_constraint_new_motor(loc, rot, rb1, rb2);
668
669                                         RB_constraint_set_enable_motor(rbc->physics_constraint, rbc->flag & RBC_FLAG_USE_MOTOR_LIN, rbc->flag & RBC_FLAG_USE_MOTOR_ANG);
670                                         RB_constraint_set_max_impulse_motor(rbc->physics_constraint, rbc->motor_lin_max_impulse, rbc->motor_ang_max_impulse);
671                                         RB_constraint_set_target_velocity_motor(rbc->physics_constraint, rbc->motor_lin_target_velocity, rbc->motor_ang_target_velocity);
672                                         break;
673                         }
674                 }
675                 else { /* can't create constraint without both rigid bodies */
676                         return;
677                 }
678
679                 RB_constraint_set_enabled(rbc->physics_constraint, rbc->flag & RBC_FLAG_ENABLED);
680
681                 if (rbc->flag & RBC_FLAG_USE_BREAKING)
682                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, rbc->breaking_threshold);
683                 else
684                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, FLT_MAX);
685
686                 if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS)
687                         RB_constraint_set_solver_iterations(rbc->physics_constraint, rbc->num_solver_iterations);
688                 else
689                         RB_constraint_set_solver_iterations(rbc->physics_constraint, -1);
690         }
691
692         if (rbw && rbw->physics_world && rbc->physics_constraint) {
693                 RB_dworld_add_constraint(rbw->physics_world, rbc->physics_constraint, rbc->flag & RBC_FLAG_DISABLE_COLLISIONS);
694         }
695 }
696
697 /* --------------------- */
698
699 /* Create physics sim world given RigidBody world settings */
700 // NOTE: this does NOT update object references that the scene uses, in case those aren't ready yet!
701 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, short rebuild)
702 {
703         /* sanity checks */
704         if (rbw == NULL)
705                 return;
706
707         /* create new sim world */
708         if (rebuild || rbw->physics_world == NULL) {
709                 if (rbw->physics_world)
710                         RB_dworld_delete(rbw->physics_world);
711                 rbw->physics_world = RB_dworld_new(scene->physics_settings.gravity);
712         }
713
714         RB_dworld_set_solver_iterations(rbw->physics_world, rbw->num_solver_iterations);
715         RB_dworld_set_split_impulse(rbw->physics_world, rbw->flag & RBW_FLAG_USE_SPLIT_IMPULSE);
716 }
717
718 /* ************************************** */
719 /* Setup Utilities - Create Settings Blocks */
720
721 /* Set up RigidBody world */
722 RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
723 {
724         /* try to get whatever RigidBody world that might be representing this already */
725         RigidBodyWorld *rbw;
726
727         /* sanity checks
728          *      - there must be a valid scene to add world to
729          *      - there mustn't be a sim world using this group already
730          */
731         if (scene == NULL)
732                 return NULL;
733
734         /* create a new sim world */
735         rbw = MEM_callocN(sizeof(RigidBodyWorld), "RigidBodyWorld");
736
737         /* set default settings */
738         rbw->effector_weights = BKE_add_effector_weights(NULL);
739
740         rbw->ltime = PSFRA;
741
742         rbw->time_scale = 1.0f;
743
744         rbw->steps_per_second = 60; /* Bullet default (60 Hz) */
745         rbw->num_solver_iterations = 10; /* 10 is bullet default */
746
747         rbw->pointcache = BKE_ptcache_add(&(rbw->ptcaches));
748         rbw->pointcache->step = 1;
749
750         /* return this sim world */
751         return rbw;
752 }
753
754 RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw)
755 {
756         RigidBodyWorld *rbwn = MEM_dupallocN(rbw);
757
758         if (rbw->effector_weights)
759                 rbwn->effector_weights = MEM_dupallocN(rbw->effector_weights);
760         if (rbwn->group)
761                 id_us_plus(&rbwn->group->id);
762         if (rbwn->constraints)
763                 id_us_plus(&rbwn->constraints->id);
764
765         rbwn->pointcache = BKE_ptcache_copy_list(&rbwn->ptcaches, &rbw->ptcaches, FALSE);
766
767         rbwn->objects = NULL;
768         rbwn->physics_world = NULL;
769         rbwn->numbodies = 0;
770
771         return rbwn;
772 }
773
774 void BKE_rigidbody_world_groups_relink(RigidBodyWorld *rbw)
775 {
776         if (rbw->group && rbw->group->id.newid)
777                 rbw->group = (Group *)rbw->group->id.newid;
778         if (rbw->constraints && rbw->constraints->id.newid)
779                 rbw->constraints = (Group *)rbw->constraints->id.newid;
780         if (rbw->effector_weights->group && rbw->effector_weights->group->id.newid)
781                 rbw->effector_weights->group = (Group *)rbw->effector_weights->group->id.newid;
782 }
783
784 /* Add rigid body settings to the specified object */
785 RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type)
786 {
787         RigidBodyOb *rbo;
788         RigidBodyWorld *rbw = scene->rigidbody_world;
789
790         /* sanity checks
791          *      - rigidbody world must exist
792          *      - object must exist
793          *      - cannot add rigid body if it already exists
794          */
795         if (ob == NULL || (ob->rigidbody_object != NULL))
796                 return NULL;
797
798         /* create new settings data, and link it up */
799         rbo = MEM_callocN(sizeof(RigidBodyOb), "RigidBodyOb");
800
801         /* set default settings */
802         rbo->type = type;
803
804         rbo->mass = 1.0f;
805
806         rbo->friction = 0.5f; /* best when non-zero. 0.5 is Bullet default */
807         rbo->restitution = 0.0f; /* best when zero. 0.0 is Bullet default */
808
809         rbo->margin = 0.04f; /* 0.04 (in meters) is Bullet default */
810
811         rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */
812         rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */
813
814         rbo->lin_damping = 0.04f; /* 0.04 is game engine default */
815         rbo->ang_damping = 0.1f; /* 0.1 is game engine default */
816
817         rbo->col_groups = 1;
818
819         /* use triangle meshes for passive objects
820          * use convex hulls for active objects since dynamic triangle meshes are very unstable
821          */
822         if (type == RBO_TYPE_ACTIVE)
823                 rbo->shape = RB_SHAPE_CONVEXH;
824         else
825                 rbo->shape = RB_SHAPE_TRIMESH;
826
827         rbo->mesh_source = RBO_MESH_DEFORM;
828
829         /* set initial transform */
830         mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
831
832         /* flag cache as outdated */
833         BKE_rigidbody_cache_reset(rbw);
834
835         /* return this object */
836         return rbo;
837 }
838
839 /* Add rigid body constraint to the specified object */
840 RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type)
841 {
842         RigidBodyCon *rbc;
843         RigidBodyWorld *rbw = scene->rigidbody_world;
844
845         /* sanity checks
846          *      - rigidbody world must exist
847          *      - object must exist
848          *      - cannot add constraint if it already exists
849          */
850         if (ob == NULL || (ob->rigidbody_constraint != NULL))
851                 return NULL;
852
853         /* create new settings data, and link it up */
854         rbc = MEM_callocN(sizeof(RigidBodyCon), "RigidBodyCon");
855
856         /* set default settings */
857         rbc->type = type;
858
859         rbc->ob1 = NULL;
860         rbc->ob2 = NULL;
861
862         rbc->flag |= RBC_FLAG_ENABLED;
863         rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS;
864
865         rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */
866         rbc->num_solver_iterations = 10; /* 10 is Bullet default */
867
868         rbc->limit_lin_x_lower = -1.0f;
869         rbc->limit_lin_x_upper = 1.0f;
870         rbc->limit_lin_y_lower = -1.0f;
871         rbc->limit_lin_y_upper = 1.0f;
872         rbc->limit_lin_z_lower = -1.0f;
873         rbc->limit_lin_z_upper = 1.0f;
874         rbc->limit_ang_x_lower = -M_PI_4;
875         rbc->limit_ang_x_upper = M_PI_4;
876         rbc->limit_ang_y_lower = -M_PI_4;
877         rbc->limit_ang_y_upper = M_PI_4;
878         rbc->limit_ang_z_lower = -M_PI_4;
879         rbc->limit_ang_z_upper = M_PI_4;
880
881         rbc->spring_damping_x = 0.5f;
882         rbc->spring_damping_y = 0.5f;
883         rbc->spring_damping_z = 0.5f;
884         rbc->spring_stiffness_x = 10.0f;
885         rbc->spring_stiffness_y = 10.0f;
886         rbc->spring_stiffness_z = 10.0f;
887
888         rbc->motor_lin_max_impulse = 1.0f;
889         rbc->motor_lin_target_velocity = 1.0f;
890         rbc->motor_ang_max_impulse = 1.0f;
891         rbc->motor_ang_target_velocity = 1.0f;
892
893         /* flag cache as outdated */
894         BKE_rigidbody_cache_reset(rbw);
895
896         /* return this object */
897         return rbc;
898 }
899
900 /* ************************************** */
901 /* Utilities API */
902
903 /* Get RigidBody world for the given scene, creating one if needed
904  * < scene: Scene to find active Rigid Body world for
905  */
906 RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene)
907 {
908         /* sanity check */
909         if (scene == NULL)
910                 return NULL;
911
912         return scene->rigidbody_world;
913 }
914
915 void BKE_rigidbody_remove_object(Scene *scene, Object *ob)
916 {
917         RigidBodyWorld *rbw = scene->rigidbody_world;
918         RigidBodyOb *rbo = ob->rigidbody_object;
919         RigidBodyCon *rbc;
920         GroupObject *go;
921         int i;
922
923         if (rbw) {
924                 /* remove from rigidbody world, free object won't do this */
925                 if (rbw->physics_world && rbo->physics_object)
926                         RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
927
928                 /* remove object from array */
929                 if (rbw && rbw->objects) {
930                         for (i = 0; i < rbw->numbodies; i++) {
931                                 if (rbw->objects[i] == ob) {
932                                         rbw->objects[i] = NULL;
933                                         break;
934                                 }
935                         }
936                 }
937
938                 /* remove object from rigid body constraints */
939                 if (rbw->constraints) {
940                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
941                                 Object *obt = go->ob;
942                                 if (obt && obt->rigidbody_constraint) {
943                                         rbc = obt->rigidbody_constraint;
944                                         if (rbc->ob1 == ob) {
945                                                 BKE_rigidbody_remove_constraint(scene, obt);
946                                         }
947                                         if (rbc->ob2 == ob) {
948                                                 BKE_rigidbody_remove_constraint(scene, obt);
949                                         }
950                                 }
951                         }
952                 }
953         }
954
955         /* remove object's settings */
956         BKE_rigidbody_free_object(ob);
957
958         /* flag cache as outdated */
959         BKE_rigidbody_cache_reset(rbw);
960 }
961
962 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob)
963 {
964         RigidBodyWorld *rbw = scene->rigidbody_world;
965         RigidBodyCon *rbc = ob->rigidbody_constraint;
966
967         /* remove from rigidbody world, free object won't do this */
968         if (rbw && rbw->physics_world && rbc->physics_constraint) {
969                 RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
970         }
971         /* remove object's settings */
972         BKE_rigidbody_free_constraint(ob);
973
974         /* flag cache as outdated */
975         BKE_rigidbody_cache_reset(rbw);
976 }
977
978
979 /* ************************************** */
980 /* Simulation Interface - Bullet */
981
982 /* Update object array and rigid body count so they're in sync with the rigid body group */
983 static void rigidbody_update_ob_array(RigidBodyWorld *rbw)
984 {
985         GroupObject *go;
986         int i, n;
987
988         n = BLI_countlist(&rbw->group->gobject);
989
990         if (rbw->numbodies != n) {
991                 rbw->numbodies = n;
992                 rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies);
993         }
994
995         for (go = rbw->group->gobject.first, i = 0; go; go = go->next, i++) {
996                 Object *ob = go->ob;
997                 rbw->objects[i] = ob;
998         }
999 }
1000
1001 static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
1002 {
1003         float adj_gravity[3];
1004
1005         /* adjust gravity to take effector weights into account */
1006         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
1007                 copy_v3_v3(adj_gravity, scene->physics_settings.gravity);
1008                 mul_v3_fl(adj_gravity, rbw->effector_weights->global_gravity * rbw->effector_weights->weight[0]);
1009         }
1010         else {
1011                 zero_v3(adj_gravity);
1012         }
1013
1014         /* update gravity, since this RNA setting is not part of RigidBody settings */
1015         RB_dworld_set_gravity(rbw->physics_world, adj_gravity);
1016
1017         /* update object array in case there are changes */
1018         rigidbody_update_ob_array(rbw);
1019 }
1020
1021 static void rigidbody_update_sim_ob(Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo)
1022 {
1023         float loc[3];
1024         float rot[4];
1025         float scale[3];
1026
1027         /* only update if rigid body exists */
1028         if (rbo->physics_object == NULL)
1029                 return;
1030
1031         mat4_decompose(loc, rot, scale, ob->obmat);
1032
1033         /* update scale for all objects */
1034         RB_body_set_scale(rbo->physics_object, scale);
1035         /* compensate for embedded convex hull collision margin */
1036         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH)
1037                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
1038
1039         /* make transformed objects temporarily kinmatic so that they can be moved by the user during simulation */
1040         if (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ) {
1041                 RB_body_set_kinematic_state(rbo->physics_object, TRUE);
1042                 RB_body_set_mass(rbo->physics_object, 0.0f);
1043         }
1044
1045         /* update rigid body location and rotation for kinematic bodies */
1046         if (rbo->flag & RBO_FLAG_KINEMATIC || (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1047                 RB_body_activate(rbo->physics_object);
1048                 RB_body_set_loc_rot(rbo->physics_object, loc, rot);
1049         }
1050         /* update influence of effectors - but don't do it on an effector */
1051         /* only dynamic bodies need effector update */
1052         else if (rbo->type == RBO_TYPE_ACTIVE && ((ob->pd == NULL) || (ob->pd->forcefield == PFIELD_NULL))) {
1053                 EffectorWeights *effector_weights = rbw->effector_weights;
1054                 EffectedPoint epoint;
1055                 ListBase *effectors;
1056
1057                 /* get effectors present in the group specified by effector_weights */
1058                 effectors = pdInitEffectors(scene, ob, NULL, effector_weights);
1059                 if (effectors) {
1060                         float eff_force[3] = {0.0f, 0.0f, 0.0f};
1061                         float eff_loc[3], eff_vel[3];
1062
1063                         /* create dummy 'point' which represents last known position of object as result of sim */
1064                         // XXX: this can create some inaccuracies with sim position, but is probably better than using unsimulated vals?
1065                         RB_body_get_position(rbo->physics_object, eff_loc);
1066                         RB_body_get_linear_velocity(rbo->physics_object, eff_vel);
1067
1068                         pd_point_from_loc(scene, eff_loc, eff_vel, 0, &epoint);
1069
1070                         /* calculate net force of effectors, and apply to sim object
1071                          *      - we use 'central force' since apply force requires a "relative position" which we don't have...
1072                          */
1073                         pdDoEffectors(effectors, NULL, effector_weights, &epoint, eff_force, NULL);
1074                         if (G.f & G_DEBUG)
1075                                 printf("\tapplying force (%f,%f,%f) to '%s'\n", eff_force[0], eff_force[1], eff_force[2], ob->id.name + 2);
1076                         /* activate object in case it is deactivated */
1077                         if (!is_zero_v3(eff_force))
1078                                 RB_body_activate(rbo->physics_object);
1079                         RB_body_apply_central_force(rbo->physics_object, eff_force);
1080                 }
1081                 else if (G.f & G_DEBUG)
1082                         printf("\tno forces to apply to '%s'\n", ob->id.name + 2);
1083
1084                 /* cleanup */
1085                 pdEndEffectors(&effectors);
1086         }
1087         /* NOTE: passive objects don't need to be updated since they don't move */
1088
1089         /* NOTE: no other settings need to be explicitly updated here,
1090          * since RNA setters take care of the rest :)
1091          */
1092 }
1093
1094 /* Updates and validates world, bodies and shapes.
1095  * < rebuild: rebuild entire simulation
1096  */
1097 static void rigidbody_update_simulation(Scene *scene, RigidBodyWorld *rbw, int rebuild)
1098 {
1099         GroupObject *go;
1100
1101         /* update world */
1102         if (rebuild)
1103                 BKE_rigidbody_validate_sim_world(scene, rbw, true);
1104         rigidbody_update_sim_world(scene, rbw);
1105
1106         /* update objects */
1107         for (go = rbw->group->gobject.first; go; go = go->next) {
1108                 Object *ob = go->ob;
1109
1110                 if (ob && ob->type == OB_MESH) {
1111                         /* validate that we've got valid object set up here... */
1112                         RigidBodyOb *rbo = ob->rigidbody_object;
1113                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1114                         BKE_object_where_is_calc(scene, ob);
1115
1116                         if (rbo == NULL) {
1117                                 /* Since this object is included in the sim group but doesn't have
1118                                  * rigid body settings (perhaps it was added manually), add!
1119                                  *      - assume object to be active? That is the default for newly added settings...
1120                                  */
1121                                 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, RBO_TYPE_ACTIVE);
1122                                 BKE_rigidbody_validate_sim_object(rbw, ob, true);
1123
1124                                 rbo = ob->rigidbody_object;
1125                         }
1126                         else {
1127                                 /* perform simulation data updates as tagged */
1128                                 /* refresh object... */
1129                                 if (rebuild) {
1130                                         /* World has been rebuilt so rebuild object */
1131                                         BKE_rigidbody_validate_sim_object(rbw, ob, true);
1132                                 }
1133                                 else if (rbo->flag & RBO_FLAG_NEEDS_VALIDATE) {
1134                                         BKE_rigidbody_validate_sim_object(rbw, ob, false);
1135                                 }
1136                                 /* refresh shape... */
1137                                 if (rbo->flag & RBO_FLAG_NEEDS_RESHAPE) {
1138                                         /* mesh/shape data changed, so force shape refresh */
1139                                         BKE_rigidbody_validate_sim_shape(ob, true);
1140                                         /* now tell RB sim about it */
1141                                         // XXX: we assume that this can only get applied for active/passive shapes that will be included as rigidbodies
1142                                         RB_body_set_collision_shape(rbo->physics_object, rbo->physics_shape);
1143                                 }
1144                                 rbo->flag &= ~(RBO_FLAG_NEEDS_VALIDATE | RBO_FLAG_NEEDS_RESHAPE);
1145                         }
1146
1147                         /* update simulation object... */
1148                         rigidbody_update_sim_ob(scene, rbw, ob, rbo);
1149                 }
1150         }
1151         /* update constraints */
1152         if (rbw->constraints == NULL) /* no constraints, move on */
1153                 return;
1154         for (go = rbw->constraints->gobject.first; go; go = go->next) {
1155                 Object *ob = go->ob;
1156
1157                 if (ob) {
1158                         /* validate that we've got valid object set up here... */
1159                         RigidBodyCon *rbc = ob->rigidbody_constraint;
1160                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1161                         BKE_object_where_is_calc(scene, ob);
1162
1163                         if (rbc == NULL) {
1164                                 /* Since this object is included in the group but doesn't have
1165                                  * constraint settings (perhaps it was added manually), add!
1166                                  */
1167                                 ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, RBC_TYPE_FIXED);
1168                                 BKE_rigidbody_validate_sim_constraint(rbw, ob, true);
1169
1170                                 rbc = ob->rigidbody_constraint;
1171                         }
1172                         else {
1173                                 /* perform simulation data updates as tagged */
1174                                 if (rebuild) {
1175                                         /* World has been rebuilt so rebuild constraint */
1176                                         BKE_rigidbody_validate_sim_constraint(rbw, ob, true);
1177                                 }
1178                                 else if (rbc->flag & RBC_FLAG_NEEDS_VALIDATE) {
1179                                         BKE_rigidbody_validate_sim_constraint(rbw, ob, false);
1180                                 }
1181                                 rbc->flag &= ~RBC_FLAG_NEEDS_VALIDATE;
1182                         }
1183                 }
1184         }
1185 }
1186
1187 static void rigidbody_update_simulation_post_step(RigidBodyWorld *rbw)
1188 {
1189         GroupObject *go;
1190
1191         for (go = rbw->group->gobject.first; go; go = go->next) {
1192                 Object *ob = go->ob;
1193
1194                 if (ob) {
1195                         RigidBodyOb *rbo = ob->rigidbody_object;
1196                         /* reset kinematic state for transformed objects */
1197                         if (rbo && (ob->flag & SELECT) && (G.moving & G_TRANSFORM_OBJ)) {
1198                                 RB_body_set_kinematic_state(rbo->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
1199                                 RB_body_set_mass(rbo->physics_object, RBO_GET_MASS(rbo));
1200                                 /* deactivate passive objects so they don't interfere with deactivation of active objects */
1201                                 if (rbo->type == RBO_TYPE_PASSIVE)
1202                                         RB_body_deactivate(rbo->physics_object);
1203                         }
1204                 }
1205         }
1206 }
1207
1208 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime)
1209 {
1210         return (rbw && (rbw->flag & RBW_FLAG_MUTED) == 0 && ctime > rbw->pointcache->startframe);
1211 }
1212
1213 /* Sync rigid body and object transformations */
1214 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime)
1215 {
1216         RigidBodyOb *rbo = ob->rigidbody_object;
1217
1218         /* keep original transform for kinematic and passive objects */
1219         if (ELEM(NULL, rbw, rbo) || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE)
1220                 return;
1221
1222         /* use rigid body transform after cache start frame if objects is not being transformed */
1223         if (BKE_rigidbody_check_sim_running(rbw, ctime) && !(ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1224                 float mat[4][4], size_mat[4][4], size[3];
1225
1226                 normalize_qt(rbo->orn); // RB_TODO investigate why quaternion isn't normalized at this point
1227                 quat_to_mat4(mat, rbo->orn);
1228                 copy_v3_v3(mat[3], rbo->pos);
1229
1230                 mat4_to_size(size, ob->obmat);
1231                 size_to_mat4(size_mat, size);
1232                 mul_m4_m4m4(mat, mat, size_mat);
1233
1234                 copy_m4_m4(ob->obmat, mat);
1235         }
1236         /* otherwise set rigid body transform to current obmat */
1237         else {
1238                 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1239         }
1240 }
1241
1242 /* Used when canceling transforms - return rigidbody and object to initial states */
1243 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
1244 {
1245         RigidBodyOb *rbo = ob->rigidbody_object;
1246
1247         /* return rigid body and object to their initial states */
1248         copy_v3_v3(rbo->pos, ob->loc);
1249         copy_v3_v3(ob->loc, loc);
1250
1251         if (ob->rotmode > 0) {
1252                 eulO_to_quat(rbo->orn, ob->rot, ob->rotmode);
1253                 copy_v3_v3(ob->rot, rot);
1254         }
1255         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1256                 axis_angle_to_quat(rbo->orn, ob->rotAxis, ob->rotAngle);
1257                 copy_v3_v3(ob->rotAxis, rotAxis);
1258                 ob->rotAngle = rotAngle;
1259         }
1260         else {
1261                 copy_qt_qt(rbo->orn, ob->quat);
1262                 copy_qt_qt(ob->quat, quat);
1263         }
1264         if (rbo->physics_object) {
1265                 /* allow passive objects to return to original transform */
1266                 if (rbo->type == RBO_TYPE_PASSIVE)
1267                         RB_body_set_kinematic_state(rbo->physics_object, TRUE);
1268                 RB_body_set_loc_rot(rbo->physics_object, rbo->pos, rbo->orn);
1269         }
1270         // 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)
1271 }
1272
1273 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw)
1274 {
1275         if (rbw)
1276                 rbw->pointcache->flag |= PTCACHE_OUTDATED;
1277 }
1278
1279 /* ------------------ */
1280
1281 /* Rebuild rigid body world */
1282 /* NOTE: this needs to be called before frame update to work correctly */
1283 void BKE_rigidbody_rebuild_world(Scene *scene, float ctime)
1284 {
1285         RigidBodyWorld *rbw = scene->rigidbody_world;
1286         PointCache *cache;
1287         PTCacheID pid;
1288         int startframe, endframe;
1289
1290         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1291         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1292         cache = rbw->pointcache;
1293
1294         /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */
1295         if (rbw->physics_world == NULL || rbw->numbodies != BLI_countlist(&rbw->group->gobject)) {
1296                 cache->flag |= PTCACHE_OUTDATED;
1297         }
1298
1299         if (ctime <= startframe + 1 && rbw->ltime == startframe) {
1300                 if (cache->flag & PTCACHE_OUTDATED) {
1301                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1302                         rigidbody_update_simulation(scene, rbw, true);
1303                         BKE_ptcache_validate(cache, (int)ctime);
1304                         cache->last_exact = 0;
1305                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1306                 }
1307         }
1308 }
1309
1310 /* Run RigidBody simulation for the specified physics world */
1311 void BKE_rigidbody_do_simulation(Scene *scene, float ctime)
1312 {
1313         float timestep;
1314         RigidBodyWorld *rbw = scene->rigidbody_world;
1315         PointCache *cache;
1316         PTCacheID pid;
1317         int startframe, endframe;
1318
1319         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1320         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1321         cache = rbw->pointcache;
1322
1323         if (ctime <= startframe) {
1324                 rbw->ltime = startframe;
1325                 return;
1326         }
1327         /* make sure we don't go out of cache frame range */
1328         else if (ctime > endframe) {
1329                 ctime = endframe;
1330         }
1331
1332         /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */
1333         if (rbw->physics_world == NULL && !(cache->flag & PTCACHE_BAKED))
1334                 return;
1335         else if (rbw->objects == NULL)
1336                 rigidbody_update_ob_array(rbw);
1337
1338         /* try to read from cache */
1339         // RB_TODO deal with interpolated, old and baked results
1340         if (BKE_ptcache_read(&pid, ctime)) {
1341                 BKE_ptcache_validate(cache, (int)ctime);
1342                 rbw->ltime = ctime;
1343                 return;
1344         }
1345
1346         /* advance simulation, we can only step one frame forward */
1347         if (ctime == rbw->ltime + 1 && !(cache->flag & PTCACHE_BAKED)) {
1348                 /* write cache for first frame when on second frame */
1349                 if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
1350                         BKE_ptcache_write(&pid, startframe);
1351                 }
1352
1353                 /* update and validate simulation */
1354                 rigidbody_update_simulation(scene, rbw, false);
1355
1356                 /* calculate how much time elapsed since last step in seconds */
1357                 timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale;
1358                 /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */
1359                 RB_dworld_step_simulation(rbw->physics_world, timestep, INT_MAX, 1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f));
1360
1361                 rigidbody_update_simulation_post_step(rbw);
1362
1363                 /* write cache for current frame */
1364                 BKE_ptcache_validate(cache, (int)ctime);
1365                 BKE_ptcache_write(&pid, (unsigned int)ctime);
1366
1367                 rbw->ltime = ctime;
1368         }
1369 }
1370 /* ************************************** */
1371
1372 #else  /* WITH_BULLET */
1373
1374 /* stubs */
1375 #ifdef __GNUC__
1376 #  pragma GCC diagnostic push
1377 #  pragma GCC diagnostic ignored "-Wunused-parameter"
1378 #endif
1379
1380 void BKE_rigidbody_free_world(RigidBodyWorld *rbw) {}
1381 void BKE_rigidbody_free_object(Object *ob) {}
1382 void BKE_rigidbody_free_constraint(Object *ob) {}
1383 struct RigidBodyOb *BKE_rigidbody_copy_object(Object *ob) { return NULL; }
1384 struct RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob) { return NULL; }
1385 void BKE_rigidbody_relink_constraint(RigidBodyCon *rbc) {}
1386 void BKE_rigidbody_validate_sim_shape(Object *ob, short rebuild) {}
1387 void BKE_rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, short rebuild) {}
1388 void BKE_rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, short rebuild) {}
1389 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, short rebuild) {}
1390 struct RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) { return NULL; }
1391 struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw) { return NULL; }
1392 void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw) {}
1393 struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; }
1394 struct RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type) { return NULL; }
1395 struct RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { return NULL; }
1396 void BKE_rigidbody_remove_object(Scene *scene, Object *ob) {}
1397 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) {}
1398 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) {}
1399 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) {}
1400 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime) { return false; }
1401 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) {}
1402 void BKE_rigidbody_rebuild_world(Scene *scene, float ctime) {}
1403 void BKE_rigidbody_do_simulation(Scene *scene, float ctime) {}
1404
1405 #ifdef __GNUC__
1406 #  pragma GCC diagnostic pop
1407 #endif
1408
1409 #endif  /* WITH_BULLET */