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