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