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