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