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