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