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