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