code cleanup: change order of args in void BKE_object_where_is_calc_time_ex() so...
[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 #include "DNA_rigidbody_types.h"
62
63 #include "BLI_blenlib.h"
64 #include "BLI_math.h"
65 #include "BLI_utildefines.h"
66 #include "BLI_linklist.h"
67
68 #include "BKE_pbvh.h"
69 #include "BKE_main.h"
70 #include "BKE_global.h"
71 #include "BKE_idprop.h"
72 #include "BKE_armature.h"
73 #include "BKE_action.h"
74 #include "BKE_bullet.h"
75 #include "BKE_colortools.h"
76 #include "BKE_deform.h"
77 #include "BKE_DerivedMesh.h"
78 #include "BKE_animsys.h"
79 #include "BKE_anim.h"
80 #include "BKE_constraint.h"
81 #include "BKE_curve.h"
82 #include "BKE_displist.h"
83 #include "BKE_effect.h"
84 #include "BKE_fcurve.h"
85 #include "BKE_group.h"
86 #include "BKE_icons.h"
87 #include "BKE_image.h"
88 #include "BKE_key.h"
89 #include "BKE_lamp.h"
90 #include "BKE_lattice.h"
91 #include "BKE_library.h"
92 #include "BKE_mesh.h"
93 #include "BKE_tessmesh.h"
94 #include "BKE_mball.h"
95 #include "BKE_modifier.h"
96 #include "BKE_node.h"
97 #include "BKE_object.h"
98 #include "BKE_paint.h"
99 #include "BKE_particle.h"
100 #include "BKE_pointcache.h"
101 #include "BKE_property.h"
102 #include "BKE_rigidbody.h"
103 #include "BKE_sca.h"
104 #include "BKE_scene.h"
105 #include "BKE_sequencer.h"
106 #include "BKE_speaker.h"
107 #include "BKE_softbody.h"
108 #include "BKE_material.h"
109 #include "BKE_camera.h"
110
111 #ifdef WITH_MOD_FLUID
112 #include "LBM_fluidsim.h"
113 #endif
114
115 #ifdef WITH_PYTHON
116 #include "BPY_extern.h"
117 #endif
118
119 #include "GPU_material.h"
120
121 /* Local function protos */
122 float originmat[3][3];  /* after BKE_object_where_is_calc(), can be used in other functions (bad!) */
123
124 void BKE_object_workob_clear(Object *workob)
125 {
126         memset(workob, 0, sizeof(Object));
127         
128         workob->size[0] = workob->size[1] = workob->size[2] = 1.0f;
129         workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f;
130         workob->rotmode = ROT_MODE_EUL;
131 }
132
133 void BKE_object_update_base_layer(struct Scene *scene, Object *ob)
134 {
135         Base *base = scene->base.first;
136
137         while (base) {
138                 if (base->object == ob) base->lay = ob->lay;
139                 base = base->next;
140         }
141 }
142
143 void BKE_object_free_particlesystems(Object *ob)
144 {
145         while (ob->particlesystem.first) {
146                 ParticleSystem *psys = ob->particlesystem.first;
147                 
148                 BLI_remlink(&ob->particlesystem, psys);
149                 
150                 psys_free(ob, psys);
151         }
152 }
153
154 void BKE_object_free_softbody(Object *ob)
155 {
156         if (ob->soft) {
157                 sbFree(ob->soft);
158                 ob->soft = NULL;
159         }
160 }
161
162 void BKE_object_free_bulletsoftbody(Object *ob)
163 {
164         if (ob->bsoft) {
165                 bsbFree(ob->bsoft);
166                 ob->bsoft = NULL;
167         }
168 }
169
170 void BKE_object_free_modifiers(Object *ob)
171 {
172         while (ob->modifiers.first) {
173                 ModifierData *md = ob->modifiers.first;
174                 
175                 BLI_remlink(&ob->modifiers, md);
176                 
177                 modifier_free(md);
178         }
179
180         /* particle modifiers were freed, so free the particlesystems as well */
181         BKE_object_free_particlesystems(ob);
182
183         /* same for softbody */
184         BKE_object_free_softbody(ob);
185 }
186
187 int BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
188 {
189         ModifierTypeInfo *mti;
190
191         mti = modifierType_getInfo(modifier_type);
192
193         if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
194               (ob->type == OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
195         {
196                 return FALSE;
197         }
198
199         return TRUE;
200 }
201
202 void BKE_object_link_modifiers(struct Object *ob_dst, struct Object *ob_src)
203 {
204         ModifierData *md;
205         BKE_object_free_modifiers(ob_dst);
206
207         if (!ELEM5(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
208                 /* only objects listed above can have modifiers and linking them to objects
209                  * which doesn't have modifiers stack is quite silly */
210                 return;
211         }
212
213         for (md = ob_src->modifiers.first; md; md = md->next) {
214                 ModifierData *nmd = NULL;
215
216                 if (ELEM4(md->type,
217                           eModifierType_Hook,
218                           eModifierType_Softbody,
219                           eModifierType_ParticleInstance,
220                           eModifierType_Collision))
221                 {
222                         continue;
223                 }
224
225                 if (!BKE_object_support_modifier_type_check(ob_dst, md->type))
226                         continue;
227
228                 nmd = modifier_new(md->type);
229                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
230                 modifier_copyData(md, nmd);
231                 BLI_addtail(&ob_dst->modifiers, nmd);
232                 modifier_unique_name(&ob_dst->modifiers, nmd);
233         }
234
235         BKE_object_copy_particlesystems(ob_dst, ob_src);
236         BKE_object_copy_softbody(ob_dst, ob_src);
237
238         /* TODO: smoke?, cloth? */
239 }
240
241 /* here we will collect all local displist stuff */
242 /* also (ab)used in depsgraph */
243 void BKE_object_free_display(Object *ob)
244 {
245         if (ob->derivedDeform) {
246                 ob->derivedDeform->needsFree = 1;
247                 ob->derivedDeform->release(ob->derivedDeform);
248                 ob->derivedDeform = NULL;
249         }
250         if (ob->derivedFinal) {
251                 ob->derivedFinal->needsFree = 1;
252                 ob->derivedFinal->release(ob->derivedFinal);
253                 ob->derivedFinal = NULL;
254         }
255         
256         BKE_displist_free(&ob->disp);
257 }
258
259 void free_sculptsession_deformMats(SculptSession *ss)
260 {
261         if (ss->orig_cos) MEM_freeN(ss->orig_cos);
262         if (ss->deform_cos) MEM_freeN(ss->deform_cos);
263         if (ss->deform_imats) MEM_freeN(ss->deform_imats);
264
265         ss->orig_cos = NULL;
266         ss->deform_cos = NULL;
267         ss->deform_imats = NULL;
268 }
269
270 /* Write out the sculpt dynamic-topology BMesh to the Mesh */
271 void sculptsession_bm_to_me(struct Object *ob, int reorder)
272 {
273         if (ob && ob->sculpt) {
274                 SculptSession *ss = ob->sculpt;
275
276                 if (ss->bm) {
277                         if (ob->data) {
278                                 BMIter iter;
279                                 BMFace *efa;
280                                 BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) {
281                                         BM_elem_flag_set(efa, BM_ELEM_SMOOTH,
282                                                          ss->bm_smooth_shading);
283                                 }
284                                 if (reorder)
285                                         BM_log_mesh_elems_reorder(ss->bm, ss->bm_log);
286                                 BM_mesh_bm_to_me(ss->bm, ob->data, FALSE);
287                         }
288                 }
289         }
290 }
291
292 void free_sculptsession(Object *ob)
293 {
294         if (ob && ob->sculpt) {
295                 SculptSession *ss = ob->sculpt;
296                 DerivedMesh *dm = ob->derivedFinal;
297
298                 if (ss->bm) {
299                         sculptsession_bm_to_me(ob, TRUE);
300                         BM_mesh_free(ss->bm);
301                 }
302
303                 if (ss->pbvh)
304                         BKE_pbvh_free(ss->pbvh);
305                 if (ss->bm_log)
306                         BM_log_free(ss->bm_log);
307
308                 if (dm && dm->getPBVH)
309                         dm->getPBVH(NULL, dm);  /* signal to clear */
310
311                 if (ss->texcache)
312                         MEM_freeN(ss->texcache);
313
314                 if (ss->tex_pool)
315                         BKE_image_pool_free(ss->tex_pool);
316
317                 if (ss->layer_co)
318                         MEM_freeN(ss->layer_co);
319
320                 if (ss->orig_cos)
321                         MEM_freeN(ss->orig_cos);
322                 if (ss->deform_cos)
323                         MEM_freeN(ss->deform_cos);
324                 if (ss->deform_imats)
325                         MEM_freeN(ss->deform_imats);
326
327                 MEM_freeN(ss);
328
329                 ob->sculpt = NULL;
330         }
331 }
332
333
334 /* do not free object itself */
335 void BKE_object_free(Object *ob)
336 {
337         int a;
338         
339         BKE_object_free_display(ob);
340         
341         /* disconnect specific data, but not for lib data (might be indirect data, can get relinked) */
342         if (ob->data) {
343                 ID *id = ob->data;
344                 id->us--;
345                 if (id->us == 0 && id->lib == NULL) {
346                         switch (ob->type) {
347                                 case OB_MESH:
348                                         BKE_mesh_unlink((Mesh *)id);
349                                         break;
350                                 case OB_CURVE:
351                                         BKE_curve_unlink((Curve *)id);
352                                         break;
353                                 case OB_MBALL:
354                                         BKE_mball_unlink((MetaBall *)id);
355                                         break;
356                         }
357                 }
358                 ob->data = NULL;
359         }
360
361         if (ob->mat) {
362                 for (a = 0; a < ob->totcol; a++) {
363                         if (ob->mat[a]) ob->mat[a]->id.us--;
364                 }
365                 MEM_freeN(ob->mat);
366         }
367         if (ob->matbits) MEM_freeN(ob->matbits);
368         ob->mat = NULL;
369         ob->matbits = NULL;
370         if (ob->bb) MEM_freeN(ob->bb); 
371         ob->bb = NULL;
372         if (ob->adt) BKE_free_animdata((ID *)ob);
373         if (ob->poselib) ob->poselib->id.us--;
374         if (ob->gpd) ((ID *)ob->gpd)->us--;
375         if (ob->defbase.first)
376                 BLI_freelistN(&ob->defbase);
377         if (ob->pose)
378                 BKE_pose_free(ob->pose);
379         if (ob->mpath)
380                 animviz_free_motionpath(ob->mpath);
381         BKE_bproperty_free_list(&ob->prop);
382         BKE_object_free_modifiers(ob);
383         
384         free_sensors(&ob->sensors);
385         free_controllers(&ob->controllers);
386         free_actuators(&ob->actuators);
387         
388         BKE_free_constraints(&ob->constraints);
389         
390         free_partdeflect(ob->pd);
391         BKE_rigidbody_free_object(ob);
392         BKE_rigidbody_free_constraint(ob);
393
394         if (ob->soft) sbFree(ob->soft);
395         if (ob->bsoft) bsbFree(ob->bsoft);
396         if (ob->gpulamp.first) GPU_lamp_free(ob);
397
398         free_sculptsession(ob);
399
400         if (ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
401 }
402
403 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
404 {
405         Object *unlinkOb = userData;
406
407         if (*obpoin == unlinkOb) {
408                 *obpoin = NULL;
409                 ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME; // XXX: should this just be OB_RECALC_DATA?
410         }
411 }
412
413 void BKE_object_unlink(Object *ob)
414 {
415         Main *bmain = G.main;
416         Object *obt;
417         Material *mat;
418         World *wrld;
419         bScreen *sc;
420         Scene *sce;
421         Curve *cu;
422         Tex *tex;
423         Group *group;
424         Camera *camera;
425         bConstraint *con;
426         //bActionStrip *strip; // XXX animsys 
427         ModifierData *md;
428         ARegion *ar;
429         RegionView3D *rv3d;
430         int a, found;
431         
432         unlink_controllers(&ob->controllers);
433         unlink_actuators(&ob->actuators);
434         
435         /* check all objects: parents en bevels and fields, also from libraries */
436         /* FIXME: need to check all animation blocks (drivers) */
437         obt = bmain->object.first;
438         while (obt) {
439                 if (obt->proxy == ob)
440                         obt->proxy = NULL;
441                 if (obt->proxy_from == ob) {
442                         obt->proxy_from = NULL;
443                         obt->recalc |= OB_RECALC_OB;
444                 }
445                 if (obt->proxy_group == ob)
446                         obt->proxy_group = NULL;
447                 
448                 if (obt->parent == ob) {
449                         obt->parent = NULL;
450                         obt->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
451                 }
452                 
453                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
454                 
455                 if (ELEM(obt->type, OB_CURVE, OB_FONT)) {
456                         cu = obt->data;
457
458                         if (cu->bevobj == ob) {
459                                 cu->bevobj = NULL;
460                                 obt->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
461                         }
462                         if (cu->taperobj == ob) {
463                                 cu->taperobj = NULL;
464                                 obt->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
465                         }
466                         if (cu->textoncurve == ob) {
467                                 cu->textoncurve = NULL;
468                                 obt->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
469                         }
470                 }
471                 else if (obt->type == OB_ARMATURE && obt->pose) {
472                         bPoseChannel *pchan;
473                         for (pchan = obt->pose->chanbase.first; pchan; pchan = pchan->next) {
474                                 for (con = pchan->constraints.first; con; con = con->next) {
475                                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
476                                         ListBase targets = {NULL, NULL};
477                                         bConstraintTarget *ct;
478                                         
479                                         if (cti && cti->get_constraint_targets) {
480                                                 cti->get_constraint_targets(con, &targets);
481                                                 
482                                                 for (ct = targets.first; ct; ct = ct->next) {
483                                                         if (ct->tar == ob) {
484                                                                 ct->tar = NULL;
485                                                                 ct->subtarget[0] = '\0';
486                                                                 obt->recalc |= OB_RECALC_DATA;
487                                                         }
488                                                 }
489                                                 
490                                                 if (cti->flush_constraint_targets)
491                                                         cti->flush_constraint_targets(con, &targets, 0);
492                                         }
493                                 }
494                                 if (pchan->custom == ob)
495                                         pchan->custom = NULL;
496                         }
497                 }
498                 else if (ELEM(OB_MBALL, ob->type, obt->type)) {
499                         if (BKE_mball_is_basis_for(obt, ob))
500                                 obt->recalc |= OB_RECALC_DATA;
501                 }
502                 
503                 sca_remove_ob_poin(obt, ob);
504                 
505                 for (con = obt->constraints.first; con; con = con->next) {
506                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
507                         ListBase targets = {NULL, NULL};
508                         bConstraintTarget *ct;
509                         
510                         if (cti && cti->get_constraint_targets) {
511                                 cti->get_constraint_targets(con, &targets);
512                                 
513                                 for (ct = targets.first; ct; ct = ct->next) {
514                                         if (ct->tar == ob) {
515                                                 ct->tar = NULL;
516                                                 ct->subtarget[0] = '\0';
517                                                 obt->recalc |= OB_RECALC_DATA;
518                                         }
519                                 }
520                                 
521                                 if (cti->flush_constraint_targets)
522                                         cti->flush_constraint_targets(con, &targets, 0);
523                         }
524                 }
525                 
526                 /* object is deflector or field */
527                 if (ob->pd) {
528                         if (obt->soft)
529                                 obt->recalc |= OB_RECALC_DATA;
530
531                         /* cloth */
532                         for (md = obt->modifiers.first; md; md = md->next)
533                                 if (md->type == eModifierType_Cloth)
534                                         obt->recalc |= OB_RECALC_DATA;
535                 }
536                 
537                 /* strips */
538 #if 0 // XXX old animation system
539                 for (strip = obt->nlastrips.first; strip; strip = strip->next) {
540                         if (strip->object == ob)
541                                 strip->object = NULL;
542                         
543                         if (strip->modifiers.first) {
544                                 bActionModifier *amod;
545                                 for (amod = strip->modifiers.first; amod; amod = amod->next)
546                                         if (amod->ob == ob)
547                                                 amod->ob = NULL;
548                         }
549                 }
550 #endif // XXX old animation system
551
552                 /* particle systems */
553                 if (obt->particlesystem.first) {
554                         ParticleSystem *tpsys = obt->particlesystem.first;
555                         for (; tpsys; tpsys = tpsys->next) {
556                                 BoidState *state = NULL;
557                                 BoidRule *rule = NULL;
558
559                                 ParticleTarget *pt = tpsys->targets.first;
560                                 for (; pt; pt = pt->next) {
561                                         if (pt->ob == ob) {
562                                                 pt->ob = NULL;
563                                                 obt->recalc |= OB_RECALC_DATA;
564                                                 break;
565                                         }
566                                 }
567
568                                 if (tpsys->target_ob == ob) {
569                                         tpsys->target_ob = NULL;
570                                         obt->recalc |= OB_RECALC_DATA;
571                                 }
572
573                                 if (tpsys->part->dup_ob == ob)
574                                         tpsys->part->dup_ob = NULL;
575
576                                 if (tpsys->part->phystype == PART_PHYS_BOIDS) {
577                                         ParticleData *pa;
578                                         BoidParticle *bpa;
579                                         int p;
580
581                                         for (p = 0, pa = tpsys->particles; p < tpsys->totpart; p++, pa++) {
582                                                 bpa = pa->boid;
583                                                 if (bpa->ground == ob)
584                                                         bpa->ground = NULL;
585                                         }
586                                 }
587                                 if (tpsys->part->boids) {
588                                         for (state = tpsys->part->boids->states.first; state; state = state->next) {
589                                                 for (rule = state->rules.first; rule; rule = rule->next) {
590                                                         if (rule->type == eBoidRuleType_Avoid) {
591                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid *)rule;
592                                                                 if (gabr->ob == ob)
593                                                                         gabr->ob = NULL;
594                                                         }
595                                                         else if (rule->type == eBoidRuleType_FollowLeader) {
596                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader *)rule;
597                                                                 if (flbr->ob == ob)
598                                                                         flbr->ob = NULL;
599                                                         }
600                                                 }
601                                         }
602                                 }
603                         }
604                         if (ob->pd)
605                                 obt->recalc |= OB_RECALC_DATA;
606                 }
607
608                 obt = obt->id.next;
609         }
610         
611         /* materials */
612         mat = bmain->mat.first;
613         while (mat) {
614         
615                 for (a = 0; a < MAX_MTEX; a++) {
616                         if (mat->mtex[a] && ob == mat->mtex[a]->object) {
617                                 /* actually, test for lib here... to do */
618                                 mat->mtex[a]->object = NULL;
619                         }
620                 }
621
622                 mat = mat->id.next;
623         }
624         
625         /* textures */
626         for (tex = bmain->tex.first; tex; tex = tex->id.next) {
627                 if (tex->env && (ob == tex->env->object)) tex->env->object = NULL;
628                 if (tex->pd  && (ob == tex->pd->object)) tex->pd->object = NULL;
629                 if (tex->vd  && (ob == tex->vd->object)) tex->vd->object = NULL;
630         }
631
632         /* worlds */
633         wrld = bmain->world.first;
634         while (wrld) {
635                 if (wrld->id.lib == NULL) {
636                         for (a = 0; a < MAX_MTEX; a++) {
637                                 if (wrld->mtex[a] && ob == wrld->mtex[a]->object)
638                                         wrld->mtex[a]->object = NULL;
639                         }
640                 }
641                 
642                 wrld = wrld->id.next;
643         }
644                 
645         /* scenes */
646         sce = bmain->scene.first;
647         while (sce) {
648                 if (sce->id.lib == NULL) {
649                         if (sce->camera == ob) sce->camera = NULL;
650                         if (sce->toolsettings->skgen_template == ob) sce->toolsettings->skgen_template = NULL;
651                         if (sce->toolsettings->particle.object == ob) sce->toolsettings->particle.object = NULL;
652
653 #ifdef DURIAN_CAMERA_SWITCH
654                         {
655                                 TimeMarker *m;
656
657                                 for (m = sce->markers.first; m; m = m->next) {
658                                         if (m->camera == ob)
659                                                 m->camera = NULL;
660                                 }
661                         }
662 #endif
663                         if (sce->ed) {
664                                 Sequence *seq;
665                                 SEQ_BEGIN(sce->ed, seq)
666                                 {
667                                         if (seq->scene_camera == ob) {
668                                                 seq->scene_camera = NULL;
669                                         }
670                                 }
671                                 SEQ_END
672                         }
673                 }
674
675                 sce = sce->id.next;
676         }
677         
678         /* screens */
679         sc = bmain->screen.first;
680         while (sc) {
681                 ScrArea *sa = sc->areabase.first;
682                 while (sa) {
683                         SpaceLink *sl;
684
685                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
686                                 if (sl->spacetype == SPACE_VIEW3D) {
687                                         View3D *v3d = (View3D *) sl;
688
689                                         /* found doesn't need to be set here */
690                                         if (v3d->ob_centre == ob) {
691                                                 v3d->ob_centre = NULL;
692                                                 v3d->ob_centre_bone[0] = '\0';
693                                         }
694                                         if (v3d->localvd && v3d->localvd->ob_centre == ob) {
695                                                 v3d->localvd->ob_centre = NULL;
696                                                 v3d->localvd->ob_centre_bone[0] = '\0';
697                                         }
698
699                                         found = 0;
700                                         if (v3d->camera == ob) {
701                                                 v3d->camera = NULL;
702                                                 found = 1;
703                                         }
704                                         if (v3d->localvd && v3d->localvd->camera == ob) {
705                                                 v3d->localvd->camera = NULL;
706                                                 found += 2;
707                                         }
708
709                                         if (found) {
710                                                 if (sa->spacetype == SPACE_VIEW3D) {
711                                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
712                                                                 if (ar->regiontype == RGN_TYPE_WINDOW) {
713                                                                         rv3d = (RegionView3D *)ar->regiondata;
714                                                                         if (found == 1 || found == 3) {
715                                                                                 if (rv3d->persp == RV3D_CAMOB)
716                                                                                         rv3d->persp = RV3D_PERSP;
717                                                                         }
718                                                                         if (found == 2 || found == 3) {
719                                                                                 if (rv3d->localvd && rv3d->localvd->persp == RV3D_CAMOB)
720                                                                                         rv3d->localvd->persp = RV3D_PERSP;
721                                                                         }
722                                                                 }
723                                                         }
724                                                 }
725                                         }
726                                 }
727                                 else if (sl->spacetype == SPACE_OUTLINER) {
728                                         SpaceOops *so = (SpaceOops *)sl;
729
730                                         if (so->treestore) {
731                                                 TreeStoreElem *tselem = so->treestore->data;
732                                                 int i;
733                                                 for (i = 0; i < so->treestore->usedelem; i++, tselem++) {
734                                                         if (tselem->id == (ID *)ob) tselem->id = NULL;
735                                                 }
736                                         }
737                                 }
738                                 else if (sl->spacetype == SPACE_BUTS) {
739                                         SpaceButs *sbuts = (SpaceButs *)sl;
740
741                                         if (sbuts->pinid == (ID *)ob) {
742                                                 sbuts->flag &= ~SB_PIN_CONTEXT;
743                                                 sbuts->pinid = NULL;
744                                         }
745                                 }
746                         }
747
748                         sa = sa->next;
749                 }
750                 sc = sc->id.next;
751         }
752
753         /* groups */
754         group = bmain->group.first;
755         while (group) {
756                 rem_from_group(group, ob, NULL, NULL);
757                 group = group->id.next;
758         }
759         
760         /* cameras */
761         camera = bmain->camera.first;
762         while (camera) {
763                 if (camera->dof_ob == ob) {
764                         camera->dof_ob = NULL;
765                 }
766                 camera = camera->id.next;
767         }
768 }
769
770 /* actual check for internal data, not context or flags */
771 int BKE_object_is_in_editmode(Object *ob)
772 {
773         if (ob->data == NULL)
774                 return 0;
775         
776         if (ob->type == OB_MESH) {
777                 Mesh *me = ob->data;
778                 if (me->edit_btmesh)
779                         return 1;
780         }
781         else if (ob->type == OB_ARMATURE) {
782                 bArmature *arm = ob->data;
783                 
784                 if (arm->edbo)
785                         return 1;
786         }
787         else if (ob->type == OB_FONT) {
788                 Curve *cu = ob->data;
789                 
790                 if (cu->editfont)
791                         return 1;
792         }
793         else if (ob->type == OB_MBALL) {
794                 MetaBall *mb = ob->data;
795                 
796                 if (mb->editelems)
797                         return 1;
798         }
799         else if (ob->type == OB_LATTICE) {
800                 Lattice *lt = ob->data;
801                 
802                 if (lt->editlatt)
803                         return 1;
804         }
805         else if (ob->type == OB_SURF || ob->type == OB_CURVE) {
806                 Curve *cu = ob->data;
807
808                 if (cu->editnurb)
809                         return 1;
810         }
811         return 0;
812 }
813
814 int BKE_object_exists_check(Object *obtest)
815 {
816         Object *ob;
817         
818         if (obtest == NULL) return 0;
819         
820         ob = G.main->object.first;
821         while (ob) {
822                 if (ob == obtest) return 1;
823                 ob = ob->id.next;
824         }
825         return 0;
826 }
827
828 /* *************************************************** */
829
830 void *BKE_object_obdata_add_from_type(int type)
831 {
832         switch (type) {
833                 case OB_MESH:      return BKE_mesh_add(G.main, "Mesh");
834                 case OB_CURVE:     return BKE_curve_add(G.main, "Curve", OB_CURVE);
835                 case OB_SURF:      return BKE_curve_add(G.main, "Surf", OB_SURF);
836                 case OB_FONT:      return BKE_curve_add(G.main, "Text", OB_FONT);
837                 case OB_MBALL:     return BKE_mball_add(G.main, "Meta");
838                 case OB_CAMERA:    return BKE_camera_add(G.main, "Camera");
839                 case OB_LAMP:      return BKE_lamp_add(G.main, "Lamp");
840                 case OB_LATTICE:   return BKE_lattice_add(G.main, "Lattice");
841                 case OB_ARMATURE:  return BKE_armature_add(G.main, "Armature");
842                 case OB_SPEAKER:   return BKE_speaker_add(G.main, "Speaker");
843                 case OB_EMPTY:     return NULL;
844                 default:
845                         printf("BKE_object_obdata_add_from_type: Internal error, bad type: %d\n", type);
846                         return NULL;
847         }
848 }
849
850 static const char *get_obdata_defname(int type)
851 {
852         switch (type) {
853                 case OB_MESH: return "Mesh";
854                 case OB_CURVE: return "Curve";
855                 case OB_SURF: return "Surf";
856                 case OB_FONT: return "Text";
857                 case OB_MBALL: return "Mball";
858                 case OB_CAMERA: return "Camera";
859                 case OB_LAMP: return "Lamp";
860                 case OB_LATTICE: return "Lattice";
861                 case OB_ARMATURE: return "Armature";
862                 case OB_SPEAKER: return "Speaker";
863                 case OB_EMPTY: return "Empty";
864                 default:
865                         printf("get_obdata_defname: Internal error, bad type: %d\n", type);
866                         return "Empty";
867         }
868 }
869
870 /* more general add: creates minimum required data, but without vertices etc. */
871 Object *BKE_object_add_only_object(Main *bmain, int type, const char *name)
872 {
873         Object *ob;
874
875         if (!name)
876                 name = get_obdata_defname(type);
877
878         ob = BKE_libblock_alloc(&bmain->object, ID_OB, name);
879
880         /* default object vars */
881         ob->type = type;
882         
883         ob->col[0] = ob->col[1] = ob->col[2] = 1.0;
884         ob->col[3] = 1.0;
885         
886         ob->size[0] = ob->size[1] = ob->size[2] = 1.0;
887         ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0;
888         
889         /* objects should default to having Euler XYZ rotations, 
890          * but rotations default to quaternions 
891          */
892         ob->rotmode = ROT_MODE_EUL;
893
894         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
895         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
896
897         unit_qt(ob->quat);
898         unit_qt(ob->dquat);
899
900         /* rotation locks should be 4D for 4 component rotations by default... */
901         ob->protectflag = OB_LOCK_ROT4D;
902         
903         unit_m4(ob->constinv);
904         unit_m4(ob->parentinv);
905         unit_m4(ob->obmat);
906         ob->dt = OB_TEXTURE;
907         ob->empty_drawtype = OB_PLAINAXES;
908         ob->empty_drawsize = 1.0;
909
910         if (type == OB_CAMERA || type == OB_LAMP || type == OB_SPEAKER) {
911                 ob->trackflag = OB_NEGZ;
912                 ob->upflag = OB_POSY;
913         }
914         else {
915                 ob->trackflag = OB_POSY;
916                 ob->upflag = OB_POSZ;
917         }
918         
919         ob->dupon = 1; ob->dupoff = 0;
920         ob->dupsta = 1; ob->dupend = 100;
921         ob->dupfacesca = 1.0;
922
923         /* Game engine defaults*/
924         ob->mass = ob->inertia = 1.0f;
925         ob->formfactor = 0.4f;
926         ob->damping = 0.04f;
927         ob->rdamping = 0.1f;
928         ob->anisotropicFriction[0] = 1.0f;
929         ob->anisotropicFriction[1] = 1.0f;
930         ob->anisotropicFriction[2] = 1.0f;
931         ob->gameflag = OB_PROP | OB_COLLISION;
932         ob->margin = 0.0;
933         ob->init_state = 1;
934         ob->state = 1;
935         /* ob->pad3 == Contact Processing Threshold */
936         ob->m_contactProcessingThreshold = 1.0f;
937         ob->obstacleRad = 1.0f;
938         ob->step_height = 0.15f;
939         ob->jump_speed = 10.0f;
940         ob->fall_speed = 55.0f;
941         ob->col_group = 0x01;
942         ob->col_mask = 0xff;
943
944         /* NT fluid sim defaults */
945         ob->fluidsimSettings = NULL;
946
947         ob->pc_ids.first = ob->pc_ids.last = NULL;
948         
949         /* Animation Visualization defaults */
950         animviz_settings_init(&ob->avs);
951
952         return ob;
953 }
954
955 /* general add: to scene, with layer from area and default name */
956 /* creates minimum required data, but without vertices etc. */
957 Object *BKE_object_add(struct Scene *scene, int type)
958 {
959         Object *ob;
960         Base *base;
961         char name[MAX_ID_NAME];
962
963         BLI_strncpy(name, get_obdata_defname(type), sizeof(name));
964         ob = BKE_object_add_only_object(G.main, type, name);
965
966         ob->data = BKE_object_obdata_add_from_type(type);
967
968         ob->lay = scene->lay;
969         
970         base = BKE_scene_base_add(scene, ob);
971         BKE_scene_base_deselect_all(scene);
972         BKE_scene_base_select(scene, base);
973         ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
974
975         return ob;
976 }
977
978 SoftBody *copy_softbody(SoftBody *sb, int copy_caches)
979 {
980         SoftBody *sbn;
981         
982         if (sb == NULL) return(NULL);
983         
984         sbn = MEM_dupallocN(sb);
985
986         if (copy_caches == FALSE) {
987                 sbn->totspring = sbn->totpoint = 0;
988                 sbn->bpoint = NULL;
989                 sbn->bspring = NULL;
990         }
991         else {
992                 sbn->totspring = sb->totspring;
993                 sbn->totpoint = sb->totpoint;
994
995                 if (sbn->bpoint) {
996                         int i;
997
998                         sbn->bpoint = MEM_dupallocN(sbn->bpoint);
999
1000                         for (i = 0; i < sbn->totpoint; i++) {
1001                                 if (sbn->bpoint[i].springs)
1002                                         sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs);
1003                         }
1004                 }
1005
1006                 if (sb->bspring)
1007                         sbn->bspring = MEM_dupallocN(sb->bspring);
1008         }
1009         
1010         sbn->keys = NULL;
1011         sbn->totkey = sbn->totpointkey = 0;
1012         
1013         sbn->scratch = NULL;
1014
1015         sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches);
1016
1017         if (sb->effector_weights)
1018                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1019
1020         return sbn;
1021 }
1022
1023 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1024 {
1025         BulletSoftBody *bsbn;
1026
1027         if (bsb == NULL)
1028                 return NULL;
1029         bsbn = MEM_dupallocN(bsb);
1030         /* no pointer in this structure yet */
1031         return bsbn;
1032 }
1033
1034 static ParticleSystem *copy_particlesystem(ParticleSystem *psys)
1035 {
1036         ParticleSystem *psysn;
1037         ParticleData *pa;
1038         int p;
1039
1040         psysn = MEM_dupallocN(psys);
1041         psysn->particles = MEM_dupallocN(psys->particles);
1042         psysn->child = MEM_dupallocN(psys->child);
1043
1044         if (psys->part->type == PART_HAIR) {
1045                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++)
1046                         pa->hair = MEM_dupallocN(pa->hair);
1047         }
1048
1049         if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
1050                 ParticleKey *key = psysn->particles->keys;
1051                 BoidParticle *boid = psysn->particles->boid;
1052
1053                 if (key)
1054                         key = MEM_dupallocN(key);
1055                 
1056                 if (boid)
1057                         boid = MEM_dupallocN(boid);
1058                 
1059                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) {
1060                         if (boid)
1061                                 pa->boid = boid++;
1062                         if (key) {
1063                                 pa->keys = key;
1064                                 key += pa->totkey;
1065                         }
1066                 }
1067         }
1068
1069         if (psys->clmd) {
1070                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1071                 modifier_copyData((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd);
1072                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1073         }
1074
1075         BLI_duplicatelist(&psysn->targets, &psys->targets);
1076
1077         psysn->pathcache = NULL;
1078         psysn->childcache = NULL;
1079         psysn->edit = NULL;
1080         psysn->frand = NULL;
1081         psysn->pdd = NULL;
1082         psysn->effectors = NULL;
1083         
1084         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1085         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1086         psysn->renderdata = NULL;
1087         
1088         psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, FALSE);
1089
1090         /* XXX - from reading existing code this seems correct but intended usage of
1091          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1092         if (psysn->clmd) {
1093                 psysn->clmd->point_cache = psysn->pointcache;
1094         }
1095
1096         id_us_plus((ID *)psysn->part);
1097
1098         return psysn;
1099 }
1100
1101 void BKE_object_copy_particlesystems(Object *obn, Object *ob)
1102 {
1103         ParticleSystem *psys, *npsys;
1104         ModifierData *md;
1105
1106         if (obn->type != OB_MESH) {
1107                 /* currently only mesh objects can have soft body */
1108                 return;
1109         }
1110
1111         obn->particlesystem.first = obn->particlesystem.last = NULL;
1112         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
1113                 npsys = copy_particlesystem(psys);
1114
1115                 BLI_addtail(&obn->particlesystem, npsys);
1116
1117                 /* need to update particle modifiers too */
1118                 for (md = obn->modifiers.first; md; md = md->next) {
1119                         if (md->type == eModifierType_ParticleSystem) {
1120                                 ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md;
1121                                 if (psmd->psys == psys)
1122                                         psmd->psys = npsys;
1123                         }
1124                         else if (md->type == eModifierType_DynamicPaint) {
1125                                 DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1126                                 if (pmd->brush) {
1127                                         if (pmd->brush->psys == psys) {
1128                                                 pmd->brush->psys = npsys;
1129                                         }
1130                                 }
1131                         }
1132                         else if (md->type == eModifierType_Smoke) {
1133                                 SmokeModifierData *smd = (SmokeModifierData *) md;
1134                                 
1135                                 if (smd->type == MOD_SMOKE_TYPE_FLOW) {
1136                                         if (smd->flow) {
1137                                                 if (smd->flow->psys == psys)
1138                                                         smd->flow->psys = npsys;
1139                                         }
1140                                 }
1141                         }
1142                 }
1143         }
1144 }
1145
1146 void BKE_object_copy_softbody(Object *obn, Object *ob)
1147 {
1148         if (ob->soft)
1149                 obn->soft = copy_softbody(ob->soft, FALSE);
1150 }
1151
1152 static void copy_object_pose(Object *obn, Object *ob)
1153 {
1154         bPoseChannel *chan;
1155         
1156         /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */
1157         obn->pose = NULL;
1158         BKE_pose_copy_data(&obn->pose, ob->pose, 1);    /* 1 = copy constraints */
1159
1160         for (chan = obn->pose->chanbase.first; chan; chan = chan->next) {
1161                 bConstraint *con;
1162                 
1163                 chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE);
1164                 
1165                 if (chan->custom) {
1166                         id_us_plus(&chan->custom->id);
1167                 }
1168                 
1169                 for (con = chan->constraints.first; con; con = con->next) {
1170                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
1171                         ListBase targets = {NULL, NULL};
1172                         bConstraintTarget *ct;
1173                         
1174                         if (cti && cti->get_constraint_targets) {
1175                                 cti->get_constraint_targets(con, &targets);
1176                                 
1177                                 for (ct = targets.first; ct; ct = ct->next) {
1178                                         if (ct->tar == ob)
1179                                                 ct->tar = obn;
1180                                 }
1181                                 
1182                                 if (cti->flush_constraint_targets)
1183                                         cti->flush_constraint_targets(con, &targets, 0);
1184                         }
1185                 }
1186         }
1187 }
1188
1189 int BKE_object_pose_context_check(Object *ob)
1190 {
1191         if ((ob) &&
1192             (ob->type == OB_ARMATURE) &&
1193             (ob->pose) &&
1194             (ob->mode & OB_MODE_POSE))
1195         {
1196                 return 1;
1197         }
1198         else {
1199                 return 0;
1200         }
1201 }
1202
1203 Object *BKE_object_pose_armature_get(Object *ob)
1204 {
1205         if (ob == NULL)
1206                 return NULL;
1207
1208         if (BKE_object_pose_context_check(ob))
1209                 return ob;
1210
1211         ob = modifiers_isDeformedByArmature(ob);
1212
1213         if (BKE_object_pose_context_check(ob))
1214                 return ob;
1215
1216         return NULL;
1217 }
1218
1219 void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
1220 {
1221         copy_v3_v3(ob_tar->loc, ob_src->loc);
1222         copy_v3_v3(ob_tar->rot, ob_src->rot);
1223         copy_v3_v3(ob_tar->quat, ob_src->quat);
1224         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1225         ob_tar->rotAngle = ob_src->rotAngle;
1226         ob_tar->rotmode = ob_src->rotmode;
1227         copy_v3_v3(ob_tar->size, ob_src->size);
1228 }
1229
1230 Object *BKE_object_copy_ex(Main *bmain, Object *ob, int copy_caches)
1231 {
1232         Object *obn;
1233         ModifierData *md;
1234         int a;
1235
1236         obn = BKE_libblock_copy_ex(bmain, &ob->id);
1237         
1238         if (ob->totcol) {
1239                 obn->mat = MEM_dupallocN(ob->mat);
1240                 obn->matbits = MEM_dupallocN(ob->matbits);
1241                 obn->totcol = ob->totcol;
1242         }
1243         
1244         if (ob->bb) obn->bb = MEM_dupallocN(ob->bb);
1245         obn->flag &= ~OB_FROMGROUP;
1246         
1247         obn->modifiers.first = obn->modifiers.last = NULL;
1248         
1249         for (md = ob->modifiers.first; md; md = md->next) {
1250                 ModifierData *nmd = modifier_new(md->type);
1251                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1252                 modifier_copyData(md, nmd);
1253                 BLI_addtail(&obn->modifiers, nmd);
1254         }
1255
1256         obn->prop.first = obn->prop.last = NULL;
1257         BKE_bproperty_copy_list(&obn->prop, &ob->prop);
1258         
1259         copy_sensors(&obn->sensors, &ob->sensors);
1260         copy_controllers(&obn->controllers, &ob->controllers);
1261         copy_actuators(&obn->actuators, &ob->actuators);
1262         
1263         if (ob->pose) {
1264                 copy_object_pose(obn, ob);
1265                 /* backwards compat... non-armatures can get poses in older files? */
1266                 if (ob->type == OB_ARMATURE)
1267                         BKE_pose_rebuild(obn, obn->data);
1268         }
1269         defgroup_copy_list(&obn->defbase, &ob->defbase);
1270         BKE_copy_constraints(&obn->constraints, &ob->constraints, TRUE);
1271
1272         obn->mode = 0;
1273         obn->sculpt = NULL;
1274
1275         /* increase user numbers */
1276         id_us_plus((ID *)obn->data);
1277         id_us_plus((ID *)obn->gpd);
1278         id_lib_extern((ID *)obn->dup_group);
1279
1280         for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1281         
1282         obn->disp.first = obn->disp.last = NULL;
1283         
1284         if (ob->pd) {
1285                 obn->pd = MEM_dupallocN(ob->pd);
1286                 if (obn->pd->tex)
1287                         id_us_plus(&(obn->pd->tex->id));
1288                 if (obn->pd->rng)
1289                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1290         }
1291         obn->soft = copy_softbody(ob->soft, copy_caches);
1292         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1293         obn->rigidbody_object = BKE_rigidbody_copy_object(ob);
1294         obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob);
1295
1296         BKE_object_copy_particlesystems(obn, ob);
1297         
1298         obn->derivedDeform = NULL;
1299         obn->derivedFinal = NULL;
1300
1301         obn->gpulamp.first = obn->gpulamp.last = NULL;
1302         obn->pc_ids.first = obn->pc_ids.last = NULL;
1303
1304         obn->mpath = NULL;
1305         
1306         return obn;
1307 }
1308
1309 /* copy objects, will re-initialize cached simulation data */
1310 Object *BKE_object_copy(Object *ob)
1311 {
1312         return BKE_object_copy_ex(G.main, ob, FALSE);
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 = BKE_scene_frame_get(scene);
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], 1.0f / 3.0f);
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 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2121 void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime,
2122                                       RigidBodyWorld *rbw)
2123 {
2124         if (ob == NULL) return;
2125         
2126         /* execute drivers only, as animation has already been done */
2127         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2128         
2129         if (ob->parent) {
2130                 Object *par = ob->parent;
2131                 float slowmat[4][4] = MAT4_UNITY;
2132                 
2133                 /* calculate parent matrix */
2134                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2135                 
2136                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
2137                  * An old-fashioned hack which probably doesn't really cut it anymore
2138                  */
2139                 if (ob->partype & PARSLOW) {
2140                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2141                                 return;
2142                 }
2143         }
2144         else {
2145                 BKE_object_to_mat4(ob, ob->obmat);
2146         }
2147
2148         /* read values pushed into RBO from sim/cache... */
2149         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2150         
2151         /* solve constraints */
2152         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2153                 bConstraintOb *cob;
2154                 
2155                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2156                 BKE_solve_constraints(&ob->constraints, cob, ctime);
2157                 BKE_constraints_clear_evalob(cob);
2158         }
2159         
2160         /* set negative scale flag in object */
2161         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2162         else ob->transflag &= ~OB_NEG_SCALE;
2163 }
2164
2165 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2166 {
2167         BKE_object_where_is_calc_time_ex(scene, ob, ctime, NULL);
2168 }
2169
2170 /* get object transformation matrix without recalculating dependencies and
2171  * constraints -- assume dependencies are already solved by depsgraph.
2172  * no changes to object and it's parent would be done.
2173  * used for bundles orientation in 3d space relative to parented blender camera */
2174 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2175 {
2176         float slowmat[4][4] = MAT4_UNITY;
2177
2178         if (ob->parent) {
2179                 Object *par = ob->parent;
2180                 
2181                 solve_parenting(scene, ob, par, obmat, slowmat, 1);
2182                 
2183                 if (ob->partype & PARSLOW)
2184                         where_is_object_parslow(ob, obmat, slowmat);
2185         }
2186         else {
2187                 BKE_object_to_mat4(ob, obmat);
2188         }
2189 }
2190
2191 void BKE_object_where_is_calc_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob)
2192 {
2193         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), rbw);
2194 }
2195 void BKE_object_where_is_calc(Scene *scene, Object *ob)
2196 {
2197         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), NULL);
2198 }
2199
2200 /* was written for the old game engine (until 2.04) */
2201 /* It seems that this function is only called
2202  * for a lamp that is the child of another object */
2203 void BKE_object_where_is_calc_simul(Scene *scene, Object *ob)
2204 {
2205         Object *par;
2206         float *fp1, *fp2;
2207         float slowmat[4][4];
2208         float fac1, fac2;
2209         int a;
2210         
2211         /* NO TIMEOFFS */
2212         if (ob->parent) {
2213                 par = ob->parent;
2214                 
2215                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2216                 
2217                 if (ob->partype & PARSLOW) {
2218                         fac1 = (float)(1.0 / (1.0 + fabs(ob->sf)));
2219                         fac2 = 1.0f - fac1;
2220                         fp1 = ob->obmat[0];
2221                         fp2 = slowmat[0];
2222                         for (a = 0; a < 16; a++, fp1++, fp2++) {
2223                                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2224                         }
2225                 }
2226         }
2227         else {
2228                 BKE_object_to_mat4(ob, ob->obmat);
2229         }
2230         
2231         /* solve constraints */
2232         if (ob->constraints.first) {
2233                 bConstraintOb *cob;
2234                 
2235                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2236                 BKE_solve_constraints(&ob->constraints, cob, BKE_scene_frame_get(scene));
2237                 BKE_constraints_clear_evalob(cob);
2238         }
2239 }
2240
2241 /* for calculation of the inverse parent transform, only used for editor */
2242 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2243 {
2244         BKE_object_workob_clear(workob);
2245         
2246         unit_m4(workob->obmat);
2247         unit_m4(workob->parentinv);
2248         unit_m4(workob->constinv);
2249         workob->parent = ob->parent;
2250
2251         workob->trackflag = ob->trackflag;
2252         workob->upflag = ob->upflag;
2253         
2254         workob->partype = ob->partype;
2255         workob->par1 = ob->par1;
2256         workob->par2 = ob->par2;
2257         workob->par3 = ob->par3;
2258
2259         workob->constraints.first = ob->constraints.first;
2260         workob->constraints.last = ob->constraints.last;
2261
2262         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2263
2264         BKE_object_where_is_calc(scene, workob);
2265 }
2266
2267 BoundBox *BKE_boundbox_alloc_unit(void)
2268 {
2269         BoundBox *bb;
2270         float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2271
2272         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2273         BKE_boundbox_init_from_minmax(bb, min, max);
2274         
2275         return bb;
2276 }
2277
2278 void BKE_boundbox_init_from_minmax(BoundBox *bb, float min[3], float max[3])
2279 {
2280         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2281         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2282         
2283         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2284         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2285
2286         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2287         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2288 }
2289
2290 BoundBox *BKE_object_boundbox_get(Object *ob)
2291 {
2292         BoundBox *bb = NULL;
2293         
2294         if (ob->type == OB_MESH) {
2295                 bb = BKE_mesh_boundbox_get(ob);
2296         }
2297         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2298                 bb = ob->bb ? ob->bb : ((Curve *)ob->data)->bb;
2299         }
2300         else if (ob->type == OB_MBALL) {
2301                 bb = ob->bb;
2302         }
2303         return bb;
2304 }
2305
2306 /* used to temporally disable/enable boundbox */
2307 void BKE_object_boundbox_flag(Object *ob, int flag, int set)
2308 {
2309         BoundBox *bb = BKE_object_boundbox_get(ob);
2310         if (bb) {
2311                 if (set) bb->flag |= flag;
2312                 else bb->flag &= ~flag;
2313         }
2314 }
2315
2316 void BKE_object_dimensions_get(Object *ob, float vec[3])
2317 {
2318         BoundBox *bb = NULL;
2319         
2320         bb = BKE_object_boundbox_get(ob);
2321         if (bb) {
2322                 float scale[3];
2323                 
2324                 mat4_to_size(scale, ob->obmat);
2325                 
2326                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2327                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2328                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2329         }
2330         else {
2331                 zero_v3(vec);
2332         }
2333 }
2334
2335 void BKE_object_dimensions_set(Object *ob, const float *value)
2336 {
2337         BoundBox *bb = NULL;
2338         
2339         bb = BKE_object_boundbox_get(ob);
2340         if (bb) {
2341                 float scale[3], len[3];
2342                 
2343                 mat4_to_size(scale, ob->obmat);
2344                 
2345                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2346                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2347                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2348                 
2349                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2350                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2351                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2352         }
2353 }
2354
2355 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const short use_hidden)
2356 {
2357         BoundBox bb;
2358         float vec[3];
2359         int a;
2360         short change = FALSE;
2361         
2362         switch (ob->type) {
2363                 case OB_CURVE:
2364                 case OB_FONT:
2365                 case OB_SURF:
2366                 {
2367                         Curve *cu = ob->data;
2368
2369                         /* Use the object bounding box so that modifier output
2370                          * gets taken into account */
2371                         if (ob->bb)
2372                                 bb = *(ob->bb);
2373                         else {
2374                                 if (cu->bb == NULL)
2375                                         BKE_curve_texspace_calc(cu);
2376                                 bb = *(cu->bb);
2377                         }
2378
2379                         for (a = 0; a < 8; a++) {
2380                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2381                                 minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2382                         }
2383                         change = TRUE;
2384                 }
2385                 break;
2386                 case OB_LATTICE:
2387                 {
2388                         Lattice *lt = ob->data;
2389                         BPoint *bp = lt->def;
2390                         int u, v, w;
2391
2392                         for (w = 0; w < lt->pntsw; w++) {
2393                                 for (v = 0; v < lt->pntsv; v++) {
2394                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2395                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2396                                                 minmax_v3v3_v3(min_r, max_r, vec);
2397                                         }
2398                                 }
2399                         }
2400                         change = TRUE;
2401                 }
2402                 break;
2403                 case OB_ARMATURE:
2404                         if (ob->pose) {
2405                                 bArmature *arm = ob->data;
2406                                 bPoseChannel *pchan;
2407
2408                                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2409                                         /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2410                                          *     (editarmature.c:2592)... Skip in this case too! */
2411                                         if (pchan->bone && !((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE))) {
2412                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2413                                                 minmax_v3v3_v3(min_r, max_r, vec);
2414                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2415                                                 minmax_v3v3_v3(min_r, max_r, vec);
2416
2417                                                 change = TRUE;
2418                                         }
2419                                 }
2420                         }
2421                         break;
2422                 case OB_MESH:
2423                 {
2424                         Mesh *me = BKE_mesh_from_object(ob);
2425
2426                         if (me) {
2427                                 bb = *BKE_mesh_boundbox_get(ob);
2428
2429                                 for (a = 0; a < 8; a++) {
2430                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2431                                         minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2432                                 }
2433                                 change = TRUE;
2434                         }
2435                 }
2436                 break;
2437         }
2438
2439         if (change == FALSE) {
2440                 float size[3];
2441
2442                 copy_v3_v3(size, ob->size);
2443                 if (ob->type == OB_EMPTY) {
2444                         mul_v3_fl(size, ob->empty_drawsize);
2445                 }
2446
2447                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2448
2449                 copy_v3_v3(vec, ob->obmat[3]);
2450                 add_v3_v3(vec, size);
2451                 minmax_v3v3_v3(min_r, max_r, vec);
2452
2453                 copy_v3_v3(vec, ob->obmat[3]);
2454                 sub_v3_v3(vec, size);
2455                 minmax_v3v3_v3(min_r, max_r, vec);
2456         }
2457 }
2458
2459 int BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const short use_hidden)
2460 {
2461         int ok = FALSE;
2462         if ((ob->transflag & OB_DUPLI) == 0) {
2463                 return ok;
2464         }
2465         else {
2466                 ListBase *lb;
2467                 DupliObject *dob;
2468                 
2469                 lb = object_duplilist(scene, ob, FALSE);
2470                 for (dob = lb->first; dob; dob = dob->next) {
2471                         if ((use_hidden == FALSE) && (dob->no_draw != 0)) {
2472                                 /* pass */
2473                         }
2474                         else {
2475                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2476
2477                                 if (bb) {
2478                                         int i;
2479                                         for (i = 0; i < 8; i++) {
2480                                                 float vec[3];
2481                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2482                                                 minmax_v3v3_v3(r_min, r_max, vec);
2483                                         }
2484
2485                                         ok = TRUE;
2486                                 }
2487                         }
2488                 }
2489                 free_object_duplilist(lb);  /* does restore */
2490         }
2491
2492         return ok;
2493 }
2494
2495 void BKE_object_foreach_display_point(
2496         Object *ob, float obmat[4][4],
2497         void (*func_cb)(const float[3], void *), void *user_data)
2498 {
2499         float co[3];
2500
2501         if (ob->derivedFinal) {
2502                 DerivedMesh *dm = ob->derivedFinal;
2503                 MVert *mv = dm->getVertArray(dm);
2504                 int totvert = dm->getNumVerts(dm);
2505                 int i;
2506
2507                 for (i = 0; i < totvert; i++, mv++) {
2508                         mul_v3_m4v3(co, obmat, mv->co);
2509                         func_cb(co, user_data);
2510                 }
2511         }
2512         else if (ob->disp.first) {
2513                 DispList *dl;
2514
2515                 for (dl = ob->disp.first; dl; dl = dl->next) {
2516                         float *v3 = dl->verts;
2517                         int totvert = dl->nr;
2518                         int i;
2519
2520                         for (i = 0; i < totvert; i++, v3 += 3) {
2521                                 mul_v3_m4v3(co, obmat, v3);
2522                                 func_cb(co, user_data);
2523                         }
2524                 }
2525         }
2526 }
2527
2528 void BKE_scene_foreach_display_point(
2529         Scene *scene, View3D *v3d, const short flag,
2530         void (*func_cb)(const float[3], void *), void *user_data)
2531 {
2532         Base *base;
2533         Object *ob;
2534
2535         for (base = FIRSTBASE; base; base = base->next) {
2536                 if (BASE_VISIBLE(v3d, base) && (base->flag & flag) == flag) {
2537                         ob = base->object;
2538
2539                         if ((ob->transflag & OB_DUPLI) == 0) {
2540                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2541                         }
2542                         else {
2543                                 ListBase *lb;
2544                                 DupliObject *dob;
2545
2546                                 lb = object_duplilist(scene, ob, FALSE);
2547                                 for (dob = lb->first; dob; dob = dob->next) {
2548                                         if (dob->no_draw == 0) {
2549                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2550                                         }
2551                                 }
2552                                 free_object_duplilist(lb);  /* does restore */
2553                         }
2554                 }
2555         }
2556 }
2557
2558 /* copied from DNA_object_types.h */
2559 typedef struct ObTfmBack {
2560         float loc[3], dloc[3], orig[3];
2561         float size[3], dscale[3];   /* scale and delta scale */
2562         float rot[3], drot[3];      /* euler rotation */
2563         float quat[4], dquat[4];    /* quaternion rotation */
2564         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2565         float rotAngle, drotAngle;  /* axis angle rotation - angle part */
2566         float obmat[4][4];      /* final worldspace matrix with constraints & animsys applied */
2567         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2568         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2569         float imat[4][4];   /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2570 } ObTfmBack;
2571
2572 void *BKE_object_tfm_backup(Object *ob)
2573 {
2574         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2575         copy_v3_v3(obtfm->loc, ob->loc);
2576         copy_v3_v3(obtfm->dloc, ob->dloc);
2577         copy_v3_v3(obtfm->orig, ob->orig);
2578         copy_v3_v3(obtfm->size, ob->size);
2579         copy_v3_v3(obtfm->dscale, ob->dscale);
2580         copy_v3_v3(obtfm->rot, ob->rot);
2581         copy_v3_v3(obtfm->drot, ob->drot);
2582         copy_qt_qt(obtfm->quat, ob->quat);
2583         copy_qt_qt(obtfm->dquat, ob->dquat);
2584         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2585         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2586         obtfm->rotAngle = ob->rotAngle;
2587         obtfm->drotAngle = ob->drotAngle;
2588         copy_m4_m4(obtfm->obmat, ob->obmat);
2589         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2590         copy_m4_m4(obtfm->constinv, ob->constinv);
2591         copy_m4_m4(obtfm->imat, ob->imat);
2592
2593         return (void *)obtfm;
2594 }
2595
2596 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2597 {
2598         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2599         copy_v3_v3(ob->loc, obtfm->loc);
2600         copy_v3_v3(ob->dloc, obtfm->dloc);
2601         copy_v3_v3(ob->orig, obtfm->orig);
2602         copy_v3_v3(ob->size, obtfm->size);
2603         copy_v3_v3(ob->dscale, obtfm->dscale);
2604         copy_v3_v3(ob->rot, obtfm->rot);
2605         copy_v3_v3(ob->drot, obtfm->drot);
2606         copy_qt_qt(ob->quat, obtfm->quat);
2607         copy_qt_qt(ob->dquat, obtfm->dquat);
2608         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2609         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2610         ob->rotAngle = obtfm->rotAngle;
2611         ob->drotAngle = obtfm->drotAngle;
2612         copy_m4_m4(ob->obmat, obtfm->obmat);
2613         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2614         copy_m4_m4(ob->constinv, obtfm->constinv);
2615         copy_m4_m4(ob->imat, obtfm->imat);
2616 }
2617
2618 int BKE_object_parent_loop_check(const Object *par, const Object *ob)
2619 {
2620         /* test if 'ob' is a parent somewhere in par's parents */
2621         if (par == NULL) return 0;
2622         if (ob == par) return 1;
2623         return BKE_object_parent_loop_check(par->parent, ob);
2624 }
2625
2626 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2627 /*           local_object->proxy      == pointer to library object, saved in files and read */
2628
2629 /* function below is polluted with proxy exceptions, cleanup will follow! */
2630
2631 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2632 /* requires flags to be set! */
2633 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
2634 void BKE_object_handle_update_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob)
2635 {
2636         if (ob->recalc & OB_RECALC_ALL) {
2637                 /* speed optimization for animation lookups */
2638                 if (ob->pose)
2639                         BKE_pose_channels_hash_make(ob->pose);
2640
2641                 if (ob->recalc & OB_RECALC_DATA) {
2642                         if (ob->type == OB_ARMATURE) {
2643                                 /* this happens for reading old files and to match library armatures
2644                                  * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
2645                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2646                                  * on file load */
2647                                 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
2648                                         BKE_pose_rebuild(ob, ob->data);
2649                         }
2650                 }
2651
2652                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2653                  * which is only in BKE_object_where_is_calc now */
2654                 /* XXX: should this case be OB_RECALC_OB instead? */
2655                 if (ob->recalc & OB_RECALC_ALL) {
2656                         
2657                         if (G.debug & G_DEBUG)
2658                                 printf("recalcob %s\n", ob->id.name + 2);
2659                         
2660                         /* handle proxy copy for target */
2661                         if (ob->id.lib && ob->proxy_from) {
2662                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2663                                 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
2664                                         Object *obg = ob->proxy_from->proxy_group;
2665                                         invert_m4_m4(obg->imat, obg->obmat);
2666                                         mult_m4_m4m4(ob->obmat, obg->imat, ob->proxy_from->obmat);
2667                                         if (obg->dup_group) { /* should always be true */
2668                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2669                                         }
2670                                 }
2671                                 else
2672                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2673                         }
2674                         else
2675                                 BKE_object_where_is_calc_ex(scene, rbw, ob);
2676                 }
2677                 
2678                 if (ob->recalc & OB_RECALC_DATA) {
2679                         ID *data_id = (ID *)ob->data;
2680                         AnimData *adt = BKE_animdata_from_id(data_id);
2681                         float ctime = BKE_scene_frame_get(scene);
2682                         
2683                         if (G.debug & G_DEBUG)
2684                                 printf("recalcdata %s\n", ob->id.name + 2);
2685
2686                         if (adt) {
2687                                 /* evaluate drivers - datalevel */
2688                                 /* XXX: for mesh types, should we push this to derivedmesh instead? */
2689                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2690                         }
2691
2692                         /* includes all keys and modifiers */
2693                         switch (ob->type) {
2694                                 case OB_MESH:
2695                                 {
2696 #if 0               // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2697                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2698                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2699                                         if (em) {
2700                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask, 0); /* was CD_MASK_BAREMESH */
2701                                         }
2702                                         else {
2703                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask, 0);
2704                                         }
2705
2706 #else               /* ensure CD_MASK_BAREMESH for now */
2707                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2708                                         uint64_t data_mask = scene->customdata_mask | ob->customdata_mask | CD_MASK_BAREMESH;
2709                                         if (em) {
2710                                                 makeDerivedMesh(scene, ob, em,  data_mask, 0); /* was CD_MASK_BAREMESH */
2711                                         }
2712                                         else {
2713                                                 makeDerivedMesh(scene, ob, NULL, data_mask, 0);
2714                                         }
2715 #endif
2716
2717                                 }
2718                                 break;
2719
2720                                 case OB_ARMATURE:
2721                                         if (ob->id.lib && ob->proxy_from) {
2722                                                 if (BKE_pose_copy_result(ob->pose, ob->proxy_from->pose) == false) {
2723                                                         printf("Proxy copy error, lib Object: %s proxy Object: %s\n",
2724                                                                ob->id.name + 2, ob->proxy_from->id.name + 2);
2725                                                 }
2726                                         }
2727                                         else {
2728                                                 BKE_pose_where_is(scene, ob);
2729                                         }
2730                                         break;
2731
2732                                 case OB_MBALL:
2733                                         BKE_displist_make_mball(scene, ob);
2734                                         break;
2735
2736                                 case OB_CURVE:
2737                                 case OB_SURF:
2738                                 case OB_FONT:
2739                                         BKE_displist_make_curveTypes(scene, ob, 0);
2740                                         break;
2741                                 
2742                                 case OB_LATTICE:
2743                                         BKE_lattice_modifiers_calc(scene, ob);
2744                                         break;
2745                         }
2746                         
2747                         /* related materials */
2748                         /* XXX: without depsgraph tagging, this will always need to be run, which will be slow! 
2749                          * However, not doing anything (or trying to hack around this lack) is not an option 
2750                          * anymore, especially due to Cycles [#31834] 
2751                          */
2752                         if (ob->totcol) {
2753                                 int a;
2754                                 
2755                                 for (a = 1; a <= ob->totcol; a++) {
2756                                         Material *ma = give_current_material(ob, a);
2757                                         
2758                                         if (ma) {
2759                                                 /* recursively update drivers for this material */
2760                                                 material_drivers_update(scene, ma, ctime);
2761                                         }
2762                                 }
2763                         }
2764                         else if (ob->type == OB_LAMP)
2765                                 lamp_drivers_update(scene, ob->data, ctime);
2766                         
2767                         /* particles */
2768                         if (ob->particlesystem.first) {
2769                                 ParticleSystem *tpsys, *psys;
2770                                 DerivedMesh *dm;
2771                                 ob->transflag &= ~OB_DUPLIPARTS;
2772                                 
2773                                 psys = ob->particlesystem.first;
2774                                 while (psys) {
2775                                         if (psys_check_enabled(ob, psys)) {
2776                                                 /* check use of dupli objects here */
2777                                                 if (psys->part && (psys->part->draw_as == PART_DRAW_REND || G.is_rendering) &&
2778                                                     ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob) ||
2779                                                      (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2780                                                 {
2781                                                         ob->transflag |= OB_DUPLIPARTS;
2782                                                 }
2783
2784                                                 particle_system_update(scene, ob, psys);
2785                                                 psys = psys->next;
2786                                         }
2787                                         else if (psys->flag & PSYS_DELETE) {
2788                                                 tpsys = psys->next;
2789                                                 BLI_remlink(&ob->particlesystem, psys);
2790                                                 psys_free(ob, psys);
2791                                                 psys = tpsys;
2792                                         }
2793                                         else
2794                                                 psys = psys->next;
2795                                 }
2796
2797                                 if (G.is_rendering && ob->transflag & OB_DUPLIPARTS) {
2798                                         /* this is to make sure we get render level duplis in groups:
2799                                          * the derivedmesh must be created before init_render_mesh,
2800                                          * since object_duplilist does dupliparticles before that */
2801                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH | CD_MASK_MTFACE | CD_MASK_MCOL);
2802                                         dm->release(dm);
2803
2804                                         for (psys = ob->particlesystem.first; psys; psys = psys->next)
2805                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2806                                 }
2807                         }
2808                         
2809                         /* quick cache removed */
2810                 }
2811
2812                 /* the no-group proxy case, we call update */
2813                 if (ob->proxy && ob->proxy_group == NULL) {
2814                         /* set pointer in library proxy target, for copying, but restore it */
2815                         ob->proxy->proxy_from = ob;
2816                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2817                         BKE_object_handle_update(scene, ob->proxy);
2818                 }
2819         
2820                 ob->recalc &= ~OB_RECALC_ALL;
2821         }
2822
2823         /* the case when this is a group proxy, object_update is called in group.c */
2824         if (ob->proxy) {
2825                 ob->proxy->proxy_from = ob;
2826                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2827         }
2828 }
2829 /* WARNING: "scene" here may not be the scene object actually resides in. 
2830  * When dealing with background-sets, "scene" is actually the active scene.
2831  * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n
2832  * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the corrent rigid body world
2833  */
2834 void BKE_object_handle_update(Scene *scene, Object *ob)
2835 {
2836         BKE_object_handle_update_ex(scene, NULL, ob);
2837 }
2838
2839 void BKE_object_sculpt_modifiers_changed(Object *ob)
2840 {
2841         SculptSession *ss = ob->sculpt;
2842
2843         if (!ss->cache) {
2844                 /* we free pbvh on changes, except during sculpt since it can't deal with
2845                  * changing PVBH node organization, we hope topology does not change in
2846                  * the meantime .. weak */
2847                 if (ss->pbvh) {
2848                         BKE_pbvh_free(ss->pbvh);
2849                         ss->pbvh = NULL;
2850                 }
2851
2852                 free_sculptsession_deformMats(ob->sculpt);
2853         }
2854         else {
2855                 PBVHNode **nodes;
2856                 int n, totnode;
2857
2858                 BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2859
2860                 for (n = 0; n < totnode; n++)
2861                         BKE_pbvh_node_mark_update(nodes[n]);
2862
2863                 MEM_freeN(nodes);
2864         }
2865 }
2866
2867 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
2868 {
2869         
2870         if (ob->data == NULL)
2871                 return 0;
2872         
2873         switch (GS(((ID *)ob->data)->name)) {
2874                 case ID_ME:
2875                 {
2876                         Mesh *me = ob->data;
2877                         if (r_texflag) *r_texflag = &me->texflag;
2878                         if (r_loc) *r_loc = me->loc;
2879                         if (r_size) *r_size = me->size;
2880                         if (r_rot) *r_rot = me->rot;
2881                         break;
2882                 }
2883                 case ID_CU:
2884                 {
2885                         Curve *cu = ob->data;
2886                         if (r_texflag) *r_texflag = &cu->texflag;
2887                         if (r_loc) *r_loc = cu->loc;
2888                         if (r_size) *r_size = cu->size;
2889                         if (r_rot) *r_rot = cu->rot;
2890                         break;
2891                 }
2892                 case ID_MB:
2893                 {
2894                         MetaBall *mb = ob->data;
2895                         if (r_texflag) *r_texflag = &mb->texflag;
2896                         if (r_loc) *r_loc = mb->loc;
2897                         if (r_size) *r_size = mb->size;
2898                         if (r_rot) *r_rot = mb->rot;
2899                         break;
2900                 }
2901                 default:
2902                         return 0;
2903         }
2904         return 1;
2905 }
2906
2907 /*
2908  * Test a bounding box for ray intersection
2909  * assumes the ray is already local to the boundbox space
2910  */
2911 int BKE_boundbox_ray_hit_check(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2912 {
2913         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2914                                               {3, 2, 6}, {3, 6, 7},
2915                                               {1, 2, 6}, {1, 6, 5},
2916                                               {5, 6, 7}, {4, 5, 7},
2917                                               {0, 3, 7}, {0, 4, 7},
2918                                               {0, 1, 5}, {0, 4, 5}};
2919         int result = 0;
2920         int i;
2921         
2922         for (i = 0; i < 12 && result == 0; i++) {
2923                 float lambda;
2924                 int v1, v2, v3;
2925                 v1 = triangle_indexes[i][0];
2926                 v2 = triangle_indexes[i][1];
2927                 v3 = triangle_indexes[i][2];
2928                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2929         }
2930         
2931         return result;
2932 }
2933
2934 static int pc_cmp(void *a, void *b)
2935 {
2936         LinkData *ad = a, *bd = b;
2937         if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2938                 return 1;
2939         else return 0;
2940 }
2941
2942 int BKE_object_insert_ptcache(Object *ob) 
2943 {
2944         LinkData *link = NULL;
2945         int i = 0;
2946
2947         BLI_sortlist(&ob->pc_ids, pc_cmp);
2948
2949         for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) {
2950                 int index = GET_INT_FROM_POINTER(link->data);
2951
2952                 if (i < index)
2953                         break;
2954         }
2955
2956         link = MEM_callocN(sizeof(LinkData), "PCLink");
2957         link->data = SET_INT_IN_POINTER(i);
2958         BLI_addtail(&ob->pc_ids, link);
2959
2960         return i;
2961 }
2962
2963 #if 0
2964 static int pc_findindex(ListBase *listbase, int index)
2965 {
2966         LinkData *link = NULL;
2967         int number = 0;
2968         
2969         if (listbase == NULL) return -1;
2970         
2971         link = listbase->first;
2972         while (link) {
2973                 if ((int)link->data == index)
2974                         return number;
2975                 
2976                 number++;
2977                 link = link->next;
2978         }
2979         
2980         return -1;
2981 }
2982
2983 void object_delete_ptcache(Object *ob, int index) 
2984 {
2985         int list_index = pc_findindex(&ob->pc_ids, index);
2986         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2987         BLI_freelinkN(&ob->pc_ids, link);
2988 }
2989 #endif
2990
2991 /* shape key utility function */
2992
2993 /************************* Mesh ************************/
2994 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
2995 {
2996         Mesh *me = ob->data;
2997         Key *key = me->key;
2998         KeyBlock *kb;
2999         int newkey = 0;
3000
3001         if (key == NULL) {
3002                 key = me->key = BKE_key_add((ID *)me);
3003                 key->type = KEY_RELATIVE;
3004                 newkey = 1;
3005         }
3006
3007         if (newkey || from_mix == FALSE) {
3008                 /* create from mesh */
3009                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3010                 BKE_key_convert_from_mesh(me, kb);
3011         }
3012         else {
3013                 /* copy from current values */
3014                 int totelem;
3015                 float *data = BKE_key_evaluate_object(scene, ob, &totelem);
3016
3017                 /* create new block with prepared data */
3018                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3019                 kb->data = data;
3020                 kb->totelem = totelem;
3021         }
3022
3023         return kb;
3024 }
3025 /************************* Lattice ************************/
3026 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
3027 {
3028         Lattice *lt = ob->data;
3029         Key *key = lt->key;
3030         KeyBlock *kb;
3031         int newkey = 0;
3032
3033         if (key == NULL) {
3034                 key = lt->key = BKE_key_add((ID *)lt);
3035                 key->type = KEY_RELATIVE;
3036                 newkey = 1;
3037         }
3038
3039         if (newkey || from_mix == FALSE) {
3040                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3041                 if (!newkey) {
3042                         KeyBlock *basekb = (KeyBlock *)key->block.first;
3043                         kb->data = MEM_dupallocN(basekb->data);
3044                         kb->totelem = basekb->totelem;
3045                 }
3046                 else {
3047                         BKE_key_convert_from_lattice(lt, kb);
3048                 }
3049         }
3050         else {
3051                 /* copy from current values */
3052                 int totelem;
3053                 float *data = BKE_key_evaluate_object(scene, ob, &totelem);
3054
3055                 /* create new block with prepared data */
3056                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3057                 kb->totelem = totelem;
3058                 kb->data = data;
3059         }
3060
3061         return kb;
3062 }
3063 /************************* Curve ************************/
3064 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
3065 {
3066         Curve *cu = ob->data;
3067         Key *key = cu->key;
3068         KeyBlock *kb;
3069         ListBase *lb = BKE_curve_nurbs_get(cu);
3070         int newkey = 0;
3071
3072         if (key == NULL) {
3073                 key = cu->key = BKE_key_add((ID *)cu);
3074                 key->type = KEY_RELATIVE;
3075                 newkey = 1;
3076         }
3077
3078         if (newkey || from_mix =