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