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