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