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