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