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