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