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