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