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