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