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