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