174fb38aadaacf853709f76850b61ff0ec557617
[blender-staging.git] / source / blender / blenkernel / intern / object.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/object.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35 #include <stdio.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_camera_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_group_types.h"
44 #include "DNA_key_types.h"
45 #include "DNA_lamp_types.h"
46 #include "DNA_lattice_types.h"
47 #include "DNA_material_types.h"
48 #include "DNA_meta_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_movieclip_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_screen_types.h"
54 #include "DNA_sequence_types.h"
55 #include "DNA_smoke_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58 #include "DNA_world_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_property_types.h"
61 #include "DNA_rigidbody_types.h"
62
63 #include "BLI_blenlib.h"
64 #include "BLI_math.h"
65 #include "BLI_threads.h"
66 #include "BLI_utildefines.h"
67 #include "BLI_linklist.h"
68 #include "BLI_kdtree.h"
69
70 #include "BLF_translation.h"
71
72 #include "BKE_pbvh.h"
73 #include "BKE_main.h"
74 #include "BKE_global.h"
75 #include "BKE_idprop.h"
76 #include "BKE_armature.h"
77 #include "BKE_action.h"
78 #include "BKE_bullet.h"
79 #include "BKE_deform.h"
80 #include "BKE_depsgraph.h"
81 #include "BKE_DerivedMesh.h"
82 #include "BKE_animsys.h"
83 #include "BKE_anim.h"
84 #include "BKE_constraint.h"
85 #include "BKE_curve.h"
86 #include "BKE_displist.h"
87 #include "BKE_effect.h"
88 #include "BKE_fcurve.h"
89 #include "BKE_group.h"
90 #include "BKE_key.h"
91 #include "BKE_lamp.h"
92 #include "BKE_lattice.h"
93 #include "BKE_library.h"
94 #include "BKE_linestyle.h"
95 #include "BKE_mesh.h"
96 #include "BKE_editmesh.h"
97 #include "BKE_mball.h"
98 #include "BKE_modifier.h"
99 #include "BKE_node.h"
100 #include "BKE_object.h"
101 #include "BKE_paint.h"
102 #include "BKE_particle.h"
103 #include "BKE_pointcache.h"
104 #include "BKE_property.h"
105 #include "BKE_rigidbody.h"
106 #include "BKE_sca.h"
107 #include "BKE_scene.h"
108 #include "BKE_sequencer.h"
109 #include "BKE_speaker.h"
110 #include "BKE_softbody.h"
111 #include "BKE_subsurf.h"
112 #include "BKE_material.h"
113 #include "BKE_camera.h"
114 #include "BKE_image.h"
115
116 #ifdef WITH_MOD_FLUID
117 #include "LBM_fluidsim.h"
118 #endif
119
120 #ifdef WITH_PYTHON
121 #include "BPY_extern.h"
122 #endif
123
124 #include "CCGSubSurf.h"
125
126 #include "GPU_material.h"
127
128 /* Vertex parent modifies original BMesh which is not safe for threading.
129  * Ideally such a modification should be handled as a separate DAG update
130  * callback for mesh datablock, but for until it is actually supported use
131  * simpler solution with a mutex lock.
132  *                                               - sergey -
133  */
134 #define VPARENT_THREADING_HACK
135
136 #ifdef VPARENT_THREADING_HACK
137 static ThreadMutex vparent_lock = BLI_MUTEX_INITIALIZER;
138 #endif
139
140 void BKE_object_workob_clear(Object *workob)
141 {
142         memset(workob, 0, sizeof(Object));
143         
144         workob->size[0] = workob->size[1] = workob->size[2] = 1.0f;
145         workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f;
146         workob->rotmode = ROT_MODE_EUL;
147 }
148
149 void BKE_object_update_base_layer(struct Scene *scene, Object *ob)
150 {
151         Base *base = scene->base.first;
152
153         while (base) {
154                 if (base->object == ob) base->lay = ob->lay;
155                 base = base->next;
156         }
157 }
158
159 void BKE_object_free_particlesystems(Object *ob)
160 {
161         ParticleSystem *psys;
162
163         while ((psys = BLI_pophead(&ob->particlesystem))) {
164                 psys_free(ob, psys);
165         }
166 }
167
168 void BKE_object_free_softbody(Object *ob)
169 {
170         if (ob->soft) {
171                 sbFree(ob->soft);
172                 ob->soft = NULL;
173         }
174 }
175
176 void BKE_object_free_bulletsoftbody(Object *ob)
177 {
178         if (ob->bsoft) {
179                 bsbFree(ob->bsoft);
180                 ob->bsoft = NULL;
181         }
182 }
183
184 void BKE_object_free_curve_cache(Object *ob)
185 {
186         if (ob->curve_cache) {
187                 BKE_displist_free(&ob->curve_cache->disp);
188                 BKE_curve_bevelList_free(&ob->curve_cache->bev);
189                 if (ob->curve_cache->path) {
190                         free_path(ob->curve_cache->path);
191                 }
192                 BKE_nurbList_free(&ob->curve_cache->deformed_nurbs);
193                 MEM_freeN(ob->curve_cache);
194                 ob->curve_cache = NULL;
195         }
196 }
197
198 void BKE_object_free_modifiers(Object *ob)
199 {
200         ModifierData *md;
201
202         while ((md = BLI_pophead(&ob->modifiers))) {
203                 modifier_free(md);
204         }
205
206         /* particle modifiers were freed, so free the particlesystems as well */
207         BKE_object_free_particlesystems(ob);
208
209         /* same for softbody */
210         BKE_object_free_softbody(ob);
211 }
212
213 void BKE_object_modifier_hook_reset(Object *ob, HookModifierData *hmd)
214 {
215         /* reset functionality */
216         if (hmd->object) {
217                 bPoseChannel *pchan = BKE_pose_channel_find_name(hmd->object->pose, hmd->subtarget);
218
219                 if (hmd->subtarget[0] && pchan) {
220                         float imat[4][4], mat[4][4];
221
222                         /* calculate the world-space matrix for the pose-channel target first, then carry on as usual */
223                         mul_m4_m4m4(mat, hmd->object->obmat, pchan->pose_mat);
224
225                         invert_m4_m4(imat, mat);
226                         mul_m4_m4m4(hmd->parentinv, imat, ob->obmat);
227                 }
228                 else {
229                         invert_m4_m4(hmd->object->imat, hmd->object->obmat);
230                         mul_m4_m4m4(hmd->parentinv, hmd->object->imat, ob->obmat);
231                 }
232         }
233 }
234
235 bool BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
236 {
237         ModifierTypeInfo *mti;
238
239         mti = modifierType_getInfo(modifier_type);
240
241         if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
242               (ob->type == OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
243         {
244                 return false;
245         }
246
247         return true;
248 }
249
250 void BKE_object_link_modifiers(struct Object *ob_dst, struct Object *ob_src)
251 {
252         ModifierData *md;
253         BKE_object_free_modifiers(ob_dst);
254
255         if (!ELEM(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
256                 /* only objects listed above can have modifiers and linking them to objects
257                  * which doesn't have modifiers stack is quite silly */
258                 return;
259         }
260
261         for (md = ob_src->modifiers.first; md; md = md->next) {
262                 ModifierData *nmd = NULL;
263
264                 if (ELEM(md->type,
265                          eModifierType_Hook,
266                          eModifierType_Softbody,
267                          eModifierType_ParticleInstance,
268                          eModifierType_Collision))
269                 {
270                         continue;
271                 }
272
273                 if (!BKE_object_support_modifier_type_check(ob_dst, md->type))
274                         continue;
275                 
276                 if (md->type == eModifierType_Skin) {
277                         /* ensure skin-node customdata exists */
278                         BKE_mesh_ensure_skin_customdata(ob_dst->data);
279                 }
280
281                 nmd = modifier_new(md->type);
282                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
283                 modifier_copyData(md, nmd);
284                 BLI_addtail(&ob_dst->modifiers, nmd);
285                 modifier_unique_name(&ob_dst->modifiers, nmd);
286         }
287
288         BKE_object_copy_particlesystems(ob_dst, ob_src);
289         BKE_object_copy_softbody(ob_dst, ob_src);
290
291         /* TODO: smoke?, cloth? */
292 }
293
294 /* free data derived from mesh, called when mesh changes or is freed */
295 void BKE_object_free_derived_caches(Object *ob)
296 {
297         /* also serves as signal to remake texspace */
298         if (ob->type == OB_MESH) {
299                 Mesh *me = ob->data;
300
301                 if (me->bb) {
302                         me->bb->flag |= BOUNDBOX_DIRTY;
303                 }
304         }
305         else if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) {
306                 Curve *cu = ob->data;
307
308                 if (cu->bb) {
309                         cu->bb->flag |= BOUNDBOX_DIRTY;
310                 }
311         }
312
313         if (ob->bb) {
314                 MEM_freeN(ob->bb);
315                 ob->bb = NULL;
316         }
317
318         if (ob->derivedFinal) {
319                 ob->derivedFinal->needsFree = 1;
320                 ob->derivedFinal->release(ob->derivedFinal);
321                 ob->derivedFinal = NULL;
322         }
323         if (ob->derivedDeform) {
324                 ob->derivedDeform->needsFree = 1;
325                 ob->derivedDeform->release(ob->derivedDeform);
326                 ob->derivedDeform = NULL;
327         }
328         
329         BKE_object_free_curve_cache(ob);
330 }
331
332 void BKE_object_free_caches(Object *object)
333 {
334         ModifierData *md;
335         short update_flag = 0;
336
337         /* Free particle system caches holding paths. */
338         if (object->particlesystem.first) {
339                 ParticleSystem *psys;
340                 for (psys = object->particlesystem.first;
341                      psys != NULL;
342                      psys = psys->next)
343                 {
344                         psys_free_path_cache(psys, psys->edit);
345                         update_flag |= PSYS_RECALC;
346                 }
347         }
348
349         /* Free memory used by cached derived meshes in the particle system modifiers. */
350         for (md = object->modifiers.first; md != NULL; md = md->next) {
351                 if (md->type == eModifierType_ParticleSystem) {
352                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData *) md;
353                         if (psmd->dm != NULL) {
354                                 psmd->dm->needsFree = 1;
355                                 psmd->dm->release(psmd->dm);
356                                 psmd->dm = NULL;
357                                 update_flag |= OB_RECALC_DATA;
358                         }
359                 }
360         }
361
362         /* Tag object for update, so once memory critical operation is over and
363          * scene update routines are back to it's business the object will be
364          * guaranteed to be in a known state.
365          */
366         if (update_flag != 0) {
367                 DAG_id_tag_update(&object->id, update_flag);
368         }
369 }
370
371 /* do not free object itself */
372 void BKE_object_free_ex(Object *ob, bool do_id_user)
373 {
374         int a;
375         
376         BKE_object_free_derived_caches(ob);
377         
378         /* disconnect specific data, but not for lib data (might be indirect data, can get relinked) */
379         if (ob->data) {
380                 ID *id = ob->data;
381                 id->us--;
382                 if (id->us == 0 && id->lib == NULL) {
383                         switch (ob->type) {
384                                 case OB_MESH:
385                                         BKE_mesh_unlink((Mesh *)id);
386                                         break;
387                                 case OB_CURVE:
388                                         BKE_curve_unlink((Curve *)id);
389                                         break;
390                                 case OB_MBALL:
391                                         BKE_mball_unlink((MetaBall *)id);
392                                         break;
393                         }
394                 }
395                 ob->data = NULL;
396         }
397
398         if (ob->mat) {
399                 for (a = 0; a < ob->totcol; a++) {
400                         if (ob->mat[a]) ob->mat[a]->id.us--;
401                 }
402                 MEM_freeN(ob->mat);
403         }
404         if (ob->matbits) MEM_freeN(ob->matbits);
405         ob->mat = NULL;
406         ob->matbits = NULL;
407         if (ob->iuser) MEM_freeN(ob->iuser);
408         ob->iuser = NULL;
409         if (ob->bb) MEM_freeN(ob->bb); 
410         ob->bb = NULL;
411         if (ob->adt) BKE_free_animdata((ID *)ob);
412         if (ob->poselib) ob->poselib->id.us--;
413         if (ob->gpd) ((ID *)ob->gpd)->us--;
414         if (ob->defbase.first)
415                 BLI_freelistN(&ob->defbase);
416         if (ob->pose)
417                 BKE_pose_free_ex(ob->pose, do_id_user);
418         if (ob->mpath)
419                 animviz_free_motionpath(ob->mpath);
420         BKE_bproperty_free_list(&ob->prop);
421         BKE_object_free_modifiers(ob);
422         
423         free_sensors(&ob->sensors);
424         free_controllers(&ob->controllers);
425         free_actuators(&ob->actuators);
426         
427         BKE_constraints_free_ex(&ob->constraints, do_id_user);
428         
429         free_partdeflect(ob->pd);
430         BKE_rigidbody_free_object(ob);
431         BKE_rigidbody_free_constraint(ob);
432
433         if (ob->soft) sbFree(ob->soft);
434         if (ob->bsoft) bsbFree(ob->bsoft);
435         if (ob->gpulamp.first) GPU_lamp_free(ob);
436
437         BKE_free_sculptsession(ob);
438
439         if (ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
440
441         BLI_freelistN(&ob->lodlevels);
442
443         /* Free runtime curves data. */
444         if (ob->curve_cache) {
445                 BKE_curve_bevelList_free(&ob->curve_cache->bev);
446                 if (ob->curve_cache->path)
447                         free_path(ob->curve_cache->path);
448                 MEM_freeN(ob->curve_cache);
449         }
450 }
451
452 void BKE_object_free(Object *ob)
453 {
454         BKE_object_free_ex(ob, true);
455 }
456
457 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
458 {
459         Object *unlinkOb = userData;
460
461         if (*obpoin == unlinkOb) {
462                 *obpoin = NULL;
463                 // XXX: should this just be OB_RECALC_DATA?
464                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
465         }
466 }
467
468 void BKE_object_unlink(Object *ob)
469 {
470         Main *bmain = G.main;
471         Object *obt;
472         Material *mat;
473         World *wrld;
474         bScreen *sc;
475         Scene *sce;
476         SceneRenderLayer *srl;
477         FreestyleLineSet *lineset;
478         bNodeTree *ntree;
479         Curve *cu;
480         Tex *tex;
481         Group *group;
482         Camera *camera;
483         bConstraint *con;
484         //bActionStrip *strip; // XXX animsys 
485         ModifierData *md;
486         ARegion *ar;
487         RegionView3D *rv3d;
488         LodLevel *lod;
489         int a, found;
490         
491         unlink_controllers(&ob->controllers);
492         unlink_actuators(&ob->actuators);
493         
494         /* check all objects: parents en bevels and fields, also from libraries */
495         /* FIXME: need to check all animation blocks (drivers) */
496         obt = bmain->object.first;
497         while (obt) {
498                 if (obt->proxy == ob)
499                         obt->proxy = NULL;
500                 if (obt->proxy_from == ob) {
501                         obt->proxy_from = NULL;
502                         DAG_id_tag_update(&obt->id, OB_RECALC_OB);
503                 }
504                 if (obt->proxy_group == ob)
505                         obt->proxy_group = NULL;
506                 
507                 if (obt->parent == ob) {
508                         obt->parent = NULL;
509                         DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
510                 }
511                 
512                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
513                 
514                 if (ELEM(obt->type, OB_CURVE, OB_FONT)) {
515                         cu = obt->data;
516
517                         if (cu->bevobj == ob) {
518                                 cu->bevobj = NULL;
519                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
520                         }
521                         if (cu->taperobj == ob) {
522                                 cu->taperobj = NULL;
523                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
524                         }
525                         if (cu->textoncurve == ob) {
526                                 cu->textoncurve = NULL;
527                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
528                         }
529                 }
530                 else if (obt->type == OB_ARMATURE && obt->pose) {
531                         bPoseChannel *pchan;
532                         for (pchan = obt->pose->chanbase.first; pchan; pchan = pchan->next) {
533                                 for (con = pchan->constraints.first; con; con = con->next) {
534                                         bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
535                                         ListBase targets = {NULL, NULL};
536                                         bConstraintTarget *ct;
537                                         
538                                         if (cti && cti->get_constraint_targets) {
539                                                 cti->get_constraint_targets(con, &targets);
540                                                 
541                                                 for (ct = targets.first; ct; ct = ct->next) {
542                                                         if (ct->tar == ob) {
543                                                                 ct->tar = NULL;
544                                                                 ct->subtarget[0] = '\0';
545                                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
546                                                         }
547                                                 }
548                                                 
549                                                 if (cti->flush_constraint_targets)
550                                                         cti->flush_constraint_targets(con, &targets, 0);
551                                         }
552                                 }
553                                 if (pchan->custom == ob)
554                                         pchan->custom = NULL;
555                         }
556                 }
557                 else if (ELEM(OB_MBALL, ob->type, obt->type)) {
558                         if (BKE_mball_is_basis_for(obt, ob))
559                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
560                 }
561                 
562                 sca_remove_ob_poin(obt, ob);
563                 
564                 for (con = obt->constraints.first; con; con = con->next) {
565                         bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
566                         ListBase targets = {NULL, NULL};
567                         bConstraintTarget *ct;
568                         
569                         if (cti && cti->get_constraint_targets) {
570                                 cti->get_constraint_targets(con, &targets);
571                                 
572                                 for (ct = targets.first; ct; ct = ct->next) {
573                                         if (ct->tar == ob) {
574                                                 ct->tar = NULL;
575                                                 ct->subtarget[0] = '\0';
576                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
577                                         }
578                                 }
579                                 
580                                 if (cti->flush_constraint_targets)
581                                         cti->flush_constraint_targets(con, &targets, 0);
582                         }
583                 }
584                 
585                 /* object is deflector or field */
586                 if (ob->pd) {
587                         if (obt->soft)
588                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
589
590                         /* cloth */
591                         for (md = obt->modifiers.first; md; md = md->next)
592                                 if (md->type == eModifierType_Cloth)
593                                         DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
594                 }
595                 
596                 /* strips */
597 #if 0 // XXX old animation system
598                 for (strip = obt->nlastrips.first; strip; strip = strip->next) {
599                         if (strip->object == ob)
600                                 strip->object = NULL;
601                         
602                         if (strip->modifiers.first) {
603                                 bActionModifier *amod;
604                                 for (amod = strip->modifiers.first; amod; amod = amod->next)
605                                         if (amod->ob == ob)
606                                                 amod->ob = NULL;
607                         }
608                 }
609 #endif // XXX old animation system
610
611                 /* particle systems */
612                 if (obt->particlesystem.first) {
613                         ParticleSystem *tpsys = obt->particlesystem.first;
614                         for (; tpsys; tpsys = tpsys->next) {
615                                 BoidState *state = NULL;
616                                 BoidRule *rule = NULL;
617
618                                 ParticleTarget *pt = tpsys->targets.first;
619                                 for (; pt; pt = pt->next) {
620                                         if (pt->ob == ob) {
621                                                 pt->ob = NULL;
622                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
623                                                 break;
624                                         }
625                                 }
626
627                                 if (tpsys->target_ob == ob) {
628                                         tpsys->target_ob = NULL;
629                                         DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
630                                 }
631
632                                 if (tpsys->part->dup_ob == ob)
633                                         tpsys->part->dup_ob = NULL;
634
635                                 if (tpsys->part->phystype == PART_PHYS_BOIDS) {
636                                         ParticleData *pa;
637                                         BoidParticle *bpa;
638                                         int p;
639
640                                         for (p = 0, pa = tpsys->particles; p < tpsys->totpart; p++, pa++) {
641                                                 bpa = pa->boid;
642                                                 if (bpa->ground == ob)
643                                                         bpa->ground = NULL;
644                                         }
645                                 }
646                                 if (tpsys->part->boids) {
647                                         for (state = tpsys->part->boids->states.first; state; state = state->next) {
648                                                 for (rule = state->rules.first; rule; rule = rule->next) {
649                                                         if (rule->type == eBoidRuleType_Avoid) {
650                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid *)rule;
651                                                                 if (gabr->ob == ob)
652                                                                         gabr->ob = NULL;
653                                                         }
654                                                         else if (rule->type == eBoidRuleType_FollowLeader) {
655                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader *)rule;
656                                                                 if (flbr->ob == ob)
657                                                                         flbr->ob = NULL;
658                                                         }
659                                                 }
660                                         }
661                                 }
662                                 
663                                 if (tpsys->parent == ob)
664                                         tpsys->parent = NULL;
665                         }
666                         if (ob->pd)
667                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
668                 }
669
670                 /* levels of detail */
671                 for (lod = obt->lodlevels.first; lod; lod = lod->next) {
672                         if (lod->source == ob)
673                                 lod->source = NULL;
674                 }
675
676                 obt = obt->id.next;
677         }
678         
679         /* materials */
680         for (mat = bmain->mat.first; mat; mat = mat->id.next) {
681                 if (mat->nodetree) {
682                         ntreeSwitchID(mat->nodetree, &ob->id, NULL);
683                 }
684                 for (a = 0; a < MAX_MTEX; a++) {
685                         if (mat->mtex[a] && ob == mat->mtex[a]->object) {
686                                 /* actually, test for lib here... to do */
687                                 mat->mtex[a]->object = NULL;
688                         }
689                 }
690         }
691
692         /* node trees */
693         for (ntree = bmain->nodetree.first; ntree; ntree = ntree->id.next) {
694                 if (ntree->type == NTREE_SHADER)
695                         ntreeSwitchID(ntree, &ob->id, NULL);
696         }
697         
698         /* textures */
699         for (tex = bmain->tex.first; tex; tex = tex->id.next) {
700                 if (tex->env && (ob == tex->env->object)) tex->env->object = NULL;
701                 if (tex->pd  && (ob == tex->pd->object)) tex->pd->object = NULL;
702                 if (tex->vd  && (ob == tex->vd->object)) tex->vd->object = NULL;
703         }
704
705         /* worlds */
706         wrld = bmain->world.first;
707         while (wrld) {
708                 if (wrld->id.lib == NULL) {
709                         for (a = 0; a < MAX_MTEX; a++) {
710                                 if (wrld->mtex[a] && ob == wrld->mtex[a]->object)
711                                         wrld->mtex[a]->object = NULL;
712                         }
713                 }
714                 
715                 wrld = wrld->id.next;
716         }
717                 
718         /* scenes */
719         sce = bmain->scene.first;
720         while (sce) {
721                 if (sce->id.lib == NULL) {
722                         if (sce->camera == ob) sce->camera = NULL;
723                         if (sce->toolsettings->skgen_template == ob) sce->toolsettings->skgen_template = NULL;
724                         if (sce->toolsettings->particle.object == ob) sce->toolsettings->particle.object = NULL;
725                         if (sce->toolsettings->particle.shape_object == ob) sce->toolsettings->particle.shape_object = NULL;
726
727 #ifdef DURIAN_CAMERA_SWITCH
728                         {
729                                 TimeMarker *m;
730
731                                 for (m = sce->markers.first; m; m = m->next) {
732                                         if (m->camera == ob)
733                                                 m->camera = NULL;
734                                 }
735                         }
736 #endif
737                         if (sce->ed) {
738                                 Sequence *seq;
739                                 SEQ_BEGIN(sce->ed, seq)
740                                 {
741                                         if (seq->scene_camera == ob) {
742                                                 seq->scene_camera = NULL;
743                                         }
744                                 }
745                                 SEQ_END
746                         }
747
748                         for (srl = sce->r.layers.first; srl; srl = srl->next) {
749                                 for (lineset = (FreestyleLineSet *)srl->freestyleConfig.linesets.first;
750                                      lineset; lineset = lineset->next)
751                                 {
752                                         if (lineset->linestyle) {
753                                                 BKE_linestyle_target_object_unlink(lineset->linestyle, ob);
754                                         }
755                                 }
756                         }
757                 }
758
759                 sce = sce->id.next;
760         }
761         
762         /* screens */
763         sc = bmain->screen.first;
764         while (sc) {
765                 ScrArea *sa = sc->areabase.first;
766                 while (sa) {
767                         SpaceLink *sl;
768
769                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
770                                 if (sl->spacetype == SPACE_VIEW3D) {
771                                         View3D *v3d = (View3D *) sl;
772
773                                         /* found doesn't need to be set here */
774                                         if (v3d->ob_centre == ob) {
775                                                 v3d->ob_centre = NULL;
776                                                 v3d->ob_centre_bone[0] = '\0';
777                                         }
778                                         if (v3d->localvd && v3d->localvd->ob_centre == ob) {
779                                                 v3d->localvd->ob_centre = NULL;
780                                                 v3d->localvd->ob_centre_bone[0] = '\0';
781                                         }
782
783                                         found = 0;
784                                         if (v3d->camera == ob) {
785                                                 v3d->camera = NULL;
786                                                 found = 1;
787                                         }
788                                         if (v3d->localvd && v3d->localvd->camera == ob) {
789                                                 v3d->localvd->camera = NULL;
790                                                 found += 2;
791                                         }
792
793                                         if (found) {
794                                                 if (sa->spacetype == SPACE_VIEW3D) {
795                                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
796                                                                 if (ar->regiontype == RGN_TYPE_WINDOW) {
797                                                                         rv3d = (RegionView3D *)ar->regiondata;
798                                                                         if (found == 1 || found == 3) {
799                                                                                 if (rv3d->persp == RV3D_CAMOB)
800                                                                                         rv3d->persp = RV3D_PERSP;
801                                                                         }
802                                                                         if (found == 2 || found == 3) {
803                                                                                 if (rv3d->localvd && rv3d->localvd->persp == RV3D_CAMOB)
804                                                                                         rv3d->localvd->persp = RV3D_PERSP;
805                                                                         }
806                                                                 }
807                                                         }
808                                                 }
809                                         }
810                                 }
811                                 else if (sl->spacetype == SPACE_OUTLINER) {
812                                         SpaceOops *so = (SpaceOops *)sl;
813
814                                         if (so->treestore) {
815                                                 TreeStoreElem *tselem;
816                                                 BLI_mempool_iter iter;
817                                                 BLI_mempool_iternew(so->treestore, &iter);
818                                                 while ((tselem = BLI_mempool_iterstep(&iter))) {
819                                                         if (tselem->id == (ID *)ob) tselem->id = NULL;
820                                                 }
821                                         }
822                                 }
823                                 else if (sl->spacetype == SPACE_BUTS) {
824                                         SpaceButs *sbuts = (SpaceButs *)sl;
825
826                                         if (sbuts->pinid == (ID *)ob) {
827                                                 sbuts->flag &= ~SB_PIN_CONTEXT;
828                                                 sbuts->pinid = NULL;
829                                         }
830                                 }
831                                 else if (sl->spacetype == SPACE_NODE) {
832                                         SpaceNode *snode = (SpaceNode *)sl;
833
834                                         if (snode->from == (ID *)ob) {
835                                                 snode->flag &= ~SNODE_PIN;
836                                                 snode->from = NULL;
837                                         }
838                                 }
839                         }
840
841                         sa = sa->next;
842                 }
843                 sc = sc->id.next;
844         }
845
846         /* groups */
847         group = bmain->group.first;
848         while (group) {
849                 BKE_group_object_unlink(group, ob, NULL, NULL);
850                 group = group->id.next;
851         }
852         
853         /* cameras */
854         camera = bmain->camera.first;
855         while (camera) {
856                 if (camera->dof_ob == ob) {
857                         camera->dof_ob = NULL;
858                 }
859                 camera = camera->id.next;
860         }
861 }
862
863 /* actual check for internal data, not context or flags */
864 bool BKE_object_is_in_editmode(Object *ob)
865 {
866         if (ob->data == NULL)
867                 return false;
868         
869         if (ob->type == OB_MESH) {
870                 Mesh *me = ob->data;
871                 if (me->edit_btmesh)
872                         return true;
873         }
874         else if (ob->type == OB_ARMATURE) {
875                 bArmature *arm = ob->data;
876                 
877                 if (arm->edbo)
878                         return true;
879         }
880         else if (ob->type == OB_FONT) {
881                 Curve *cu = ob->data;
882                 
883                 if (cu->editfont)
884                         return true;
885         }
886         else if (ob->type == OB_MBALL) {
887                 MetaBall *mb = ob->data;
888                 
889                 if (mb->editelems)
890                         return true;
891         }
892         else if (ob->type == OB_LATTICE) {
893                 Lattice *lt = ob->data;
894                 
895                 if (lt->editlatt)
896                         return true;
897         }
898         else if (ob->type == OB_SURF || ob->type == OB_CURVE) {
899                 Curve *cu = ob->data;
900
901                 if (cu->editnurb)
902                         return true;
903         }
904         return false;
905 }
906
907 bool BKE_object_is_in_editmode_vgroup(Object *ob)
908 {
909         return (OB_TYPE_SUPPORT_VGROUP(ob->type) &&
910                 BKE_object_is_in_editmode(ob));
911 }
912
913 bool BKE_object_is_in_wpaint_select_vert(Object *ob)
914 {
915         if (ob->type == OB_MESH) {
916                 Mesh *me = ob->data;
917                 return ((ob->mode & OB_MODE_WEIGHT_PAINT) &&
918                         (me->edit_btmesh == NULL) &&
919                         (ME_EDIT_PAINT_SEL_MODE(me) == SCE_SELECT_VERTEX));
920         }
921
922         return false;
923 }
924
925 bool BKE_object_exists_check(Object *obtest)
926 {
927         Object *ob;
928         
929         if (obtest == NULL) return false;
930         
931         ob = G.main->object.first;
932         while (ob) {
933                 if (ob == obtest) return true;
934                 ob = ob->id.next;
935         }
936         return false;
937 }
938
939 /* *************************************************** */
940
941 void *BKE_object_obdata_add_from_type(Main *bmain, int type)
942 {
943         switch (type) {
944                 case OB_MESH:      return BKE_mesh_add(bmain, "Mesh");
945                 case OB_CURVE:     return BKE_curve_add(bmain, "Curve", OB_CURVE);
946                 case OB_SURF:      return BKE_curve_add(bmain, "Surf", OB_SURF);
947                 case OB_FONT:      return BKE_curve_add(bmain, "Text", OB_FONT);
948                 case OB_MBALL:     return BKE_mball_add(bmain, "Meta");
949                 case OB_CAMERA:    return BKE_camera_add(bmain, "Camera");
950                 case OB_LAMP:      return BKE_lamp_add(bmain, "Lamp");
951                 case OB_LATTICE:   return BKE_lattice_add(bmain, "Lattice");
952                 case OB_ARMATURE:  return BKE_armature_add(bmain, "Armature");
953                 case OB_SPEAKER:   return BKE_speaker_add(bmain, "Speaker");
954                 case OB_EMPTY:     return NULL;
955                 default:
956                         printf("BKE_object_obdata_add_from_type: Internal error, bad type: %d\n", type);
957                         return NULL;
958         }
959 }
960
961 static const char *get_obdata_defname(int type)
962 {
963         switch (type) {
964                 case OB_MESH: return DATA_("Mesh");
965                 case OB_CURVE: return DATA_("Curve");
966                 case OB_SURF: return DATA_("Surf");
967                 case OB_FONT: return DATA_("Text");
968                 case OB_MBALL: return DATA_("Mball");
969                 case OB_CAMERA: return DATA_("Camera");
970                 case OB_LAMP: return DATA_("Lamp");
971                 case OB_LATTICE: return DATA_("Lattice");
972                 case OB_ARMATURE: return DATA_("Armature");
973                 case OB_SPEAKER: return DATA_("Speaker");
974                 case OB_EMPTY: return DATA_("Empty");
975                 default:
976                         printf("get_obdata_defname: Internal error, bad type: %d\n", type);
977                         return DATA_("Empty");
978         }
979 }
980
981 /* more general add: creates minimum required data, but without vertices etc. */
982 Object *BKE_object_add_only_object(Main *bmain, int type, const char *name)
983 {
984         Object *ob;
985
986         if (!name)
987                 name = get_obdata_defname(type);
988
989         ob = BKE_libblock_alloc(bmain, ID_OB, name);
990
991         /* default object vars */
992         ob->type = type;
993         
994         ob->col[0] = ob->col[1] = ob->col[2] = 1.0;
995         ob->col[3] = 1.0;
996         
997         ob->size[0] = ob->size[1] = ob->size[2] = 1.0;
998         ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0;
999         
1000         /* objects should default to having Euler XYZ rotations, 
1001          * but rotations default to quaternions 
1002          */
1003         ob->rotmode = ROT_MODE_EUL;
1004
1005         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
1006         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
1007
1008         unit_qt(ob->quat);
1009         unit_qt(ob->dquat);
1010
1011         /* rotation locks should be 4D for 4 component rotations by default... */
1012         ob->protectflag = OB_LOCK_ROT4D;
1013         
1014         unit_m4(ob->constinv);
1015         unit_m4(ob->parentinv);
1016         unit_m4(ob->obmat);
1017         ob->dt = OB_TEXTURE;
1018         ob->empty_drawtype = OB_PLAINAXES;
1019         ob->empty_drawsize = 1.0;
1020
1021         if (ELEM(type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1022                 ob->trackflag = OB_NEGZ;
1023                 ob->upflag = OB_POSY;
1024         }
1025         else {
1026                 ob->trackflag = OB_POSY;
1027                 ob->upflag = OB_POSZ;
1028         }
1029         
1030         ob->dupon = 1; ob->dupoff = 0;
1031         ob->dupsta = 1; ob->dupend = 100;
1032         ob->dupfacesca = 1.0;
1033
1034         /* Game engine defaults*/
1035         ob->mass = ob->inertia = 1.0f;
1036         ob->formfactor = 0.4f;
1037         ob->damping = 0.04f;
1038         ob->rdamping = 0.1f;
1039         ob->anisotropicFriction[0] = 1.0f;
1040         ob->anisotropicFriction[1] = 1.0f;
1041         ob->anisotropicFriction[2] = 1.0f;
1042         ob->gameflag = OB_PROP | OB_COLLISION;
1043         ob->margin = 0.04f;
1044         ob->init_state = 1;
1045         ob->state = 1;
1046         ob->obstacleRad = 1.0f;
1047         ob->step_height = 0.15f;
1048         ob->jump_speed = 10.0f;
1049         ob->fall_speed = 55.0f;
1050         ob->col_group = 0x01;
1051         ob->col_mask = 0xff;
1052
1053         /* NT fluid sim defaults */
1054         ob->fluidsimSettings = NULL;
1055
1056         BLI_listbase_clear(&ob->pc_ids);
1057         
1058         /* Animation Visualization defaults */
1059         animviz_settings_init(&ob->avs);
1060
1061         return ob;
1062 }
1063
1064 /* general add: to scene, with layer from area and default name */
1065 /* creates minimum required data, but without vertices etc. */
1066 Object *BKE_object_add(Main *bmain, Scene *scene, int type)
1067 {
1068         Object *ob;
1069         Base *base;
1070         char name[MAX_ID_NAME];
1071
1072         BLI_strncpy(name, get_obdata_defname(type), sizeof(name));
1073         ob = BKE_object_add_only_object(bmain, type, name);
1074
1075         ob->data = BKE_object_obdata_add_from_type(bmain, type);
1076
1077         ob->lay = scene->lay;
1078         
1079         base = BKE_scene_base_add(scene, ob);
1080         BKE_scene_base_deselect_all(scene);
1081         BKE_scene_base_select(scene, base);
1082         DAG_id_tag_update_ex(bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1083
1084         return ob;
1085 }
1086
1087
1088 #ifdef WITH_GAMEENGINE
1089
1090 void BKE_object_lod_add(Object *ob)
1091 {
1092         LodLevel *lod = MEM_callocN(sizeof(LodLevel), "LoD Level");
1093         LodLevel *last = ob->lodlevels.last;
1094
1095         /* If the lod list is empty, initialize it with the base lod level */
1096         if (!last) {
1097                 LodLevel *base = MEM_callocN(sizeof(LodLevel), "Base LoD Level");
1098                 BLI_addtail(&ob->lodlevels, base);
1099                 base->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT;
1100                 base->source = ob;
1101                 base->obhysteresis = 10;
1102                 last = ob->currentlod = base;
1103         }
1104         
1105         lod->distance = last->distance + 25.0f;
1106         lod->obhysteresis = 10;
1107         lod->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT;
1108
1109         BLI_addtail(&ob->lodlevels, lod);
1110 }
1111
1112 static int lod_cmp(const void *a, const void *b)
1113 {
1114         const LodLevel *loda = a;
1115         const LodLevel *lodb = b;
1116
1117         if (loda->distance < lodb->distance) return -1;
1118         return loda->distance > lodb->distance;
1119 }
1120
1121 void BKE_object_lod_sort(Object *ob)
1122 {
1123         BLI_listbase_sort(&ob->lodlevels, lod_cmp);
1124 }
1125
1126 bool BKE_object_lod_remove(Object *ob, int level)
1127 {
1128         LodLevel *rem;
1129
1130         if (level < 1 || level > BLI_listbase_count(&ob->lodlevels) - 1)
1131                 return false;
1132
1133         rem = BLI_findlink(&ob->lodlevels, level);
1134
1135         if (rem == ob->currentlod) {
1136                 ob->currentlod = rem->prev;
1137         }
1138
1139         BLI_remlink(&ob->lodlevels, rem);
1140         MEM_freeN(rem);
1141
1142         /* If there are no user defined lods, remove the base lod as well */
1143         if (BLI_listbase_is_single(&ob->lodlevels)) {
1144                 LodLevel *base = ob->lodlevels.first;
1145                 BLI_remlink(&ob->lodlevels, base);
1146                 MEM_freeN(base);
1147                 ob->currentlod = NULL;
1148         }
1149
1150         return true;
1151 }
1152
1153 static LodLevel *lod_level_select(Object *ob, const float camera_position[3])
1154 {
1155         LodLevel *current = ob->currentlod;
1156         float dist_sq, dist_sq_curr;
1157
1158         if (!current) return NULL;
1159
1160         dist_sq = len_squared_v3v3(ob->obmat[3], camera_position);
1161         dist_sq_curr = current->distance * current->distance;
1162
1163         if (dist_sq < dist_sq_curr) {
1164                 /* check for higher LoD */
1165                 while (current->prev && dist_sq < dist_sq_curr) {
1166                         current = current->prev;
1167                 }
1168         }
1169         else {
1170                 /* check for lower LoD */
1171                 while (current->next && dist_sq > SQUARE(current->next->distance)) {
1172                         current = current->next;
1173                 }
1174         }
1175
1176         return current;
1177 }
1178
1179 bool BKE_object_lod_is_usable(Object *ob, Scene *scene)
1180 {
1181         bool active = (scene) ? ob == OBACT : false;
1182         return (ob->mode == OB_MODE_OBJECT || !active);
1183 }
1184
1185 void BKE_object_lod_update(Object *ob, const float camera_position[3])
1186 {
1187         LodLevel *cur_level = ob->currentlod;
1188         LodLevel *new_level = lod_level_select(ob, camera_position);
1189
1190         if (new_level != cur_level) {
1191                 ob->currentlod = new_level;
1192         }
1193 }
1194
1195 static Object *lod_ob_get(Object *ob, Scene *scene, int flag)
1196 {
1197         LodLevel *current = ob->currentlod;
1198
1199         if (!current || !BKE_object_lod_is_usable(ob, scene))
1200                 return ob;
1201
1202         while (current->prev && (!(current->flags & flag) || !current->source || current->source->type != OB_MESH)) {
1203                 current = current->prev;
1204         }
1205
1206         return current->source;
1207 }
1208
1209 struct Object *BKE_object_lod_meshob_get(Object *ob, Scene *scene)
1210 {
1211         return lod_ob_get(ob, scene, OB_LOD_USE_MESH);
1212 }
1213
1214 struct Object *BKE_object_lod_matob_get(Object *ob, Scene *scene)
1215 {
1216         return lod_ob_get(ob, scene, OB_LOD_USE_MAT);
1217 }
1218
1219 #endif  /* WITH_GAMEENGINE */
1220
1221
1222 SoftBody *copy_softbody(SoftBody *sb, bool copy_caches)
1223 {
1224         SoftBody *sbn;
1225         
1226         if (sb == NULL) return(NULL);
1227         
1228         sbn = MEM_dupallocN(sb);
1229
1230         if (copy_caches == false) {
1231                 sbn->totspring = sbn->totpoint = 0;
1232                 sbn->bpoint = NULL;
1233                 sbn->bspring = NULL;
1234         }
1235         else {
1236                 sbn->totspring = sb->totspring;
1237                 sbn->totpoint = sb->totpoint;
1238
1239                 if (sbn->bpoint) {
1240                         int i;
1241
1242                         sbn->bpoint = MEM_dupallocN(sbn->bpoint);
1243
1244                         for (i = 0; i < sbn->totpoint; i++) {
1245                                 if (sbn->bpoint[i].springs)
1246                                         sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs);
1247                         }
1248                 }
1249
1250                 if (sb->bspring)
1251                         sbn->bspring = MEM_dupallocN(sb->bspring);
1252         }
1253         
1254         sbn->keys = NULL;
1255         sbn->totkey = sbn->totpointkey = 0;
1256         
1257         sbn->scratch = NULL;
1258
1259         sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches);
1260
1261         if (sb->effector_weights)
1262                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1263
1264         return sbn;
1265 }
1266
1267 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1268 {
1269         BulletSoftBody *bsbn;
1270
1271         if (bsb == NULL)
1272                 return NULL;
1273         bsbn = MEM_dupallocN(bsb);
1274         /* no pointer in this structure yet */
1275         return bsbn;
1276 }
1277
1278 ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys)
1279 {
1280         ParticleSystem *psysn;
1281         ParticleData *pa;
1282         int p;
1283
1284         psysn = MEM_dupallocN(psys);
1285         psysn->particles = MEM_dupallocN(psys->particles);
1286         psysn->child = MEM_dupallocN(psys->child);
1287
1288         if (psys->part->type == PART_HAIR) {
1289                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++)
1290                         pa->hair = MEM_dupallocN(pa->hair);
1291         }
1292
1293         if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
1294                 ParticleKey *key = psysn->particles->keys;
1295                 BoidParticle *boid = psysn->particles->boid;
1296
1297                 if (key)
1298                         key = MEM_dupallocN(key);
1299                 
1300                 if (boid)
1301                         boid = MEM_dupallocN(boid);
1302                 
1303                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) {
1304                         if (boid)
1305                                 pa->boid = boid++;
1306                         if (key) {
1307                                 pa->keys = key;
1308                                 key += pa->totkey;
1309                         }
1310                 }
1311         }
1312
1313         if (psys->clmd) {
1314                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1315                 modifier_copyData((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd);
1316                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1317         }
1318
1319         BLI_duplicatelist(&psysn->targets, &psys->targets);
1320
1321         psysn->pathcache = NULL;
1322         psysn->childcache = NULL;
1323         psysn->edit = NULL;
1324         psysn->pdd = NULL;
1325         psysn->effectors = NULL;
1326         psysn->tree = NULL;
1327         psysn->bvhtree = NULL;
1328         
1329         BLI_listbase_clear(&psysn->pathcachebufs);
1330         BLI_listbase_clear(&psysn->childcachebufs);
1331         psysn->renderdata = NULL;
1332         
1333         psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, false);
1334
1335         /* XXX - from reading existing code this seems correct but intended usage of
1336          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1337         if (psysn->clmd) {
1338                 psysn->clmd->point_cache = psysn->pointcache;
1339         }
1340
1341         id_us_plus((ID *)psysn->part);
1342
1343         return psysn;
1344 }
1345
1346 void BKE_object_copy_particlesystems(Object *obn, Object *ob)
1347 {
1348         ParticleSystem *psys, *npsys;
1349         ModifierData *md;
1350
1351         if (obn->type != OB_MESH) {
1352                 /* currently only mesh objects can have soft body */
1353                 return;
1354         }
1355
1356         BLI_listbase_clear(&obn->particlesystem);
1357         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
1358                 npsys = BKE_object_copy_particlesystem(psys);
1359
1360                 BLI_addtail(&obn->particlesystem, npsys);
1361
1362                 /* need to update particle modifiers too */
1363                 for (md = obn->modifiers.first; md; md = md->next) {
1364                         if (md->type == eModifierType_ParticleSystem) {
1365                                 ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md;
1366                                 if (psmd->psys == psys)
1367                                         psmd->psys = npsys;
1368                         }
1369                         else if (md->type == eModifierType_DynamicPaint) {
1370                                 DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1371                                 if (pmd->brush) {
1372                                         if (pmd->brush->psys == psys) {
1373                                                 pmd->brush->psys = npsys;
1374                                         }
1375                                 }
1376                         }
1377                         else if (md->type == eModifierType_Smoke) {
1378                                 SmokeModifierData *smd = (SmokeModifierData *) md;
1379                                 
1380                                 if (smd->type == MOD_SMOKE_TYPE_FLOW) {
1381                                         if (smd->flow) {
1382                                                 if (smd->flow->psys == psys)
1383                                                         smd->flow->psys = npsys;
1384                                         }
1385                                 }
1386                         }
1387                 }
1388         }
1389 }
1390
1391 void BKE_object_copy_softbody(Object *obn, Object *ob)
1392 {
1393         if (ob->soft)
1394                 obn->soft = copy_softbody(ob->soft, false);
1395 }
1396
1397 static void copy_object_pose(Object *obn, Object *ob)
1398 {
1399         bPoseChannel *chan;
1400         
1401         /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */
1402         obn->pose = NULL;
1403         BKE_pose_copy_data(&obn->pose, ob->pose, 1);    /* 1 = copy constraints */
1404
1405         for (chan = obn->pose->chanbase.first; chan; chan = chan->next) {
1406                 bConstraint *con;
1407                 
1408                 chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE);
1409                 
1410                 for (con = chan->constraints.first; con; con = con->next) {
1411                         bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1412                         ListBase targets = {NULL, NULL};
1413                         bConstraintTarget *ct;
1414                         
1415                         if (cti && cti->get_constraint_targets) {
1416                                 cti->get_constraint_targets(con, &targets);
1417                                 
1418                                 for (ct = targets.first; ct; ct = ct->next) {
1419                                         if (ct->tar == ob)
1420                                                 ct->tar = obn;
1421                                 }
1422                                 
1423                                 if (cti->flush_constraint_targets)
1424                                         cti->flush_constraint_targets(con, &targets, 0);
1425                         }
1426                 }
1427         }
1428 }
1429
1430 static void copy_object_lod(Object *obn, Object *ob)
1431 {
1432         BLI_duplicatelist(&obn->lodlevels, &ob->lodlevels);
1433
1434         if (obn->lodlevels.first)
1435                 ((LodLevel *)obn->lodlevels.first)->source = obn;
1436
1437         obn->currentlod = (LodLevel *)obn->lodlevels.first;
1438 }
1439
1440 bool BKE_object_pose_context_check(Object *ob)
1441 {
1442         if ((ob) &&
1443             (ob->type == OB_ARMATURE) &&
1444             (ob->pose) &&
1445             (ob->mode & OB_MODE_POSE))
1446         {
1447                 return true;
1448         }
1449         else {
1450                 return false;
1451         }
1452 }
1453
1454 Object *BKE_object_pose_armature_get(Object *ob)
1455 {
1456         if (ob == NULL)
1457                 return NULL;
1458
1459         if (BKE_object_pose_context_check(ob))
1460                 return ob;
1461
1462         ob = modifiers_isDeformedByArmature(ob);
1463
1464         if (BKE_object_pose_context_check(ob))
1465                 return ob;
1466
1467         return NULL;
1468 }
1469
1470 void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
1471 {
1472         copy_v3_v3(ob_tar->loc, ob_src->loc);
1473         copy_v3_v3(ob_tar->rot, ob_src->rot);
1474         copy_v3_v3(ob_tar->quat, ob_src->quat);
1475         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1476         ob_tar->rotAngle = ob_src->rotAngle;
1477         ob_tar->rotmode = ob_src->rotmode;
1478         copy_v3_v3(ob_tar->size, ob_src->size);
1479 }
1480
1481 Object *BKE_object_copy_ex(Main *bmain, Object *ob, bool copy_caches)
1482 {
1483         Object *obn;
1484         ModifierData *md;
1485         int a;
1486
1487         obn = BKE_libblock_copy_ex(bmain, &ob->id);
1488         
1489         if (ob->totcol) {
1490                 obn->mat = MEM_dupallocN(ob->mat);
1491                 obn->matbits = MEM_dupallocN(ob->matbits);
1492                 obn->totcol = ob->totcol;
1493         }
1494
1495         if (ob->iuser) obn->iuser = MEM_dupallocN(ob->iuser);
1496         
1497         if (ob->bb) obn->bb = MEM_dupallocN(ob->bb);
1498         obn->flag &= ~OB_FROMGROUP;
1499         
1500         BLI_listbase_clear(&obn->modifiers);
1501         
1502         for (md = ob->modifiers.first; md; md = md->next) {
1503                 ModifierData *nmd = modifier_new(md->type);
1504                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1505                 modifier_copyData(md, nmd);
1506                 BLI_addtail(&obn->modifiers, nmd);
1507         }
1508
1509         BLI_listbase_clear(&obn->prop);
1510         BKE_bproperty_copy_list(&obn->prop, &ob->prop);
1511         
1512         copy_sensors(&obn->sensors, &ob->sensors);
1513         copy_controllers(&obn->controllers, &ob->controllers);
1514         copy_actuators(&obn->actuators, &ob->actuators);
1515         
1516         if (ob->pose) {
1517                 copy_object_pose(obn, ob);
1518                 /* backwards compat... non-armatures can get poses in older files? */
1519                 if (ob->type == OB_ARMATURE)
1520                         BKE_pose_rebuild(obn, obn->data);
1521         }
1522         defgroup_copy_list(&obn->defbase, &ob->defbase);
1523         BKE_constraints_copy(&obn->constraints, &ob->constraints, true);
1524
1525         obn->mode = OB_MODE_OBJECT;
1526         obn->sculpt = NULL;
1527
1528         /* increase user numbers */
1529         id_us_plus((ID *)obn->data);
1530         id_us_plus((ID *)obn->gpd);
1531         id_lib_extern((ID *)obn->dup_group);
1532
1533         for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1534         
1535         if (ob->pd) {
1536                 obn->pd = MEM_dupallocN(ob->pd);
1537                 if (obn->pd->tex)
1538                         id_us_plus(&(obn->pd->tex->id));
1539                 if (obn->pd->rng)
1540                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1541         }
1542         obn->soft = copy_softbody(ob->soft, copy_caches);
1543         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1544         obn->rigidbody_object = BKE_rigidbody_copy_object(ob);
1545         obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob);
1546
1547         BKE_object_copy_particlesystems(obn, ob);
1548         
1549         obn->derivedDeform = NULL;
1550         obn->derivedFinal = NULL;
1551
1552         BLI_listbase_clear(&obn->gpulamp);
1553         BLI_listbase_clear(&obn->pc_ids);
1554
1555         obn->mpath = NULL;
1556
1557         copy_object_lod(obn, ob);
1558         
1559
1560         /* Copy runtime surve data. */
1561         obn->curve_cache = NULL;
1562
1563         if (ob->id.lib) {
1564                 BKE_id_lib_local_paths(bmain, ob->id.lib, &obn->id);
1565         }
1566
1567         return obn;
1568 }
1569
1570 /* copy objects, will re-initialize cached simulation data */
1571 Object *BKE_object_copy(Object *ob)
1572 {
1573         return BKE_object_copy_ex(G.main, ob, false);
1574 }
1575
1576 static void extern_local_object__modifiersForeachIDLink(
1577         void *UNUSED(userData), Object *UNUSED(ob),
1578         ID **idpoin)
1579 {
1580         if (*idpoin) {
1581                 /* intentionally omit ID_OB */
1582                 if (ELEM(GS((*idpoin)->name), ID_IM, ID_TE)) {
1583                         id_lib_extern(*idpoin);
1584                 }
1585         }
1586 }
1587
1588 static void extern_local_object(Object *ob)
1589 {
1590         ParticleSystem *psys;
1591
1592         id_lib_extern((ID *)ob->data);
1593         id_lib_extern((ID *)ob->dup_group);
1594         id_lib_extern((ID *)ob->poselib);
1595         id_lib_extern((ID *)ob->gpd);
1596
1597         extern_local_matarar(ob->mat, ob->totcol);
1598
1599         for (psys = ob->particlesystem.first; psys; psys = psys->next)
1600                 id_lib_extern((ID *)psys->part);
1601
1602         modifiers_foreachIDLink(ob, extern_local_object__modifiersForeachIDLink, NULL);
1603 }
1604
1605 void BKE_object_make_local(Object *ob)
1606 {
1607         Main *bmain = G.main;
1608         Scene *sce;
1609         Base *base;
1610         bool is_local = false, is_lib = false;
1611
1612         /* - only lib users: do nothing
1613          * - only local users: set flag
1614          * - mixed: make copy
1615          */
1616
1617         if (ob->id.lib == NULL) return;
1618         
1619         ob->proxy = ob->proxy_from = NULL;
1620         
1621         if (ob->id.us == 1) {
1622                 id_clear_lib_data(bmain, &ob->id);
1623                 extern_local_object(ob);
1624         }
1625         else {
1626                 for (sce = bmain->scene.first; sce && ELEM(0, is_lib, is_local); sce = sce->id.next) {
1627                         if (BKE_scene_base_find(sce, ob)) {
1628                                 if (sce->id.lib) is_lib = true;
1629                                 else is_local = true;
1630                         }
1631                 }
1632
1633                 if (is_local && is_lib == false) {
1634                         id_clear_lib_data(bmain, &ob->id);
1635                         extern_local_object(ob);
1636                 }
1637                 else if (is_local && is_lib) {
1638                         Object *ob_new = BKE_object_copy(ob);
1639
1640                         ob_new->id.us = 0;
1641                         
1642                         /* Remap paths of new ID using old library as base. */
1643                         BKE_id_lib_local_paths(bmain, ob->id.lib, &ob_new->id);
1644
1645                         sce = bmain->scene.first;
1646                         while (sce) {
1647                                 if (sce->id.lib == NULL) {
1648                                         base = sce->base.first;
1649                                         while (base) {
1650                                                 if (base->object == ob) {
1651                                                         base->object = ob_new;
1652                                                         ob_new->id.us++;
1653                                                         ob->id.us--;
1654                                                 }
1655                                                 base = base->next;
1656                                         }
1657                                 }
1658                                 sce = sce->id.next;
1659                         }
1660                 }
1661         }
1662 }
1663
1664 /*
1665  * Returns true if the Object is a from an external blend file (libdata)
1666  */
1667 bool BKE_object_is_libdata(Object *ob)
1668 {
1669         if (!ob) return false;
1670         if (ob->proxy) return false;
1671         if (ob->id.lib) return true;
1672         return false;
1673 }
1674
1675 /* Returns true if the Object data is a from an external blend file (libdata) */
1676 bool BKE_object_obdata_is_libdata(Object *ob)
1677 {
1678         if (!ob) return false;
1679         if (ob->proxy && (ob->data == NULL || ((ID *)ob->data)->lib == NULL)) return false;
1680         if (ob->id.lib) return true;
1681         if (ob->data == NULL) return false;
1682         if (((ID *)ob->data)->lib) return true;
1683
1684         return false;
1685 }
1686
1687 /* *************** PROXY **************** */
1688
1689 /* when you make proxy, ensure the exposed layers are extern */
1690 static void armature_set_id_extern(Object *ob)
1691 {
1692         bArmature *arm = ob->data;
1693         bPoseChannel *pchan;
1694         unsigned int lay = arm->layer_protected;
1695         
1696         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1697                 if (!(pchan->bone->layer & lay))
1698                         id_lib_extern((ID *)pchan->custom);
1699         }
1700                         
1701 }
1702
1703 void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
1704 {
1705         if ((target->adt) && (target->adt->drivers.first)) {
1706                 FCurve *fcu;
1707                 
1708                 /* add new animdata block */
1709                 if (!ob->adt)
1710                         ob->adt = BKE_id_add_animdata(&ob->id);
1711                 
1712                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1713                 free_fcurves(&ob->adt->drivers);
1714                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1715                 
1716                 for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) {
1717                         ChannelDriver *driver = fcu->driver;
1718                         DriverVar *dvar;
1719                         
1720                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1721                                 /* all drivers */
1722                                 DRIVER_TARGETS_LOOPER(dvar) 
1723                                 {
1724                                         if (dtar->id) {
1725                                                 if ((Object *)dtar->id == target)
1726                                                         dtar->id = (ID *)ob;
1727                                                 else {
1728                                                         /* only on local objects because this causes indirect links
1729                                                          * 'a -> b -> c', blend to point directly to a.blend
1730                                                          * when a.blend has a proxy thats linked into c.blend  */
1731                                                         if (ob->id.lib == NULL)
1732                                                                 id_lib_extern((ID *)dtar->id);
1733                                                 }
1734                                         }
1735                                 }
1736                                 DRIVER_TARGETS_LOOPER_END
1737                         }
1738                 }
1739         }
1740 }
1741
1742 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1743 /*             local_object->proxy == pointer to library object, saved in files and read */
1744 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1745
1746 void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
1747 {
1748         /* paranoia checks */
1749         if (ob->id.lib || target->id.lib == NULL) {
1750                 printf("cannot make proxy\n");
1751                 return;
1752         }
1753         
1754         ob->proxy = target;
1755         ob->proxy_group = gob;
1756         id_lib_extern(&target->id);
1757         
1758         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1759         DAG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1760         
1761         /* copy transform
1762          * - gob means this proxy comes from a group, just apply the matrix
1763          *   so the object wont move from its dupli-transform.
1764          *
1765          * - no gob means this is being made from a linked object,
1766          *   this is closer to making a copy of the object - in-place. */
1767         if (gob) {
1768                 ob->rotmode = target->rotmode;
1769                 mul_m4_m4m4(ob->obmat, gob->obmat, target->obmat);
1770                 if (gob->dup_group) { /* should always be true */
1771                         float tvec[3];
1772                         copy_v3_v3(tvec, gob->dup_group->dupli_ofs);
1773                         mul_mat3_m4_v3(ob->obmat, tvec);
1774                         sub_v3_v3(ob->obmat[3], tvec);
1775                 }
1776                 BKE_object_apply_mat4(ob, ob->obmat, false, true);
1777         }
1778         else {
1779                 BKE_object_transform_copy(ob, target);
1780                 ob->parent = target->parent; /* libdata */
1781                 copy_m4_m4(ob->parentinv, target->parentinv);
1782         }
1783         
1784         /* copy animdata stuff - drivers only for now... */
1785         BKE_object_copy_proxy_drivers(ob, target);
1786
1787         /* skip constraints? */
1788         /* FIXME: this is considered by many as a bug */
1789         
1790         /* set object type and link to data */
1791         ob->type = target->type;
1792         ob->data = target->data;
1793         id_us_plus((ID *)ob->data);     /* ensures lib data becomes LIB_EXTERN */
1794         
1795         /* copy material and index information */
1796         ob->actcol = ob->totcol = 0;
1797         if (ob->mat) MEM_freeN(ob->mat);
1798         if (ob->matbits) MEM_freeN(ob->matbits);
1799         ob->mat = NULL;
1800         ob->matbits = NULL;
1801         if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1802                 int i;
1803                 
1804                 ob->actcol = target->actcol;
1805                 ob->totcol = target->totcol;
1806                 
1807                 ob->mat = MEM_dupallocN(target->mat);
1808                 ob->matbits = MEM_dupallocN(target->matbits);
1809                 for (i = 0; i < target->totcol; i++) {
1810                         /* don't need to run test_object_materials since we know this object is new and not used elsewhere */
1811                         id_us_plus((ID *)ob->mat[i]); 
1812                 }
1813         }
1814         
1815         /* type conversions */
1816         if (target->type == OB_ARMATURE) {
1817                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1818                 BKE_pose_rest(ob->pose);            /* clear all transforms in channels */
1819                 BKE_pose_rebuild(ob, ob->data); /* set all internal links */
1820                 
1821                 armature_set_id_extern(ob);
1822         }
1823         else if (target->type == OB_EMPTY) {
1824                 ob->empty_drawtype = target->empty_drawtype;
1825                 ob->empty_drawsize = target->empty_drawsize;
1826         }
1827
1828         /* copy IDProperties */
1829         if (ob->id.properties) {
1830                 IDP_FreeProperty(ob->id.properties);
1831                 MEM_freeN(ob->id.properties);
1832                 ob->id.properties = NULL;
1833         }
1834         if (target->id.properties) {
1835                 ob->id.properties = IDP_CopyProperty(target->id.properties);
1836         }
1837
1838         /* copy drawtype info */
1839         ob->dt = target->dt;
1840 }
1841
1842 /**
1843  * Use with newly created objects to set their size
1844  * (used to apply scene-scale).
1845  */
1846 void BKE_object_obdata_size_init(struct Object *ob, const float size)
1847 {
1848         /* apply radius as a scale to types that support it */
1849         switch (ob->type) {
1850                 case OB_EMPTY:
1851                 {
1852                         ob->empty_drawsize *= size;
1853                         break;
1854                 }
1855                 case OB_FONT:
1856                 {
1857                         Curve *cu = ob->data;
1858                         cu->fsize *= size;
1859                         break;
1860                 }
1861                 case OB_CAMERA:
1862                 {
1863                         Camera *cam = ob->data;
1864                         cam->drawsize *= size;
1865                         break;
1866                 }
1867                 case OB_LAMP:
1868                 {
1869                         Lamp *lamp = ob->data;
1870                         lamp->dist *= size;
1871                         lamp->area_size  *= size;
1872                         lamp->area_sizey *= size;
1873                         lamp->area_sizez *= size;
1874                         break;
1875                 }
1876                 /* Only lattice (not mesh, curve, mball...),
1877                  * because its got data when newly added */
1878                 case OB_LATTICE:
1879                 {
1880                         struct Lattice *lt = ob->data;
1881                         float mat[4][4];
1882
1883                         unit_m4(mat);
1884                         scale_m4_fl(mat, size);
1885
1886                         BKE_lattice_transform(lt, (float (*)[4])mat, false);
1887                         break;
1888                 }
1889         }
1890 }
1891
1892 /* *************** CALC ****************** */
1893
1894 void BKE_object_scale_to_mat3(Object *ob, float mat[3][3])
1895 {
1896         float vec[3];
1897         mul_v3_v3v3(vec, ob->size, ob->dscale);
1898         size_to_mat3(mat, vec);
1899 }
1900
1901 void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot)
1902 {
1903         float rmat[3][3], dmat[3][3];
1904         
1905         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1906          * with the rotation matrix to yield the appropriate rotation
1907          */
1908
1909         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1910         if (ob->rotmode > 0) {
1911                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1912                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1913                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1914         }
1915         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1916                 /* axis-angle - not really that great for 3D-changing orientations */
1917                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1918                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1919         }
1920         else {
1921                 /* quats are normalized before use to eliminate scaling issues */
1922                 float tquat[4];
1923                 
1924                 normalize_qt_qt(tquat, ob->quat);
1925                 quat_to_mat3(rmat, tquat);
1926                 
1927                 normalize_qt_qt(tquat, ob->dquat);
1928                 quat_to_mat3(dmat, tquat);
1929         }
1930         
1931         /* combine these rotations */
1932         if (use_drot)
1933                 mul_m3_m3m3(mat, dmat, rmat);
1934         else
1935                 copy_m3_m3(mat, rmat);
1936 }
1937
1938 void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], bool use_compat)
1939 {
1940         switch (ob->rotmode) {
1941                 case ROT_MODE_QUAT:
1942                 {
1943                         float dquat[4];
1944                         mat3_to_quat(ob->quat, mat);
1945                         normalize_qt_qt(dquat, ob->dquat);
1946                         invert_qt(dquat);
1947                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1948                         break;
1949                 }
1950                 case ROT_MODE_AXISANGLE:
1951                 {
1952                         mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1953                         sub_v3_v3(ob->rotAxis, ob->drotAxis);
1954                         ob->rotAngle -= ob->drotAngle;
1955                         break;
1956                 }
1957                 default: /* euler */
1958                 {
1959                         float quat[4];
1960                         float dquat[4];
1961                         float tmat[3][3];
1962
1963                         /* without drot we could apply 'mat' directly */
1964                         mat3_to_quat(quat, mat);
1965                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1966                         invert_qt(dquat);
1967                         mul_qt_qtqt(quat, dquat, quat);
1968                         quat_to_mat3(tmat, quat);
1969                         /* end drot correction */
1970
1971                         if (use_compat) mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1972                         else            mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1973                         break;
1974                 }
1975         }
1976 }
1977
1978 void BKE_object_tfm_protected_backup(const Object *ob,
1979                                      ObjectTfmProtectedChannels *obtfm)
1980 {
1981
1982 #define TFMCPY(_v) (obtfm->_v = ob->_v)
1983 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
1984 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
1985
1986         TFMCPY3D(loc);
1987         TFMCPY3D(dloc);
1988         TFMCPY3D(size);
1989         TFMCPY3D(dscale);
1990         TFMCPY3D(rot);
1991         TFMCPY3D(drot);
1992         TFMCPY4D(quat);
1993         TFMCPY4D(dquat);
1994         TFMCPY3D(rotAxis);
1995         TFMCPY3D(drotAxis);
1996         TFMCPY(rotAngle);
1997         TFMCPY(drotAngle);
1998
1999 #undef TFMCPY
2000 #undef TFMCPY3D
2001 #undef TFMCPY4D
2002
2003 }
2004
2005 void BKE_object_tfm_protected_restore(Object *ob,
2006                                       const ObjectTfmProtectedChannels *obtfm,
2007                                       const short protectflag)
2008 {
2009         unsigned int i;
2010
2011         for (i = 0; i < 3; i++) {
2012                 if (protectflag & (OB_LOCK_LOCX << i)) {
2013                         ob->loc[i] =  obtfm->loc[i];
2014                         ob->dloc[i] = obtfm->dloc[i];
2015                 }
2016
2017                 if (protectflag & (OB_LOCK_SCALEX << i)) {
2018                         ob->size[i] =  obtfm->size[i];
2019                         ob->dscale[i] = obtfm->dscale[i];
2020                 }
2021
2022                 if (protectflag & (OB_LOCK_ROTX << i)) {
2023                         ob->rot[i] =  obtfm->rot[i];
2024                         ob->drot[i] = obtfm->drot[i];
2025
2026                         ob->quat[i + 1] =  obtfm->quat[i + 1];
2027                         ob->dquat[i + 1] = obtfm->dquat[i + 1];
2028
2029                         ob->rotAxis[i] =  obtfm->rotAxis[i];
2030                         ob->drotAxis[i] = obtfm->drotAxis[i];
2031                 }
2032         }
2033
2034         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
2035                 ob->quat[0] =  obtfm->quat[0];
2036                 ob->dquat[0] = obtfm->dquat[0];
2037
2038                 ob->rotAngle =  obtfm->rotAngle;
2039                 ob->drotAngle = obtfm->drotAngle;
2040         }
2041 }
2042
2043 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
2044 {
2045         float smat[3][3];
2046         float rmat[3][3];
2047         /*float q1[4];*/
2048         
2049         /* size */
2050         BKE_object_scale_to_mat3(ob, smat);
2051
2052         /* rot */
2053         BKE_object_rot_to_mat3(ob, rmat, true);
2054         mul_m3_m3m3(mat, rmat, smat);
2055 }
2056
2057 void BKE_object_to_mat4(Object *ob, float mat[4][4])
2058 {
2059         float tmat[3][3];
2060         
2061         BKE_object_to_mat3(ob, tmat);
2062         
2063         copy_m4_m3(mat, tmat);
2064
2065         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
2066 }
2067
2068 static void ob_get_parent_matrix(Scene *scene, Object *ob, Object *par, float parentmat[4][4]);
2069
2070 void BKE_object_matrix_local_get(struct Object *ob, float mat[4][4])
2071 {
2072         if (ob->parent) {
2073                 float par_imat[4][4];
2074
2075                 ob_get_parent_matrix(NULL, ob, ob->parent, par_imat);
2076                 invert_m4(par_imat);
2077                 mul_m4_m4m4(mat, par_imat, ob->obmat);
2078         }
2079         else {
2080                 copy_m4_m4(mat, ob->obmat);
2081         }
2082 }
2083
2084 /* extern */
2085 int enable_cu_speed = 1;
2086
2087 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4])
2088 {
2089         Curve *cu;
2090         float vec[4], dir[3], quat[4], radius, ctime;
2091         
2092         unit_m4(mat);
2093         
2094         cu = par->data;
2095         if (ELEM(NULL, par->curve_cache, par->curve_cache->path, par->curve_cache->path->data)) /* only happens on reload file, but violates depsgraph still... fix! */
2096                 BKE_displist_make_curveTypes(scene, par, 0);
2097         if (par->curve_cache->path == NULL) return;
2098         
2099         /* catch exceptions: feature for nla stride editing */
2100         if (ob->ipoflag & OB_DISABLE_PATH) {
2101                 ctime = 0.0f;
2102         }
2103         /* catch exceptions: curve paths used as a duplicator */
2104         else if (enable_cu_speed) {
2105                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
2106                  * but this will only work if it actually is animated... 
2107                  *
2108                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
2109                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
2110                  */
2111                 if (cu->pathlen) {
2112                         ctime = cu->ctime / cu->pathlen;
2113                 }
2114                 else {
2115                         ctime = cu->ctime;
2116                 }
2117
2118                 CLAMP(ctime, 0.0f, 1.0f);
2119         }
2120         else {
2121                 ctime = BKE_scene_frame_get(scene);
2122                 if (cu->pathlen) {
2123                         ctime /= cu->pathlen;
2124                 }
2125                 
2126                 CLAMP(ctime, 0.0f, 1.0f);
2127         }
2128         
2129         /* vec: 4 items! */
2130         if (where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat : NULL, &radius, NULL)) {
2131
2132                 if (cu->flag & CU_FOLLOW) {
2133 #if 0
2134                         float si, q[4];
2135                         vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
2136                         
2137                         /* the tilt */
2138                         normalize_v3(dir);
2139                         q[0] = cosf(0.5 * vec[3]);
2140                         si = sinf(0.5 * vec[3]);
2141                         q[1] = -si * dir[0];
2142                         q[2] = -si * dir[1];
2143                         q[3] = -si * dir[2];
2144                         mul_qt_qtqt(quat, q, quat);
2145 #else
2146                         quat_apply_track(quat, ob->trackflag, ob->upflag);
2147 #endif
2148                         normalize_qt(quat);
2149                         quat_to_mat4(mat, quat);
2150                 }
2151                 
2152                 if (cu->flag & CU_PATH_RADIUS) {
2153                         float tmat[4][4], rmat[4][4];
2154                         scale_m4_fl(tmat, radius);
2155                         mul_m4_m4m4(rmat, tmat, mat);
2156                         copy_m4_m4(mat, rmat);
2157                 }
2158
2159                 copy_v3_v3(mat[3], vec);
2160                 
2161         }
2162 }
2163
2164 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
2165 {       
2166         bPoseChannel *pchan;
2167         float vec[3];
2168         
2169         if (par->type != OB_ARMATURE) {
2170                 unit_m4(mat);
2171                 return;
2172         }
2173         
2174         /* Make sure the bone is still valid */
2175         pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
2176         if (!pchan || !pchan->bone) {
2177                 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
2178                 unit_m4(mat);
2179                 return;
2180         }
2181
2182         /* get bone transform */
2183         if (pchan->bone->flag & BONE_RELATIVE_PARENTING) {
2184                 /* the new option uses the root - expected bahaviour, but differs from old... */
2185                 /* XXX check on version patching? */
2186                 copy_m4_m4(mat, pchan->chan_mat);
2187         }
2188         else {
2189                 copy_m4_m4(mat, pchan->pose_mat);
2190
2191                 /* but for backwards compatibility, the child has to move to the tail */
2192                 copy_v3_v3(vec, mat[1]);
2193                 mul_v3_fl(vec, pchan->bone->length);
2194                 add_v3_v3(mat[3], vec);
2195         }
2196 }
2197
2198 static void give_parvert(Object *par, int nr, float vec[3])
2199 {
2200         zero_v3(vec);
2201         
2202         if (par->type == OB_MESH) {
2203                 Mesh *me = par->data;
2204                 BMEditMesh *em = me->edit_btmesh;
2205                 DerivedMesh *dm;
2206
2207                 dm = (em) ? em->derivedFinal : par->derivedFinal;
2208                         
2209                 if (dm) {
2210                         int count = 0;
2211                         int numVerts = dm->getNumVerts(dm);
2212
2213                         if (nr < numVerts) {
2214                                 bool use_special_ss_case = false;
2215
2216                                 if (dm->type == DM_TYPE_CCGDM) {
2217                                         ModifierData *md;
2218                                         VirtualModifierData virtualModifierData;
2219                                         use_special_ss_case = true;
2220                                         for (md = modifiers_getVirtualModifierList(par, &virtualModifierData);
2221                                              md != NULL;
2222                                              md = md->next)
2223                                         {
2224                                                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2225                                                 /* TODO(sergey): Check for disabled modifiers. */
2226                                                 if (mti->type != eModifierTypeType_OnlyDeform && md->next != NULL) {
2227                                                         use_special_ss_case = false;
2228                                                         break;
2229                                                 }
2230                                         }
2231                                 }
2232
2233                                 if (!use_special_ss_case) {
2234                                         /* avoid dm->getVertDataArray() since it allocates arrays in the dm (not thread safe) */
2235                                         if (em && dm->type == DM_TYPE_EDITBMESH) {
2236                                                 if (em->bm->elem_table_dirty & BM_VERT) {
2237 #ifdef VPARENT_THREADING_HACK
2238                                                         BLI_mutex_lock(&vparent_lock);
2239                                                         if (em->bm->elem_table_dirty & BM_VERT) {
2240                                                                 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
2241                                                         }
2242                                                         BLI_mutex_unlock(&vparent_lock);
2243 #else
2244                                                         BLI_assert(!"Not safe for threading");
2245                                                         BM_mesh_elem_table_ensure(em->bm, BM_VERT);
2246 #endif
2247                                                 }
2248                                         }
2249                                 }
2250
2251                                 if (use_special_ss_case) {
2252                                         /* Special case if the last modifier is SS and no constructive modifier are in front of it. */
2253                                         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2254                                         CCGVert *ccg_vert = ccgSubSurf_getVert(ccgdm->ss, SET_INT_IN_POINTER(nr));
2255                                         /* In case we deleted some verts, nr may refer to inexistent one now, see T42557. */
2256                                         if (ccg_vert) {
2257                                                 float *co = ccgSubSurf_getVertData(ccgdm->ss, ccg_vert);
2258                                                 add_v3_v3(vec, co);
2259                                                 count++;
2260                                         }
2261                                 }
2262                                 else if (CustomData_has_layer(&dm->vertData, CD_ORIGINDEX) &&
2263                                          !(em && dm->type == DM_TYPE_EDITBMESH))
2264                                 {
2265                                         int i;
2266
2267                                         /* Get the average of all verts with (original index == nr). */
2268                                         for (i = 0; i < numVerts; i++) {
2269                                                 const int *index = dm->getVertData(dm, i, CD_ORIGINDEX);
2270                                                 if (*index == nr) {
2271                                                         float co[3];
2272                                                         dm->getVertCo(dm, i, co);
2273                                                         add_v3_v3(vec, co);
2274                                                         count++;
2275                                                 }
2276                                         }
2277                                 }
2278                                 else {
2279                                         if (nr < numVerts) {
2280                                                 float co[3];
2281                                                 dm->getVertCo(dm, nr, co);
2282                                                 add_v3_v3(vec, co);
2283                                                 count++;
2284                                         }
2285                                 }
2286                         }
2287
2288                         if (count == 0) {
2289                                 /* keep as 0, 0, 0 */
2290                         }
2291                         else if (count > 0) {
2292                                 mul_v3_fl(vec, 1.0f / count);
2293                         }
2294                         else {
2295                                 /* use first index if its out of range */
2296                                 dm->getVertCo(dm, 0, vec);
2297                         }
2298                 }
2299                 else {
2300                         fprintf(stderr,
2301                                 "%s: DerivedMesh is needed to solve parenting, "
2302                                 "object position can be wrong now\n", __func__);
2303                 }
2304         }
2305         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
2306                 ListBase *nurb;
2307
2308                 /* Unless there's some weird depsgraph failure the cache should exist. */
2309                 BLI_assert(par->curve_cache != NULL);
2310
2311                 if (par->curve_cache->deformed_nurbs.first != NULL) {
2312                         nurb = &par->curve_cache->deformed_nurbs;
2313                 }
2314                 else {
2315                         Curve *cu = par->data;
2316                         nurb = BKE_curve_nurbs_get(cu);
2317                 }
2318
2319                 BKE_nurbList_index_get_co(nurb, nr, vec);
2320         }
2321         else if (par->type == OB_LATTICE) {
2322                 Lattice *latt  = par->data;
2323                 DispList *dl   = par->curve_cache ? BKE_displist_find(&par->curve_cache->disp, DL_VERTS) : NULL;
2324                 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
2325                 int tot;
2326
2327                 if (latt->editlatt) latt = latt->editlatt->latt;
2328
2329                 tot = latt->pntsu * latt->pntsv * latt->pntsw;
2330
2331                 /* ensure dl is correct size */
2332                 BLI_assert(dl == NULL || dl->nr == tot);
2333
2334                 if (nr < tot) {
2335                         if (co) {
2336                                 copy_v3_v3(vec, co[nr]);
2337                         }
2338                         else {
2339                                 copy_v3_v3(vec, latt->def[nr].vec);
2340                         }
2341                 }
2342         }
2343 }
2344
2345 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
2346 {
2347
2348         /* in local ob space */
2349         if (OB_TYPE_SUPPORT_PARVERT(par->type)) {
2350                 float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2351
2352                 give_parvert(par, ob->par1, v1);
2353                 give_parvert(par, ob->par2, v2);
2354                 give_parvert(par, ob->par3, v3);
2355
2356                 tri_to_quat(q, v1, v2, v3);
2357                 quat_to_mat3(cmat, q);
2358                 copy_m4_m3(mat, cmat);
2359
2360                 mid_v3_v3v3v3(mat[3], v1, v2, v3);
2361         }
2362         else {
2363                 unit_m4(mat);
2364         }
2365 }
2366
2367 static void ob_get_parent_matrix(Scene *scene, Object *ob, Object *par, float parentmat[4][4])
2368 {
2369         float tmat[4][4];
2370         float vec[3];
2371         bool ok;
2372
2373         switch (ob->partype & PARTYPE) {
2374                 case PAROBJECT:
2375                         ok = 0;
2376                         if (par->type == OB_CURVE) {
2377                                 if (scene && ((Curve *)par->data)->flag & CU_PATH) {
2378                                         ob_parcurve(scene, ob, par, tmat);
2379                                         ok = 1;
2380                                 }
2381                         }
2382                         
2383                         if (ok) mul_m4_m4m4(parentmat, par->obmat, tmat);
2384                         else copy_m4_m4(parentmat, par->obmat);
2385                         
2386                         break;
2387                 case PARBONE:
2388                         ob_parbone(ob, par, tmat);
2389                         mul_m4_m4m4(parentmat, par->obmat, tmat);
2390                         break;
2391                 
2392                 case PARVERT1:
2393                         unit_m4(parentmat);
2394                         give_parvert(par, ob->par1, vec);
2395                         mul_v3_m4v3(parentmat[3], par->obmat, vec);
2396                         break;
2397                 case PARVERT3:
2398                         ob_parvert3(ob, par, tmat);
2399                         
2400                         mul_m4_m4m4(parentmat, par->obmat, tmat);
2401                         break;
2402                 
2403                 case PARSKEL:
2404                         copy_m4_m4(parentmat, par->obmat);
2405                         break;
2406         }
2407
2408 }
2409
2410 /**
2411  * \param r_originmat  Optional matrix that stores the space the object is in (without its own matrix applied)
2412  */
2413 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4][4], float slowmat[4][4],
2414                             float r_originmat[3][3], const bool set_origin)
2415 {
2416         float totmat[4][4];
2417         float tmat[4][4];
2418         float locmat[4][4];
2419         
2420         BKE_object_to_mat4(ob, locmat);
2421         
2422         if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2423
2424         ob_get_parent_matrix(scene, ob, par, totmat);
2425         
2426         /* total */
2427         mul_m4_m4m4(tmat, totmat, ob->parentinv);
2428         mul_m4_m4m4(obmat, tmat, locmat);
2429         
2430         if (r_originmat) {
2431                 /* usable originmat */
2432                 copy_m3_m4(r_originmat, tmat);
2433         }
2434         
2435         /* origin, for help line */
2436         if (set_origin) {
2437                 if ((ob->partype & PARTYPE) == PARSKEL) {
2438                         copy_v3_v3(ob->orig, par->obmat[3]);
2439                 }
2440                 else {
2441                         copy_v3_v3(ob->orig, totmat[3]);
2442                 }
2443         }
2444 }
2445
2446 static bool where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
2447 {
2448         float *fp1, *fp2;
2449         float fac1, fac2;
2450         int a;
2451
2452         /* include framerate */
2453         fac1 = (1.0f / (1.0f + fabsf(ob->sf)));
2454         if (fac1 >= 1.0f) return false;
2455         fac2 = 1.0f - fac1;
2456
2457         fp1 = obmat[0];
2458         fp2 = slowmat[0];
2459         for (a = 0; a < 16; a++, fp1++, fp2++) {
2460                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2461         }
2462
2463         return true;
2464 }
2465
2466 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2467 void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime,
2468                                       RigidBodyWorld *rbw, float r_originmat[3][3])
2469 {
2470         if (ob == NULL) return;
2471         
2472         /* execute drivers only, as animation has already been done */
2473         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2474         
2475         if (ob->parent) {
2476                 Object *par = ob->parent;
2477                 float slowmat[4][4];
2478                 
2479                 /* calculate parent matrix */
2480                 solve_parenting(scene, ob, par, ob->obmat, slowmat, r_originmat, true);
2481                 
2482                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
2483                  * An old-fashioned hack which probably doesn't really cut it anymore
2484                  */
2485                 if (ob->partype & PARSLOW) {
2486                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2487                                 return;
2488                 }
2489         }
2490         else {
2491                 BKE_object_to_mat4(ob, ob->obmat);
2492         }
2493
2494         /* try to fall back to the scene rigid body world if none given */
2495         rbw = rbw ? rbw : scene->rigidbody_world;
2496         /* read values pushed into RBO from sim/cache... */
2497         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2498         
2499         /* solve constraints */
2500         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2501                 bConstraintOb *cob;
2502                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2503                 BKE_constraints_solve(&ob->constraints, cob, ctime);
2504                 BKE_constraints_clear_evalob(cob);
2505         }
2506         
2507         /* set negative scale flag in object */
2508         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2509         else ob->transflag &= ~OB_NEG_SCALE;
2510 }
2511
2512 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2513 {
2514         BKE_object_where_is_calc_time_ex(scene, ob, ctime, NULL, NULL);
2515 }
2516
2517 /* get object transformation matrix without recalculating dependencies and
2518  * constraints -- assume dependencies are already solved by depsgraph.
2519  * no changes to object and it's parent would be done.
2520  * used for bundles orientation in 3d space relative to parented blender camera */
2521 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2522 {
2523
2524         if (ob->parent) {
2525                 float slowmat[4][4];
2526
2527                 Object *par = ob->parent;
2528                 
2529                 solve_parenting(scene, ob, par, obmat, slowmat, NULL, false);
2530                 
2531                 if (ob->partype & PARSLOW)
2532                         where_is_object_parslow(ob, obmat, slowmat);
2533         }
2534         else {
2535                 BKE_object_to_mat4(ob, obmat);
2536         }
2537 }
2538
2539 void BKE_object_where_is_calc_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob, float r_originmat[3][3])
2540 {
2541         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), rbw, r_originmat);
2542 }
2543 void BKE_object_where_is_calc(Scene *scene, Object *ob)
2544 {
2545         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), NULL, NULL);
2546 }
2547
2548 /* for calculation of the inverse parent transform, only used for editor */
2549 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2550 {
2551         BKE_object_workob_clear(workob);
2552         
2553         unit_m4(workob->obmat);
2554         unit_m4(workob->parentinv);
2555         unit_m4(workob->constinv);
2556         workob->parent = ob->parent;
2557
2558         workob->trackflag = ob->trackflag;
2559         workob->upflag = ob->upflag;
2560         
2561         workob->partype = ob->partype;
2562         workob->par1 = ob->par1;
2563         workob->par2 = ob->par2;
2564         workob->par3 = ob->par3;
2565
2566         workob->constraints.first = ob->constraints.first;
2567         workob->constraints.last = ob->constraints.last;
2568
2569         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2570
2571         BKE_object_where_is_calc(scene, workob);
2572 }
2573
2574 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
2575 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const bool use_compat, const bool use_parent)
2576 {
2577         float rot[3][3];
2578
2579         if (use_parent && ob->parent) {
2580                 float rmat[4][4], diff_mat[4][4], imat[4][4], parent_mat[4][4];
2581
2582                 ob_get_parent_matrix(NULL, ob, ob->parent, parent_mat);
2583
2584                 mul_m4_m4m4(diff_mat, parent_mat, ob->parentinv);
2585                 invert_m4_m4(imat, diff_mat);
2586                 mul_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
2587
2588                 /* same as below, use rmat rather than mat */
2589                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
2590         }
2591         else {
2592                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
2593         }
2594
2595         BKE_object_mat3_to_rot(ob, rot, use_compat);
2596
2597         sub_v3_v3(ob->loc, ob->dloc);
2598
2599         if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
2600         if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
2601         if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
2602
2603         /* BKE_object_mat3_to_rot handles delta rotations */
2604 }
2605
2606 BoundBox *BKE_boundbox_alloc_unit(void)
2607 {
2608         BoundBox *bb;
2609         const float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2610
2611         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2612         BKE_boundbox_init_from_minmax(bb, min, max);
2613         
2614         return bb;
2615 }
2616
2617 void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float max[3])
2618 {
2619         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2620         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2621         
2622         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2623         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2624
2625         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2626         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2627 }
2628
2629 void BKE_boundbox_calc_center_aabb(const BoundBox *bb, float r_cent[3])
2630 {
2631         r_cent[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]);
2632         r_cent[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]);
2633         r_cent[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]);
2634 }
2635
2636 void BKE_boundbox_calc_size_aabb(const BoundBox *bb, float r_size[3])
2637 {
2638         r_size[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]);
2639         r_size[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]);
2640         r_size[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]);
2641 }
2642
2643 BoundBox *BKE_object_boundbox_get(Object *ob)
2644 {
2645         BoundBox *bb = NULL;
2646         
2647         if (ob->type == OB_MESH) {
2648                 bb = BKE_mesh_boundbox_get(ob);
2649         }
2650         else if (ELEM(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2651                 bb = BKE_curve_boundbox_get(ob);
2652         }
2653         else if (ob->type == OB_MBALL) {
2654                 bb = ob->bb;
2655         }
2656         return bb;
2657 }
2658
2659 /* used to temporally disable/enable boundbox */
2660 void BKE_object_boundbox_flag(Object *ob, int flag, const bool set)
2661 {
2662         BoundBox *bb = BKE_object_boundbox_get(ob);
2663         if (bb) {
2664                 if (set) bb->flag |= flag;
2665                 else bb->flag &= ~flag;
2666         }
2667 }
2668
2669 void BKE_object_dimensions_get(Object *ob, float vec[3])
2670 {
2671         BoundBox *bb = NULL;
2672         
2673         bb = BKE_object_boundbox_get(ob);
2674         if (bb) {
2675                 float scale[3];
2676                 
2677                 mat4_to_size(scale, ob->obmat);
2678                 
2679                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2680                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2681                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2682         }
2683         else {
2684                 zero_v3(vec);
2685         }
2686 }
2687
2688 void BKE_object_dimensions_set(Object *ob, const float value[3])
2689 {
2690         BoundBox *bb = NULL;
2691         
2692         bb = BKE_object_boundbox_get(ob);
2693         if (bb) {
2694                 float scale[3], len[3];
2695                 
2696                 mat4_to_size(scale, ob->obmat);
2697                 
2698                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2699                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2700                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2701                 
2702                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2703                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2704                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2705         }
2706 }
2707
2708 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool use_hidden)
2709 {
2710         BoundBox bb;
2711         float vec[3];
2712         int a;
2713         bool changed = false;
2714         
2715         switch (ob->type) {
2716                 case OB_CURVE:
2717                 case OB_FONT:
2718                 case OB_SURF:
2719                 {
2720                         bb = *BKE_curve_boundbox_get(ob);
2721
2722                         for (a = 0; a < 8; a++) {
2723                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2724                                 minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2725                         }
2726                         changed = true;
2727                         break;
2728                 }
2729                 case OB_LATTICE:
2730                 {
2731                         Lattice *lt = ob->data;
2732                         BPoint *bp = lt->def;
2733                         int u, v, w;
2734
2735                         for (w = 0; w < lt->pntsw; w++) {
2736                                 for (v = 0; v < lt->pntsv; v++) {
2737                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2738                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2739                                                 minmax_v3v3_v3(min_r, max_r, vec);
2740                                         }
2741                                 }
2742                         }
2743                         changed = true;
2744                         break;
2745                 }
2746                 case OB_ARMATURE:
2747                 {
2748                         if (ob->pose) {
2749                                 bArmature *arm = ob->data;
2750                                 bPoseChannel *pchan;
2751
2752                                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2753                                         /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2754                                          *     (editarmature.c:2592)... Skip in this case too! */
2755                                         if (pchan->bone && !((use_hidden == false) && (PBONE_VISIBLE(arm, pchan->bone) == false))) {
2756                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2757                                                 minmax_v3v3_v3(min_r, max_r, vec);
2758                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2759                                                 minmax_v3v3_v3(min_r, max_r, vec);
2760
2761                                                 changed = true;
2762                                         }
2763                                 }
2764                         }
2765                         break;
2766                 }
2767                 case OB_MESH:
2768                 {
2769                         Mesh *me = BKE_mesh_from_object(ob);
2770
2771                         if (me) {
2772                                 bb = *BKE_mesh_boundbox_get(ob);
2773
2774                                 for (a = 0; a < 8; a++) {
2775                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2776                                         minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2777                                 }
2778                                 changed = true;
2779                         }
2780                         break;
2781                 }
2782                 case OB_MBALL:
2783                 {
2784                         float ob_min[3], ob_max[3];
2785
2786                         changed = BKE_mball_minmax_ex(ob->data, ob_min, ob_max, ob->obmat, 0);
2787                         if (changed) {
2788                                 minmax_v3v3_v3(min_r, max_r, ob_min);
2789                                 minmax_v3v3_v3(min_r, max_r, ob_max);
2790                         }
2791                         break;
2792                 }
2793         }
2794
2795         if (changed == false) {
2796                 float size[3];
2797
2798                 copy_v3_v3(size, ob->size);
2799                 if (ob->type == OB_EMPTY) {
2800                         mul_v3_fl(size, ob->empty_drawsize);
2801                 }
2802
2803                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2804
2805                 copy_v3_v3(vec, ob->obmat[3]);
2806                 add_v3_v3(vec, size);
2807                 minmax_v3v3_v3(min_r, max_r, vec);
2808
2809                 copy_v3_v3(vec, ob->obmat[3]);
2810                 sub_v3_v3(vec, size);
2811                 minmax_v3v3_v3(min_r, max_r, vec);
2812         }
2813 }
2814
2815 void BKE_object_empty_draw_type_set(Object *ob, const int value)
2816 {
2817         ob->empty_drawtype = value;
2818
2819         if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
2820                 if (!ob->iuser) {
2821                         ob->iuser = MEM_callocN(sizeof(ImageUser), "image user");
2822                         ob->iuser->ok = 1;
2823                         ob->iuser->frames = 100;
2824                         ob->iuser->sfra = 1;
2825                         ob->iuser->fie_ima = 2;
2826                 }
2827         }
2828         else {
2829                 if (ob->iuser) {
2830                         MEM_freeN(ob->iuser);
2831                         ob->iuser = NULL;
2832                 }
2833         }
2834 }
2835
2836 bool BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const bool use_hidden)
2837 {
2838         bool ok = false;
2839         if ((ob->transflag & OB_DUPLI) == 0) {
2840                 return ok;
2841         }
2842         else {
2843                 ListBase *lb;
2844                 DupliObject *dob;
2845                 lb = object_duplilist(G.main->eval_ctx, scene, ob);
2846                 for (dob = lb->first; dob; dob = dob->next) {
2847                         if ((use_hidden == false) && (dob->no_draw != 0)) {
2848                                 /* pass */
2849                         }
2850                         else {
2851                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2852
2853                                 if (bb) {
2854                                         int i;
2855                                         for (i = 0; i < 8; i++) {
2856                                                 float vec[3];
2857                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2858                                                 minmax_v3v3_v3(r_min, r_max, vec);
2859                                         }
2860
2861                                         ok = true;
2862                                 }
2863                         }
2864                 }
2865                 free_object_duplilist(lb);  /* does restore */
2866         }
2867
2868         return ok;
2869 }
2870
2871 void BKE_object_foreach_display_point(
2872         Object *ob, float obmat[4][4],
2873         void (*func_cb)(const float[3], void *), void *user_data)
2874 {
2875         float co[3];
2876
2877         if (ob->derivedFinal) {
2878                 DerivedMesh *dm = ob->derivedFinal;
2879                 MVert *mv = dm->getVertArray(dm);
2880                 int totvert = dm->getNumVerts(dm);
2881                 int i;
2882
2883                 for (i = 0; i < totvert; i++, mv++) {
2884                         mul_v3_m4v3(co, obmat, mv->co);
2885                         func_cb(co, user_data);
2886                 }
2887         }
2888         else if (ob->curve_cache && ob->curve_cache->disp.first) {
2889                 DispList *dl;
2890
2891                 for (dl = ob->curve_cache->disp.first; dl; dl = dl->next) {
2892                         const float *v3 = dl->verts;
2893                         int totvert = dl->nr;
2894                         int i;
2895
2896                         for (i = 0; i < totvert; i++, v3 += 3) {
2897                                 mul_v3_m4v3(co, obmat, v3);
2898                                 func_cb(co, user_data);
2899                         }
2900                 }
2901         }
2902 }
2903
2904 void BKE_scene_foreach_display_point(
2905         Scene *scene, View3D *v3d, const short flag,
2906         void (*func_cb)(const float[3], void *), void *user_data)
2907 {
2908         Base *base;
2909         Object *ob;
2910
2911         for (base = FIRSTBASE; base; base = base->next) {
2912                 if (BASE_VISIBLE_BGMODE(v3d, scene, base) && (base->flag & flag) == flag) {
2913                         ob = base->object;
2914
2915                         if ((ob->transflag & OB_DUPLI) == 0) {
2916                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2917                         }
2918                         else {
2919                                 ListBase *lb;
2920                                 DupliObject *dob;
2921
2922                                 lb = object_duplilist(G.main->eval_ctx, scene, ob);
2923                                 for (dob = lb->first; dob; dob = dob->next) {
2924                                         if (dob->no_draw == 0) {
2925                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2926                                         }
2927                                 }
2928                                 free_object_duplilist(lb);  /* does restore */
2929                         }
2930                 }
2931         }
2932 }
2933
2934 /* copied from DNA_object_types.h */
2935 typedef struct ObTfmBack {
2936         float loc[3], dloc[3], orig[3];
2937         float size[3], dscale[3];   /* scale and delta scale */
2938         float rot[3], drot[3];      /* euler rotation */
2939         float quat[4], dquat[4];    /* quaternion rotation */
2940         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2941         float rotAngle, drotAngle;  /* axis angle rotation - angle part */
2942         float obmat[4][4];      /* final worldspace matrix with constraints & animsys applied */
2943         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2944         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2945         float imat[4][4];   /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2946 } ObTfmBack;
2947
2948 void *BKE_object_tfm_backup(Object *ob)
2949 {
2950         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2951         copy_v3_v3(obtfm->loc, ob->loc);
2952         copy_v3_v3(obtfm->dloc, ob->dloc);
2953         copy_v3_v3(obtfm->orig, ob->orig);
2954         copy_v3_v3(obtfm->size, ob->size);
2955         copy_v3_v3(obtfm->dscale, ob->dscale);
2956         copy_v3_v3(obtfm->rot, ob->rot);
2957         copy_v3_v3(obtfm->drot, ob->drot);
2958         copy_qt_qt(obtfm->quat, ob->quat);
2959         copy_qt_qt(obtfm->dquat, ob->dquat);
2960         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2961         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2962         obtfm->rotAngle = ob->rotAngle;
2963         obtfm->drotAngle = ob->drotAngle;
2964         copy_m4_m4(obtfm->obmat, ob->obmat);
2965         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2966         copy_m4_m4(obtfm->constinv, ob->constinv);
2967         copy_m4_m4(obtfm->imat, ob->imat);
2968
2969         return (void *)obtfm;
2970 }
2971
2972 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2973 {
2974         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2975         copy_v3_v3(ob->loc, obtfm->loc);
2976         copy_v3_v3(ob->dloc, obtfm->dloc);
2977         copy_v3_v3(ob->orig, obtfm->orig);
2978         copy_v3_v3(ob->size, obtfm->size);
2979         copy_v3_v3(ob->dscale, obtfm->dscale);
2980         copy_v3_v3(ob->rot, obtfm->rot);
2981         copy_v3_v3(ob->drot, obtfm->drot);
2982         copy_qt_qt(ob->quat, obtfm->quat);
2983         copy_qt_qt(ob->dquat, obtfm->dquat);
2984         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2985         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2986         ob->rotAngle = obtfm->rotAngle;
2987         ob->drotAngle = obtfm->drotAngle;
2988         copy_m4_m4(ob->obmat, obtfm->obmat);
2989         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2990         copy_m4_m4(ob->constinv, obtfm->constinv);
2991         copy_m4_m4(ob->imat, obtfm->imat);
2992 }
2993
2994 bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
2995 {
2996         /* test if 'ob' is a parent somewhere in par's parents */
2997         if (par == NULL) return false;
2998         if (ob == par) return true;
2999         return BKE_object_parent_loop_check(par->parent, ob);
3000 }
3001
3002 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
3003 /*           local_object->proxy      == pointer to library object, saved in files and read */
3004
3005 /* function below is polluted with proxy exceptions, cleanup will follow! */
3006
3007 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
3008 /* requires flags to be set! */
3009 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
3010 void BKE_object_handle_update_ex(EvaluationContext *eval_ctx,
3011                                  Scene *scene, Object *ob,
3012                                  RigidBodyWorld *rbw,
3013                                  const bool do_proxy_update)
3014 {
3015         if (ob->recalc & OB_RECALC_ALL) {
3016                 /* speed optimization for animation lookups */
3017                 if (ob->pose) {
3018                         BKE_pose_channels_hash_make(ob->pose);
3019                         if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
3020                                 BKE_pose_update_constraint_flags(ob->pose);
3021                         }
3022                 }
3023
3024                 if (ob->recalc & OB_RECALC_DATA) {
3025                         if (ob->type == OB_ARMATURE) {
3026                                 /* this happens for reading old files and to match library armatures
3027                                  * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
3028                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
3029                                  * on file load */
3030                                 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
3031                                         BKE_pose_rebuild(ob, ob->data);
3032                         }
3033                 }
3034
3035                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
3036                  * which is only in BKE_object_where_is_calc now */
3037                 /* XXX: should this case be OB_RECALC_OB instead? */
3038                 if (ob->recalc & OB_RECALC_ALL) {
3039                         
3040                         if (G.debug & G_DEBUG_DEPSGRAPH)
3041                                 printf("recalcob %s\n", ob->id.name + 2);
3042                         
3043                         /* handle proxy copy for target */
3044                         if (ob->id.lib && ob->proxy_from) {
3045                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
3046                                 if (ob->proxy_from->proxy_group) { /* transform proxy i