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