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->gpd);
1168 id_us_plus((ID *)obn->dup_group);
1170 for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1173 obn->pd = MEM_dupallocN(ob->pd);
1175 id_us_plus(&(obn->pd->tex->id));
1177 obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1179 obn->soft = copy_softbody(ob->soft, copy_caches);
1180 obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1181 obn->rigidbody_object = BKE_rigidbody_copy_object(ob);
1182 obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob);
1184 BKE_object_copy_particlesystems(obn, ob);
1186 obn->derivedDeform = NULL;
1187 obn->derivedFinal = NULL;
1189 BLI_listbase_clear(&obn->gpulamp);
1190 BLI_listbase_clear(&obn->pc_ids);
1191 BLI_listbase_clear(&obn->drawdata);
1195 copy_object_lod(obn, ob);
1197 /* Copy runtime surve data. */
1198 obn->curve_cache = NULL;
1200 BKE_id_copy_ensure_local(bmain, &ob->id, &obn->id);
1202 /* Do not copy object's preview (mostly due to the fact renderers create temp copy of objects). */
1203 obn->preview = NULL;
1208 /* copy objects, will re-initialize cached simulation data */
1209 Object *BKE_object_copy(Main *bmain, Object *ob)
1211 return BKE_object_copy_ex(bmain, ob, false);
1214 void BKE_object_make_local_ex(Main *bmain, Object *ob, const bool lib_local, const bool clear_proxy)
1216 bool is_local = false, is_lib = false;
1218 /* - only lib users: do nothing (unless force_local is set)
1219 * - only local users: set flag
1220 * - mixed: make copy
1221 * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
1224 if (!ID_IS_LINKED_DATABLOCK(ob)) {
1228 BKE_library_ID_test_usages(bmain, ob, &is_local, &is_lib);
1230 if (lib_local || is_local) {
1232 id_clear_lib_data(bmain, &ob->id);
1233 BKE_id_expand_local(bmain, &ob->id);
1235 if (ob->proxy_from != NULL) {
1236 ob->proxy_from->proxy = NULL;
1237 ob->proxy_from->proxy_group = NULL;
1239 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
1243 Object *ob_new = BKE_object_copy(bmain, ob);
1246 ob_new->proxy = ob_new->proxy_from = ob_new->proxy_group = NULL;
1248 /* setting newid is mandatory for complex make_lib_local logic... */
1249 ID_NEW_SET(ob, ob_new);
1252 BKE_libblock_remap(bmain, ob, ob_new, ID_REMAP_SKIP_INDIRECT_USAGE);
1258 void BKE_object_make_local(Main *bmain, Object *ob, const bool lib_local)
1260 BKE_object_make_local_ex(bmain, ob, lib_local, true);
1263 /* Returns true if the Object is from an external blend file (libdata) */
1264 bool BKE_object_is_libdata(Object *ob)
1266 return (ob && ID_IS_LINKED_DATABLOCK(ob));
1269 /* Returns true if the Object data is from an external blend file (libdata) */
1270 bool BKE_object_obdata_is_libdata(Object *ob)
1272 /* Linked objects with local obdata are forbidden! */
1273 BLI_assert(!ob || !ob->data || (ID_IS_LINKED_DATABLOCK(ob) ? ID_IS_LINKED_DATABLOCK(ob->data) : true));
1274 return (ob && ob->data && ID_IS_LINKED_DATABLOCK(ob->data));
1277 /* *************** PROXY **************** */
1279 /* when you make proxy, ensure the exposed layers are extern */
1280 static void armature_set_id_extern(Object *ob)
1282 bArmature *arm = ob->data;
1283 bPoseChannel *pchan;
1284 unsigned int lay = arm->layer_protected;
1286 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1287 if (!(pchan->bone->layer & lay))
1288 id_lib_extern((ID *)pchan->custom);
1293 void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
1295 if ((target->adt) && (target->adt->drivers.first)) {
1298 /* add new animdata block */
1300 ob->adt = BKE_animdata_add_id(&ob->id);
1302 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1303 free_fcurves(&ob->adt->drivers);
1304 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1306 for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) {
1307 ChannelDriver *driver = fcu->driver;
1310 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1312 DRIVER_TARGETS_LOOPER(dvar)
1315 if ((Object *)dtar->id == target)
1316 dtar->id = (ID *)ob;
1318 /* only on local objects because this causes indirect links
1319 * 'a -> b -> c', blend to point directly to a.blend
1320 * when a.blend has a proxy thats linked into c.blend */
1321 if (!ID_IS_LINKED_DATABLOCK(ob))
1322 id_lib_extern((ID *)dtar->id);
1326 DRIVER_TARGETS_LOOPER_END
1332 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1333 /* local_object->proxy == pointer to library object, saved in files and read */
1334 /* local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1336 void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
1338 /* paranoia checks */
1339 if (ID_IS_LINKED_DATABLOCK(ob) || !ID_IS_LINKED_DATABLOCK(target)) {
1340 printf("cannot make proxy\n");
1345 ob->proxy_group = gob;
1346 id_lib_extern(&target->id);
1348 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1349 DEG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1352 * - gob means this proxy comes from a group, just apply the matrix
1353 * so the object wont move from its dupli-transform.
1355 * - no gob means this is being made from a linked object,
1356 * this is closer to making a copy of the object - in-place. */
1358 ob->rotmode = target->rotmode;
1359 mul_m4_m4m4(ob->obmat, gob->obmat, target->obmat);
1360 if (gob->dup_group) { /* should always be true */
1362 mul_v3_mat3_m4v3(tvec, ob->obmat, gob->dup_group->dupli_ofs);
1363 sub_v3_v3(ob->obmat[3], tvec);
1365 BKE_object_apply_mat4(ob, ob->obmat, false, true);
1368 BKE_object_transform_copy(ob, target);
1369 ob->parent = target->parent; /* libdata */
1370 copy_m4_m4(ob->parentinv, target->parentinv);
1373 /* copy animdata stuff - drivers only for now... */
1374 BKE_object_copy_proxy_drivers(ob, target);
1376 /* skip constraints? */
1377 /* FIXME: this is considered by many as a bug */
1379 /* set object type and link to data */
1380 ob->type = target->type;
1381 ob->data = target->data;
1382 id_us_plus((ID *)ob->data); /* ensures lib data becomes LIB_TAG_EXTERN */
1384 /* copy vertex groups */
1385 defgroup_copy_list(&ob->defbase, &target->defbase);
1387 /* copy material and index information */
1388 ob->actcol = ob->totcol = 0;
1389 if (ob->mat) MEM_freeN(ob->mat);
1390 if (ob->matbits) MEM_freeN(ob->matbits);
1393 if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1396 ob->actcol = target->actcol;
1397 ob->totcol = target->totcol;
1399 ob->mat = MEM_dupallocN(target->mat);
1400 ob->matbits = MEM_dupallocN(target->matbits);
1401 for (i = 0; i < target->totcol; i++) {
1402 /* don't need to run test_object_materials since we know this object is new and not used elsewhere */
1403 id_us_plus((ID *)ob->mat[i]);
1407 /* type conversions */
1408 if (target->type == OB_ARMATURE) {
1409 copy_object_pose(ob, target); /* data copy, object pointers in constraints */
1410 BKE_pose_rest(ob->pose); /* clear all transforms in channels */
1411 BKE_pose_rebuild(ob, ob->data); /* set all internal links */
1413 armature_set_id_extern(ob);
1415 else if (target->type == OB_EMPTY) {
1416 ob->empty_drawtype = target->empty_drawtype;
1417 ob->empty_drawsize = target->empty_drawsize;
1420 /* copy IDProperties */
1421 if (ob->id.properties) {
1422 IDP_FreeProperty(ob->id.properties);
1423 MEM_freeN(ob->id.properties);
1424 ob->id.properties = NULL;
1426 if (target->id.properties) {
1427 ob->id.properties = IDP_CopyProperty(target->id.properties);
1430 /* copy drawtype info */
1431 ob->dt = target->dt;
1435 * Use with newly created objects to set their size
1436 * (used to apply scene-scale).
1438 void BKE_object_obdata_size_init(struct Object *ob, const float size)
1440 /* apply radius as a scale to types that support it */
1444 ob->empty_drawsize *= size;
1449 Curve *cu = ob->data;
1455 Camera *cam = ob->data;
1456 cam->drawsize *= size;
1461 Lamp *lamp = ob->data;
1463 lamp->area_size *= size;
1464 lamp->area_sizey *= size;
1465 lamp->area_sizez *= size;
1468 /* Only lattice (not mesh, curve, mball...),
1469 * because its got data when newly added */
1472 struct Lattice *lt = ob->data;
1476 scale_m4_fl(mat, size);
1478 BKE_lattice_transform(lt, (float (*)[4])mat, false);
1484 /* *************** CALC ****************** */
1486 void BKE_object_scale_to_mat3(Object *ob, float mat[3][3])
1489 mul_v3_v3v3(vec, ob->size, ob->dscale);
1490 size_to_mat3(mat, vec);
1493 void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot)
1495 float rmat[3][3], dmat[3][3];
1497 /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1498 * with the rotation matrix to yield the appropriate rotation
1501 /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1502 if (ob->rotmode > 0) {
1503 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1504 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1505 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1507 else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1508 /* axis-angle - not really that great for 3D-changing orientations */
1509 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1510 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1513 /* quats are normalized before use to eliminate scaling issues */
1516 normalize_qt_qt(tquat, ob->quat);
1517 quat_to_mat3(rmat, tquat);
1519 normalize_qt_qt(tquat, ob->dquat);
1520 quat_to_mat3(dmat, tquat);
1523 /* combine these rotations */
1525 mul_m3_m3m3(mat, dmat, rmat);
1527 copy_m3_m3(mat, rmat);
1530 void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], bool use_compat)
1532 BLI_ASSERT_UNIT_M3(mat);
1534 switch (ob->rotmode) {
1538 mat3_normalized_to_quat(ob->quat, mat);
1539 normalize_qt_qt(dquat, ob->dquat);
1540 invert_qt_normalized(dquat);
1541 mul_qt_qtqt(ob->quat, dquat, ob->quat);
1544 case ROT_MODE_AXISANGLE:
1549 /* without drot we could apply 'mat' directly */
1550 mat3_normalized_to_quat(quat, mat);
1551 axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
1552 invert_qt_normalized(dquat);
1553 mul_qt_qtqt(quat, dquat, quat);
1554 quat_to_axis_angle(ob->rotAxis, &ob->rotAngle, quat);
1557 default: /* euler */
1562 /* without drot we could apply 'mat' directly */
1563 mat3_normalized_to_quat(quat, mat);
1564 eulO_to_quat(dquat, ob->drot, ob->rotmode);
1565 invert_qt_normalized(dquat);
1566 mul_qt_qtqt(quat, dquat, quat);
1567 /* end drot correction */
1569 if (use_compat) quat_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, quat);
1570 else quat_to_eulO(ob->rot, ob->rotmode, quat);
1576 void BKE_object_tfm_protected_backup(const Object *ob,
1577 ObjectTfmProtectedChannels *obtfm)
1580 #define TFMCPY(_v) (obtfm->_v = ob->_v)
1581 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
1582 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
1603 void BKE_object_tfm_protected_restore(Object *ob,
1604 const ObjectTfmProtectedChannels *obtfm,
1605 const short protectflag)
1609 for (i = 0; i < 3; i++) {
1610 if (protectflag & (OB_LOCK_LOCX << i)) {
1611 ob->loc[i] = obtfm->loc[i];
1612 ob->dloc[i] = obtfm->dloc[i];
1615 if (protectflag & (OB_LOCK_SCALEX << i)) {
1616 ob->size[i] = obtfm->size[i];
1617 ob->dscale[i] = obtfm->dscale[i];
1620 if (protectflag & (OB_LOCK_ROTX << i)) {
1621 ob->rot[i] = obtfm->rot[i];
1622 ob->drot[i] = obtfm->drot[i];
1624 ob->quat[i + 1] = obtfm->quat[i + 1];
1625 ob->dquat[i + 1] = obtfm->dquat[i + 1];
1627 ob->rotAxis[i] = obtfm->rotAxis[i];
1628 ob->drotAxis[i] = obtfm->drotAxis[i];
1632 if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
1633 ob->quat[0] = obtfm->quat[0];
1634 ob->dquat[0] = obtfm->dquat[0];
1636 ob->rotAngle = obtfm->rotAngle;
1637 ob->drotAngle = obtfm->drotAngle;
1641 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
1648 BKE_object_scale_to_mat3(ob, smat);
1651 BKE_object_rot_to_mat3(ob, rmat, true);
1652 mul_m3_m3m3(mat, rmat, smat);
1655 void BKE_object_to_mat4(Object *ob, float mat[4][4])
1659 BKE_object_to_mat3(ob, tmat);
1661 copy_m4_m3(mat, tmat);
1663 add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1666 void BKE_object_matrix_local_get(struct Object *ob, float mat[4][4])
1669 float par_imat[4][4];
1671 BKE_object_get_parent_matrix(NULL, ob, ob->parent, par_imat);
1672 invert_m4(par_imat);
1673 mul_m4_m4m4(mat, par_imat, ob->obmat);
1676 copy_m4_m4(mat, ob->obmat);
1681 int enable_cu_speed = 1;
1684 * \param scene: Used when curve cache needs to be calculated, or for dupli-frame time.
1685 * \return success if \a mat is set.
1687 static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4])
1689 Curve *cu = par->data;
1690 float vec[4], dir[3], quat[4], radius, ctime;
1692 /* only happens on reload file, but violates depsgraph still... fix! */
1693 if (par->curve_cache == NULL) {
1694 if (scene == NULL) {
1697 BKE_displist_make_curveTypes(scene, par, 0);
1700 if (par->curve_cache->path == NULL) {
1704 /* catch exceptions: curve paths used as a duplicator */
1705 if (enable_cu_speed) {
1706 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1707 * but this will only work if it actually is animated...
1709 * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1710 * factor, which then gets clamped to lie within 0.0 - 1.0 range
1713 ctime = cu->ctime / cu->pathlen;
1719 CLAMP(ctime, 0.0f, 1.0f);
1722 /* For dupli-frames only */
1723 if (scene == NULL) {
1727 ctime = BKE_scene_frame_get(scene);
1729 ctime /= cu->pathlen;
1732 CLAMP(ctime, 0.0f, 1.0f);
1738 if (where_on_path(par, ctime, vec, dir, (cu->flag & CU_FOLLOW) ? quat : NULL, &radius, NULL)) {
1740 if (cu->flag & CU_FOLLOW) {
1743 vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
1747 q[0] = cosf(0.5 * vec[3]);
1748 si = sinf(0.5 * vec[3]);
1749 q[1] = -si * dir[0];
1750 q[2] = -si * dir[1];
1751 q[3] = -si * dir[2];
1752 mul_qt_qtqt(quat, q, quat);
1754 quat_apply_track(quat, ob->trackflag, ob->upflag);
1757 quat_to_mat4(mat, quat);
1760 if (cu->flag & CU_PATH_RADIUS) {
1761 float tmat[4][4], rmat[4][4];
1762 scale_m4_fl(tmat, radius);
1763 mul_m4_m4m4(rmat, tmat, mat);
1764 copy_m4_m4(mat, rmat);
1767 copy_v3_v3(mat[3], vec);
1774 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
1776 bPoseChannel *pchan;
1779 if (par->type != OB_ARMATURE) {
1784 /* Make sure the bone is still valid */
1785 pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
1786 if (!pchan || !pchan->bone) {
1787 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
1792 /* get bone transform */
1793 if (pchan->bone->flag & BONE_RELATIVE_PARENTING) {
1794 /* the new option uses the root - expected bahaviour, but differs from old... */
1795 /* XXX check on version patching? */
1796 copy_m4_m4(mat, pchan->chan_mat);
1799 copy_m4_m4(mat, pchan->pose_mat);
1801 /* but for backwards compatibility, the child has to move to the tail */
1802 copy_v3_v3(vec, mat[1]);
1803 mul_v3_fl(vec, pchan->bone->length);
1804 add_v3_v3(mat[3], vec);
1808 static void give_parvert(Object *par, int nr, float vec[3])
1812 if (par->type == OB_MESH) {
1813 Mesh *me = par->data;
1814 BMEditMesh *em = me->edit_btmesh;
1817 dm = (em) ? em->derivedFinal : par->derivedFinal;
1821 int numVerts = dm->getNumVerts(dm);
1823 if (nr < numVerts) {
1824 bool use_special_ss_case = false;
1826 if (dm->type == DM_TYPE_CCGDM) {
1828 VirtualModifierData virtualModifierData;
1829 use_special_ss_case = true;
1830 for (md = modifiers_getVirtualModifierList(par, &virtualModifierData);
1834 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1835 /* TODO(sergey): Check for disabled modifiers. */
1836 if (mti->type != eModifierTypeType_OnlyDeform && md->next != NULL) {
1837 use_special_ss_case = false;
1843 if (!use_special_ss_case) {
1844 /* avoid dm->getVertDataArray() since it allocates arrays in the dm (not thread safe) */
1845 if (em && dm->type == DM_TYPE_EDITBMESH) {
1846 if (em->bm->elem_table_dirty & BM_VERT) {
1847 #ifdef VPARENT_THREADING_HACK
1848 BLI_mutex_lock(&vparent_lock);
1849 if (em->bm->elem_table_dirty & BM_VERT) {
1850 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
1852 BLI_mutex_unlock(&vparent_lock);
1854 BLI_assert(!"Not safe for threading");
1855 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
1861 if (use_special_ss_case) {
1862 /* Special case if the last modifier is SS and no constructive modifier are in front of it. */
1863 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1864 CCGVert *ccg_vert = ccgSubSurf_getVert(ccgdm->ss, SET_INT_IN_POINTER(nr));
1865 /* In case we deleted some verts, nr may refer to inexistent one now, see T42557. */
1867 float *co = ccgSubSurf_getVertData(ccgdm->ss, ccg_vert);
1872 else if (CustomData_has_layer(&dm->vertData, CD_ORIGINDEX) &&
1873 !(em && dm->type == DM_TYPE_EDITBMESH))
1877 /* Get the average of all verts with (original index == nr). */
1878 for (i = 0; i < numVerts; i++) {
1879 const int *index = dm->getVertData(dm, i, CD_ORIGINDEX);
1882 dm->getVertCo(dm, i, co);
1889 if (nr < numVerts) {
1891 dm->getVertCo(dm, nr, co);
1899 /* keep as 0, 0, 0 */
1901 else if (count > 0) {
1902 mul_v3_fl(vec, 1.0f / count);
1905 /* use first index if its out of range */
1906 dm->getVertCo(dm, 0, vec);
1911 "%s: DerivedMesh is needed to solve parenting, "
1912 "object position can be wrong now\n", __func__);
1915 else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1918 /* Unless there's some weird depsgraph failure the cache should exist. */
1919 BLI_assert(par->curve_cache != NULL);
1921 if (par->curve_cache->deformed_nurbs.first != NULL) {
1922 nurb = &par->curve_cache->deformed_nurbs;
1925 Curve *cu = par->data;
1926 nurb = BKE_curve_nurbs_get(cu);
1929 BKE_nurbList_index_get_co(nurb, nr, vec);
1931 else if (par->type == OB_LATTICE) {
1932 Lattice *latt = par->data;
1933 DispList *dl = par->curve_cache ? BKE_displist_find(&par->curve_cache->disp, DL_VERTS) : NULL;
1934 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
1937 if (latt->editlatt) latt = latt->editlatt->latt;
1939 tot = latt->pntsu * latt->pntsv * latt->pntsw;
1941 /* ensure dl is correct size */
1942 BLI_assert(dl == NULL || dl->nr == tot);
1946 copy_v3_v3(vec, co[nr]);
1949 copy_v3_v3(vec, latt->def[nr].vec);
1955 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
1958 /* in local ob space */
1959 if (OB_TYPE_SUPPORT_PARVERT(par->type)) {
1960 float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1962 give_parvert(par, ob->par1, v1);
1963 give_parvert(par, ob->par2, v2);
1964 give_parvert(par, ob->par3, v3);
1966 tri_to_quat(q, v1, v2, v3);
1967 quat_to_mat3(cmat, q);
1968 copy_m4_m3(mat, cmat);
1970 mid_v3_v3v3v3(mat[3], v1, v2, v3);
1978 void BKE_object_get_parent_matrix(Scene *scene, Object *ob, Object *par, float parentmat[4][4])
1984 switch (ob->partype & PARTYPE) {
1987 if (par->type == OB_CURVE) {
1988 if ((((Curve *)par->data)->flag & CU_PATH) &&
1989 (ob_parcurve(scene, ob, par, tmat)))
1995 if (ok) mul_m4_m4m4(parentmat, par->obmat, tmat);
1996 else copy_m4_m4(parentmat, par->obmat);
2000 ob_parbone(ob, par, tmat);
2001 mul_m4_m4m4(parentmat, par->obmat, tmat);
2006 give_parvert(par, ob->par1, vec);
2007 mul_v3_m4v3(parentmat[3], par->obmat, vec);
2010 ob_parvert3(ob, par, tmat);
2012 mul_m4_m4m4(parentmat, par->obmat, tmat);
2016 copy_m4_m4(parentmat, par->obmat);
2023 * \param r_originmat Optional matrix that stores the space the object is in (without its own matrix applied)
2025 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4][4], float slowmat[4][4],
2026 float r_originmat[3][3], const bool set_origin)
2032 BKE_object_to_mat4(ob, locmat);
2034 if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2036 BKE_object_get_parent_matrix(scene, ob, par, totmat);
2039 mul_m4_m4m4(tmat, totmat, ob->parentinv);
2040 mul_m4_m4m4(obmat, tmat, locmat);
2043 /* usable originmat */
2044 copy_m3_m4(r_originmat, tmat);
2047 /* origin, for help line */
2049 if ((ob->partype & PARTYPE) == PARSKEL) {
2050 copy_v3_v3(ob->orig, par->obmat[3]);
2053 copy_v3_v3(ob->orig, totmat[3]);
2058 static bool where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
2064 /* include framerate */
2065 fac1 = (1.0f / (1.0f + fabsf(ob->sf)));
2066 if (fac1 >= 1.0f) return false;
2071 for (a = 0; a < 16; a++, fp1++, fp2++) {
2072 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2078 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2079 void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime,
2080 RigidBodyWorld *rbw, float r_originmat[3][3])
2082 if (ob == NULL) return;
2084 /* execute drivers only, as animation has already been done */
2085 BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2088 Object *par = ob->parent;
2089 float slowmat[4][4];
2091 /* calculate parent matrix */
2092 solve_parenting(scene, ob, par, ob->obmat, slowmat, r_originmat, true);
2094 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around
2095 * An old-fashioned hack which probably doesn't really cut it anymore
2097 if (ob->partype & PARSLOW) {
2098 if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2103 BKE_object_to_mat4(ob, ob->obmat);
2106 /* try to fall back to the scene rigid body world if none given */
2107 rbw = rbw ? rbw : scene->rigidbody_world;
2108 /* read values pushed into RBO from sim/cache... */
2109 BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2111 /* solve constraints */
2112 if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2114 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2115 BKE_constraints_solve(&ob->constraints, cob, ctime);
2116 BKE_constraints_clear_evalob(cob);
2119 /* set negative scale flag in object */
2120 if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2121 else ob->transflag &= ~OB_NEG_SCALE;
2124 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2126 BKE_object_where_is_calc_time_ex(scene, ob, ctime, NULL, NULL);
2129 /* get object transformation matrix without recalculating dependencies and
2130 * constraints -- assume dependencies are already solved by depsgraph.
2131 * no changes to object and it's parent would be done.
2132 * used for bundles orientation in 3d space relative to parented blender camera */
2133 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2137 float slowmat[4][4];
2139 Object *par = ob->parent;
2141 solve_parenting(scene, ob, par, obmat, slowmat, NULL, false);
2143 if (ob->partype & PARSLOW)
2144 where_is_object_parslow(ob, obmat, slowmat);
2147 BKE_object_to_mat4(ob, obmat);
2151 void BKE_object_where_is_calc_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob, float r_originmat[3][3])
2153 BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), rbw, r_originmat);
2155 void BKE_object_where_is_calc(Scene *scene, Object *ob)
2157 BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), NULL, NULL);
2160 /* for calculation of the inverse parent transform, only used for editor */
2161 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2163 BKE_object_workob_clear(workob);
2165 unit_m4(workob->obmat);
2166 unit_m4(workob->parentinv);
2167 unit_m4(workob->constinv);
2168 workob->parent = ob->parent;
2170 workob->trackflag = ob->trackflag;
2171 workob->upflag = ob->upflag;
2173 workob->partype = ob->partype;
2174 workob->par1 = ob->par1;
2175 workob->par2 = ob->par2;
2176 workob->par3 = ob->par3;
2178 workob->constraints.first = ob->constraints.first;
2179 workob->constraints.last = ob->constraints.last;
2181 BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2183 BKE_object_where_is_calc(scene, workob);
2186 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
2187 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const bool use_compat, const bool use_parent)
2191 if (use_parent && ob->parent) {
2192 float rmat[4][4], diff_mat[4][4], imat[4][4], parent_mat[4][4];
2194 BKE_object_get_parent_matrix(NULL, ob, ob->parent, parent_mat);
2196 mul_m4_m4m4(diff_mat, parent_mat, ob->parentinv);
2197 invert_m4_m4(imat, diff_mat);
2198 mul_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
2200 /* same as below, use rmat rather than mat */
2201 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
2204 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
2207 BKE_object_mat3_to_rot(ob, rot, use_compat);
2209 sub_v3_v3(ob->loc, ob->dloc);
2211 if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
2212 if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
2213 if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
2215 /* BKE_object_mat3_to_rot handles delta rotations */
2218 BoundBox *BKE_boundbox_alloc_unit(void)
2221 const float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2223 bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2224 BKE_boundbox_init_from_minmax(bb, min, max);
2229 void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float max[3])
2231 bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2232 bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2234 bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2235 bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2237 bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2238 bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2241 void BKE_boundbox_calc_center_aabb(const BoundBox *bb, float r_cent[3])
2243 r_cent[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]);
2244 r_cent[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]);
2245 r_cent[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]);
2248 void BKE_boundbox_calc_size_aabb(const BoundBox *bb, float r_size[3])
2250 r_size[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]);
2251 r_size[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]);
2252 r_size[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]);
2255 void BKE_boundbox_minmax(const BoundBox *bb, float obmat[4][4], float r_min[3], float r_max[3])
2258 for (i = 0; i < 8; i++) {
2260 mul_v3_m4v3(vec, obmat, bb->vec[i]);
2261 minmax_v3v3_v3(r_min, r_max, vec);
2265 BoundBox *BKE_object_boundbox_get(Object *ob)
2267 BoundBox *bb = NULL;
2269 if (ob->type == OB_MESH) {
2270 bb = BKE_mesh_boundbox_get(ob);
2272 else if (ELEM(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2273 bb = BKE_curve_boundbox_get(ob);
2275 else if (ob->type == OB_MBALL) {
2278 else if (ob->type == OB_LATTICE) {
2279 bb = BKE_lattice_boundbox_get(ob);
2281 else if (ob->type == OB_ARMATURE) {
2282 bb = BKE_armature_boundbox_get(ob);
2287 /* used to temporally disable/enable boundbox */
2288 void BKE_object_boundbox_flag(Object *ob, int flag, const bool set)
2290 BoundBox *bb = BKE_object_boundbox_get(ob);
2292 if (set) bb->flag |= flag;
2293 else bb->flag &= ~flag;
2297 void BKE_object_dimensions_get(Object *ob, float vec[3])
2299 BoundBox *bb = NULL;
2301 bb = BKE_object_boundbox_get(ob);
2305 mat4_to_size(scale, ob->obmat);
2307 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2308 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2309 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2316 void BKE_object_dimensions_set(Object *ob, const float value[3])
2318 BoundBox *bb = NULL;
2320 bb = BKE_object_boundbox_get(ob);
2322 float scale[3], len[3];
2324 mat4_to_size(scale, ob->obmat);
2326 len[0] = bb->vec[4][0] - bb->vec[0][0];
2327 len[1] = bb->vec[2][1] - bb->vec[0][1];
2328 len[2] = bb->vec[1][2] - bb->vec[0][2];
2330 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2331 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2332 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2336 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool use_hidden)
2340 bool changed = false;
2347 bb = *BKE_curve_boundbox_get(ob);
2348 BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2354 Lattice *lt = ob->data;
2355 BPoint *bp = lt->def;
2358 for (w = 0; w < lt->pntsw; w++) {
2359 for (v = 0; v < lt->pntsv; v++) {
2360 for (u = 0; u < lt->pntsu; u++, bp++) {
2361 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2362 minmax_v3v3_v3(min_r, max_r, vec);
2371 changed = BKE_pose_minmax(ob, min_r, max_r, use_hidden, false);
2376 Mesh *me = BKE_mesh_from_object(ob);
2379 bb = *BKE_mesh_boundbox_get(ob);
2380 BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2387 float ob_min[3], ob_max[3];
2389 changed = BKE_mball_minmax_ex(ob->data, ob_min, ob_max, ob->obmat, 0);
2391 minmax_v3v3_v3(min_r, max_r, ob_min);
2392 minmax_v3v3_v3(min_r, max_r, ob_max);
2398 if (changed == false) {
2401 copy_v3_v3(size, ob->size);
2402 if (ob->type == OB_EMPTY) {
2403 mul_v3_fl(size, ob->empty_drawsize);
2406 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2408 copy_v3_v3(vec, ob->obmat[3]);
2409 add_v3_v3(vec, size);
2410 minmax_v3v3_v3(min_r, max_r, vec);
2412 copy_v3_v3(vec, ob->obmat[3]);
2413 sub_v3_v3(vec, size);
2414 minmax_v3v3_v3(min_r, max_r, vec);
2418 void BKE_object_empty_draw_type_set(Object *ob, const int value)
2420 ob->empty_drawtype = value;
2422 if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
2424 ob->iuser = MEM_callocN(sizeof(ImageUser), "image user");
2426 ob->iuser->frames = 100;
2427 ob->iuser->sfra = 1;
2428 ob->iuser->fie_ima = 2;
2433 MEM_freeN(ob->iuser);
2439 bool BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const bool use_hidden)
2442 if ((ob->transflag & OB_DUPLI) == 0) {
2448 lb = object_duplilist(G.main->eval_ctx, scene, ob);
2449 for (dob = lb->first; dob; dob = dob->next) {
2450 if ((use_hidden == false) && (dob->no_draw != 0)) {
2454 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2458 for (i = 0; i < 8; i++) {
2460 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2461 minmax_v3v3_v3(r_min, r_max, vec);
2468 free_object_duplilist(lb); /* does restore */
2474 void BKE_object_foreach_display_point(
2475 Object *ob, float obmat[4][4],
2476 void (*func_cb)(const float[3], void *), void *user_data)
2480 if (ob->derivedFinal) {
2481 DerivedMesh *dm = ob->derivedFinal;
2482 MVert *mv = dm->getVertArray(dm);
2483 int totvert = dm->getNumVerts(dm);
2486 for (i = 0; i < totvert; i++, mv++) {
2487 mul_v3_m4v3(co, obmat, mv->co);
2488 func_cb(co, user_data);
2491 else if (ob->curve_cache && ob->curve_cache->disp.first) {
2494 for (dl = ob->curve_cache->disp.first; dl; dl = dl->next) {
2495 const float *v3 = dl->verts;
2496 int totvert = dl->nr;
2499 for (i = 0; i < totvert; i++, v3 += 3) {
2500 mul_v3_m4v3(co, obmat, v3);
2501 func_cb(co, user_data);
2507 void BKE_scene_foreach_display_point(
2508 Scene *scene, SceneLayer *sl,
2509 void (*func_cb)(const float[3], void *), void *user_data)
2514 for (base = FIRSTBASE_NEW; base; base = base->next) {
2515 if (((base->flag & BASE_VISIBLED) != 0) && ((base->flag & BASE_SELECTED) != 0)) {
2518 if ((ob->transflag & OB_DUPLI) == 0) {
2519 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2525 lb = object_duplilist(G.main->eval_ctx, scene, ob);
2526 for (dob = lb->first; dob; dob = dob->next) {
2527 if (dob->no_draw == 0) {
2528 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2531 free_object_duplilist(lb); /* does restore */
2537 /* copied from DNA_object_types.h */
2538 typedef struct ObTfmBack {
2539 float loc[3], dloc[3], orig[3];
2540 float size[3], dscale[3]; /* scale and delta scale */
2541 float rot[3], drot[3]; /* euler rotation */
2542 float quat[4], dquat[4]; /* quaternion rotation */
2543 float rotAxis[3], drotAxis[3]; /* axis angle rotation - axis part */
2544 float rotAngle, drotAngle; /* axis angle rotation - angle part */
2545 float obmat[4][4]; /* final worldspace matrix with constraints & animsys applied */
2546 float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2547 float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2548 float imat[4][4]; /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform */
2551 void *BKE_object_tfm_backup(Object *ob)
2553 ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2554 copy_v3_v3(obtfm->loc, ob->loc);
2555 copy_v3_v3(obtfm->dloc, ob->dloc);
2556 copy_v3_v3(obtfm->orig, ob->orig);
2557 copy_v3_v3(obtfm->size, ob->size);
2558 copy_v3_v3(obtfm->dscale, ob->dscale);
2559 copy_v3_v3(obtfm->rot, ob->rot);
2560 copy_v3_v3(obtfm->drot, ob->drot);
2561 copy_qt_qt(obtfm->quat, ob->quat);
2562 copy_qt_qt(obtfm->dquat, ob->dquat);
2563 copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2564 copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2565 obtfm->rotAngle = ob->rotAngle;
2566 obtfm->drotAngle = ob->drotAngle;
2567 copy_m4_m4(obtfm->obmat, ob->obmat);
2568 copy_m4_m4(obtfm->parentinv, ob->parentinv);
2569 copy_m4_m4(obtfm->constinv, ob->constinv);
2570 copy_m4_m4(obtfm->imat, ob->imat);
2572 return (void *)obtfm;
2575 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2577 ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2578 copy_v3_v3(ob->loc, obtfm->loc);
2579 copy_v3_v3(ob->dloc, obtfm->dloc);
2580 copy_v3_v3(ob->orig, obtfm->orig);
2581 copy_v3_v3(ob->size, obtfm->size);
2582 copy_v3_v3(ob->dscale, obtfm->dscale);
2583 copy_v3_v3(ob->rot, obtfm->rot);
2584 copy_v3_v3(ob->drot, obtfm->drot);
2585 copy_qt_qt(ob->quat, obtfm->quat);
2586 copy_qt_qt(ob->dquat, obtfm->dquat);
2587 copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2588 copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2589 ob->rotAngle = obtfm->rotAngle;
2590 ob->drotAngle = obtfm->drotAngle;
2591 copy_m4_m4(ob->obmat, obtfm->obmat);
2592 copy_m4_m4(ob->parentinv, obtfm->parentinv);
2593 copy_m4_m4(ob->constinv, obtfm->constinv);
2594 copy_m4_m4(ob->imat, obtfm->imat);
2597 bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
2599 /* test if 'ob' is a parent somewhere in par's parents */
2600 if (par == NULL) return false;
2601 if (ob == par) return true;
2602 return BKE_object_parent_loop_check(par->parent, ob);
2605 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2606 /* local_object->proxy == pointer to library object, saved in files and read */
2608 /* function below is polluted with proxy exceptions, cleanup will follow! */
2610 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2611 /* requires flags to be set! */
2612 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
2613 void BKE_object_handle_update_ex(EvaluationContext *eval_ctx,
2614 Scene *scene, Object *ob,
2615 RigidBodyWorld *rbw,
2616 const bool do_proxy_update)
2618 if (ob->recalc & OB_RECALC_ALL) {
2619 /* speed optimization for animation lookups */
2621 BKE_pose_channels_hash_make(ob->pose);
2622 if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
2623 BKE_pose_update_constraint_flags(ob->pose);
2627 if (ob->recalc & OB_RECALC_DATA) {
2628 if (ob->type == OB_ARMATURE) {
2629 /* this happens for reading old files and to match library armatures
2630 * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
2631 * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2633 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
2634 BKE_pose_rebuild(ob, ob->data);
2638 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers,
2639 * which is only in BKE_object_where_is_calc now */
2640 /* XXX: should this case be OB_RECALC_OB instead? */
2641 if (ob->recalc & OB_RECALC_ALL) {
2643 if (G.debug & G_DEBUG_DEPSGRAPH)
2644 printf("recalcob %s\n", ob->id.name + 2);
2646 /* handle proxy copy for target */
2647 if (ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from) {
2648 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2649 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
2650 Object *obg = ob->proxy_from->proxy_group;
2652 invert_m4_m4(imat, obg->obmat);
2653 mul_m4_m4m4(ob->obmat, imat, ob->proxy_from->obmat);
2654 if (obg->dup_group) { /* should always be true */
2655 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2659 copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2662 BKE_object_where_is_calc_ex(scene, rbw, ob, NULL);
2665 if (ob->recalc & OB_RECALC_DATA) {
2666 BKE_object_handle_data_update(eval_ctx, scene, ob);
2669 ob->recalc &= ~OB_RECALC_ALL;
2672 /* the case when this is a group proxy, object_update is called in group.c */
2674 /* set pointer in library proxy target, for copying, but restore it */
2675 ob->proxy->proxy_from = ob;
2676 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2678 /* the no-group proxy case, we call update */
2679 if (ob->proxy_group == NULL) {
2680 if (do_proxy_update) {
2681 // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2682 BKE_object_handle_update(eval_ctx, scene, ob->proxy);
2687 /* WARNING: "scene" here may not be the scene object actually resides in.
2688 * When dealing with background-sets, "scene" is actually the active scene.
2689 * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n
2690 * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the corrent rigid body world
2692 void BKE_object_handle_update(EvaluationContext *eval_ctx, Scene *scene, Object *ob)
2694 BKE_object_handle_update_ex(eval_ctx, scene, ob, NULL, true);
2697 void BKE_object_sculpt_modifiers_changed(Object *ob)
2699 SculptSession *ss = ob->sculpt;
2703 /* we free pbvh on changes, except during sculpt since it can't deal with
2704 * changing PVBH node organization, we hope topology does not change in
2705 * the meantime .. weak */
2707 BKE_pbvh_free(ss->pbvh);
2711 BKE_sculptsession_free_deformMats(ob->sculpt);
2717 BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2719 for (n = 0; n < totnode; n++)
2720 BKE_pbvh_node_mark_update(nodes[n]);
2727 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
2730 if (ob->data == NULL)
2733 switch (GS(((ID *)ob->data)->name)) {
2736 Mesh *me = ob->data;
2737 if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) {
2738 BKE_mesh_texspace_calc(me);
2740 if (r_texflag) *r_texflag = &me->texflag;
2741 if (r_loc) *r_loc = me->loc;
2742 if (r_size) *r_size = me->size;
2743 if (r_rot) *r_rot = me->rot;
2748 Curve *cu = ob->data;
2749 if (cu->bb == NULL || (cu->bb->flag & BOUNDBOX_DIRTY)) {
2750 BKE_curve_texspace_calc(cu);
2752 if (r_texflag) *r_texflag = &cu->texflag;
2753 if (r_loc) *r_loc = cu->loc;
2754 if (r_size) *r_size = cu->size;
2755 if (r_rot) *r_rot = cu->rot;
2760 MetaBall *mb = ob->data;
2761 if (r_texflag) *r_texflag = &mb->texflag;
2762 if (r_loc) *r_loc = mb->loc;
2763 if (r_size) *r_size = mb->size;
2764 if (r_rot) *r_rot = mb->rot;
2773 static int pc_cmp(const void *a, const void *b)
2775 const LinkData *ad = a, *bd = b;
2776 if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2781 int BKE_object_insert_ptcache(Object *ob)
2783 LinkData *link = NULL;
2786 BLI_listbase_sort(&ob->pc_ids, pc_cmp);
2788 for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) {
2789 int index = GET_INT_FROM_POINTER(link->data);
2795 link = MEM_callocN(sizeof(LinkData), "PCLink");
2796 link->data = SET_INT_IN_POINTER(i);
2797 BLI_addtail(&ob->pc_ids, link);
2802 static int pc_findindex(ListBase *listbase, int index)
2804 LinkData *link = NULL;
2807 if (listbase == NULL) return -1;
2809 link = listbase->first;
2811 if (GET_INT_FROM_POINTER(link->data) == index)
2821 void BKE_object_delete_ptcache(Object *ob, int index)
2823 int list_index = pc_findindex(&ob->pc_ids, index);
2824 LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2825 BLI_freelinkN(&ob->pc_ids, link);
2828 /* shape key utility function */
2830 /************************* Mesh ************************/
2831 static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mix)
2833 Mesh *me = ob->data;
2839 key = me->key = BKE_key_add((ID *)me);
2840 key->type = KEY_RELATIVE;
2844 if (newkey || from_mix == false) {
2845 /* create from mesh */
2846 kb = BKE_keyblock_add_ctime(key, name, false);
2847 BKE_keyblock_convert_from_mesh(me, kb);
2850 /* copy from current values */
2852 float *data = BKE_key_evaluate_object(ob, &totelem);
2854 /* create new block with prepared data */
2855 kb = BKE_keyblock_add_ctime(key, name, false);
2857 kb->totelem = totelem;
2862 /************************* Lattice ************************/
2863 static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mix)
2865 Lattice *lt = ob->data;
2871 key = lt->key = BKE_key_add((ID *)lt);
2872 key->type = KEY_RELATIVE;
2876 if (newkey || from_mix == false) {
2877 kb = BKE_keyblock_add_ctime(key, name, false);
2879 KeyBlock *basekb = (KeyBlock *)key->block.first;
2880 kb->data = MEM_dupallocN(basekb->data);
2881 kb->totelem = basekb->totelem;
2884 BKE_keyblock_convert_from_lattice(lt, kb);
2888 /* copy from current values */
2890 float *data = BKE_key_evaluate_object(ob, &totelem);
2892 /* create new block with prepared data */
2893 kb = BKE_keyblock_add_ctime(key, name, false);
2894 kb->totelem = totelem;
2900 /************************* Curve ************************/
2901 static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_mix)
2903 Curve *cu = ob->data;
2906 ListBase *lb = BKE_curve_nurbs_get(cu);
2910 key = cu->key = BKE_key_add((ID *)cu);
2911 key->type = KEY_RELATIVE;
2915 if (newkey || from_mix == false) {
2916 /* create from curve */
2917 kb = BKE_keyblock_add_ctime(key, name, false);
2919 KeyBlock *basekb = (KeyBlock *)key->block.first;
2920 kb->data = MEM_dupallocN(basekb->data);
2921 kb->totelem = basekb->totelem;
2924 BKE_keyblock_convert_from_curve(cu, kb, lb);
2928 /* copy from current values */
2930 float *data = BKE_key_evaluate_object(ob, &totelem);
2932 /* create new block with prepared data */
2933 kb = BKE_keyblock_add_ctime(key, name, false);
2934 kb->totelem = totelem;
2941 KeyBlock *BKE_object_shapekey_insert(Object *ob, const char *name, const bool from_mix)
2945 return insert_meshkey(ob, name, from_mix);
2948 return insert_curvekey(ob, name, from_mix);
2950 return insert_lattkey(ob, name, from_mix);
2957 bool BKE_object_shapekey_free(Main *bmain, Object *ob)
2961 key_p = BKE_key_from_object_p(ob);
2962 if (ELEM(NULL, key_p, *key_p)) {
2969 BKE_libblock_free_us(bmain, key);
2974 bool BKE_object_shapekey_remove(Main *bmain, Object *ob, KeyBlock *kb)
2977 Key *key = BKE_key_from_object(ob);
2984 kb_index = BLI_findindex(&key->block, kb);
2985 BLI_assert(kb_index != -1);
2987 for (rkb = key->block.first; rkb; rkb = rkb->next) {
2988 if (rkb->relative == kb_index) {
2989 /* remap to the 'Basis' */
2992 else if (rkb->relative >= kb_index) {
2993 /* Fix positional shift of the keys when kb is deleted from the list */
2998 BLI_remlink(&key->block, kb);
3000 if (key->refkey == kb) {
3001 key->refkey = key->block.first;
3004 /* apply new basis key on original data */
3007 BKE_keyblock_convert_to_mesh(key->refkey, ob->data);
3011 BKE_keyblock_convert_to_curve(key->refkey, ob->data, BKE_curve_nurbs_get(ob->data));
3014 BKE_keyblock_convert_to_lattice(key->refkey, ob->data);
3021 MEM_freeN(kb->data);
3025 if (ob->shapenr > 1) {
3029 if (key->totkey == 0) {
3030 BKE_object_shapekey_free(bmain, ob);
3036 bool BKE_object_flag_test_recursive(const Object *ob, short flag)
3038 if (ob->flag & flag) {
3041 else if (ob->parent) {
3042 return BKE_object_flag_test_recursive(ob->parent, flag);
3049 bool BKE_object_is_child_recursive(Object *ob_parent, Object *ob_child)
3051 for (ob_child = ob_child->parent; ob_child; ob_child = ob_child->parent) {
3052 if (ob_child == ob_parent) {
3059 /* most important if this is modified it should _always_ return True, in certain
3060 * cases false positives are hard to avoid (shape keys for example) */
3061 int BKE_object_is_modified(Scene *scene, Object *ob)
3065 if (BKE_key_from_object(ob)) {
3066 flag |= eModifierMode_Render | eModifierMode_Realtime;
3070 VirtualModifierData virtualModifierData;
3072 for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
3073 md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
3076 if ((flag & eModifierMode_Render) == 0 && modifier_isEnabled(scene, md, eModifierMode_Render))
3077 flag |= eModifierMode_Render;
3079 if ((flag & eModifierMode_Realtime) == 0 && modifier_isEnabled(scene, md, eModifierMode_Realtime))
3080 flag |= eModifierMode_Realtime;
3087 /* Check of objects moves in time. */
3088 /* NOTE: This function is currently optimized for usage in combination
3089 * with mti->canDeform, so modifiers can quickly check if their target
3090 * objects moves (causing deformation motion blur) or not.
3092 * This makes it possible to give some degree of false-positives here,
3093 * but it's currently an acceptable tradeoff between complexity and check
3094 * speed. In combination with checks of modifier stack and real life usage
3095 * percentage of false-positives shouldn't be that hight.
3097 static bool object_moves_in_time(Object *object)
3099 AnimData *adt = object->adt;
3101 /* If object has any sort of animation data assume it is moving. */
3102 if (adt->action != NULL ||
3103 !BLI_listbase_is_empty(&adt->nla_tracks) ||
3104 !BLI_listbase_is_empty(&adt->drivers) ||
3105 !BLI_listbase_is_empty(&adt->overrides))
3110 if (!BLI_listbase_is_empty(&object->constraints)) {
3113 if (object->parent != NULL) {
3114 /* TODO(sergey): Do recursive check here? */
3120 static bool object_deforms_in_time(Object *object)
3122 if (BKE_key_from_object(object) != NULL) {
3125 if (!BLI_listbase_is_empty(&object->modifiers)) {
3128 return object_moves_in_time(object);
3131 static bool constructive_modifier_is_deform_modified(ModifierData *md)
3133 /* TODO(sergey): Consider generalizing this a bit so all modifier logic
3134 * is concentrated in MOD_{modifier}.c file,
3136 if (md->type == eModifierType_Array) {
3137 ArrayModifierData *amd = (ArrayModifierData *)md;
3138 /* TODO(sergey): Check if curve is deformed. */
3139 return (amd->start_cap != NULL && object_moves_in_time(amd->start_cap)) ||
3140 (amd->end_cap != NULL && object_moves_in_time(amd->end_cap)) ||
3141 (amd->curve_ob != NULL && object_moves_in_time(amd->curve_ob)) ||
3142 (amd->offset_ob != NULL && object_moves_in_time(amd->offset_ob));
3144 else if (md->type == eModifierType_Mirror) {
3145 MirrorModifierData *mmd = (MirrorModifierData *)md;
3146 return mmd->mirror_ob != NULL && object_moves_in_time(mmd->mirror_ob);
3148 else if (md->type == eModifierType_Screw) {
3149 ScrewModifierData *smd = (ScrewModifierData *)md;
3150 return smd->ob_axis != NULL && object_moves_in_time(smd->ob_axis);
3152 else if (md->type == eModifierType_MeshSequenceCache) {
3153 /* NOTE: Not ideal because it's unknown whether topology changes or not.
3154 * This will be detected later, so by assuming it's only deformation
3155 * going on here we allow to bake deform-only mesh to Alembic and have
3156 * proper motion blur after that.
3163 static bool modifiers_has_animation_check(Object *ob)
3165 /* TODO(sergey): This is a bit code duplication with depsgraph, but
3166 * would be nicer to solve this as a part of new dependency graph
3167 * work, so we avoid conflicts and so.
3169 if (ob->adt != NULL) {
3170 AnimData *adt = ob->adt;
3172 if (adt->action != NULL) {
3173 for (fcu = adt->action->curves.first; fcu; fcu = fcu->next) {
3174 if (fcu->rna_path && strstr(fcu->rna_path, "modifiers[")) {
3179 for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
3180 if (fcu->rna_path && strstr(fcu->rna_path, "modifiers[")) {
3188 /* test if object is affected by deforming modifiers (for motion blur). again
3189 * most important is to avoid false positives, this is to skip computations
3190 * and we can still if there was actual deformation afterwards */
3191 int BKE_object_is_deform_modified(Scene *scene, Object *ob)
3194 VirtualModifierData virtualModifierData;
3196 const bool is_modifier_animated = modifiers_has_animation_check(ob);
3198 if (BKE_key_from_object(ob)) {
3199 flag |= eModifierMode_Realtime | eModifierMode_Render;
3202 if (ob->type == OB_CURVE) {
3203 Curve *cu = (Curve *)ob->data;
3204 if (cu->taperobj != NULL && object_deforms_in_time(cu->taperobj)) {
3205 flag |= eModifierMode_Realtime | eModifierMode_Render;
3210 for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
3211 md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
3214 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
3215 bool can_deform = mti->type == eModifierTypeType_OnlyDeform ||
3216 is_modifier_animated;
3219 can_deform = constructive_modifier_is_deform_modified(md);
3223 if (!(flag & eModifierMode_Render) && modifier_isEnabled(scene, md, eModifierMode_Render))
3224 flag |= eModifierMode_Render;
3226 if (!(flag & eModifierMode_Realtime) && modifier_isEnabled(scene, md, eModifierMode_Realtime))
3227 flag |= eModifierMode_Realtime;
3234 /* See if an object is using an animated modifier */
3235 bool BKE_object_is_animated(Scene *scene, Object *ob)
3238 VirtualModifierData virtualModifierData;
3240 for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next)
3241 if (modifier_dependsOnTime(md) &&
3242 (modifier_isEnabled(scene, md, eModifierMode_Realtime) ||
3243 modifier_isEnabled(scene, md, eModifierMode_Render)))
3250 MovieClip *BKE_object_movieclip_get(Scene *scene, Object *ob, bool use_default)
3252 MovieClip *clip = use_default ? scene->clip : NULL;
3253 bConstraint *con = ob->constraints.first, *scon = NULL;