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