object_mat3_to_rot wasn't correctly accounting for the euler delta rotations, so...
[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 /** \file blender/blenkernel/intern/object.c
33  *  \ingroup bke
34  */
35
36
37 #include <string.h>
38 #include <math.h>
39 #include <stdio.h>                      
40
41 #include "MEM_guardedalloc.h"
42
43 #include "DNA_anim_types.h"
44 #include "DNA_armature_types.h"
45 #include "DNA_camera_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_group_types.h"
48 #include "DNA_key_types.h"
49 #include "DNA_lamp_types.h"
50 #include "DNA_lattice_types.h"
51 #include "DNA_material_types.h"
52 #include "DNA_meta_types.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_screen_types.h"
56 #include "DNA_sequence_types.h"
57 #include "DNA_space_types.h"
58 #include "DNA_view3d_types.h"
59 #include "DNA_world_types.h"
60
61 #include "BLI_blenlib.h"
62 #include "BLI_editVert.h"
63 #include "BLI_math.h"
64 #include "BLI_pbvh.h"
65 #include "BLI_utildefines.h"
66
67 #include "BKE_main.h"
68 #include "BKE_global.h"
69 #include "BKE_idprop.h"
70 #include "BKE_armature.h"
71 #include "BKE_action.h"
72 #include "BKE_bullet.h"
73 #include "BKE_colortools.h"
74 #include "BKE_deform.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_animsys.h"
77 #include "BKE_anim.h"
78 #include "BKE_constraint.h"
79 #include "BKE_curve.h"
80 #include "BKE_displist.h"
81 #include "BKE_effect.h"
82 #include "BKE_fcurve.h"
83 #include "BKE_group.h"
84 #include "BKE_icons.h"
85 #include "BKE_key.h"
86 #include "BKE_lattice.h"
87 #include "BKE_library.h"
88 #include "BKE_mesh.h"
89 #include "BKE_mball.h"
90 #include "BKE_modifier.h"
91 #include "BKE_object.h"
92 #include "BKE_paint.h"
93 #include "BKE_particle.h"
94 #include "BKE_pointcache.h"
95 #include "BKE_property.h"
96 #include "BKE_sca.h"
97 #include "BKE_scene.h"
98 #include "BKE_sequencer.h"
99 #include "BKE_softbody.h"
100 #include "BKE_material.h"
101
102 #include "LBM_fluidsim.h"
103
104 #ifdef WITH_PYTHON
105 #include "BPY_extern.h"
106 #endif
107
108 #include "GPU_material.h"
109
110 /* Local function protos */
111 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
112
113 float originmat[3][3];  /* after where_is_object(), can be used in other functions (bad!) */
114
115 void clear_workob(Object *workob)
116 {
117         memset(workob, 0, sizeof(Object));
118         
119         workob->size[0]= workob->size[1]= workob->size[2]= 1.0f;
120         workob->rotmode= ROT_MODE_EUL;
121 }
122
123 void copy_baseflags(struct Scene *scene)
124 {
125         Base *base= scene->base.first;
126         
127         while(base) {
128                 base->object->flag= base->flag;
129                 base= base->next;
130         }
131 }
132
133 void copy_objectflags(struct Scene *scene)
134 {
135         Base *base= scene->base.first;
136         
137         while(base) {
138                 base->flag= base->object->flag;
139                 base= base->next;
140         }
141 }
142
143 void update_base_layer(struct Scene *scene, Object *ob)
144 {
145         Base *base= scene->base.first;
146
147         while (base) {
148                 if (base->object == ob) base->lay= ob->lay;
149                 base= base->next;
150         }
151 }
152
153 void object_free_particlesystems(Object *ob)
154 {
155         while(ob->particlesystem.first){
156                 ParticleSystem *psys = ob->particlesystem.first;
157                 
158                 BLI_remlink(&ob->particlesystem,psys);
159                 
160                 psys_free(ob,psys);
161         }
162 }
163
164 void object_free_softbody(Object *ob)
165 {
166         if(ob->soft) {
167                 sbFree(ob->soft);
168                 ob->soft= NULL;
169         }
170 }
171
172 void object_free_bulletsoftbody(Object *ob)
173 {
174         if(ob->bsoft) {
175                 bsbFree(ob->bsoft);
176                 ob->bsoft= NULL;
177         }
178 }
179
180 void object_free_modifiers(Object *ob)
181 {
182         while (ob->modifiers.first) {
183                 ModifierData *md = ob->modifiers.first;
184                 
185                 BLI_remlink(&ob->modifiers, md);
186                 
187                 modifier_free(md);
188         }
189
190         /* particle modifiers were freed, so free the particlesystems as well */
191         object_free_particlesystems(ob);
192
193         /* same for softbody */
194         object_free_softbody(ob);
195 }
196
197 void object_link_modifiers(struct Object *ob, struct Object *from)
198 {
199         ModifierData *md;
200         object_free_modifiers(ob);
201
202         for (md=from->modifiers.first; md; md=md->next) {
203                 ModifierData *nmd = NULL;
204
205                 if(ELEM4(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_ParticleInstance, eModifierType_Collision)) continue;
206
207                 nmd = modifier_new(md->type);
208                 modifier_copyData(md, nmd);
209                 BLI_addtail(&ob->modifiers, nmd);
210         }
211
212         copy_object_particlesystems(ob, from);
213         copy_object_softbody(ob, from);
214
215         // TODO: smoke?, cloth?
216 }
217
218 /* here we will collect all local displist stuff */
219 /* also (ab)used in depsgraph */
220 void object_free_display(Object *ob)
221 {
222         if(ob->derivedDeform) {
223                 ob->derivedDeform->needsFree = 1;
224                 ob->derivedDeform->release(ob->derivedDeform);
225                 ob->derivedDeform= NULL;
226         }
227         if(ob->derivedFinal) {
228                 ob->derivedFinal->needsFree = 1;
229                 ob->derivedFinal->release(ob->derivedFinal);
230                 ob->derivedFinal= NULL;
231         }
232         
233         freedisplist(&ob->disp);
234 }
235
236 void free_sculptsession(Object *ob)
237 {
238         if(ob && ob->sculpt) {
239                 SculptSession *ss = ob->sculpt;
240                 DerivedMesh *dm= ob->derivedFinal;
241
242                 if(ss->pbvh)
243                         BLI_pbvh_free(ss->pbvh);
244                 if(dm && dm->getPBVH)
245                         dm->getPBVH(NULL, dm); /* signal to clear */
246
247                 if(ss->texcache)
248                         MEM_freeN(ss->texcache);
249
250                 if(ss->layer_co)
251                         MEM_freeN(ss->layer_co);
252
253                 if(ss->orig_cos)
254                         MEM_freeN(ss->orig_cos);
255                 if(ss->deform_cos)
256                         MEM_freeN(ss->deform_cos);
257                 if(ss->deform_imats)
258                         MEM_freeN(ss->deform_imats);
259
260                 MEM_freeN(ss);
261
262                 ob->sculpt = NULL;
263         }
264 }
265
266 /* do not free object itself */
267 void free_object(Object *ob)
268 {
269         int a;
270         
271         object_free_display(ob);
272         
273         /* disconnect specific data */
274         if(ob->data) {
275                 ID *id= ob->data;
276                 id->us--;
277                 if(id->us==0) {
278                         if(ob->type==OB_MESH) unlink_mesh(ob->data);
279                         else if(ob->type==OB_CURVE) unlink_curve(ob->data);
280                         else if(ob->type==OB_MBALL) unlink_mball(ob->data);
281                 }
282                 ob->data= NULL;
283         }
284         
285         for(a=0; a<ob->totcol; a++) {
286                 if(ob->mat[a]) ob->mat[a]->id.us--;
287         }
288         if(ob->mat) MEM_freeN(ob->mat);
289         if(ob->matbits) MEM_freeN(ob->matbits);
290         ob->mat= NULL;
291         ob->matbits= NULL;
292         if(ob->bb) MEM_freeN(ob->bb); 
293         ob->bb= NULL;
294         if(ob->path) free_path(ob->path); 
295         ob->path= NULL;
296         if(ob->adt) BKE_free_animdata((ID *)ob);
297         if(ob->poselib) ob->poselib->id.us--;
298         if(ob->gpd) ((ID *)ob->gpd)->us--;
299         if(ob->defbase.first)
300                 BLI_freelistN(&ob->defbase);
301         if(ob->pose)
302                 free_pose(ob->pose);
303         if(ob->mpath)
304                 animviz_free_motionpath(ob->mpath);
305         free_properties(&ob->prop);
306         object_free_modifiers(ob);
307         
308         free_sensors(&ob->sensors);
309         free_controllers(&ob->controllers);
310         free_actuators(&ob->actuators);
311         
312         free_constraints(&ob->constraints);
313         
314         free_partdeflect(ob->pd);
315
316         if(ob->soft) sbFree(ob->soft);
317         if(ob->bsoft) bsbFree(ob->bsoft);
318         if(ob->gpulamp.first) GPU_lamp_free(ob);
319
320         free_sculptsession(ob);
321
322         if(ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
323 }
324
325 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
326 {
327         Object *unlinkOb = userData;
328
329         if (*obpoin==unlinkOb) {
330                 *obpoin = NULL;
331                 ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME; // XXX: should this just be OB_RECALC_DATA?
332         }
333 }
334
335 void unlink_object(Object *ob)
336 {
337         Main *bmain= G.main;
338         Object *obt;
339         Material *mat;
340         World *wrld;
341         bScreen *sc;
342         Scene *sce;
343         Curve *cu;
344         Tex *tex;
345         Group *group;
346         Camera *camera;
347         bConstraint *con;
348         //bActionStrip *strip; // XXX animsys 
349         ModifierData *md;
350         ARegion *ar;
351         RegionView3D *rv3d;
352         int a, found;
353         
354         unlink_controllers(&ob->controllers);
355         unlink_actuators(&ob->actuators);
356         
357         /* check all objects: parents en bevels and fields, also from libraries */
358         // FIXME: need to check all animation blocks (drivers)
359         obt= bmain->object.first;
360         while(obt) {
361                 if(obt->proxy==ob)
362                         obt->proxy= NULL;
363                 if(obt->proxy_from==ob) {
364                         obt->proxy_from= NULL;
365                         obt->recalc |= OB_RECALC_OB;
366                 }
367                 if(obt->proxy_group==ob)
368                         obt->proxy_group= NULL;
369                 
370                 if(obt->parent==ob) {
371                         obt->parent= NULL;
372                         obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
373                 }
374                 
375                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
376                 
377                 if ELEM(obt->type, OB_CURVE, OB_FONT) {
378                         cu= obt->data;
379
380                         if(cu->bevobj==ob) {
381                                 cu->bevobj= NULL;
382                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
383                         }
384                         if(cu->taperobj==ob) {
385                                 cu->taperobj= NULL;
386                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
387                         }
388                         if(cu->textoncurve==ob) {
389                                 cu->textoncurve= NULL;
390                                 obt->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
391                         }
392                 }
393                 else if(obt->type==OB_ARMATURE && obt->pose) {
394                         bPoseChannel *pchan;
395                         for(pchan= obt->pose->chanbase.first; pchan; pchan= pchan->next) {
396                                 for (con = pchan->constraints.first; con; con=con->next) {
397                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
398                                         ListBase targets = {NULL, NULL};
399                                         bConstraintTarget *ct;
400                                         
401                                         if (cti && cti->get_constraint_targets) {
402                                                 cti->get_constraint_targets(con, &targets);
403                                                 
404                                                 for (ct= targets.first; ct; ct= ct->next) {
405                                                         if (ct->tar == ob) {
406                                                                 ct->tar = NULL;
407                                                                 strcpy(ct->subtarget, "");
408                                                                 obt->recalc |= OB_RECALC_DATA;
409                                                         }
410                                                 }
411                                                 
412                                                 if (cti->flush_constraint_targets)
413                                                         cti->flush_constraint_targets(con, &targets, 0);
414                                         }
415                                 }
416                                 if(pchan->custom==ob)
417                                         pchan->custom= NULL;
418                         }
419                 } else if(ELEM(OB_MBALL, ob->type, obt->type)) {
420                         if(is_mball_basis_for(obt, ob))
421                                 obt->recalc|= OB_RECALC_DATA;
422                 }
423                 
424                 sca_remove_ob_poin(obt, ob);
425                 
426                 for (con = obt->constraints.first; con; con=con->next) {
427                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
428                         ListBase targets = {NULL, NULL};
429                         bConstraintTarget *ct;
430                         
431                         if (cti && cti->get_constraint_targets) {
432                                 cti->get_constraint_targets(con, &targets);
433                                 
434                                 for (ct= targets.first; ct; ct= ct->next) {
435                                         if (ct->tar == ob) {
436                                                 ct->tar = NULL;
437                                                 strcpy(ct->subtarget, "");
438                                                 obt->recalc |= OB_RECALC_DATA;
439                                         }
440                                 }
441                                 
442                                 if (cti->flush_constraint_targets)
443                                         cti->flush_constraint_targets(con, &targets, 0);
444                         }
445                 }
446                 
447                 /* object is deflector or field */
448                 if(ob->pd) {
449                         if(obt->soft)
450                                 obt->recalc |= OB_RECALC_DATA;
451
452                         /* cloth */
453                         for(md=obt->modifiers.first; md; md=md->next)
454                                 if(md->type == eModifierType_Cloth)
455                                         obt->recalc |= OB_RECALC_DATA;
456                 }
457                 
458                 /* strips */
459 #if 0 // XXX old animation system
460                 for(strip= obt->nlastrips.first; strip; strip= strip->next) {
461                         if(strip->object==ob)
462                                 strip->object= NULL;
463                         
464                         if(strip->modifiers.first) {
465                                 bActionModifier *amod;
466                                 for(amod= strip->modifiers.first; amod; amod= amod->next)
467                                         if(amod->ob==ob)
468                                                 amod->ob= NULL;
469                         }
470                 }
471 #endif // XXX old animation system
472
473                 /* particle systems */
474                 if(obt->particlesystem.first) {
475                         ParticleSystem *tpsys= obt->particlesystem.first;
476                         for(; tpsys; tpsys=tpsys->next) {
477                                 BoidState *state = NULL;
478                                 BoidRule *rule = NULL;
479
480                                 ParticleTarget *pt = tpsys->targets.first;
481                                 for(; pt; pt=pt->next) {
482                                         if(pt->ob==ob) {
483                                                 pt->ob = NULL;
484                                                 obt->recalc |= OB_RECALC_DATA;
485                                                 break;
486                                         }
487                                 }
488
489                                 if(tpsys->target_ob==ob) {
490                                         tpsys->target_ob= NULL;
491                                         obt->recalc |= OB_RECALC_DATA;
492                                 }
493
494                                 if(tpsys->part->dup_ob==ob)
495                                         tpsys->part->dup_ob= NULL;
496
497                                 if(tpsys->part->phystype==PART_PHYS_BOIDS) {
498                                         ParticleData *pa;
499                                         BoidParticle *bpa;
500                                         int p;
501
502                                         for(p=0,pa=tpsys->particles; p<tpsys->totpart; p++,pa++) {
503                                                 bpa = pa->boid;
504                                                 if(bpa->ground == ob)
505                                                         bpa->ground = NULL;
506                                         }
507                                 }
508                                 if(tpsys->part->boids) {
509                                         for(state = tpsys->part->boids->states.first; state; state=state->next) {
510                                                 for(rule = state->rules.first; rule; rule=rule->next) {
511                                                         if(rule->type==eBoidRuleType_Avoid) {
512                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*)rule;
513                                                                 if(gabr->ob==ob)
514                                                                         gabr->ob= NULL;
515                                                         }
516                                                         else if(rule->type==eBoidRuleType_FollowLeader) {
517                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*)rule;
518                                                                 if(flbr->ob==ob)
519                                                                         flbr->ob= NULL;
520                                                         }
521                                                 }
522                                         }
523                                 }
524                         }
525                         if(ob->pd)
526                                 obt->recalc |= OB_RECALC_DATA;
527                 }
528
529                 obt= obt->id.next;
530         }
531         
532         /* materials */
533         mat= bmain->mat.first;
534         while(mat) {
535         
536                 for(a=0; a<MAX_MTEX; a++) {
537                         if(mat->mtex[a] && ob==mat->mtex[a]->object) {
538                                 /* actually, test for lib here... to do */
539                                 mat->mtex[a]->object= NULL;
540                         }
541                 }
542
543                 mat= mat->id.next;
544         }
545         
546         /* textures */
547         for(tex= bmain->tex.first; tex; tex= tex->id.next) {
548                 if(tex->env && (ob==tex->env->object)) tex->env->object= NULL;
549                 if(tex->pd  && (ob==tex->pd->object))  tex->pd->object= NULL;
550                 if(tex->vd  && (ob==tex->vd->object))  tex->vd->object= NULL;
551         }
552
553         /* worlds */
554         wrld= bmain->world.first;
555         while(wrld) {
556                 if(wrld->id.lib==NULL) {
557                         for(a=0; a<MAX_MTEX; a++) {
558                                 if(wrld->mtex[a] && ob==wrld->mtex[a]->object)
559                                         wrld->mtex[a]->object= NULL;
560                         }
561                 }
562                 
563                 wrld= wrld->id.next;
564         }
565                 
566         /* scenes */
567         sce= bmain->scene.first;
568         while(sce) {
569                 if(sce->id.lib==NULL) {
570                         if(sce->camera==ob) sce->camera= NULL;
571                         if(sce->toolsettings->skgen_template==ob) sce->toolsettings->skgen_template = NULL;
572                         if(sce->toolsettings->particle.object==ob) sce->toolsettings->particle.object= NULL;
573
574 #ifdef DURIAN_CAMERA_SWITCH
575                         {
576                                 TimeMarker *m;
577
578                                 for (m= sce->markers.first; m; m= m->next) {
579                                         if(m->camera==ob)
580                                                 m->camera= NULL;
581                                 }
582                         }
583 #endif
584                         if(sce->ed) {
585                                 Sequence *seq;
586                                 SEQ_BEGIN(sce->ed, seq)
587                                         if(seq->scene_camera==ob) {
588                                                 seq->scene_camera= NULL;
589                                         }
590                                 SEQ_END
591                         }
592                 }
593
594                 sce= sce->id.next;
595         }
596         
597 #if 0 // XXX old animation system
598         /* ipos */
599         ipo= bmain->ipo.first;
600         while(ipo) {
601                 if(ipo->id.lib==NULL) {
602                         IpoCurve *icu;
603                         for(icu= ipo->curve.first; icu; icu= icu->next) {
604                                 if(icu->driver && icu->driver->ob==ob)
605                                         icu->driver->ob= NULL;
606                         }
607                 }
608                 ipo= ipo->id.next;
609         }
610 #endif // XXX old animation system
611         
612         /* screens */
613         sc= bmain->screen.first;
614         while(sc) {
615                 ScrArea *sa= sc->areabase.first;
616                 while(sa) {
617                         SpaceLink *sl;
618
619                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
620                                 if(sl->spacetype==SPACE_VIEW3D) {
621                                         View3D *v3d= (View3D*) sl;
622
623                                         found= 0;
624                                         if(v3d->camera==ob) {
625                                                 v3d->camera= NULL;
626                                                 found= 1;
627                                         }
628                                         if(v3d->localvd && v3d->localvd->camera==ob ) {
629                                                 v3d->localvd->camera= NULL;
630                                                 found += 2;
631                                         }
632
633                                         if (found) {
634                                                 if (sa->spacetype == SPACE_VIEW3D) {
635                                                         for (ar= sa->regionbase.first; ar; ar= ar->next) {
636                                                                 if (ar->regiontype==RGN_TYPE_WINDOW) {
637                                                                         rv3d= (RegionView3D *)ar->regiondata;
638                                                                         if (found == 1 || found == 3) {
639                                                                                 if (rv3d->persp == RV3D_CAMOB)
640                                                                                         rv3d->persp= RV3D_PERSP;
641                                                                         }
642                                                                         if (found == 2 || found == 3) {
643                                                                                 if (rv3d->localvd && rv3d->localvd->persp == RV3D_CAMOB)
644                                                                                         rv3d->localvd->persp= RV3D_PERSP;
645                                                                         }
646                                                                 }
647                                                         }
648                                                 }
649                                         }
650                                 }
651                                 else if(sl->spacetype==SPACE_OUTLINER) {
652                                         SpaceOops *so= (SpaceOops *)sl;
653
654                                         if(so->treestore) {
655                                                 TreeStoreElem *tselem= so->treestore->data;
656                                                 int a;
657                                                 for(a=0; a<so->treestore->usedelem; a++, tselem++) {
658                                                         if(tselem->id==(ID *)ob) tselem->id= NULL;
659                                                 }
660                                         }
661                                 }
662                                 else if(sl->spacetype==SPACE_BUTS) {
663                                         SpaceButs *sbuts= (SpaceButs *)sl;
664
665                                         if(sbuts->pinid==(ID *)ob) {
666                                                 sbuts->flag&= ~SB_PIN_CONTEXT;
667                                                 sbuts->pinid= NULL;
668                                         }
669                                 }
670                         }
671
672                         sa= sa->next;
673                 }
674                 sc= sc->id.next;
675         }
676
677         /* groups */
678         group= bmain->group.first;
679         while(group) {
680                 rem_from_group(group, ob, NULL, NULL);
681                 group= group->id.next;
682         }
683         
684         /* cameras */
685         camera= bmain->camera.first;
686         while(camera) {
687                 if (camera->dof_ob==ob) {
688                         camera->dof_ob = NULL;
689                 }
690                 camera= camera->id.next;
691         }
692 }
693
694 int exist_object(Object *obtest)
695 {
696         Object *ob;
697         
698         if(obtest==NULL) return 0;
699         
700         ob= G.main->object.first;
701         while(ob) {
702                 if(ob==obtest) return 1;
703                 ob= ob->id.next;
704         }
705         return 0;
706 }
707
708 void *add_camera(const char *name)
709 {
710         Camera *cam;
711         
712         cam=  alloc_libblock(&G.main->camera, ID_CA, name);
713
714         cam->lens= 35.0f;
715         cam->clipsta= 0.1f;
716         cam->clipend= 100.0f;
717         cam->drawsize= 0.5f;
718         cam->ortho_scale= 6.0;
719         cam->flag |= CAM_SHOWPASSEPARTOUT;
720         cam->passepartalpha = 0.5f;
721         
722         return cam;
723 }
724
725 Camera *copy_camera(Camera *cam)
726 {
727         Camera *camn;
728         
729         camn= copy_libblock(cam);
730         
731         return camn;
732 }
733
734
735
736 void make_local_camera(Camera *cam)
737 {
738         Main *bmain= G.main;
739         Object *ob;
740         int local=0, lib=0;
741
742         /* - only lib users: do nothing
743          * - only local users: set flag
744          * - mixed: make copy
745          */
746         
747         if(cam->id.lib==NULL) return;
748         if(cam->id.us==1) {
749                 cam->id.lib= NULL;
750                 cam->id.flag= LIB_LOCAL;
751                 new_id(&bmain->camera, (ID *)cam, NULL);
752                 return;
753         }
754         
755         for(ob= bmain->object.first; ob && ELEM(0, lib, local); ob= ob->id.next) {
756                 if(ob->data==cam) {
757                         if(ob->id.lib) lib= 1;
758                         else local= 1;
759                 }
760         }
761         
762         if(local && lib==0) {
763                 cam->id.lib= NULL;
764                 cam->id.flag= LIB_LOCAL;
765                 new_id(&bmain->camera, (ID *)cam, NULL);
766         }
767         else if(local && lib) {
768                 Camera *camn= copy_camera(cam);
769                 camn->id.us= 0;
770                 
771                 for(ob= bmain->object.first; ob; ob= ob->id.next) {
772                         if(ob->data == cam) {
773                                 if(ob->id.lib==NULL) {
774                                         ob->data= camn;
775                                         camn->id.us++;
776                                         cam->id.us--;
777                                 }
778                         }
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(&bmain->lamp, (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(&bmain->lamp, (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 static void extern_local_object(Object *ob)
1365 {
1366         //bActionStrip *strip;
1367         ParticleSystem *psys;
1368
1369 #if 0 // XXX old animation system
1370         id_lib_extern((ID *)ob->action);
1371         id_lib_extern((ID *)ob->ipo);
1372 #endif // XXX old animation system
1373         id_lib_extern((ID *)ob->data);
1374         id_lib_extern((ID *)ob->dup_group);
1375         id_lib_extern((ID *)ob->poselib);
1376         id_lib_extern((ID *)ob->gpd);
1377
1378         extern_local_matarar(ob->mat, ob->totcol);
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         Scene *sce;
1393         Base *base;
1394         int local=0, lib=0;
1395
1396         /* - only lib users: do nothing
1397          * - only local users: set flag
1398          * - mixed: make copy
1399          */
1400
1401         if(ob->id.lib==NULL) return;
1402         
1403         ob->proxy= ob->proxy_from= NULL;
1404         
1405         if(ob->id.us==1) {
1406                 ob->id.lib= NULL;
1407                 ob->id.flag= LIB_LOCAL;
1408                 new_id(&bmain->object, (ID *)ob, NULL);
1409         }
1410         else {
1411                 for(sce= bmain->scene.first; sce && ELEM(0, lib, local); sce= sce->id.next) {
1412                         if(object_in_scene(ob, sce)) {
1413                                 if(sce->id.lib) lib= 1;
1414                                 else local= 1;
1415                         }
1416                 }
1417
1418                 if(local && lib==0) {
1419                         ob->id.lib= NULL;
1420                         ob->id.flag= LIB_LOCAL;
1421                         new_id(&bmain->object, (ID *)ob, NULL);
1422                 }
1423                 else if(local && lib) {
1424                         Object *obn= copy_object(ob);
1425                         obn->id.us= 0;
1426                         
1427                         sce= bmain->scene.first;
1428                         while(sce) {
1429                                 if(sce->id.lib==NULL) {
1430                                         base= sce->base.first;
1431                                         while(base) {
1432                                                 if(base->object==ob) {
1433                                                         base->object= obn;
1434                                                         obn->id.us++;
1435                                                         ob->id.us--;
1436                                                 }
1437                                                 base= base->next;
1438                                         }
1439                                 }
1440                                 sce= sce->id.next;
1441                         }
1442                 }
1443         }
1444         
1445         extern_local_object(ob);
1446 }
1447
1448 /*
1449  * Returns true if the Object is a from an external blend file (libdata)
1450  */
1451 int object_is_libdata(Object *ob)
1452 {
1453         if (!ob) return 0;
1454         if (ob->proxy) return 0;
1455         if (ob->id.lib) return 1;
1456         return 0;
1457 }
1458
1459 /* Returns true if the Object data is a from an external blend file (libdata) */
1460 int object_data_is_libdata(Object *ob)
1461 {
1462         if(!ob) return 0;
1463         if(ob->proxy && (ob->data==NULL || ((ID *)ob->data)->lib==NULL)) return 0;
1464         if(ob->id.lib) return 1;
1465         if(ob->data==NULL) return 0;
1466         if(((ID *)ob->data)->lib) return 1;
1467
1468         return 0;
1469 }
1470
1471 /* *************** PROXY **************** */
1472
1473 /* when you make proxy, ensure the exposed layers are extern */
1474 static void armature_set_id_extern(Object *ob)
1475 {
1476         bArmature *arm= ob->data;
1477         bPoseChannel *pchan;
1478         unsigned int lay= arm->layer_protected;
1479         
1480         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1481                 if(!(pchan->bone->layer & lay))
1482                         id_lib_extern((ID *)pchan->custom);
1483         }
1484                         
1485 }
1486
1487 void object_copy_proxy_drivers(Object *ob, Object *target)
1488 {
1489         if ((target->adt) && (target->adt->drivers.first)) {
1490                 FCurve *fcu;
1491                 
1492                 /* add new animdata block */
1493                 if(!ob->adt)
1494                         ob->adt= BKE_id_add_animdata(&ob->id);
1495                 
1496                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1497                 free_fcurves(&ob->adt->drivers);
1498                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1499                 
1500                 for (fcu= ob->adt->drivers.first; fcu; fcu= fcu->next) {
1501                         ChannelDriver *driver= fcu->driver;
1502                         DriverVar *dvar;
1503                         
1504                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1505                                 /* all drivers */
1506                                 DRIVER_TARGETS_LOOPER(dvar) 
1507                                 {
1508                                         if(dtar->id) {
1509                                                 if ((Object *)dtar->id == target)
1510                                                         dtar->id= (ID *)ob;
1511                                                 else {
1512                                                         /* only on local objects because this causes indirect links a -> b -> c,blend to point directly to a.blend
1513                                                          * when a.blend has a proxy thats linked into c.blend  */
1514                                                         if(ob->id.lib==NULL)
1515                                                                 id_lib_extern((ID *)dtar->id);
1516                                                 }
1517                                         }
1518                                 }
1519                                 DRIVER_TARGETS_LOOPER_END
1520                         }
1521                 }
1522         }
1523 }
1524
1525 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1526 /*             local_object->proxy == pointer to library object, saved in files and read */
1527 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1528
1529 void object_make_proxy(Object *ob, Object *target, Object *gob)
1530 {
1531         /* paranoia checks */
1532         if(ob->id.lib || target->id.lib==NULL) {
1533                 printf("cannot make proxy\n");
1534                 return;
1535         }
1536         
1537         ob->proxy= target;
1538         ob->proxy_group= gob;
1539         id_lib_extern(&target->id);
1540         
1541         ob->recalc= target->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
1542         
1543         /* copy transform
1544          * - gob means this proxy comes from a group, just apply the matrix
1545          *   so the object wont move from its dupli-transform.
1546          *
1547          * - no gob means this is being made from a linked object,
1548          *   this is closer to making a copy of the object - in-place. */
1549         if(gob) {
1550                 ob->rotmode= target->rotmode;
1551                 mul_m4_m4m4(ob->obmat, target->obmat, gob->obmat);
1552                 if(gob->dup_group) { /* should always be true */
1553                         float tvec[3];
1554                         copy_v3_v3(tvec, gob->dup_group->dupli_ofs);
1555                         mul_mat3_m4_v3(ob->obmat, tvec);
1556                         sub_v3_v3(ob->obmat[3], tvec);
1557                 }
1558                 object_apply_mat4(ob, ob->obmat, FALSE, TRUE);
1559         }
1560         else {
1561                 copy_object_transform(ob, target);
1562                 ob->parent= target->parent;     /* libdata */
1563                 copy_m4_m4(ob->parentinv, target->parentinv);
1564         }
1565         
1566         /* copy animdata stuff - drivers only for now... */
1567         object_copy_proxy_drivers(ob, target);
1568
1569         /* skip constraints? */
1570         // FIXME: this is considered by many as a bug
1571         
1572         /* set object type and link to data */
1573         ob->type= target->type;
1574         ob->data= target->data;
1575         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1576         
1577         /* copy material and index information */
1578         ob->actcol= ob->totcol= 0;
1579         if(ob->mat) MEM_freeN(ob->mat);
1580         if(ob->matbits) MEM_freeN(ob->matbits);
1581         ob->mat = NULL;
1582         ob->matbits= NULL;
1583         if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
1584                 int i;
1585                 ob->colbits = target->colbits;
1586                 
1587                 ob->actcol= target->actcol;
1588                 ob->totcol= target->totcol;
1589                 
1590                 ob->mat = MEM_dupallocN(target->mat);
1591                 ob->matbits = MEM_dupallocN(target->matbits);
1592                 for(i=0; i<target->totcol; i++) {
1593                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1594                         id_us_plus((ID *)ob->mat[i]); 
1595                 }
1596         }
1597         
1598         /* type conversions */
1599         if(target->type == OB_ARMATURE) {
1600                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1601                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1602                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1603                 
1604                 armature_set_id_extern(ob);
1605         }
1606         else if (target->type == OB_EMPTY) {
1607                 ob->empty_drawtype = target->empty_drawtype;
1608                 ob->empty_drawsize = target->empty_drawsize;
1609         }
1610
1611         /* copy IDProperties */
1612         if(ob->id.properties) {
1613                 IDP_FreeProperty(ob->id.properties);
1614                 MEM_freeN(ob->id.properties);
1615                 ob->id.properties= NULL;
1616         }
1617         if(target->id.properties) {
1618                 ob->id.properties= IDP_CopyProperty(target->id.properties);
1619         }
1620
1621         /* copy drawtype info */
1622         ob->dt= target->dt;
1623 }
1624
1625
1626 /* *************** CALC ****************** */
1627
1628 /* there is also a timing calculation in drawobject() */
1629
1630 static int no_speed_curve= 0;
1631
1632 void disable_speed_curve(int val)
1633 {
1634         no_speed_curve= val;
1635 }
1636
1637 // XXX THIS CRUFT NEEDS SERIOUS RECODING ASAP!
1638 /* ob can be NULL */
1639 float bsystem_time(struct Scene *scene, Object *UNUSED(ob), float cfra, float ofs)
1640 {
1641         /* returns float ( see BKE_curframe in scene.c) */
1642         cfra += scene->r.subframe;
1643         
1644         /* global time */
1645         if (scene)
1646                 cfra*= scene->r.framelen;       
1647         
1648 #if 0 // XXX old animation system
1649         if (ob) {
1650                 /* ofset frames */
1651                 if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) 
1652                         cfra-= give_timeoffset(ob);
1653         }
1654 #endif // XXX old animation system
1655         
1656         cfra-= ofs;
1657
1658         return cfra;
1659 }
1660
1661 void object_scale_to_mat3(Object *ob, float mat[][3])
1662 {
1663         float vec[3];
1664         add_v3_v3v3(vec, ob->size, ob->dsize);
1665         size_to_mat3( mat,vec);
1666 }
1667
1668
1669 void object_rot_to_mat3(Object *ob, float mat[][3])
1670 {
1671         float rmat[3][3], dmat[3][3];
1672         
1673         /* initialise the delta-rotation matrix, which will get (pre)multiplied 
1674          * with the rotation matrix to yield the appropriate rotation
1675          */
1676         unit_m3(dmat);
1677         
1678         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1679         if (ob->rotmode > 0) {
1680                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1681                 eulO_to_mat3( rmat,ob->rot, ob->rotmode);
1682                 eulO_to_mat3( dmat,ob->drot, ob->rotmode);
1683         }
1684         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1685                 /* axis-angle -  not really that great for 3D-changing orientations */
1686                 axis_angle_to_mat3( rmat,ob->rotAxis, ob->rotAngle);
1687                 axis_angle_to_mat3( dmat,ob->drotAxis, ob->drotAngle);
1688         }
1689         else {
1690                 /* quats are normalised before use to eliminate scaling issues */
1691                 float tquat[4];
1692                 
1693                 normalize_qt_qt(tquat, ob->quat);
1694                 quat_to_mat3(rmat, tquat);
1695                 
1696                 normalize_qt_qt(tquat, ob->dquat);
1697                 quat_to_mat3(dmat, tquat);
1698         }
1699         
1700         /* combine these rotations */
1701         mul_m3_m3m3(mat, dmat, rmat);
1702 }
1703
1704 void object_mat3_to_rot(Object *ob, float mat[][3], short use_compat)
1705 {
1706         switch(ob->rotmode) {
1707         case ROT_MODE_QUAT:
1708                 {
1709                         float dquat[4];
1710                         mat3_to_quat(ob->quat, mat);
1711                         normalize_qt_qt(dquat, ob->dquat);
1712                         invert_qt(dquat);
1713                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1714                 }
1715                 break;
1716         case ROT_MODE_AXISANGLE:
1717                 mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1718                 sub_v3_v3(ob->rotAxis, ob->drotAxis);
1719                 ob->rotAngle -= ob->drotAngle;
1720                 break;
1721         default: /* euler */
1722                 {
1723                         float quat[4];
1724                         float dquat[4];
1725                         float tmat[3][3];
1726
1727                         /* without drot we could apply 'mat' directly */
1728                         mat3_to_quat(quat, mat);
1729                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1730                         invert_qt(dquat);
1731                         mul_qt_qtqt(quat, dquat, quat);
1732                         quat_to_mat3(tmat, quat);
1733                         /* end drot correction */
1734
1735                         if(use_compat)  mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1736                         else                    mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1737                 }
1738         }
1739 }
1740
1741 /* see pchan_apply_mat4() for the equivalent 'pchan' function */
1742 void object_apply_mat4(Object *ob, float mat[][4], const short use_compat, const short use_parent)
1743 {
1744         float rot[3][3];
1745
1746         if(use_parent && ob->parent) {
1747                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1748                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
1749                 invert_m4_m4(imat, diff_mat);
1750                 mul_m4_m4m4(rmat, mat, imat); /* get the parent relative matrix */
1751                 object_apply_mat4(ob, rmat, use_compat, FALSE);
1752                 
1753                 /* same as below, use rmat rather then mat */
1754                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1755                 object_mat3_to_rot(ob, rot, use_compat);
1756         }
1757         else {
1758                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1759                 object_mat3_to_rot(ob, rot, use_compat);
1760         }
1761         
1762         sub_v3_v3(ob->loc, ob->dloc);
1763         sub_v3_v3(ob->size, ob->dsize);
1764         /* object_mat3_to_rot handles delta rotations */
1765 }
1766
1767 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1768 {
1769         float smat[3][3];
1770         float rmat[3][3];
1771         /*float q1[4];*/
1772         
1773         /* size */
1774         object_scale_to_mat3(ob, smat);
1775
1776         /* rot */
1777         object_rot_to_mat3(ob, rmat);
1778         mul_m3_m3m3(mat, rmat, smat);
1779 }
1780
1781 void object_to_mat4(Object *ob, float mat[][4])
1782 {
1783         float tmat[3][3];
1784         
1785         object_to_mat3(ob, tmat);
1786         
1787         copy_m4_m3(mat, tmat);
1788
1789         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1790 }
1791
1792 /* extern */
1793 int enable_cu_speed= 1;
1794
1795 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1796 {
1797         Curve *cu;
1798         float vec[4], dir[3], quat[4], radius, ctime;
1799         float timeoffs = 0.0, sf_orig = 0.0;
1800         
1801         unit_m4(mat);
1802         
1803         cu= par->data;
1804         if(cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1805                 makeDispListCurveTypes(scene, par, 0);
1806         if(cu->path==NULL) return;
1807         
1808         /* exception, timeoffset is regarded as distance offset */
1809         if(cu->flag & CU_OFFS_PATHDIST) {
1810                 timeoffs = give_timeoffset(ob);
1811                 SWAP(float, sf_orig, ob->sf);
1812         }
1813         
1814         /* catch exceptions: feature for nla stride editing */
1815         if(ob->ipoflag & OB_DISABLE_PATH) {
1816                 ctime= 0.0f;
1817         }
1818         /* catch exceptions: curve paths used as a duplicator */
1819         else if(enable_cu_speed) {
1820                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1821                  * but this will only work if it actually is animated... 
1822                  *
1823                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1824                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1825                  */
1826                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1827                         ctime= cu->ctime / cu->pathlen;
1828                 else
1829                         ctime= cu->ctime;
1830
1831                 CLAMP(ctime, 0.0f, 1.0f);
1832         }
1833         else {
1834                 ctime= scene->r.cfra - give_timeoffset(ob);
1835                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1836                         ctime /= cu->pathlen;
1837                 
1838                 CLAMP(ctime, 0.0f, 1.0f);
1839         }
1840         
1841         /* time calculus is correct, now apply distance offset */
1842         if(cu->flag & CU_OFFS_PATHDIST) {
1843                 ctime += timeoffs/cu->path->totdist;
1844
1845                 /* restore */
1846                 SWAP(float, sf_orig, ob->sf);
1847         }
1848         
1849         
1850         /* vec: 4 items! */
1851         if( where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat:NULL, &radius, NULL) ) {
1852
1853                 if(cu->flag & CU_FOLLOW) {
1854 #if 0
1855                         float x1, q[4];
1856                         vec_to_quat( quat,dir, ob->trackflag, ob->upflag);
1857                         
1858                         /* the tilt */
1859                         normalize_v3(dir);
1860                         q[0]= (float)cos(0.5*vec[3]);
1861                         x1= (float)sin(0.5*vec[3]);
1862                         q[1]= -x1*dir[0];
1863                         q[2]= -x1*dir[1];
1864                         q[3]= -x1*dir[2];
1865                         mul_qt_qtqt(quat, q, quat);
1866 #else
1867                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1868 #endif
1869                         normalize_qt(quat);
1870                         quat_to_mat4(mat, quat);
1871                 }
1872                 
1873                 if(cu->flag & CU_PATH_RADIUS) {
1874                         float tmat[4][4], rmat[4][4];
1875                         scale_m4_fl(tmat, radius);
1876                         mul_m4_m4m4(rmat, mat, tmat);
1877                         copy_m4_m4(mat, rmat);
1878                 }
1879
1880                 copy_v3_v3(mat[3], vec);
1881                 
1882         }
1883 }
1884
1885 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1886 {       
1887         bPoseChannel *pchan;
1888         float vec[3];
1889         
1890         if (par->type!=OB_ARMATURE) {
1891                 unit_m4(mat);
1892                 return;
1893         }
1894         
1895         /* Make sure the bone is still valid */
1896         pchan= get_pose_channel(par->pose, ob->parsubstr);
1897         if (!pchan){
1898                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1899                 unit_m4(mat);
1900                 return;
1901         }
1902
1903         /* get bone transform */
1904         copy_m4_m4(mat, pchan->pose_mat);
1905
1906         /* but for backwards compatibility, the child has to move to the tail */
1907         copy_v3_v3(vec, mat[1]);
1908         mul_v3_fl(vec, pchan->bone->length);
1909         add_v3_v3(mat[3], vec);
1910 }
1911
1912 static void give_parvert(Object *par, int nr, float *vec)
1913 {
1914         EditMesh *em;
1915         int a, count;
1916         
1917         vec[0]=vec[1]=vec[2]= 0.0f;
1918         
1919         if(par->type==OB_MESH) {
1920                 Mesh *me= par->data;
1921                 DerivedMesh *dm;
1922
1923                 em = BKE_mesh_get_editmesh(me);
1924                 dm = (em)? em->derivedFinal: par->derivedFinal;
1925                         
1926                 if(dm) {
1927                         MVert *mvert= dm->getVertArray(dm);
1928                         int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1929                         int i, vindex, numVerts = dm->getNumVerts(dm);
1930
1931                         /* get the average of all verts with (original index == nr) */
1932                         count= 0;
1933                         for(i = 0; i < numVerts; i++) {
1934                                 vindex= (index)? index[i]: i;
1935
1936                                 if(vindex == nr) {
1937                                         add_v3_v3(vec, mvert[i].co);
1938                                         count++;
1939                                 }
1940                         }
1941
1942                         if (count==0) {
1943                                 /* keep as 0,0,0 */
1944                         } else if(count > 0) {
1945                                 mul_v3_fl(vec, 1.0f / count);
1946                         } else {
1947                                 /* use first index if its out of range */
1948                                 dm->getVertCo(dm, 0, vec);
1949                         }
1950                 }
1951
1952                 if(em)
1953                         BKE_mesh_end_editmesh(me, em);
1954         }
1955         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1956                 Nurb *nu;
1957                 Curve *cu;
1958                 BPoint *bp;
1959                 BezTriple *bezt;
1960                 int found= 0;
1961                 ListBase *nurbs;
1962
1963                 cu= par->data;
1964                 nurbs= BKE_curve_nurbs(cu);
1965                 nu= nurbs->first;
1966
1967                 count= 0;
1968                 while(nu && !found) {
1969                         if(nu->type == CU_BEZIER) {
1970                                 bezt= nu->bezt;
1971                                 a= nu->pntsu;
1972                                 while(a--) {
1973                                         if(count==nr) {
1974                                                 found= 1;
1975                                                 VECCOPY(vec, bezt->vec[1]);
1976                                                 break;
1977                                         }
1978                                         count++;
1979                                         bezt++;
1980                                 }
1981                         }
1982                         else {
1983                                 bp= nu->bp;
1984                                 a= nu->pntsu*nu->pntsv;
1985                                 while(a--) {
1986                                         if(count==nr) {
1987                                                 found= 1;
1988                                                 memcpy(vec, bp->vec, sizeof(float)*3);
1989                                                 break;
1990                                         }
1991                                         count++;
1992                                         bp++;
1993                                 }
1994                         }
1995                         nu= nu->next;
1996                 }
1997
1998         }
1999         else if(par->type==OB_LATTICE) {
2000                 Lattice *latt= par->data;
2001                 BPoint *bp;
2002                 DispList *dl = find_displist(&par->disp, DL_VERTS);
2003                 float *co = dl?dl->verts:NULL;
2004                 
2005                 if(latt->editlatt) latt= latt->editlatt->latt;
2006                 
2007                 a= latt->pntsu*latt->pntsv*latt->pntsw;
2008                 count= 0;
2009                 bp= latt->def;
2010                 while(a--) {
2011                         if(count==nr) {
2012                                 if(co)
2013                                         memcpy(vec, co, 3*sizeof(float));
2014                                 else
2015                                         memcpy(vec, bp->vec, 3*sizeof(float));
2016                                 break;
2017                         }
2018                         count++;
2019                         if(co) co+= 3;
2020                         else bp++;
2021                 }
2022         }
2023 }
2024
2025 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
2026 {
2027         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2028
2029         /* in local ob space */
2030         unit_m4(mat);
2031         
2032         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
2033                 
2034                 give_parvert(par, ob->par1, v1);
2035                 give_parvert(par, ob->par2, v2);
2036                 give_parvert(par, ob->par3, v3);
2037                                 
2038                 tri_to_quat( q,v1, v2, v3);
2039                 quat_to_mat3( cmat,q);
2040                 copy_m4_m3(mat, cmat);
2041                 
2042                 if(ob->type==OB_CURVE) {
2043                         VECCOPY(mat[3], v1);
2044                 }
2045                 else {
2046                         add_v3_v3v3(mat[3], v1, v2);
2047                         add_v3_v3(mat[3], v3);
2048                         mul_v3_fl(mat[3], 0.3333333f);
2049                 }
2050         }
2051 }
2052
2053 // XXX what the hell is this?
2054 static int no_parent_ipo=0;
2055 void set_no_parent_ipo(int val)
2056 {
2057         no_parent_ipo= val;
2058 }
2059
2060 void where_is_object_time(Scene *scene, Object *ob, float ctime)
2061 {
2062         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
2063         float stime=ctime, fac1, fac2;
2064         int a;
2065         
2066         /* new version: correct parent+vertexparent and track+parent */
2067         /* this one only calculates direct attached parent and track */
2068         /* is faster, but should keep track of timeoffs */
2069         
2070         if(ob==NULL) return;
2071         
2072         /* execute drivers only, as animation has already been done */
2073         BKE_animsys_evaluate_animdata(&ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2074         
2075         if(ob->parent) {
2076                 Object *par= ob->parent;
2077                 
2078                 // XXX depreceated - animsys
2079                 if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
2080                 
2081                 /* hurms, code below conflicts with depgraph... (ton) */
2082                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
2083                 if(no_parent_ipo==0 && stime != par->ctime) {
2084                         // only for ipo systems? 
2085                         Object tmp= *par;
2086                         
2087                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
2088                         else where_is_object_time(scene, par, ctime);
2089
2090                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2091
2092                         *par= tmp;
2093                 }
2094                 else
2095                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2096                 
2097                 if(ob->partype & PARSLOW) {
2098                         // include framerate
2099                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
2100                         if(fac1 >= 1.0f) return;
2101                         fac2= 1.0f-fac1;
2102                         
2103                         fp1= ob->obmat[0];
2104                         fp2= slowmat[0];
2105                         for(a=0; a<16; a++, fp1++, fp2++) {
2106                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2107                         }
2108                 }
2109         }
2110         else {
2111                 object_to_mat4(ob, ob->obmat);
2112         }
2113
2114         /* solve constraints */
2115         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2116                 bConstraintOb *cob;
2117                 
2118                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2119                 
2120                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
2121                 solve_constraints (&ob->constraints, cob, ctime);
2122                 
2123                 constraints_clear_evalob(cob);
2124         }
2125         
2126         /* set negative scale flag in object */
2127         if(is_negative_m4(ob->obmat))   ob->transflag |= OB_NEG_SCALE;
2128         else                                                    ob->transflag &= ~OB_NEG_SCALE;
2129 }
2130
2131 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2132 {
2133         float totmat[4][4];
2134         float tmat[4][4];
2135         float locmat[4][4];
2136         float vec[3];
2137         int ok;
2138         
2139         object_to_mat4(ob, locmat);
2140         
2141         if(ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2142
2143         switch(ob->partype & PARTYPE) {
2144         case PAROBJECT:
2145                 ok= 0;
2146                 if(par->type==OB_CURVE) {
2147                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2148                                 ob_parcurve(scene, ob, par, tmat);
2149                                 ok= 1;
2150                         }
2151                 }
2152                 
2153                 if(ok) mul_serie_m4(totmat, par->obmat, tmat, 
2154                         NULL, NULL, NULL, NULL, NULL, NULL);
2155                 else copy_m4_m4(totmat, par->obmat);
2156                 
2157                 break;
2158         case PARBONE:
2159                 ob_parbone(ob, par, tmat);
2160                 mul_serie_m4(totmat, par->obmat, tmat,         
2161                         NULL, NULL, NULL, NULL, NULL, NULL);
2162                 break;
2163                 
2164         case PARVERT1:
2165                 unit_m4(totmat);
2166                 if (simul){
2167                         VECCOPY(totmat[3], par->obmat[3]);
2168                 }
2169                 else{
2170                         give_parvert(par, ob->par1, vec);
2171                         mul_v3_m4v3(totmat[3], par->obmat, vec);
2172                 }
2173                 break;
2174         case PARVERT3:
2175                 ob_parvert3(ob, par, tmat);
2176                 
2177                 mul_serie_m4(totmat, par->obmat, tmat,         
2178                         NULL, NULL, NULL, NULL, NULL, NULL);
2179                 break;
2180                 
2181         case PARSKEL:
2182                 copy_m4_m4(totmat, par->obmat);
2183                 break;
2184         }
2185         
2186         // total 
2187         mul_serie_m4(tmat, totmat, ob->parentinv,         
2188                 NULL, NULL, NULL, NULL, NULL, NULL);
2189         mul_serie_m4(obmat, tmat, locmat,         
2190                 NULL, NULL, NULL, NULL, NULL, NULL);
2191         
2192         if (simul) {
2193
2194         }
2195         else{
2196                 // external usable originmat 
2197                 copy_m3_m4(originmat, tmat);
2198                 
2199                 // origin, voor help line
2200                 if( (ob->partype & PARTYPE)==PARSKEL ) {
2201                         VECCOPY(ob->orig, par->obmat[3]);
2202                 }
2203                 else {
2204                         VECCOPY(ob->orig, totmat[3]);
2205                 }
2206         }
2207
2208 }
2209
2210 void where_is_object(struct Scene *scene, Object *ob)
2211 {
2212         where_is_object_time(scene, ob, (float)scene->r.cfra);
2213 }
2214
2215
2216 void where_is_object_simul(Scene *scene, Object *ob)
2217 /* was written for the old game engine (until 2.04) */
2218 /* It seems that this function is only called
2219 for a lamp that is the child of another object */
2220 {
2221         Object *par;
2222         //Ipo *ipo;
2223         float *fp1, *fp2;
2224         float slowmat[4][4];
2225         float fac1, fac2;
2226         int a;
2227         
2228         /* NO TIMEOFFS */
2229         if(ob->parent) {
2230                 par= ob->parent;
2231                 
2232                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2233
2234                 if(ob->partype & PARSLOW) {
2235
2236                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2237                         fac2= 1.0f-fac1;
2238                         fp1= ob->obmat[0];
2239                         fp2= slowmat[0];
2240                         for(a=0; a<16; a++, fp1++, fp2++) {
2241                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2242                         }
2243                 }
2244                 
2245         }
2246         else {
2247                 object_to_mat4(ob, ob->obmat);
2248         }
2249         
2250         /* solve constraints */
2251         if (ob->constraints.first) {
2252                 bConstraintOb *cob;
2253                 
2254                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2255                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2256                 constraints_clear_evalob(cob);
2257         }
2258 }
2259
2260 /* for calculation of the inverse parent transform, only used for editor */
2261 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2262 {
2263         clear_workob(workob);
2264         
2265         unit_m4(workob->obmat);
2266         unit_m4(workob->parentinv);
2267         unit_m4(workob->constinv);
2268         workob->parent= ob->parent;
2269
2270         workob->trackflag= ob->trackflag;
2271         workob->upflag= ob->upflag;
2272         
2273         workob->partype= ob->partype;
2274         workob->par1= ob->par1;
2275         workob->par2= ob->par2;
2276         workob->par3= ob->par3;
2277
2278         workob->constraints.first = ob->constraints.first;
2279         workob->constraints.last = ob->constraints.last;
2280
2281         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2282
2283         where_is_object(scene, workob);
2284 }
2285
2286 BoundBox *unit_boundbox(void)
2287 {
2288         BoundBox *bb;
2289         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2290
2291         bb= MEM_callocN(sizeof(BoundBox), "bb");
2292         boundbox_set_from_min_max(bb, min, max);
2293         
2294         return bb;
2295 }
2296
2297 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2298 {
2299         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2300         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2301         
2302         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2303         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2304
2305         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2306         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2307 }
2308
2309 BoundBox *object_get_boundbox(Object *ob)
2310 {
2311         BoundBox *bb= NULL;
2312         
2313         if(ob->type==OB_MESH) {
2314                 bb = mesh_get_bb(ob);
2315         }
2316         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2317                 bb= ob->bb ? ob->bb : ( (Curve *)ob->data )->bb;
2318         }
2319         else if(ob->type==OB_MBALL) {
2320                 bb= ob->bb;
2321         }
2322         return bb;
2323 }
2324
2325 /* used to temporally disable/enable boundbox */
2326 void object_boundbox_flag(Object *ob, int flag, int set)
2327 {
2328         BoundBox *bb= object_get_boundbox(ob);
2329         if(bb) {
2330                 if(set) bb->flag |= flag;
2331                 else bb->flag &= ~flag;
2332         }
2333 }
2334
2335 void object_get_dimensions(Object *ob, float *value)
2336 {
2337         BoundBox *bb = NULL;
2338         
2339         bb= object_get_boundbox(ob);
2340         if (bb) {
2341                 float scale[3];
2342                 
2343                 mat4_to_size( scale,ob->obmat);
2344                 
2345                 value[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2346                 value[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2347                 value[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2348         } else {
2349                 value[0] = value[1] = value[2] = 0.f;
2350         }
2351 }
2352
2353 void object_set_dimensions(Object *ob, const float *value)
2354 {
2355         BoundBox *bb = NULL;
2356         
2357         bb= object_get_boundbox(ob);
2358         if (bb) {
2359                 float scale[3], len[3];
2360                 
2361                 mat4_to_size( scale,ob->obmat);
2362                 
2363                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2364                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2365                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2366                 
2367                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2368                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2369                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2370         }
2371 }
2372
2373 void minmax_object(Object *ob, float *min, float *max)
2374 {
2375         BoundBox bb;
2376         Mesh *me;
2377         Curve *cu;
2378         float vec[3];
2379         int a;
2380         
2381         switch(ob->type) {
2382                 
2383         case OB_CURVE:
2384         case OB_FONT:
2385         case OB_SURF:
2386                 cu= ob->data;
2387                 
2388                 if(cu->bb==NULL) tex_space_curve(cu);
2389                 bb= *(cu->bb);
2390                 
2391                 for(a=0; a<8; a++) {
2392                         mul_m4_v3(ob->obmat, bb.vec[a]);
2393                         DO_MINMAX(bb.vec[a], min, max);
2394                 }
2395                 break;
2396         case OB_ARMATURE:
2397                 if(ob->pose) {
2398                         bPoseChannel *pchan;
2399                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2400                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2401                                 DO_MINMAX(vec, min, max);
2402                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2403                                 DO_MINMAX(vec, min, max);
2404                         }
2405                         break;
2406                 }
2407                 /* no break, get_mesh will give NULL and it passes on to default */
2408         case OB_MESH:
2409                 me= get_mesh(ob);
2410                 
2411                 if(me) {
2412                         bb = *mesh_get_bb(ob);
2413                         
2414                         for(a=0; a<8; a++) {
2415                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2416                                 DO_MINMAX(bb.vec[a], min, max);
2417                         }
2418                 }
2419                 if(min[0] < max[0] ) break;
2420                 
2421                 /* else here no break!!!, mesh can be zero sized */
2422                 
2423         default:
2424                 DO_MINMAX(ob->obmat[3], min, max);
2425
2426                 copy_v3_v3(vec, ob->obmat[3]);
2427                 add_v3_v3(vec, ob->size);
2428                 DO_MINMAX(vec, min, max);
2429
2430                 copy_v3_v3(vec, ob->obmat[3]);
2431                 sub_v3_v3(vec, ob->size);
2432                 DO_MINMAX(vec, min, max);
2433                 break;
2434         }
2435 }
2436
2437 int minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2438 {
2439         int ok= 0;
2440         if ((ob->transflag & OB_DUPLI)==0) {
2441                 return ok;
2442         } else {
2443                 ListBase *lb;
2444                 DupliObject *dob;
2445                 
2446                 lb= object_duplilist(scene, ob);
2447                 for(dob= lb->first; dob; dob= dob->next) {
2448                         if(dob->no_draw == 0) {
2449                                 BoundBox *bb= object_get_boundbox(dob->ob);
2450
2451                                 if(bb) {
2452                                         int i;
2453                                         for(i=0; i<8; i++) {
2454                                                 float vec[3];
2455                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2456                                                 DO_MINMAX(vec, min, max);
2457                                         }
2458
2459                                         ok= 1;
2460                                 }
2461                         }
2462                 }
2463                 free_object_duplilist(lb);      /* does restore */
2464         }
2465
2466         return ok;
2467 }
2468
2469 /* copied from DNA_object_types.h */
2470 typedef struct ObTfmBack {
2471         float loc[3], dloc[3], orig[3];
2472         float size[3], dsize[3];        /* scale and delta scale */
2473         float rot[3], drot[3];          /* euler rotation */
2474         float quat[4], dquat[4];        /* quaternion rotation */
2475         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2476         float rotAngle, drotAngle;      /* axis angle rotation - angle part */
2477         float obmat[4][4];              /* final worldspace matrix with constraints & animsys applied */
2478         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2479         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2480         float imat[4][4];       /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2481 } ObTfmBack;
2482
2483 void *object_tfm_backup(Object *ob)
2484 {
2485         ObTfmBack *obtfm= MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2486         copy_v3_v3(obtfm->loc, ob->loc);
2487         copy_v3_v3(obtfm->dloc, ob->dloc);
2488         copy_v3_v3(obtfm->orig, ob->orig);
2489         copy_v3_v3(obtfm->size, ob->size);
2490         copy_v3_v3(obtfm->dsize, ob->dsize);
2491         copy_v3_v3(obtfm->rot, ob->rot);
2492         copy_v3_v3(obtfm->drot, ob->drot);
2493         copy_qt_qt(obtfm->quat, ob->quat);
2494         copy_qt_qt(obtfm->dquat, ob->dquat);
2495         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2496         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2497         obtfm->rotAngle= ob->rotAngle;
2498         obtfm->drotAngle= ob->drotAngle;
2499         copy_m4_m4(obtfm->obmat, ob->obmat);
2500         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2501         copy_m4_m4(obtfm->constinv, ob->constinv);
2502         copy_m4_m4(obtfm->imat, ob->imat);
2503
2504         return (void *)obtfm;
2505 }
2506
2507 void object_tfm_restore(Object *ob, void *obtfm_pt)
2508 {
2509         ObTfmBack *obtfm= (ObTfmBack *)obtfm_pt;
2510         copy_v3_v3(ob->loc, obtfm->loc);
2511         copy_v3_v3(ob->dloc, obtfm->dloc);
2512         copy_v3_v3(ob->orig, obtfm->orig);
2513         copy_v3_v3(ob->size, obtfm->size);
2514         copy_v3_v3(ob->dsize, obtfm->dsize);
2515         copy_v3_v3(ob->rot, obtfm->rot);
2516         copy_v3_v3(ob->drot, obtfm->drot);
2517         copy_qt_qt(ob->quat, obtfm->quat);
2518         copy_qt_qt(ob->dquat, obtfm->dquat);
2519         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2520         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2521         ob->rotAngle= obtfm->rotAngle;
2522         ob->drotAngle= obtfm->drotAngle;
2523         copy_m4_m4(ob->obmat, obtfm->obmat);
2524         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2525         copy_m4_m4(ob->constinv, obtfm->constinv);
2526         copy_m4_m4(ob->imat, obtfm->imat);
2527 }
2528
2529 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2530 /*           local_object->proxy      == pointer to library object, saved in files and read */
2531
2532 /* function below is polluted with proxy exceptions, cleanup will follow! */
2533
2534 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2535 /* requires flags to be set! */
2536 void object_handle_update(Scene *scene, Object *ob)
2537 {
2538         if(ob->recalc & OB_RECALC_ALL) {
2539                 /* speed optimization for animation lookups */
2540                 if(ob->pose)
2541                         make_pose_channels_hash(ob->pose);
2542
2543                 if(ob->recalc & OB_RECALC_DATA) {
2544                         if(ob->type==OB_ARMATURE) {
2545                                 /* this happens for reading old files and to match library armatures
2546                                    with poses we do it ahead of where_is_object to ensure animation
2547                                    is evaluated on the rebuilt pose, otherwise we get incorrect poses
2548                                    on file load */
2549                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2550                                         armature_rebuild_pose(ob, ob->data);
2551                         }
2552                 }
2553
2554                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2555                    which is only in where_is_object now */
2556                 // XXX: should this case be OB_RECALC_OB instead?
2557                 if(ob->recalc & OB_RECALC_ALL) {
2558                         
2559                         if (G.f & G_DEBUG)
2560                                 printf("recalcob %s\n", ob->id.name+2);
2561                         
2562                         /* handle proxy copy for target */
2563                         if(ob->id.lib && ob->proxy_from) {
2564                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2565                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2566                                         Object *obg= ob->proxy_from->proxy_group;
2567                                         invert_m4_m4(obg->imat, obg->obmat);
2568                                         mul_m4_m4m4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2569                                         if(obg->dup_group) { /* should always be true */
2570                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2571                                         }
2572                                 }
2573                                 else
2574                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2575                         }
2576                         else
2577                                 where_is_object(scene, ob);
2578                 }
2579                 
2580                 if(ob->recalc & OB_RECALC_DATA) {
2581                         ID *data_id= (ID *)ob->data;
2582                         AnimData *adt= BKE_animdata_from_id(data_id);
2583                         float ctime= (float)scene->r.cfra; // XXX this is bad...
2584                         ListBase pidlist;
2585                         PTCacheID *pid;
2586                         
2587                         if (G.f & G_DEBUG)
2588                                 printf("recalcdata %s\n", ob->id.name+2);
2589
2590                         if(adt) {
2591                                 /* evaluate drivers */
2592                                 // XXX: for mesh types, should we push this to derivedmesh instead?
2593                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2594                         }
2595
2596                         /* includes all keys and modifiers */
2597                         switch(ob->type) {
2598                         case OB_MESH:
2599                                 {
2600 #if 0                           // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2601                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2602                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2603                                         if(em) {
2604                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask); /* was CD_MASK_BAREMESH */
2605                                                 BKE_mesh_end_editmesh(ob->data, em);
2606                                         } else
2607                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask);
2608
2609 #else                           /* ensure CD_MASK_BAREMESH for now */
2610                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2611                                         if(em) {
2612                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask | CD_MASK_BAREMESH); /* was CD_MASK_BAREMESH */
2613                                                 BKE_mesh_end_editmesh(ob->data, em);
2614                                         } else
2615                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask | CD_MASK_BAREMESH);
2616 #endif
2617
2618                                 }
2619                                 break;
2620
2621                         case OB_ARMATURE:
2622                                 if(ob->id.lib && ob->proxy_from) {
2623                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2624                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2625                                 }
2626                                 else {
2627                                         where_is_pose(scene, ob);
2628                                 }
2629                                 break;
2630
2631                         case OB_MBALL:
2632                                 makeDispListMBall(scene, ob);
2633                                 break;
2634
2635                         case OB_CURVE:
2636                         case OB_SURF:
2637                         case OB_FONT:
2638                                 makeDispListCurveTypes(scene, ob, 0);
2639                                 break;
2640                                 
2641                         case OB_LATTICE:
2642                                 lattice_calc_modifiers(scene, ob);
2643                                 break;
2644                         }
2645
2646
2647                         if(ob->particlesystem.first) {
2648                                 ParticleSystem *tpsys, *psys;
2649                                 DerivedMesh *dm;
2650                                 ob->transflag &= ~OB_DUPLIPARTS;
2651                                 
2652                                 psys= ob->particlesystem.first;
2653                                 while(psys) {
2654                                         if(psys_check_enabled(ob, psys)) {
2655                                                 /* check use of dupli objects here */
2656                                                 if(psys->part && (psys->part->draw_as == PART_DRAW_REND || G.rendering) &&
2657                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2658                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2659                                                         ob->transflag |= OB_DUPLIPARTS;
2660
2661                                                 particle_system_update(scene, ob, psys);
2662                                                 psys= psys->next;
2663                                         }
2664                                         else if(psys->flag & PSYS_DELETE) {
2665                                                 tpsys=psys->next;
2666                                                 BLI_remlink(&ob->particlesystem, psys);
2667                                                 psys_free(ob,psys);
2668                                                 psys= tpsys;
2669                                         }
2670                                         else
2671                                                 psys= psys->next;
2672                                 }
2673
2674                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2675                                         /* this is to make sure we get render level duplis in groups:
2676                                          * the derivedmesh must be created before init_render_mesh,
2677                                          * since object_duplilist does dupliparticles before that */
2678                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2679                                         dm->release(dm);
2680
2681                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2682                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2683                                 }
2684                         }
2685
2686                         /* check if quick cache is needed */
2687                         BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
2688
2689                         for(pid=pidlist.first; pid; pid=pid->next) {
2690                                 if((pid->cache->flag & PTCACHE_BAKED)
2691                                         || (pid->cache->flag & PTCACHE_QUICK_CACHE)==0)
2692                                         continue;
2693
2694                                 if(pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID)==0) {
2695                                         scene->physics_settings.quick_cache_step =
2696                                                 scene->physics_settings.quick_cache_step ?
2697                                                 MIN2(scene->physics_settings.quick_cache_step, pid->cache->step) :
2698                                                 pid->cache->step;
2699                                 }
2700                         }
2701
2702                         BLI_freelistN(&pidlist);
2703                 }
2704
2705                 /* the no-group proxy case, we call update */
2706                 if(ob->proxy && ob->proxy_group==NULL) {
2707                         /* set pointer in library proxy target, for copying, but restore it */
2708                         ob->proxy->proxy_from= ob;
2709                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2710                         object_handle_update(scene, ob->proxy);
2711                 }
2712         
2713                 ob->recalc &= ~OB_RECALC_ALL;
2714         }
2715
2716         /* the case when this is a group proxy, object_update is called in group.c */
2717         if(ob->proxy) {
2718                 ob->proxy->proxy_from= ob;
2719                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2720         }
2721 }
2722
2723 float give_timeoffset(Object *ob) {
2724         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2725                 return ob->sf + give_timeoffset(ob->parent);
2726         } else {
2727                 return ob->sf;
2728         }
2729 }
2730
2731 int give_obdata_texspace(Object *ob, short **texflag, float **loc, float **size, float **rot) {
2732         
2733         if (ob->data==NULL)
2734                 return 0;
2735         
2736         switch (GS(((ID *)ob->data)->name)) {
2737         case ID_ME:
2738         {
2739                 Mesh *me= ob->data;
2740                 if (texflag)    *texflag = &me->texflag;
2741                 if (loc)                *loc = me->loc;
2742                 if (size)               *size = me->size;
2743                 if (rot)                *rot = me->rot;
2744                 break;
2745         }
2746         case ID_CU:
2747         {
2748                 Curve *cu= ob->data;
2749                 if (texflag)    *texflag = &cu->texflag;
2750                 if (loc)                *loc = cu->loc;
2751                 if (size)               *size = cu->size;
2752                 if (rot)                *rot = cu->rot;
2753                 break;
2754         }
2755         case ID_MB:
2756         {
2757                 MetaBall *mb= ob->data;
2758                 if (texflag)    *texflag = &mb->texflag;
2759                 if (loc)                *loc = mb->loc;
2760                 if (size)               *size = mb->size;
2761                 if (rot)                *rot = mb->rot;
2762                 break;
2763         }
2764         default:
2765                 return 0;
2766         }
2767         return 1;
2768 }
2769
2770 /*
2771  * Test a bounding box for ray intersection
2772  * assumes the ray is already local to the boundbox space
2773  */
2774 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2775 {
2776         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2777                                                                                   {3, 2, 6}, {3, 6, 7},
2778                                                                                   {1, 2, 6}, {1, 6, 5}, 
2779                                                                                   {5, 6, 7}, {4, 5, 7},
2780                                                                                   {0, 3, 7}, {0, 4, 7},
2781                                                                                   {0, 1, 5}, {0, 4, 5}};
2782         int result = 0;
2783         int i;
2784         
2785         for (i = 0; i < 12 && result == 0; i++)
2786         {
2787                 float lambda;
2788                 int v1, v2, v3;
2789                 v1 = triangle_indexes[i][0];
2790                 v2 = triangle_indexes[i][1];
2791                 v3 = triangle_indexes[i][2];
2792                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2793         }
2794         
2795         return result;
2796 }
2797
2798 static int pc_cmp(void *a, void *b)
2799 {
2800         LinkData *ad = a, *bd = b;
2801         if(GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2802                 return 1;
2803         else return 0;
2804 }
2805
2806 int object_insert_ptcache(Object *ob) 
2807 {
2808         LinkData *link = NULL;
2809         int i = 0;
2810
2811         BLI_sortlist(&ob->pc_ids, pc_cmp);
2812
2813         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2814         {
2815                 int index = GET_INT_FROM_POINTER(link->data);
2816
2817                 if(i < index)
2818                         break;
2819         }
2820
2821         link = MEM_callocN(sizeof(LinkData), "PCLink");
2822         link->data = SET_INT_IN_POINTER(i);
2823         BLI_addtail(&ob->pc_ids, link);
2824
2825         return i;
2826 }
2827
2828 void object_camera_mode(RenderData *rd, Object *camera)
2829 {
2830         rd->mode &= ~(R_ORTHO|R_PANORAMA);
2831         if(camera && camera->type==OB_CAMERA) {
2832                 Camera *cam= camera->data;
2833                 if(cam->type == CAM_ORTHO) rd->mode |= R_ORTHO;
2834                 if(cam->flag & CAM_PANORAMA) rd->mode |= R_PANORAMA;
2835         }
2836 }
2837
2838 /* 'lens' may be set for envmap only */
2839 void object_camera_matrix(
2840                 RenderData *rd, Object *camera, int winx, int winy, short field_second,
2841                 float winmat[][4], rctf *viewplane, float *clipsta, float *clipend, float *lens, float *ycor,
2842                 float *viewdx, float *viewdy
2843 ) {
2844         Camera *cam=NULL;
2845         float pixsize;
2846         float shiftx=0.0, shifty=0.0, winside, viewfac;
2847         short is_ortho= FALSE;
2848
2849         /* question mark */
2850         (*ycor)= rd->yasp / rd->xasp;
2851         if(rd->mode & R_FIELDS)
2852                 (*ycor) *= 2.0f;
2853
2854         if(camera->type==OB_CAMERA) {
2855                 cam= camera->data;
2856
2857                 if(cam->type == CAM_ORTHO) {
2858                         is_ortho= TRUE;
2859                 }
2860
2861                 /* solve this too... all time depending stuff is in convertblender.c?
2862                  * Need to update the camera early because it's used for projection matrices
2863                  * and other stuff BEFORE the animation update loop is done
2864                  * */
2865 #if 0 // XXX old animation system
2866                 if(cam->ipo) {
2867                         calc_ipo(cam->ipo, frame_to_float(re->scene, re->r.cfra));
2868                         execute_ipo(&cam->id, cam->ipo);
2869                 }
2870 #endif // XXX old animation system
2871                 shiftx=cam->shiftx;
2872                 shifty=cam->shifty;
2873                 (*lens)= cam->lens;
2874                 (*clipsta)= cam->clipsta;
2875                 (*clipend)= cam->clipend;
2876         }
2877         else if(camera->type==OB_LAMP) {
2878                 Lamp *la= camera->data;
2879                 float fac= cosf((float)M_PI*la->spotsize/360.0f);
2880                 float phi= acos(fac);
2881
2882                 (*lens)= 16.0f*fac/sinf(phi);
2883                 if((*lens)==0.0f)
2884                         (*lens)= 35.0f;
2885                 (*clipsta)= la->clipsta;
2886                 (*clipend)= la->clipend;
2887         }
2888         else {  /* envmap exception... */;
2889                 if((*lens)==0.0f)
2890                         (*lens)= 16.0f;
2891
2892                 if((*clipsta)==0.0f || (*clipend)==0.0f) {
2893                         (*clipsta)= 0.1f;
2894                         (*clipend)= 1000.0f;
2895                 }
2896         }
2897
2898         /* ortho only with camera available */
2899         if(cam && is_ortho) {
2900                 if(rd->xasp*winx >= rd->yasp*winy) {
2901                         viewfac= winx;
2902                 }
2903                 else {
2904                         viewfac= (*ycor) * winy;
2905                 }
2906                 /* ortho_scale == 1.0 means exact 1 to 1 mapping */
2907                 pixsize= cam->ortho_scale/viewfac;
2908         }
2909         else {
2910                 if(rd->xasp*winx >= rd->yasp*winy)      viewfac= ((*lens) * winx)/32.0f;
2911                 else                                                            viewfac= (*ycor) * ((*lens) * winy)/32.0f;
2912                 pixsize= (*clipsta) / viewfac;
2913         }
2914
2915         /* viewplane fully centered, zbuffer fills in jittered between -.5 and +.5 */
2916         winside= MAX2(winx, winy);
2917         viewplane->xmin= -0.5f*(float)winx + shiftx*winside;
2918         viewplane->ymin= -0.5f*(*ycor)*(float)winy + shifty*winside;
2919         viewplane->xmax=  0.5f*(float)winx + shiftx*winside;
2920         viewplane->ymax=  0.5f*(*ycor)*(float)winy + shifty*winside;
2921
2922         if(field_second) {
2923                 if(rd->mode & R_ODDFIELD) {
2924                         viewplane->ymin-= 0.5f * (*ycor);
2925                         viewplane->ymax-= 0.5f * (*ycor);
2926                 }
2927                 else {
2928                         viewplane->ymin+= 0.5f * (*ycor);
2929                         viewplane->ymax+= 0.5f * (*ycor);
2930                 }
2931         }
2932         /* the window matrix is used for clipping, and not changed during OSA steps */
2933         /* using an offset of +0.5 here would give clip errors on edges */
2934         viewplane->xmin *= pixsize;
2935         viewplane->xmax *= pixsize;
2936         viewplane->ymin *= pixsize;
2937         viewplane->ymax *= pixsize;
2938
2939         (*viewdx)= pixsize;
2940         (*viewdy)= (*ycor) * pixsize;
2941
2942         if(is_ortho)
2943                 orthographic_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2944         else
2945                 perspective_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2946
2947 }
2948
2949 #if 0
2950 static int pc_findindex(ListBase *listbase, int index)
2951 {
2952         LinkData *link= NULL;
2953         int number= 0;
2954         
2955         if (listbase == NULL) return -1;
2956         
2957         link= listbase->first;
2958         while (link) {
2959                 if ((int)link->data == index)
2960                         return number;
2961                 
2962                 number++;
2963                 link= link->next;
2964         }
2965         
2966         return -1;
2967 }
2968
2969 void object_delete_ptcache(Object *ob, int index) 
2970 {
2971         int list_index = pc_findindex(&ob->pc_ids, index);
2972         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2973         BLI_freelinkN(&ob->pc_ids, link);
2974 }
2975 #endif
2976
2977 /* shape key utility function */
2978
2979 /************************* Mesh ************************/
2980 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
2981 {
2982         Mesh *me= ob->data;
2983         Key *key= me->key;
2984         KeyBlock *kb;
2985         int newkey= 0;
2986
2987         if(key == NULL) {
2988                 key= me->key= add_key((ID *)me);
2989                 key->type= KEY_RELATIVE;
2990                 newkey= 1;
2991         }
2992
2993         if(newkey || from_mix==FALSE) {
2994                 /* create from mesh */
2995                 kb= add_keyblock(key, name);
2996                 mesh_to_key(me, kb);
2997         }
2998         else {
2999                 /* copy from current values */
3000                 float *data= do_ob_key(scene, ob);
3001
3002                 /* create new block with prepared data */
3003                 kb= add_keyblock(key, name);
3004                 kb->data= data;
3005                 kb->totelem= me->totvert;
3006         }
3007
3008         return kb;
3009 }
3010 /************************* Lattice ************************/
3011 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
3012 {
3013         Lattice *lt= ob->data;
3014         Key *key= lt->key;
3015         KeyBlock *kb;
3016         int newkey= 0;
3017
3018         if(key==NULL) {
3019                 key= lt->key= add_key( (ID *)lt);
3020                 key->type= KEY_RELATIVE;
3021                 newkey= 1;
3022         }
3023
3024         if(newkey || from_mix==FALSE) {
3025                 kb= add_keyblock(key, name);
3026
3027                 /* create from lattice */
3028                 latt_to_key(lt, kb);
3029         }
3030         else {
3031                 /* copy from current values */
3032                 float *data= do_ob_key(scene, ob);
3033
3034                 /* create new block with prepared data */
3035                 kb= add_keyblock(key, name);
3036                 kb->totelem= lt->pntsu*lt->pntsv*lt->pntsw;
3037                 kb->data= data;
3038         }
3039
3040         return kb;
3041 }
3042 /************************* Curve ************************/
3043 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
3044 {
3045         Curve *cu= ob->data;
3046         Key *key= cu->key;
3047         KeyBlock *kb;
3048         ListBase *lb= BKE_curve_nurbs(cu);
3049         int newkey= 0;
3050
3051         if(key==NULL) {
3052                 key= cu->key= add_key( (ID *)cu);
3053                 key->type = KEY_RELATIVE;
3054                 newkey= 1;
3055         }
3056
3057         if(newkey || from_mix==FALSE) {
3058                 /* create from curve */
3059                 kb= add_keyblock(key, name);
3060                 if (!newkey) {
3061                         KeyBlock *basekb= (KeyBlock *)key->block.first;
3062                         kb->data= MEM_dupallocN(basekb->data);
3063                         kb->totelem= basekb->totelem;
3064                 } else curve_to_key(cu, kb, lb);
3065         }
3066         else {
3067                 /* copy from current values */
3068                 float *data= do_ob_key(scene, ob);
3069
3070                 /* create new block with prepared data */
3071                 kb= add_keyblock(key, name);
3072                 kb->totelem= count_curveverts(lb);
3073                 kb->data= data;
3074         }
3075
3076         return kb;
3077 }
3078
3079 KeyBlock *object_insert_shape_key(Scene *scene, Object *ob, const char *name, int from_mix)
3080 {
3081         if(ob->type==OB_MESH)                                    return insert_meshkey(scene, ob, name, from_mix);
3082         else if ELEM(ob->type, OB_CURVE, OB_SURF)return insert_curvekey(scene, ob, name, from_mix);
3083         else if(ob->type==OB_LATTICE)                    return insert_lattkey(scene, ob, name, from_mix);
3084         else                                                                     return NULL;
3085 }
3086
3087 /* most important if this is modified it should _always_ return True, in certain
3088  * cases false positives are hard to avoid (shape keys for eg)
3089  */
3090 int object_is_modified(Scene *scene, Object *ob)
3091 {
3092         int flag= 0;
3093
3094         if(ob_get_key(ob)) {
3095                 flag |= eModifierMode_Render | eModifierMode_Render;
3096         }
3097         else {
3098                 ModifierData *md;
3099                 /* cloth */
3100                 for(md=modifiers_getVirtualModifierList(ob); md && (flag != (eModifierMode_Render | eModifierMode_Realtime)); md=md->next) {
3101                         if((flag & eModifierMode_Render) == 0   && modifier_isEnabled(scene, md, eModifierMode_Render))         flag |= eModifierMode_Render;
3102                         if((flag & eModifierMode_Realtime) == 0 && modifier_isEnabled(scene, md, eModifierMode_Realtime))       flag |= eModifierMode_Realtime;
3103                 }
3104         }
3105
3106         return flag;
3107 }
3108
3109 static void copy_object__forwardModifierLinks(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin)
3110 {
3111         /* this is copied from ID_NEW; it might be better to have a macro */
3112         if(*idpoin && (*idpoin)->newid) *idpoin = (*idpoin)->newid;
3113 }
3114
3115 void object_relink(Object *ob)
3116 {
3117         if(ob->id.lib)
3118                 return;
3119
3120         relink_constraints(&ob->constraints);
3121         if (ob->pose){
3122                 bPoseChannel *chan;
3123                 for (chan = ob->pose->chanbase.first; chan; chan=chan->next){
3124                         relink_constraints(&chan->constraints);
3125                 }
3126         }
3127         modifiers_foreachIDLink(ob, copy_object__forwardModifierLinks, NULL);
3128
3129         if(ob->adt)
3130                 BKE_relink_animdata(ob->adt);
3131
3132         ID_NEW(ob->parent);
3133
3134         ID_NEW(ob->proxy);
3135         ID_NEW(ob->proxy_group);
3136 }