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