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