2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/object.c
37 #include "MEM_guardedalloc.h"
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_gpencil_types.h"
44 #include "DNA_group_types.h"
45 #include "DNA_key_types.h"
46 #include "DNA_lamp_types.h"
47 #include "DNA_lattice_types.h"
48 #include "DNA_material_types.h"
49 #include "DNA_meta_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_meshdata_types.h"
52 #include "DNA_movieclip_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_screen_types.h"
55 #include "DNA_sequence_types.h"
56 #include "DNA_smoke_types.h"
57 #include "DNA_space_types.h"
58 #include "DNA_view3d_types.h"
59 #include "DNA_world_types.h"
60 #include "DNA_object_types.h"
61 #include "DNA_property_types.h"
62 #include "DNA_rigidbody_types.h"
64 #include "BLI_blenlib.h"
66 #include "BLI_threads.h"
67 #include "BLI_utildefines.h"
68 #include "BLI_linklist.h"
69 #include "BLI_kdtree.h"
71 #include "BLT_translation.h"
75 #include "BKE_global.h"
76 #include "BKE_idprop.h"
77 #include "BKE_armature.h"
78 #include "BKE_action.h"
79 #include "BKE_bullet.h"
80 #include "BKE_deform.h"
81 #include "BKE_DerivedMesh.h"
82 #include "BKE_animsys.h"
84 #include "BKE_constraint.h"
85 #include "BKE_curve.h"
86 #include "BKE_displist.h"
87 #include "BKE_effect.h"
88 #include "BKE_fcurve.h"
89 #include "BKE_group.h"
90 #include "BKE_icons.h"
93 #include "BKE_layer.h"
94 #include "BKE_lattice.h"
95 #include "BKE_library.h"
96 #include "BKE_library_query.h"
97 #include "BKE_library_remap.h"
98 #include "BKE_linestyle.h"
100 #include "BKE_editmesh.h"
101 #include "BKE_mball.h"
102 #include "BKE_modifier.h"
103 #include "BKE_multires.h"
104 #include "BKE_node.h"
105 #include "BKE_object.h"
106 #include "BKE_paint.h"
107 #include "BKE_particle.h"
108 #include "BKE_pointcache.h"
109 #include "BKE_property.h"
110 #include "BKE_rigidbody.h"
112 #include "BKE_scene.h"
113 #include "BKE_sequencer.h"
114 #include "BKE_speaker.h"
115 #include "BKE_softbody.h"
116 #include "BKE_subsurf.h"
117 #include "BKE_material.h"
118 #include "BKE_camera.h"
119 #include "BKE_image.h"
121 #include "DEG_depsgraph.h"
123 #include "DRW_engine.h"
125 #ifdef WITH_MOD_FLUID
126 #include "LBM_fluidsim.h"
130 #include "BPY_extern.h"
133 #include "CCGSubSurf.h"
134 #include "atomic_ops.h"
136 #include "GPU_lamp.h"
138 /* Vertex parent modifies original BMesh which is not safe for threading.
139 * Ideally such a modification should be handled as a separate DAG update
140 * callback for mesh datablock, but for until it is actually supported use
141 * simpler solution with a mutex lock.
144 #define VPARENT_THREADING_HACK
146 #ifdef VPARENT_THREADING_HACK
147 static ThreadMutex vparent_lock = BLI_MUTEX_INITIALIZER;
150 void BKE_object_workob_clear(Object *workob)
152 memset(workob, 0, sizeof(Object));
154 workob->size[0] = workob->size[1] = workob->size[2] = 1.0f;
155 workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f;
156 workob->rotmode = ROT_MODE_EUL;
159 void BKE_object_update_base_layer(struct Scene *scene, Object *ob)
161 BaseLegacy *base = scene->base.first;
164 if (base->object == ob) base->lay = ob->lay;
169 void BKE_object_free_particlesystems(Object *ob)
171 ParticleSystem *psys;
173 while ((psys = BLI_pophead(&ob->particlesystem))) {
178 void BKE_object_free_softbody(Object *ob)
186 void BKE_object_free_bulletsoftbody(Object *ob)
194 void BKE_object_free_curve_cache(Object *ob)
196 if (ob->curve_cache) {
197 BKE_displist_free(&ob->curve_cache->disp);
198 BKE_curve_bevelList_free(&ob->curve_cache->bev);
199 if (ob->curve_cache->path) {
200 free_path(ob->curve_cache->path);
202 BKE_nurbList_free(&ob->curve_cache->deformed_nurbs);
203 MEM_freeN(ob->curve_cache);
204 ob->curve_cache = NULL;
208 void BKE_object_free_modifiers(Object *ob)
212 while ((md = BLI_pophead(&ob->modifiers))) {
216 /* particle modifiers were freed, so free the particlesystems as well */
217 BKE_object_free_particlesystems(ob);
219 /* same for softbody */
220 BKE_object_free_softbody(ob);
222 /* modifiers may have stored data in the DM cache */
223 BKE_object_free_derived_caches(ob);
226 void BKE_object_modifier_hook_reset(Object *ob, HookModifierData *hmd)
228 /* reset functionality */
230 bPoseChannel *pchan = BKE_pose_channel_find_name(hmd->object->pose, hmd->subtarget);
232 if (hmd->subtarget[0] && pchan) {
233 float imat[4][4], mat[4][4];
235 /* calculate the world-space matrix for the pose-channel target first, then carry on as usual */
236 mul_m4_m4m4(mat, hmd->object->obmat, pchan->pose_mat);
238 invert_m4_m4(imat, mat);
239 mul_m4_m4m4(hmd->parentinv, imat, ob->obmat);
242 invert_m4_m4(hmd->object->imat, hmd->object->obmat);
243 mul_m4_m4m4(hmd->parentinv, hmd->object->imat, ob->obmat);
248 bool BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
250 const ModifierTypeInfo *mti;
252 mti = modifierType_getInfo(modifier_type);
254 /* only geometry objects should be able to get modifiers [#25291] */
255 if (!ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
259 if (ob->type == OB_LATTICE && (mti->flags & eModifierTypeFlag_AcceptsLattice) == 0) {
263 if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
264 (ob->type == OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
272 void BKE_object_link_modifiers(struct Object *ob_dst, const struct Object *ob_src)
275 BKE_object_free_modifiers(ob_dst);
277 if (!ELEM(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
278 /* only objects listed above can have modifiers and linking them to objects
279 * which doesn't have modifiers stack is quite silly */
283 for (md = ob_src->modifiers.first; md; md = md->next) {
284 ModifierData *nmd = NULL;
288 eModifierType_Collision))
293 if (!BKE_object_support_modifier_type_check(ob_dst, md->type))
297 case eModifierType_Softbody:
298 BKE_object_copy_softbody(ob_dst, ob_src);
300 case eModifierType_Skin:
301 /* ensure skin-node customdata exists */
302 BKE_mesh_ensure_skin_customdata(ob_dst->data);
306 nmd = modifier_new(md->type);
307 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
309 if (md->type == eModifierType_Multires) {
310 /* Has to be done after mod creation, but *before* we actually copy its settings! */
311 multiresModifier_sync_levels_ex(ob_dst, (MultiresModifierData *)md, (MultiresModifierData *)nmd);
314 modifier_copyData(md, nmd);
315 BLI_addtail(&ob_dst->modifiers, nmd);
316 modifier_unique_name(&ob_dst->modifiers, nmd);
319 BKE_object_copy_particlesystems(ob_dst, ob_src);
321 /* TODO: smoke?, cloth? */
324 /* free data derived from mesh, called when mesh changes or is freed */
325 void BKE_object_free_derived_caches(Object *ob)
327 /* Also serves as signal to remake texspace.
329 * NOTE: This function can be called from threads on different objects
330 * sharing same data datablock. So we need to ensure atomic nature of
331 * data modification here.
333 if (ob->type == OB_MESH) {
337 atomic_fetch_and_or_uint32((uint*)&me->bb->flag, BOUNDBOX_DIRTY);
340 else if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) {
341 Curve *cu = ob->data;
344 atomic_fetch_and_or_uint32((uint*)&cu->bb->flag, BOUNDBOX_DIRTY);
353 if (ob->derivedFinal) {
354 ob->derivedFinal->needsFree = 1;
355 ob->derivedFinal->release(ob->derivedFinal);
356 ob->derivedFinal = NULL;
358 if (ob->derivedDeform) {
359 ob->derivedDeform->needsFree = 1;
360 ob->derivedDeform->release(ob->derivedDeform);
361 ob->derivedDeform = NULL;
364 BKE_object_free_curve_cache(ob);
367 void BKE_object_free_caches(Object *object)
370 short update_flag = 0;
372 /* Free particle system caches holding paths. */
373 if (object->particlesystem.first) {
374 ParticleSystem *psys;
375 for (psys = object->particlesystem.first;
379 psys_free_path_cache(psys, psys->edit);
380 update_flag |= PSYS_RECALC_REDO;
384 /* Free memory used by cached derived meshes in the particle system modifiers. */
385 for (md = object->modifiers.first; md != NULL; md = md->next) {
386 if (md->type == eModifierType_ParticleSystem) {
387 ParticleSystemModifierData *psmd = (ParticleSystemModifierData *) md;
388 if (psmd->dm_final != NULL) {
389 psmd->dm_final->needsFree = 1;
390 psmd->dm_final->release(psmd->dm_final);
391 psmd->dm_final = NULL;
392 if (psmd->dm_deformed != NULL) {
393 psmd->dm_deformed->needsFree = 1;
394 psmd->dm_deformed->release(psmd->dm_deformed);
395 psmd->dm_deformed = NULL;
397 psmd->flag |= eParticleSystemFlag_file_loaded;
398 update_flag |= OB_RECALC_DATA;
403 /* Tag object for update, so once memory critical operation is over and
404 * scene update routines are back to it's business the object will be
405 * guaranteed to be in a known state.
407 if (update_flag != 0) {
408 DEG_id_tag_update(&object->id, update_flag);
412 /** Free (or release) any data used by this object (does not free the object itself). */
413 void BKE_object_free(Object *ob)
415 BKE_animdata_free((ID *)ob, false);
417 BKE_object_free_modifiers(ob);
419 MEM_SAFE_FREE(ob->mat);
420 MEM_SAFE_FREE(ob->matbits);
421 MEM_SAFE_FREE(ob->iuser);
422 MEM_SAFE_FREE(ob->bb);
424 BLI_freelistN(&ob->defbase);
426 BKE_pose_free_ex(ob->pose, false);
430 animviz_free_motionpath(ob->mpath);
433 BKE_bproperty_free_list(&ob->prop);
435 free_sensors(&ob->sensors);
436 free_controllers(&ob->controllers);
437 free_actuators(&ob->actuators);
439 BKE_constraints_free_ex(&ob->constraints, false);
441 free_partdeflect(ob->pd);
442 BKE_rigidbody_free_object(ob);
443 BKE_rigidbody_free_constraint(ob);
455 DRW_object_engine_data_free(ob);
457 BKE_sculptsession_free(ob);
459 BLI_freelistN(&ob->pc_ids);
461 BLI_freelistN(&ob->lodlevels);
463 /* Free runtime curves data. */
464 if (ob->curve_cache) {
465 BKE_curve_bevelList_free(&ob->curve_cache->bev);
466 if (ob->curve_cache->path)
467 free_path(ob->curve_cache->path);
468 MEM_freeN(ob->curve_cache);
469 ob->curve_cache = NULL;
472 BKE_previewimg_free(&ob->preview);
474 /* don't free, let the base free it */
475 ob->base_collection_properties = NULL;
478 /* actual check for internal data, not context or flags */
479 bool BKE_object_is_in_editmode(Object *ob)
481 if (ob->data == NULL)
484 if (ob->type == OB_MESH) {
489 else if (ob->type == OB_ARMATURE) {
490 bArmature *arm = ob->data;
495 else if (ob->type == OB_FONT) {
496 Curve *cu = ob->data;
501 else if (ob->type == OB_MBALL) {
502 MetaBall *mb = ob->data;
507 else if (ob->type == OB_LATTICE) {
508 Lattice *lt = ob->data;
513 else if (ob->type == OB_SURF || ob->type == OB_CURVE) {
514 Curve *cu = ob->data;
522 bool BKE_object_is_in_editmode_vgroup(Object *ob)
524 return (OB_TYPE_SUPPORT_VGROUP(ob->type) &&
525 BKE_object_is_in_editmode(ob));
528 bool BKE_object_is_in_wpaint_select_vert(Object *ob)
530 if (ob->type == OB_MESH) {
532 return ((ob->mode & OB_MODE_WEIGHT_PAINT) &&
533 (me->edit_btmesh == NULL) &&
534 (ME_EDIT_PAINT_SEL_MODE(me) == SCE_SELECT_VERTEX));
540 bool BKE_object_exists_check(Object *obtest)
544 if (obtest == NULL) return false;
546 ob = G.main->object.first;
548 if (ob == obtest) return true;
554 /* *************************************************** */
556 static const char *get_obdata_defname(int type)
559 case OB_MESH: return DATA_("Mesh");
560 case OB_CURVE: return DATA_("Curve");
561 case OB_SURF: return DATA_("Surf");
562 case OB_FONT: return DATA_("Text");
563 case OB_MBALL: return DATA_("Mball");
564 case OB_CAMERA: return DATA_("Camera");
565 case OB_LAMP: return DATA_("Lamp");
566 case OB_LATTICE: return DATA_("Lattice");
567 case OB_ARMATURE: return DATA_("Armature");
568 case OB_SPEAKER: return DATA_("Speaker");
569 case OB_EMPTY: return DATA_("Empty");
571 printf("get_obdata_defname: Internal error, bad type: %d\n", type);
572 return DATA_("Empty");
576 void *BKE_object_obdata_add_from_type(Main *bmain, int type, const char *name)
579 name = get_obdata_defname(type);
583 case OB_MESH: return BKE_mesh_add(bmain, name);
584 case OB_CURVE: return BKE_curve_add(bmain, name, OB_CURVE);
585 case OB_SURF: return BKE_curve_add(bmain, name, OB_SURF);
586 case OB_FONT: return BKE_curve_add(bmain, name, OB_FONT);
587 case OB_MBALL: return BKE_mball_add(bmain, name);
588 case OB_CAMERA: return BKE_camera_add(bmain, name);
589 case OB_LAMP: return BKE_lamp_add(bmain, name);
590 case OB_LATTICE: return BKE_lattice_add(bmain, name);
591 case OB_ARMATURE: return BKE_armature_add(bmain, name);
592 case OB_SPEAKER: return BKE_speaker_add(bmain, name);
593 case OB_EMPTY: return NULL;
595 printf("%s: Internal error, bad type: %d\n", __func__, type);
600 void BKE_object_init(Object *ob)
602 /* BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(ob, id)); */ /* ob->type is already initialized... */
604 ob->col[0] = ob->col[1] = ob->col[2] = 1.0;
607 ob->size[0] = ob->size[1] = ob->size[2] = 1.0;
608 ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0;
610 /* objects should default to having Euler XYZ rotations,
611 * but rotations default to quaternions
613 ob->rotmode = ROT_MODE_EUL;
615 unit_axis_angle(ob->rotAxis, &ob->rotAngle);
616 unit_axis_angle(ob->drotAxis, &ob->drotAngle);
621 /* rotation locks should be 4D for 4 component rotations by default... */
622 ob->protectflag = OB_LOCK_ROT4D;
624 unit_m4(ob->constinv);
625 unit_m4(ob->parentinv);
628 ob->empty_drawtype = OB_PLAINAXES;
629 ob->empty_drawsize = 1.0;
631 if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
632 ob->trackflag = OB_NEGZ;
633 ob->upflag = OB_POSY;
636 ob->trackflag = OB_POSY;
637 ob->upflag = OB_POSZ;
640 ob->dupon = 1; ob->dupoff = 0;
641 ob->dupsta = 1; ob->dupend = 100;
642 ob->dupfacesca = 1.0;
644 /* Game engine defaults*/
645 ob->mass = ob->inertia = 1.0f;
646 ob->formfactor = 0.4f;
649 ob->anisotropicFriction[0] = 1.0f;
650 ob->anisotropicFriction[1] = 1.0f;
651 ob->anisotropicFriction[2] = 1.0f;
652 ob->gameflag = OB_PROP | OB_COLLISION;
656 ob->obstacleRad = 1.0f;
657 ob->step_height = 0.15f;
658 ob->jump_speed = 10.0f;
659 ob->fall_speed = 55.0f;
661 ob->col_group = 0x01;
662 ob->col_mask = 0xffff;
665 /* NT fluid sim defaults */
666 ob->fluidsimSettings = NULL;
668 BLI_listbase_clear(&ob->pc_ids);
670 /* Animation Visualization defaults */
671 animviz_settings_init(&ob->avs);
674 /* more general add: creates minimum required data, but without vertices etc. */
675 Object *BKE_object_add_only_object(Main *bmain, int type, const char *name)
680 name = get_obdata_defname(type);
682 ob = BKE_libblock_alloc(bmain, ID_OB, name);
684 /* default object vars */
692 /* general add: to scene, with layer from area and default name */
693 /* creates minimum required data, but without vertices etc. */
694 Object *BKE_object_add(
695 Main *bmain, Scene *scene, SceneLayer *sl,
696 int type, const char *name)
702 ob = BKE_object_add_only_object(bmain, type, name);
704 ob->data = BKE_object_obdata_add_from_type(bmain, type, name);
706 lc = BKE_layer_collection_active(sl);
709 BLI_assert(BLI_listbase_count_ex(&sl->layer_collections, 1) == 0);
710 /* when there is no collection linked to this SceneLayer, create one */
711 SceneCollection *sc = BKE_collection_add(scene, NULL, NULL);
712 lc = BKE_collection_link(sl, sc);
715 BKE_collection_object_add(scene, lc->scene_collection, ob);
717 base = BKE_scene_layer_base_find(sl, ob);
718 BKE_scene_layer_base_deselect_all(sl);
719 BKE_scene_layer_base_select(sl, base);
721 DEG_id_tag_update_ex(bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
726 #ifdef WITH_GAMEENGINE
728 void BKE_object_lod_add(Object *ob)
730 LodLevel *lod = MEM_callocN(sizeof(LodLevel), "LoD Level");
731 LodLevel *last = ob->lodlevels.last;
733 /* If the lod list is empty, initialize it with the base lod level */
735 LodLevel *base = MEM_callocN(sizeof(LodLevel), "Base LoD Level");
736 BLI_addtail(&ob->lodlevels, base);
737 base->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT;
739 base->obhysteresis = 10;
740 last = ob->currentlod = base;
743 lod->distance = last->distance + 25.0f;
744 lod->obhysteresis = 10;
745 lod->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT;
747 BLI_addtail(&ob->lodlevels, lod);
750 static int lod_cmp(const void *a, const void *b)
752 const LodLevel *loda = a;
753 const LodLevel *lodb = b;
755 if (loda->distance < lodb->distance) return -1;
756 return loda->distance > lodb->distance;
759 void BKE_object_lod_sort(Object *ob)
761 BLI_listbase_sort(&ob->lodlevels, lod_cmp);
764 bool BKE_object_lod_remove(Object *ob, int level)
768 if (level < 1 || level > BLI_listbase_count(&ob->lodlevels) - 1)
771 rem = BLI_findlink(&ob->lodlevels, level);
773 if (rem == ob->currentlod) {
774 ob->currentlod = rem->prev;
777 BLI_remlink(&ob->lodlevels, rem);
780 /* If there are no user defined lods, remove the base lod as well */
781 if (BLI_listbase_is_single(&ob->lodlevels)) {
782 LodLevel *base = ob->lodlevels.first;
783 BLI_remlink(&ob->lodlevels, base);
785 ob->currentlod = NULL;
791 static LodLevel *lod_level_select(Object *ob, const float camera_position[3])
793 LodLevel *current = ob->currentlod;
796 if (!current) return NULL;
798 dist_sq = len_squared_v3v3(ob->obmat[3], camera_position);
800 if (dist_sq < SQUARE(current->distance)) {
801 /* check for higher LoD */
802 while (current->prev && dist_sq < SQUARE(current->distance)) {
803 current = current->prev;
807 /* check for lower LoD */
808 while (current->next && dist_sq > SQUARE(current->next->distance)) {
809 current = current->next;
816 bool BKE_object_lod_is_usable(Object *ob, SceneLayer *sl)
818 bool active = (sl) ? ob == OBACT_NEW : false;
819 return (ob->mode == OB_MODE_OBJECT || !active);
822 void BKE_object_lod_update(Object *ob, const float camera_position[3])
824 LodLevel *cur_level = ob->currentlod;
825 LodLevel *new_level = lod_level_select(ob, camera_position);
827 if (new_level != cur_level) {
828 ob->currentlod = new_level;
832 static Object *lod_ob_get(Object *ob, SceneLayer *sl, int flag)
834 LodLevel *current = ob->currentlod;
836 if (!current || !BKE_object_lod_is_usable(ob, sl))
839 while (current->prev && (!(current->flags & flag) || !current->source || current->source->type != OB_MESH)) {
840 current = current->prev;
843 return current->source;
846 struct Object *BKE_object_lod_meshob_get(Object *ob, SceneLayer *sl)
848 return lod_ob_get(ob, sl, OB_LOD_USE_MESH);
851 struct Object *BKE_object_lod_matob_get(Object *ob, SceneLayer *sl)
853 return lod_ob_get(ob, sl, OB_LOD_USE_MAT);
856 #endif /* WITH_GAMEENGINE */
859 SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches)
863 if (sb == NULL) return(NULL);
865 sbn = MEM_dupallocN(sb);
867 if (copy_caches == false) {
868 sbn->totspring = sbn->totpoint = 0;
873 sbn->totspring = sb->totspring;
874 sbn->totpoint = sb->totpoint;
879 sbn->bpoint = MEM_dupallocN(sbn->bpoint);
881 for (i = 0; i < sbn->totpoint; i++) {
882 if (sbn->bpoint[i].springs)
883 sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs);
888 sbn->bspring = MEM_dupallocN(sb->bspring);
892 sbn->totkey = sbn->totpointkey = 0;
896 sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches);
898 if (sb->effector_weights)
899 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
904 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
906 BulletSoftBody *bsbn;
910 bsbn = MEM_dupallocN(bsb);
911 /* no pointer in this structure yet */
915 ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys)
917 ParticleSystem *psysn;
921 psysn = MEM_dupallocN(psys);
922 psysn->particles = MEM_dupallocN(psys->particles);
923 psysn->child = MEM_dupallocN(psys->child);
925 if (psys->part->type == PART_HAIR) {
926 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++)
927 pa->hair = MEM_dupallocN(pa->hair);
930 if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
931 ParticleKey *key = psysn->particles->keys;
932 BoidParticle *boid = psysn->particles->boid;
935 key = MEM_dupallocN(key);
938 boid = MEM_dupallocN(boid);
940 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) {
951 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
952 modifier_copyData((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd);
953 psys->hair_in_dm = psys->hair_out_dm = NULL;
956 BLI_duplicatelist(&psysn->targets, &psys->targets);
958 psysn->pathcache = NULL;
959 psysn->childcache = NULL;
962 psysn->effectors = NULL;
964 psysn->bvhtree = NULL;
966 BLI_listbase_clear(&psysn->pathcachebufs);
967 BLI_listbase_clear(&psysn->childcachebufs);
968 psysn->renderdata = NULL;
970 psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, false);
972 /* XXX - from reading existing code this seems correct but intended usage of
973 * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
975 psysn->clmd->point_cache = psysn->pointcache;
978 id_us_plus((ID *)psysn->part);
983 void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src)
985 ParticleSystem *psys, *npsys;
988 if (ob_dst->type != OB_MESH) {
989 /* currently only mesh objects can have soft body */
993 BLI_listbase_clear(&ob_dst->particlesystem);
994 for (psys = ob_src->particlesystem.first; psys; psys = psys->next) {
995 npsys = BKE_object_copy_particlesystem(psys);
997 BLI_addtail(&ob_dst->particlesystem, npsys);
999 /* need to update particle modifiers too */
1000 for (md = ob_dst->modifiers.first; md; md = md->next) {
1001 if (md->type == eModifierType_ParticleSystem) {
1002 ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md;
1003 if (psmd->psys == psys)
1006 else if (md->type == eModifierType_DynamicPaint) {
1007 DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1009 if (pmd->brush->psys == psys) {
1010 pmd->brush->psys = npsys;
1014 else if (md->type == eModifierType_Smoke) {
1015 SmokeModifierData *smd = (SmokeModifierData *) md;
1017 if (smd->type == MOD_SMOKE_TYPE_FLOW) {
1019 if (smd->flow->psys == psys)
1020 smd->flow->psys = npsys;
1028 void BKE_object_copy_softbody(Object *ob_dst, const Object *ob_src)
1031 ob_dst->softflag = ob_src->softflag;
1032 ob_dst->soft = copy_softbody(ob_src->soft, false);
1036 static void copy_object_pose(Object *obn, Object *ob)
1040 /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */
1042 BKE_pose_copy_data(&obn->pose, ob->pose, 1); /* 1 = copy constraints */
1044 for (chan = obn->pose->chanbase.first; chan; chan = chan->next) {
1047 chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE);
1049 for (con = chan->constraints.first; con; con = con->next) {
1050 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1051 ListBase targets = {NULL, NULL};
1052 bConstraintTarget *ct;
1054 if (cti && cti->get_constraint_targets) {
1055 cti->get_constraint_targets(con, &targets);
1057 for (ct = targets.first; ct; ct = ct->next) {
1062 if (cti->flush_constraint_targets)
1063 cti->flush_constraint_targets(con, &targets, 0);
1069 static void copy_object_lod(Object *obn, Object *ob)
1071 BLI_duplicatelist(&obn->lodlevels, &ob->lodlevels);
1073 if (obn->lodlevels.first)
1074 ((LodLevel *)obn->lodlevels.first)->source = obn;
1076 obn->currentlod = (LodLevel *)obn->lodlevels.first;
1079 bool BKE_object_pose_context_check(Object *ob)
1082 (ob->type == OB_ARMATURE) &&
1084 (ob->mode & OB_MODE_POSE))
1093 Object *BKE_object_pose_armature_get(Object *ob)
1098 if (BKE_object_pose_context_check(ob))
1101 ob = modifiers_isDeformedByArmature(ob);
1103 if (BKE_object_pose_context_check(ob))
1109 void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
1111 copy_v3_v3(ob_tar->loc, ob_src->loc);
1112 copy_v3_v3(ob_tar->rot, ob_src->rot);
1113 copy_v3_v3(ob_tar->quat, ob_src->quat);
1114 copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1115 ob_tar->rotAngle = ob_src->rotAngle;
1116 ob_tar->rotmode = ob_src->rotmode;
1117 copy_v3_v3(ob_tar->size, ob_src->size);
1120 Object *BKE_object_copy_ex(Main *bmain, Object *ob, bool copy_caches)
1126 obn = BKE_libblock_copy(bmain, &ob->id);
1129 obn->mat = MEM_dupallocN(ob->mat);
1130 obn->matbits = MEM_dupallocN(ob->matbits);
1131 obn->totcol = ob->totcol;
1134 if (ob->iuser) obn->iuser = MEM_dupallocN(ob->iuser);
1136 if (ob->bb) obn->bb = MEM_dupallocN(ob->bb);
1137 obn->flag &= ~OB_FROMGROUP;
1139 BLI_listbase_clear(&obn->modifiers);
1141 for (md = ob->modifiers.first; md; md = md->next) {
1142 ModifierData *nmd = modifier_new(md->type);
1143 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1144 modifier_copyData(md, nmd);
1145 BLI_addtail(&obn->modifiers, nmd);
1148 BLI_listbase_clear(&obn->prop);
1149 BKE_bproperty_copy_list(&obn->prop, &ob->prop);
1151 BKE_sca_logic_copy(obn, ob);
1154 copy_object_pose(obn, ob);
1155 /* backwards compat... non-armatures can get poses in older files? */
1156 if (ob->type == OB_ARMATURE)
1157 BKE_pose_rebuild(obn, obn->data);
1159 defgroup_copy_list(&obn->defbase, &ob->defbase);
1160 BKE_constraints_copy(&obn->constraints, &ob->constraints, true);
1162 obn->mode = OB_MODE_OBJECT;
1165 /* increase user numbers */
1166 id_us_plus((ID *)obn->data);
1167 id_us_plus((ID *)obn->poselib);
1168 id_us_plus((ID *)obn->gpd);
1169 id_us_plus((ID *)obn->dup_group);
1171 for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1174 obn->pd = MEM_dupallocN(ob->pd);
1176 id_us_plus(&(obn->pd->tex->id));
1178 obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1180 obn->soft = copy_softbody(ob->soft, copy_caches);
1181 obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1182 obn->rigidbody_object = BKE_rigidbody_copy_object(ob);
1183 obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob);
1185 BKE_object_copy_particlesystems(obn, ob);
1187 obn->derivedDeform = NULL;
1188 obn->derivedFinal = NULL;
1190 BLI_listbase_clear(&obn->gpulamp);
1191 BLI_listbase_clear(&obn->pc_ids);
1192 BLI_listbase_clear(&obn->drawdata);
1196 copy_object_lod(obn, ob);
1198 /* Copy runtime surve data. */
1199 obn->curve_cache = NULL;
1201 BKE_id_copy_ensure_local(bmain, &ob->id, &obn->id);
1203 /* Do not copy object's preview (mostly due to the fact renderers create temp copy of objects). */
1204 obn->preview = NULL;
1209 /* copy objects, will re-initialize cached simulation data */
1210 Object *BKE_object_copy(Main *bmain, Object *ob)
1212 return BKE_object_copy_ex(bmain, ob, false);
1215 void BKE_object_make_local_ex(Main *bmain, Object *ob, const bool lib_local, const bool clear_proxy)
1217 bool is_local = false, is_lib = false;
1219 /* - only lib users: do nothing (unless force_local is set)
1220 * - only local users: set flag
1221 * - mixed: make copy
1222 * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
1225 if (!ID_IS_LINKED_DATABLOCK(ob)) {
1229 BKE_library_ID_test_usages(bmain, ob, &is_local, &is_lib);
1231 if (lib_local || is_local) {
1233 id_clear_lib_data(bmain, &ob->id);
1234 BKE_id_expand_local(bmain, &ob->id);
1236 if (ob->proxy_from != NULL) {
1237 ob->proxy_from->proxy = NULL;
1238 ob->proxy_from->proxy_group = NULL;
1240 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
1244 Object *ob_new = BKE_object_copy(bmain, ob);
1247 ob_new->proxy = ob_new->proxy_from = ob_new->proxy_group = NULL;
1249 /* setting newid is mandatory for complex make_lib_local logic... */
1250 ID_NEW_SET(ob, ob_new);
1253 BKE_libblock_remap(bmain, ob, ob_new, ID_REMAP_SKIP_INDIRECT_USAGE);
1259 void BKE_object_make_local(Main *bmain, Object *ob, const bool lib_local)
1261 BKE_object_make_local_ex(bmain, ob, lib_local, true);
1264 /* Returns true if the Object is from an external blend file (libdata) */
1265 bool BKE_object_is_libdata(Object *ob)
1267 return (ob && ID_IS_LINKED_DATABLOCK(ob));
1270 /* Returns true if the Object data is from an external blend file (libdata) */
1271 bool BKE_object_obdata_is_libdata(Object *ob)
1273 /* Linked objects with local obdata are forbidden! */
1274 BLI_assert(!ob || !ob->data || (ID_IS_LINKED_DATABLOCK(ob) ? ID_IS_LINKED_DATABLOCK(ob->data) : true));
1275 return (ob && ob->data && ID_IS_LINKED_DATABLOCK(ob->data));
1278 /* *************** PROXY **************** */
1280 /* when you make proxy, ensure the exposed layers are extern */
1281 static void armature_set_id_extern(Object *ob)
1283 bArmature *arm = ob->data;
1284 bPoseChannel *pchan;
1285 unsigned int lay = arm->layer_protected;
1287 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1288 if (!(pchan->bone->layer & lay))
1289 id_lib_extern((ID *)pchan->custom);
1294 void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
1296 if ((target->adt) && (target->adt->drivers.first)) {
1299 /* add new animdata block */
1301 ob->adt = BKE_animdata_add_id(&ob->id);
1303 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1304 free_fcurves(&ob->adt->drivers);
1305 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1307 for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) {
1308 ChannelDriver *driver = fcu->driver;
1311 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1313 DRIVER_TARGETS_LOOPER(dvar)
1316 if ((Object *)dtar->id == target)
1317 dtar->id = (ID *)ob;
1319 /* only on local objects because this causes indirect links
1320 * 'a -> b -> c', blend to point directly to a.blend
1321 * when a.blend has a proxy thats linked into c.blend */
1322 if (!ID_IS_LINKED_DATABLOCK(ob))
1323 id_lib_extern((ID *)dtar->id);
1327 DRIVER_TARGETS_LOOPER_END
1333 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1334 /* local_object->proxy == pointer to library object, saved in files and read */
1335 /* local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1337 void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
1339 /* paranoia checks */
1340 if (ID_IS_LINKED_DATABLOCK(ob) || !ID_IS_LINKED_DATABLOCK(target)) {
1341 printf("cannot make proxy\n");
1346 ob->proxy_group = gob;
1347 id_lib_extern(&target->id);
1349 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1350 DEG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1353 * - gob means this proxy comes from a group, just apply the matrix
1354 * so the object wont move from its dupli-transform.
1356 * - no gob means this is being made from a linked object,
1357 * this is closer to making a copy of the object - in-place. */
1359 ob->rotmode = target->rotmode;
1360 mul_m4_m4m4(ob->obmat, gob->obmat, target->obmat);
1361 if (gob->dup_group) { /* should always be true */
1363 mul_v3_mat3_m4v3(tvec, ob->obmat, gob->dup_group->dupli_ofs);
1364 sub_v3_v3(ob->obmat[3], tvec);
1366 BKE_object_apply_mat4(ob, ob->obmat, false, true);
1369 BKE_object_transform_copy(ob, target);
1370 ob->parent = target->parent; /* libdata */
1371 copy_m4_m4(ob->parentinv, target->parentinv);
1374 /* copy animdata stuff - drivers only for now... */
1375 BKE_object_copy_proxy_drivers(ob, target);
1377 /* skip constraints? */
1378 /* FIXME: this is considered by many as a bug */
1380 /* set object type and link to data */
1381 ob->type = target->type;
1382 ob->data = target->data;
1383 id_us_plus((ID *)ob->data); /* ensures lib data becomes LIB_TAG_EXTERN */
1385 /* copy vertex groups */
1386 defgroup_copy_list(&ob->defbase, &target->defbase);
1388 /* copy material and index information */
1389 ob->actcol = ob->totcol = 0;
1390 if (ob->mat) MEM_freeN(ob->mat);
1391 if (ob->matbits) MEM_freeN(ob->matbits);
1394 if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1397 ob->actcol = target->actcol;
1398 ob->totcol = target->totcol;
1400 ob->mat = MEM_dupallocN(target->mat);
1401 ob->matbits = MEM_dupallocN(target->matbits);
1402 for (i = 0; i < target->totcol; i++) {
1403 /* don't need to run test_object_materials since we know this object is new and not used elsewhere */
1404 id_us_plus((ID *)ob->mat[i]);
1408 /* type conversions */
1409 if (target->type == OB_ARMATURE) {
1410 copy_object_pose(ob, target); /* data copy, object pointers in constraints */
1411 BKE_pose_rest(ob->pose); /* clear all transforms in channels */
1412 BKE_pose_rebuild(ob, ob->data); /* set all internal links */
1414 armature_set_id_extern(ob);
1416 else if (target->type == OB_EMPTY) {
1417 ob->empty_drawtype = target->empty_drawtype;
1418 ob->empty_drawsize = target->empty_drawsize;
1421 /* copy IDProperties */
1422 if (ob->id.properties) {
1423 IDP_FreeProperty(ob->id.properties);
1424 MEM_freeN(ob->id.properties);
1425 ob->id.properties = NULL;
1427 if (target->id.properties) {
1428 ob->id.properties = IDP_CopyProperty(target->id.properties);
1431 /* copy drawtype info */
1432 ob->dt = target->dt;
1436 * Use with newly created objects to set their size
1437 * (used to apply scene-scale).
1439 void BKE_object_obdata_size_init(struct Object *ob, const float size)
1441 /* apply radius as a scale to types that support it */
1445 ob->empty_drawsize *= size;
1450 Curve *cu = ob->data;
1456 Camera *cam = ob->data;
1457 cam->drawsize *= size;
1462 Lamp *lamp = ob->data;
1464 lamp->area_size *= size;
1465 lamp->area_sizey *= size;
1466 lamp->area_sizez *= size;
1469 /* Only lattice (not mesh, curve, mball...),
1470 * because its got data when newly added */
1473 struct Lattice *lt = ob->data;
1477 scale_m4_fl(mat, size);
1479 BKE_lattice_transform(lt, (float (*)[4])mat, false);
1485 /* *************** CALC ****************** */
1487 void BKE_object_scale_to_mat3(Object *ob, float mat[3][3])
1490 mul_v3_v3v3(vec, ob->size, ob->dscale);
1491 size_to_mat3(mat, vec);
1494 void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot)
1496 float rmat[3][3], dmat[3][3];
1498 /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1499 * with the rotation matrix to yield the appropriate rotation
1502 /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1503 if (ob->rotmode > 0) {
1504 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1505 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1506 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1508 else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1509 /* axis-angle - not really that great for 3D-changing orientations */
1510 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1511 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1514 /* quats are normalized before use to eliminate scaling issues */
1517 normalize_qt_qt(tquat, ob->quat);
1518 quat_to_mat3(rmat, tquat);
1520 normalize_qt_qt(tquat, ob->dquat);
1521 quat_to_mat3(dmat, tquat);
1524 /* combine these rotations */
1526 mul_m3_m3m3(mat, dmat, rmat);
1528 copy_m3_m3(mat, rmat);
1531 void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], bool use_compat)
1533 BLI_ASSERT_UNIT_M3(mat);
1535 switch (ob->rotmode) {
1539 mat3_normalized_to_quat(ob->quat, mat);
1540 normalize_qt_qt(dquat, ob->dquat);
1541 invert_qt_normalized(dquat);
1542 mul_qt_qtqt(ob->quat, dquat, ob->quat);
1545 case ROT_MODE_AXISANGLE:
1550 /* without drot we could apply 'mat' directly */
1551 mat3_normalized_to_quat(quat, mat);
1552 axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
1553 invert_qt_normalized(dquat);
1554 mul_qt_qtqt(quat, dquat, quat);
1555 quat_to_axis_angle(ob->rotAxis, &ob->rotAngle, quat);
1558 default: /* euler */
1563 /* without drot we could apply 'mat' directly */
1564 mat3_normalized_to_quat(quat, mat);
1565 eulO_to_quat(dquat, ob->drot, ob->rotmode);
1566 invert_qt_normalized(dquat);
1567 mul_qt_qtqt(quat, dquat, quat);
1568 /* end drot correction */
1570 if (use_compat) quat_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, quat);
1571 else quat_to_eulO(ob->rot, ob->rotmode, quat);
1577 void BKE_object_tfm_protected_backup(const Object *ob,
1578 ObjectTfmProtectedChannels *obtfm)
1581 #define TFMCPY(_v) (obtfm->_v = ob->_v)
1582 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
1583 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
1604 void BKE_object_tfm_protected_restore(Object *ob,
1605 const ObjectTfmProtectedChannels *obtfm,
1606 const short protectflag)
1610 for (i = 0; i < 3; i++) {
1611 if (protectflag & (OB_LOCK_LOCX << i)) {
1612 ob->loc[i] = obtfm->loc[i];
1613 ob->dloc[i] = obtfm->dloc[i];
1616 if (protectflag & (OB_LOCK_SCALEX << i)) {
1617 ob->size[i] = obtfm->size[i];
1618 ob->dscale[i] = obtfm->dscale[i];
1621 if (protectflag & (OB_LOCK_ROTX << i)) {
1622 ob->rot[i] = obtfm->rot[i];
1623 ob->drot[i] = obtfm->drot[i];
1625 ob->quat[i + 1] = obtfm->quat[i + 1];
1626 ob->dquat[i + 1] = obtfm->dquat[i + 1];
1628 ob->rotAxis[i] = obtfm->rotAxis[i];
1629 ob->drotAxis[i] = obtfm->drotAxis[i];
1633 if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
1634 ob->quat[0] = obtfm->quat[0];
1635 ob->dquat[0] = obtfm->dquat[0];
1637 ob->rotAngle = obtfm->rotAngle;
1638 ob->drotAngle = obtfm->drotAngle;
1642 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
1649 BKE_object_scale_to_mat3(ob, smat);
1652 BKE_object_rot_to_mat3(ob, rmat, true);
1653 mul_m3_m3m3(mat, rmat, smat);
1656 void BKE_object_to_mat4(Object *ob, float mat[4][4])
1660 BKE_object_to_mat3(ob, tmat);
1662 copy_m4_m3(mat, tmat);
1664 add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1667 void BKE_object_matrix_local_get(struct Object *ob, float mat[4][4])
1670 float par_imat[4][4];
1672 BKE_object_get_parent_matrix(NULL, ob, ob->parent, par_imat);
1673 invert_m4(par_imat);
1674 mul_m4_m4m4(mat, par_imat, ob->obmat);
1677 copy_m4_m4(mat, ob->obmat);
1682 int enable_cu_speed = 1;
1685 * \param scene: Used when curve cache needs to be calculated, or for dupli-frame time.
1686 * \return success if \a mat is set.
1688 static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4])
1690 Curve *cu = par->data;
1691 float vec[4], dir[3], quat[4], radius, ctime;
1693 /* only happens on reload file, but violates depsgraph still... fix! */
1694 if (par->curve_cache == NULL) {
1695 if (scene == NULL) {
1698 BKE_displist_make_curveTypes(scene, par, 0);
1701 if (par->curve_cache->path == NULL) {
1705 /* catch exceptions: curve paths used as a duplicator */
1706 if (enable_cu_speed) {
1707 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1708 * but this will only work if it actually is animated...
1710 * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1711 * factor, which then gets clamped to lie within 0.0 - 1.0 range
1714 ctime = cu->ctime / cu->pathlen;
1720 CLAMP(ctime, 0.0f, 1.0f);
1723 /* For dupli-frames only */
1724 if (scene == NULL) {
1728 ctime = BKE_scene_frame_get(scene);
1730 ctime /= cu->pathlen;
1733 CLAMP(ctime, 0.0f, 1.0f);
1739 if (where_on_path(par, ctime, vec, dir, (cu->flag & CU_FOLLOW) ? quat : NULL, &radius, NULL)) {
1741 if (cu->flag & CU_FOLLOW) {
1744 vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
1748 q[0] = cosf(0.5 * vec[3]);
1749 si = sinf(0.5 * vec[3]);
1750 q[1] = -si * dir[0];
1751 q[2] = -si * dir[1];
1752 q[3] = -si * dir[2];
1753 mul_qt_qtqt(quat, q, quat);
1755 quat_apply_track(quat, ob->trackflag, ob->upflag);
1758 quat_to_mat4(mat, quat);
1761 if (cu->flag & CU_PATH_RADIUS) {
1762 float tmat[4][4], rmat[4][4];
1763 scale_m4_fl(tmat, radius);
1764 mul_m4_m4m4(rmat, tmat, mat);
1765 copy_m4_m4(mat, rmat);
1768 copy_v3_v3(mat[3], vec);
1775 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
1777 bPoseChannel *pchan;
1780 if (par->type != OB_ARMATURE) {
1785 /* Make sure the bone is still valid */
1786 pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
1787 if (!pchan || !pchan->bone) {
1788 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
1793 /* get bone transform */
1794 if (pchan->bone->flag & BONE_RELATIVE_PARENTING) {
1795 /* the new option uses the root - expected bahaviour, but differs from old... */
1796 /* XXX check on version patching? */
1797 copy_m4_m4(mat, pchan->chan_mat);
1800 copy_m4_m4(mat, pchan->pose_mat);
1802 /* but for backwards compatibility, the child has to move to the tail */
1803 copy_v3_v3(vec, mat[1]);
1804 mul_v3_fl(vec, pchan->bone->length);
1805 add_v3_v3(mat[3], vec);
1809 static void give_parvert(Object *par, int nr, float vec[3])
1813 if (par->type == OB_MESH) {
1814 Mesh *me = par->data;
1815 BMEditMesh *em = me->edit_btmesh;
1818 dm = (em) ? em->derivedFinal : par->derivedFinal;
1822 int numVerts = dm->getNumVerts(dm);
1824 if (nr < numVerts) {
1825 bool use_special_ss_case = false;
1827 if (dm->type == DM_TYPE_CCGDM) {
1829 VirtualModifierData virtualModifierData;
1830 use_special_ss_case = true;
1831 for (md = modifiers_getVirtualModifierList(par, &virtualModifierData);
1835 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1836 /* TODO(sergey): Check for disabled modifiers. */
1837 if (mti->type != eModifierTypeType_OnlyDeform && md->next != NULL) {
1838 use_special_ss_case = false;
1844 if (!use_special_ss_case) {
1845 /* avoid dm->getVertDataArray() since it allocates arrays in the dm (not thread safe) */
1846 if (em && dm->type == DM_TYPE_EDITBMESH) {
1847 if (em->bm->elem_table_dirty & BM_VERT) {
1848 #ifdef VPARENT_THREADING_HACK
1849 BLI_mutex_lock(&vparent_lock);
1850 if (em->bm->elem_table_dirty & BM_VERT) {
1851 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
1853 BLI_mutex_unlock(&vparent_lock);
1855 BLI_assert(!"Not safe for threading");
1856 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
1862 if (use_special_ss_case) {
1863 /* Special case if the last modifier is SS and no constructive modifier are in front of it. */
1864 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1865 CCGVert *ccg_vert = ccgSubSurf_getVert(ccgdm->ss, SET_INT_IN_POINTER(nr));
1866 /* In case we deleted some verts, nr may refer to inexistent one now, see T42557. */
1868 float *co = ccgSubSurf_getVertData(ccgdm->ss, ccg_vert);
1873 else if (CustomData_has_layer(&dm->vertData, CD_ORIGINDEX) &&
1874 !(em && dm->type == DM_TYPE_EDITBMESH))
1878 /* Get the average of all verts with (original index == nr). */
1879 for (i = 0; i < numVerts; i++) {
1880 const int *index = dm->getVertData(dm, i, CD_ORIGINDEX);
1883 dm->getVertCo(dm, i, co);
1890 if (nr < numVerts) {
1892 dm->getVertCo(dm, nr, co);
1900 /* keep as 0, 0, 0 */
1902 else if (count > 0) {
1903 mul_v3_fl(vec, 1.0f / count);
1906 /* use first index if its out of range */
1907 dm->getVertCo(dm, 0, vec);
1912 "%s: DerivedMesh is needed to solve parenting, "
1913 "object position can be wrong now\n", __func__);
1916 else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1919 /* Unless there's some weird depsgraph failure the cache should exist. */
1920 BLI_assert(par->curve_cache != NULL);
1922 if (par->curve_cache->deformed_nurbs.first != NULL) {
1923 nurb = &par->curve_cache->deformed_nurbs;
1926 Curve *cu = par->data;
1927 nurb = BKE_curve_nurbs_get(cu);
1930 BKE_nurbList_index_get_co(nurb, nr, vec);
1932 else if (par->type == OB_LATTICE) {
1933 Lattice *latt = par->data;
1934 DispList *dl = par->curve_cache ? BKE_displist_find(&par->curve_cache->disp, DL_VERTS) : NULL;
1935 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
1938 if (latt->editlatt) latt = latt->editlatt->latt;
1940 tot = latt->pntsu * latt->pntsv * latt->pntsw;
1942 /* ensure dl is correct size */
1943 BLI_assert(dl == NULL || dl->nr == tot);
1947 copy_v3_v3(vec, co[nr]);
1950 copy_v3_v3(vec, latt->def[nr].vec);
1956 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
1959 /* in local ob space */
1960 if (OB_TYPE_SUPPORT_PARVERT(par->type)) {
1961 float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1963 give_parvert(par, ob->par1, v1);
1964 give_parvert(par, ob->par2, v2);
1965 give_parvert(par, ob->par3, v3);
1967 tri_to_quat(q, v1, v2, v3);
1968 quat_to_mat3(cmat, q);
1969 copy_m4_m3(mat, cmat);
1971 mid_v3_v3v3v3(mat[3], v1, v2, v3);
1979 void BKE_object_get_parent_matrix(Scene *scene, Object *ob, Object *par, float parentmat[4][4])
1985 switch (ob->partype & PARTYPE) {
1988 if (par->type == OB_CURVE) {
1989 if ((((Curve *)par->data)->flag & CU_PATH) &&
1990 (ob_parcurve(scene, ob, par, tmat)))
1996 if (ok) mul_m4_m4m4(parentmat, par->obmat, tmat);
1997 else copy_m4_m4(parentmat, par->obmat);
2001 ob_parbone(ob, par, tmat);
2002 mul_m4_m4m4(parentmat, par->obmat, tmat);
2007 give_parvert(par, ob->par1, vec);
2008 mul_v3_m4v3(parentmat[3], par->obmat, vec);
2011 ob_parvert3(ob, par, tmat);
2013 mul_m4_m4m4(parentmat, par->obmat, tmat);
2017 copy_m4_m4(parentmat, par->obmat);
2024 * \param r_originmat Optional matrix that stores the space the object is in (without its own matrix applied)
2026 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4][4], float slowmat[4][4],
2027 float r_originmat[3][3], const bool set_origin)
2033 BKE_object_to_mat4(ob, locmat);
2035 if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2037 BKE_object_get_parent_matrix(scene, ob, par, totmat);
2040 mul_m4_m4m4(tmat, totmat, ob->parentinv);
2041 mul_m4_m4m4(obmat, tmat, locmat);
2044 /* usable originmat */
2045 copy_m3_m4(r_originmat, tmat);
2048 /* origin, for help line */
2050 if ((ob->partype & PARTYPE) == PARSKEL) {
2051 copy_v3_v3(ob->orig, par->obmat[3]);
2054 copy_v3_v3(ob->orig, totmat[3]);
2059 static bool where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
2065 /* include framerate */
2066 fac1 = (1.0f / (1.0f + fabsf(ob->sf)));
2067 if (fac1 >= 1.0f) return false;
2072 for (a = 0; a < 16; a++, fp1++, fp2++) {
2073 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2079 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2080 void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime,
2081 RigidBodyWorld *rbw, float r_originmat[3][3])
2083 if (ob == NULL) return;
2085 /* execute drivers only, as animation has already been done */
2086 BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2089 Object *par = ob->parent;
2090 float slowmat[4][4];
2092 /* calculate parent matrix */
2093 solve_parenting(scene, ob, par, ob->obmat, slowmat, r_originmat, true);
2095 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around
2096 * An old-fashioned hack which probably doesn't really cut it anymore
2098 if (ob->partype & PARSLOW) {
2099 if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2104 BKE_object_to_mat4(ob, ob->obmat);
2107 /* try to fall back to the scene rigid body world if none given */
2108 rbw = rbw ? rbw : scene->rigidbody_world;
2109 /* read values pushed into RBO from sim/cache... */
2110 BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2112 /* solve constraints */
2113 if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2115 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2116 BKE_constraints_solve(&ob->constraints, cob, ctime);
2117 BKE_constraints_clear_evalob(cob);
2120 /* set negative scale flag in object */
2121 if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2122 else ob->transflag &= ~OB_NEG_SCALE;
2125 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2127 BKE_object_where_is_calc_time_ex(scene, ob, ctime, NULL, NULL);
2130 /* get object transformation matrix without recalculating dependencies and
2131 * constraints -- assume dependencies are already solved by depsgraph.
2132 * no changes to object and it's parent would be done.
2133 * used for bundles orientation in 3d space relative to parented blender camera */
2134 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2138 float slowmat[4][4];
2140 Object *par = ob->parent;
2142 solve_parenting(scene, ob, par, obmat, slowmat, NULL, false);
2144 if (ob->partype & PARSLOW)
2145 where_is_object_parslow(ob, obmat, slowmat);
2148 BKE_object_to_mat4(ob, obmat);
2152 void BKE_object_where_is_calc_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob, float r_originmat[3][3])
2154 BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), rbw, r_originmat);
2156 void BKE_object_where_is_calc(Scene *scene, Object *ob)
2158 BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), NULL, NULL);
2161 /* for calculation of the inverse parent transform, only used for editor */
2162 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2164 BKE_object_workob_clear(workob);
2166 unit_m4(workob->obmat);
2167 unit_m4(workob->parentinv);
2168 unit_m4(workob->constinv);
2169 workob->parent = ob->parent;
2171 workob->trackflag = ob->trackflag;
2172 workob->upflag = ob->upflag;
2174 workob->partype = ob->partype;
2175 workob->par1 = ob->par1;
2176 workob->par2 = ob->par2;
2177 workob->par3 = ob->par3;
2179 workob->constraints.first = ob->constraints.first;
2180 workob->constraints.last = ob->constraints.last;
2182 BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2184 BKE_object_where_is_calc(scene, workob);
2187 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
2188 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const bool use_compat, const bool use_parent)
2192 if (use_parent && ob->parent) {
2193 float rmat[4][4], diff_mat[4][4], imat[4][4], parent_mat[4][4];
2195 BKE_object_get_parent_matrix(NULL, ob, ob->parent, parent_mat);
2197 mul_m4_m4m4(diff_mat, parent_mat, ob->parentinv);
2198 invert_m4_m4(imat, diff_mat);
2199 mul_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
2201 /* same as below, use rmat rather than mat */
2202 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
2205 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
2208 BKE_object_mat3_to_rot(ob, rot, use_compat);
2210 sub_v3_v3(ob->loc, ob->dloc);
2212 if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
2213 if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
2214 if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
2216 /* BKE_object_mat3_to_rot handles delta rotations */
2219 BoundBox *BKE_boundbox_alloc_unit(void)
2222 const float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2224 bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2225 BKE_boundbox_init_from_minmax(bb, min, max);
2230 void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float max[3])
2232 bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2233 bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2235 bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2236 bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2238 bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2239 bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2242 void BKE_boundbox_calc_center_aabb(const BoundBox *bb, float r_cent[3])
2244 r_cent[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]);
2245 r_cent[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]);
2246 r_cent[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]);
2249 void BKE_boundbox_calc_size_aabb(const BoundBox *bb, float r_size[3])
2251 r_size[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]);
2252 r_size[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]);
2253 r_size[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]);
2256 void BKE_boundbox_minmax(const BoundBox *bb, float obmat[4][4], float r_min[3], float r_max[3])
2259 for (i = 0; i < 8; i++) {
2261 mul_v3_m4v3(vec, obmat, bb->vec[i]);
2262 minmax_v3v3_v3(r_min, r_max, vec);
2266 BoundBox *BKE_object_boundbox_get(Object *ob)
2268 BoundBox *bb = NULL;
2270 if (ob->type == OB_MESH) {
2271 bb = BKE_mesh_boundbox_get(ob);
2273 else if (ELEM(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2274 bb = BKE_curve_boundbox_get(ob);
2276 else if (ob->type == OB_MBALL) {
2279 else if (ob->type == OB_LATTICE) {
2280 bb = BKE_lattice_boundbox_get(ob);
2282 else if (ob->type == OB_ARMATURE) {
2283 bb = BKE_armature_boundbox_get(ob);
2288 /* used to temporally disable/enable boundbox */
2289 void BKE_object_boundbox_flag(Object *ob, int flag, const bool set)
2291 BoundBox *bb = BKE_object_boundbox_get(ob);
2293 if (set) bb->flag |= flag;
2294 else bb->flag &= ~flag;
2298 void BKE_object_dimensions_get(Object *ob, float vec[3])
2300 BoundBox *bb = NULL;
2302 bb = BKE_object_boundbox_get(ob);
2306 mat4_to_size(scale, ob->obmat);
2308 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2309 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2310 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2317 void BKE_object_dimensions_set(Object *ob, const float value[3])
2319 BoundBox *bb = NULL;
2321 bb = BKE_object_boundbox_get(ob);
2323 float scale[3], len[3];
2325 mat4_to_size(scale, ob->obmat);
2327 len[0] = bb->vec[4][0] - bb->vec[0][0];
2328 len[1] = bb->vec[2][1] - bb->vec[0][1];
2329 len[2] = bb->vec[1][2] - bb->vec[0][2];
2331 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2332 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2333 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2337 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool use_hidden)
2341 bool changed = false;
2348 bb = *BKE_curve_boundbox_get(ob);
2349 BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2355 Lattice *lt = ob->data;
2356 BPoint *bp = lt->def;
2359 for (w = 0; w < lt->pntsw; w++) {
2360 for (v = 0; v < lt->pntsv; v++) {
2361 for (u = 0; u < lt->pntsu; u++, bp++) {
2362 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2363 minmax_v3v3_v3(min_r, max_r, vec);
2372 changed = BKE_pose_minmax(ob, min_r, max_r, use_hidden, false);
2377 Mesh *me = BKE_mesh_from_object(ob);
2380 bb = *BKE_mesh_boundbox_get(ob);
2381 BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2388 float ob_min[3], ob_max[3];
2390 changed = BKE_mball_minmax_ex(ob->data, ob_min, ob_max, ob->obmat, 0);
2392 minmax_v3v3_v3(min_r, max_r, ob_min);
2393 minmax_v3v3_v3(min_r, max_r, ob_max);
2399 if (changed == false) {
2402 copy_v3_v3(size, ob->size);
2403 if (ob->type == OB_EMPTY) {
2404 mul_v3_fl(size, ob->empty_drawsize);
2407 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2409 copy_v3_v3(vec, ob->obmat[3]);
2410 add_v3_v3(vec, size);
2411 minmax_v3v3_v3(min_r, max_r, vec);
2413 copy_v3_v3(vec, ob->obmat[3]);
2414 sub_v3_v3(vec, size);
2415 minmax_v3v3_v3(min_r, max_r, vec);
2419 void BKE_object_empty_draw_type_set(Object *ob, const int value)
2421 ob->empty_drawtype = value;
2423 if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
2425 ob->iuser = MEM_callocN(sizeof(ImageUser), "image user");
2427 ob->iuser->frames = 100;
2428 ob->iuser->sfra = 1;
2429 ob->iuser->fie_ima = 2;
2434 MEM_freeN(ob->iuser);
2440 bool BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const bool use_hidden)
2443 if ((ob->transflag & OB_DUPLI) == 0) {
2449 lb = object_duplilist(G.main->eval_ctx, scene, ob);
2450 for (dob = lb->first; dob; dob = dob->next) {
2451 if ((use_hidden == false) && (dob->no_draw != 0)) {
2455 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2459 for (i = 0; i < 8; i++) {
2461 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2462 minmax_v3v3_v3(r_min, r_max, vec);
2469 free_object_duplilist(lb); /* does restore */
2475 void BKE_object_foreach_display_point(
2476 Object *ob, float obmat[4][4],
2477 void (*func_cb)(const float[3], void *), void *user_data)
2481 if (ob->derivedFinal) {
2482 DerivedMesh *dm = ob->derivedFinal;
2483 MVert *mv = dm->getVertArray(dm);
2484 int totvert = dm->getNumVerts(dm);
2487 for (i = 0; i < totvert; i++, mv++) {
2488 mul_v3_m4v3(co, obmat, mv->co);
2489 func_cb(co, user_data);
2492 else if (ob->curve_cache && ob->curve_cache->disp.first) {
2495 for (dl = ob->curve_cache->disp.first; dl; dl = dl->next) {
2496 const float *v3 = dl->verts;
2497 int totvert = dl->nr;
2500 for (i = 0; i < totvert; i++, v3 += 3) {
2501 mul_v3_m4v3(co, obmat, v3);
2502 func_cb(co, user_data);
2508 void BKE_scene_foreach_display_point(
2509 Scene *scene, SceneLayer *sl,
2510 void (*func_cb)(const float[3], void *), void *user_data)
2515 for (base = FIRSTBASE_NEW; base; base = base->next) {
2516 if (((base->flag & BASE_VISIBLED) != 0) && ((base->flag & BASE_SELECTED) != 0)) {
2519 if ((ob->transflag & OB_DUPLI) == 0) {
2520 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2526 lb = object_duplilist(G.main->eval_ctx, scene, ob);
2527 for (dob = lb->first; dob; dob = dob->next) {
2528 if (dob->no_draw == 0) {
2529 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2532 free_object_duplilist(lb); /* does restore */
2538 /* copied from DNA_object_types.h */
2539 typedef struct ObTfmBack {
2540 float loc[3], dloc[3], orig[3];
2541 float size[3], dscale[3]; /* scale and delta scale */
2542 float rot[3], drot[3]; /* euler rotation */
2543 float quat[4], dquat[4]; /* quaternion rotation */
2544 float rotAxis[3], drotAxis[3]; /* axis angle rotation - axis part */
2545 float rotAngle, drotAngle; /* axis angle rotation - angle part */
2546 float obmat[4][4]; /* final worldspace matrix with constraints & animsys applied */
2547 float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2548 float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2549 float imat[4][4]; /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform */
2552 void *BKE_object_tfm_backup(Object *ob)
2554 ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2555 copy_v3_v3(obtfm->loc, ob->loc);
2556 copy_v3_v3(obtfm->dloc, ob->dloc);
2557 copy_v3_v3(obtfm->orig, ob->orig);
2558 copy_v3_v3(obtfm->size, ob->size);
2559 copy_v3_v3(obtfm->dscale, ob->dscale);
2560 copy_v3_v3(obtfm->rot, ob->rot);
2561 copy_v3_v3(obtfm->drot, ob->drot);
2562 copy_qt_qt(obtfm->quat, ob->quat);
2563 copy_qt_qt(obtfm->dquat, ob->dquat);
2564 copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2565 copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2566 obtfm->rotAngle = ob->rotAngle;
2567 obtfm->drotAngle = ob->drotAngle;
2568 copy_m4_m4(obtfm->obmat, ob->obmat);
2569 copy_m4_m4(obtfm->parentinv, ob->parentinv);
2570 copy_m4_m4(obtfm->constinv, ob->constinv);
2571 copy_m4_m4(obtfm->imat, ob->imat);
2573 return (void *)obtfm;
2576 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2578 ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2579 copy_v3_v3(ob->loc, obtfm->loc);
2580 copy_v3_v3(ob->dloc, obtfm->dloc);
2581 copy_v3_v3(ob->orig, obtfm->orig);
2582 copy_v3_v3(ob->size, obtfm->size);
2583 copy_v3_v3(ob->dscale, obtfm->dscale);
2584 copy_v3_v3(ob->rot, obtfm->rot);
2585 copy_v3_v3(ob->drot, obtfm->drot);
2586 copy_qt_qt(ob->quat, obtfm->quat);
2587 copy_qt_qt(ob->dquat, obtfm->dquat);
2588 copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2589 copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2590 ob->rotAngle = obtfm->rotAngle;
2591 ob->drotAngle = obtfm->drotAngle;
2592 copy_m4_m4(ob->obmat, obtfm->obmat);
2593 copy_m4_m4(ob->parentinv, obtfm->parentinv);
2594 copy_m4_m4(ob->constinv, obtfm->constinv);
2595 copy_m4_m4(ob->imat, obtfm->imat);
2598 bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
2600 /* test if 'ob' is a parent somewhere in par's parents */
2601 if (par == NULL) return false;
2602 if (ob == par) return true;
2603 return BKE_object_parent_loop_check(par->parent, ob);
2606 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2607 /* local_object->proxy == pointer to library object, saved in files and read */
2609 /* function below is polluted with proxy exceptions, cleanup will follow! */
2611 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2612 /* requires flags to be set! */
2613 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
2614 void BKE_object_handle_update_ex(EvaluationContext *eval_ctx,
2615 Scene *scene, Object *ob,
2616 RigidBodyWorld *rbw,
2617 const bool do_proxy_update)
2619 if (ob->recalc & OB_RECALC_ALL) {
2620 /* speed optimization for animation lookups */
2622 BKE_pose_channels_hash_make(ob->pose);
2623 if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
2624 BKE_pose_update_constraint_flags(ob->pose);
2628 if (ob->recalc & OB_RECALC_DATA) {
2629 if (ob->type == OB_ARMATURE) {
2630 /* this happens for reading old files and to match library armatures
2631 * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
2632 * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2634 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
2635 BKE_pose_rebuild(ob, ob->data);
2639 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers,
2640 * which is only in BKE_object_where_is_calc now */
2641 /* XXX: should this case be OB_RECALC_OB instead? */
2642 if (ob->recalc & OB_RECALC_ALL) {
2644 if (G.debug & G_DEBUG_DEPSGRAPH)
2645 printf("recalcob %s\n", ob->id.name + 2);
2647 /* handle proxy copy for target */
2648 if (ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from) {
2649 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2650 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
2651 Object *obg = ob->proxy_from->proxy_group;
2653 invert_m4_m4(imat, obg->obmat);
2654 mul_m4_m4m4(ob->obmat, imat, ob->proxy_from->obmat);
2655 if (obg->dup_group) { /* should always be true */
2656 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2660 copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2663 BKE_object_where_is_calc_ex(scene, rbw, ob, NULL);
2666 if (ob->recalc & OB_RECALC_DATA) {
2667 BKE_object_handle_data_update(eval_ctx, scene, ob);
2670 ob->recalc &= ~OB_RECALC_ALL;
2673 /* the case when this is a group proxy, object_update is called in group.c */
2675 /* set pointer in library proxy target, for copying, but restore it */
2676 ob->proxy->proxy_from = ob;
2677 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2679 /* the no-group proxy case, we call update */
2680 if (ob->proxy_group == NULL) {
2681 if (do_proxy_update) {
2682 // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2683 BKE_object_handle_update(eval_ctx, scene, ob->proxy);
2688 /* WARNING: "scene" here may not be the scene object actually resides in.
2689 * When dealing with background-sets, "scene" is actually the active scene.
2690 * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n
2691 * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the corrent rigid body world
2693 void BKE_object_handle_update(EvaluationContext *eval_ctx, Scene *scene, Object *ob)
2695 BKE_object_handle_update_ex(eval_ctx, scene, ob, NULL, true);
2698 void BKE_object_sculpt_modifiers_changed(Object *ob)
2700 SculptSession *ss = ob->sculpt;
2704 /* we free pbvh on changes, except during sculpt since it can't deal with
2705 * changing PVBH node organization, we hope topology does not change in
2706 * the meantime .. weak */
2708 BKE_pbvh_free(ss->pbvh);
2712 BKE_sculptsession_free_deformMats(ob->sculpt);
2718 BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2720 for (n = 0; n < totnode; n++)
2721 BKE_pbvh_node_mark_update(nodes[n]);
2728 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
2731 if (ob->data == NULL)
2734 switch (GS(((ID *)ob->data)->name)) {
2737 Mesh *me = ob->data;
2738 if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) {
2739 BKE_mesh_texspace_calc(me);
2741 if (r_texflag) *r_texflag = &me->texflag;
2742 if (r_loc) *r_loc = me->loc;
2743 if (r_size) *r_size = me->size;
2744 if (r_rot) *r_rot = me->rot;
2749 Curve *cu = ob->data;
2750 if (cu->bb == NULL || (cu->bb->flag & BOUNDBOX_DIRTY)) {
2751 BKE_curve_texspace_calc(cu);
2753 if (r_texflag) *r_texflag = &cu->texflag;
2754 if (r_loc) *r_loc = cu->loc;
2755 if (r_size) *r_size = cu->size;
2756 if (r_rot) *r_rot = cu->rot;
2761 MetaBall *mb = ob->data;
2762 if (r_texflag) *r_texflag = &mb->texflag;
2763 if (r_loc) *r_loc = mb->loc;
2764 if (r_size) *r_size = mb->size;
2765 if (r_rot) *r_rot = mb->rot;
2774 static int pc_cmp(const void *a, const void *b)
2776 const LinkData *ad = a, *bd = b;
2777 if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2782 int BKE_object_insert_ptcache(Object *ob)
2784 LinkData *link = NULL;
2787 BLI_listbase_sort(&ob->pc_ids, pc_cmp);
2789 for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) {
2790 int index = GET_INT_FROM_POINTER(link->data);
2796 link = MEM_callocN(sizeof(LinkData), "PCLink");
2797 link->data = SET_INT_IN_POINTER(i);
2798 BLI_addtail(&ob->pc_ids, link);
2803 static int pc_findindex(ListBase *listbase, int index)
2805 LinkData *link = NULL;
2808 if (listbase == NULL) return -1;
2810 link = listbase->first;
2812 if (GET_INT_FROM_POINTER(link->data) == index)
2822 void BKE_object_delete_ptcache(Object *ob, int index)
2824 int list_index = pc_findindex(&ob->pc_ids, index);
2825 LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2826 BLI_freelinkN(&ob->pc_ids, link);
2829 /* shape key utility function */
2831 /************************* Mesh ************************/
2832 static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mix)
2834 Mesh *me = ob->data;
2840 key = me->key = BKE_key_add((ID *)me);
2841 key->type = KEY_RELATIVE;
2845 if (newkey || from_mix == false) {
2846 /* create from mesh */
2847 kb = BKE_keyblock_add_ctime(key, name, false);
2848 BKE_keyblock_convert_from_mesh(me, kb);
2851 /* copy from current values */
2853 float *data = BKE_key_evaluate_object(ob, &totelem);
2855 /* create new block with prepared data */
2856 kb = BKE_keyblock_add_ctime(key, name, false);
2858 kb->totelem = totelem;
2863 /************************* Lattice ************************/
2864 static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mix)
2866 Lattice *lt = ob->data;
2872 key = lt->key = BKE_key_add((ID *)lt);
2873 key->type = KEY_RELATIVE;
2877 if (newkey || from_mix == false) {
2878 kb = BKE_keyblock_add_ctime(key, name, false);
2880 KeyBlock *basekb = (KeyBlock *)key->block.first;
2881 kb->data = MEM_dupallocN(basekb->data);
2882 kb->totelem = basekb->totelem;
2885 BKE_keyblock_convert_from_lattice(lt, kb);
2889 /* copy from current values */
2891 float *data = BKE_key_evaluate_object(ob, &totelem);
2893 /* create new block with prepared data */
2894 kb = BKE_keyblock_add_ctime(key, name, false);
2895 kb->totelem = totelem;
2901 /************************* Curve ************************/
2902 static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_mix)
2904 Curve *cu = ob->data;
2907 ListBase *lb = BKE_curve_nurbs_get(cu);
2911 key = cu->key = BKE_key_add((ID *)cu);
2912 key->type = KEY_RELATIVE;
2916 if (newkey || from_mix == false) {
2917 /* create from curve */
2918 kb = BKE_keyblock_add_ctime(key, name, false);
2920 KeyBlock *basekb = (KeyBlock *)key->block.first;
2921 kb->data = MEM_dupallocN(basekb->data);
2922 kb->totelem = basekb->totelem;
2925 BKE_keyblock_convert_from_curve(cu, kb, lb);
2929 /* copy from current values */
2931 float *data = BKE_key_evaluate_object(ob, &totelem);
2933 /* create new block with prepared data */
2934 kb = BKE_keyblock_add_ctime(key, name, false);
2935 kb->totelem = totelem;
2942 KeyBlock *BKE_object_shapekey_insert(Object *ob, const char *name, const bool from_mix)
2946 return insert_meshkey(ob, name, from_mix);
2949 return insert_curvekey(ob, name, from_mix);
2951 return insert_lattkey(ob, name, from_mix);
2958 bool BKE_object_shapekey_free(Main *bmain, Object *ob)
2962 key_p = BKE_key_from_object_p(ob);
2963 if (ELEM(NULL, key_p, *key_p)) {
2970 BKE_libblock_free_us(bmain, key);
2975 bool BKE_object_shapekey_remove(Main *bmain, Object *ob, KeyBlock *kb)
2978 Key *key = BKE_key_from_object(ob);
2985 kb_index = BLI_findindex(&key->block, kb);
2986 BLI_assert(kb_index != -1);
2988 for (rkb = key->block.first; rkb; rkb = rkb->next) {
2989 if (rkb->relative == kb_index) {
2990 /* remap to the 'Basis' */
2993 else if (rkb->relative >= kb_index) {
2994 /* Fix positional shift of the keys when kb is deleted from the list */
2999 BLI_remlink(&key->block, kb);
3001 if (key->refkey == kb) {
3002 key->refkey = key->block.first;
3005 /* apply new basis key on original data */
3008 BKE_keyblock_convert_to_mesh(key->refkey, ob->data);
3012 BKE_keyblock_convert_to_curve(key->refkey, ob->data, BKE_curve_nurbs_get(ob->data));
3015 BKE_keyblock_convert_to_lattice(key->refkey, ob->data);
3022 MEM_freeN(kb->data);
3026 if (ob->shapenr > 1) {
3030 if (key->totkey == 0) {
3031 BKE_object_shapekey_free(bmain, ob);
3037 bool BKE_object_flag_test_recursive(const Object *ob, short flag)
3039 if (ob->flag & flag) {
3042 else if (ob->parent) {
3043 return BKE_object_flag_test_recursive(ob->parent, flag);
3050 bool BKE_object_is_child_recursive(Object *ob_parent, Object *ob_child)
3052 for (ob_child = ob_child->parent; ob_child; ob_child = ob_child->parent) {
3053 if (ob_child == ob_parent) {
3060 /* most important if this is modified it should _always_ return True, in certain
3061 * cases false positives are hard to avoid (shape keys for example) */
3062 int BKE_object_is_modified(Scene *scene, Object *ob)
3066 if (BKE_key_from_object(ob)) {
3067 flag |= eModifierMode_Render | eModifierMode_Realtime;
3071 VirtualModifierData virtualModifierData;
3073 for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
3074 md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
3077 if ((flag & eModifierMode_Render) == 0 && modifier_isEnabled(scene, md, eModifierMode_Render))
3078 flag |= eModifierMode_Render;
3080 if ((flag & eModifierMode_Realtime) == 0 && modifier_isEnabled(scene, md, eModifierMode_Realtime))
3081 flag |= eModifierMode_Realtime;
3088 /* Check of objects moves in time. */
3089 /* NOTE: This function is currently optimized for usage in combination
3090 * with mti->canDeform, so modifiers can quickly check if their target
3091 * objects moves (causing deformation motion blur) or not.
3093 * This makes it possible to give some degree of false-positives here,
3094 * but it's currently an acceptable tradeoff between complexity and check
3095 * speed. In combination with checks of modifier stack and real life usage
3096 * percentage of false-positives shouldn't be that hight.
3098 static bool object_moves_in_time(Object *object)
3100 AnimData *adt = object->adt;
3102 /* If object has any sort of animation data assume it is moving. */
3103 if (adt->action != NULL ||
3104 !BLI_listbase_is_empty(&adt->nla_tracks) ||
3105 !BLI_listbase_is_empty(&adt->drivers) ||
3106 !BLI_listbase_is_empty(&adt->overrides))
3111 if (!BLI_listbase_is_empty(&object->constraints)) {
3114 if (object->parent != NULL) {
3115 /* TODO(sergey): Do recursive check here? */
3121 static bool object_deforms_in_time(Object *object)
3123 if (BKE_key_from_object(object) != NULL) {
3126 if (!BLI_listbase_is_empty(&object->modifiers)) {
3129 return object_moves_in_time(object);
3132 static bool constructive_modifier_is_deform_modified(ModifierData *md)
3134 /* TODO(sergey): Consider generalizing this a bit so all modifier logic
3135 * is concentrated in MOD_{modifier}.c file,
3137 if (md->type == eModifierType_Array) {
3138 ArrayModifierData *amd = (ArrayModifierData *)md;
3139 /* TODO(sergey): Check if curve is deformed. */
3140 return (amd->start_cap != NULL && object_moves_in_time(amd->start_cap)) ||
3141 (amd->end_cap != NULL && object_moves_in_time(amd->end_cap)) ||
3142 (amd->curve_ob != NULL && object_moves_in_time(amd->curve_ob)) ||
3143 (amd->offset_ob != NULL && object_moves_in_time(amd->offset_ob));
3145 else if (md->type == eModifierType_Mirror) {
3146 MirrorModifierData *mmd = (MirrorModifierData *)md;
3147 return mmd->mirror_ob != NULL && object_moves_in_time(mmd->mirror_ob);
3149 else if (md->type == eModifierType_Screw) {
3150 ScrewModifierData *smd = (ScrewModifierData *)md;
3151 return smd->ob_axis != NULL && object_moves_in_time(smd->ob_axis);
3153 else if (md->type == eModifierType_MeshSequenceCache) {
3154 /* NOTE: Not ideal because it's unknown whether topology changes or not.
3155 * This will be detected later, so by assuming it's only deformation
3156 * going on here we allow to bake deform-only mesh to Alembic and have
3157 * proper motion blur after that.
3164 static bool modifiers_has_animation_check(Object *ob)
3166 /* TODO(sergey): This is a bit code duplication with depsgraph, but
3167 * would be nicer to solve this as a part of new dependency graph
3168 * work, so we avoid conflicts and so.
3170 if (ob->adt != NULL) {
3171 AnimData *adt = ob->adt;
3173 if (adt->action != NULL) {
3174 for (fcu = adt->action->curves.first; fcu; fcu = fcu->next) {
3175 if (fcu->rna_path && strstr(fcu->rna_path, "modifiers[")) {
3180 for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
3181 if (fcu->rna_path && strstr(fcu->rna_path, "modifiers[")) {
3189 /* test if object is affected by deforming modifiers (for motion blur). again
3190 * most important is to avoid false positives, this is to skip computations
3191 * and we can still if there was actual deformation afterwards */
3192 int BKE_object_is_deform_modified(Scene *scene, Object *ob)
3195 VirtualModifierData virtualModifierData;
3197 const bool is_modifier_animated = modifiers_has_animation_check(ob);
3199 if (BKE_key_from_object(ob)) {
3200 flag |= eModifierMode_Realtime | eModifierMode_Render;
3203 if (ob->type == OB_CURVE) {
3204 Curve *cu = (Curve *)ob->data;
3205 if (cu->taperobj != NULL && object_deforms_in_time(cu->taperobj)) {
3206 flag |= eModifierMode_Realtime | eModifierMode_Render;
3211 for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
3212 md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
3215 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
3216 bool can_deform = mti->type == eModifierTypeType_OnlyDeform ||
3217 is_modifier_animated;
3220 can_deform = constructive_modifier_is_deform_modified(md);
3224 if (!(flag & eModifierMode_Render) && modifier_isEnabled(scene, md, eModifierMode_Render))
3225 flag |= eModifierMode_Render;
3227 if (!(flag & eModifierMode_Realtime) && modifier_isEnabled(scene, md, eModifierMode_Realtime))
3228 flag |= eModifierMode_Realtime;
3235 /* See if an object is using an animated modifier */
3236 bool BKE_object_is_animated(Scene *scene, Object *ob)
3239 VirtualModifierData virtualModifierData;
3241 for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next)
3242 if (modifier_dependsOnTime(md) &&
3243 (modifier_isEnabled(scene, md, eModifierMode_Realtime) ||
3244 modifier_isEnabled(scene, md, eModifierMode_Render)))
3251 MovieClip *BKE_object_movieclip_get(Scene *scene, Object *ob, bool use_default)
3253 MovieClip *clip = use_default ? scene->clip : NULL;
3254 bConstraint *con = ob->constraints.first, *scon = NULL;