Fix #31522: wrong ID user count on custom bone shape object after duplicate
[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         BKE_displist_free(&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) BKE_mesh_unlink(ob->data);
303                         else if (ob->type == OB_CURVE) BKE_curve_unlink(ob->data);
304                         else if (ob->type == OB_MBALL) BKE_mball_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                 BKE_pose_free(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_mball_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 BKE_mesh_add("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_mball_add("Meta");
738                 case OB_CAMERA:    return BKE_camera_add("Camera");
739                 case OB_LAMP:      return BKE_lamp_add("Lamp");
740                 case OB_LATTICE:   return BKE_lattice_add("Lattice");
741                 case OB_ARMATURE:  return BKE_armature_add("Armature");
742                 case OB_SPEAKER:   return BKE_speaker_add("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 = BKE_scene_base_add(scene, ob);
866         BKE_scene_base_deselect_all(scene);
867         BKE_scene_base_select(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 BKE_pose_copy_data works (otherwise there's a crash) */
1031         obn->pose = NULL;
1032         BKE_pose_copy_data(&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                 if (chan->custom) {
1040                         id_us_plus(&chan->custom->id);
1041                 }
1042                 
1043                 for (con = chan->constraints.first; con; con = con->next) {
1044                         bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
1045                         ListBase targets = {NULL, NULL};
1046                         bConstraintTarget *ct;
1047                         
1048                         if (cti && cti->get_constraint_targets) {
1049                                 cti->get_constraint_targets(con, &targets);
1050                                 
1051                                 for (ct = targets.first; ct; ct = ct->next) {
1052                                         if (ct->tar == ob)
1053                                                 ct->tar = obn;
1054                                 }
1055                                 
1056                                 if (cti->flush_constraint_targets)
1057                                         cti->flush_constraint_targets(con, &targets, 0);
1058                         }
1059                 }
1060         }
1061 }
1062
1063 static int object_pose_context(Object *ob)
1064 {
1065         if ( (ob) &&
1066              (ob->type == OB_ARMATURE) &&
1067              (ob->pose) &&
1068              (ob->mode & OB_MODE_POSE))
1069         {
1070                 return 1;
1071         }
1072         else {
1073                 return 0;
1074         }
1075 }
1076
1077 Object *BKE_object_pose_armature_get(Object *ob)
1078 {
1079         if (ob == NULL)
1080                 return NULL;
1081
1082         if (object_pose_context(ob))
1083                 return ob;
1084
1085         ob = modifiers_isDeformedByArmature(ob);
1086
1087         if (object_pose_context(ob))
1088                 return ob;
1089
1090         return NULL;
1091 }
1092
1093 static void copy_object_transform(Object *ob_tar, Object *ob_src)
1094 {
1095         copy_v3_v3(ob_tar->loc, ob_src->loc);
1096         copy_v3_v3(ob_tar->rot, ob_src->rot);
1097         copy_v3_v3(ob_tar->quat, ob_src->quat);
1098         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1099         ob_tar->rotAngle = ob_src->rotAngle;
1100         ob_tar->rotmode = ob_src->rotmode;
1101         copy_v3_v3(ob_tar->size, ob_src->size);
1102 }
1103
1104 Object *BKE_object_copy(Object *ob)
1105 {
1106         Object *obn;
1107         ModifierData *md;
1108         int a;
1109
1110         obn = BKE_libblock_copy(&ob->id);
1111         
1112         if (ob->totcol) {
1113                 obn->mat = MEM_dupallocN(ob->mat);
1114                 obn->matbits = MEM_dupallocN(ob->matbits);
1115                 obn->totcol = ob->totcol;
1116         }
1117         
1118         if (ob->bb) obn->bb = MEM_dupallocN(ob->bb);
1119         obn->flag &= ~OB_FROMGROUP;
1120         
1121         obn->modifiers.first = obn->modifiers.last = NULL;
1122         
1123         for (md = ob->modifiers.first; md; md = md->next) {
1124                 ModifierData *nmd = modifier_new(md->type);
1125                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1126                 modifier_copyData(md, nmd);
1127                 BLI_addtail(&obn->modifiers, nmd);
1128         }
1129
1130         obn->prop.first = obn->prop.last = NULL;
1131         copy_properties(&obn->prop, &ob->prop);
1132         
1133         copy_sensors(&obn->sensors, &ob->sensors);
1134         copy_controllers(&obn->controllers, &ob->controllers);
1135         copy_actuators(&obn->actuators, &ob->actuators);
1136         
1137         if (ob->pose) {
1138                 copy_object_pose(obn, ob);
1139                 /* backwards compat... non-armatures can get poses in older files? */
1140                 if (ob->type == OB_ARMATURE)
1141                         BKE_pose_rebuild(obn, obn->data);
1142         }
1143         defgroup_copy_list(&obn->defbase, &ob->defbase);
1144         copy_constraints(&obn->constraints, &ob->constraints, TRUE);
1145
1146         obn->mode = 0;
1147         obn->sculpt = NULL;
1148
1149         /* increase user numbers */
1150         id_us_plus((ID *)obn->data);
1151         id_us_plus((ID *)obn->gpd);
1152         id_lib_extern((ID *)obn->dup_group);
1153
1154         for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1155         
1156         obn->disp.first = obn->disp.last = NULL;
1157         
1158         if (ob->pd) {
1159                 obn->pd = MEM_dupallocN(ob->pd);
1160                 if (obn->pd->tex)
1161                         id_us_plus(&(obn->pd->tex->id));
1162                 if (obn->pd->rng)
1163                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1164         }
1165         obn->soft = copy_softbody(ob->soft);
1166         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1167
1168         BKE_object_copy_particlesystems(obn, ob);
1169         
1170         obn->derivedDeform = NULL;
1171         obn->derivedFinal = NULL;
1172
1173         obn->gpulamp.first = obn->gpulamp.last = NULL;
1174         obn->pc_ids.first = obn->pc_ids.last = NULL;
1175
1176         obn->mpath = NULL;
1177         
1178         return obn;
1179 }
1180
1181 static void extern_local_object(Object *ob)
1182 {
1183         ParticleSystem *psys;
1184
1185         id_lib_extern((ID *)ob->data);
1186         id_lib_extern((ID *)ob->dup_group);
1187         id_lib_extern((ID *)ob->poselib);
1188         id_lib_extern((ID *)ob->gpd);
1189
1190         extern_local_matarar(ob->mat, ob->totcol);
1191
1192         for (psys = ob->particlesystem.first; psys; psys = psys->next)
1193                 id_lib_extern((ID *)psys->part);
1194 }
1195
1196 void BKE_object_make_local(Object *ob)
1197 {
1198         Main *bmain = G.main;
1199         Scene *sce;
1200         Base *base;
1201         int is_local = FALSE, is_lib = FALSE;
1202
1203         /* - only lib users: do nothing
1204          * - only local users: set flag
1205          * - mixed: make copy
1206          */
1207
1208         if (ob->id.lib == NULL) return;
1209         
1210         ob->proxy = ob->proxy_from = NULL;
1211         
1212         if (ob->id.us == 1) {
1213                 id_clear_lib_data(bmain, &ob->id);
1214                 extern_local_object(ob);
1215         }
1216         else {
1217                 for (sce = bmain->scene.first; sce && ELEM(0, is_lib, is_local); sce = sce->id.next) {
1218                         if (BKE_scene_base_find(sce, ob)) {
1219                                 if (sce->id.lib) is_lib = TRUE;
1220                                 else is_local = TRUE;
1221                         }
1222                 }
1223
1224                 if (is_local && is_lib == FALSE) {
1225                         id_clear_lib_data(bmain, &ob->id);
1226                         extern_local_object(ob);
1227                 }
1228                 else if (is_local && is_lib) {
1229                         Object *ob_new = BKE_object_copy(ob);
1230
1231                         ob_new->id.us = 0;
1232                         
1233                         /* Remap paths of new ID using old library as base. */
1234                         BKE_id_lib_local_paths(bmain, ob->id.lib, &ob_new->id);
1235
1236                         sce = bmain->scene.first;
1237                         while (sce) {
1238                                 if (sce->id.lib == NULL) {
1239                                         base = sce->base.first;
1240                                         while (base) {
1241                                                 if (base->object == ob) {
1242                                                         base->object = ob_new;
1243                                                         ob_new->id.us++;
1244                                                         ob->id.us--;
1245                                                 }
1246                                                 base = base->next;
1247                                         }
1248                                 }
1249                                 sce = sce->id.next;
1250                         }
1251                 }
1252         }
1253 }
1254
1255 /*
1256  * Returns true if the Object is a from an external blend file (libdata)
1257  */
1258 int BKE_object_is_libdata(Object *ob)
1259 {
1260         if (!ob) return 0;
1261         if (ob->proxy) return 0;
1262         if (ob->id.lib) return 1;
1263         return 0;
1264 }
1265
1266 /* Returns true if the Object data is a from an external blend file (libdata) */
1267 int BKE_object_obdata_is_libdata(Object *ob)
1268 {
1269         if (!ob) return 0;
1270         if (ob->proxy && (ob->data == NULL || ((ID *)ob->data)->lib == NULL)) return 0;
1271         if (ob->id.lib) return 1;
1272         if (ob->data == NULL) return 0;
1273         if (((ID *)ob->data)->lib) return 1;
1274
1275         return 0;
1276 }
1277
1278 /* *************** PROXY **************** */
1279
1280 /* when you make proxy, ensure the exposed layers are extern */
1281 static void armature_set_id_extern(Object *ob)
1282 {
1283         bArmature *arm = ob->data;
1284         bPoseChannel *pchan;
1285         unsigned int lay = arm->layer_protected;
1286         
1287         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1288                 if (!(pchan->bone->layer & lay))
1289                         id_lib_extern((ID *)pchan->custom);
1290         }
1291                         
1292 }
1293
1294 void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
1295 {
1296         if ((target->adt) && (target->adt->drivers.first)) {
1297                 FCurve *fcu;
1298                 
1299                 /* add new animdata block */
1300                 if (!ob->adt)
1301                         ob->adt = BKE_id_add_animdata(&ob->id);
1302                 
1303                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1304                 free_fcurves(&ob->adt->drivers);
1305                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1306                 
1307                 for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) {
1308                         ChannelDriver *driver = fcu->driver;
1309                         DriverVar *dvar;
1310                         
1311                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1312                                 /* all drivers */
1313                                 DRIVER_TARGETS_LOOPER(dvar) 
1314                                 {
1315                                         if (dtar->id) {
1316                                                 if ((Object *)dtar->id == target)
1317                                                         dtar->id = (ID *)ob;
1318                                                 else {
1319                                                         /* only on local objects because this causes indirect links a -> b -> c, blend to point directly to a.blend
1320                                                          * when a.blend has a proxy thats linked into c.blend  */
1321                                                         if (ob->id.lib == NULL)
1322                                                                 id_lib_extern((ID *)dtar->id);
1323                                                 }
1324                                         }
1325                                 }
1326                                 DRIVER_TARGETS_LOOPER_END
1327                         }
1328                 }
1329         }
1330 }
1331
1332 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1333 /*             local_object->proxy == pointer to library object, saved in files and read */
1334 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1335
1336 void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
1337 {
1338         /* paranoia checks */
1339         if (ob->id.lib || target->id.lib == NULL) {
1340                 printf("cannot make proxy\n");
1341                 return;
1342         }
1343         
1344         ob->proxy = target;
1345         ob->proxy_group = gob;
1346         id_lib_extern(&target->id);
1347         
1348         ob->recalc = target->recalc = OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
1349         
1350         /* copy transform
1351          * - gob means this proxy comes from a group, just apply the matrix
1352          *   so the object wont move from its dupli-transform.
1353          *
1354          * - no gob means this is being made from a linked object,
1355          *   this is closer to making a copy of the object - in-place. */
1356         if (gob) {
1357                 ob->rotmode = target->rotmode;
1358                 mult_m4_m4m4(ob->obmat, gob->obmat, target->obmat);
1359                 if (gob->dup_group) { /* should always be true */
1360                         float tvec[3];
1361                         copy_v3_v3(tvec, gob->dup_group->dupli_ofs);
1362                         mul_mat3_m4_v3(ob->obmat, tvec);
1363                         sub_v3_v3(ob->obmat[3], tvec);
1364                 }
1365                 BKE_object_apply_mat4(ob, ob->obmat, FALSE, TRUE);
1366         }
1367         else {
1368                 copy_object_transform(ob, target);
1369                 ob->parent = target->parent; /* libdata */
1370                 copy_m4_m4(ob->parentinv, target->parentinv);
1371         }
1372         
1373         /* copy animdata stuff - drivers only for now... */
1374         BKE_object_copy_proxy_drivers(ob, target);
1375
1376         /* skip constraints? */
1377         // FIXME: this is considered by many as a bug
1378         
1379         /* set object type and link to data */
1380         ob->type = target->type;
1381         ob->data = target->data;
1382         id_us_plus((ID *)ob->data);     /* ensures lib data becomes LIB_EXTERN */
1383         
1384         /* copy material and index information */
1385         ob->actcol = ob->totcol = 0;
1386         if (ob->mat) MEM_freeN(ob->mat);
1387         if (ob->matbits) MEM_freeN(ob->matbits);
1388         ob->mat = NULL;
1389         ob->matbits = NULL;
1390         if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1391                 int i;
1392                 
1393                 ob->actcol = target->actcol;
1394                 ob->totcol = target->totcol;
1395                 
1396                 ob->mat = MEM_dupallocN(target->mat);
1397                 ob->matbits = MEM_dupallocN(target->matbits);
1398                 for (i = 0; i < target->totcol; i++) {
1399                         /* don't need to run test_object_materials since we know this object is new and not used elsewhere */
1400                         id_us_plus((ID *)ob->mat[i]); 
1401                 }
1402         }
1403         
1404         /* type conversions */
1405         if (target->type == OB_ARMATURE) {
1406                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1407                 BKE_pose_rest(ob->pose);            /* clear all transforms in channels */
1408                 BKE_pose_rebuild(ob, ob->data); /* set all internal links */
1409                 
1410                 armature_set_id_extern(ob);
1411         }
1412         else if (target->type == OB_EMPTY) {
1413                 ob->empty_drawtype = target->empty_drawtype;
1414                 ob->empty_drawsize = target->empty_drawsize;
1415         }
1416
1417         /* copy IDProperties */
1418         if (ob->id.properties) {
1419                 IDP_FreeProperty(ob->id.properties);
1420                 MEM_freeN(ob->id.properties);
1421                 ob->id.properties = NULL;
1422         }
1423         if (target->id.properties) {
1424                 ob->id.properties = IDP_CopyProperty(target->id.properties);
1425         }
1426
1427         /* copy drawtype info */
1428         ob->dt = target->dt;
1429 }
1430
1431
1432 /* *************** CALC ****************** */
1433
1434 void BKE_object_scale_to_mat3(Object *ob, float mat[][3])
1435 {
1436         float vec[3];
1437         mul_v3_v3v3(vec, ob->size, ob->dscale);
1438         size_to_mat3(mat, vec);
1439 }
1440
1441 void BKE_object_rot_to_mat3(Object *ob, float mat[][3])
1442 {
1443         float rmat[3][3], dmat[3][3];
1444         
1445         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1446          * with the rotation matrix to yield the appropriate rotation
1447          */
1448
1449         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1450         if (ob->rotmode > 0) {
1451                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1452                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1453                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1454         }
1455         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1456                 /* axis-angle -  not really that great for 3D-changing orientations */
1457                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1458                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1459         }
1460         else {
1461                 /* quats are normalised before use to eliminate scaling issues */
1462                 float tquat[4];
1463                 
1464                 normalize_qt_qt(tquat, ob->quat);
1465                 quat_to_mat3(rmat, tquat);
1466                 
1467                 normalize_qt_qt(tquat, ob->dquat);
1468                 quat_to_mat3(dmat, tquat);
1469         }
1470         
1471         /* combine these rotations */
1472         mul_m3_m3m3(mat, dmat, rmat);
1473 }
1474
1475 void BKE_object_mat3_to_rot(Object *ob, float mat[][3], short use_compat)
1476 {
1477         switch (ob->rotmode) {
1478                 case ROT_MODE_QUAT:
1479                 {
1480                         float dquat[4];
1481                         mat3_to_quat(ob->quat, mat);
1482                         normalize_qt_qt(dquat, ob->dquat);
1483                         invert_qt(dquat);
1484                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1485                 }
1486                 break;
1487                 case ROT_MODE_AXISANGLE:
1488                         mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1489                         sub_v3_v3(ob->rotAxis, ob->drotAxis);
1490                         ob->rotAngle -= ob->drotAngle;
1491                         break;
1492                 default: /* euler */
1493                 {
1494                         float quat[4];
1495                         float dquat[4];
1496                         float tmat[3][3];
1497
1498                         /* without drot we could apply 'mat' directly */
1499                         mat3_to_quat(quat, mat);
1500                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1501                         invert_qt(dquat);
1502                         mul_qt_qtqt(quat, dquat, quat);
1503                         quat_to_mat3(tmat, quat);
1504                         /* end drot correction */
1505
1506                         if (use_compat) mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1507                         else mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1508                 }
1509         }
1510 }
1511
1512 void BKE_object_tfm_protected_backup(const Object *ob,
1513                                      ObjectTfmProtectedChannels *obtfm)
1514 {
1515
1516 #define TFMCPY(_v) (obtfm->_v = ob->_v)
1517 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
1518 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
1519
1520         TFMCPY3D(loc);
1521         TFMCPY3D(dloc);
1522         TFMCPY3D(size);
1523         TFMCPY3D(dscale);
1524         TFMCPY3D(rot);
1525         TFMCPY3D(drot);
1526         TFMCPY4D(quat);
1527         TFMCPY4D(dquat);
1528         TFMCPY3D(rotAxis);
1529         TFMCPY3D(drotAxis);
1530         TFMCPY(rotAngle);
1531         TFMCPY(drotAngle);
1532
1533 #undef TFMCPY
1534 #undef TFMCPY3D
1535 #undef TFMCPY4D
1536
1537 }
1538
1539 void BKE_object_tfm_protected_restore(Object *ob,
1540                                       const ObjectTfmProtectedChannels *obtfm,
1541                                       const short protectflag)
1542 {
1543         unsigned int i;
1544
1545         for (i = 0; i < 3; i++) {
1546                 if (protectflag & (OB_LOCK_LOCX << i)) {
1547                         ob->loc[i] =  obtfm->loc[i];
1548                         ob->dloc[i] = obtfm->dloc[i];
1549                 }
1550
1551                 if (protectflag & (OB_LOCK_SCALEX << i)) {
1552                         ob->size[i] =  obtfm->size[i];
1553                         ob->dscale[i] = obtfm->dscale[i];
1554                 }
1555
1556                 if (protectflag & (OB_LOCK_ROTX << i)) {
1557                         ob->rot[i] =  obtfm->rot[i];
1558                         ob->drot[i] = obtfm->drot[i];
1559
1560                         ob->quat[i + 1] =  obtfm->quat[i + 1];
1561                         ob->dquat[i + 1] = obtfm->dquat[i + 1];
1562
1563                         ob->rotAxis[i] =  obtfm->rotAxis[i];
1564                         ob->drotAxis[i] = obtfm->drotAxis[i];
1565                 }
1566         }
1567
1568         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
1569                 ob->quat[0] =  obtfm->quat[0];
1570                 ob->dquat[0] = obtfm->dquat[0];
1571
1572                 ob->rotAngle =  obtfm->rotAngle;
1573                 ob->drotAngle = obtfm->drotAngle;
1574         }
1575 }
1576
1577 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
1578 void BKE_object_apply_mat4(Object *ob, float mat[][4], const short use_compat, const short use_parent)
1579 {
1580         float rot[3][3];
1581
1582         if (use_parent && ob->parent) {
1583                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1584                 mult_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
1585                 invert_m4_m4(imat, diff_mat);
1586                 mult_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
1587                 BKE_object_apply_mat4(ob, rmat, use_compat, FALSE);
1588                 
1589                 /* same as below, use rmat rather than mat */
1590                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1591                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1592         }
1593         else {
1594                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1595                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1596         }
1597         
1598         sub_v3_v3(ob->loc, ob->dloc);
1599
1600         if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
1601         if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
1602         if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
1603
1604         /* BKE_object_mat3_to_rot handles delta rotations */
1605 }
1606
1607 void BKE_object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1608 {
1609         float smat[3][3];
1610         float rmat[3][3];
1611         /*float q1[4];*/
1612         
1613         /* size */
1614         BKE_object_scale_to_mat3(ob, smat);
1615
1616         /* rot */
1617         BKE_object_rot_to_mat3(ob, rmat);
1618         mul_m3_m3m3(mat, rmat, smat);
1619 }
1620
1621 void BKE_object_to_mat4(Object *ob, float mat[][4])
1622 {
1623         float tmat[3][3];
1624         
1625         BKE_object_to_mat3(ob, tmat);
1626         
1627         copy_m4_m3(mat, tmat);
1628
1629         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1630 }
1631
1632 /* extern */
1633 int enable_cu_speed = 1;
1634
1635 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1636 {
1637         Curve *cu;
1638         float vec[4], dir[3], quat[4], radius, ctime;
1639         float timeoffs = 0.0, sf_orig = 0.0;
1640         
1641         unit_m4(mat);
1642         
1643         cu = par->data;
1644         if (cu->path == NULL || cu->path->data == NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1645                 BKE_displist_make_curveTypes(scene, par, 0);
1646         if (cu->path == NULL) return;
1647         
1648         /* catch exceptions: feature for nla stride editing */
1649         if (ob->ipoflag & OB_DISABLE_PATH) {
1650                 ctime = 0.0f;
1651         }
1652         /* catch exceptions: curve paths used as a duplicator */
1653         else if (enable_cu_speed) {
1654                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1655                  * but this will only work if it actually is animated... 
1656                  *
1657                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1658                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1659                  */
1660                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1661                         ctime = cu->ctime / cu->pathlen;
1662                 else
1663                         ctime = cu->ctime;
1664
1665                 CLAMP(ctime, 0.0f, 1.0f);
1666         }
1667         else {
1668                 ctime = scene->r.cfra;
1669                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1670                         ctime /= cu->pathlen;
1671                 
1672                 CLAMP(ctime, 0.0f, 1.0f);
1673         }
1674         
1675         /* time calculus is correct, now apply distance offset */
1676         if (cu->flag & CU_OFFS_PATHDIST) {
1677                 ctime += timeoffs / cu->path->totdist;
1678
1679                 /* restore */
1680                 SWAP(float, sf_orig, ob->sf);
1681         }
1682         
1683         
1684         /* vec: 4 items! */
1685         if (where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat : NULL, &radius, NULL)) {
1686
1687                 if (cu->flag & CU_FOLLOW) {
1688 #if 0
1689                         float x1, q[4];
1690                         vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
1691                         
1692                         /* the tilt */
1693                         normalize_v3(dir);
1694                         q[0] = (float)cos(0.5 * vec[3]);
1695                         x1 = (float)sin(0.5 * vec[3]);
1696                         q[1] = -x1 * dir[0];
1697                         q[2] = -x1 * dir[1];
1698                         q[3] = -x1 * dir[2];
1699                         mul_qt_qtqt(quat, q, quat);
1700 #else
1701                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1702 #endif
1703                         normalize_qt(quat);
1704                         quat_to_mat4(mat, quat);
1705                 }
1706                 
1707                 if (cu->flag & CU_PATH_RADIUS) {
1708                         float tmat[4][4], rmat[4][4];
1709                         scale_m4_fl(tmat, radius);
1710                         mult_m4_m4m4(rmat, tmat, mat);
1711                         copy_m4_m4(mat, rmat);
1712                 }
1713
1714                 copy_v3_v3(mat[3], vec);
1715                 
1716         }
1717 }
1718
1719 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1720 {       
1721         bPoseChannel *pchan;
1722         float vec[3];
1723         
1724         if (par->type != OB_ARMATURE) {
1725                 unit_m4(mat);
1726                 return;
1727         }
1728         
1729         /* Make sure the bone is still valid */
1730         pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
1731         if (!pchan) {
1732                 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
1733                 unit_m4(mat);
1734                 return;
1735         }
1736
1737         /* get bone transform */
1738         copy_m4_m4(mat, pchan->pose_mat);
1739
1740         /* but for backwards compatibility, the child has to move to the tail */
1741         copy_v3_v3(vec, mat[1]);
1742         mul_v3_fl(vec, pchan->bone->length);
1743         add_v3_v3(mat[3], vec);
1744 }
1745
1746 static void give_parvert(Object *par, int nr, float vec[3])
1747 {
1748         BMEditMesh *em;
1749         int a, count;
1750         
1751         vec[0] = vec[1] = vec[2] = 0.0f;
1752         
1753         if (par->type == OB_MESH) {
1754                 Mesh *me = par->data;
1755                 DerivedMesh *dm;
1756
1757                 em = me->edit_btmesh;
1758
1759 #if 0   /* this was bmesh only, better, evaluate why this was needed - campbell*/
1760                 if (em) {
1761                         BMVert *eve;
1762                         BMIter iter;
1763
1764                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1765                                 int *keyindex = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
1766                                 
1767                                 if (keyindex && *keyindex == nr) {
1768                                         copy_v3_v3(vec, eve->co);
1769                                         break;
1770                                 }
1771                         }
1772                 }
1773 #endif
1774
1775                 dm = (em) ? em->derivedFinal : par->derivedFinal;
1776                         
1777                 if (dm) {
1778                         MVert *mvert = dm->getVertArray(dm);
1779                         int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1780                         int i, vindex, numVerts = dm->getNumVerts(dm);
1781
1782                         /* get the average of all verts with (original index == nr) */
1783                         count = 0;
1784                         for (i = 0; i < numVerts; i++) {
1785                                 vindex = (index) ? index[i] : i;
1786
1787                                 if (vindex == nr) {
1788                                         add_v3_v3(vec, mvert[i].co);
1789                                         count++;
1790                                 }
1791                         }
1792
1793                         if (count == 0) {
1794                                 /* keep as 0, 0, 0 */
1795                         }
1796                         else if (count > 0) {
1797                                 mul_v3_fl(vec, 1.0f / count);
1798                         }
1799                         else {
1800                                 /* use first index if its out of range */
1801                                 dm->getVertCo(dm, 0, vec);
1802                         }
1803                 }
1804                 else fprintf(stderr, "%s: DerivedMesh is needed to solve parenting, object position can be wrong now\n", __func__);
1805         }
1806         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1807                 Nurb *nu;
1808                 Curve *cu;
1809                 BPoint *bp;
1810                 BezTriple *bezt;
1811                 int found = 0;
1812                 ListBase *nurbs;
1813
1814                 cu = par->data;
1815                 nurbs = BKE_curve_nurbs_get(cu);
1816                 nu = nurbs->first;
1817
1818                 count = 0;
1819                 while (nu && !found) {
1820                         if (nu->type == CU_BEZIER) {
1821                                 bezt = nu->bezt;
1822                                 a = nu->pntsu;
1823                                 while (a--) {
1824                                         if (count == nr) {
1825                                                 found = 1;
1826                                                 copy_v3_v3(vec, bezt->vec[1]);
1827                                                 break;
1828                                         }
1829                                         count++;
1830                                         bezt++;
1831                                 }
1832                         }
1833                         else {
1834                                 bp = nu->bp;
1835                                 a = nu->pntsu * nu->pntsv;
1836                                 while (a--) {
1837                                         if (count == nr) {
1838                                                 found = 1;
1839                                                 memcpy(vec, bp->vec, sizeof(float) * 3);
1840                                                 break;
1841                                         }
1842                                         count++;
1843                                         bp++;
1844                                 }
1845                         }
1846                         nu = nu->next;
1847                 }
1848
1849         }
1850         else if (par->type == OB_LATTICE) {
1851                 Lattice *latt = par->data;
1852                 BPoint *bp;
1853                 DispList *dl = BKE_displist_find(&par->disp, DL_VERTS);
1854                 float *co = dl ? dl->verts : NULL;
1855                 
1856                 if (latt->editlatt) latt = latt->editlatt->latt;
1857                 
1858                 a = latt->pntsu * latt->pntsv * latt->pntsw;
1859                 count = 0;
1860                 bp = latt->def;
1861                 while (a--) {
1862                         if (count == nr) {
1863                                 if (co)
1864                                         memcpy(vec, co, 3 * sizeof(float));
1865                                 else
1866                                         memcpy(vec, bp->vec, 3 * sizeof(float));
1867                                 break;
1868                         }
1869                         count++;
1870                         if (co) co += 3;
1871                         else bp++;
1872                 }
1873         }
1874 }
1875
1876 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
1877 {
1878         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1879
1880         /* in local ob space */
1881         unit_m4(mat);
1882         
1883         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
1884                 
1885                 give_parvert(par, ob->par1, v1);
1886                 give_parvert(par, ob->par2, v2);
1887                 give_parvert(par, ob->par3, v3);
1888                                 
1889                 tri_to_quat(q, v1, v2, v3);
1890                 quat_to_mat3(cmat, q);
1891                 copy_m4_m3(mat, cmat);
1892                 
1893                 if (ob->type == OB_CURVE) {
1894                         copy_v3_v3(mat[3], v1);
1895                 }
1896                 else {
1897                         add_v3_v3v3(mat[3], v1, v2);
1898                         add_v3_v3(mat[3], v3);
1899                         mul_v3_fl(mat[3], 0.3333333f);
1900                 }
1901         }
1902 }
1903
1904 static int where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
1905 {
1906         float *fp1, *fp2;
1907         float fac1, fac2;
1908         int a;
1909
1910         // include framerate
1911         fac1 = (1.0f / (1.0f + fabsf(ob->sf)) );
1912         if (fac1 >= 1.0f) return 0;
1913         fac2 = 1.0f - fac1;
1914
1915         fp1 = obmat[0];
1916         fp2 = slowmat[0];
1917         for (a = 0; a < 16; a++, fp1++, fp2++) {
1918                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
1919         }
1920
1921         return 1;
1922 }
1923
1924 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
1925 {
1926         float slowmat[4][4] = MAT4_UNITY;
1927         float stime = ctime;
1928         
1929         /* new version: correct parent+vertexparent and track+parent */
1930         /* this one only calculates direct attached parent and track */
1931         /* is faster, but should keep track of timeoffs */
1932         
1933         if (ob == NULL) return;
1934         
1935         /* execute drivers only, as animation has already been done */
1936         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
1937         
1938         if (ob->parent) {
1939                 Object *par = ob->parent;
1940                 
1941                 /* hurms, code below conflicts with depgraph... (ton) */
1942                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
1943                 if (stime != par->ctime) {
1944                         // only for ipo systems? 
1945                         Object tmp = *par;
1946                         
1947                         if (par->proxy_from) ;  // was a copied matrix, no where_is! bad...
1948                         else BKE_object_where_is_calc_time(scene, par, ctime);
1949                         
1950                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1951                         
1952                         *par = tmp;
1953                 }
1954                 else
1955                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
1956                 
1957                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
1958                  * An old-fashioned hack which probably doesn't really cut it anymore
1959                  */
1960                 if (ob->partype & PARSLOW) {
1961                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
1962                                 return;
1963                 }
1964         }
1965         else {
1966                 BKE_object_to_mat4(ob, ob->obmat);
1967         }
1968
1969         /* solve constraints */
1970         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
1971                 bConstraintOb *cob;
1972                 
1973                 cob = constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
1974                 
1975                 /* constraints need ctime, not stime. Some call BKE_object_where_is_calc_time and bsystem_time */
1976                 solve_constraints(&ob->constraints, cob, ctime);
1977                 
1978                 constraints_clear_evalob(cob);
1979         }
1980         
1981         /* set negative scale flag in object */
1982         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
1983         else ob->transflag &= ~OB_NEG_SCALE;
1984 }
1985
1986 /* get object transformation matrix without recalculating dependencies and
1987  * constraints -- assume dependencies are already solved by depsgraph.
1988  * no changes to object and it's parent would be done.
1989  * used for bundles orientation in 3d space relative to parented blender camera */
1990 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
1991 {
1992         float slowmat[4][4] = MAT4_UNITY;
1993
1994         if (ob->parent) {
1995                 Object *par = ob->parent;
1996
1997                 solve_parenting(scene, ob, par, obmat, slowmat, 1);
1998
1999                 if (ob->partype & PARSLOW)
2000                         where_is_object_parslow(ob, obmat, slowmat);
2001         }
2002         else {
2003                 BKE_object_to_mat4(ob, obmat);
2004         }
2005 }
2006
2007 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2008 {
2009         float totmat[4][4];
2010         float tmat[4][4];
2011         float locmat[4][4];
2012         float vec[3];
2013         int ok;
2014         
2015         BKE_object_to_mat4(ob, locmat);
2016         
2017         if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2018
2019         switch (ob->partype & PARTYPE) {
2020                 case PAROBJECT:
2021                         ok = 0;
2022                         if (par->type == OB_CURVE) {
2023                                 if (((Curve *)par->data)->flag & CU_PATH) {
2024                                         ob_parcurve(scene, ob, par, tmat);
2025                                         ok = 1;
2026                                 }
2027                         }
2028                 
2029                         if (ok) mul_serie_m4(totmat, par->obmat, tmat,
2030                                                  NULL, NULL, NULL, NULL, NULL, NULL);
2031                         else copy_m4_m4(totmat, par->obmat);
2032                 
2033                         break;
2034                 case PARBONE:
2035                         ob_parbone(ob, par, tmat);
2036                         mul_serie_m4(totmat, par->obmat, tmat,
2037                                      NULL, NULL, NULL, NULL, NULL, NULL);
2038                         break;
2039                 
2040                 case PARVERT1:
2041                         unit_m4(totmat);
2042                         if (simul) {
2043                                 copy_v3_v3(totmat[3], par->obmat[3]);
2044                         }
2045                         else {
2046                                 give_parvert(par, ob->par1, vec);
2047                                 mul_v3_m4v3(totmat[3], par->obmat, vec);
2048                         }
2049                         break;
2050                 case PARVERT3:
2051                         ob_parvert3(ob, par, tmat);
2052                 
2053                         mul_serie_m4(totmat, par->obmat, tmat,
2054                                      NULL, NULL, NULL, NULL, NULL, NULL);
2055                         break;
2056                 
2057                 case PARSKEL:
2058                         copy_m4_m4(totmat, par->obmat);
2059                         break;
2060         }
2061         
2062         // total 
2063         mul_serie_m4(tmat, totmat, ob->parentinv,         
2064                      NULL, NULL, NULL, NULL, NULL, NULL);
2065         mul_serie_m4(obmat, tmat, locmat,         
2066                      NULL, NULL, NULL, NULL, NULL, NULL);
2067         
2068         if (simul) {
2069
2070         }
2071         else {
2072                 // external usable originmat 
2073                 copy_m3_m4(originmat, tmat);
2074                 
2075                 // origin, voor help line
2076                 if ((ob->partype & PARTYPE) == PARSKEL) {
2077                         copy_v3_v3(ob->orig, par->obmat[3]);
2078                 }
2079                 else {
2080                         copy_v3_v3(ob->orig, totmat[3]);
2081                 }
2082         }
2083
2084 }
2085
2086 void BKE_object_where_is_calc(struct Scene *scene, Object *ob)
2087 {
2088         BKE_object_where_is_calc_time(scene, ob, (float)scene->r.cfra);
2089 }
2090
2091
2092 void BKE_object_where_is_calc_simul(Scene *scene, Object *ob)
2093 /* was written for the old game engine (until 2.04) */
2094 /* It seems that this function is only called
2095  * for a lamp that is the child of another object */
2096 {
2097         Object *par;
2098         float *fp1, *fp2;
2099         float slowmat[4][4];
2100         float fac1, fac2;
2101         int a;
2102         
2103         /* NO TIMEOFFS */
2104         if (ob->parent) {
2105                 par = ob->parent;
2106                 
2107                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2108                 
2109                 if (ob->partype & PARSLOW) {
2110                         fac1 = (float)(1.0 / (1.0 + fabs(ob->sf)));
2111                         fac2 = 1.0f - fac1;
2112                         fp1 = ob->obmat[0];
2113                         fp2 = slowmat[0];
2114                         for (a = 0; a < 16; a++, fp1++, fp2++) {
2115                                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2116                         }
2117                 }
2118         }
2119         else {
2120                 BKE_object_to_mat4(ob, ob->obmat);
2121         }
2122         
2123         /* solve constraints */
2124         if (ob->constraints.first) {
2125                 bConstraintOb *cob;
2126                 
2127                 cob = constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2128                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2129                 constraints_clear_evalob(cob);
2130         }
2131 }
2132
2133 /* for calculation of the inverse parent transform, only used for editor */
2134 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2135 {
2136         BKE_object_workob_clear(workob);
2137         
2138         unit_m4(workob->obmat);
2139         unit_m4(workob->parentinv);
2140         unit_m4(workob->constinv);
2141         workob->parent = ob->parent;
2142
2143         workob->trackflag = ob->trackflag;
2144         workob->upflag = ob->upflag;
2145         
2146         workob->partype = ob->partype;
2147         workob->par1 = ob->par1;
2148         workob->par2 = ob->par2;
2149         workob->par3 = ob->par3;
2150
2151         workob->constraints.first = ob->constraints.first;
2152         workob->constraints.last = ob->constraints.last;
2153
2154         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2155
2156         BKE_object_where_is_calc(scene, workob);
2157 }
2158
2159 BoundBox *BKE_boundbox_alloc_unit(void)
2160 {
2161         BoundBox *bb;
2162         float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2163
2164         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2165         BKE_boundbox_init_from_minmax(bb, min, max);
2166         
2167         return bb;
2168 }
2169
2170 void BKE_boundbox_init_from_minmax(BoundBox *bb, float min[3], float max[3])
2171 {
2172         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2173         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2174         
2175         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2176         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2177
2178         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2179         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2180 }
2181
2182 BoundBox *BKE_object_boundbox_get(Object *ob)
2183 {
2184         BoundBox *bb = NULL;
2185         
2186         if (ob->type == OB_MESH) {
2187                 bb = BKE_mesh_boundbox_get(ob);
2188         }
2189         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2190                 bb = ob->bb ? ob->bb : ((Curve *)ob->data)->bb;
2191         }
2192         else if (ob->type == OB_MBALL) {
2193                 bb = ob->bb;
2194         }
2195         return bb;
2196 }
2197
2198 /* used to temporally disable/enable boundbox */
2199 void BKE_object_boundbox_flag(Object *ob, int flag, int set)
2200 {
2201         BoundBox *bb = BKE_object_boundbox_get(ob);
2202         if (bb) {
2203                 if (set) bb->flag |= flag;
2204                 else bb->flag &= ~flag;
2205         }
2206 }
2207
2208 void BKE_object_dimensions_get(Object *ob, float vec[3])
2209 {
2210         BoundBox *bb = NULL;
2211         
2212         bb = BKE_object_boundbox_get(ob);
2213         if (bb) {
2214                 float scale[3];
2215                 
2216                 mat4_to_size(scale, ob->obmat);
2217                 
2218                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2219                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2220                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2221         }
2222         else {
2223                 zero_v3(vec);
2224         }
2225 }
2226
2227 void BKE_object_dimensions_set(Object *ob, const float *value)
2228 {
2229         BoundBox *bb = NULL;
2230         
2231         bb = BKE_object_boundbox_get(ob);
2232         if (bb) {
2233                 float scale[3], len[3];
2234                 
2235                 mat4_to_size(scale, ob->obmat);
2236                 
2237                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2238                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2239                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2240                 
2241                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2242                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2243                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2244         }
2245 }
2246
2247 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3])
2248 {
2249         BoundBox bb;
2250         float vec[3];
2251         int a;
2252         short change = FALSE;
2253         
2254         switch (ob->type) {
2255                 case OB_CURVE:
2256                 case OB_FONT:
2257                 case OB_SURF:
2258                 {
2259                         Curve *cu = ob->data;
2260
2261                         if (cu->bb == NULL) BKE_curve_texspace_calc(cu);
2262                         bb = *(cu->bb);
2263
2264                         for (a = 0; a < 8; a++) {
2265                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2266                                 minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2267                         }
2268                         change = TRUE;
2269                 }
2270                 break;
2271                 case OB_LATTICE:
2272                 {
2273                         Lattice *lt = ob->data;
2274                         BPoint *bp = lt->def;
2275                         int u, v, w;
2276
2277                         for (w = 0; w < lt->pntsw; w++) {
2278                                 for (v = 0; v < lt->pntsv; v++) {
2279                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2280                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2281                                                 minmax_v3v3_v3(min_r, max_r, vec);
2282                                         }
2283                                 }
2284                         }
2285                         change = TRUE;
2286                 }
2287                 break;
2288                 case OB_ARMATURE:
2289                         if (ob->pose) {
2290                                 bPoseChannel *pchan;
2291                                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2292                                         mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2293                                         minmax_v3v3_v3(min_r, max_r, vec);
2294                                         mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2295                                         minmax_v3v3_v3(min_r, max_r, vec);
2296                                 }
2297                                 change = TRUE;
2298                         }
2299                         break;
2300                 case OB_MESH:
2301                 {
2302                         Mesh *me = BKE_mesh_from_object(ob);
2303
2304                         if (me) {
2305                                 bb = *BKE_mesh_boundbox_get(ob);
2306
2307                                 for (a = 0; a < 8; a++) {
2308                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2309                                         minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2310                                 }
2311                                 change = TRUE;
2312                         }
2313                 }
2314                 break;
2315         }
2316
2317         if (change == FALSE) {
2318                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2319
2320                 copy_v3_v3(vec, ob->obmat[3]);
2321                 add_v3_v3(vec, ob->size);
2322                 minmax_v3v3_v3(min_r, max_r, vec);
2323
2324                 copy_v3_v3(vec, ob->obmat[3]);
2325                 sub_v3_v3(vec, ob->size);
2326                 minmax_v3v3_v3(min_r, max_r, vec);
2327         }
2328 }
2329
2330 int BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3])
2331 {
2332         int ok = 0;
2333         if ((ob->transflag & OB_DUPLI) == 0) {
2334                 return ok;
2335         }
2336         else {
2337                 ListBase *lb;
2338                 DupliObject *dob;
2339                 
2340                 lb = object_duplilist(scene, ob);
2341                 for (dob = lb->first; dob; dob = dob->next) {
2342                         if (dob->no_draw == 0) {
2343                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2344
2345                                 if (bb) {
2346                                         int i;
2347                                         for (i = 0; i < 8; i++) {
2348                                                 float vec[3];
2349                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2350                                                 minmax_v3v3_v3(r_min, r_max, vec);
2351                                         }
2352
2353                                         ok = 1;
2354                                 }
2355                         }
2356                 }
2357                 free_object_duplilist(lb);  /* does restore */
2358         }
2359
2360         return ok;
2361 }
2362
2363 void BKE_object_foreach_display_point(
2364         Object *ob, float obmat[4][4],
2365         void (*func_cb)(const float[3], void *), void *user_data)
2366 {
2367         float co[3];
2368
2369         if (ob->derivedFinal) {
2370                 DerivedMesh *dm = ob->derivedFinal;
2371                 MVert *mv = dm->getVertArray(dm);
2372                 int totvert = dm->getNumVerts(dm);
2373                 int i;
2374
2375                 for (i = 0; i < totvert; i++, mv++) {
2376                         mul_v3_m4v3(co, obmat, mv->co);
2377                         func_cb(co, user_data);
2378                 }
2379         }
2380         else if (ob->disp.first) {
2381                 DispList *dl;
2382
2383                 for (dl = ob->disp.first; dl; dl = dl->next) {
2384                         float *v3 = dl->verts;
2385                         int totvert = dl->nr;
2386                         int i;
2387
2388                         for (i = 0; i < totvert; i++, v3 += 3) {
2389                                 mul_v3_m4v3(co, obmat, v3);
2390                                 func_cb(co, user_data);
2391                         }
2392                 }
2393         }
2394 }
2395
2396 void BKE_scene_foreach_display_point(
2397         Scene *scene, View3D *v3d, const short flag,
2398         void (*func_cb)(const float[3], void *), void *user_data)
2399 {
2400         Base *base;
2401         Object *ob;
2402
2403         for (base = FIRSTBASE; base; base = base->next) {
2404                 if (BASE_VISIBLE(v3d, base) && (base->flag & flag) == flag) {
2405                         ob = base->object;
2406
2407                         if ((ob->transflag & OB_DUPLI) == 0) {
2408                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2409                         }
2410                         else {
2411                                 ListBase *lb;
2412                                 DupliObject *dob;
2413
2414                                 lb = object_duplilist(scene, ob);
2415                                 for (dob = lb->first; dob; dob = dob->next) {
2416                                         if (dob->no_draw == 0) {
2417                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2418                                         }
2419                                 }
2420                                 free_object_duplilist(lb);  /* does restore */
2421                         }
2422                 }
2423         }
2424 }
2425
2426 /* copied from DNA_object_types.h */
2427 typedef struct ObTfmBack {
2428         float loc[3], dloc[3], orig[3];
2429         float size[3], dscale[3];   /* scale and delta scale */
2430         float rot[3], drot[3];      /* euler rotation */
2431         float quat[4], dquat[4];    /* quaternion rotation */
2432         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2433         float rotAngle, drotAngle;  /* axis angle rotation - angle part */
2434         float obmat[4][4];      /* final worldspace matrix with constraints & animsys applied */
2435         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2436         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2437         float imat[4][4];   /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2438 } ObTfmBack;
2439
2440 void *BKE_object_tfm_backup(Object *ob)
2441 {
2442         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2443         copy_v3_v3(obtfm->loc, ob->loc);
2444         copy_v3_v3(obtfm->dloc, ob->dloc);
2445         copy_v3_v3(obtfm->orig, ob->orig);
2446         copy_v3_v3(obtfm->size, ob->size);
2447         copy_v3_v3(obtfm->dscale, ob->dscale);
2448         copy_v3_v3(obtfm->rot, ob->rot);
2449         copy_v3_v3(obtfm->drot, ob->drot);
2450         copy_qt_qt(obtfm->quat, ob->quat);
2451         copy_qt_qt(obtfm->dquat, ob->dquat);
2452         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2453         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2454         obtfm->rotAngle = ob->rotAngle;
2455         obtfm->drotAngle = ob->drotAngle;
2456         copy_m4_m4(obtfm->obmat, ob->obmat);
2457         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2458         copy_m4_m4(obtfm->constinv, ob->constinv);
2459         copy_m4_m4(obtfm->imat, ob->imat);
2460
2461         return (void *)obtfm;
2462 }
2463
2464 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2465 {
2466         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2467         copy_v3_v3(ob->loc, obtfm->loc);
2468         copy_v3_v3(ob->dloc, obtfm->dloc);
2469         copy_v3_v3(ob->orig, obtfm->orig);
2470         copy_v3_v3(ob->size, obtfm->size);
2471         copy_v3_v3(ob->dscale, obtfm->dscale);
2472         copy_v3_v3(ob->rot, obtfm->rot);
2473         copy_v3_v3(ob->drot, obtfm->drot);
2474         copy_qt_qt(ob->quat, obtfm->quat);
2475         copy_qt_qt(ob->dquat, obtfm->dquat);
2476         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2477         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2478         ob->rotAngle = obtfm->rotAngle;
2479         ob->drotAngle = obtfm->drotAngle;
2480         copy_m4_m4(ob->obmat, obtfm->obmat);
2481         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2482         copy_m4_m4(ob->constinv, obtfm->constinv);
2483         copy_m4_m4(ob->imat, obtfm->imat);
2484 }
2485
2486 int BKE_object_parent_loop_check(const Object *par, const Object *ob)
2487 {
2488         /* test if 'ob' is a parent somewhere in par's parents */
2489         if (par == NULL) return 0;
2490         if (ob == par) return 1;
2491         return BKE_object_parent_loop_check(par->parent, ob);
2492 }
2493
2494 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2495 /*           local_object->proxy      == pointer to library object, saved in files and read */
2496
2497 /* function below is polluted with proxy exceptions, cleanup will follow! */
2498
2499 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2500 /* requires flags to be set! */
2501 void BKE_object_handle_update(Scene *scene, Object *ob)
2502 {
2503         if (ob->recalc & OB_RECALC_ALL) {
2504                 /* speed optimization for animation lookups */
2505                 if (ob->pose)
2506                         BKE_pose_channels_hash_make(ob->pose);
2507
2508                 if (ob->recalc & OB_RECALC_DATA) {
2509                         if (ob->type == OB_ARMATURE) {
2510                                 /* this happens for reading old files and to match library armatures
2511                                  * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
2512                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2513                                  * on file load */
2514                                 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
2515                                         BKE_pose_rebuild(ob, ob->data);
2516                         }
2517                 }
2518
2519                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2520                  * which is only in BKE_object_where_is_calc now */
2521                 // XXX: should this case be OB_RECALC_OB instead?
2522                 if (ob->recalc & OB_RECALC_ALL) {
2523                         
2524                         if (G.debug & G_DEBUG)
2525                                 printf("recalcob %s\n", ob->id.name + 2);
2526                         
2527                         /* handle proxy copy for target */
2528                         if (ob->id.lib && ob->proxy_from) {
2529                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2530                                 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
2531                                         Object *obg = ob->proxy_from->proxy_group;
2532                                         invert_m4_m4(obg->imat, obg->obmat);
2533                                         mult_m4_m4m4(ob->obmat, obg->imat, ob->proxy_from->obmat);
2534                                         if (obg->dup_group) { /* should always be true */
2535                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2536                                         }
2537                                 }
2538                                 else
2539                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2540                         }
2541                         else
2542                                 BKE_object_where_is_calc(scene, ob);
2543                 }
2544                 
2545                 if (ob->recalc & OB_RECALC_DATA) {
2546                         ID *data_id = (ID *)ob->data;
2547                         AnimData *adt = BKE_animdata_from_id(data_id);
2548                         float ctime = (float)scene->r.cfra; // XXX this is bad...
2549                         ListBase pidlist;
2550                         PTCacheID *pid;
2551                         
2552                         if (G.debug & G_DEBUG)
2553                                 printf("recalcdata %s\n", ob->id.name + 2);
2554
2555                         if (adt) {
2556                                 /* evaluate drivers */
2557                                 // XXX: for mesh types, should we push this to derivedmesh instead?
2558                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2559                         }
2560
2561                         /* includes all keys and modifiers */
2562                         switch (ob->type) {
2563                                 case OB_MESH:
2564                                 {
2565 #if 0               // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2566                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2567                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2568                                         if (em) {
2569                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask, 0); /* was CD_MASK_BAREMESH */
2570                                         }
2571                                         else {
2572                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask, 0);
2573                                         }
2574
2575 #else               /* ensure CD_MASK_BAREMESH for now */
2576                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2577                                         uint64_t data_mask = scene->customdata_mask | ob->customdata_mask | CD_MASK_BAREMESH;
2578                                         if (em) {
2579                                                 makeDerivedMesh(scene, ob, em,  data_mask, 0); /* was CD_MASK_BAREMESH */
2580                                         }
2581                                         else {
2582                                                 makeDerivedMesh(scene, ob, NULL, data_mask, 0);
2583                                         }
2584 #endif
2585
2586                                 }
2587                                 break;
2588
2589                                 case OB_ARMATURE:
2590                                         if (ob->id.lib && ob->proxy_from) {
2591                                                 // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2592                                                 BKE_pose_copy_result(ob->pose, ob->proxy_from->pose);
2593                                         }
2594                                         else {
2595                                                 BKE_pose_where_is(scene, ob);
2596                                         }
2597                                         break;
2598
2599                                 case OB_MBALL:
2600                                         BKE_displist_make_mball(scene, ob);
2601                                         break;
2602
2603                                 case OB_CURVE:
2604                                 case OB_SURF:
2605                                 case OB_FONT:
2606                                         BKE_displist_make_curveTypes(scene, ob, 0);
2607                                         break;
2608                                 
2609                                 case OB_LATTICE:
2610                                         BKE_lattice_modifiers_calc(scene, ob);
2611                                         break;
2612                         }
2613
2614
2615                         if (ob->particlesystem.first) {
2616                                 ParticleSystem *tpsys, *psys;
2617                                 DerivedMesh *dm;
2618                                 ob->transflag &= ~OB_DUPLIPARTS;
2619                                 
2620                                 psys = ob->particlesystem.first;
2621                                 while (psys) {
2622                                         if (psys_check_enabled(ob, psys)) {
2623                                                 /* check use of dupli objects here */
2624                                                 if (psys->part && (psys->part->draw_as == PART_DRAW_REND || G.rendering) &&
2625                                                     ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob) ||
2626                                                      (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2627                                                 {
2628                                                         ob->transflag |= OB_DUPLIPARTS;
2629                                                 }
2630
2631                                                 particle_system_update(scene, ob, psys);
2632                                                 psys = psys->next;
2633                                         }
2634                                         else if (psys->flag & PSYS_DELETE) {
2635                                                 tpsys = psys->next;
2636                                                 BLI_remlink(&ob->particlesystem, psys);
2637                                                 psys_free(ob, psys);
2638                                                 psys = tpsys;
2639                                         }
2640                                         else
2641                                                 psys = psys->next;
2642                                 }
2643
2644                                 if (G.rendering && ob->transflag & OB_DUPLIPARTS) {
2645                                         /* this is to make sure we get render level duplis in groups:
2646                                          * the derivedmesh must be created before init_render_mesh,
2647                                          * since object_duplilist does dupliparticles before that */
2648                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH | CD_MASK_MTFACE | CD_MASK_MCOL);
2649                                         dm->release(dm);
2650
2651                                         for (psys = ob->particlesystem.first; psys; psys = psys->next)
2652                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2653                                 }
2654                         }
2655
2656                         /* check if quick cache is needed */
2657                         BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
2658
2659                         for (pid = pidlist.first; pid; pid = pid->next) {
2660                                 if ((pid->cache->flag & PTCACHE_BAKED) ||
2661                                     (pid->cache->flag & PTCACHE_QUICK_CACHE) == 0)
2662                                 {
2663                                         continue;
2664                                 }
2665
2666                                 if (pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID) == 0) {
2667                                         scene->physics_settings.quick_cache_step =
2668                                                 scene->physics_settings.quick_cache_step ?
2669                                                 MIN2(scene->physics_settings.quick_cache_step, pid->cache->step) :
2670                                                 pid->cache->step;
2671                                 }
2672                         }
2673
2674                         BLI_freelistN(&pidlist);
2675                 }
2676
2677                 /* the no-group proxy case, we call update */
2678                 if (ob->proxy && ob->proxy_group == NULL) {
2679                         /* set pointer in library proxy target, for copying, but restore it */
2680                         ob->proxy->proxy_from = ob;
2681                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2682                         BKE_object_handle_update(scene, ob->proxy);
2683                 }
2684         
2685                 ob->recalc &= ~OB_RECALC_ALL;
2686         }
2687
2688         /* the case when this is a group proxy, object_update is called in group.c */
2689         if (ob->proxy) {
2690                 ob->proxy->proxy_from = ob;
2691                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2692         }
2693 }
2694
2695 void BKE_object_sculpt_modifiers_changed(Object *ob)
2696 {
2697         SculptSession *ss = ob->sculpt;
2698
2699         if (!ss->cache) {
2700                 /* we free pbvh on changes, except during sculpt since it can't deal with
2701                  * changing PVBH node organization, we hope topology does not change in
2702                  * the meantime .. weak */
2703                 if (ss->pbvh) {
2704                         BLI_pbvh_free(ss->pbvh);
2705                         ss->pbvh = NULL;
2706                 }
2707
2708                 free_sculptsession_deformMats(ob->sculpt);
2709         }
2710         else {
2711                 PBVHNode **nodes;
2712                 int n, totnode;
2713
2714                 BLI_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2715
2716                 for (n = 0; n < totnode; n++)
2717                         BLI_pbvh_node_mark_update(nodes[n]);
2718
2719                 MEM_freeN(nodes);
2720         }
2721 }
2722
2723 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
2724 {
2725         
2726         if (ob->data == NULL)
2727                 return 0;
2728         
2729         switch (GS(((ID *)ob->data)->name)) {
2730                 case ID_ME:
2731                 {
2732                         Mesh *me = ob->data;
2733                         if (r_texflag) *r_texflag = &me->texflag;
2734                         if (r_loc) *r_loc = me->loc;
2735                         if (r_size) *r_size = me->size;
2736                         if (r_rot) *r_rot = me->rot;
2737                         break;
2738                 }
2739                 case ID_CU:
2740                 {
2741                         Curve *cu = ob->data;
2742                         if (r_texflag) *r_texflag = &cu->texflag;
2743                         if (r_loc) *r_loc = cu->loc;
2744                         if (r_size) *r_size = cu->size;
2745                         if (r_rot) *r_rot = cu->rot;
2746                         break;
2747                 }
2748                 case ID_MB:
2749                 {
2750                         MetaBall *mb = ob->data;
2751                         if (r_texflag) *r_texflag = &mb->texflag;
2752                         if (r_loc) *r_loc = mb->loc;
2753                         if (r_size) *r_size = mb->size;
2754                         if (r_rot) *r_rot = mb->rot;
2755                         break;
2756                 }
2757                 default:
2758                         return 0;
2759         }
2760         return 1;
2761 }
2762
2763 /*
2764  * Test a bounding box for ray intersection
2765  * assumes the ray is already local to the boundbox space
2766  */
2767 int BKE_boundbox_ray_hit_check(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2768 {
2769         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2770                                               {3, 2, 6}, {3, 6, 7},
2771                                               {1, 2, 6}, {1, 6, 5},
2772                                               {5, 6, 7}, {4, 5, 7},
2773                                               {0, 3, 7}, {0, 4, 7},
2774                                               {0, 1, 5}, {0, 4, 5}};
2775         int result = 0;
2776         int i;
2777         
2778         for (i = 0; i < 12 && result == 0; i++) {
2779                 float lambda;
2780                 int v1, v2, v3;
2781                 v1 = triangle_indexes[i][0];
2782                 v2 = triangle_indexes[i][1];
2783                 v3 = triangle_indexes[i][2];
2784                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2785         }
2786         
2787         return result;
2788 }
2789
2790 static int pc_cmp(void *a, void *b)
2791 {
2792         LinkData *ad = a, *bd = b;
2793         if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2794                 return 1;
2795         else return 0;
2796 }
2797
2798 int BKE_object_insert_ptcache(Object *ob) 
2799 {
2800         LinkData *link = NULL;
2801         int i = 0;
2802
2803         BLI_sortlist(&ob->pc_ids, pc_cmp);
2804
2805         for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) {
2806                 int index = GET_INT_FROM_POINTER(link->data);
2807
2808                 if (i < index)
2809                         break;
2810         }
2811
2812         link = MEM_callocN(sizeof(LinkData), "PCLink");
2813         link->data = SET_INT_IN_POINTER(i);
2814         BLI_addtail(&ob->pc_ids, link);
2815
2816         return i;
2817 }
2818
2819 #if 0
2820 static int pc_findindex(ListBase *listbase, int index)
2821 {
2822         LinkData *link = NULL;
2823         int number = 0;
2824         
2825         if (listbase == NULL) return -1;
2826         
2827         link = listbase->first;
2828         while (link) {
2829                 if ((int)link->data == index)
2830                         return number;
2831                 
2832                 number++;
2833                 link = link->next;
2834         }
2835         
2836         return -1;
2837 }
2838
2839 void object_delete_ptcache(Object *ob, int index) 
2840 {
2841         int list_index = pc_findindex(&ob->pc_ids, index);
2842         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2843         BLI_freelinkN(&ob->pc_ids, link);
2844 }
2845 #endif
2846
2847 /* shape key utility function */
2848
2849 /************************* Mesh ************************/
2850 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
2851 {
2852         Mesh *me = ob->data;
2853         Key *key = me->key;
2854         KeyBlock *kb;
2855         int newkey = 0;
2856
2857         if (key == NULL) {
2858                 key = me->key = add_key((ID *)me);
2859                 key->type = KEY_RELATIVE;
2860                 newkey = 1;
2861         }
2862
2863         if (newkey || from_mix == FALSE) {
2864                 /* create from mesh */
2865                 kb = add_keyblock_ctime(key, name, FALSE);
2866                 mesh_to_key(me, kb);
2867         }
2868         else {
2869                 /* copy from current values */
2870                 float *data = do_ob_key(scene, ob);
2871
2872                 /* create new block with prepared data */
2873                 kb = add_keyblock_ctime(key, name, FALSE);
2874                 kb->data = data;
2875                 kb->totelem = me->totvert;
2876         }
2877
2878         return kb;
2879 }
2880 /************************* Lattice ************************/
2881 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
2882 {
2883         Lattice *lt = ob->data;
2884         Key *key = lt->key;
2885         KeyBlock *kb;
2886         int newkey = 0;
2887
2888         if (key == NULL) {
2889                 key = lt->key = add_key((ID *)lt);
2890                 key->type = KEY_RELATIVE;
2891                 newkey = 1;
2892         }
2893
2894         if (newkey || from_mix == FALSE) {
2895                 kb = add_keyblock_ctime(key, name, FALSE);
2896                 if (!newkey) {
2897                         KeyBlock *basekb = (KeyBlock *)key->block.first;
2898                         kb->data = MEM_dupallocN(basekb->data);
2899                         kb->totelem = basekb->totelem;
2900                 }
2901                 else {
2902                         latt_to_key(lt, kb);
2903                 }
2904         }
2905         else {
2906                 /* copy from current values */
2907                 float *data = do_ob_key(scene, ob);
2908
2909                 /* create new block with prepared data */
2910                 kb = add_keyblock_ctime(key, name, FALSE);
2911                 kb->totelem = lt->pntsu * lt->pntsv * lt->pntsw;
2912                 kb->data = data;
2913         }
2914
2915         return kb;
2916 }
2917 /************************* Curve ************************/
2918 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
2919 {
2920         Curve *cu = ob->data;
2921         Key *key = cu->key;
2922         KeyBlock *kb;
2923         ListBase *lb = BKE_curve_nurbs_get(cu);
2924         int newkey = 0;
2925
2926         if (key == NULL) {
2927                 key = cu->key = add_key((ID *)cu);
2928                 key->type = KEY_RELATIVE;
2929                 newkey = 1;
2930         }
2931
2932         if (newkey || from_mix == FALSE) {
2933                 /* create from curve */
2934                 kb = add_keyblock_ctime(key, name, FALSE);
2935                 if (!newkey) {
2936                         KeyBlock *basekb = (KeyBlock *)key->block.first;
2937                         kb->data = MEM_dupallocN(basekb->data);
2938                         kb->totelem = basekb->totelem;
2939                 }
2940                 else {
2941                         curve_to_key(cu, kb, lb);
2942                 }
2943         }
2944         else {
2945                 /* copy from current values */
2946                 float *data = do_ob_key(scene, ob);
2947
2948                 /* create new block with prepared data */
2949                 kb = add_keyblock_ctime(key, name, FALSE);
2950                 kb->totelem = BKE_nurbList_verts_count(lb);
2951                 kb->data = data;
2952         }
2953
2954         return kb;
2955 }
2956
2957 KeyBlock *BKE_object_insert_shape_key(Scene *scene, Object *ob, const char *name, int from_mix)
2958 {       
2959         switch (ob->type) {
2960                 case OB_MESH:
2961                         return insert_meshkey(scene, ob, name, from_mix);
2962                 case OB_CURVE:
2963                 case OB_SURF:
2964                         return insert_curvekey(scene, ob, name, from_mix);
2965                 case OB_LATTICE:
2966                         return insert_lattkey(scene, ob, name, from_mix);
2967                 default:
2968                         return NULL;
2969         }
2970
2971 }
2972
2973 /* most important if this is modified it should _always_ return True, in certain
2974  * cases false positives are hard to avoid (shape keys for example) */
2975 int BKE_object_is_modified(Scene *scene, Object *ob)
2976 {
2977         int flag = 0;
2978
2979         if (ob_get_key(ob)) {
2980                 flag |= eModifierMode_Render;
2981         }
2982         else {
2983                 ModifierData *md;
2984                 /* cloth */
2985                 for (md = modifiers_getVirtualModifierList(ob);
2986                      md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
2987                      md = md->next)
2988                 {
2989                         if ((flag & eModifierMode_Render) == 0 && modifier_isEnabled(scene, md, eModifierMode_Render))
2990                                 flag |= eModifierMode_Render;
2991
2992                         if ((flag & eModifierMode_Realtime) == 0 && modifier_isEnabled(scene, md, eModifierMode_Realtime))
2993                                 flag |= eModifierMode_Realtime;
2994                 }
2995         }
2996
2997         return flag;
2998 }
2999
3000 /* test if object is affected by deforming modifiers (for motion blur). again
3001  * most important is to avoid false positives, this is to skip computations
3002  * and we can still if there was actual deformation afterwards */
3003 int BKE_object_is_deform_modified(Scene *scene, Object *ob)
3004 {
3005         ModifierData *md;
3006         int flag = 0;
3007
3008         /* cloth */
3009         for (md = modifiers_getVirtualModifierList(ob);
3010              md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
3011              md = md->next)
3012         {
3013                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
3014
3015                 if (mti->type == eModifierTypeType_OnlyDeform) {
3016                         if (!(flag & eModifierMode_Render) && modifier_isEnabled(scene, md, eModifierMode_Render))
3017                                 flag |= eModifierMode_Render;
3018
3019                         if (!(flag & eModifierMode_Realtime) && modifier_isEnabled(scene, md, eModifierMode_Realtime))
3020                                 flag |= eModifierMode_Realtime;
3021                 }
3022         }
3023
3024         return flag;
3025 }
3026
3027 /* See if an object is using an animated modifier */
3028 int BKE_object_is_animated(Scene *scene, Object *ob)
3029 {
3030         ModifierData *md;
3031
3032         for (md = modifiers_getVirtualModifierList(ob); md; md = md->next)
3033                 if(modifier_dependsOnTime(md) && 
3034                         (modifier_isEnabled(scene, md, eModifierMode_Realtime) || 
3035                         modifier_isEnabled(scene, md, eModifierMode_Render)))
3036                         return 1;
3037         return 0;
3038 }
3039
3040 static void copy_object__forwardModifierLinks(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin)
3041 {
3042         /* this is copied from ID_NEW; it might be better to have a macro */
3043         if (*idpoin && (*idpoin)->newid) *idpoin = (*idpoin)->newid;
3044 }
3045
3046 void BKE_object_relink(Object *ob)
3047 {
3048         if (ob->id.lib)
3049                 return;
3050
3051         relink_constraints(&ob->constraints);
3052         if (ob->pose) {
3053                 bPoseChannel *chan;
3054                 for (chan = ob->pose->chanbase.first; chan; chan = chan->next) {
3055                         relink_constraints(&chan->constraints);
3056                 }
3057         }
3058         modifiers_foreachIDLink(ob, copy_object__forwardModifierLinks, NULL);
3059
3060         if (ob->adt)
3061                 BKE_relink_animdata(ob->adt);
3062
3063         ID_NEW(ob->parent);
3064
3065         ID_NEW(ob->proxy);
3066         ID_NEW(ob->proxy_group);
3067 }
3068
3069 MovieClip *BKE_object_movieclip_get(Scene *scene, Object *ob, int use_default)
3070 {
3071         MovieClip *clip = use_default ? scene->clip : NULL;
3072         bConstraint *con = ob->constraints.first, *scon = NULL;
3073
3074         while (con) {
3075                 if (con->type == CONSTRAINT_TYPE_CAMERASOLVER) {
3076                         if (scon == NULL || (scon->flag & CONSTRAINT_OFF))
3077                                 scon = con;
3078                 }
3079
3080                 con = con->next;
3081         }
3082
3083         if (scon) {
3084                 bCameraSolverConstraint *solver = scon->data;
3085                 if ((solver->flag & CAMERASOLVER_ACTIVECLIP) == 0)
3086                         clip = solver->clip;
3087                 else
3088                         clip = scene->clip;
3089         }
3090
3091         return clip;
3092 }