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