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