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