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