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