svn merge -r40000:40179 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[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_view3d_types.h"
60 #include "DNA_world_types.h"
61
62 #include "BLI_blenlib.h"
63 #include "BLI_editVert.h"
64 #include "BLI_math.h"
65 #include "BLI_pbvh.h"
66 #include "BLI_utildefines.h"
67
68 #include "BKE_main.h"
69 #include "BKE_global.h"
70 #include "BKE_idprop.h"
71 #include "BKE_armature.h"
72 #include "BKE_action.h"
73 #include "BKE_bullet.h"
74 #include "BKE_colortools.h"
75 #include "BKE_deform.h"
76 #include "BKE_DerivedMesh.h"
77 #include "BKE_animsys.h"
78 #include "BKE_anim.h"
79 #include "BKE_constraint.h"
80 #include "BKE_curve.h"
81 #include "BKE_displist.h"
82 #include "BKE_effect.h"
83 #include "BKE_fcurve.h"
84 #include "BKE_group.h"
85 #include "BKE_icons.h"
86 #include "BKE_key.h"
87 #include "BKE_lattice.h"
88 #include "BKE_library.h"
89 #include "BKE_mesh.h"
90 #include "BKE_mball.h"
91 #include "BKE_modifier.h"
92 #include "BKE_object.h"
93 #include "BKE_paint.h"
94 #include "BKE_particle.h"
95 #include "BKE_pointcache.h"
96 #include "BKE_property.h"
97 #include "BKE_sca.h"
98 #include "BKE_scene.h"
99 #include "BKE_sequencer.h"
100 #include "BKE_speaker.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 /* *************************************************** */
981
982 static void *add_obdata_from_type(int type)
983 {
984         switch (type) {
985         case OB_MESH: return add_mesh("Mesh");
986         case OB_CURVE: return add_curve("Curve", OB_CURVE);
987         case OB_SURF: return add_curve("Surf", OB_SURF);
988         case OB_FONT: return add_curve("Text", OB_FONT);
989         case OB_MBALL: return add_mball("Meta");
990         case OB_CAMERA: return add_camera("Camera");
991         case OB_LAMP: return add_lamp("Lamp");
992         case OB_LATTICE: return add_lattice("Lattice");
993         case OB_ARMATURE: return add_armature("Armature");
994         case OB_SPEAKER: return add_speaker("Speaker");
995         case OB_EMPTY: return NULL;
996         default:
997                 printf("add_obdata_from_type: Internal error, bad type: %d\n", type);
998                 return NULL;
999         }
1000 }
1001
1002 static const char *get_obdata_defname(int type)
1003 {
1004         switch (type) {
1005         case OB_MESH: return "Mesh";
1006         case OB_CURVE: return "Curve";
1007         case OB_SURF: return "Surf";
1008         case OB_FONT: return "Text";
1009         case OB_MBALL: return "Mball";
1010         case OB_CAMERA: return "Camera";
1011         case OB_LAMP: return "Lamp";
1012         case OB_LATTICE: return "Lattice";
1013         case OB_ARMATURE: return "Armature";
1014         case OB_SPEAKER: return "Speaker";
1015         case OB_EMPTY: return "Empty";
1016         default:
1017                 printf("get_obdata_defname: Internal error, bad type: %d\n", type);
1018                 return "Empty";
1019         }
1020 }
1021
1022 /* more general add: creates minimum required data, but without vertices etc. */
1023 Object *add_only_object(int type, const char *name)
1024 {
1025         Object *ob;
1026
1027         ob= alloc_libblock(&G.main->object, ID_OB, name);
1028
1029         /* default object vars */
1030         ob->type= type;
1031         
1032         ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
1033         ob->col[3]= 1.0;
1034         
1035         ob->size[0]= ob->size[1]= ob->size[2]= 1.0;
1036         
1037         /* objects should default to having Euler XYZ rotations, 
1038          * but rotations default to quaternions 
1039          */
1040         ob->rotmode= ROT_MODE_EUL;
1041
1042         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
1043         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
1044
1045         unit_qt(ob->quat);
1046         unit_qt(ob->dquat);
1047
1048         /* rotation locks should be 4D for 4 component rotations by default... */
1049         ob->protectflag = OB_LOCK_ROT4D;
1050         
1051         unit_m4(ob->constinv);
1052         unit_m4(ob->parentinv);
1053         unit_m4(ob->obmat);
1054         ob->dt= OB_TEXTURE;
1055         ob->empty_drawtype= OB_PLAINAXES;
1056         ob->empty_drawsize= 1.0;
1057
1058         if(type==OB_CAMERA || type==OB_LAMP || type==OB_SPEAKER) {
1059                 ob->trackflag= OB_NEGZ;
1060                 ob->upflag= OB_POSY;
1061         }
1062         else {
1063                 ob->trackflag= OB_POSY;
1064                 ob->upflag= OB_POSZ;
1065         }
1066         
1067         ob->dupon= 1; ob->dupoff= 0;
1068         ob->dupsta= 1; ob->dupend= 100;
1069         ob->dupfacesca = 1.0;
1070
1071         /* Game engine defaults*/
1072         ob->mass= ob->inertia= 1.0f;
1073         ob->formfactor= 0.4f;
1074         ob->damping= 0.04f;
1075         ob->rdamping= 0.1f;
1076         ob->anisotropicFriction[0] = 1.0f;
1077         ob->anisotropicFriction[1] = 1.0f;
1078         ob->anisotropicFriction[2] = 1.0f;
1079         ob->gameflag= OB_PROP|OB_COLLISION;
1080         ob->margin = 0.0;
1081         ob->init_state=1;
1082         ob->state=1;
1083         /* ob->pad3 == Contact Processing Threshold */
1084         ob->m_contactProcessingThreshold = 1.;
1085         ob->obstacleRad = 1.;
1086         
1087         /* NT fluid sim defaults */
1088         ob->fluidsimFlag = 0;
1089         ob->fluidsimSettings = NULL;
1090
1091         ob->pc_ids.first = ob->pc_ids.last = NULL;
1092         
1093         /* Animation Visualisation defaults */
1094         animviz_settings_init(&ob->avs);
1095
1096         return ob;
1097 }
1098
1099 /* general add: to scene, with layer from area and default name */
1100 /* creates minimum required data, but without vertices etc. */
1101 Object *add_object(struct Scene *scene, int type)
1102 {
1103         Object *ob;
1104         Base *base;
1105         char name[32];
1106
1107         BLI_strncpy(name, get_obdata_defname(type), sizeof(name));
1108         ob = add_only_object(type, name);
1109
1110         ob->data= add_obdata_from_type(type);
1111
1112         ob->lay= scene->lay;
1113         
1114         base= scene_add_base(scene, ob);
1115         scene_select_base(scene, base);
1116         ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
1117
1118         return ob;
1119 }
1120
1121 SoftBody *copy_softbody(SoftBody *sb)
1122 {
1123         SoftBody *sbn;
1124         
1125         if (sb==NULL) return(NULL);
1126         
1127         sbn= MEM_dupallocN(sb);
1128         sbn->totspring= sbn->totpoint= 0;
1129         sbn->bpoint= NULL;
1130         sbn->bspring= NULL;
1131         
1132         sbn->keys= NULL;
1133         sbn->totkey= sbn->totpointkey= 0;
1134         
1135         sbn->scratch= NULL;
1136
1137         sbn->pointcache= BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches);
1138
1139         if(sb->effector_weights)
1140                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1141
1142         return sbn;
1143 }
1144
1145 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1146 {
1147         BulletSoftBody *bsbn;
1148
1149         if (bsb == NULL)
1150                 return NULL;
1151         bsbn = MEM_dupallocN(bsb);
1152         /* no pointer in this structure yet */
1153         return bsbn;
1154 }
1155
1156 static ParticleSystem *copy_particlesystem(ParticleSystem *psys)
1157 {
1158         ParticleSystem *psysn;
1159         ParticleData *pa;
1160         int p;
1161
1162         psysn= MEM_dupallocN(psys);
1163         psysn->particles= MEM_dupallocN(psys->particles);
1164         psysn->child= MEM_dupallocN(psys->child);
1165
1166         if(psys->part->type == PART_HAIR) {
1167                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++)
1168                         pa->hair = MEM_dupallocN(pa->hair);
1169         }
1170
1171         if(psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
1172                 ParticleKey *key = psysn->particles->keys;
1173                 BoidParticle *boid = psysn->particles->boid;
1174
1175                 if(key)
1176                         key = MEM_dupallocN(key);
1177                 
1178                 if(boid)
1179                         boid = MEM_dupallocN(boid);
1180                 
1181                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++) {
1182                         if(boid)
1183                                 pa->boid = boid++;
1184                         if(key) {
1185                                 pa->keys = key;
1186                                 key += pa->totkey;
1187                         }
1188                 }
1189         }
1190
1191         if(psys->clmd) {
1192                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1193                 modifier_copyData((ModifierData*)psys->clmd, (ModifierData*)psysn->clmd);
1194                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1195         }
1196
1197         BLI_duplicatelist(&psysn->targets, &psys->targets);
1198
1199         psysn->pathcache= NULL;
1200         psysn->childcache= NULL;
1201         psysn->edit= NULL;
1202         psysn->frand= NULL;
1203         psysn->pdd= NULL;
1204         psysn->effectors= NULL;
1205         
1206         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1207         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1208         psysn->renderdata = NULL;
1209         
1210         psysn->pointcache= BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches);
1211
1212         /* XXX - from reading existing code this seems correct but intended usage of
1213          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1214         if(psysn->clmd) {
1215                 psysn->clmd->point_cache= psysn->pointcache;
1216         }
1217
1218         id_us_plus((ID *)psysn->part);
1219
1220         return psysn;
1221 }
1222
1223 void copy_object_particlesystems(Object *obn, Object *ob)
1224 {
1225         ParticleSystemModifierData *psmd;
1226         ParticleSystem *psys, *npsys;
1227         ModifierData *md;
1228
1229         obn->particlesystem.first= obn->particlesystem.last= NULL;
1230         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
1231                 npsys= copy_particlesystem(psys);
1232
1233                 BLI_addtail(&obn->particlesystem, npsys);
1234
1235                 /* need to update particle modifiers too */
1236                 for(md=obn->modifiers.first; md; md=md->next) {
1237                         if(md->type==eModifierType_ParticleSystem) {
1238                                 psmd= (ParticleSystemModifierData*)md;
1239                                 if(psmd->psys==psys)
1240                                         psmd->psys= npsys;
1241                         }
1242                 }
1243         }
1244 }
1245
1246 void copy_object_softbody(Object *obn, Object *ob)
1247 {
1248         if(ob->soft)
1249                 obn->soft= copy_softbody(ob->soft);
1250 }
1251
1252 static void copy_object_pose(Object *obn, Object *ob)
1253 {
1254         bPoseChannel *chan;
1255         
1256         /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
1257         obn->pose= NULL;
1258         copy_pose(&obn->pose, ob->pose, 1);     /* 1 = copy constraints */
1259
1260         for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
1261                 bConstraint *con;
1262                 
1263                 chan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1264                 
1265                 for (con= chan->constraints.first; con; con= con->next) {
1266                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1267                         ListBase targets = {NULL, NULL};
1268                         bConstraintTarget *ct;
1269                         
1270 #if 0 // XXX old animation system
1271                         /* note that we can't change lib linked ipo blocks. for making
1272                          * proxies this still works correct however because the object
1273                          * is changed to object->proxy_from when evaluating the driver. */
1274                         if(con->ipo && !con->ipo->id.lib) {
1275                                 IpoCurve *icu;
1276                                 
1277                                 con->ipo= copy_ipo(con->ipo);
1278                                 
1279                                 for(icu= con->ipo->curve.first; icu; icu= icu->next) {
1280                                         if(icu->driver && icu->driver->ob==ob)
1281                                                 icu->driver->ob= obn;
1282                                 }
1283                         }
1284 #endif // XXX old animation system
1285                         
1286                         if (cti && cti->get_constraint_targets) {
1287                                 cti->get_constraint_targets(con, &targets);
1288                                 
1289                                 for (ct= targets.first; ct; ct= ct->next) {
1290                                         if (ct->tar == ob)
1291                                                 ct->tar = obn;
1292                                 }
1293                                 
1294                                 if (cti->flush_constraint_targets)
1295                                         cti->flush_constraint_targets(con, &targets, 0);
1296                         }
1297                 }
1298         }
1299 }
1300
1301 static void copy_object_transform(Object *ob_tar, Object *ob_src)
1302 {
1303         copy_v3_v3(ob_tar->loc, ob_src->loc);
1304         copy_v3_v3(ob_tar->rot, ob_src->rot);
1305         copy_v3_v3(ob_tar->quat, ob_src->quat);
1306         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1307         ob_tar->rotAngle= ob_src->rotAngle;
1308         ob_tar->rotmode= ob_src->rotmode;
1309         copy_v3_v3(ob_tar->size, ob_src->size);
1310 }
1311
1312 Object *copy_object(Object *ob)
1313 {
1314         Object *obn;
1315         ModifierData *md;
1316         int a;
1317
1318         obn= copy_libblock(ob);
1319         
1320         if(ob->totcol) {
1321                 obn->mat= MEM_dupallocN(ob->mat);
1322                 obn->matbits= MEM_dupallocN(ob->matbits);
1323                 obn->totcol= ob->totcol;
1324         }
1325         
1326         if(ob->bb) obn->bb= MEM_dupallocN(ob->bb);
1327         obn->path= NULL;
1328         obn->flag &= ~OB_FROMGROUP;
1329         
1330         obn->modifiers.first = obn->modifiers.last= NULL;
1331         
1332         for (md=ob->modifiers.first; md; md=md->next) {
1333                 ModifierData *nmd = modifier_new(md->type);
1334                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1335                 modifier_copyData(md, nmd);
1336                 BLI_addtail(&obn->modifiers, nmd);
1337         }
1338
1339         obn->prop.first = obn->prop.last = NULL;
1340         copy_properties(&obn->prop, &ob->prop);
1341         
1342         copy_sensors(&obn->sensors, &ob->sensors);
1343         copy_controllers(&obn->controllers, &ob->controllers);
1344         copy_actuators(&obn->actuators, &ob->actuators);
1345         
1346         if(ob->pose) {
1347                 copy_object_pose(obn, ob);
1348                 /* backwards compat... non-armatures can get poses in older files? */
1349                 if(ob->type==OB_ARMATURE)
1350                         armature_rebuild_pose(obn, obn->data);
1351         }
1352         defgroup_copy_list(&obn->defbase, &ob->defbase);
1353         copy_constraints(&obn->constraints, &ob->constraints, TRUE);
1354
1355         obn->mode = 0;
1356         obn->sculpt = NULL;
1357
1358         /* increase user numbers */
1359         id_us_plus((ID *)obn->data);
1360         id_us_plus((ID *)obn->gpd);
1361         id_lib_extern((ID *)obn->dup_group);
1362
1363         for(a=0; a<obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1364         
1365         obn->disp.first= obn->disp.last= NULL;
1366         
1367         if(ob->pd){
1368                 obn->pd= MEM_dupallocN(ob->pd);
1369                 if(obn->pd->tex)
1370                         id_us_plus(&(obn->pd->tex->id));
1371                 if(obn->pd->rng)
1372                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1373         }
1374         obn->soft= copy_softbody(ob->soft);
1375         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1376
1377         copy_object_particlesystems(obn, ob);
1378         
1379         obn->derivedDeform = NULL;
1380         obn->derivedFinal = NULL;
1381
1382         obn->gpulamp.first = obn->gpulamp.last = NULL;
1383         obn->pc_ids.first = obn->pc_ids.last = NULL;
1384
1385         obn->mpath= NULL;
1386         
1387         return obn;
1388 }
1389
1390 static void extern_local_object(Object *ob)
1391 {
1392         //bActionStrip *strip;
1393         ParticleSystem *psys;
1394
1395 #if 0 // XXX old animation system
1396         id_lib_extern((ID *)ob->action);
1397         id_lib_extern((ID *)ob->ipo);
1398 #endif // XXX old animation system
1399         id_lib_extern((ID *)ob->data);
1400         id_lib_extern((ID *)ob->dup_group);
1401         id_lib_extern((ID *)ob->poselib);
1402         id_lib_extern((ID *)ob->gpd);
1403
1404         extern_local_matarar(ob->mat, ob->totcol);
1405
1406 #if 0 // XXX old animation system
1407         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1408                 id_lib_extern((ID *)strip->act);
1409         }
1410 #endif // XXX old animation system
1411         for(psys=ob->particlesystem.first; psys; psys=psys->next)
1412                 id_lib_extern((ID *)psys->part);
1413 }
1414
1415 void make_local_object(Object *ob)
1416 {
1417         Main *bmain= G.main;
1418         Scene *sce;
1419         Base *base;
1420         int local=0, lib=0;
1421
1422         /* - only lib users: do nothing
1423          * - only local users: set flag
1424          * - mixed: make copy
1425          */
1426
1427         if(ob->id.lib==NULL) return;
1428         
1429         ob->proxy= ob->proxy_from= NULL;
1430         
1431         if(ob->id.us==1) {
1432                 ob->id.lib= NULL;
1433                 ob->id.flag= LIB_LOCAL;
1434                 new_id(&bmain->object, (ID *)ob, NULL);
1435         }
1436         else {
1437                 for(sce= bmain->scene.first; sce && ELEM(0, lib, local); sce= sce->id.next) {
1438                         if(object_in_scene(ob, sce)) {
1439                                 if(sce->id.lib) lib= 1;
1440                                 else local= 1;
1441                         }
1442                 }
1443
1444                 if(local && lib==0) {
1445                         ob->id.lib= NULL;
1446                         ob->id.flag= LIB_LOCAL;
1447                         new_id(&bmain->object, (ID *)ob, NULL);
1448                 }
1449                 else if(local && lib) {
1450                         Object *obn= copy_object(ob);
1451                         obn->id.us= 0;
1452                         
1453                         sce= bmain->scene.first;
1454                         while(sce) {
1455                                 if(sce->id.lib==NULL) {
1456                                         base= sce->base.first;
1457                                         while(base) {
1458                                                 if(base->object==ob) {
1459                                                         base->object= obn;
1460                                                         obn->id.us++;
1461                                                         ob->id.us--;
1462                                                 }
1463                                                 base= base->next;
1464                                         }
1465                                 }
1466                                 sce= sce->id.next;
1467                         }
1468                 }
1469         }
1470         
1471         extern_local_object(ob);
1472 }
1473
1474 /*
1475  * Returns true if the Object is a from an external blend file (libdata)
1476  */
1477 int object_is_libdata(Object *ob)
1478 {
1479         if (!ob) return 0;
1480         if (ob->proxy) return 0;
1481         if (ob->id.lib) return 1;
1482         return 0;
1483 }
1484
1485 /* Returns true if the Object data is a from an external blend file (libdata) */
1486 int object_data_is_libdata(Object *ob)
1487 {
1488         if(!ob) return 0;
1489         if(ob->proxy && (ob->data==NULL || ((ID *)ob->data)->lib==NULL)) return 0;
1490         if(ob->id.lib) return 1;
1491         if(ob->data==NULL) return 0;
1492         if(((ID *)ob->data)->lib) return 1;
1493
1494         return 0;
1495 }
1496
1497 /* *************** PROXY **************** */
1498
1499 /* when you make proxy, ensure the exposed layers are extern */
1500 static void armature_set_id_extern(Object *ob)
1501 {
1502         bArmature *arm= ob->data;
1503         bPoseChannel *pchan;
1504         unsigned int lay= arm->layer_protected;
1505         
1506         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1507                 if(!(pchan->bone->layer & lay))
1508                         id_lib_extern((ID *)pchan->custom);
1509         }
1510                         
1511 }
1512
1513 void object_copy_proxy_drivers(Object *ob, Object *target)
1514 {
1515         if ((target->adt) && (target->adt->drivers.first)) {
1516                 FCurve *fcu;
1517                 
1518                 /* add new animdata block */
1519                 if(!ob->adt)
1520                         ob->adt= BKE_id_add_animdata(&ob->id);
1521                 
1522                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1523                 free_fcurves(&ob->adt->drivers);
1524                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1525                 
1526                 for (fcu= ob->adt->drivers.first; fcu; fcu= fcu->next) {
1527                         ChannelDriver *driver= fcu->driver;
1528                         DriverVar *dvar;
1529                         
1530                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1531                                 /* all drivers */
1532                                 DRIVER_TARGETS_LOOPER(dvar) 
1533                                 {
1534                                         if(dtar->id) {
1535                                                 if ((Object *)dtar->id == target)
1536                                                         dtar->id= (ID *)ob;
1537                                                 else {
1538                                                         /* only on local objects because this causes indirect links a -> b -> c,blend to point directly to a.blend
1539                                                          * when a.blend has a proxy thats linked into c.blend  */
1540                                                         if(ob->id.lib==NULL)
1541                                                                 id_lib_extern((ID *)dtar->id);
1542                                                 }
1543                                         }
1544                                 }
1545                                 DRIVER_TARGETS_LOOPER_END
1546                         }
1547                 }
1548         }
1549 }
1550
1551 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1552 /*             local_object->proxy == pointer to library object, saved in files and read */
1553 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1554
1555 void object_make_proxy(Object *ob, Object *target, Object *gob)
1556 {
1557         /* paranoia checks */
1558         if(ob->id.lib || target->id.lib==NULL) {
1559                 printf("cannot make proxy\n");
1560                 return;
1561         }
1562         
1563         ob->proxy= target;
1564         ob->proxy_group= gob;
1565         id_lib_extern(&target->id);
1566         
1567         ob->recalc= target->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
1568         
1569         /* copy transform
1570          * - gob means this proxy comes from a group, just apply the matrix
1571          *   so the object wont move from its dupli-transform.
1572          *
1573          * - no gob means this is being made from a linked object,
1574          *   this is closer to making a copy of the object - in-place. */
1575         if(gob) {
1576                 ob->rotmode= target->rotmode;
1577                 mul_m4_m4m4(ob->obmat, target->obmat, gob->obmat);
1578                 if(gob->dup_group) { /* should always be true */
1579                         float tvec[3];
1580                         copy_v3_v3(tvec, gob->dup_group->dupli_ofs);
1581                         mul_mat3_m4_v3(ob->obmat, tvec);
1582                         sub_v3_v3(ob->obmat[3], tvec);
1583                 }
1584                 object_apply_mat4(ob, ob->obmat, FALSE, TRUE);
1585         }
1586         else {
1587                 copy_object_transform(ob, target);
1588                 ob->parent= target->parent;     /* libdata */
1589                 copy_m4_m4(ob->parentinv, target->parentinv);
1590         }
1591         
1592         /* copy animdata stuff - drivers only for now... */
1593         object_copy_proxy_drivers(ob, target);
1594
1595         /* skip constraints? */
1596         // FIXME: this is considered by many as a bug
1597         
1598         /* set object type and link to data */
1599         ob->type= target->type;
1600         ob->data= target->data;
1601         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1602         
1603         /* copy material and index information */
1604         ob->actcol= ob->totcol= 0;
1605         if(ob->mat) MEM_freeN(ob->mat);
1606         if(ob->matbits) MEM_freeN(ob->matbits);
1607         ob->mat = NULL;
1608         ob->matbits= NULL;
1609         if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
1610                 int i;
1611                 ob->colbits = target->colbits;
1612                 
1613                 ob->actcol= target->actcol;
1614                 ob->totcol= target->totcol;
1615                 
1616                 ob->mat = MEM_dupallocN(target->mat);
1617                 ob->matbits = MEM_dupallocN(target->matbits);
1618                 for(i=0; i<target->totcol; i++) {
1619                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1620                         id_us_plus((ID *)ob->mat[i]); 
1621                 }
1622         }
1623         
1624         /* type conversions */
1625         if(target->type == OB_ARMATURE) {
1626                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1627                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1628                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1629                 
1630                 armature_set_id_extern(ob);
1631         }
1632         else if (target->type == OB_EMPTY) {
1633                 ob->empty_drawtype = target->empty_drawtype;
1634                 ob->empty_drawsize = target->empty_drawsize;
1635         }
1636
1637         /* copy IDProperties */
1638         if(ob->id.properties) {
1639                 IDP_FreeProperty(ob->id.properties);
1640                 MEM_freeN(ob->id.properties);
1641                 ob->id.properties= NULL;
1642         }
1643         if(target->id.properties) {
1644                 ob->id.properties= IDP_CopyProperty(target->id.properties);
1645         }
1646
1647         /* copy drawtype info */
1648         ob->dt= target->dt;
1649 }
1650
1651
1652 /* *************** CALC ****************** */
1653
1654 /* there is also a timing calculation in drawobject() */
1655
1656
1657 // XXX THIS CRUFT NEEDS SERIOUS RECODING ASAP!
1658 /* ob can be NULL */
1659 float bsystem_time(struct Scene *scene, Object *UNUSED(ob), float cfra, float ofs)
1660 {
1661         /* returns float ( see BKE_curframe in scene.c) */
1662         cfra += scene->r.subframe;
1663         
1664         /* global time */
1665         if (scene)
1666                 cfra*= scene->r.framelen;       
1667         
1668 #if 0 // XXX old animation system
1669         if (ob) {
1670                 /* ofset frames */
1671                 if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) 
1672                         cfra-= give_timeoffset(ob);
1673         }
1674 #endif // XXX old animation system
1675         
1676         cfra-= ofs;
1677
1678         return cfra;
1679 }
1680
1681 void object_scale_to_mat3(Object *ob, float mat[][3])
1682 {
1683         float vec[3];
1684         add_v3_v3v3(vec, ob->size, ob->dsize);
1685         size_to_mat3( mat,vec);
1686 }
1687
1688
1689 void object_rot_to_mat3(Object *ob, float mat[][3])
1690 {
1691         float rmat[3][3], dmat[3][3];
1692         
1693         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1694          * with the rotation matrix to yield the appropriate rotation
1695          */
1696
1697         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1698         if (ob->rotmode > 0) {
1699                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1700                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1701                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1702         }
1703         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1704                 /* axis-angle -  not really that great for 3D-changing orientations */
1705                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1706                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1707         }
1708         else {
1709                 /* quats are normalised before use to eliminate scaling issues */
1710                 float tquat[4];
1711                 
1712                 normalize_qt_qt(tquat, ob->quat);
1713                 quat_to_mat3(rmat, tquat);
1714                 
1715                 normalize_qt_qt(tquat, ob->dquat);
1716                 quat_to_mat3(dmat, tquat);
1717         }
1718         
1719         /* combine these rotations */
1720         mul_m3_m3m3(mat, dmat, rmat);
1721 }
1722
1723 void object_mat3_to_rot(Object *ob, float mat[][3], short use_compat)
1724 {
1725         switch(ob->rotmode) {
1726         case ROT_MODE_QUAT:
1727                 {
1728                         float dquat[4];
1729                         mat3_to_quat(ob->quat, mat);
1730                         normalize_qt_qt(dquat, ob->dquat);
1731                         invert_qt(dquat);
1732                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1733                 }
1734                 break;
1735         case ROT_MODE_AXISANGLE:
1736                 mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1737                 sub_v3_v3(ob->rotAxis, ob->drotAxis);
1738                 ob->rotAngle -= ob->drotAngle;
1739                 break;
1740         default: /* euler */
1741                 {
1742                         float quat[4];
1743                         float dquat[4];
1744                         float tmat[3][3];
1745
1746                         /* without drot we could apply 'mat' directly */
1747                         mat3_to_quat(quat, mat);
1748                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1749                         invert_qt(dquat);
1750                         mul_qt_qtqt(quat, dquat, quat);
1751                         quat_to_mat3(tmat, quat);
1752                         /* end drot correction */
1753
1754                         if(use_compat)  mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1755                         else                    mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1756                 }
1757         }
1758 }
1759
1760 /* see pchan_apply_mat4() for the equivalent 'pchan' function */
1761 void object_apply_mat4(Object *ob, float mat[][4], const short use_compat, const short use_parent)
1762 {
1763         float rot[3][3];
1764
1765         if(use_parent && ob->parent) {
1766                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1767                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
1768                 invert_m4_m4(imat, diff_mat);
1769                 mul_m4_m4m4(rmat, mat, imat); /* get the parent relative matrix */
1770                 object_apply_mat4(ob, rmat, use_compat, FALSE);
1771                 
1772                 /* same as below, use rmat rather than mat */
1773                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1774                 object_mat3_to_rot(ob, rot, use_compat);
1775         }
1776         else {
1777                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1778                 object_mat3_to_rot(ob, rot, use_compat);
1779         }
1780         
1781         sub_v3_v3(ob->loc, ob->dloc);
1782         sub_v3_v3(ob->size, ob->dsize);
1783         /* object_mat3_to_rot handles delta rotations */
1784 }
1785
1786 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1787 {
1788         float smat[3][3];
1789         float rmat[3][3];
1790         /*float q1[4];*/
1791         
1792         /* size */
1793         object_scale_to_mat3(ob, smat);
1794
1795         /* rot */
1796         object_rot_to_mat3(ob, rmat);
1797         mul_m3_m3m3(mat, rmat, smat);
1798 }
1799
1800 void object_to_mat4(Object *ob, float mat[][4])
1801 {
1802         float tmat[3][3];
1803         
1804         object_to_mat3(ob, tmat);
1805         
1806         copy_m4_m3(mat, tmat);
1807
1808         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1809 }
1810
1811 /* extern */
1812 int enable_cu_speed= 1;
1813
1814 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1815 {
1816         Curve *cu;
1817         float vec[4], dir[3], quat[4], radius, ctime;
1818         float timeoffs = 0.0, sf_orig = 0.0;
1819         
1820         unit_m4(mat);
1821         
1822         cu= par->data;
1823         if(cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1824                 makeDispListCurveTypes(scene, par, 0);
1825         if(cu->path==NULL) return;
1826         
1827         /* exception, timeoffset is regarded as distance offset */
1828         if(cu->flag & CU_OFFS_PATHDIST) {
1829                 timeoffs = give_timeoffset(ob);
1830                 SWAP(float, sf_orig, ob->sf);
1831         }
1832         
1833         /* catch exceptions: feature for nla stride editing */
1834         if(ob->ipoflag & OB_DISABLE_PATH) {
1835                 ctime= 0.0f;
1836         }
1837         /* catch exceptions: curve paths used as a duplicator */
1838         else if(enable_cu_speed) {
1839                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1840                  * but this will only work if it actually is animated... 
1841                  *
1842                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1843                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1844                  */
1845                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1846                         ctime= cu->ctime / cu->pathlen;
1847                 else
1848                         ctime= cu->ctime;
1849
1850                 CLAMP(ctime, 0.0f, 1.0f);
1851         }
1852         else {
1853                 ctime= scene->r.cfra - give_timeoffset(ob);
1854                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1855                         ctime /= cu->pathlen;
1856                 
1857                 CLAMP(ctime, 0.0f, 1.0f);
1858         }
1859         
1860         /* time calculus is correct, now apply distance offset */
1861         if(cu->flag & CU_OFFS_PATHDIST) {
1862                 ctime += timeoffs/cu->path->totdist;
1863
1864                 /* restore */
1865                 SWAP(float, sf_orig, ob->sf);
1866         }
1867         
1868         
1869         /* vec: 4 items! */
1870         if( where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat:NULL, &radius, NULL) ) {
1871
1872                 if(cu->flag & CU_FOLLOW) {
1873 #if 0
1874                         float x1, q[4];
1875                         vec_to_quat( quat,dir, ob->trackflag, ob->upflag);
1876                         
1877                         /* the tilt */
1878                         normalize_v3(dir);
1879                         q[0]= (float)cos(0.5*vec[3]);
1880                         x1= (float)sin(0.5*vec[3]);
1881                         q[1]= -x1*dir[0];
1882                         q[2]= -x1*dir[1];
1883                         q[3]= -x1*dir[2];
1884                         mul_qt_qtqt(quat, q, quat);
1885 #else
1886                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1887 #endif
1888                         normalize_qt(quat);
1889                         quat_to_mat4(mat, quat);
1890                 }
1891                 
1892                 if(cu->flag & CU_PATH_RADIUS) {
1893                         float tmat[4][4], rmat[4][4];
1894                         scale_m4_fl(tmat, radius);
1895                         mul_m4_m4m4(rmat, mat, tmat);
1896                         copy_m4_m4(mat, rmat);
1897                 }
1898
1899                 copy_v3_v3(mat[3], vec);
1900                 
1901         }
1902 }
1903
1904 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1905 {       
1906         bPoseChannel *pchan;
1907         float vec[3];
1908         
1909         if (par->type!=OB_ARMATURE) {
1910                 unit_m4(mat);
1911                 return;
1912         }
1913         
1914         /* Make sure the bone is still valid */
1915         pchan= get_pose_channel(par->pose, ob->parsubstr);
1916         if (!pchan){
1917                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1918                 unit_m4(mat);
1919                 return;
1920         }
1921
1922         /* get bone transform */
1923         copy_m4_m4(mat, pchan->pose_mat);
1924
1925         /* but for backwards compatibility, the child has to move to the tail */
1926         copy_v3_v3(vec, mat[1]);
1927         mul_v3_fl(vec, pchan->bone->length);
1928         add_v3_v3(mat[3], vec);
1929 }
1930
1931 static void give_parvert(Object *par, int nr, float *vec)
1932 {
1933         EditMesh *em;
1934         int a, count;
1935         
1936         vec[0]=vec[1]=vec[2]= 0.0f;
1937         
1938         if(par->type==OB_MESH) {
1939                 Mesh *me= par->data;
1940                 DerivedMesh *dm;
1941
1942                 em = BKE_mesh_get_editmesh(me);
1943                 dm = (em)? em->derivedFinal: par->derivedFinal;
1944                         
1945                 if(dm) {
1946                         MVert *mvert= dm->getVertArray(dm);
1947                         int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1948                         int i, vindex, numVerts = dm->getNumVerts(dm);
1949
1950                         /* get the average of all verts with (original index == nr) */
1951                         count= 0;
1952                         for(i = 0; i < numVerts; i++) {
1953                                 vindex= (index)? index[i]: i;
1954
1955                                 if(vindex == nr) {
1956                                         add_v3_v3(vec, mvert[i].co);
1957                                         count++;
1958                                 }
1959                         }
1960
1961                         if (count==0) {
1962                                 /* keep as 0,0,0 */
1963                         } else if(count > 0) {
1964                                 mul_v3_fl(vec, 1.0f / count);
1965                         } else {
1966                                 /* use first index if its out of range */
1967                                 dm->getVertCo(dm, 0, vec);
1968                         }
1969                 }
1970
1971                 if(em)
1972                         BKE_mesh_end_editmesh(me, em);
1973         }
1974         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1975                 Nurb *nu;
1976                 Curve *cu;
1977                 BPoint *bp;
1978                 BezTriple *bezt;
1979                 int found= 0;
1980                 ListBase *nurbs;
1981
1982                 cu= par->data;
1983                 nurbs= BKE_curve_nurbs(cu);
1984                 nu= nurbs->first;
1985
1986                 count= 0;
1987                 while(nu && !found) {
1988                         if(nu->type == CU_BEZIER) {
1989                                 bezt= nu->bezt;
1990                                 a= nu->pntsu;
1991                                 while(a--) {
1992                                         if(count==nr) {
1993                                                 found= 1;
1994                                                 VECCOPY(vec, bezt->vec[1]);
1995                                                 break;
1996                                         }
1997                                         count++;
1998                                         bezt++;
1999                                 }
2000                         }
2001                         else {
2002                                 bp= nu->bp;
2003                                 a= nu->pntsu*nu->pntsv;
2004                                 while(a--) {
2005                                         if(count==nr) {
2006                                                 found= 1;
2007                                                 memcpy(vec, bp->vec, sizeof(float)*3);
2008                                                 break;
2009                                         }
2010                                         count++;
2011                                         bp++;
2012                                 }
2013                         }
2014                         nu= nu->next;
2015                 }
2016
2017         }
2018         else if(par->type==OB_LATTICE) {
2019                 Lattice *latt= par->data;
2020                 BPoint *bp;
2021                 DispList *dl = find_displist(&par->disp, DL_VERTS);
2022                 float *co = dl?dl->verts:NULL;
2023                 
2024                 if(latt->editlatt) latt= latt->editlatt->latt;
2025                 
2026                 a= latt->pntsu*latt->pntsv*latt->pntsw;
2027                 count= 0;
2028                 bp= latt->def;
2029                 while(a--) {
2030                         if(count==nr) {
2031                                 if(co)
2032                                         memcpy(vec, co, 3*sizeof(float));
2033                                 else
2034                                         memcpy(vec, bp->vec, 3*sizeof(float));
2035                                 break;
2036                         }
2037                         count++;
2038                         if(co) co+= 3;
2039                         else bp++;
2040                 }
2041         }
2042 }
2043
2044 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
2045 {
2046         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2047
2048         /* in local ob space */
2049         unit_m4(mat);
2050         
2051         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
2052                 
2053                 give_parvert(par, ob->par1, v1);
2054                 give_parvert(par, ob->par2, v2);
2055                 give_parvert(par, ob->par3, v3);
2056                                 
2057                 tri_to_quat( q,v1, v2, v3);
2058                 quat_to_mat3( cmat,q);
2059                 copy_m4_m3(mat, cmat);
2060                 
2061                 if(ob->type==OB_CURVE) {
2062                         VECCOPY(mat[3], v1);
2063                 }
2064                 else {
2065                         add_v3_v3v3(mat[3], v1, v2);
2066                         add_v3_v3(mat[3], v3);
2067                         mul_v3_fl(mat[3], 0.3333333f);
2068                 }
2069         }
2070 }
2071
2072 // XXX what the hell is this?
2073 static int no_parent_ipo=0;
2074 void set_no_parent_ipo(int val)
2075 {
2076         no_parent_ipo= val;
2077 }
2078
2079 void where_is_object_time(Scene *scene, Object *ob, float ctime)
2080 {
2081         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
2082         float stime=ctime, fac1, fac2;
2083         int a;
2084         
2085         /* new version: correct parent+vertexparent and track+parent */
2086         /* this one only calculates direct attached parent and track */
2087         /* is faster, but should keep track of timeoffs */
2088         
2089         if(ob==NULL) return;
2090         
2091         /* execute drivers only, as animation has already been done */
2092         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2093         
2094         if(ob->parent) {
2095                 Object *par= ob->parent;
2096                 
2097                 // XXX depreceated - animsys
2098                 if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
2099                 
2100                 /* hurms, code below conflicts with depgraph... (ton) */
2101                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
2102                 if(no_parent_ipo==0 && stime != par->ctime) {
2103                         // only for ipo systems? 
2104                         Object tmp= *par;
2105                         
2106                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
2107                         else where_is_object_time(scene, par, ctime);
2108
2109                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2110
2111                         *par= tmp;
2112                 }
2113                 else
2114                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2115                 
2116                 if(ob->partype & PARSLOW) {
2117                         // include framerate
2118                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
2119                         if(fac1 >= 1.0f) return;
2120                         fac2= 1.0f-fac1;
2121                         
2122                         fp1= ob->obmat[0];
2123                         fp2= slowmat[0];
2124                         for(a=0; a<16; a++, fp1++, fp2++) {
2125                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2126                         }
2127                 }
2128         }
2129         else {
2130                 object_to_mat4(ob, ob->obmat);
2131         }
2132
2133         /* solve constraints */
2134         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2135                 bConstraintOb *cob;
2136                 
2137                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2138                 
2139                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
2140                 solve_constraints (&ob->constraints, cob, ctime);
2141                 
2142                 constraints_clear_evalob(cob);
2143         }
2144         
2145         /* set negative scale flag in object */
2146         if(is_negative_m4(ob->obmat))   ob->transflag |= OB_NEG_SCALE;
2147         else                                                    ob->transflag &= ~OB_NEG_SCALE;
2148 }
2149
2150 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2151 {
2152         float totmat[4][4];
2153         float tmat[4][4];
2154         float locmat[4][4];
2155         float vec[3];
2156         int ok;
2157         
2158         object_to_mat4(ob, locmat);
2159         
2160         if(ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2161
2162         switch(ob->partype & PARTYPE) {
2163         case PAROBJECT:
2164                 ok= 0;
2165                 if(par->type==OB_CURVE) {
2166                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2167                                 ob_parcurve(scene, ob, par, tmat);
2168                                 ok= 1;
2169                         }
2170                 }
2171                 
2172                 if(ok) mul_serie_m4(totmat, par->obmat, tmat, 
2173                         NULL, NULL, NULL, NULL, NULL, NULL);
2174                 else copy_m4_m4(totmat, par->obmat);
2175                 
2176                 break;
2177         case PARBONE:
2178                 ob_parbone(ob, par, tmat);
2179                 mul_serie_m4(totmat, par->obmat, tmat,         
2180                         NULL, NULL, NULL, NULL, NULL, NULL);
2181                 break;
2182                 
2183         case PARVERT1:
2184                 unit_m4(totmat);
2185                 if (simul){
2186                         VECCOPY(totmat[3], par->obmat[3]);
2187                 }
2188                 else{
2189                         give_parvert(par, ob->par1, vec);
2190                         mul_v3_m4v3(totmat[3], par->obmat, vec);
2191                 }
2192                 break;
2193         case PARVERT3:
2194                 ob_parvert3(ob, par, tmat);
2195                 
2196                 mul_serie_m4(totmat, par->obmat, tmat,         
2197                         NULL, NULL, NULL, NULL, NULL, NULL);
2198                 break;
2199                 
2200         case PARSKEL:
2201                 copy_m4_m4(totmat, par->obmat);
2202                 break;
2203         }
2204         
2205         // total 
2206         mul_serie_m4(tmat, totmat, ob->parentinv,         
2207                 NULL, NULL, NULL, NULL, NULL, NULL);
2208         mul_serie_m4(obmat, tmat, locmat,         
2209                 NULL, NULL, NULL, NULL, NULL, NULL);
2210         
2211         if (simul) {
2212
2213         }
2214         else{
2215                 // external usable originmat 
2216                 copy_m3_m4(originmat, tmat);
2217                 
2218                 // origin, voor help line
2219                 if( (ob->partype & PARTYPE)==PARSKEL ) {
2220                         VECCOPY(ob->orig, par->obmat[3]);
2221                 }
2222                 else {
2223                         VECCOPY(ob->orig, totmat[3]);
2224                 }
2225         }
2226
2227 }
2228
2229 void where_is_object(struct Scene *scene, Object *ob)
2230 {
2231         where_is_object_time(scene, ob, (float)scene->r.cfra);
2232 }
2233
2234
2235 void where_is_object_simul(Scene *scene, Object *ob)
2236 /* was written for the old game engine (until 2.04) */
2237 /* It seems that this function is only called
2238 for a lamp that is the child of another object */
2239 {
2240         Object *par;
2241         //Ipo *ipo;
2242         float *fp1, *fp2;
2243         float slowmat[4][4];
2244         float fac1, fac2;
2245         int a;
2246         
2247         /* NO TIMEOFFS */
2248         if(ob->parent) {
2249                 par= ob->parent;
2250                 
2251                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2252
2253                 if(ob->partype & PARSLOW) {
2254
2255                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2256                         fac2= 1.0f-fac1;
2257                         fp1= ob->obmat[0];
2258                         fp2= slowmat[0];
2259                         for(a=0; a<16; a++, fp1++, fp2++) {
2260                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2261                         }
2262                 }
2263                 
2264         }
2265         else {
2266                 object_to_mat4(ob, ob->obmat);
2267         }
2268         
2269         /* solve constraints */
2270         if (ob->constraints.first) {
2271                 bConstraintOb *cob;
2272                 
2273                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2274                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2275                 constraints_clear_evalob(cob);
2276         }
2277 }
2278
2279 /* for calculation of the inverse parent transform, only used for editor */
2280 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2281 {
2282         clear_workob(workob);
2283         
2284         unit_m4(workob->obmat);
2285         unit_m4(workob->parentinv);
2286         unit_m4(workob->constinv);
2287         workob->parent= ob->parent;
2288
2289         workob->trackflag= ob->trackflag;
2290         workob->upflag= ob->upflag;
2291         
2292         workob->partype= ob->partype;
2293         workob->par1= ob->par1;
2294         workob->par2= ob->par2;
2295         workob->par3= ob->par3;
2296
2297         workob->constraints.first = ob->constraints.first;
2298         workob->constraints.last = ob->constraints.last;
2299
2300         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2301
2302         where_is_object(scene, workob);
2303 }
2304
2305 BoundBox *unit_boundbox(void)
2306 {
2307         BoundBox *bb;
2308         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2309
2310         bb= MEM_callocN(sizeof(BoundBox), "bb");
2311         boundbox_set_from_min_max(bb, min, max);
2312         
2313         return bb;
2314 }
2315
2316 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2317 {
2318         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2319         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2320         
2321         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2322         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2323
2324         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2325         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2326 }
2327
2328 BoundBox *object_get_boundbox(Object *ob)
2329 {
2330         BoundBox *bb= NULL;
2331         
2332         if(ob->type==OB_MESH) {
2333                 bb = mesh_get_bb(ob);
2334         }
2335         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2336                 bb= ob->bb ? ob->bb : ( (Curve *)ob->data )->bb;
2337         }
2338         else if(ob->type==OB_MBALL) {
2339                 bb= ob->bb;
2340         }
2341         return bb;
2342 }
2343
2344 /* used to temporally disable/enable boundbox */
2345 void object_boundbox_flag(Object *ob, int flag, int set)
2346 {
2347         BoundBox *bb= object_get_boundbox(ob);
2348         if(bb) {
2349                 if(set) bb->flag |= flag;
2350                 else bb->flag &= ~flag;
2351         }
2352 }
2353
2354 void object_get_dimensions(Object *ob, float *value)
2355 {
2356         BoundBox *bb = NULL;
2357         
2358         bb= object_get_boundbox(ob);
2359         if (bb) {
2360                 float scale[3];
2361                 
2362                 mat4_to_size( scale,ob->obmat);
2363                 
2364                 value[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2365                 value[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2366                 value[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2367         } else {
2368                 value[0] = value[1] = value[2] = 0.f;
2369         }
2370 }
2371
2372 void object_set_dimensions(Object *ob, const float *value)
2373 {
2374         BoundBox *bb = NULL;
2375         
2376         bb= object_get_boundbox(ob);
2377         if (bb) {
2378                 float scale[3], len[3];
2379                 
2380                 mat4_to_size( scale,ob->obmat);
2381                 
2382                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2383                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2384                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2385                 
2386                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2387                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2388                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2389         }
2390 }
2391
2392 void minmax_object(Object *ob, float *min, float *max)
2393 {
2394         BoundBox bb;
2395         float vec[3];
2396         int a;
2397         short change= FALSE;
2398         
2399         switch(ob->type) {
2400         case OB_CURVE:
2401         case OB_FONT:
2402         case OB_SURF:
2403                 {
2404                         Curve *cu= ob->data;
2405
2406                         if(cu->bb==NULL) tex_space_curve(cu);
2407                         bb= *(cu->bb);
2408
2409                         for(a=0; a<8; a++) {
2410                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2411                                 DO_MINMAX(bb.vec[a], min, max);
2412                         }
2413                         change= TRUE;
2414                 }
2415                 break;
2416         case OB_LATTICE:
2417                 {
2418                         Lattice *lt= ob->data;
2419                         BPoint *bp= lt->def;
2420                         int u, v, w;
2421
2422                         for(w=0; w<lt->pntsw; w++) {
2423                                 for(v=0; v<lt->pntsv; v++) {
2424                                         for(u=0; u<lt->pntsu; u++, bp++) {
2425                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2426                                                 DO_MINMAX(vec, min, max);
2427                                         }
2428                                 }
2429                         }
2430                         change= TRUE;
2431                 }
2432                 break;
2433         case OB_ARMATURE:
2434                 if(ob->pose) {
2435                         bPoseChannel *pchan;
2436                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2437                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2438                                 DO_MINMAX(vec, min, max);
2439                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2440                                 DO_MINMAX(vec, min, max);
2441                         }
2442                         change= TRUE;
2443                 }
2444                 break;
2445         case OB_MESH:
2446                 {
2447                         Mesh *me= get_mesh(ob);
2448
2449                         if(me) {
2450                                 bb = *mesh_get_bb(ob);
2451
2452                                 for(a=0; a<8; a++) {
2453                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2454                                         DO_MINMAX(bb.vec[a], min, max);
2455                                 }
2456                                 change= TRUE;
2457                         }
2458                 }
2459                 break;
2460         }
2461
2462         if(change == FALSE) {
2463                 DO_MINMAX(ob->obmat[3], min, max);
2464
2465                 copy_v3_v3(vec, ob->obmat[3]);
2466                 add_v3_v3(vec, ob->size);
2467                 DO_MINMAX(vec, min, max);
2468
2469                 copy_v3_v3(vec, ob->obmat[3]);
2470                 sub_v3_v3(vec, ob->size);
2471                 DO_MINMAX(vec, min, max);
2472         }
2473 }
2474
2475 int minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2476 {
2477         int ok= 0;
2478         if ((ob->transflag & OB_DUPLI)==0) {
2479                 return ok;
2480         } else {
2481                 ListBase *lb;
2482                 DupliObject *dob;
2483                 
2484                 lb= object_duplilist(scene, ob);
2485                 for(dob= lb->first; dob; dob= dob->next) {
2486                         if(dob->no_draw == 0) {
2487                                 BoundBox *bb= object_get_boundbox(dob->ob);
2488
2489                                 if(bb) {
2490                                         int i;
2491                                         for(i=0; i<8; i++) {
2492                                                 float vec[3];
2493                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2494                                                 DO_MINMAX(vec, min, max);
2495                                         }
2496
2497                                         ok= 1;
2498                                 }
2499                         }
2500                 }
2501                 free_object_duplilist(lb);      /* does restore */
2502         }
2503
2504         return ok;
2505 }
2506
2507 /* copied from DNA_object_types.h */
2508 typedef struct ObTfmBack {
2509         float loc[3], dloc[3], orig[3];
2510         float size[3], dsize[3];        /* scale and delta scale */
2511         float rot[3], drot[3];          /* euler rotation */
2512         float quat[4], dquat[4];        /* quaternion rotation */
2513         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2514         float rotAngle, drotAngle;      /* axis angle rotation - angle part */
2515         float obmat[4][4];              /* final worldspace matrix with constraints & animsys applied */
2516         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2517         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2518         float imat[4][4];       /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2519 } ObTfmBack;
2520
2521 void *object_tfm_backup(Object *ob)
2522 {
2523         ObTfmBack *obtfm= MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2524         copy_v3_v3(obtfm->loc, ob->loc);
2525         copy_v3_v3(obtfm->dloc, ob->dloc);
2526         copy_v3_v3(obtfm->orig, ob->orig);
2527         copy_v3_v3(obtfm->size, ob->size);
2528         copy_v3_v3(obtfm->dsize, ob->dsize);
2529         copy_v3_v3(obtfm->rot, ob->rot);
2530         copy_v3_v3(obtfm->drot, ob->drot);
2531         copy_qt_qt(obtfm->quat, ob->quat);
2532         copy_qt_qt(obtfm->dquat, ob->dquat);
2533         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2534         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2535         obtfm->rotAngle= ob->rotAngle;
2536         obtfm->drotAngle= ob->drotAngle;
2537         copy_m4_m4(obtfm->obmat, ob->obmat);
2538         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2539         copy_m4_m4(obtfm->constinv, ob->constinv);
2540         copy_m4_m4(obtfm->imat, ob->imat);
2541
2542         return (void *)obtfm;
2543 }
2544
2545 void object_tfm_restore(Object *ob, void *obtfm_pt)
2546 {
2547         ObTfmBack *obtfm= (ObTfmBack *)obtfm_pt;
2548         copy_v3_v3(ob->loc, obtfm->loc);
2549         copy_v3_v3(ob->dloc, obtfm->dloc);
2550         copy_v3_v3(ob->orig, obtfm->orig);
2551         copy_v3_v3(ob->size, obtfm->size);
2552         copy_v3_v3(ob->dsize, obtfm->dsize);
2553         copy_v3_v3(ob->rot, obtfm->rot);
2554         copy_v3_v3(ob->drot, obtfm->drot);
2555         copy_qt_qt(ob->quat, obtfm->quat);
2556         copy_qt_qt(ob->dquat, obtfm->dquat);
2557         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2558         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2559         ob->rotAngle= obtfm->rotAngle;
2560         ob->drotAngle= obtfm->drotAngle;
2561         copy_m4_m4(ob->obmat, obtfm->obmat);
2562         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2563         copy_m4_m4(ob->constinv, obtfm->constinv);
2564         copy_m4_m4(ob->imat, obtfm->imat);
2565 }
2566
2567 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2568 /*           local_object->proxy      == pointer to library object, saved in files and read */
2569
2570 /* function below is polluted with proxy exceptions, cleanup will follow! */
2571
2572 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2573 /* requires flags to be set! */
2574 void object_handle_update(Scene *scene, Object *ob)
2575 {
2576         if(ob->recalc & OB_RECALC_ALL) {
2577                 /* speed optimization for animation lookups */
2578                 if(ob->pose)
2579                         make_pose_channels_hash(ob->pose);
2580
2581                 if(ob->recalc & OB_RECALC_DATA) {
2582                         if(ob->type==OB_ARMATURE) {
2583                                 /* this happens for reading old files and to match library armatures
2584                                    with poses we do it ahead of where_is_object to ensure animation
2585                                    is evaluated on the rebuilt pose, otherwise we get incorrect poses
2586                                    on file load */
2587                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2588                                         armature_rebuild_pose(ob, ob->data);
2589                         }
2590                 }
2591
2592                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2593                    which is only in where_is_object now */
2594                 // XXX: should this case be OB_RECALC_OB instead?
2595                 if(ob->recalc & OB_RECALC_ALL) {
2596                         
2597                         if (G.f & G_DEBUG)
2598                                 printf("recalcob %s\n", ob->id.name+2);
2599                         
2600                         /* handle proxy copy for target */
2601                         if(ob->id.lib && ob->proxy_from) {
2602                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2603                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2604                                         Object *obg= ob->proxy_from->proxy_group;
2605                                         invert_m4_m4(obg->imat, obg->obmat);
2606                                         mul_m4_m4m4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2607                                         if(obg->dup_group) { /* should always be true */
2608                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2609                                         }
2610                                 }
2611                                 else
2612                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2613                         }
2614                         else
2615                                 where_is_object(scene, ob);
2616                 }
2617                 
2618                 if(ob->recalc & OB_RECALC_DATA) {
2619                         ID *data_id= (ID *)ob->data;
2620                         AnimData *adt= BKE_animdata_from_id(data_id);
2621                         float ctime= (float)scene->r.cfra; // XXX this is bad...
2622                         ListBase pidlist;
2623                         PTCacheID *pid;
2624                         
2625                         if (G.f & G_DEBUG)
2626                                 printf("recalcdata %s\n", ob->id.name+2);
2627
2628                         if(adt) {
2629                                 /* evaluate drivers */
2630                                 // XXX: for mesh types, should we push this to derivedmesh instead?
2631                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2632                         }
2633
2634                         /* includes all keys and modifiers */
2635                         switch(ob->type) {
2636                         case OB_MESH:
2637                                 {
2638 #if 0                           // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2639                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2640                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2641                                         if(em) {
2642                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask); /* was CD_MASK_BAREMESH */
2643                                                 BKE_mesh_end_editmesh(ob->data, em);
2644                                         } else
2645                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask);
2646
2647 #else                           /* ensure CD_MASK_BAREMESH for now */
2648                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2649                                         unsigned int data_mask= scene->customdata_mask | ob->customdata_mask | CD_MASK_BAREMESH;
2650                                         if(em) {
2651                                                 makeDerivedMesh(scene, ob, em,  data_mask); /* was CD_MASK_BAREMESH */
2652                                                 BKE_mesh_end_editmesh(ob->data, em);
2653                                         } else
2654                                                 makeDerivedMesh(scene, ob, NULL, data_mask);
2655 #endif
2656
2657                                 }
2658                                 break;
2659
2660                         case OB_ARMATURE:
2661                                 if(ob->id.lib && ob->proxy_from) {
2662                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2663                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2664                                 }
2665                                 else {
2666                                         where_is_pose(scene, ob);
2667                                 }
2668                                 break;
2669
2670                         case OB_MBALL:
2671                                 makeDispListMBall(scene, ob);
2672                                 break;
2673
2674                         case OB_CURVE:
2675                         case OB_SURF:
2676                         case OB_FONT:
2677                                 makeDispListCurveTypes(scene, ob, 0);
2678                                 break;
2679                                 
2680                         case OB_LATTICE:
2681                                 lattice_calc_modifiers(scene, ob);
2682                                 break;
2683                         }
2684
2685
2686                         if(ob->particlesystem.first) {
2687                                 ParticleSystem *tpsys, *psys;
2688                                 DerivedMesh *dm;
2689                                 ob->transflag &= ~OB_DUPLIPARTS;
2690                                 
2691                                 psys= ob->particlesystem.first;
2692                                 while(psys) {
2693                                         if(psys_check_enabled(ob, psys)) {
2694                                                 /* check use of dupli objects here */
2695                                                 if(psys->part && (psys->part->draw_as == PART_DRAW_REND || G.rendering) &&
2696                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2697                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2698                                                         ob->transflag |= OB_DUPLIPARTS;
2699
2700                                                 particle_system_update(scene, ob, psys);
2701                                                 psys= psys->next;
2702                                         }
2703                                         else if(psys->flag & PSYS_DELETE) {
2704                                                 tpsys=psys->next;
2705                                                 BLI_remlink(&ob->particlesystem, psys);
2706                                                 psys_free(ob,psys);
2707                                                 psys= tpsys;
2708                                         }
2709                                         else
2710                                                 psys= psys->next;
2711                                 }
2712
2713                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2714                                         /* this is to make sure we get render level duplis in groups:
2715                                          * the derivedmesh must be created before init_render_mesh,
2716                                          * since object_duplilist does dupliparticles before that */
2717                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2718                                         dm->release(dm);
2719
2720                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2721                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2722                                 }
2723                         }
2724
2725                         /* check if quick cache is needed */
2726                         BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
2727
2728                         for(pid=pidlist.first; pid; pid=pid->next) {
2729                                 if((pid->cache->flag & PTCACHE_BAKED)
2730                                         || (pid->cache->flag & PTCACHE_QUICK_CACHE)==0)
2731                                         continue;
2732
2733                                 if(pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID)==0) {
2734                                         scene->physics_settings.quick_cache_step =
2735                                                 scene->physics_settings.quick_cache_step ?
2736                                                 MIN2(scene->physics_settings.quick_cache_step, pid->cache->step) :
2737                                                 pid->cache->step;
2738                                 }
2739                         }
2740
2741                         BLI_freelistN(&pidlist);
2742                 }
2743
2744                 /* the no-group proxy case, we call update */
2745                 if(ob->proxy && ob->proxy_group==NULL) {
2746                         /* set pointer in library proxy target, for copying, but restore it */
2747                         ob->proxy->proxy_from= ob;
2748                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2749                         object_handle_update(scene, ob->proxy);
2750                 }
2751         
2752                 ob->recalc &= ~OB_RECALC_ALL;
2753         }
2754
2755         /* the case when this is a group proxy, object_update is called in group.c */
2756         if(ob->proxy) {
2757                 ob->proxy->proxy_from= ob;
2758                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2759         }
2760 }
2761
2762 float give_timeoffset(Object *ob) {
2763         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2764                 return ob->sf + give_timeoffset(ob->parent);
2765         } else {
2766                 return ob->sf;
2767         }
2768 }
2769
2770 int give_obdata_texspace(Object *ob, short **texflag, float **loc, float **size, float **rot) {
2771         
2772         if (ob->data==NULL)
2773                 return 0;
2774         
2775         switch (GS(((ID *)ob->data)->name)) {
2776         case ID_ME:
2777         {
2778                 Mesh *me= ob->data;
2779                 if (texflag)    *texflag = &me->texflag;
2780                 if (loc)                *loc = me->loc;
2781                 if (size)               *size = me->size;
2782                 if (rot)                *rot = me->rot;
2783                 break;
2784         }
2785         case ID_CU:
2786         {
2787                 Curve *cu= ob->data;
2788                 if (texflag)    *texflag = &cu->texflag;
2789                 if (loc)                *loc = cu->loc;
2790                 if (size)               *size = cu->size;
2791                 if (rot)                *rot = cu->rot;
2792                 break;
2793         }
2794         case ID_MB:
2795         {
2796                 MetaBall *mb= ob->data;
2797                 if (texflag)    *texflag = &mb->texflag;
2798                 if (loc)                *loc = mb->loc;
2799                 if (size)               *size = mb->size;
2800                 if (rot)                *rot = mb->rot;
2801                 break;
2802         }
2803         default:
2804                 return 0;
2805         }
2806         return 1;
2807 }
2808
2809 /*
2810  * Test a bounding box for ray intersection
2811  * assumes the ray is already local to the boundbox space
2812  */
2813 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2814 {
2815         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2816                                                                                   {3, 2, 6}, {3, 6, 7},
2817                                                                                   {1, 2, 6}, {1, 6, 5}, 
2818                                                                                   {5, 6, 7}, {4, 5, 7},
2819                                                                                   {0, 3, 7}, {0, 4, 7},
2820                                                                                   {0, 1, 5}, {0, 4, 5}};
2821         int result = 0;
2822         int i;
2823         
2824         for (i = 0; i < 12 && result == 0; i++)
2825         {
2826                 float lambda;
2827                 int v1, v2, v3;
2828                 v1 = triangle_indexes[i][0];
2829                 v2 = triangle_indexes[i][1];
2830                 v3 = triangle_indexes[i][2];
2831                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2832         }
2833         
2834         return result;
2835 }
2836
2837 static int pc_cmp(void *a, void *b)
2838 {
2839         LinkData *ad = a, *bd = b;
2840         if(GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2841                 return 1;
2842         else return 0;
2843 }
2844
2845 int object_insert_ptcache(Object *ob) 
2846 {
2847         LinkData *link = NULL;
2848         int i = 0;
2849
2850         BLI_sortlist(&ob->pc_ids, pc_cmp);
2851
2852         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2853         {
2854                 int index = GET_INT_FROM_POINTER(link->data);
2855
2856                 if(i < index)
2857                         break;
2858         }
2859
2860         link = MEM_callocN(sizeof(LinkData), "PCLink");
2861         link->data = SET_INT_IN_POINTER(i);
2862         BLI_addtail(&ob->pc_ids, link);
2863
2864         return i;
2865 }
2866
2867 void object_camera_mode(RenderData *rd, Object *camera)
2868 {
2869         rd->mode &= ~(R_ORTHO|R_PANORAMA);
2870         if(camera && camera->type==OB_CAMERA) {
2871                 Camera *cam= camera->data;
2872                 if(cam->type == CAM_ORTHO) rd->mode |= R_ORTHO;
2873                 if(cam->flag & CAM_PANORAMA) rd->mode |= R_PANORAMA;
2874         }
2875 }
2876
2877 /* 'lens' may be set for envmap only */
2878 void object_camera_matrix(
2879                 RenderData *rd, Object *camera, int winx, int winy, short field_second,
2880                 float winmat[][4], rctf *viewplane, float *clipsta, float *clipend, float *lens, float *ycor,
2881                 float *viewdx, float *viewdy
2882 ) {
2883         Camera *cam=NULL;
2884         float pixsize;
2885         float shiftx=0.0, shifty=0.0, winside, viewfac;
2886         short is_ortho= FALSE;
2887
2888         /* question mark */
2889         (*ycor)= rd->yasp / rd->xasp;
2890         if(rd->mode & R_FIELDS)
2891                 (*ycor) *= 2.0f;
2892
2893         if(camera->type==OB_CAMERA) {
2894                 cam= camera->data;
2895
2896                 if(cam->type == CAM_ORTHO) {
2897                         is_ortho= TRUE;
2898                 }
2899
2900                 /* solve this too... all time depending stuff is in convertblender.c?
2901                  * Need to update the camera early because it's used for projection matrices
2902                  * and other stuff BEFORE the animation update loop is done
2903                  * */
2904 #if 0 // XXX old animation system
2905                 if(cam->ipo) {
2906                         calc_ipo(cam->ipo, frame_to_float(re->scene, re->r.cfra));
2907                         execute_ipo(&cam->id, cam->ipo);
2908                 }
2909 #endif // XXX old animation system
2910                 shiftx=cam->shiftx;
2911                 shifty=cam->shifty;
2912                 (*lens)= cam->lens;
2913                 (*clipsta)= cam->clipsta;
2914                 (*clipend)= cam->clipend;
2915         }
2916         else if(camera->type==OB_LAMP) {
2917                 Lamp *la= camera->data;
2918                 float fac= cosf((float)M_PI*la->spotsize/360.0f);
2919                 float phi= acos(fac);
2920
2921                 (*lens)= 16.0f*fac/sinf(phi);
2922                 if((*lens)==0.0f)
2923                         (*lens)= 35.0f;
2924                 (*clipsta)= la->clipsta;
2925                 (*clipend)= la->clipend;
2926         }
2927         else {  /* envmap exception... */;
2928                 if((*lens)==0.0f)
2929                         (*lens)= 16.0f;
2930
2931                 if((*clipsta)==0.0f || (*clipend)==0.0f) {
2932                         (*clipsta)= 0.1f;
2933                         (*clipend)= 1000.0f;
2934                 }
2935         }
2936
2937         /* ortho only with camera available */
2938         if(cam && is_ortho) {
2939                 if(rd->xasp*winx >= rd->yasp*winy) {
2940                         viewfac= winx;
2941                 }
2942                 else {
2943                         viewfac= (*ycor) * winy;
2944                 }
2945                 /* ortho_scale == 1.0 means exact 1 to 1 mapping */
2946                 pixsize= cam->ortho_scale/viewfac;
2947         }
2948         else {
2949                 if(rd->xasp*winx >= rd->yasp*winy)      viewfac= ((*lens) * winx)/32.0f;
2950                 else                                                            viewfac= (*ycor) * ((*lens) * winy)/32.0f;
2951                 pixsize= (*clipsta) / viewfac;
2952         }
2953
2954         /* viewplane fully centered, zbuffer fills in jittered between -.5 and +.5 */
2955         winside= MAX2(winx, winy);
2956         viewplane->xmin= -0.5f*(float)winx + shiftx*winside;
2957         viewplane->ymin= -0.5f*(*ycor)*(float)winy + shifty*winside;
2958         viewplane->xmax=  0.5f*(float)winx + shiftx*winside;
2959         viewplane->ymax=  0.5f*(*ycor)*(float)winy + shifty*winside;
2960
2961         if(field_second) {
2962                 if(rd->mode & R_ODDFIELD) {
2963                         viewplane->ymin-= 0.5f * (*ycor);
2964                         viewplane->ymax-= 0.5f * (*ycor);
2965                 }
2966                 else {
2967                         viewplane->ymin+= 0.5f * (*ycor);
2968                         viewplane->ymax+= 0.5f * (*ycor);
2969                 }
2970         }
2971         /* the window matrix is used for clipping, and not changed during OSA steps */
2972         /* using an offset of +0.5 here would give clip errors on edges */
2973         viewplane->xmin *= pixsize;
2974         viewplane->xmax *= pixsize;
2975         viewplane->ymin *= pixsize;
2976         viewplane->ymax *= pixsize;
2977
2978         (*viewdx)= pixsize;
2979         (*viewdy)= (*ycor) * pixsize;
2980
2981         if(is_ortho)
2982                 orthographic_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2983         else
2984                 perspective_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2985
2986 }
2987
2988 #if 0
2989 static int pc_findindex(ListBase *listbase, int index)
2990 {
2991         LinkData *link= NULL;
2992         int number= 0;
2993         
2994         if (listbase == NULL) return -1;
2995         
2996         link= listbase->first;
2997         while (link) {
2998                 if ((int)link->data == index)
2999                         return number;
3000                 
3001                 number++;
3002                 link= link->next;
3003         }
3004         
3005         return -1;
3006 }
3007
3008 void object_delete_ptcache(Object *ob, int index) 
3009 {
3010         int list_index = pc_findindex(&ob->pc_ids, index);
3011         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
3012         BLI_freelinkN(&ob->pc_ids, link);
3013 }
3014 #endif
3015
3016 /* shape key utility function */
3017
3018 /************************* Mesh ************************/
3019 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
3020 {
3021         Mesh *me= ob->data;
3022         Key *key= me->key;
3023         KeyBlock *kb;
3024         int newkey= 0;
3025
3026         if(key == NULL) {
3027                 key= me->key= add_key((ID *)me);
3028                 key->type= KEY_RELATIVE;
3029                 newkey= 1;
3030         }
3031
3032         if(newkey || from_mix==FALSE) {
3033                 /* create from mesh */
3034                 kb= add_keyblock(key, name);
3035                 mesh_to_key(me, kb);
3036         }
3037         else {
3038                 /* copy from current values */
3039                 float *data= do_ob_key(scene, ob);
3040
3041                 /* create new block with prepared data */
3042                 kb= add_keyblock(key, name);
3043                 kb->data= data;
3044                 kb->totelem= me->totvert;
3045         }
3046
3047         return kb;
3048 }
3049 /************************* Lattice ************************/
3050 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
3051 {
3052         Lattice *lt= ob->data;
3053         Key *key= lt->key;
3054         KeyBlock *kb;
3055         int newkey= 0;
3056
3057         if(key==NULL) {
3058                 key= lt->key= add_key( (ID *)lt);
3059                 key->type= KEY_RELATIVE;
3060                 newkey= 1;
3061         }
3062
3063         if(newkey || from_mix==FALSE) {
3064                 kb= add_keyblock(key, name);
3065                 if (!newkey) {
3066                         KeyBlock *basekb= (KeyBlock *)key->block.first;
3067                         kb->data= MEM_dupallocN(basekb->data);
3068                         kb->totelem= basekb->totelem;
3069                 }
3070                 else {
3071                         latt_to_key(lt, kb);
3072                 }
3073         }
3074         else {
3075                 /* copy from current values */
3076                 float *data= do_ob_key(scene, ob);
3077
3078                 /* create new block with prepared data */
3079                 kb= add_keyblock(key, name);
3080                 kb->totelem= lt->pntsu*lt->pntsv*lt->pntsw;
3081                 kb->data= data;
3082         }
3083
3084         return kb;
3085 }
3086 /************************* Curve ************************/
3087 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
3088 {
3089         Curve *cu= ob->data;
3090         Key *key= cu->key;
3091         KeyBlock *kb;
3092         ListBase *lb= BKE_curve_nurbs(cu);
3093         int newkey= 0;
3094
3095         if(key==NULL) {
3096                 key= cu->key= add_key( (ID *)cu);
3097                 key->type = KEY_RELATIVE;
3098                 newkey= 1;
3099         }
3100
3101         if(newkey || from_mix==FALSE) {
3102                 /* create from curve */
3103                 kb= add_keyblock(key, name);
3104                 if (!newkey) {
3105                         KeyBlock *basekb= (KeyBlock *)key->block.first;
3106                         kb->data= MEM_dupallocN(basekb->data);
3107                         kb->totelem= basekb->totelem;
3108                 }
3109                 else {
3110                         curve_to_key(cu, kb, lb);
3111                 }
3112         }
3113         else {
3114                 /* copy from current values */
3115                 float *data= do_ob_key(scene, ob);
3116
3117                 /* create new block with prepared data */
3118                 kb= add_keyblock(key, name);
3119                 kb->totelem= count_curveverts(lb);
3120                 kb->data= data;
3121         }
3122
3123         return kb;
3124 }
3125
3126 KeyBlock *object_insert_shape_key(Scene *scene, Object *ob, const char *name, int from_mix)
3127 {
3128         if(ob->type==OB_MESH)                                    return insert_meshkey(scene, ob, name, from_mix);
3129         else if ELEM(ob->type, OB_CURVE, OB_SURF)return insert_curvekey(scene, ob, name, from_mix);
3130         else if(ob->type==OB_LATTICE)                    return insert_lattkey(scene, ob, name, from_mix);
3131         else                                                                     return NULL;
3132 }
3133
3134 /* most important if this is modified it should _always_ return True, in certain
3135  * cases false positives are hard to avoid (shape keys for eg)
3136  */
3137 int object_is_modified(Scene *scene, Object *ob)
3138 {
3139         int flag= 0;
3140
3141         if(ob_get_key(ob)) {
3142                 flag |= eModifierMode_Render;
3143         }
3144         else {
3145                 ModifierData *md;
3146                 /* cloth */