2.5 - Animation Tweaks
[blender.git] / source / blender / blenkernel / intern / object.c
1 /* object.c
2  *
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <string.h>
33 #include <math.h>
34 #include <stdio.h>                      
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include "MEM_guardedalloc.h"
41
42 #include "DNA_anim_types.h"
43 #include "DNA_action_types.h"
44 #include "DNA_armature_types.h"
45 #include "DNA_boid_types.h"
46 #include "DNA_camera_types.h"
47 #include "DNA_constraint_types.h"
48 #include "DNA_curve_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_lamp_types.h"
51 #include "DNA_lattice_types.h"
52 #include "DNA_material_types.h"
53 #include "DNA_mesh_types.h"
54 #include "DNA_meta_types.h"
55 #include "DNA_curve_types.h"
56 #include "DNA_meshdata_types.h"
57 #include "DNA_modifier_types.h"
58 #include "DNA_nla_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_object_force.h"
61 #include "DNA_object_fluidsim.h"
62 #include "DNA_outliner_types.h"
63 #include "DNA_particle_types.h"
64 #include "DNA_scene_types.h"
65 #include "DNA_screen_types.h"
66 #include "DNA_space_types.h"
67 #include "DNA_texture_types.h"
68 #include "DNA_userdef_types.h"
69 #include "DNA_view3d_types.h"
70 #include "DNA_world_types.h"
71
72 #include "BLI_blenlib.h"
73 #include "BLI_arithb.h"
74 #include "BLI_editVert.h"
75
76 #include "BKE_utildefines.h"
77
78 #include "BKE_main.h"
79 #include "BKE_global.h"
80
81 #include "BKE_armature.h"
82 #include "BKE_action.h"
83 #include "BKE_bullet.h"
84 #include "BKE_colortools.h"
85 #include "BKE_deform.h"
86 #include "BKE_DerivedMesh.h"
87 #include "BKE_nla.h"
88 #include "BKE_animsys.h"
89 #include "BKE_anim.h"
90 #include "BKE_blender.h"
91 #include "BKE_constraint.h"
92 #include "BKE_curve.h"
93 #include "BKE_displist.h"
94 #include "BKE_fcurve.h"
95 #include "BKE_group.h"
96 #include "BKE_icons.h"
97 #include "BKE_key.h"
98 #include "BKE_lattice.h"
99 #include "BKE_library.h"
100 #include "BKE_mesh.h"
101 #include "BKE_mball.h"
102 #include "BKE_modifier.h"
103 #include "BKE_object.h"
104 #include "BKE_paint.h"
105 #include "BKE_particle.h"
106 #include "BKE_pointcache.h"
107 #include "BKE_property.h"
108 #include "BKE_sca.h"
109 #include "BKE_scene.h"
110 #include "BKE_screen.h"
111 #include "BKE_softbody.h"
112
113 #include "LBM_fluidsim.h"
114
115 #ifndef DISABLE_PYTHON
116 #include "BPY_extern.h"
117 #endif
118
119 #include "GPU_material.h"
120
121 /* Local function protos */
122 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
123
124 float originmat[3][3];  /* after where_is_object(), can be used in other functions (bad!) */
125
126 void clear_workob(Object *workob)
127 {
128         memset(workob, 0, sizeof(Object));
129         
130         workob->size[0]= workob->size[1]= workob->size[2]= 1.0;
131         
132 }
133
134 void copy_baseflags(struct Scene *scene)
135 {
136         Base *base= scene->base.first;
137         
138         while(base) {
139                 base->object->flag= base->flag;
140                 base= base->next;
141         }
142 }
143
144 void copy_objectflags(struct Scene *scene)
145 {
146         Base *base= scene->base.first;
147         
148         while(base) {
149                 base->flag= base->object->flag;
150                 base= base->next;
151         }
152 }
153
154 void update_base_layer(struct Scene *scene, Object *ob)
155 {
156         Base *base= scene->base.first;
157
158         while (base) {
159                 if (base->object == ob) base->lay= ob->lay;
160                 base= base->next;
161         }
162 }
163
164 void object_free_particlesystems(Object *ob)
165 {
166         while(ob->particlesystem.first){
167                 ParticleSystem *psys = ob->particlesystem.first;
168
169                 BLI_remlink(&ob->particlesystem,psys);
170
171                 psys_free(ob,psys);
172         }
173 }
174
175 void object_free_softbody(Object *ob)
176 {
177         if(ob->soft) {
178                 sbFree(ob->soft);
179                 ob->soft= NULL;
180         }
181 }
182
183 void object_free_bulletsoftbody(Object *ob)
184 {
185         if(ob->bsoft) {
186                 bsbFree(ob->bsoft);
187                 ob->bsoft= NULL;
188         }
189 }
190
191 void object_free_modifiers(Object *ob)
192 {
193         while (ob->modifiers.first) {
194                 ModifierData *md = ob->modifiers.first;
195
196                 BLI_remlink(&ob->modifiers, md);
197
198                 modifier_free(md);
199         }
200
201         /* particle modifiers were freed, so free the particlesystems as well */
202         object_free_particlesystems(ob);
203
204         /* same for softbody */
205         object_free_softbody(ob);
206 }
207
208 /* here we will collect all local displist stuff */
209 /* also (ab)used in depsgraph */
210 void object_free_display(Object *ob)
211 {
212         if(ob->derivedDeform) {
213                 ob->derivedDeform->needsFree = 1;
214                 ob->derivedDeform->release(ob->derivedDeform);
215                 ob->derivedDeform= NULL;
216         }
217         if(ob->derivedFinal) {
218                 ob->derivedFinal->needsFree = 1;
219                 ob->derivedFinal->release(ob->derivedFinal);
220                 ob->derivedFinal= NULL;
221         }
222         
223         freedisplist(&ob->disp);
224 }
225
226 void free_sculptsession(SculptSession **ssp)
227 {
228         if(ssp && *ssp) {
229                 SculptSession *ss = *ssp;
230                 if(ss->projverts)
231                         MEM_freeN(ss->projverts);
232
233                 if(ss->fmap)
234                         MEM_freeN(ss->fmap);
235
236                 if(ss->fmap_mem)
237                         MEM_freeN(ss->fmap_mem);
238
239                 if(ss->texcache)
240                         MEM_freeN(ss->texcache);
241
242                 if(ss->layer_disps)
243                         MEM_freeN(ss->layer_disps);
244
245                 if(ss->mesh_co_orig)
246                         MEM_freeN(ss->mesh_co_orig);
247
248                 MEM_freeN(ss);
249
250                 *ssp = NULL;
251         }
252 }
253
254 /* do not free object itself */
255 void free_object(Object *ob)
256 {
257         int a;
258         
259         object_free_display(ob);
260         
261         /* disconnect specific data */
262         if(ob->data) {
263                 ID *id= ob->data;
264                 id->us--;
265                 if(id->us==0) {
266                         if(ob->type==OB_MESH) unlink_mesh(ob->data);
267                         else if(ob->type==OB_CURVE) unlink_curve(ob->data);
268                         else if(ob->type==OB_MBALL) unlink_mball(ob->data);
269                 }
270                 ob->data= 0;
271         }
272         
273         for(a=0; a<ob->totcol; a++) {
274                 if(ob->mat[a]) ob->mat[a]->id.us--;
275         }
276         if(ob->mat) MEM_freeN(ob->mat);
277         if(ob->matbits) MEM_freeN(ob->matbits);
278         ob->mat= 0;
279         ob->matbits= 0;
280         if(ob->bb) MEM_freeN(ob->bb); 
281         ob->bb= 0;
282         if(ob->path) free_path(ob->path); 
283         ob->path= 0;
284         if(ob->adt) BKE_free_animdata((ID *)ob);
285         if(ob->poselib) ob->poselib->id.us--;
286         if(ob->dup_group) ob->dup_group->id.us--;
287         if(ob->gpd) ob->gpd->id.us--;
288         if(ob->defbase.first)
289                 BLI_freelistN(&ob->defbase);
290         if(ob->pose)
291                 free_pose(ob->pose);
292         free_properties(&ob->prop);
293         object_free_modifiers(ob);
294         
295         free_sensors(&ob->sensors);
296         free_controllers(&ob->controllers);
297         free_actuators(&ob->actuators);
298         
299         free_constraints(&ob->constraints);
300         
301         if(ob->pd){
302                 if(ob->pd->tex)
303                         ob->pd->tex->id.us--;
304                 MEM_freeN(ob->pd);
305         }
306         if(ob->soft) sbFree(ob->soft);
307         if(ob->bsoft) bsbFree(ob->bsoft);
308         if(ob->gpulamp.first) GPU_lamp_free(ob);
309
310         free_sculptsession(&ob->sculpt);
311
312         if(ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
313 }
314
315 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
316 {
317         Object *unlinkOb = userData;
318
319         if (*obpoin==unlinkOb) {
320                 *obpoin = NULL;
321                 ob->recalc |= OB_RECALC;
322         }
323 }
324 void unlink_object(Scene *scene, Object *ob)
325 {
326         Object *obt;
327         Material *mat;
328         World *wrld;
329         bScreen *sc;
330         Scene *sce;
331         Curve *cu;
332         Tex *tex;
333         Group *group;
334         Camera *camera;
335         bConstraint *con;
336         //bActionStrip *strip; // XXX animsys 
337         ModifierData *md;
338         int a;
339         
340         unlink_controllers(&ob->controllers);
341         unlink_actuators(&ob->actuators);
342         
343         /* check all objects: parents en bevels and fields, also from libraries */
344         obt= G.main->object.first;
345         while(obt) {
346                 if(obt->proxy==ob)
347                         obt->proxy= NULL;
348                 if(obt->proxy_from==ob) {
349                         obt->proxy_from= NULL;
350                         obt->recalc |= OB_RECALC_OB;
351                 }
352                 if(obt->proxy_group==ob)
353                         obt->proxy_group= NULL;
354                 
355                 if(obt->parent==ob) {
356                         obt->parent= NULL;
357                         obt->recalc |= OB_RECALC;
358                 }
359                 
360                 if(obt->track==ob) {
361                         obt->track= NULL;
362                         obt->recalc |= OB_RECALC_OB;
363                 }
364                 
365                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
366                 
367                 if ELEM(obt->type, OB_CURVE, OB_FONT) {
368                         cu= obt->data;
369
370                         if(cu->bevobj==ob) {
371                                 cu->bevobj= NULL;
372                                 obt->recalc |= OB_RECALC;
373                         }
374                         if(cu->taperobj==ob) {
375                                 cu->taperobj= NULL;
376                                 obt->recalc |= OB_RECALC;
377                         }
378                         if(cu->textoncurve==ob) {
379                                 cu->textoncurve= NULL;
380                                 obt->recalc |= OB_RECALC;
381                         }
382                 }
383                 else if(obt->type==OB_ARMATURE && obt->pose) {
384                         bPoseChannel *pchan;
385                         for(pchan= obt->pose->chanbase.first; pchan; pchan= pchan->next) {
386                                 for (con = pchan->constraints.first; con; con=con->next) {
387                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
388                                         ListBase targets = {NULL, NULL};
389                                         bConstraintTarget *ct;
390                                         
391                                         if (cti && cti->get_constraint_targets) {
392                                                 cti->get_constraint_targets(con, &targets);
393                                                 
394                                                 for (ct= targets.first; ct; ct= ct->next) {
395                                                         if (ct->tar == ob) {
396                                                                 ct->tar = NULL;
397                                                                 strcpy(ct->subtarget, "");
398                                                                 obt->recalc |= OB_RECALC_DATA;
399                                                         }
400                                                 }
401                                                 
402                                                 if (cti->flush_constraint_targets)
403                                                         cti->flush_constraint_targets(con, &targets, 0);
404                                         }
405                                 }
406                                 if(pchan->custom==ob)
407                                         pchan->custom= NULL;
408                         }
409                 }
410                 
411                 sca_remove_ob_poin(obt, ob);
412                 
413                 for (con = obt->constraints.first; con; con=con->next) {
414                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
415                         ListBase targets = {NULL, NULL};
416                         bConstraintTarget *ct;
417                         
418                         if (cti && cti->get_constraint_targets) {
419                                 cti->get_constraint_targets(con, &targets);
420                                 
421                                 for (ct= targets.first; ct; ct= ct->next) {
422                                         if (ct->tar == ob) {
423                                                 ct->tar = NULL;
424                                                 strcpy(ct->subtarget, "");
425                                                 obt->recalc |= OB_RECALC_DATA;
426                                         }
427                                 }
428                                 
429                                 if (cti->flush_constraint_targets)
430                                         cti->flush_constraint_targets(con, &targets, 0);
431                         }
432                 }
433                 
434                 /* object is deflector or field */
435                 if(ob->pd) {
436                         if(obt->soft)
437                                 obt->recalc |= OB_RECALC_DATA;
438
439                         /* cloth */
440                         for(md=obt->modifiers.first; md; md=md->next)
441                                 if(md->type == eModifierType_Cloth)
442                                         obt->recalc |= OB_RECALC_DATA;
443                 }
444                 
445                 /* strips */
446 #if 0 // XXX old animation system
447                 for(strip= obt->nlastrips.first; strip; strip= strip->next) {
448                         if(strip->object==ob)
449                                 strip->object= NULL;
450                         
451                         if(strip->modifiers.first) {
452                                 bActionModifier *amod;
453                                 for(amod= strip->modifiers.first; amod; amod= amod->next)
454                                         if(amod->ob==ob)
455                                                 amod->ob= NULL;
456                         }
457                 }
458 #endif // XXX old animation system
459
460                 /* particle systems */
461                 if(obt->particlesystem.first) {
462                         ParticleSystem *tpsys= obt->particlesystem.first;
463                         for(; tpsys; tpsys=tpsys->next) {
464                                 BoidState *state = NULL;
465                                 BoidRule *rule = NULL;
466
467                                 ParticleTarget *pt = tpsys->targets.first;
468                                 for(; pt; pt=pt->next) {
469                                         if(pt->ob==ob) {
470                                                 pt->ob = NULL;
471                                                 obt->recalc |= OB_RECALC_DATA;
472                                                 break;
473                                         }
474                                 }
475
476                                 if(tpsys->target_ob==ob) {
477                                         tpsys->target_ob= NULL;
478                                         obt->recalc |= OB_RECALC_DATA;
479                                 }
480
481                                 if(tpsys->part->dup_ob==ob)
482                                         tpsys->part->dup_ob= NULL;
483
484                                 if(tpsys->part->phystype==PART_PHYS_BOIDS) {
485                                         ParticleData *pa;
486                                         BoidParticle *bpa;
487                                         int p;
488
489                                         for(p=0,pa=tpsys->particles; p<tpsys->totpart; p++,pa++) {
490                                                 bpa = pa->boid;
491                                                 if(bpa->ground == ob)
492                                                         bpa->ground = NULL;
493                                         }
494                                 }
495                                 if(tpsys->part->boids) {
496                                         for(state = tpsys->part->boids->states.first; state; state=state->next) {
497                                                 for(rule = state->rules.first; rule; rule=rule->next) {
498                                                         if(rule->type==eBoidRuleType_Avoid) {
499                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*)rule;
500                                                                 if(gabr->ob==ob)
501                                                                         gabr->ob= NULL;
502                                                         }
503                                                         else if(rule->type==eBoidRuleType_FollowLeader) {
504                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*)rule;
505                                                                 if(flbr->ob==ob)
506                                                                         flbr->ob= NULL;
507                                                         }
508                                                 }
509                                         }
510                                 }
511                         }
512                         if(ob->pd)
513                                 obt->recalc |= OB_RECALC_DATA;
514                 }
515
516                 obt= obt->id.next;
517         }
518         
519         /* materials */
520         mat= G.main->mat.first;
521         while(mat) {
522         
523                 for(a=0; a<MAX_MTEX; a++) {
524                         if(mat->mtex[a] && ob==mat->mtex[a]->object) {
525                                 /* actually, test for lib here... to do */
526                                 mat->mtex[a]->object= NULL;
527                         }
528                 }
529
530                 mat= mat->id.next;
531         }
532         
533         /* textures */
534         tex= G.main->tex.first;
535         while(tex) {
536                 if(tex->env) {
537                         if(tex->env->object == ob) tex->env->object= NULL;
538                 }
539                 tex= tex->id.next;
540         }
541         
542         /* mballs (scene==NULL when called from library.c) */
543         if(scene && ob->type==OB_MBALL) {
544                 obt= find_basis_mball(scene, ob);
545                 if(obt) freedisplist(&obt->disp);
546         }
547         
548         /* worlds */
549         wrld= G.main->world.first;
550         while(wrld) {
551                 if(wrld->id.lib==NULL) {
552                         for(a=0; a<MAX_MTEX; a++) {
553                                 if(wrld->mtex[a] && ob==wrld->mtex[a]->object)
554                                         wrld->mtex[a]->object= NULL;
555                         }
556                 }
557                 
558                 wrld= wrld->id.next;
559         }
560                 
561         /* scenes */
562         sce= G.main->scene.first;
563         while(sce) {
564                 if(sce->id.lib==NULL) {
565                         if(sce->camera==ob) sce->camera= NULL;
566                         if(sce->toolsettings->skgen_template==ob) sce->toolsettings->skgen_template = NULL;
567                 }
568                 sce= sce->id.next;
569         }
570         
571 #if 0 // XXX old animation system
572         /* ipos */
573         ipo= G.main->ipo.first;
574         while(ipo) {
575                 if(ipo->id.lib==NULL) {
576                         IpoCurve *icu;
577                         for(icu= ipo->curve.first; icu; icu= icu->next) {
578                                 if(icu->driver && icu->driver->ob==ob)
579                                         icu->driver->ob= NULL;
580                         }
581                 }
582                 ipo= ipo->id.next;
583         }
584 #endif // XXX old animation system
585         
586         /* screens */
587         sc= G.main->screen.first;
588         while(sc) {
589                 ScrArea *sa= sc->areabase.first;
590                 while(sa) {
591                         SpaceLink *sl;
592
593                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
594                                 if(sl->spacetype==SPACE_VIEW3D) {
595                                         View3D *v3d= (View3D*) sl;
596
597                                         if(v3d->camera==ob) {
598                                                 v3d->camera= NULL;
599                                                 // XXX if(v3d->persp==V3D_CAMOB) v3d->persp= V3D_PERSP;
600                                         }
601                                         if(v3d->localvd && v3d->localvd->camera==ob ) {
602                                                 v3d->localvd->camera= NULL;
603                                                 // XXX if(v3d->localvd->persp==V3D_CAMOB) v3d->localvd->persp= V3D_PERSP;
604                                         }
605                                 }
606                                 else if(sl->spacetype==SPACE_OUTLINER) {
607                                         SpaceOops *so= (SpaceOops *)sl;
608
609                                         if(so->treestore) {
610                                                 TreeStoreElem *tselem= so->treestore->data;
611                                                 int a;
612                                                 for(a=0; a<so->treestore->usedelem; a++, tselem++) {
613                                                         if(tselem->id==(ID *)ob) tselem->id= NULL;
614                                                 }
615                                         }
616                                 }
617                         }
618
619                         sa= sa->next;
620                 }
621                 sc= sc->id.next;
622         }
623
624         /* groups */
625         group= G.main->group.first;
626         while(group) {
627                 rem_from_group(group, ob);
628                 group= group->id.next;
629         }
630         
631         /* cameras */
632         camera= G.main->camera.first;
633         while(camera) {
634                 if (camera->dof_ob==ob) {
635                         camera->dof_ob = NULL;
636                 }
637                 camera= camera->id.next;
638         }
639 }
640
641 int exist_object(Object *obtest)
642 {
643         Object *ob;
644         
645         if(obtest==NULL) return 0;
646         
647         ob= G.main->object.first;
648         while(ob) {
649                 if(ob==obtest) return 1;
650                 ob= ob->id.next;
651         }
652         return 0;
653 }
654
655 void *add_camera(char *name)
656 {
657         Camera *cam;
658         
659         cam=  alloc_libblock(&G.main->camera, ID_CA, name);
660
661         cam->lens= 35.0f;
662         cam->angle= 49.14f;
663         cam->clipsta= 0.1f;
664         cam->clipend= 100.0f;
665         cam->drawsize= 0.5f;
666         cam->ortho_scale= 6.0;
667         cam->flag |= CAM_SHOWTITLESAFE;
668         cam->passepartalpha = 0.2f;
669         
670         return cam;
671 }
672
673 Camera *copy_camera(Camera *cam)
674 {
675         Camera *camn;
676         
677         camn= copy_libblock(cam);
678         camn->adt= BKE_copy_animdata(cam->adt);
679         
680         return camn;
681 }
682
683
684
685 void make_local_camera(Camera *cam)
686 {
687         Object *ob;
688         Camera *camn;
689         int local=0, lib=0;
690
691         /* - only lib users: do nothing
692             * - only local users: set flag
693             * - mixed: make copy
694             */
695         
696         if(cam->id.lib==0) return;
697         if(cam->id.us==1) {
698                 cam->id.lib= 0;
699                 cam->id.flag= LIB_LOCAL;
700                 new_id(0, (ID *)cam, 0);
701                 return;
702         }
703         
704         ob= G.main->object.first;
705         while(ob) {
706                 if(ob->data==cam) {
707                         if(ob->id.lib) lib= 1;
708                         else local= 1;
709                 }
710                 ob= ob->id.next;
711         }
712         
713         if(local && lib==0) {
714                 cam->id.lib= 0;
715                 cam->id.flag= LIB_LOCAL;
716                 new_id(0, (ID *)cam, 0);
717         }
718         else if(local && lib) {
719                 camn= copy_camera(cam);
720                 camn->id.us= 0;
721                 
722                 ob= G.main->object.first;
723                 while(ob) {
724                         if(ob->data==cam) {
725                                 
726                                 if(ob->id.lib==0) {
727                                         ob->data= camn;
728                                         camn->id.us++;
729                                         cam->id.us--;
730                                 }
731                         }
732                         ob= ob->id.next;
733                 }
734         }
735 }
736
737 /* get the camera's dof value, takes the dof object into account */
738 float dof_camera(Object *ob)
739 {
740         Camera *cam = (Camera *)ob->data; 
741         if (ob->type != OB_CAMERA)
742                 return 0.0f;
743         if (cam->dof_ob) {      
744                 /* too simple, better to return the distance on the view axis only
745                  * return VecLenf(ob->obmat[3], cam->dof_ob->obmat[3]); */
746                 float mat[4][4], obmat[4][4];
747                 
748                 Mat4CpyMat4(obmat, ob->obmat);
749                 Mat4Ortho(obmat);
750                 Mat4Invert(ob->imat, obmat);
751                 Mat4MulMat4(mat, cam->dof_ob->obmat, ob->imat);
752                 return (float)fabs(mat[3][2]);
753         }
754         return cam->YF_dofdist;
755 }
756
757 void *add_lamp(char *name)
758 {
759         Lamp *la;
760         
761         la=  alloc_libblock(&G.main->lamp, ID_LA, name);
762         
763         la->r= la->g= la->b= la->k= 1.0f;
764         la->haint= la->energy= 1.0f;
765         la->dist= 25.0f;
766         la->spotsize= 45.0f;
767         la->spotblend= 0.15f;
768         la->att2= 1.0f;
769         la->mode= LA_SHAD_BUF;
770         la->bufsize= 512;
771         la->clipsta= 0.5f;
772         la->clipend= 40.0f;
773         la->shadspotsize= 45.0f;
774         la->samp= 3;
775         la->bias= 1.0f;
776         la->soft= 3.0f;
777         la->ray_samp= la->ray_sampy= la->ray_sampz= 1; 
778         la->area_size=la->area_sizey=la->area_sizez= 1.0f; 
779         la->buffers= 1;
780         la->buftype= LA_SHADBUF_HALFWAY;
781         la->ray_samp_method = LA_SAMP_HALTON;
782         la->adapt_thresh = 0.001f;
783         la->preview=NULL;
784         la->falloff_type = LA_FALLOFF_INVSQUARE;
785         la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
786         la->sun_effect_type = 0;
787         la->horizon_brightness = 1.0;
788         la->spread = 1.0;
789         la->sun_brightness = 1.0;
790         la->sun_size = 1.0;
791         la->backscattered_light = 1.0f;
792         la->atm_turbidity = 2.0f;
793         la->atm_inscattering_factor = 1.0f;
794         la->atm_extinction_factor = 1.0f;
795         la->atm_distance_factor = 1.0f;
796         la->sun_intensity = 1.0f;
797         la->skyblendtype= MA_RAMP_ADD;
798         la->skyblendfac= 1.0f;
799         la->sky_colorspace= BLI_CS_CIE;
800         la->sky_exposure= 1.0f;
801         
802         curvemapping_initialize(la->curfalloff);
803         return la;
804 }
805
806 Lamp *copy_lamp(Lamp *la)
807 {
808         Lamp *lan;
809         int a;
810         
811         lan= copy_libblock(la);
812
813         for(a=0; a<MAX_MTEX; a++) {
814                 if(lan->mtex[a]) {
815                         lan->mtex[a]= MEM_mallocN(sizeof(MTex), "copylamptex");
816                         memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex));
817                         id_us_plus((ID *)lan->mtex[a]->tex);
818                 }
819         }
820         
821         lan->curfalloff = curvemapping_copy(la->curfalloff);
822         
823 #if 0 // XXX old animation system
824         id_us_plus((ID *)lan->ipo);
825 #endif // XXX old animation system
826
827         if (la->preview) lan->preview = BKE_previewimg_copy(la->preview);
828         
829         return lan;
830 }
831
832 void make_local_lamp(Lamp *la)
833 {
834         Object *ob;
835         Lamp *lan;
836         int local=0, lib=0;
837
838         /* - only lib users: do nothing
839             * - only local users: set flag
840             * - mixed: make copy
841             */
842         
843         if(la->id.lib==0) return;
844         if(la->id.us==1) {
845                 la->id.lib= 0;
846                 la->id.flag= LIB_LOCAL;
847                 new_id(0, (ID *)la, 0);
848                 return;
849         }
850         
851         ob= G.main->object.first;
852         while(ob) {
853                 if(ob->data==la) {
854                         if(ob->id.lib) lib= 1;
855                         else local= 1;
856                 }
857                 ob= ob->id.next;
858         }
859         
860         if(local && lib==0) {
861                 la->id.lib= 0;
862                 la->id.flag= LIB_LOCAL;
863                 new_id(0, (ID *)la, 0);
864         }
865         else if(local && lib) {
866                 lan= copy_lamp(la);
867                 lan->id.us= 0;
868                 
869                 ob= G.main->object.first;
870                 while(ob) {
871                         if(ob->data==la) {
872                                 
873                                 if(ob->id.lib==0) {
874                                         ob->data= lan;
875                                         lan->id.us++;
876                                         la->id.us--;
877                                 }
878                         }
879                         ob= ob->id.next;
880                 }
881         }
882 }
883
884 void free_camera(Camera *ca)
885 {
886         BKE_free_animdata((ID *)ca);
887 }
888
889 void free_lamp(Lamp *la)
890 {
891         MTex *mtex;
892         int a;
893
894         for(a=0; a<MAX_MTEX; a++) {
895                 mtex= la->mtex[a];
896                 if(mtex && mtex->tex) mtex->tex->id.us--;
897                 if(mtex) MEM_freeN(mtex);
898         }
899         
900         BKE_free_animdata((ID *)la);
901
902         curvemapping_free(la->curfalloff);
903         
904         BKE_previewimg_free(&la->preview);
905         BKE_icon_delete(&la->id);
906         la->id.icon_id = 0;
907 }
908
909 void *add_wave()
910 {
911         return 0;
912 }
913
914
915 /* *************************************************** */
916
917 static void *add_obdata_from_type(int type)
918 {
919         switch (type) {
920         case OB_MESH: return add_mesh("Mesh");
921         case OB_CURVE: return add_curve("Curve", OB_CURVE);
922         case OB_SURF: return add_curve("Surf", OB_SURF);
923         case OB_FONT: return add_curve("Text", OB_FONT);
924         case OB_MBALL: return add_mball("Meta");
925         case OB_CAMERA: return add_camera("Camera");
926         case OB_LAMP: return add_lamp("Lamp");
927         case OB_LATTICE: return add_lattice("Lattice");
928         case OB_WAVE: return add_wave();
929         case OB_ARMATURE: return add_armature("Armature");
930         case OB_EMPTY: return NULL;
931         default:
932                 printf("add_obdata_from_type: Internal error, bad type: %d\n", type);
933                 return NULL;
934         }
935 }
936
937 static char *get_obdata_defname(int type)
938 {
939         switch (type) {
940         case OB_MESH: return "Mesh";
941         case OB_CURVE: return "Curve";
942         case OB_SURF: return "Surf";
943         case OB_FONT: return "Font";
944         case OB_MBALL: return "Mball";
945         case OB_CAMERA: return "Camera";
946         case OB_LAMP: return "Lamp";
947         case OB_LATTICE: return "Lattice";
948         case OB_WAVE: return "Wave";
949         case OB_ARMATURE: return "Armature";
950         case OB_EMPTY: return "Empty";
951         default:
952                 printf("get_obdata_defname: Internal error, bad type: %d\n", type);
953                 return "Empty";
954         }
955 }
956
957 /* more general add: creates minimum required data, but without vertices etc. */
958 Object *add_only_object(int type, char *name)
959 {
960         Object *ob;
961
962         ob= alloc_libblock(&G.main->object, ID_OB, name);
963
964         /* default object vars */
965         ob->type= type;
966         /* ob->transflag= OB_QUAT; */
967
968 #if 0 /* not used yet */
969         QuatOne(ob->quat);
970         QuatOne(ob->dquat);
971 #endif 
972
973         ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
974         ob->col[3]= 1.0;
975
976         ob->loc[0]= ob->loc[1]= ob->loc[2]= 0.0;
977         ob->rot[0]= ob->rot[1]= ob->rot[2]= 0.0;
978         ob->size[0]= ob->size[1]= ob->size[2]= 1.0;
979
980         Mat4One(ob->constinv);
981         Mat4One(ob->parentinv);
982         Mat4One(ob->obmat);
983         ob->dt= OB_SHADED;
984         ob->empty_drawtype= OB_ARROWS;
985         ob->empty_drawsize= 1.0;
986
987         if(type==OB_CAMERA || type==OB_LAMP) {
988                 ob->trackflag= OB_NEGZ;
989                 ob->upflag= OB_POSY;
990         }
991         else {
992                 ob->trackflag= OB_POSY;
993                 ob->upflag= OB_POSZ;
994         }
995         
996 #if 0 // XXX old animation system
997         ob->ipoflag = OB_OFFS_OB+OB_OFFS_PARENT;
998         ob->ipowin= ID_OB;      /* the ipowin shown */
999 #endif // XXX old animation system
1000         
1001         ob->dupon= 1; ob->dupoff= 0;
1002         ob->dupsta= 1; ob->dupend= 100;
1003         ob->dupfacesca = 1.0;
1004
1005         /* Game engine defaults*/
1006         ob->mass= ob->inertia= 1.0f;
1007         ob->formfactor= 0.4f;
1008         ob->damping= 0.04f;
1009         ob->rdamping= 0.1f;
1010         ob->anisotropicFriction[0] = 1.0f;
1011         ob->anisotropicFriction[1] = 1.0f;
1012         ob->anisotropicFriction[2] = 1.0f;
1013         ob->gameflag= OB_PROP|OB_COLLISION;
1014         ob->margin = 0.0;
1015         /* ob->pad3 == Contact Processing Threshold */
1016         ob->m_contactProcessingThreshold = 1.;
1017         
1018         /* NT fluid sim defaults */
1019         ob->fluidsimFlag = 0;
1020         ob->fluidsimSettings = NULL;
1021
1022         ob->pc_ids.first = ob->pc_ids.last = NULL;
1023
1024         return ob;
1025 }
1026
1027 /* general add: to scene, with layer from area and default name */
1028 /* creates minimum required data, but without vertices etc. */
1029 Object *add_object(struct Scene *scene, int type)
1030 {
1031         Object *ob;
1032         Base *base;
1033         char name[32];
1034
1035         strcpy(name, get_obdata_defname(type));
1036         ob = add_only_object(type, name);
1037
1038         ob->data= add_obdata_from_type(type);
1039
1040         ob->lay= scene->lay;
1041
1042         base= scene_add_base(scene, ob);
1043         scene_select_base(scene, base);
1044         ob->recalc |= OB_RECALC;
1045
1046         return ob;
1047 }
1048
1049 SoftBody *copy_softbody(SoftBody *sb)
1050 {
1051         SoftBody *sbn;
1052         
1053         if (sb==NULL) return(NULL);
1054         
1055         sbn= MEM_dupallocN(sb);
1056         sbn->totspring= sbn->totpoint= 0;
1057         sbn->bpoint= NULL;
1058         sbn->bspring= NULL;
1059         
1060         sbn->keys= NULL;
1061         sbn->totkey= sbn->totpointkey= 0;
1062         
1063         sbn->scratch= NULL;
1064
1065         sbn->pointcache= BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches);
1066
1067         return sbn;
1068 }
1069
1070 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1071 {
1072         BulletSoftBody *bsbn;
1073
1074         if (bsb == NULL)
1075                 return NULL;
1076         bsbn = MEM_dupallocN(bsb);
1077         /* no pointer in this structure yet */
1078         return bsbn;
1079 }
1080
1081 ParticleSystem *copy_particlesystem(ParticleSystem *psys)
1082 {
1083         ParticleSystem *psysn;
1084         ParticleData *pa;
1085         int p;
1086
1087         psysn= MEM_dupallocN(psys);
1088         psysn->particles= MEM_dupallocN(psys->particles);
1089         psysn->child= MEM_dupallocN(psys->child);
1090
1091         if(psys->part->type == PART_HAIR) {
1092                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++)
1093                         pa->hair = MEM_dupallocN(pa->hair);
1094         }
1095
1096         if(psysn->particles->keys || psysn->particles->boid) {
1097                 ParticleKey *key = psysn->particles->keys;
1098                 BoidParticle *boid = psysn->particles->boid;
1099
1100                 if(key)
1101                         key = MEM_dupallocN(key);
1102                 
1103                 if(boid)
1104                         boid = MEM_dupallocN(boid);
1105                 
1106                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++) {
1107                         if(boid)
1108                                 pa->boid = boid++;
1109                         if(key) {
1110                                 pa->keys = key;
1111                                 key += pa->totkey;
1112                         }
1113                 }
1114         }
1115
1116         if(psys->clmd) {
1117                 ClothModifierData *nclmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1118                 modifier_copyData((ModifierData*)psys->clmd, (ModifierData*)nclmd);
1119                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1120         }
1121
1122         BLI_duplicatelist(&psysn->targets, &psys->targets);
1123         
1124         psysn->pathcache= NULL;
1125         psysn->childcache= NULL;
1126         psysn->edit= NULL;
1127         psysn->effectors.first= psysn->effectors.last= 0;
1128         
1129         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1130         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1131         psysn->reactevents.first = psysn->reactevents.last = NULL;
1132         psysn->renderdata = NULL;
1133         
1134         psysn->pointcache= BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches);
1135
1136         id_us_plus((ID *)psysn->part);
1137
1138         return psysn;
1139 }
1140
1141 void copy_object_particlesystems(Object *obn, Object *ob)
1142 {
1143         ParticleSystemModifierData *psmd;
1144         ParticleSystem *psys, *npsys;
1145         ModifierData *md;
1146
1147         obn->particlesystem.first= obn->particlesystem.last= NULL;
1148         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
1149                 npsys= copy_particlesystem(psys);
1150
1151                 BLI_addtail(&obn->particlesystem, npsys);
1152
1153                 /* need to update particle modifiers too */
1154                 for(md=obn->modifiers.first; md; md=md->next) {
1155                         if(md->type==eModifierType_ParticleSystem) {
1156                                 psmd= (ParticleSystemModifierData*)md;
1157                                 if(psmd->psys==psys)
1158                                         psmd->psys= npsys;
1159                         }
1160                 }
1161         }
1162 }
1163
1164 void copy_object_softbody(Object *obn, Object *ob)
1165 {
1166         if(ob->soft)
1167                 obn->soft= copy_softbody(ob->soft);
1168 }
1169
1170 static void copy_object_pose(Object *obn, Object *ob)
1171 {
1172         bPoseChannel *chan;
1173         
1174         /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
1175         obn->pose= NULL;
1176         copy_pose(&obn->pose, ob->pose, 1);     /* 1 = copy constraints */
1177
1178         for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
1179                 bConstraint *con;
1180                 
1181                 chan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1182                 
1183                 for (con= chan->constraints.first; con; con= con->next) {
1184                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1185                         ListBase targets = {NULL, NULL};
1186                         bConstraintTarget *ct;
1187                         
1188 #if 0 // XXX old animation system
1189                         /* note that we can't change lib linked ipo blocks. for making
1190                          * proxies this still works correct however because the object
1191                          * is changed to object->proxy_from when evaluating the driver. */
1192                         if(con->ipo && !con->ipo->id.lib) {
1193                                 IpoCurve *icu;
1194                                 
1195                                 con->ipo= copy_ipo(con->ipo);
1196                                 
1197                                 for(icu= con->ipo->curve.first; icu; icu= icu->next) {
1198                                         if(icu->driver && icu->driver->ob==ob)
1199                                                 icu->driver->ob= obn;
1200                                 }
1201                         }
1202 #endif // XXX old animation system
1203                         
1204                         if (cti && cti->get_constraint_targets) {
1205                                 cti->get_constraint_targets(con, &targets);
1206                                 
1207                                 for (ct= targets.first; ct; ct= ct->next) {
1208                                         if (ct->tar == ob)
1209                                                 ct->tar = obn;
1210                                 }
1211                                 
1212                                 if (cti->flush_constraint_targets)
1213                                         cti->flush_constraint_targets(con, &targets, 0);
1214                         }
1215                 }
1216         }
1217 }
1218
1219 Object *copy_object(Object *ob)
1220 {
1221         Object *obn;
1222         ModifierData *md;
1223         int a;
1224
1225         obn= copy_libblock(ob);
1226         
1227         if(ob->totcol) {
1228                 obn->mat= MEM_dupallocN(ob->mat);
1229                 obn->matbits= MEM_dupallocN(ob->matbits);
1230         }
1231         
1232         if(ob->bb) obn->bb= MEM_dupallocN(ob->bb);
1233         obn->path= NULL;
1234         obn->flag &= ~OB_FROMGROUP;
1235         
1236         obn->modifiers.first = obn->modifiers.last= NULL;
1237         
1238         for (md=ob->modifiers.first; md; md=md->next) {
1239                 ModifierData *nmd = modifier_new(md->type);
1240                 modifier_copyData(md, nmd);
1241                 BLI_addtail(&obn->modifiers, nmd);
1242         }
1243
1244         obn->prop.first = obn->prop.last = NULL;
1245         copy_properties(&obn->prop, &ob->prop);
1246         
1247         copy_sensors(&obn->sensors, &ob->sensors);
1248         copy_controllers(&obn->controllers, &ob->controllers);
1249         copy_actuators(&obn->actuators, &ob->actuators);
1250         
1251         if(ob->pose) {
1252                 copy_object_pose(obn, ob);
1253                 /* backwards compat... non-armatures can get poses in older files? */
1254                 if(ob->type==OB_ARMATURE)
1255                         armature_rebuild_pose(obn, obn->data);
1256         }
1257         copy_defgroups(&obn->defbase, &ob->defbase);
1258         copy_constraints(&obn->constraints, &ob->constraints);
1259
1260         obn->mode = 0;
1261         obn->sculpt = NULL;
1262
1263         /* increase user numbers */
1264         id_us_plus((ID *)obn->data);
1265         id_us_plus((ID *)obn->dup_group);
1266         // FIXME: add this for animdata too...
1267
1268         for(a=0; a<obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1269         
1270         obn->disp.first= obn->disp.last= NULL;
1271         
1272         if(ob->pd){
1273                 obn->pd= MEM_dupallocN(ob->pd);
1274                 if(obn->pd->tex)
1275                         id_us_plus(&(obn->pd->tex->id));
1276         }
1277         obn->soft= copy_softbody(ob->soft);
1278         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1279
1280         copy_object_particlesystems(obn, ob);
1281         
1282         obn->derivedDeform = NULL;
1283         obn->derivedFinal = NULL;
1284
1285         obn->gpulamp.first = obn->gpulamp.last = NULL;
1286         obn->pc_ids.first = obn->pc_ids.last = NULL;
1287         
1288         return obn;
1289 }
1290
1291 void expand_local_object(Object *ob)
1292 {
1293         //bActionStrip *strip;
1294         ParticleSystem *psys;
1295         int a;
1296
1297 #if 0 // XXX old animation system
1298         id_lib_extern((ID *)ob->action);
1299         id_lib_extern((ID *)ob->ipo);
1300 #endif // XXX old animation system
1301         id_lib_extern((ID *)ob->data);
1302         id_lib_extern((ID *)ob->dup_group);
1303         
1304         for(a=0; a<ob->totcol; a++) {
1305                 id_lib_extern((ID *)ob->mat[a]);
1306         }
1307 #if 0 // XXX old animation system
1308         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1309                 id_lib_extern((ID *)strip->act);
1310         }
1311 #endif // XXX old animation system
1312         for(psys=ob->particlesystem.first; psys; psys=psys->next)
1313                 id_lib_extern((ID *)psys->part);
1314 }
1315
1316 void make_local_object(Object *ob)
1317 {
1318         Object *obn;
1319         Scene *sce;
1320         Base *base;
1321         int local=0, lib=0;
1322
1323         /* - only lib users: do nothing
1324             * - only local users: set flag
1325             * - mixed: make copy
1326             */
1327         
1328         if(ob->id.lib==NULL) return;
1329         
1330         ob->proxy= ob->proxy_from= NULL;
1331         
1332         if(ob->id.us==1) {
1333                 ob->id.lib= NULL;
1334                 ob->id.flag= LIB_LOCAL;
1335                 new_id(0, (ID *)ob, 0);
1336
1337         }
1338         else {
1339                 sce= G.main->scene.first;
1340                 while(sce) {
1341                         base= sce->base.first;
1342                         while(base) {
1343                                 if(base->object==ob) {
1344                                         if(sce->id.lib) lib++;
1345                                         else local++;
1346                                         break;
1347                                 }
1348                                 base= base->next;
1349                         }
1350                         sce= sce->id.next;
1351                 }
1352                 
1353                 if(local && lib==0) {
1354                         ob->id.lib= 0;
1355                         ob->id.flag= LIB_LOCAL;
1356                         new_id(0, (ID *)ob, 0);
1357                 }
1358                 else if(local && lib) {
1359                         obn= copy_object(ob);
1360                         obn->id.us= 0;
1361                         
1362                         sce= G.main->scene.first;
1363                         while(sce) {
1364                                 if(sce->id.lib==0) {
1365                                         base= sce->base.first;
1366                                         while(base) {
1367                                                 if(base->object==ob) {
1368                                                         base->object= obn;
1369                                                         obn->id.us++;
1370                                                         ob->id.us--;
1371                                                 }
1372                                                 base= base->next;
1373                                         }
1374                                 }
1375                                 sce= sce->id.next;
1376                         }
1377                 }
1378         }
1379         
1380         expand_local_object(ob);
1381 }
1382
1383 /*
1384  * Returns true if the Object is a from an external blend file (libdata)
1385  */
1386 int object_is_libdata(Object *ob)
1387 {
1388         if (!ob) return 0;
1389         if (ob->proxy) return 0;
1390         if (ob->id.lib) return 1;
1391         return 0;
1392 }
1393
1394 /* Returns true if the Object data is a from an external blend file (libdata) */
1395 int object_data_is_libdata(Object *ob)
1396 {
1397         if(!ob) return 0;
1398         if(ob->proxy) return 0;
1399         if(ob->id.lib) return 1;
1400         if(!ob->data) return 0;
1401         if(((ID *)ob->data)->lib) return 1;
1402
1403         return 0;
1404 }
1405
1406 /* *************** PROXY **************** */
1407
1408 /* when you make proxy, ensure the exposed layers are extern */
1409 static void armature_set_id_extern(Object *ob)
1410 {
1411         bArmature *arm= ob->data;
1412         bPoseChannel *pchan;
1413         int lay= arm->layer_protected;
1414         
1415         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1416                 if(!(pchan->bone->layer & lay))
1417                         id_lib_extern((ID *)pchan->custom);
1418         }
1419                         
1420 }
1421
1422 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1423 /*             local_object->proxy == pointer to library object, saved in files and read */
1424 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1425
1426 void object_make_proxy(Object *ob, Object *target, Object *gob)
1427 {
1428         /* paranoia checks */
1429         if(ob->id.lib || target->id.lib==NULL) {
1430                 printf("cannot make proxy\n");
1431                 return;
1432         }
1433         
1434         ob->proxy= target;
1435         ob->proxy_group= gob;
1436         id_lib_extern(&target->id);
1437         
1438         ob->recalc= target->recalc= OB_RECALC;
1439         
1440         /* copy transform */
1441         if(gob) {
1442                 VECCOPY(ob->loc, gob->loc);
1443                 VECCOPY(ob->rot, gob->rot);
1444                 VECCOPY(ob->size, gob->size);
1445                 
1446                 group_tag_recalc(gob->dup_group);
1447         }
1448         else {
1449                 VECCOPY(ob->loc, target->loc);
1450                 VECCOPY(ob->rot, target->rot);
1451                 VECCOPY(ob->size, target->size);
1452         }
1453         
1454         ob->parent= target->parent;     /* libdata */
1455         Mat4CpyMat4(ob->parentinv, target->parentinv);
1456         
1457         /* copy animdata stuff - drivers only for now... */
1458         if ((target->adt) && (target->adt->drivers.first)) {
1459                 FCurve *fcu;
1460                 
1461                 /* add new animdata block */
1462                 ob->adt= BKE_id_add_animdata(&ob->id);
1463                 
1464                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1465                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1466                 
1467                 for (fcu= ob->adt->drivers.first; fcu; fcu= fcu->next) {
1468                         ChannelDriver *driver= fcu->driver;
1469                         DriverTarget *dtar;
1470                         
1471                         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
1472                                 if ((Object *)dtar->id == target)
1473                                         dtar->id= (ID *)ob;
1474                                 else
1475                                         id_lib_extern((ID *)dtar->id);
1476                         }
1477                 }
1478         }
1479         
1480         /* skip constraints? */
1481         // FIXME: this is considered by many as a bug
1482         
1483         /* set object type and link to data */
1484         ob->type= target->type;
1485         ob->data= target->data;
1486         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1487         
1488         /* copy material and index information */
1489         ob->actcol= ob->totcol= 0;
1490         if(ob->mat) MEM_freeN(ob->mat);
1491         if(ob->matbits) MEM_freeN(ob->matbits);
1492         ob->mat = NULL;
1493         ob->matbits= NULL;
1494         if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
1495                 int i;
1496                 ob->colbits = target->colbits;
1497                 
1498                 ob->actcol= target->actcol;
1499                 ob->totcol= target->totcol;
1500                 
1501                 ob->mat = MEM_dupallocN(target->mat);
1502                 ob->matbits = MEM_dupallocN(target->matbits);
1503                 for(i=0; i<target->totcol; i++) {
1504                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1505                         id_us_plus((ID *)ob->mat[i]); 
1506                 }
1507         }
1508         
1509         /* type conversions */
1510         if(target->type == OB_ARMATURE) {
1511                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1512                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1513                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1514                 
1515                 armature_set_id_extern(ob);
1516         }
1517         
1518         /* copy drawtype info */
1519         ob->dt= target->dt;
1520 }
1521
1522
1523 /* *************** CALC ****************** */
1524
1525 /* there is also a timing calculation in drawobject() */
1526
1527 float bluroffs= 0.0f, fieldoffs= 0.0f;
1528 int no_speed_curve= 0;
1529
1530 /* ugly calls from render */
1531 void set_mblur_offs(float blur)
1532 {
1533         bluroffs= blur;
1534 }
1535
1536 void set_field_offs(float field)
1537 {
1538         fieldoffs= field;
1539 }
1540
1541 void disable_speed_curve(int val)
1542 {
1543         no_speed_curve= val;
1544 }
1545
1546 // XXX THIS CRUFT NEEDS SERIOUS RECODING ASAP!
1547 /* ob can be NULL */
1548 float bsystem_time(struct Scene *scene, Object *ob, float cfra, float ofs)
1549 {
1550         /* returns float ( see frame_to_float in ipo.c) */
1551         
1552         /* bluroffs and fieldoffs are ugly globals that are set by render */
1553         cfra+= bluroffs+fieldoffs;
1554
1555         /* global time */
1556         if (scene)
1557                 cfra*= scene->r.framelen;       
1558         
1559 #if 0 // XXX old animation system
1560         if (ob) {
1561                 /* ofset frames */
1562                 if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) 
1563                         cfra-= give_timeoffset(ob);
1564         }
1565 #endif // XXX old animation system
1566         
1567         cfra-= ofs;
1568
1569         return cfra;
1570 }
1571
1572 void object_scale_to_mat3(Object *ob, float mat[][3])
1573 {
1574         float vec[3];
1575         
1576         vec[0]= ob->size[0]+ob->dsize[0];
1577         vec[1]= ob->size[1]+ob->dsize[1];
1578         vec[2]= ob->size[2]+ob->dsize[2];
1579         SizeToMat3(vec, mat);
1580 }
1581
1582 // TODO: this should take rotation orders into account later...
1583 void object_rot_to_mat3(Object *ob, float mat[][3])
1584 {
1585         float vec[3];
1586         
1587         vec[0]= ob->rot[0]+ob->drot[0];
1588         vec[1]= ob->rot[1]+ob->drot[1];
1589         vec[2]= ob->rot[2]+ob->drot[2];
1590         EulToMat3(vec, mat);
1591 }
1592
1593 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1594 {
1595         float smat[3][3];
1596         float rmat[3][3];
1597         /*float q1[4];*/
1598         
1599         /* size */
1600         object_scale_to_mat3(ob, smat);
1601
1602         /* rot */
1603         /* Quats arnt used yet */
1604         /*if(ob->transflag & OB_QUAT) {
1605                 QuatMul(q1, ob->quat, ob->dquat);
1606                 QuatToMat3(q1, rmat);
1607         }
1608         else {*/
1609                 object_rot_to_mat3(ob, rmat);
1610         /*}*/
1611         Mat3MulMat3(mat, rmat, smat);
1612 }
1613
1614 void object_to_mat4(Object *ob, float mat[][4])
1615 {
1616         float tmat[3][3];
1617         
1618         object_to_mat3(ob, tmat);
1619         
1620         Mat4CpyMat3(mat, tmat);
1621         
1622         mat[3][0]= ob->loc[0] + ob->dloc[0];
1623         mat[3][1]= ob->loc[1] + ob->dloc[1];
1624         mat[3][2]= ob->loc[2] + ob->dloc[2];
1625 }
1626
1627 int enable_cu_speed= 1;
1628
1629 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1630 {
1631         Curve *cu;
1632         float q[4], vec[4], dir[3], quat[4], radius, x1, ctime;
1633         float timeoffs = 0.0, sf_orig = 0.0;
1634         
1635         Mat4One(mat);
1636         
1637         cu= par->data;
1638         if(cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1639                 makeDispListCurveTypes(scene, par, 0);
1640         if(cu->path==NULL) return;
1641         
1642         /* exception, timeoffset is regarded as distance offset */
1643         if(cu->flag & CU_OFFS_PATHDIST) {
1644                 timeoffs = give_timeoffset(ob);
1645                 SWAP(float, sf_orig, ob->sf);
1646         }
1647         
1648         /* catch exceptions: feature for nla stride editing */
1649         if(ob->ipoflag & OB_DISABLE_PATH) {
1650                 ctime= 0.0f;
1651         }
1652         /* catch exceptions: curve paths used as a duplicator */
1653         else if(enable_cu_speed) {
1654                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1655                  * but this will only work if it actually is animated... 
1656                  *
1657                  * we firstly calculate the modulus of cu->ctime/cu->pathlen to clamp ctime within the 0.0 to 1.0 times pathlen
1658                  * range, then divide this (the modulus) by pathlen to get a value between 0.0 and 1.0
1659                  */
1660                 ctime= fmod(cu->ctime, cu->pathlen) / cu->pathlen;
1661                 CLAMP(ctime, 0.0, 1.0);
1662         }
1663         else {
1664                 ctime= scene->r.cfra - give_timeoffset(ob);
1665                 ctime /= cu->pathlen;
1666                 
1667                 CLAMP(ctime, 0.0, 1.0);
1668         }
1669         
1670         /* time calculus is correct, now apply distance offset */
1671         if(cu->flag & CU_OFFS_PATHDIST) {
1672                 ctime += timeoffs/cu->path->totdist;
1673
1674                 /* restore */
1675                 SWAP(float, sf_orig, ob->sf);
1676         }
1677         
1678         
1679         /* vec: 4 items! */
1680         if( where_on_path(par, ctime, vec, dir, NULL, &radius) ) {
1681
1682                 if(cu->flag & CU_FOLLOW) {
1683                         vectoquat(dir, ob->trackflag, ob->upflag, quat);
1684                         
1685                         /* the tilt */
1686                         Normalize(dir);
1687                         q[0]= (float)cos(0.5*vec[3]);
1688                         x1= (float)sin(0.5*vec[3]);
1689                         q[1]= -x1*dir[0];
1690                         q[2]= -x1*dir[1];
1691                         q[3]= -x1*dir[2];
1692                         QuatMul(quat, q, quat);
1693                         
1694                         QuatToMat4(quat, mat);
1695                 }
1696                 
1697                 if(cu->flag & CU_PATH_RADIUS) {
1698                         float tmat[4][4], rmat[4][4];
1699                         Mat4Scale(tmat, radius);
1700                         Mat4MulMat4(rmat, mat, tmat);
1701                         Mat4CpyMat4(mat, rmat);
1702                 }
1703
1704                 VECCOPY(mat[3], vec);
1705                 
1706         }
1707 }
1708
1709 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1710 {       
1711         bPoseChannel *pchan;
1712         float vec[3];
1713         
1714         if (par->type!=OB_ARMATURE) {
1715                 Mat4One(mat);
1716                 return;
1717         }
1718         
1719         /* Make sure the bone is still valid */
1720         pchan= get_pose_channel(par->pose, ob->parsubstr);
1721         if (!pchan){
1722                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1723                 Mat4One(mat);
1724                 return;
1725         }
1726
1727         /* get bone transform */
1728         Mat4CpyMat4(mat, pchan->pose_mat);
1729
1730         /* but for backwards compatibility, the child has to move to the tail */
1731         VECCOPY(vec, mat[1]);
1732         VecMulf(vec, pchan->bone->length);
1733         VecAddf(mat[3], mat[3], vec);
1734 }
1735
1736 static void give_parvert(Object *par, int nr, float *vec)
1737 {
1738         EditMesh *em;
1739         int a, count;
1740         
1741         vec[0]=vec[1]=vec[2]= 0.0f;
1742         
1743         if(par->type==OB_MESH) {
1744                 Mesh *me= par->data;
1745                 em = BKE_mesh_get_editmesh(me);
1746
1747                 if(em) {
1748                         EditVert *eve;
1749                         
1750                         for(eve= em->verts.first; eve; eve= eve->next) {
1751                                 if(eve->keyindex==nr) {
1752                                         memcpy(vec, eve->co, sizeof(float)*3);
1753                                         break;
1754                                 }
1755                         }
1756                         BKE_mesh_end_editmesh(me, em);
1757                 }
1758                 else {
1759                         DerivedMesh *dm = par->derivedFinal;
1760                         
1761                         if(dm) {
1762                                 int i, count = 0, numVerts = dm->getNumVerts(dm);
1763                                 int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1764                                 float co[3];
1765
1766                                 /* get the average of all verts with (original index == nr) */
1767                                 for(i = 0; i < numVerts; ++i, ++index) {
1768                                         if(*index == nr) {
1769                                                 dm->getVertCo(dm, i, co);
1770                                                 VecAddf(vec, vec, co);
1771                                                 count++;
1772                                         }
1773                                 }
1774
1775                                 if (count==0) {
1776                                         /* keep as 0,0,0 */
1777                                 } else if(count > 0) {
1778                                         VecMulf(vec, 1.0f / count);
1779                                 } else {
1780                                         /* use first index if its out of range */
1781                                         dm->getVertCo(dm, 0, vec);
1782                                 }
1783                         }
1784                 }
1785         }
1786         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1787                 Nurb *nu;
1788                 Curve *cu;
1789                 BPoint *bp;
1790                 BezTriple *bezt;
1791                 int found= 0;
1792                 
1793                 cu= par->data;
1794                 if(cu->editnurb)
1795                         nu= cu->editnurb->first;
1796                 else
1797                         nu= cu->nurb.first;
1798                 
1799                 count= 0;
1800                 while(nu && !found) {
1801                         if(nu->type == CU_BEZIER) {
1802                                 bezt= nu->bezt;
1803                                 a= nu->pntsu;
1804                                 while(a--) {
1805                                         if(count==nr) {
1806                                                 found= 1;
1807                                                 VECCOPY(vec, bezt->vec[1]);
1808                                                 break;
1809                                         }
1810                                         count++;
1811                                         bezt++;
1812                                 }
1813                         }
1814                         else {
1815                                 bp= nu->bp;
1816                                 a= nu->pntsu*nu->pntsv;
1817                                 while(a--) {
1818                                         if(count==nr) {
1819                                                 found= 1;
1820                                                 memcpy(vec, bp->vec, sizeof(float)*3);
1821                                                 break;
1822                                         }
1823                                         count++;
1824                                         bp++;
1825                                 }
1826                         }
1827                         nu= nu->next;
1828                 }
1829
1830         }
1831         else if(par->type==OB_LATTICE) {
1832                 Lattice *latt= par->data;
1833                 BPoint *bp;
1834                 DispList *dl = find_displist(&par->disp, DL_VERTS);
1835                 float *co = dl?dl->verts:NULL;
1836                 
1837                 if(latt->editlatt) latt= latt->editlatt;
1838                 
1839                 a= latt->pntsu*latt->pntsv*latt->pntsw;
1840                 count= 0;
1841                 bp= latt->def;
1842                 while(a--) {
1843                         if(count==nr) {
1844                                 if(co)
1845                                         memcpy(vec, co, 3*sizeof(float));
1846                                 else
1847                                         memcpy(vec, bp->vec, 3*sizeof(float));
1848                                 break;
1849                         }
1850                         count++;
1851                         if(co) co+= 3;
1852                         else bp++;
1853                 }
1854         }
1855 }
1856
1857 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
1858 {
1859         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1860
1861         /* in local ob space */
1862         Mat4One(mat);
1863         
1864         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
1865                 
1866                 give_parvert(par, ob->par1, v1);
1867                 give_parvert(par, ob->par2, v2);
1868                 give_parvert(par, ob->par3, v3);
1869                                 
1870                 triatoquat(v1, v2, v3, q);
1871                 QuatToMat3(q, cmat);
1872                 Mat4CpyMat3(mat, cmat);
1873                 
1874                 if(ob->type==OB_CURVE) {
1875                         VECCOPY(mat[3], v1);
1876                 }
1877                 else {
1878                         VecAddf(mat[3], v1, v2);
1879                         VecAddf(mat[3], mat[3], v3);
1880                         VecMulf(mat[3], 0.3333333f);
1881                 }
1882         }
1883 }
1884
1885 // XXX what the hell is this?
1886 static int no_parent_ipo=0;
1887 void set_no_parent_ipo(int val)
1888 {
1889         no_parent_ipo= val;
1890 }
1891
1892 void where_is_object_time(Scene *scene, Object *ob, float ctime)
1893 {
1894         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
1895         float stime=ctime, fac1, fac2, vec[3];
1896         int a;
1897         int pop; 
1898         
1899         /* new version: correct parent+vertexparent and track+parent */
1900         /* this one only calculates direct attached parent and track */
1901         /* is faster, but should keep track of timeoffs */
1902         
1903         if(ob==NULL) return;
1904         
1905 #if 0 // XXX old animation system
1906         /* this is needed to be able to grab objects with ipos, otherwise it always freezes them */
1907         stime= bsystem_time(scene, ob, ctime, 0.0);
1908         if(stime != ob->ctime) {
1909                 
1910                 ob->ctime= stime;
1911                 
1912                 if(ob->ipo) {
1913                         calc_ipo(ob->ipo, stime);
1914                         execute_ipo((ID *)ob, ob->ipo);
1915                 }
1916                 else 
1917                         do_all_object_actions(scene, ob);
1918                 
1919                 /* do constraint ipos ..., note it needs stime (0 = all ipos) */
1920                 do_constraint_channels(&ob->constraints, &ob->constraintChannels, stime, 0);
1921         }
1922         else {
1923                 /* but, the drivers have to be done */
1924                 if(ob->ipo) do_ob_ipodrivers(ob, ob->ipo, stime);
1925                 /* do constraint ipos ..., note it needs stime (1 = only drivers ipos) */
1926                 do_constraint_channels(&ob->constraints, &ob->constraintChannels, stime, 1);
1927         }
1928 #endif // XXX old animation system
1929
1930         /* execute drivers only, as animation has already been done */
1931         BKE_animsys_evaluate_animdata(&ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
1932         
1933         if(ob->parent) {
1934                 Object *par= ob->parent;
1935                 
1936                 // XXX depreceated - animsys
1937                 if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
1938                 
1939                 /* hurms, code below conflicts with depgraph... (ton) */
1940                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
1941                 pop= 0;
1942                 if(no_parent_ipo==0 && stime != par->ctime) {
1943                         // only for ipo systems? 
1944                         pushdata(par, sizeof(Object));
1945                         pop= 1;
1946                         
1947                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
1948                         else where_is_object_time(scene, par, ctime);
1949                 }
1950                 
1951                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1952                 
1953                 if(pop) {
1954                         poplast(par);
1955                 }
1956                 
1957                 if(ob->partype & PARSLOW) {
1958                         // include framerate
1959                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
1960                         if(fac1 >= 1.0f) return;
1961                         fac2= 1.0f-fac1;
1962                         
1963                         fp1= ob->obmat[0];
1964                         fp2= slowmat[0];
1965                         for(a=0; a<16; a++, fp1++, fp2++) {
1966                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
1967                         }
1968                 }
1969         }
1970         else {
1971                 object_to_mat4(ob, ob->obmat);
1972         }
1973
1974         /* Handle tracking */
1975         if(ob->track) {
1976                 if( ctime != ob->track->ctime) where_is_object_time(scene, ob->track, ctime);
1977                 solve_tracking (ob, ob->track->obmat);
1978         }
1979
1980         /* solve constraints */
1981         if (ob->constraints.first) {
1982                 bConstraintOb *cob;
1983                 
1984                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
1985                 
1986                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
1987                 solve_constraints (&ob->constraints, cob, ctime);
1988                 
1989                 constraints_clear_evalob(cob);
1990         }
1991         
1992         /* set negative scale flag in object */
1993         Crossf(vec, ob->obmat[0], ob->obmat[1]);
1994         if( Inpf(vec, ob->obmat[2]) < 0.0 ) ob->transflag |= OB_NEG_SCALE;
1995         else ob->transflag &= ~OB_NEG_SCALE;
1996 }
1997
1998 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
1999 {
2000         float totmat[4][4];
2001         float tmat[4][4];
2002         float locmat[4][4];
2003         float vec[3];
2004         int ok;
2005         
2006         object_to_mat4(ob, locmat);
2007         
2008         if(ob->partype & PARSLOW) Mat4CpyMat4(slowmat, obmat);
2009
2010         switch(ob->partype & PARTYPE) {
2011         case PAROBJECT:
2012                 ok= 0;
2013                 if(par->type==OB_CURVE) {
2014                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2015                                 ob_parcurve(scene, ob, par, tmat);
2016                                 ok= 1;
2017                         }
2018                 }
2019                 
2020                 if(ok) Mat4MulSerie(totmat, par->obmat, tmat, 
2021                         NULL, NULL, NULL, NULL, NULL, NULL);
2022                 else Mat4CpyMat4(totmat, par->obmat);
2023                 
2024                 break;
2025         case PARBONE:
2026                 ob_parbone(ob, par, tmat);
2027                 Mat4MulSerie(totmat, par->obmat, tmat,         
2028                         NULL, NULL, NULL, NULL, NULL, NULL);
2029                 break;
2030                 
2031         case PARVERT1:
2032                 Mat4One(totmat);
2033                 if (simul){
2034                         VECCOPY(totmat[3], par->obmat[3]);
2035                 }
2036                 else{
2037                         give_parvert(par, ob->par1, vec);
2038                         VecMat4MulVecfl(totmat[3], par->obmat, vec);
2039                 }
2040                 break;
2041         case PARVERT3:
2042                 ob_parvert3(ob, par, tmat);
2043                 
2044                 Mat4MulSerie(totmat, par->obmat, tmat,         
2045                         NULL, NULL, NULL, NULL, NULL, NULL);
2046                 break;
2047                 
2048         case PARSKEL:
2049                 Mat4CpyMat4(totmat, par->obmat);
2050                 break;
2051         }
2052         
2053         // total 
2054         Mat4MulSerie(tmat, totmat, ob->parentinv,         
2055                 NULL, NULL, NULL, NULL, NULL, NULL);
2056         Mat4MulSerie(obmat, tmat, locmat,         
2057                 NULL, NULL, NULL, NULL, NULL, NULL);
2058         
2059         if (simul) {
2060
2061         }
2062         else{
2063                 // external usable originmat 
2064                 Mat3CpyMat4(originmat, tmat);
2065                 
2066                 // origin, voor help line
2067                 if( (ob->partype & 15)==PARSKEL ) {
2068                         VECCOPY(ob->orig, par->obmat[3]);
2069                 }
2070                 else {
2071                         VECCOPY(ob->orig, totmat[3]);
2072                 }
2073         }
2074
2075 }
2076 void solve_tracking (Object *ob, float targetmat[][4])
2077 {
2078         float quat[4];
2079         float vec[3];
2080         float totmat[3][3];
2081         float tmat[4][4];
2082         
2083         VecSubf(vec, ob->obmat[3], targetmat[3]);
2084         vectoquat(vec, ob->trackflag, ob->upflag, quat);
2085         QuatToMat3(quat, totmat);
2086         
2087         if(ob->parent && (ob->transflag & OB_POWERTRACK)) {
2088                 /* 'temporal' : clear parent info */
2089                 object_to_mat4(ob, tmat);
2090                 tmat[0][3]= ob->obmat[0][3];
2091                 tmat[1][3]= ob->obmat[1][3];
2092                 tmat[2][3]= ob->obmat[2][3];
2093                 tmat[3][0]= ob->obmat[3][0];
2094                 tmat[3][1]= ob->obmat[3][1];
2095                 tmat[3][2]= ob->obmat[3][2];
2096                 tmat[3][3]= ob->obmat[3][3];
2097         }
2098         else Mat4CpyMat4(tmat, ob->obmat);
2099         
2100         Mat4MulMat34(ob->obmat, totmat, tmat);
2101
2102 }
2103
2104 void where_is_object(struct Scene *scene, Object *ob)
2105 {
2106         where_is_object_time(scene, ob, (float)scene->r.cfra);
2107 }
2108
2109
2110 void where_is_object_simul(Scene *scene, Object *ob)
2111 /* was written for the old game engine (until 2.04) */
2112 /* It seems that this function is only called
2113 for a lamp that is the child of another object */
2114 {
2115         Object *par;
2116         //Ipo *ipo;
2117         float *fp1, *fp2;
2118         float slowmat[4][4];
2119         float fac1, fac2;
2120         int a;
2121         
2122         /* NO TIMEOFFS */
2123         
2124         /* no ipo! (because of dloc and realtime-ipos) */
2125                 // XXX old animation system
2126         //ipo= ob->ipo;
2127         //ob->ipo= NULL;
2128
2129         if(ob->parent) {
2130                 par= ob->parent;
2131                 
2132                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2133
2134                 if(ob->partype & PARSLOW) {
2135
2136                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2137                         fac2= 1.0f-fac1;
2138                         fp1= ob->obmat[0];
2139                         fp2= slowmat[0];
2140                         for(a=0; a<16; a++, fp1++, fp2++) {
2141                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2142                         }
2143                 }
2144                 
2145         }
2146         else {
2147                 object_to_mat4(ob, ob->obmat);
2148         }
2149         
2150         if(ob->track) 
2151                 solve_tracking(ob, ob->track->obmat);
2152
2153         /* solve constraints */
2154         if (ob->constraints.first) {
2155                 bConstraintOb *cob;
2156                 
2157                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2158                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2159                 constraints_clear_evalob(cob);
2160         }
2161         
2162         /*  WATCH IT!!! */
2163                 // XXX old animation system
2164         //ob->ipo= ipo;
2165 }
2166
2167 /* for calculation of the inverse parent transform, only used for editor */
2168 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2169 {
2170         clear_workob(workob);
2171         
2172         Mat4One(workob->obmat);
2173         Mat4One(workob->parentinv);
2174         Mat4One(workob->constinv);
2175         workob->parent= ob->parent;
2176         workob->track= ob->track;
2177
2178         workob->trackflag= ob->trackflag;
2179         workob->upflag= ob->upflag;
2180         
2181         workob->partype= ob->partype;
2182         workob->par1= ob->par1;
2183         workob->par2= ob->par2;
2184         workob->par3= ob->par3;
2185
2186         workob->constraints.first = ob->constraints.first;
2187         workob->constraints.last = ob->constraints.last;
2188
2189         strcpy(workob->parsubstr, ob->parsubstr); 
2190
2191         where_is_object(scene, workob);
2192 }
2193
2194 BoundBox *unit_boundbox()
2195 {
2196         BoundBox *bb;
2197         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2198
2199         bb= MEM_callocN(sizeof(BoundBox), "bb");
2200         boundbox_set_from_min_max(bb, min, max);
2201         
2202         return bb;
2203 }
2204
2205 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2206 {
2207         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2208         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2209         
2210         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2211         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2212
2213         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2214         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2215 }
2216
2217 BoundBox *object_get_boundbox(Object *ob)
2218 {
2219         BoundBox *bb= NULL;
2220         
2221         if(ob->type==OB_MESH) {
2222                 bb = mesh_get_bb(ob);
2223         }
2224         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2225                 bb= ( (Curve *)ob->data )->bb;
2226         }
2227         else if(ob->type==OB_MBALL) {
2228                 bb= ob->bb;
2229         }
2230         return bb;
2231 }
2232
2233 /* used to temporally disable/enable boundbox */
2234 void object_boundbox_flag(Object *ob, int flag, int set)
2235 {
2236         BoundBox *bb= object_get_boundbox(ob);
2237         if(bb) {
2238                 if(set) bb->flag |= flag;
2239                 else bb->flag &= ~flag;
2240         }
2241 }
2242
2243 void minmax_object(Object *ob, float *min, float *max)
2244 {
2245         BoundBox bb;
2246         Mesh *me;
2247         Curve *cu;
2248         float vec[3];
2249         int a;
2250         
2251         switch(ob->type) {
2252                 
2253         case OB_CURVE:
2254         case OB_FONT:
2255         case OB_SURF:
2256                 cu= ob->data;
2257                 
2258                 if(cu->bb==NULL) tex_space_curve(cu);
2259                 bb= *(cu->bb);
2260                 
2261                 for(a=0; a<8; a++) {
2262                         Mat4MulVecfl(ob->obmat, bb.vec[a]);
2263                         DO_MINMAX(bb.vec[a], min, max);
2264                 }
2265                 break;
2266         case OB_ARMATURE:
2267                 if(ob->pose) {
2268                         bPoseChannel *pchan;
2269                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2270                                 VECCOPY(vec, pchan->pose_head);
2271                                 Mat4MulVecfl(ob->obmat, vec);
2272                                 DO_MINMAX(vec, min, max);
2273                                 VECCOPY(vec, pchan->pose_tail);
2274                                 Mat4MulVecfl(ob->obmat, vec);
2275                                 DO_MINMAX(vec, min, max);
2276                         }
2277                         break;
2278                 }
2279                 /* no break, get_mesh will give NULL and it passes on to default */
2280         case OB_MESH:
2281                 me= get_mesh(ob);
2282                 
2283                 if(me) {
2284                         bb = *mesh_get_bb(ob);
2285                         
2286                         for(a=0; a<8; a++) {
2287                                 Mat4MulVecfl(ob->obmat, bb.vec[a]);
2288                                 DO_MINMAX(bb.vec[a], min, max);
2289                         }
2290                 }
2291                 if(min[0] < max[0] ) break;
2292                 
2293                 /* else here no break!!!, mesh can be zero sized */
2294                 
2295         default:
2296                 DO_MINMAX(ob->obmat[3], min, max);
2297
2298                 VECCOPY(vec, ob->obmat[3]);
2299                 VecAddf(vec, vec, ob->size);
2300                 DO_MINMAX(vec, min, max);
2301
2302                 VECCOPY(vec, ob->obmat[3]);
2303                 VecSubf(vec, vec, ob->size);
2304                 DO_MINMAX(vec, min, max);
2305                 break;
2306         }
2307 }
2308
2309 /* TODO - use dupli objects bounding boxes */
2310 void minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2311 {
2312         if ((ob->transflag & OB_DUPLI)==0) {
2313                 return;
2314         } else {
2315                 ListBase *lb;
2316                 DupliObject *dob;
2317                 
2318                 lb= object_duplilist(scene, ob);
2319                 for(dob= lb->first; dob; dob= dob->next) {
2320                         if(dob->no_draw);
2321                         else {
2322                                 /* should really use bound box of dup object */
2323                                 DO_MINMAX(dob->mat[3], min, max);
2324                         }
2325                 }
2326                 free_object_duplilist(lb);      /* does restore */
2327         }
2328 }
2329
2330
2331 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2332 /*           local_object->proxy      == pointer to library object, saved in files and read */
2333
2334 /* function below is polluted with proxy exceptions, cleanup will follow! */
2335
2336 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2337 /* requires flags to be set! */
2338 void object_handle_update(Scene *scene, Object *ob)
2339 {
2340         if(ob->recalc & OB_RECALC) {
2341                 
2342                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2343                    which is only in where_is_object now */
2344                 if(ob->recalc & OB_RECALC) {
2345                         
2346                         if (G.f & G_DEBUG)
2347                                 printf("recalcob %s\n", ob->id.name+2);
2348                         
2349                         /* handle proxy copy for target */
2350                         if(ob->id.lib && ob->proxy_from) {
2351                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2352                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2353                                         Object *obg= ob->proxy_from->proxy_group;
2354                                         Mat4Invert(obg->imat, obg->obmat);
2355                                         Mat4MulMat4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2356                                 }
2357                                 else
2358                                         Mat4CpyMat4(ob->obmat, ob->proxy_from->obmat);
2359                         }
2360                         else
2361                                 where_is_object(scene, ob);
2362                 }
2363                 
2364                 if(ob->recalc & OB_RECALC_DATA) {
2365                         
2366                         if (G.f & G_DEBUG)
2367                                 printf("recalcdata %s\n", ob->id.name+2);
2368                         
2369                         /* includes all keys and modifiers */
2370                         if(ob->type==OB_MESH) {
2371                                 EditMesh *em = BKE_mesh_get_editmesh(ob->data);
2372
2373                                         // here was vieweditdatamask? XXX
2374                                 if(ob==scene->obedit) {
2375                                         makeDerivedMesh(scene, ob, em, CD_MASK_BAREMESH);
2376                                         BKE_mesh_end_editmesh(ob->data, em);
2377                                 } else
2378                                         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH);
2379                         }
2380                         else if(ob->type==OB_MBALL) {
2381                                 makeDispListMBall(scene, ob);
2382                         } 
2383                         else if(ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2384                                 makeDispListCurveTypes(scene, ob, 0);
2385                         }
2386                         else if(ELEM(ob->type, OB_CAMERA, OB_LAMP)) {
2387                                 ID *data_id= (ID *)ob->data;
2388                                 AnimData *adt= BKE_animdata_from_id(data_id);
2389                                 float ctime= (float)scene->r.cfra; // XXX this is bad...
2390                                 
2391                                 /* evaluate drivers */
2392                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2393                         }
2394                         else if(ob->type==OB_LATTICE) {
2395                                 lattice_calc_modifiers(scene, ob);
2396                         }
2397                         else if(ob->type==OB_ARMATURE) {
2398                                 /* this happens for reading old files and to match library armatures with poses */
2399                                 // XXX this won't screw up the pose set already...
2400                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2401                                         armature_rebuild_pose(ob, ob->data);
2402                                 
2403                                 if(ob->id.lib && ob->proxy_from) {
2404                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2405                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2406                                 }
2407                                 else {
2408                                         where_is_pose(scene, ob);
2409                                 }
2410                         }
2411
2412                         if(ob->particlesystem.first) {
2413                                 ParticleSystem *tpsys, *psys;
2414                                 DerivedMesh *dm;
2415                                 ob->transflag &= ~OB_DUPLIPARTS;
2416                                 
2417                                 psys= ob->particlesystem.first;
2418                                 while(psys) {
2419                                         if(psys_check_enabled(ob, psys)) {
2420                                                 /* check use of dupli objects here */
2421                                                 if(psys->part && psys->part->draw_as == PART_DRAW_REND &&
2422                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2423                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2424                                                         ob->transflag |= OB_DUPLIPARTS;
2425
2426                                                 particle_system_update(scene, ob, psys);
2427                                                 psys= psys->next;
2428                                         }
2429                                         else if(psys->flag & PSYS_DELETE) {
2430                                                 tpsys=psys->next;
2431                                                 BLI_remlink(&ob->particlesystem, psys);
2432                                                 psys_free(ob,psys);
2433                                                 psys= tpsys;
2434                                         }
2435                                         else
2436                                                 psys= psys->next;
2437                                 }
2438
2439                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2440                                         /* this is to make sure we get render level duplis in groups:
2441                                          * the derivedmesh must be created before init_render_mesh,
2442                                          * since object_duplilist does dupliparticles before that */
2443                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2444                                         dm->release(dm);
2445
2446                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2447                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2448                                 }
2449                         }
2450                 }
2451
2452                 /* the no-group proxy case, we call update */
2453                 if(ob->proxy && ob->proxy_group==NULL) {
2454                         /* set pointer in library proxy target, for copying, but restore it */
2455                         ob->proxy->proxy_from= ob;
2456                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2457                         object_handle_update(scene, ob->proxy);
2458                 }
2459         
2460                 ob->recalc &= ~OB_RECALC;
2461         }
2462
2463         /* the case when this is a group proxy, object_update is called in group.c */
2464         if(ob->proxy) {
2465                 ob->proxy->proxy_from= ob;
2466                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2467         }
2468 }
2469
2470 float give_timeoffset(Object *ob) {
2471         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2472                 return ob->sf + give_timeoffset(ob->parent);
2473         } else {
2474                 return ob->sf;
2475         }
2476 }
2477
2478 int give_obdata_texspace(Object *ob, int **texflag, float **loc, float **size, float **rot) {
2479         
2480         if (ob->data==NULL)
2481                 return 0;
2482         
2483         switch (GS(((ID *)ob->data)->name)) {
2484         case ID_ME:
2485         {
2486                 Mesh *me= ob->data;
2487                 if (texflag)    *texflag = &me->texflag;
2488                 if (loc)                *loc = me->loc;
2489                 if (size)               *size = me->size;
2490                 if (rot)                *rot = me->rot;
2491                 break;
2492         }
2493         case ID_CU:
2494         {
2495                 Curve *cu= ob->data;
2496                 if (texflag)    *texflag = &cu->texflag;
2497                 if (loc)                *loc = cu->loc;
2498                 if (size)               *size = cu->size;
2499                 if (rot)                *rot = cu->rot;
2500                 break;
2501         }
2502         case ID_MB:
2503         {
2504                 MetaBall *mb= ob->data;
2505                 if (texflag)    *texflag = &mb->texflag;
2506                 if (loc)                *loc = mb->loc;
2507                 if (size)               *size = mb->size;
2508                 if (rot)                *rot = mb->rot;
2509                 break;
2510         }
2511         default:
2512                 return 0;
2513         }
2514         return 1;
2515 }
2516
2517 /*
2518  * Test a bounding box for ray intersection
2519  * assumes the ray is already local to the boundbox space
2520  */
2521 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2522 {
2523         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2524                                                                                   {3, 2, 6}, {3, 6, 7},
2525                                                                                   {1, 2, 6}, {1, 6, 5}, 
2526                                                                                   {5, 6, 7}, {4, 5, 7},
2527                                                                                   {0, 3, 7}, {0, 4, 7},
2528                                                                                   {0, 1, 5}, {0, 4, 5}};
2529         int result = 0;
2530         int i;
2531         
2532         for (i = 0; i < 12 && result == 0; i++)
2533         {
2534                 float lambda;
2535                 int v1, v2, v3;
2536                 v1 = triangle_indexes[i][0];
2537                 v2 = triangle_indexes[i][1];
2538                 v3 = triangle_indexes[i][2];
2539                 result = RayIntersectsTriangle(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2540         }
2541         
2542         return result;
2543 }
2544
2545 static int pc_cmp(void *a, void *b)
2546 {
2547         LinkData *ad = a, *bd = b;
2548         if(GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2549                 return 1;
2550         else return 0;
2551 }
2552
2553 int object_insert_ptcache(Object *ob) 
2554 {
2555         LinkData *link = NULL;
2556         int i = 0;
2557
2558         BLI_sortlist(&ob->pc_ids, pc_cmp);
2559
2560         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2561         {
2562                 int index = GET_INT_FROM_POINTER(link->data);
2563
2564                 if(i < index)
2565                         break;
2566         }
2567
2568         link = MEM_callocN(sizeof(LinkData), "PCLink");
2569         link->data = SET_INT_IN_POINTER(i);
2570         BLI_addtail(&ob->pc_ids, link);
2571
2572         return i;
2573 }
2574
2575 #if 0
2576 static int pc_findindex(ListBase *listbase, int index)
2577 {
2578         LinkData *link= NULL;
2579         int number= 0;
2580         
2581         if (listbase == NULL) return -1;
2582         
2583         link= listbase->first;
2584         while (link) {
2585                 if ((int)link->data == index)
2586                         return number;
2587                 
2588                 number++;
2589                 link= link->next;
2590         }
2591         
2592         return -1;
2593 }
2594
2595 void object_delete_ptcache(Object *ob, int index) 
2596 {
2597         int list_index = pc_findindex(&ob->pc_ids, index);
2598         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2599         BLI_freelinkN(&ob->pc_ids, link);
2600 }
2601 #endif