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