diff options
author | Lukas Tönne <lukas.toenne@gmail.com> | 2021-07-18 14:14:23 +0300 |
---|---|---|
committer | Lukas Tönne <lukas.toenne@gmail.com> | 2021-07-18 14:14:23 +0300 |
commit | ca50a1f762703d477ee84cf494dec601fd540299 (patch) | |
tree | fbd86a77e77015d7cc6becc1255a63e436a45b2a /source/blender/blenkernel/intern | |
parent | d35969a74ff7a71fc0ca233ae65a2f1c47eb9a25 (diff) | |
parent | e82c5c660778b3805f50f3f2901923692c17db2a (diff) |
Merge branch 'master' into geometry-nodes-unnamed-attributesgeometry-nodes-unnamed-attributes
Diffstat (limited to 'source/blender/blenkernel/intern')
135 files changed, 2279 insertions, 1595 deletions
diff --git a/source/blender/blenkernel/intern/DerivedMesh.cc b/source/blender/blenkernel/intern/DerivedMesh.cc index 7063c670ee4..ba8cf8debe9 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.cc +++ b/source/blender/blenkernel/intern/DerivedMesh.cc @@ -829,7 +829,7 @@ static void mesh_calc_modifier_final_normals(const Mesh *mesh_input, } if (do_loop_normals) { - /* Compute loop normals (note: will compute poly and vert normals as well, if needed!) */ + /* Compute loop normals (NOTE: will compute poly and vert normals as well, if needed!). */ BKE_mesh_calc_normals_split(mesh_final); BKE_mesh_tessface_clear(mesh_final); } @@ -900,7 +900,7 @@ static Mesh *prepare_geometry_set_for_mesh_modifier(Mesh *mesh, GeometrySet &r_g { /* Add the mesh to the geometry set. */ MeshComponent &mesh_component = r_geometry_set.get_component_for_write<MeshComponent>(); - mesh_component.replace_mesh_but_keep_vertex_group_names(mesh, GeometryOwnershipType::Editable); + mesh_component.replace(mesh, GeometryOwnershipType::Editable); } { /* Combine mesh and all instances into a single mesh that can be passed to the modifier. */ @@ -948,8 +948,7 @@ static Mesh *modifier_modify_mesh_and_geometry_set(ModifierData *md, /* Replace only the mesh rather than the whole component, because the entire #MeshComponent * might have been replaced by data from a different object in the node tree, which means the * component contains vertex group name data for that object that should not be removed. */ - mesh_component.replace_mesh_but_keep_vertex_group_names(input_mesh, - GeometryOwnershipType::Editable); + mesh_component.replace(input_mesh, GeometryOwnershipType::Editable); /* Let the modifier change the geometry set. */ mti->modifyGeometrySet(md, &mectx, &geometry_set); @@ -993,12 +992,6 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, /* This geometry set contains the non-mesh data that might be generated by modifiers. */ GeometrySet geometry_set_final; - /* Add the initial mesh component, with a copy of the vertex group names from the object, - * since they need to be stored in the geometry set for evaluation. */ - MeshComponent &initial_mesh_component = - geometry_set_final.get_component_for_write<MeshComponent>(); - initial_mesh_component.copy_vertex_group_names_from_object(*ob); - BLI_assert((mesh_input->id.tag & LIB_TAG_COPIED_ON_WRITE_EVAL_RESULT) == 0); /* Deformed vertex locations array. Deform only modifier need this type of @@ -1076,10 +1069,6 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, continue; } - if (mti->dependsOnTime && mti->dependsOnTime(md)) { - continue; - } - if (mti->type == eModifierTypeType_OnlyDeform && !sculpt_dyntopo) { if (!deformed_verts) { deformed_verts = BKE_mesh_vert_coords_alloc(mesh_input, &num_deformed_verts); @@ -1173,10 +1162,6 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, continue; } - if (mti->dependsOnTime && mti->dependsOnTime(md)) { - continue; - } - /* Add orco mesh as layer if needed by this modifier. */ if (mesh_final && mesh_orco && mti->requiredDataMask) { CustomData_MeshMasks mask = {0}; @@ -1412,7 +1397,7 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, * we need to apply these back onto the Mesh. If we have no * Mesh then we need to build one. */ if (mesh_final == nullptr) { - /* Note: this check on cdmask is a bit dodgy, it handles the issue at stake here (see T68211), + /* NOTE: this check on cdmask is a bit dodgy, it handles the issue at stake here (see T68211), * but other cases might require similar handling? * Could be a good idea to define a proper CustomData_MeshMask for that then. */ if (deformed_verts == nullptr && allow_shared_mesh && @@ -1610,12 +1595,6 @@ static void editbmesh_calc_modifiers(struct Depsgraph *depsgraph, /* This geometry set contains the non-mesh data that might be generated by modifiers. */ GeometrySet geometry_set_final; - /* Add the initial mesh component, with a copy of the vertex group names from the object, - * since they need to be stored in the geometry set for evaluation. */ - MeshComponent &initial_mesh_component = - geometry_set_final.get_component_for_write<MeshComponent>(); - initial_mesh_component.copy_vertex_group_names_from_object(*ob); - /* Deformed vertex locations array. Deform only modifier need this type of * float array rather than MVert*. Tracked along with mesh_final as an * optimization to avoid copying coordinates back and forth if there are @@ -1959,8 +1938,7 @@ static void mesh_build_data(struct Depsgraph *depsgraph, /* Add the final mesh as read-only non-owning component to the geometry set. */ MeshComponent &mesh_component = geometry_set_eval->get_component_for_write<MeshComponent>(); - mesh_component.replace_mesh_but_keep_vertex_group_names(mesh_eval, - GeometryOwnershipType::ReadOnly); + mesh_component.replace(mesh_eval, GeometryOwnershipType::ReadOnly); ob->runtime.geometry_set_eval = geometry_set_eval; ob->runtime.mesh_deform_eval = mesh_deform_eval; @@ -1998,7 +1976,7 @@ static void editbmesh_build_data(struct Depsgraph *depsgraph, BKE_sculpt_update_object_before_eval(obedit); } - BKE_editmesh_free_derivedmesh(em); + BKE_editmesh_free_derived_caches(em); Mesh *me_cage; Mesh *me_final; @@ -2426,7 +2404,7 @@ static void dm_debug_info_layers(DynStr *dynstr, for (type = 0; type < CD_NUMTYPES; type++) { if (CustomData_has_layer(cd, type)) { - /* note: doesn't account for multiple layers */ + /* NOTE: doesn't account for multiple layers. */ const char *name = CustomData_layertype_name(type); const int size = CustomData_sizeof(type); const void *pt = getElemDataArray(dm, type); diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index fdf3558abed..d55f023d209 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -120,7 +120,7 @@ static void action_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, for (fcurve_src = action_src->curves.first; fcurve_src; fcurve_src = fcurve_src->next) { /* Duplicate F-Curve. */ - /* XXX TODO pass subdata flag? + /* XXX TODO: pass subdata flag? * But surprisingly does not seem to be doing any ID refcounting... */ fcurve_dst = BKE_fcurve_copy(fcurve_src); @@ -497,9 +497,8 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) } /* Reconstruct group channel pointers. - * Assumes that the channels are still in the proper order, i.e. that channels of the same group - * are adjacent in the act->channels list. It also assumes that the groups - * referred to by the FCurves are already in act->groups. + * Assumes that the groups referred to by the FCurves are already in act->groups. + * Reorders the main channel list to match group order. */ void BKE_action_groups_reconstruct(bAction *act) { @@ -514,23 +513,30 @@ void BKE_action_groups_reconstruct(bAction *act) BLI_listbase_clear(&group->channels); } - bActionGroup *grp; - bActionGroup *last_grp = NULL; - LISTBASE_FOREACH (FCurve *, fcurve, &act->curves) { - if (fcurve->grp == NULL) { - continue; - } + /* Sort the channels into the group lists, destroying the act->curves list. */ + ListBase ungrouped = {NULL, NULL}; - grp = fcurve->grp; - if (last_grp != grp) { - /* If this is the first time we see this group, this must be the first channel. */ - grp->channels.first = fcurve; + LISTBASE_FOREACH_MUTABLE (FCurve *, fcurve, &act->curves) { + if (fcurve->grp) { + BLI_assert(BLI_findindex(&act->groups, fcurve->grp) >= 0); + + BLI_addtail(&fcurve->grp->channels, fcurve); + } + else { + BLI_addtail(&ungrouped, fcurve); } + } + + /* Recombine into the main list. */ + BLI_listbase_clear(&act->curves); - /* This is the last channel, until it's overwritten by a later iteration. */ - grp->channels.last = fcurve; - last_grp = grp; + LISTBASE_FOREACH (bActionGroup *, group, &act->groups) { + /* Copy the list header to preserve the pointers in the group. */ + ListBase tmp = group->channels; + BLI_movelisttolist(&act->curves, &tmp); } + + BLI_movelisttolist(&act->curves, &ungrouped); } /* Remove the given channel from all groups */ diff --git a/source/blender/blenkernel/intern/action_mirror.c b/source/blender/blenkernel/intern/action_mirror.c index 69e0091444b..48472dfc9b3 100644 --- a/source/blender/blenkernel/intern/action_mirror.c +++ b/source/blender/blenkernel/intern/action_mirror.c @@ -322,6 +322,25 @@ static void action_flip_pchan(Object *ob_arm, /* Move back to bone-space space, using the flipped bone if it exists. */ mul_m4_m4m4(chan_mat, arm_mat_inv, chan_mat); + /* The rest pose having an X-axis that is not mapping to a left/right direction (so aligned + * with the Y or Z axis) creates issues when flipping the pose. Instead of a negative scale on + * the X-axis, it turns into a 180 degree rotation over the Y-axis. + * This has only been observed with bones that can't be flipped, + * hence the check for `pchan_flip`. */ + const float unit_x[4] = {1.0f, 0.0f, 0.0f, 0.0f}; + const bool is_problematic = pchan_flip == NULL && + fabsf(dot_v4v4(pchan->bone->arm_mat[0], unit_x)) <= 1e-6; + if (is_problematic) { + /* Matrix needs to flip both the X and Z axes to come out right. */ + float extra_mat[4][4] = { + {-1.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, -1.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 1.0f}, + }; + mul_m4_m4m4(chan_mat, extra_mat, chan_mat); + } + BKE_pchan_apply_mat4(&pchan_temp, chan_mat, false); /* Write the values back to the F-curves. */ diff --git a/source/blender/blenkernel/intern/action_test.cc b/source/blender/blenkernel/intern/action_test.cc new file mode 100644 index 00000000000..c02eca966ad --- /dev/null +++ b/source/blender/blenkernel/intern/action_test.cc @@ -0,0 +1,144 @@ +/* + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * The Original Code is Copyright (C) 2021 Blender Foundation + * All rights reserved. + */ + +#include "BKE_action.h" + +#include "DNA_action_types.h" +#include "DNA_anim_types.h" + +#include "BLI_listbase.h" + +#include "testing/testing.h" + +namespace blender::bke::tests { + +TEST(action_groups, ReconstructGroupsWithReordering) +{ + /* Construct an Action with three groups. */ + bAction action = {{nullptr}}; + FCurve groupAcurve1 = {nullptr}; + FCurve groupAcurve2 = {nullptr}; + FCurve groupBcurve1 = {nullptr}; + FCurve groupBcurve2 = {nullptr}; + FCurve groupBcurve3 = {nullptr}; + /* Group C has no curves intentionally. */ + FCurve groupDcurve1 = {nullptr}; + FCurve groupDcurve2 = {nullptr}; + + groupAcurve1.rna_path = (char *)"groupAcurve1"; + groupAcurve2.rna_path = (char *)"groupAcurve2"; + groupBcurve1.rna_path = (char *)"groupBcurve1"; + groupBcurve2.rna_path = (char *)"groupBcurve2"; + groupDcurve1.rna_path = (char *)"groupDcurve1"; + groupBcurve3.rna_path = (char *)"groupBcurve3"; + groupDcurve2.rna_path = (char *)"groupDcurve2"; + + BLI_addtail(&action.curves, &groupAcurve1); + BLI_addtail(&action.curves, &groupAcurve2); + BLI_addtail(&action.curves, &groupBcurve1); + BLI_addtail(&action.curves, &groupBcurve2); + BLI_addtail(&action.curves, &groupDcurve1); + BLI_addtail(&action.curves, &groupBcurve3); /* <-- The error that should be corrected. */ + BLI_addtail(&action.curves, &groupDcurve2); + + /* Introduce another error type, by changing some `prev` pointers. */ + groupBcurve1.prev = nullptr; + groupBcurve3.prev = &groupBcurve2; + groupDcurve1.prev = &groupBcurve3; + + bActionGroup groupA = {nullptr}; + bActionGroup groupB = {nullptr}; + bActionGroup groupC = {nullptr}; + bActionGroup groupD = {nullptr}; + strcpy(groupA.name, "groupA"); + strcpy(groupB.name, "groupB"); + strcpy(groupC.name, "groupC"); + strcpy(groupD.name, "groupD"); + + BLI_addtail(&action.groups, &groupA); + BLI_addtail(&action.groups, &groupB); + BLI_addtail(&action.groups, &groupC); + BLI_addtail(&action.groups, &groupD); + + groupAcurve1.grp = &groupA; + groupAcurve2.grp = &groupA; + groupBcurve1.grp = &groupB; + groupBcurve2.grp = &groupB; + groupBcurve3.grp = &groupB; + groupDcurve1.grp = &groupD; + groupDcurve2.grp = &groupD; + + groupA.channels.first = &groupAcurve1; + groupA.channels.last = &groupAcurve2; + groupB.channels.first = &groupBcurve1; + groupB.channels.last = &groupBcurve3; /* The last channel in group B, after group C curve 1. */ + groupD.channels.first = &groupDcurve1; + groupD.channels.last = &groupDcurve2; + + EXPECT_EQ(groupA.channels.first, &groupAcurve1); + EXPECT_EQ(groupA.channels.last, &groupAcurve2); + EXPECT_EQ(groupB.channels.first, &groupBcurve1); + EXPECT_EQ(groupB.channels.last, &groupBcurve3); + EXPECT_EQ(groupC.channels.first, nullptr); + EXPECT_EQ(groupC.channels.last, nullptr); + EXPECT_EQ(groupD.channels.first, &groupDcurve1); + EXPECT_EQ(groupD.channels.last, &groupDcurve2); + + BKE_action_groups_reconstruct(&action); + + EXPECT_EQ(action.curves.first, &groupAcurve1); + EXPECT_EQ(action.curves.last, &groupDcurve2); + + EXPECT_EQ(groupA.prev, nullptr); + EXPECT_EQ(groupB.prev, &groupA); + EXPECT_EQ(groupC.prev, &groupB); + EXPECT_EQ(groupD.prev, &groupC); + + EXPECT_EQ(groupA.next, &groupB); + EXPECT_EQ(groupB.next, &groupC); + EXPECT_EQ(groupC.next, &groupD); + EXPECT_EQ(groupD.next, nullptr); + + EXPECT_EQ(groupA.channels.first, &groupAcurve1); + EXPECT_EQ(groupA.channels.last, &groupAcurve2); + EXPECT_EQ(groupB.channels.first, &groupBcurve1); + EXPECT_EQ(groupB.channels.last, &groupBcurve3); + EXPECT_EQ(groupC.channels.first, nullptr); + EXPECT_EQ(groupC.channels.last, nullptr); + EXPECT_EQ(groupD.channels.first, &groupDcurve1); + EXPECT_EQ(groupD.channels.last, &groupDcurve2); + + EXPECT_EQ(groupAcurve1.prev, nullptr); + EXPECT_EQ(groupAcurve2.prev, &groupAcurve1); + EXPECT_EQ(groupBcurve1.prev, &groupAcurve2); + EXPECT_EQ(groupBcurve2.prev, &groupBcurve1); + EXPECT_EQ(groupBcurve3.prev, &groupBcurve2); + EXPECT_EQ(groupDcurve1.prev, &groupBcurve3); + EXPECT_EQ(groupDcurve2.prev, &groupDcurve1); + + EXPECT_EQ(groupAcurve1.next, &groupAcurve2); + EXPECT_EQ(groupAcurve2.next, &groupBcurve1); + EXPECT_EQ(groupBcurve1.next, &groupBcurve2); + EXPECT_EQ(groupBcurve2.next, &groupBcurve3); + EXPECT_EQ(groupBcurve3.next, &groupDcurve1); + EXPECT_EQ(groupDcurve1.next, &groupDcurve2); + EXPECT_EQ(groupDcurve2.next, nullptr); +} + +} // namespace blender::bke::tests diff --git a/source/blender/blenkernel/intern/anim_data.c b/source/blender/blenkernel/intern/anim_data.c index 2f71dda17f2..7e4ab754500 100644 --- a/source/blender/blenkernel/intern/anim_data.c +++ b/source/blender/blenkernel/intern/anim_data.c @@ -89,16 +89,16 @@ bool id_can_have_animdata(const ID *id) return id_type_can_have_animdata(GS(id->name)); } -/* Get AnimData from the given ID-block. In order for this to work, we assume that - * the AnimData pointer is stored immediately after the given ID-block in the struct, - * as per IdAdtTemplate. +/** + * Get #AnimData from the given ID-block. */ AnimData *BKE_animdata_from_id(ID *id) { - /* only some ID-blocks have this info for now, so we cast the - * types that do to be of type IdAdtTemplate, and extract the - * AnimData that way - */ + /* In order for this to work, we assume that the #AnimData pointer is stored + * immediately after the given ID-block in the struct, as per IdAdtTemplate. */ + + /* Only some ID-blocks have this info for now, so we cast the types that do + * to be of type IdAdtTemplate, and add the AnimData to it using the template. */ if (id_can_have_animdata(id)) { IdAdtTemplate *iat = (IdAdtTemplate *)id; return iat->adt; @@ -106,16 +106,16 @@ AnimData *BKE_animdata_from_id(ID *id) return NULL; } -/* Add AnimData to the given ID-block. In order for this to work, we assume that - * the AnimData pointer is stored immediately after the given ID-block in the struct, - * as per IdAdtTemplate. Also note that +/** + * Ensure #AnimData exists in the given ID-block (when supported). */ -AnimData *BKE_animdata_add_id(ID *id) +AnimData *BKE_animdata_ensure_id(ID *id) { - /* Only some ID-blocks have this info for now, so we cast the - * types that do to be of type IdAdtTemplate, and add the AnimData - * to it using the template - */ + /* In order for this to work, we assume that the #AnimData pointer is stored + * immediately after the given ID-block in the struct, as per IdAdtTemplate. */ + + /* Only some ID-blocks have this info for now, so we cast the types that do + * to be of type IdAdtTemplate, and add the AnimData to it using the template. */ if (id_can_have_animdata(id)) { IdAdtTemplate *iat = (IdAdtTemplate *)id; @@ -336,7 +336,7 @@ AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const int flag) * BKE_id_copy_ex(). * So in case we do copy the ID and its sub-IDs in bmain, silence the 'no usercount' flag for * the sub-IDs copying. - * Note: This is a bit weak, as usually when it comes to recursive ID copy. Should work for + * NOTE: This is a bit weak, as usually when it comes to recursive ID copy. Should work for * now, but we may have to revisit this at some point and add a proper extra flag to deal with * that situation. Or refactor completely the way we handle such recursion, by flattening it * e.g. */ @@ -444,7 +444,7 @@ void BKE_animdata_merge_copy( return; } - // TODO: we must unset all "tweakmode" flags + /* TODO: we must unset all "tweak-mode" flags. */ if ((src->flag & ADT_NLA_EDIT_ON) || (dst->flag & ADT_NLA_EDIT_ON)) { CLOG_ERROR( &LOG, @@ -667,7 +667,7 @@ void BKE_animdata_transfer_by_basepath(Main *bmain, ID *srcID, ID *dstID, ListBa /* get animdata from src, and create for destination (if needed) */ srcAdt = BKE_animdata_from_id(srcID); - dstAdt = BKE_animdata_add_id(dstID); + dstAdt = BKE_animdata_ensure_id(dstID); if (ELEM(NULL, srcAdt, dstAdt)) { if (G.debug & G_DEBUG) { @@ -1563,7 +1563,7 @@ void BKE_animdata_blend_write(BlendWriter *writer, struct AnimData *adt) BLO_write_string(writer, aor->rna_path); } - /* TODO write the remaps (if they are needed) */ + /* TODO: write the remaps (if they are needed). */ /* write NLA data */ BKE_nla_blend_write(writer, &adt->nla_tracks); @@ -1590,10 +1590,10 @@ void BKE_animdata_blend_read_data(BlendDataReader *reader, AnimData *adt) /* relink active track/strip - even though strictly speaking this should only be used * if we're in 'tweaking mode', we need to be able to have this loaded back for - * undo, but also since users may not exit tweakmode before saving (T24535) + * undo, but also since users may not exit tweak-mode before saving (T24535). */ /* TODO: it's not really nice that anyone should be able to save the file in this - * state, but it's going to be too hard to enforce this single case... */ + * state, but it's going to be too hard to enforce this single case. */ BLO_read_data_address(reader, &adt->act_track); BLO_read_data_address(reader, &adt->actstrip); } diff --git a/source/blender/blenkernel/intern/anim_path.c b/source/blender/blenkernel/intern/anim_path.c index e2c2708101b..de470a15041 100644 --- a/source/blender/blenkernel/intern/anim_path.c +++ b/source/blender/blenkernel/intern/anim_path.c @@ -216,7 +216,7 @@ static bool binary_search_anim_path(const float *accum_len_arr, if (UNLIKELY(cur_step == 0)) { /* This should never happen unless there is something horribly wrong. */ CLOG_ERROR(&LOG, "Couldn't find any valid point on the animation path!"); - BLI_assert(!"Couldn't find any valid point on the animation path!"); + BLI_assert_msg(0, "Couldn't find any valid point on the animation path!"); return false; } diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c index 08a3f3fcf4f..2879a995ad6 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -621,6 +621,115 @@ static void animsys_evaluate_fcurves(PointerRNA *ptr, } } +/* This function assumes that the quaternion is fully keyed, and is stored in array index order. */ +static void animsys_quaternion_evaluate_fcurves(PathResolvedRNA quat_rna, + FCurve *first_fcurve, + const AnimationEvalContext *anim_eval_context, + float r_quaternion[4]) +{ + FCurve *quat_curve_fcu = first_fcurve; + for (int prop_index = 0; prop_index < 4; ++prop_index, quat_curve_fcu = quat_curve_fcu->next) { + /* Big fat assumption that the quaternion is fully keyed, and stored in order. */ + BLI_assert(STREQ(quat_curve_fcu->rna_path, first_fcurve->rna_path) && + quat_curve_fcu->array_index == prop_index); + + quat_rna.prop_index = prop_index; + r_quaternion[prop_index] = calculate_fcurve(&quat_rna, quat_curve_fcu, anim_eval_context); + } +} + +/* This function assumes that the quaternion is fully keyed, and is stored in array index order. */ +static void animsys_blend_fcurves_quaternion(PathResolvedRNA *anim_rna, + FCurve *first_fcurve, + const AnimationEvalContext *anim_eval_context, + const float blend_factor) +{ + float current_quat[4]; + RNA_property_float_get_array(&anim_rna->ptr, anim_rna->prop, current_quat); + + float target_quat[4]; + animsys_quaternion_evaluate_fcurves(*anim_rna, first_fcurve, anim_eval_context, target_quat); + + float blended_quat[4]; + interp_qt_qtqt(blended_quat, current_quat, target_quat, blend_factor); + + RNA_property_float_set_array(&anim_rna->ptr, anim_rna->prop, blended_quat); +} + +/* LERP between current value (blend_factor=0.0) and the value from the FCurve (blend_factor=1.0) + */ +static void animsys_blend_in_fcurves(PointerRNA *ptr, + ListBase *fcurves, + const AnimationEvalContext *anim_eval_context, + const float blend_factor) +{ + char *channel_to_skip = NULL; + int num_channels_to_skip = 0; + LISTBASE_FOREACH (FCurve *, fcu, fcurves) { + + if (num_channels_to_skip) { + /* For skipping already-handled rotation channels. Rotation channels are handled per group, + * and not per individual channel. */ + BLI_assert(channel_to_skip != NULL); + if (STREQ(channel_to_skip, fcu->rna_path)) { + /* This is indeed the channel we want to skip. */ + num_channels_to_skip--; + continue; + } + } + + if (!is_fcurve_evaluatable(fcu)) { + continue; + } + + PathResolvedRNA anim_rna; + if (!BKE_animsys_rna_path_resolve(ptr, fcu->rna_path, fcu->array_index, &anim_rna)) { + continue; + } + + if (STREQ(RNA_property_identifier(anim_rna.prop), "rotation_quaternion")) { + animsys_blend_fcurves_quaternion(&anim_rna, fcu, anim_eval_context, blend_factor); + + /* Skip the next three channels, because those have already been handled here. */ + MEM_SAFE_FREE(channel_to_skip); + channel_to_skip = BLI_strdup(fcu->rna_path); + num_channels_to_skip = 3; + continue; + } + /* TODO(Sybren): do something similar as above for Euler and Axis/Angle representations. */ + + const float fcurve_value = calculate_fcurve(&anim_rna, fcu, anim_eval_context); + + float current_value; + float value_to_write; + if (BKE_animsys_read_from_rna_path(&anim_rna, ¤t_value)) { + value_to_write = (1 - blend_factor) * current_value + blend_factor * fcurve_value; + + switch (RNA_property_type(anim_rna.prop)) { + case PROP_BOOLEAN: + /* Without this, anything less than 1.0 is converted to 'False' by + * ANIMSYS_FLOAT_AS_BOOL(). This is probably not desirable for blends, where anything + * above a 50% blend should act more like the FCurve than like the current value. */ + case PROP_INT: + case PROP_ENUM: + value_to_write = roundf(value_to_write); + break; + default: + /* All other types are just handled as float, and value_to_write is already correct. */ + break; + } + } + else { + /* Unable to read the current value for blending, so just apply the FCurve value instead. */ + value_to_write = fcurve_value; + } + + BKE_animsys_write_to_rna_path(&anim_rna, value_to_write); + } + + MEM_SAFE_FREE(channel_to_skip); +} + /* ***************************************** */ /* Driver Evaluation */ @@ -769,6 +878,16 @@ void animsys_evaluate_action(PointerRNA *ptr, animsys_evaluate_fcurves(ptr, &act->curves, anim_eval_context, flush_to_original); } +/* Evaluate Action and blend it into the current values of the animated properties. */ +void animsys_blend_in_action(PointerRNA *ptr, + bAction *act, + const AnimationEvalContext *anim_eval_context, + const float blend_factor) +{ + action_idcode_patch_check(ptr->owner_id, act); + animsys_blend_in_fcurves(ptr, &act->curves, anim_eval_context, blend_factor); +} + /* ***************************************** */ /* NLA System - Evaluation */ @@ -1457,7 +1576,7 @@ static float nla_blend_value(const int blendmode, return influence * (lower_value * strip_value) + (1 - influence) * lower_value; case NLASTRIP_MODE_COMBINE: - BLI_assert(!"combine mode"); + BLI_assert_msg(0, "combine mode"); ATTR_FALLTHROUGH; default: @@ -1495,7 +1614,7 @@ static float nla_combine_value(const int mix_mode, return lower_value * powf(strip_value / base_value, influence); default: - BLI_assert(!"invalid mix mode"); + BLI_assert_msg(0, "invalid mix mode"); return lower_value; } } @@ -1546,7 +1665,7 @@ static bool nla_blend_get_inverted_strip_value(const int blendmode, return true; case NLASTRIP_MODE_COMBINE: - BLI_assert(!"combine mode"); + BLI_assert_msg(0, "combine mode"); ATTR_FALLTHROUGH; default: @@ -1602,7 +1721,7 @@ static bool nla_combine_get_inverted_strip_value(const int mix_mode, return true; default: - BLI_assert(!"invalid mix mode"); + BLI_assert_msg(0, "invalid mix mode"); return false; } } @@ -2746,7 +2865,7 @@ static void animsys_evaluate_nla_for_keyframing(PointerRNA *ptr, } } - /** Note: Although we early out, we can still keyframe to the non-pushed action since the + /** NOTE: Although we early out, we can still keyframe to the non-pushed action since the * keyframe remap function detects (r_context->strip.act == NULL) and will keyframe without * remapping. */ @@ -3033,7 +3152,7 @@ bool BKE_animsys_nla_remap_keyframe_values(struct NlaKeyframingContext *context, NlaEvalChannel *nec = nlaevalchan_verify_key(eval_data, NULL, &key); BLI_assert(nec); if (nec->base_snapshot.length != count) { - BLI_assert(!"invalid value count"); + BLI_assert_msg(0, "invalid value count"); nlaeval_snapshot_free_data(&blended_snapshot); return false; } @@ -3126,7 +3245,7 @@ static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) * * 3) Drivers/expressions are evaluated on top of this, in an order where dependencies are * resolved nicely. - * Note: it may be necessary to have some tools to handle the cases where some higher-level + * NOTE: it may be necessary to have some tools to handle the cases where some higher-level * drivers are added and cause some problematic dependencies that * didn't exist in the local levels... * diff --git a/source/blender/blenkernel/intern/anim_visualization.c b/source/blender/blenkernel/intern/anim_visualization.c index ecd71ec08fe..56bd8e769bc 100644 --- a/source/blender/blenkernel/intern/anim_visualization.c +++ b/source/blender/blenkernel/intern/anim_visualization.c @@ -50,8 +50,8 @@ void animviz_settings_init(bAnimVizSettings *avs) /* path settings */ avs->path_bc = avs->path_ac = 10; - avs->path_sf = 1; /* xxx - take from scene instead? */ - avs->path_ef = 250; /* xxx - take from scene instead? */ + avs->path_sf = 1; /* XXX: Take from scene instead? */ + avs->path_ef = 250; /* XXX: Take from scene instead? */ avs->path_viewflag = (MOTIONPATH_VIEW_KFRAS | MOTIONPATH_VIEW_KFNOS); diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index 579f671e2b0..eae331fc7d1 100644 --- a/source/blender/blenkernel/intern/appdir.c +++ b/source/blender/blenkernel/intern/appdir.c @@ -191,8 +191,7 @@ bool BKE_appdir_folder_documents(char *dir) { dir[0] = '\0'; - const char *documents_path = (const char *)GHOST_getUserSpecialDir( - GHOST_kUserSpecialDirDocuments); + const char *documents_path = GHOST_getUserSpecialDir(GHOST_kUserSpecialDirDocuments); /* Usual case: Ghost gave us the documents path. We're done here. */ if (documents_path && BLI_is_dir(documents_path)) { @@ -462,7 +461,7 @@ static bool get_path_user_ex(char *targetpath, } user_path[0] = '\0'; - user_base_path = (const char *)GHOST_getUserDir(version, blender_version_decimal(version)); + user_base_path = GHOST_getUserDir(version, blender_version_decimal(version)); if (user_base_path) { BLI_strncpy(user_path, user_base_path, FILE_MAX); } @@ -522,7 +521,7 @@ static bool get_path_system_ex(char *targetpath, } system_path[0] = '\0'; - system_base_path = (const char *)GHOST_getSystemDir(version, blender_version_decimal(version)); + system_base_path = GHOST_getSystemDir(version, blender_version_decimal(version)); if (system_base_path) { BLI_strncpy(system_path, system_base_path, FILE_MAX); } @@ -780,7 +779,7 @@ const char *BKE_appdir_folder_id_version(const int folder_id, default: path[0] = '\0'; /* in case check_is_dir is false */ ok = false; - BLI_assert(!"incorrect ID"); + BLI_assert_msg(0, "incorrect ID"); break; } return ok ? path : NULL; diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c index d0604f4bfda..b8ed519e8d1 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -2405,9 +2405,9 @@ static void pose_proxy_sync(Object *ob, Object *from, int layer_protected) BKE_pose_rest(frompose, false); /* copy over all of the proxy's bone groups */ - /* TODO for later + /* TODO: for later * - implement 'local' bone groups as for constraints - * Note: this isn't trivial, as bones reference groups by index not by pointer, + * NOTE: this isn't trivial, as bones reference groups by index not by pointer, * so syncing things correctly needs careful attention */ BLI_freelistN(&pose->agroups); BLI_duplicatelist(&pose->agroups, &frompose->agroups); @@ -2543,7 +2543,7 @@ static int rebuild_pose_bone( * (grand-(grand-(...)))-child (as processed by the recursive, depth-first nature of this * function) of the previous sibling. * - * Note: In most cases there is nothing to do here, but pose list may get out of order when some + * NOTE: In most cases there is nothing to do here, but pose list may get out of order when some * bones are added, removed or moved in the armature data. */ bPoseChannel *pchan_prev = pchan->prev; const Bone *last_visited_bone = *r_last_visited_bone_p; @@ -2843,7 +2843,7 @@ void BKE_pose_where_is(struct Depsgraph *depsgraph, Scene *scene, Object *ob) * hopefully this is OK. */ BKE_pose_ensure(NULL, ob, arm, true); - ctime = BKE_scene_frame_get(scene); /* not accurate... */ + ctime = BKE_scene_ctime_get(scene); /* not accurate... */ /* In edit-mode or rest-position we read the data from the bones. */ if (arm->edbo || (arm->flag & ARM_RESTPOS)) { diff --git a/source/blender/blenkernel/intern/armature_deform.c b/source/blender/blenkernel/intern/armature_deform.c index bca5503c8d2..5f721b49361 100644 --- a/source/blender/blenkernel/intern/armature_deform.c +++ b/source/blender/blenkernel/intern/armature_deform.c @@ -47,6 +47,7 @@ #include "BKE_action.h" #include "BKE_armature.h" +#include "BKE_customdata.h" #include "BKE_deform.h" #include "BKE_editmesh.h" #include "BKE_lattice.h" @@ -485,7 +486,7 @@ static void armature_deform_coords_impl(const Object *ob_arm, int defbase_len = 0; /* safety for vertexgroup index overflow */ int i, dverts_len = 0; /* safety for vertexgroup overflow */ bool use_dverts = false; - int armature_def_nr; + int armature_def_nr = -1; int cd_dvert_offset = -1; /* in editmode, or not an armature */ @@ -500,11 +501,11 @@ static void armature_deform_coords_impl(const Object *ob_arm, BLI_assert(0); } - /* get the def_nr for the overall armature vertex group if present */ - armature_def_nr = BKE_object_defgroup_name_index(ob_target, defgrp_name); + if (BKE_object_supports_vertex_groups(ob_target)) { + /* get the def_nr for the overall armature vertex group if present */ + armature_def_nr = BKE_object_defgroup_name_index(ob_target, defgrp_name); - if (ELEM(ob_target->type, OB_MESH, OB_LATTICE, OB_GPENCIL)) { - defbase_len = BLI_listbase_count(&ob_target->defbase); + defbase_len = BKE_object_defgroup_count(ob_target); if (ob_target->type == OB_MESH) { if (em_target == NULL) { @@ -528,11 +529,9 @@ static void armature_deform_coords_impl(const Object *ob_arm, dverts_len = gps_target->totpoints; } } - } - /* get a vertex-deform-index to posechannel array */ - if (deformflag & ARM_DEF_VGROUP) { - if (ELEM(ob_target->type, OB_MESH, OB_LATTICE, OB_GPENCIL)) { + /* get a vertex-deform-index to posechannel array */ + if (deformflag & ARM_DEF_VGROUP) { /* if we have a Mesh, only use dverts if it has them */ if (em_target) { cd_dvert_offset = CustomData_get_offset(&em_target->bm->vdata, CD_MDEFORMVERT); @@ -551,7 +550,8 @@ static void armature_deform_coords_impl(const Object *ob_arm, * * - Check whether keeping this consistent across frames gives speedup. */ - for (i = 0, dg = ob_target->defbase.first; dg; i++, dg = dg->next) { + const ListBase *defbase = BKE_object_defgroup_list(ob_target); + for (i = 0, dg = defbase->first; dg; i++, dg = dg->next) { pchan_from_defbase[i] = BKE_pose_channel_find_name(ob_arm->pose, dg->name); /* exclude non-deforming bones */ if (pchan_from_defbase[i]) { diff --git a/source/blender/blenkernel/intern/armature_pose.cc b/source/blender/blenkernel/intern/armature_pose.cc index ca11692372b..09e1c7d6615 100644 --- a/source/blender/blenkernel/intern/armature_pose.cc +++ b/source/blender/blenkernel/intern/armature_pose.cc @@ -26,6 +26,7 @@ #include "BKE_animsys.h" #include "BKE_armature.h" +#include "BLI_function_ref.hh" #include "BLI_set.hh" #include "DNA_action_types.h" @@ -38,16 +39,62 @@ namespace { using BoneNameSet = blender::Set<std::string>; +using ActionApplier = + blender::FunctionRef<void(PointerRNA *, bAction *, const AnimationEvalContext *)>; + // Forward declarations. BoneNameSet pose_apply_find_selected_bones(const bArmature *armature, const bPose *pose); void pose_apply_disable_fcurves_for_unselected_bones(bAction *action, const BoneNameSet &selected_bone_names); void pose_apply_restore_fcurves(bAction *action); + +void pose_apply(struct Object *ob, + struct bAction *action, + struct AnimationEvalContext *anim_eval_context, + ActionApplier applier); + } // namespace -void BKE_pose_apply_action(struct Object *ob, - struct bAction *action, - struct AnimationEvalContext *anim_eval_context) +void BKE_pose_apply_action_selected_bones(struct Object *ob, + struct bAction *action, + struct AnimationEvalContext *anim_eval_context) +{ + auto evaluate_and_apply = + [](PointerRNA *ptr, bAction *act, const AnimationEvalContext *anim_eval_context) { + animsys_evaluate_action(ptr, act, anim_eval_context, false); + }; + + pose_apply(ob, action, anim_eval_context, evaluate_and_apply); +} + +void BKE_pose_apply_action_all_bones(struct Object *ob, + struct bAction *action, + struct AnimationEvalContext *anim_eval_context) +{ + PointerRNA pose_owner_ptr; + RNA_id_pointer_create(&ob->id, &pose_owner_ptr); + animsys_evaluate_action(&pose_owner_ptr, action, anim_eval_context, false); +} + +void BKE_pose_apply_action_blend(struct Object *ob, + struct bAction *action, + struct AnimationEvalContext *anim_eval_context, + const float blend_factor) +{ + auto evaluate_and_blend = [blend_factor](PointerRNA *ptr, + bAction *act, + const AnimationEvalContext *anim_eval_context) { + animsys_blend_in_action(ptr, act, anim_eval_context, blend_factor); + }; + + pose_apply(ob, action, anim_eval_context, evaluate_and_blend); +} + +namespace { +void pose_apply(struct Object *ob, + struct bAction *action, + struct AnimationEvalContext *anim_eval_context, + ActionApplier applier) { bPose *pose = ob->pose; if (pose == nullptr) { @@ -67,14 +114,14 @@ void BKE_pose_apply_action(struct Object *ob, /* Apply the Action. */ PointerRNA pose_owner_ptr; RNA_id_pointer_create(&ob->id, &pose_owner_ptr); - animsys_evaluate_action(&pose_owner_ptr, action, anim_eval_context, false); + + applier(&pose_owner_ptr, action, anim_eval_context); if (limit_to_selected_bones) { pose_apply_restore_fcurves(action); } } -namespace { BoneNameSet pose_apply_find_selected_bones(const bArmature *armature, const bPose *pose) { BoneNameSet selected_bone_names; diff --git a/source/blender/blenkernel/intern/armature_update.c b/source/blender/blenkernel/intern/armature_update.c index 0f8956a1a91..35ae2d2dbef 100644 --- a/source/blender/blenkernel/intern/armature_update.c +++ b/source/blender/blenkernel/intern/armature_update.c @@ -562,7 +562,7 @@ static void splineik_evaluate_bone( * spline dictates, while still maintaining roll control from the existing bone animation. */ mul_m3_m3m3(pose_mat, dmat, rmat); - /* Attempt to reduce shearing, though I doubt this'll really help too much now... */ + /* Attempt to reduce shearing, though I doubt this will really help too much now. */ normalize_m3(pose_mat); mul_m3_m3m3(base_pose_mat, dmat, base_pose_mat); @@ -828,7 +828,7 @@ void BKE_pose_eval_init_ik(struct Depsgraph *depsgraph, Scene *scene, Object *ob { DEG_debug_print_eval(depsgraph, __func__, object->id.name, object); BLI_assert(object->type == OB_ARMATURE); - const float ctime = BKE_scene_frame_get(scene); /* not accurate... */ + const float ctime = BKE_scene_ctime_get(scene); /* not accurate... */ bArmature *armature = (bArmature *)object->data; if (armature->flag & ARM_RESTPOS) { return; @@ -869,7 +869,7 @@ void BKE_pose_eval_bone(struct Depsgraph *depsgraph, Scene *scene, Object *objec else { if ((pchan->flag & POSE_DONE) == 0) { /* TODO(sergey): Use time source node for time. */ - float ctime = BKE_scene_frame_get(scene); /* not accurate... */ + float ctime = BKE_scene_ctime_get(scene); /* not accurate... */ BKE_pose_where_is_bone(depsgraph, scene, object, pchan, ctime, 1); } } @@ -897,7 +897,7 @@ void BKE_pose_constraints_evaluate(struct Depsgraph *depsgraph, } else { if ((pchan->flag & POSE_DONE) == 0) { - float ctime = BKE_scene_frame_get(scene); /* not accurate... */ + float ctime = BKE_scene_ctime_get(scene); /* not accurate... */ BKE_pose_where_is_bone(depsgraph, scene, object, pchan, ctime, 1); } } @@ -981,7 +981,7 @@ void BKE_pose_iktree_evaluate(struct Depsgraph *depsgraph, DEG_debug_print_eval_subdata( depsgraph, __func__, object->id.name, object, "rootchan", rootchan->name, rootchan); BLI_assert(object->type == OB_ARMATURE); - const float ctime = BKE_scene_frame_get(scene); /* not accurate... */ + const float ctime = BKE_scene_ctime_get(scene); /* not accurate... */ if (armature->flag & ARM_RESTPOS) { return; } @@ -1002,7 +1002,7 @@ void BKE_pose_splineik_evaluate(struct Depsgraph *depsgraph, DEG_debug_print_eval_subdata( depsgraph, __func__, object->id.name, object, "rootchan", rootchan->name, rootchan); BLI_assert(object->type == OB_ARMATURE); - const float ctime = BKE_scene_frame_get(scene); /* not accurate... */ + const float ctime = BKE_scene_ctime_get(scene); /* not accurate... */ if (armature->flag & ARM_RESTPOS) { return; } @@ -1031,7 +1031,7 @@ void BKE_pose_eval_cleanup(struct Depsgraph *depsgraph, Scene *scene, Object *ob bPose *pose = object->pose; BLI_assert(pose != NULL); UNUSED_VARS_NDEBUG(pose); - const float ctime = BKE_scene_frame_get(scene); /* not accurate... */ + const float ctime = BKE_scene_ctime_get(scene); /* not accurate... */ DEG_debug_print_eval(depsgraph, __func__, object->id.name, object); BLI_assert(object->type == OB_ARMATURE); /* Release the IK tree. */ diff --git a/source/blender/blenkernel/intern/asset.cc b/source/blender/blenkernel/intern/asset.cc index b5a7f5e37a6..f74018b20c5 100644 --- a/source/blender/blenkernel/intern/asset.cc +++ b/source/blender/blenkernel/intern/asset.cc @@ -110,6 +110,11 @@ void BKE_asset_metadata_tag_remove(AssetMetaData *asset_data, AssetTag *tag) BLI_assert(BLI_listbase_count(&asset_data->tags) == asset_data->tot_tags); } +void BKE_asset_library_reference_init_default(AssetLibraryReference *library_ref) +{ + memcpy(library_ref, DNA_struct_default_get(AssetLibraryReference), sizeof(*library_ref)); +} + /* Queries -------------------------------------------- */ PreviewImage *BKE_asset_metadata_preview_get_from_id(const AssetMetaData *UNUSED(asset_data), diff --git a/source/blender/blenkernel/intern/attribute.c b/source/blender/blenkernel/intern/attribute.c index 5db45471f0a..ad2be4ffe30 100644 --- a/source/blender/blenkernel/intern/attribute.c +++ b/source/blender/blenkernel/intern/attribute.c @@ -119,7 +119,7 @@ bool BKE_id_attribute_rename(ID *id, ReportList *reports) { if (BKE_id_attribute_required(id, layer)) { - BLI_assert(!"Required attribute name is not editable"); + BLI_assert_msg(0, "Required attribute name is not editable"); return false; } @@ -202,7 +202,7 @@ AttributeDomain BKE_id_attribute_domain(ID *id, CustomDataLayer *layer) } } - BLI_assert(!"Custom data layer not found in geometry"); + BLI_assert_msg(0, "Custom data layer not found in geometry"); return ATTR_DOMAIN_NUM; } @@ -218,7 +218,7 @@ int BKE_id_attribute_data_length(ID *id, CustomDataLayer *layer) } } - BLI_assert(!"Custom data layer not found in geometry"); + BLI_assert_msg(0, "Custom data layer not found in geometry"); return 0; } diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index e84b485c466..97a54f289ee 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -127,7 +127,7 @@ static void blender_version_init(void) version_cycle = ""; } else { - BLI_assert(!"Invalid Blender version cycle"); + BLI_assert_msg(0, "Invalid Blender version cycle"); } BLI_snprintf(blender_version_string, diff --git a/source/blender/blenkernel/intern/blendfile.c b/source/blender/blenkernel/intern/blendfile.c index f31d8f5ade7..19721b4313d 100644 --- a/source/blender/blenkernel/intern/blendfile.c +++ b/source/blender/blenkernel/intern/blendfile.c @@ -128,7 +128,7 @@ static void setup_app_userdef(BlendFileData *bfd) } /** - * Context matching, handle no-ui case + * Context matching, handle no-UI case. * * \note this is called on Undo so any slow conversion functions here * should be avoided or check (mode != LOAD_UNDO). @@ -622,6 +622,7 @@ UserDef *BKE_blendfile_userdef_from_defaults(void) "io_scene_obj", "io_scene_x3d", "cycles", + "pose_library", }; for (int i = 0; i < ARRAY_SIZE(addons); i++) { bAddon *addon = BKE_addon_new(); diff --git a/source/blender/blenkernel/intern/bpath.c b/source/blender/blenkernel/intern/bpath.c index f26a9f06697..70274de8bff 100644 --- a/source/blender/blenkernel/intern/bpath.c +++ b/source/blender/blenkernel/intern/bpath.c @@ -18,7 +18,7 @@ * \ingroup bli */ -/* TODO, +/* TODO: * currently there are some cases we don't support. * - passing output paths to the visitor?, like render out. * - passing sequence strips with many images. diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index fdf9cf21b85..abf7bab7612 100644 --- a/source/blender/blenkernel/intern/brush.c +++ b/source/blender/blenkernel/intern/brush.c @@ -379,10 +379,10 @@ static void brush_undo_preserve(BlendLibReader *reader, ID *id_new, ID *id_old) BKE_lib_id_swap(NULL, id_new, id_old); /* `id_new` now has content from `id_old`, we need to ensure those old ID pointers are valid. - * Note: Since we want to re-use all old pointers here, code is much simpler than for Scene. */ + * NOTE: Since we want to re-use all old pointers here, code is much simpler than for Scene. */ BKE_library_foreach_ID_link(NULL, id_new, brush_undo_preserve_cb, reader, IDWALK_NOP); - /* Note: We do not swap IDProperties, as dealing with potential ID pointers in those would be + /* NOTE: We do not swap IDProperties, as dealing with potential ID pointers in those would be * fairly delicate. */ SWAP(IDProperty *, id_new->properties, id_old->properties); } diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.cc index 4659c464099..164f921c7ac 100644 --- a/source/blender/blenkernel/intern/bvhutils.c +++ b/source/blender/blenkernel/intern/bvhutils.cc @@ -21,9 +21,9 @@ * \ingroup bke */ -#include <math.h> -#include <stdio.h> -#include <string.h> +#include <cmath> +#include <cstdio> +#include <cstring> #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" @@ -46,15 +46,15 @@ /** \name BVHCache * \{ */ -typedef struct BVHCacheItem { +struct BVHCacheItem { bool is_filled; BVHTree *tree; -} BVHCacheItem; +}; -typedef struct BVHCache { +struct BVHCache { BVHCacheItem items[BVHTREE_MAX_ITEM]; ThreadMutex mutex; -} BVHCache; +}; /** * Queries a bvhcache for the cache bvhtree of the request type @@ -74,14 +74,14 @@ static bool bvhcache_find(BVHCache **bvh_cache_p, if (r_locked) { *r_locked = false; } - if (*bvh_cache_p == NULL) { + if (*bvh_cache_p == nullptr) { if (!do_lock) { /* Cache does not exist and no lock is requested. */ return false; } /* Lazy initialization of the bvh_cache using the `mesh_eval_mutex`. */ BLI_mutex_lock(mesh_eval_mutex); - if (*bvh_cache_p == NULL) { + if (*bvh_cache_p == nullptr) { *bvh_cache_p = bvhcache_init(); } BLI_mutex_unlock(mesh_eval_mutex); @@ -94,7 +94,7 @@ static bool bvhcache_find(BVHCache **bvh_cache_p, } if (do_lock) { BLI_mutex_lock(&bvh_cache->mutex); - bool in_cache = bvhcache_find(bvh_cache_p, type, r_tree, NULL, NULL); + bool in_cache = bvhcache_find(bvh_cache_p, type, r_tree, nullptr, nullptr); if (in_cache) { BLI_mutex_unlock(&bvh_cache->mutex); return in_cache; @@ -113,11 +113,11 @@ static void bvhcache_unlock(BVHCache *bvh_cache, bool lock_started) bool bvhcache_has_tree(const BVHCache *bvh_cache, const BVHTree *tree) { - if (bvh_cache == NULL) { + if (bvh_cache == nullptr) { return false; } - for (BVHCacheType i = 0; i < BVHTREE_MAX_ITEM; i++) { + for (int i = 0; i < BVHTREE_MAX_ITEM; i++) { if (bvh_cache->items[i].tree == tree) { return true; } @@ -127,7 +127,7 @@ bool bvhcache_has_tree(const BVHCache *bvh_cache, const BVHTree *tree) BVHCache *bvhcache_init(void) { - BVHCache *cache = MEM_callocN(sizeof(BVHCache), __func__); + BVHCache *cache = (BVHCache *)MEM_callocN(sizeof(BVHCache), __func__); BLI_mutex_init(&cache->mutex); return cache; } @@ -137,7 +137,7 @@ BVHCache *bvhcache_init(void) * as that will be done when the cache is freed. * * A call to this assumes that there was no previous cached tree of the given type - * \warning The #BVHTree can be NULL. + * \warning The #BVHTree can be nullptr. */ static void bvhcache_insert(BVHCache *bvh_cache, BVHTree *tree, BVHCacheType type) { @@ -152,10 +152,10 @@ static void bvhcache_insert(BVHCache *bvh_cache, BVHTree *tree, BVHCacheType typ */ void bvhcache_free(BVHCache *bvh_cache) { - for (BVHCacheType index = 0; index < BVHTREE_MAX_ITEM; index++) { + for (int index = 0; index < BVHTREE_MAX_ITEM; index++) { BVHCacheItem *item = &bvh_cache->items[index]; BLI_bvhtree_free(item->tree); - item->tree = NULL; + item->tree = nullptr; } BLI_mutex_end(&bvh_cache->mutex); MEM_freeN(bvh_cache); @@ -197,9 +197,10 @@ float bvhtree_ray_tri_intersection(const BVHTreeRay *ray, float dist; #ifdef USE_KDOPBVH_WATERTIGHT - if (isect_ray_tri_watertight_v3(ray->origin, ray->isect_precalc, v0, v1, v2, &dist, NULL)) + if (isect_ray_tri_watertight_v3(ray->origin, ray->isect_precalc, v0, v1, v2, &dist, nullptr)) #else - if (isect_ray_tri_epsilon_v3(ray->origin, ray->direction, v0, v1, v2, &dist, NULL, FLT_EPSILON)) + if (isect_ray_tri_epsilon_v3( + ray->origin, ray->direction, v0, v1, v2, &dist, nullptr, FLT_EPSILON)) #endif { return dist; @@ -247,7 +248,7 @@ static void mesh_faces_nearest_point(void *userdata, t0 = vert[face->v1].co; t1 = vert[face->v2].co; t2 = vert[face->v3].co; - t3 = face->v4 ? vert[face->v4].co : NULL; + t3 = face->v4 ? vert[face->v4].co : nullptr; do { float nearest_tmp[3], dist_sq; @@ -264,7 +265,7 @@ static void mesh_faces_nearest_point(void *userdata, t1 = t2; t2 = t3; - t3 = NULL; + t3 = nullptr; } while (t2); } @@ -300,7 +301,7 @@ static void editmesh_looptri_nearest_point(void *userdata, const float co[3], BVHTreeNearest *nearest) { - const BVHTreeFromEditMesh *data = userdata; + const BVHTreeFromEditMesh *data = (const BVHTreeFromEditMesh *)userdata; BMEditMesh *em = data->em; const BMLoop **ltri = (const BMLoop **)em->looptris[index]; @@ -339,7 +340,7 @@ static void mesh_faces_spherecast(void *userdata, t0 = vert[face->v1].co; t1 = vert[face->v2].co; t2 = vert[face->v3].co; - t3 = face->v4 ? vert[face->v4].co : NULL; + t3 = face->v4 ? vert[face->v4].co : nullptr; do { float dist; @@ -360,7 +361,7 @@ static void mesh_faces_spherecast(void *userdata, t1 = t2; t2 = t3; - t3 = NULL; + t3 = nullptr; } while (t2); } @@ -457,7 +458,7 @@ static void mesh_edges_nearest_point(void *userdata, } } -/* Helper, does all the point-spherecast work actually. */ +/* Helper, does all the point-sphere-cast work actually. */ static void mesh_verts_spherecast_do(int index, const float v[3], const BVHTreeRay *ray, @@ -484,7 +485,7 @@ static void editmesh_verts_spherecast(void *userdata, const BVHTreeRay *ray, BVHTreeRayHit *hit) { - const BVHTreeFromEditMesh *data = userdata; + const BVHTreeFromEditMesh *data = (const BVHTreeFromEditMesh *)userdata; BMVert *eve = BM_vert_at_index(data->em->bm, index); mesh_verts_spherecast_do(index, eve->co, ray, hit); @@ -600,7 +601,7 @@ static BVHTree *bvhtree_from_mesh_verts_create_tree(float epsilon, const BLI_bitmap *verts_mask, int verts_num_active) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (verts_mask) { BLI_assert(IN_RANGE_INCL(verts_num_active, 0, verts_num)); @@ -637,9 +638,9 @@ static void bvhtree_from_mesh_verts_setup_data(BVHTreeFromMesh *data, data->tree = tree; data->cached = is_cached; - /* a NULL nearest callback works fine + /* a nullptr nearest callback works fine * remember the min distance to point is the same as the min distance to BV of point */ - data->nearest_callback = NULL; + data->nearest_callback = nullptr; data->raycast_callback = mesh_verts_spherecast; data->vert = vert; @@ -658,7 +659,7 @@ BVHTree *bvhtree_from_editmesh_verts_ex(BVHTreeFromEditMesh *data, BVHCache **bvh_cache_p, ThreadMutex *mesh_eval_mutex) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (bvh_cache_p) { bool lock_started = false; @@ -671,7 +672,7 @@ BVHTree *bvhtree_from_editmesh_verts_ex(BVHTreeFromEditMesh *data, bvhtree_balance(tree, true); /* Save on cache for later use */ - /* printf("BVHTree built and saved on cache\n"); */ + // printf("BVHTree built and saved on cache\n"); bvhcache_insert(*bvh_cache_p, tree, bvh_cache_type); data->cached = true; } @@ -687,9 +688,9 @@ BVHTree *bvhtree_from_editmesh_verts_ex(BVHTreeFromEditMesh *data, memset(data, 0, sizeof(*data)); data->tree = tree; data->em = em; - data->nearest_callback = NULL; + data->nearest_callback = nullptr; data->raycast_callback = editmesh_verts_spherecast; - data->cached = bvh_cache_p != NULL; + data->cached = bvh_cache_p != nullptr; } return tree; @@ -699,11 +700,11 @@ BVHTree *bvhtree_from_editmesh_verts( BVHTreeFromEditMesh *data, BMEditMesh *em, float epsilon, int tree_type, int axis) { return bvhtree_from_editmesh_verts_ex( - data, em, NULL, -1, epsilon, tree_type, axis, 0, NULL, NULL); + data, em, nullptr, -1, epsilon, tree_type, axis, BVHTREE_FROM_VERTS, nullptr, nullptr); } /** - * Builds a bvh tree where nodes are the given vertices (note: does not copy given mverts!). + * Builds a bvh tree where nodes are the given vertices (NOTE: does not copy given `vert`!). * \param vert_allocated: if true, vert freeing will be done when freeing data. * \param verts_mask: if not null, true elements give which vert to add to BVH tree. * \param verts_num_active: if >= 0, number of active verts to add to BVH tree @@ -724,7 +725,7 @@ BVHTree *bvhtree_from_mesh_verts_ex(BVHTreeFromMesh *data, { bool in_cache = false; bool lock_started = false; - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (bvh_cache_p) { in_cache = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, &lock_started, mesh_eval_mutex); } @@ -732,11 +733,11 @@ BVHTree *bvhtree_from_mesh_verts_ex(BVHTreeFromMesh *data, if (in_cache == false) { tree = bvhtree_from_mesh_verts_create_tree( epsilon, tree_type, axis, vert, verts_num, verts_mask, verts_num_active); - bvhtree_balance(tree, bvh_cache_p != NULL); + bvhtree_balance(tree, bvh_cache_p != nullptr); if (bvh_cache_p) { /* Save on cache for later use */ - /* printf("BVHTree built and saved on cache\n"); */ + // printf("BVHTree built and saved on cache\n"); BVHCache *bvh_cache = *bvh_cache_p; bvhcache_insert(bvh_cache, tree, bvh_cache_type); in_cache = true; @@ -807,7 +808,7 @@ static BVHTree *bvhtree_from_mesh_edges_create_tree(const MVert *vert, int tree_type, int axis) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (edges_mask) { BLI_assert(IN_RANGE_INCL(edges_num_active, 0, edge_num)); @@ -817,7 +818,7 @@ static BVHTree *bvhtree_from_mesh_edges_create_tree(const MVert *vert, } if (edges_num_active) { - /* Create a bvh-tree of the given target */ + /* Create a BVH-tree of the given target */ tree = BLI_bvhtree_new(edges_num_active, epsilon, tree_type, axis); if (tree) { for (int i = 0; i < edge_num; i++) { @@ -871,7 +872,7 @@ BVHTree *bvhtree_from_editmesh_edges_ex(BVHTreeFromEditMesh *data, BVHCache **bvh_cache_p, ThreadMutex *mesh_eval_mutex) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (bvh_cache_p) { bool lock_started = false; @@ -883,7 +884,7 @@ BVHTree *bvhtree_from_editmesh_edges_ex(BVHTreeFromEditMesh *data, epsilon, tree_type, axis, em, edges_mask, edges_num_active); bvhtree_balance(tree, true); /* Save on cache for later use */ - /* printf("BVHTree built and saved on cache\n"); */ + // printf("BVHTree built and saved on cache\n"); bvhcache_insert(bvh_cache, tree, bvh_cache_type); data->cached = true; } @@ -899,9 +900,9 @@ BVHTree *bvhtree_from_editmesh_edges_ex(BVHTreeFromEditMesh *data, memset(data, 0, sizeof(*data)); data->tree = tree; data->em = em; - data->nearest_callback = NULL; /* TODO */ - data->raycast_callback = NULL; /* TODO */ - data->cached = bvh_cache_p != NULL; + data->nearest_callback = nullptr; /* TODO */ + data->raycast_callback = nullptr; /* TODO */ + data->cached = bvh_cache_p != nullptr; } return tree; @@ -911,7 +912,7 @@ BVHTree *bvhtree_from_editmesh_edges( BVHTreeFromEditMesh *data, BMEditMesh *em, float epsilon, int tree_type, int axis) { return bvhtree_from_editmesh_edges_ex( - data, em, NULL, -1, epsilon, tree_type, axis, 0, NULL, NULL); + data, em, nullptr, -1, epsilon, tree_type, axis, BVHTREE_FROM_VERTS, nullptr, nullptr); } /** @@ -939,7 +940,7 @@ BVHTree *bvhtree_from_mesh_edges_ex(BVHTreeFromMesh *data, { bool in_cache = false; bool lock_started = false; - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (bvh_cache_p) { in_cache = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, &lock_started, mesh_eval_mutex); } @@ -953,7 +954,7 @@ BVHTree *bvhtree_from_mesh_edges_ex(BVHTreeFromMesh *data, BVHCache *bvh_cache = *bvh_cache_p; /* Save on cache for later use */ - /* printf("BVHTree built and saved on cache\n"); */ + // printf("BVHTree built and saved on cache\n"); bvhcache_insert(bvh_cache, tree, bvh_cache_type); in_cache = true; } @@ -988,7 +989,7 @@ static BVHTree *bvhtree_from_mesh_faces_create_tree(float epsilon, const BLI_bitmap *faces_mask, int faces_num_active) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (faces_num) { if (faces_mask) { @@ -998,8 +999,8 @@ static BVHTree *bvhtree_from_mesh_faces_create_tree(float epsilon, faces_num_active = faces_num; } - /* Create a bvh-tree of the given target */ - /* printf("%s: building BVH, total=%d\n", __func__, numFaces); */ + /* Create a BVH-tree of the given target. */ + // printf("%s: building BVH, total=%d\n", __func__, numFaces); tree = BLI_bvhtree_new(faces_num_active, epsilon, tree_type, axis); if (tree) { if (vert && face) { @@ -1050,7 +1051,7 @@ static void bvhtree_from_mesh_faces_setup_data(BVHTreeFromMesh *data, /** * Builds a bvh tree where nodes are the given tessellated faces - * (note: does not copy given mfaces!). + * (NOTE: does not copy given mfaces!). * \param vert_allocated: if true, vert freeing will be done when freeing data. * \param face_allocated: if true, face freeing will be done when freeing data. * \param faces_mask: if not null, true elements give which faces to add to BVH tree. @@ -1074,7 +1075,7 @@ BVHTree *bvhtree_from_mesh_faces_ex(BVHTreeFromMesh *data, { bool in_cache = false; bool lock_started = false; - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (bvh_cache_p) { in_cache = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, &lock_started, mesh_eval_mutex); } @@ -1082,11 +1083,11 @@ BVHTree *bvhtree_from_mesh_faces_ex(BVHTreeFromMesh *data, if (in_cache == false) { tree = bvhtree_from_mesh_faces_create_tree( epsilon, tree_type, axis, vert, face, numFaces, faces_mask, faces_num_active); - bvhtree_balance(tree, bvh_cache_p != NULL); + bvhtree_balance(tree, bvh_cache_p != nullptr); if (bvh_cache_p) { /* Save on cache for later use */ - /* printf("BVHTree built and saved on cache\n"); */ + // printf("BVHTree built and saved on cache\n"); BVHCache *bvh_cache = *bvh_cache_p; bvhcache_insert(bvh_cache, tree, bvh_cache_type); in_cache = true; @@ -1117,7 +1118,7 @@ static BVHTree *bvhtree_from_editmesh_looptri_create_tree(float epsilon, const BLI_bitmap *looptri_mask, int looptri_num_active) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; const int looptri_num = em->tottri; if (looptri_num) { @@ -1128,11 +1129,11 @@ static BVHTree *bvhtree_from_editmesh_looptri_create_tree(float epsilon, looptri_num_active = looptri_num; } - /* Create a bvh-tree of the given target */ - /* printf("%s: building BVH, total=%d\n", __func__, numFaces); */ + /* Create a BVH-tree of the given target */ + // printf("%s: building BVH, total=%d\n", __func__, numFaces); tree = BLI_bvhtree_new(looptri_num_active, epsilon, tree_type, axis); if (tree) { - const struct BMLoop *(*looptris)[3] = (void *)em->looptris; + const BMLoop *(*looptris)[3] = (const BMLoop *(*)[3])em->looptris; /* Insert BMesh-tessellation triangles into the bvh tree, unless they are hidden * and/or selected. Even if the faces themselves are not selected for the snapped @@ -1169,7 +1170,7 @@ static BVHTree *bvhtree_from_mesh_looptri_create_tree(float epsilon, const BLI_bitmap *looptri_mask, int looptri_num_active) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (looptri_mask) { BLI_assert(IN_RANGE_INCL(looptri_num_active, 0, looptri_num)); @@ -1179,8 +1180,8 @@ static BVHTree *bvhtree_from_mesh_looptri_create_tree(float epsilon, } if (looptri_num_active) { - /* Create a bvh-tree of the given target */ - /* printf("%s: building BVH, total=%d\n", __func__, numFaces); */ + /* Create a BVH-tree of the given target */ + // printf("%s: building BVH, total=%d\n", __func__, numFaces); tree = BLI_bvhtree_new(looptri_num_active, epsilon, tree_type, axis); if (tree) { if (vert && looptri) { @@ -1247,7 +1248,7 @@ BVHTree *bvhtree_from_editmesh_looptri_ex(BVHTreeFromEditMesh *data, /* BMESH specific check that we have tessfaces, * we _could_ tessellate here but rather not - campbell */ - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (bvh_cache_p) { bool lock_started = false; bool in_cache = bvhcache_find( @@ -1260,7 +1261,7 @@ BVHTree *bvhtree_from_editmesh_looptri_ex(BVHTreeFromEditMesh *data, epsilon, tree_type, axis, em, looptri_mask, looptri_num_active); /* Save on cache for later use */ - /* printf("BVHTree built and saved on cache\n"); */ + // printf("BVHTree built and saved on cache\n"); bvhcache_insert(bvh_cache, tree, bvh_cache_type); } bvhcache_unlock(bvh_cache, lock_started); @@ -1276,7 +1277,7 @@ BVHTree *bvhtree_from_editmesh_looptri_ex(BVHTreeFromEditMesh *data, data->nearest_callback = editmesh_looptri_nearest_point; data->raycast_callback = editmesh_looptri_spherecast; data->em = em; - data->cached = bvh_cache_p != NULL; + data->cached = bvh_cache_p != nullptr; } return tree; } @@ -1285,13 +1286,13 @@ BVHTree *bvhtree_from_editmesh_looptri( BVHTreeFromEditMesh *data, BMEditMesh *em, float epsilon, int tree_type, int axis) { return bvhtree_from_editmesh_looptri_ex( - data, em, NULL, -1, epsilon, tree_type, axis, 0, NULL, NULL); + data, em, nullptr, -1, epsilon, tree_type, axis, BVHTREE_FROM_VERTS, nullptr, nullptr); } /** - * Builds a bvh tree where nodes are the looptri faces of the given dm + * Builds a BVH-tree where nodes are the looptri faces of the given mesh. * - * \note for editmesh this is currently a duplicate of bvhtree_from_mesh_faces_ex + * \note for edit-mesh this is currently a duplicate of #bvhtree_from_mesh_faces_ex */ BVHTree *bvhtree_from_mesh_looptri_ex(BVHTreeFromMesh *data, const struct MVert *vert, @@ -1312,7 +1313,7 @@ BVHTree *bvhtree_from_mesh_looptri_ex(BVHTreeFromMesh *data, { bool in_cache = false; bool lock_started = false; - BVHTree *tree = NULL; + BVHTree *tree = nullptr; if (bvh_cache_p) { in_cache = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, &lock_started, mesh_eval_mutex); } @@ -1329,7 +1330,7 @@ BVHTree *bvhtree_from_mesh_looptri_ex(BVHTreeFromMesh *data, looptri_mask, looptri_num_active); - bvhtree_balance(tree, bvh_cache_p != NULL); + bvhtree_balance(tree, bvh_cache_p != nullptr); if (bvh_cache_p) { BVHCache *bvh_cache = *bvh_cache_p; @@ -1437,19 +1438,22 @@ static BLI_bitmap *looptri_no_hidden_map_get(const MPoly *mpoly, /** * Builds or queries a bvhcache for the cache bvhtree of the request type. + * + * \note This function only fills a cache, and therefore the mesh argument can + * be considered logically const. Concurrent access is protected by a mutex. */ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, - struct Mesh *mesh, + const struct Mesh *mesh, const BVHCacheType bvh_cache_type, const int tree_type) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; BVHCache **bvh_cache_p = (BVHCache **)&mesh->runtime.bvh_cache; ThreadMutex *mesh_eval_mutex = (ThreadMutex *)mesh->runtime.eval_mutex; - bool is_cached = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, NULL, NULL); + const bool is_cached = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, nullptr, nullptr); - if (is_cached && tree == NULL) { + if (is_cached && tree == nullptr) { memset(data, 0, sizeof(*data)); return tree; } @@ -1458,7 +1462,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, case BVHTREE_FROM_VERTS: case BVHTREE_FROM_LOOSEVERTS: if (is_cached == false) { - BLI_bitmap *loose_verts_mask = NULL; + BLI_bitmap *loose_verts_mask = nullptr; int loose_vert_len = -1; int verts_len = mesh->totvert; @@ -1480,7 +1484,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, bvh_cache_p, mesh_eval_mutex); - if (loose_verts_mask != NULL) { + if (loose_verts_mask != nullptr) { MEM_freeN(loose_verts_mask); } } @@ -1493,7 +1497,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, case BVHTREE_FROM_EDGES: case BVHTREE_FROM_LOOSEEDGES: if (is_cached == false) { - BLI_bitmap *loose_edges_mask = NULL; + BLI_bitmap *loose_edges_mask = nullptr; int loose_edges_len = -1; int edges_len = mesh->totedge; @@ -1516,7 +1520,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, bvh_cache_p, mesh_eval_mutex); - if (loose_edges_mask != NULL) { + if (loose_edges_mask != nullptr) { MEM_freeN(loose_edges_mask); } } @@ -1538,7 +1542,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, mesh->mface, num_faces, false, - NULL, + nullptr, -1, 0.0, tree_type, @@ -1561,7 +1565,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, int looptri_len = BKE_mesh_runtime_looptri_len(mesh); int looptri_mask_active_len = -1; - BLI_bitmap *looptri_mask = NULL; + BLI_bitmap *looptri_mask = nullptr; if (bvh_cache_type == BVHTREE_FROM_LOOPTRI_NO_HIDDEN) { looptri_mask = looptri_no_hidden_map_get( mesh->mpoly, looptri_len, &looptri_mask_active_len); @@ -1584,7 +1588,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, bvh_cache_p, mesh_eval_mutex); - if (looptri_mask != NULL) { + if (looptri_mask != nullptr) { MEM_freeN(looptri_mask); } } @@ -1603,7 +1607,7 @@ BVHTree *BKE_bvhtree_from_mesh_get(struct BVHTreeFromMesh *data, break; } - if (data->tree != NULL) { + if (data->tree != nullptr) { #ifdef DEBUG if (BLI_bvhtree_get_tree_type(data->tree) != tree_type) { printf("tree_type %d obtained instead of %d\n", @@ -1631,15 +1635,15 @@ BVHTree *BKE_bvhtree_from_editmesh_get(BVHTreeFromEditMesh *data, BVHCache **bvh_cache_p, ThreadMutex *mesh_eval_mutex) { - BVHTree *tree = NULL; + BVHTree *tree = nullptr; bool is_cached = false; memset(data, 0, sizeof(*data)); if (bvh_cache_p) { - is_cached = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, NULL, NULL); + is_cached = bvhcache_find(bvh_cache_p, bvh_cache_type, &tree, nullptr, nullptr); - if (is_cached && tree == NULL) { + if (is_cached && tree == nullptr) { return tree; } } @@ -1650,31 +1654,55 @@ BVHTree *BKE_bvhtree_from_editmesh_get(BVHTreeFromEditMesh *data, switch (bvh_cache_type) { case BVHTREE_FROM_EM_VERTS: if (is_cached == false) { - tree = bvhtree_from_editmesh_verts_ex( - data, em, NULL, -1, 0.0f, tree_type, 6, bvh_cache_type, bvh_cache_p, mesh_eval_mutex); + tree = bvhtree_from_editmesh_verts_ex(data, + em, + nullptr, + -1, + 0.0f, + tree_type, + 6, + bvh_cache_type, + bvh_cache_p, + mesh_eval_mutex); } else { - data->nearest_callback = NULL; + data->nearest_callback = nullptr; data->raycast_callback = editmesh_verts_spherecast; } break; case BVHTREE_FROM_EM_EDGES: if (is_cached == false) { - tree = bvhtree_from_editmesh_edges_ex( - data, em, NULL, -1, 0.0f, tree_type, 6, bvh_cache_type, bvh_cache_p, mesh_eval_mutex); + tree = bvhtree_from_editmesh_edges_ex(data, + em, + nullptr, + -1, + 0.0f, + tree_type, + 6, + bvh_cache_type, + bvh_cache_p, + mesh_eval_mutex); } else { /* Setup BVHTreeFromMesh */ - data->nearest_callback = NULL; /* TODO */ - data->raycast_callback = NULL; /* TODO */ + data->nearest_callback = nullptr; /* TODO */ + data->raycast_callback = nullptr; /* TODO */ } break; case BVHTREE_FROM_EM_LOOPTRI: if (is_cached == false) { - tree = bvhtree_from_editmesh_looptri_ex( - data, em, NULL, -1, 0.0f, tree_type, 6, bvh_cache_type, bvh_cache_p, mesh_eval_mutex); + tree = bvhtree_from_editmesh_looptri_ex(data, + em, + nullptr, + -1, + 0.0f, + tree_type, + 6, + bvh_cache_type, + bvh_cache_p, + mesh_eval_mutex); } else { /* Setup BVHTreeFromMesh */ @@ -1694,7 +1722,7 @@ BVHTree *BKE_bvhtree_from_editmesh_get(BVHTreeFromEditMesh *data, break; } - if (data->tree != NULL) { + if (data->tree != nullptr) { #ifdef DEBUG if (BLI_bvhtree_get_tree_type(data->tree) != tree_type) { printf("tree_type %d obtained instead of %d\n", @@ -1763,7 +1791,7 @@ BVHTree *BKE_bvhtree_from_pointcloud_get(BVHTreeFromPointCloud *data, { BVHTree *tree = BLI_bvhtree_new(pointcloud->totpoint, 0.0f, tree_type, 6); if (!tree) { - return NULL; + return nullptr; } for (int i = 0; i < pointcloud->totpoint; i++) { @@ -1774,7 +1802,7 @@ BVHTree *BKE_bvhtree_from_pointcloud_get(BVHTreeFromPointCloud *data, data->coords = pointcloud->co; data->tree = tree; - data->nearest_callback = NULL; + data->nearest_callback = nullptr; return tree; } diff --git a/source/blender/blenkernel/intern/cachefile.c b/source/blender/blenkernel/intern/cachefile.c index 30e9ae39b67..eaba5d33a20 100644 --- a/source/blender/blenkernel/intern/cachefile.c +++ b/source/blender/blenkernel/intern/cachefile.c @@ -314,7 +314,7 @@ bool BKE_cachefile_filepath_get(const Main *bmain, if (cache_file->is_sequence && BLI_path_frame_get(r_filepath, &fframe, &frame_len)) { Scene *scene = DEG_get_evaluated_scene(depsgraph); - const float ctime = BKE_scene_frame_get(scene); + const float ctime = BKE_scene_ctime_get(scene); const float fps = (((double)scene->r.frs_sec) / (double)scene->r.frs_sec_base); const float frame = BKE_cachefile_time_offset(cache_file, ctime, fps); diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index 879313783d9..039a971fe2c 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -289,7 +289,7 @@ static DerivedMesh *cdDM_from_mesh_ex(Mesh *mesh, if (mesh->runtime.cd_dirty_vert & CD_MASK_NORMAL) { dm->dirty |= DM_DIRTY_NORMALS; } - /* TODO DM_DIRTY_TESS_CDLAYERS ? Maybe not though, + /* TODO: DM_DIRTY_TESS_CDLAYERS ? Maybe not though, * since we probably want to switch to looptris? */ CustomData_merge(&mesh->vdata, &dm->vertData, cddata_masks.vmask, alloctype, mesh->totvert); diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c index 09bd397cc78..0fa58a74f2b 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -96,7 +96,7 @@ static BVHTree *bvhtree_build_from_cloth(ClothModifierData *clmd, float epsilon) return NULL; } - /* create quadtree with k=26 */ + /* Create quad-tree with k=26. */ BVHTree *bvhtree = BLI_bvhtree_new(cloth->primitive_num, epsilon, 4, 26); /* fill tree */ @@ -262,17 +262,19 @@ static bool do_init_cloth(Object *ob, ClothModifierData *clmd, Mesh *result, int static int do_step_cloth( Depsgraph *depsgraph, Object *ob, ClothModifierData *clmd, Mesh *result, int framenr) { + /* simulate 1 frame forward */ ClothVertex *verts = NULL; Cloth *cloth; ListBase *effectors = NULL; MVert *mvert; unsigned int i = 0; int ret = 0; + bool vert_mass_changed = false; - /* simulate 1 frame forward */ cloth = clmd->clothObject; verts = cloth->verts; mvert = result->mvert; + vert_mass_changed = verts->mass != clmd->sim_parms->mass; /* force any pinned verts to their constrained location. */ for (i = 0; i < clmd->clothObject->mvert_num; i++, verts++) { @@ -283,6 +285,11 @@ static int do_step_cloth( /* Get the current position. */ copy_v3_v3(verts->xconst, mvert[i].co); mul_m4_v3(ob->obmat, verts->xconst); + + if (vert_mass_changed) { + verts->mass = clmd->sim_parms->mass; + SIM_mass_spring_set_implicit_vertex_mass(cloth->implicit, i, verts->mass); + } } effectors = BKE_effectors_create(depsgraph, ob, NULL, clmd->sim_parms->effector_weights, false); @@ -597,7 +604,7 @@ static void cloth_to_object(Object *ob, ClothModifierData *clmd, float (*vertexC Cloth *cloth = clmd->clothObject; if (clmd->clothObject) { - /* inverse matrix is not uptodate... */ + /* Inverse matrix is not up to date. */ invert_m4_m4(ob->imat, ob->obmat); for (i = 0; i < cloth->mvert_num; i++) { @@ -991,7 +998,7 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) return; } - /* XXX Note: we need to propagate frames from the root up, + /* XXX NOTE: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. * The bending springs however are then inserted in the same * order as vertices again ... @@ -1049,7 +1056,7 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) return; } - /* XXX Note: we need to propagate frames from the root up, + /* XXX NOTE: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. * The bending springs however are then inserted in the same * order as vertices again ... @@ -1883,7 +1890,7 @@ static bool cloth_build_springs(ClothModifierData *clmd, Mesh *mesh) cloth_hair_update_bending_rest_targets(clmd); } - /* note: the edges may already exist so run reinsert */ + /* NOTE: the edges may already exist so run reinsert. */ /* insert other near springs in edgeset AFTER bending springs are calculated (for selfcolls) */ for (int i = 0; i < numedges; i++) { /* struct springs */ diff --git a/source/blender/blenkernel/intern/collection.c b/source/blender/blenkernel/intern/collection.c index 24266dc6bea..c354115e030 100644 --- a/source/blender/blenkernel/intern/collection.c +++ b/source/blender/blenkernel/intern/collection.c @@ -115,7 +115,7 @@ static void collection_copy_data(Main *bmain, ID *id_dst, const ID *id_src, cons ((collection_src->id.flag & LIB_EMBEDDED_DATA) != 0)); /* Do not copy collection's preview (same behavior as for objects). */ - if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */ + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO: temp hack. */ BKE_previewimg_id_copy(&collection_dst->id, &collection_src->id); } else { @@ -191,7 +191,7 @@ static ID *collection_owner_get(Main *bmain, ID *id) } } - BLI_assert(!"Embedded collection with no owner. Critical Main inconsistency."); + BLI_assert_msg(0, "Embedded collection with no owner. Critical Main inconsistency."); return NULL; } @@ -522,7 +522,7 @@ bool BKE_collection_delete(Main *bmain, Collection *collection, bool hierarchy) { /* Master collection is not real datablock, can't be removed. */ if (collection->flag & COLLECTION_IS_MASTER) { - BLI_assert(!"Scene master collection can't be deleted"); + BLI_assert_msg(0, "Scene master collection can't be deleted"); return false; } @@ -888,7 +888,7 @@ Collection *BKE_collection_master_add() { /* Not an actual datablock, but owned by scene. */ Collection *master_collection = BKE_libblock_alloc( - NULL, ID_GR, "Master Collection", LIB_ID_CREATE_NO_MAIN); + NULL, ID_GR, BKE_SCENE_COLLECTION_NAME, LIB_ID_CREATE_NO_MAIN); master_collection->id.flag |= LIB_EMBEDDED_DATA; master_collection->flag |= COLLECTION_IS_MASTER; master_collection->color_tag = COLLECTION_COLOR_NONE; @@ -1706,7 +1706,7 @@ void BKE_main_collections_parent_relations_rebuild(Main *bmain) for (Collection *collection = bmain->collections.first; collection != NULL; collection = collection->id.next) { if (collection->tag & COLLECTION_TAG_RELATION_REBUILD) { - /* Note: we do not have easy access to 'which collections is root' info in that case, which + /* NOTE: we do not have easy access to 'which collections is root' info in that case, which * means test for cycles in collection relationships may fail here. I don't think that is an * issue in practice here, but worth keeping in mind... */ collection_parents_rebuild_recursive(collection); @@ -1896,7 +1896,7 @@ static void layer_collection_flags_restore_recursive(LayerCollection *layer_coll * and now we moved a new collection to be part of the background this collection should * probably be disabled. * - * Note: If we were to also keep the exclude flag we would need to re-sync the collections. + * NOTE: If we were to also keep the exclude flag we would need to re-sync the collections. */ layer_collection->flag = flag->flag | (layer_collection->flag & LAYER_COLLECTION_EXCLUDE); } @@ -2203,8 +2203,8 @@ void BKE_scene_objects_iterator_end(BLI_Iterator *iter) * Generate a new GSet (or extend given `objects_gset` if not NULL) with all objects referenced by * all collections of given `scene`. * - * \note: This will include objects without a base currently (because they would belong to excluded - * collections only e.g.). + * \note This will include objects without a base currently + * (because they would belong to excluded collections only e.g.). */ GSet *BKE_scene_objects_as_gset(Scene *scene, GSet *objects_gset) { diff --git a/source/blender/blenkernel/intern/colorband.c b/source/blender/blenkernel/intern/colorband.c index d6b318caa5e..52a599a0361 100644 --- a/source/blender/blenkernel/intern/colorband.c +++ b/source/blender/blenkernel/intern/colorband.c @@ -295,7 +295,7 @@ void BKE_colorband_init_from_table_rgba(ColorBand *coba, const int array_len, bool filter_samples) { - /* Note, we could use MAXCOLORBAND here, but results of re-sampling are nicer, + /* NOTE: we could use MAXCOLORBAND here, but results of re-sampling are nicer, * avoid different behavior when limit is hit. */ if (array_len < 2) { /* No Re-sample, just de-duplicate. */ @@ -420,7 +420,7 @@ bool BKE_colorband_evaluate(const ColorBand *coba, float in, float out[4]) cbd1 = coba->data; - /* Note: when ipotype >= COLBAND_INTERP_B_SPLINE, + /* NOTE: when ipotype >= COLBAND_INTERP_B_SPLINE, * we cannot do early-out with a constant color before first color stop and after last one, * because interpolation starts before and ends after those... */ ipotype = (coba->color_mode == COLBAND_BLEND_RGB) ? coba->ipotype : COLBAND_INTERP_LINEAR; diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index 1484021cb9d..a9f0f69b855 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -873,7 +873,7 @@ static int sort_curvepoints(const void *a1, const void *a2) /* ************************ more CurveMapping calls *************** */ -/* note; only does current curvemap! */ +/* NOTE: only does current curvemap! */ void BKE_curvemapping_changed(CurveMapping *cumap, const bool rem_doubles) { CurveMap *cuma = cumap->cm + cumap->cur; @@ -1267,9 +1267,9 @@ void BKE_curvemapping_blend_read(BlendDataReader *reader, CurveMapping *cumap) BLI_INLINE int get_bin_float(float f) { - int bin = (int)((f * 255.0f) + 0.5f); /* 0.5 to prevent quantisation differences */ + int bin = (int)((f * 255.0f) + 0.5f); /* 0.5 to prevent quantization differences */ - /* note: clamp integer instead of float to avoid problems with NaN */ + /* NOTE: clamp integer instead of float to avoid problems with NaN. */ CLAMP(bin, 0, 255); return bin; @@ -1497,7 +1497,7 @@ static void scopes_update_cb(void *__restrict userdata, mul_v3_fl(ycc, INV_255); minmax_v3v3_v3(min, max, ycc); } - /* Increment count for histo. */ + /* Increment count for histogram. */ bin_lum[get_bin_float(luma)]++; bin_r[get_bin_float(rgba[0])]++; bin_g[get_bin_float(rgba[1])]++; diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index ca03c9c3de4..47df31e3a2c 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -299,7 +299,10 @@ void BKE_constraint_mat_convertspace(Object *ob, mul_m4_m4m4(mat, imat, mat); /* Use pose-space as stepping stone for other spaces. */ - if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) { + if (ELEM(to, + CONSTRAINT_SPACE_LOCAL, + CONSTRAINT_SPACE_PARLOCAL, + CONSTRAINT_SPACE_OWNLOCAL)) { /* Call self with slightly different values. */ BKE_constraint_mat_convertspace( ob, pchan, cob, mat, CONSTRAINT_SPACE_POSE, to, keep_scale); @@ -315,6 +318,17 @@ void BKE_constraint_mat_convertspace(Object *ob, BKE_armature_mat_pose_to_bone(pchan, mat, mat); } } + /* pose to owner local */ + else if (to == CONSTRAINT_SPACE_OWNLOCAL) { + /* pose to local */ + if (pchan->bone) { + BKE_armature_mat_pose_to_bone(pchan, mat, mat); + } + + /* local to owner local (recursive) */ + BKE_constraint_mat_convertspace( + ob, pchan, cob, mat, CONSTRAINT_SPACE_LOCAL, to, keep_scale); + } /* pose to local with parent */ else if (to == CONSTRAINT_SPACE_PARLOCAL) { if (pchan->bone) { @@ -336,17 +350,59 @@ void BKE_constraint_mat_convertspace(Object *ob, } case CONSTRAINT_SPACE_LOCAL: /* ------------ FROM LOCALSPACE --------- */ { + /* local to owner local */ + if (to == CONSTRAINT_SPACE_OWNLOCAL) { + if (pchan->bone) { + copy_m4_m4(diff_mat, pchan->bone->arm_mat); + + if (cob && cob->pchan && cob->pchan->bone) { + invert_m4_m4(imat, cob->pchan->bone->arm_mat); + mul_m4_m4m4(diff_mat, imat, diff_mat); + } + + zero_v3(diff_mat[3]); + invert_m4_m4(imat, diff_mat); + mul_m4_series(mat, diff_mat, mat, imat); + } + } /* local to pose - do inverse procedure that was done for pose to local */ + else { + if (pchan->bone) { + /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */ + BKE_armature_mat_bone_to_pose(pchan, mat, mat); + } + + /* use pose-space as stepping stone for other spaces */ + if (ELEM(to, + CONSTRAINT_SPACE_WORLD, + CONSTRAINT_SPACE_PARLOCAL, + CONSTRAINT_SPACE_CUSTOM)) { + /* call self with slightly different values */ + BKE_constraint_mat_convertspace( + ob, pchan, cob, mat, CONSTRAINT_SPACE_POSE, to, keep_scale); + } + } + break; + } + case CONSTRAINT_SPACE_OWNLOCAL: { /* -------------- FROM OWNER LOCAL ---------- */ + /* owner local to local */ if (pchan->bone) { - /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */ - BKE_armature_mat_bone_to_pose(pchan, mat, mat); + copy_m4_m4(diff_mat, pchan->bone->arm_mat); + + if (cob && cob->pchan && cob->pchan->bone) { + invert_m4_m4(imat, cob->pchan->bone->arm_mat); + mul_m4_m4m4(diff_mat, imat, diff_mat); + } + + zero_v3(diff_mat[3]); + invert_m4_m4(imat, diff_mat); + mul_m4_series(mat, imat, mat, diff_mat); } - /* use pose-space as stepping stone for other spaces */ - if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL, CONSTRAINT_SPACE_CUSTOM)) { + if (to != CONSTRAINT_SPACE_LOCAL) { /* call self with slightly different values */ BKE_constraint_mat_convertspace( - ob, pchan, cob, mat, CONSTRAINT_SPACE_POSE, to, keep_scale); + ob, pchan, cob, mat, CONSTRAINT_SPACE_LOCAL, to, keep_scale); } break; } @@ -358,7 +414,11 @@ void BKE_constraint_mat_convertspace(Object *ob, } /* use pose-space as stepping stone for other spaces */ - if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_CUSTOM)) { + if (ELEM(to, + CONSTRAINT_SPACE_WORLD, + CONSTRAINT_SPACE_LOCAL, + CONSTRAINT_SPACE_OWNLOCAL, + CONSTRAINT_SPACE_CUSTOM)) { /* call self with slightly different values */ BKE_constraint_mat_convertspace( ob, pchan, cob, mat, CONSTRAINT_SPACE_POSE, to, keep_scale); @@ -470,7 +530,7 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ /* when not in EditMode, use the 'final' evaluated mesh, depsgraph * ensures we build with CD_MDEFORMVERT layer */ - Mesh *me_eval = BKE_object_get_evaluated_mesh(ob); + const Mesh *me_eval = BKE_object_get_evaluated_mesh(ob); BMEditMesh *em = BKE_editmesh_from_object(ob); float plane[3]; float imat[3][3], tmat[3][3]; @@ -488,17 +548,17 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ float normal[3] = {0.0f, 0.0f, 0.0f}; float weightsum = 0.0f; if (me_eval) { - MDeformVert *dvert = CustomData_get_layer(&me_eval->vdata, CD_MDEFORMVERT); + const MDeformVert *dvert = CustomData_get_layer(&me_eval->vdata, CD_MDEFORMVERT); int numVerts = me_eval->totvert; /* check that dvert is a valid pointers (just in case) */ if (dvert) { - MDeformVert *dv = dvert; - MVert *mv = me_eval->mvert; /* get the average of all verts with that are in the vertex-group */ - for (int i = 0; i < numVerts; i++, dv++, mv++) { - MDeformWeight *dw = BKE_defvert_find_index(dv, defgroup); + for (int i = 0; i < numVerts; i++) { + const MDeformVert *dv = &dvert[i]; + const MVert *mv = &me_eval->mvert[i]; + const MDeformWeight *dw = BKE_defvert_find_index(dv, defgroup); if (dw && dw->weight > 0.0f) { float nor[3]; @@ -867,7 +927,7 @@ static void default_get_tarmat_full_bbone(struct Depsgraph *UNUSED(depsgraph), /* This following macro should be used for all standard single-target *_flush_tars functions * to save typing and reduce maintenance woes. - * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed) + * NOTE: the pointer to ct will be changed to point to the next in the list (as it gets removed) * (Hopefully all compilers will be happy with the lines with just a space on them. Those are * really just to help this code easier to read) */ @@ -889,7 +949,7 @@ static void default_get_tarmat_full_bbone(struct Depsgraph *UNUSED(depsgraph), /* This following macro should be used for all standard single-target *_flush_tars functions * to save typing and reduce maintenance woes. It does not do the subtarget related operations. - * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed) + * NOTE: the pointer to ct will be changed to point to the next in the list (as it gets removed) * (Hopefully all compilers will be happy with the lines with just a space on them. Those are * really just to help this code easier to read) */ @@ -1088,7 +1148,7 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar } } -/* XXX note, con->flag should be CONSTRAINT_SPACEONCE for bone-childof, patched in readfile.c */ +/* XXX NOTE: con->flag should be CONSTRAINT_SPACEONCE for bone-childof, patched in `readfile.c`. */ static bConstraintTypeInfo CTI_CHILDOF = { CONSTRAINT_TYPE_CHILDOF, /* type */ sizeof(bChildOfConstraint), /* size */ @@ -1205,7 +1265,7 @@ static void vectomat(const float vec[3], u[2] = 1; } - /* note: even though 'n' is normalized, don't use 'project_v3_v3v3_normalized' below + /* NOTE: even though 'n' is normalized, don't use 'project_v3_v3v3_normalized' below * because precision issues cause a problem in near degenerate states, see: T53455. */ /* project the up vector onto the plane specified by n */ @@ -1459,7 +1519,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), unit_m4(ct->matrix); - /* note: when creating constraints that follow path, the curve gets the CU_PATH set now, + /* NOTE: when creating constraints that follow path, the curve gets the CU_PATH set now, * currently for paths to work it needs to go through the bevlist/displist system (ton) */ @@ -1543,8 +1603,8 @@ static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase * /* un-apply scaling caused by path */ if ((data->followflag & FOLLOWPATH_RADIUS) == 0) { - /* XXX: Assume that scale correction means that radius - * will have some scale error in it - Campbell. */ + /* XXX(campbell): Assume that scale correction means that radius + * will have some scale error in it. */ float obsize[3]; mat4_to_size(obsize, cob->matrix); @@ -2235,21 +2295,51 @@ static void translike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t bConstraintTarget *ct = targets->first; if (VALID_CONS_TARGET(ct)) { + float target_mat[4][4]; + + copy_m4_m4(target_mat, ct->matrix); + + /* Remove the shear of the target matrix if enabled. + * Use Y as the axis since it's the natural default for bones. */ + if (data->flag & TRANSLIKE_REMOVE_TARGET_SHEAR) { + orthogonalize_m4_stable(target_mat, 1, false); + } + + /* Finally, combine the matrices. */ switch (data->mix_mode) { case TRANSLIKE_MIX_REPLACE: - copy_m4_m4(cob->matrix, ct->matrix); + copy_m4_m4(cob->matrix, target_mat); break; + /* Simple matrix multiplication. */ + case TRANSLIKE_MIX_BEFORE_FULL: + mul_m4_m4m4(cob->matrix, target_mat, cob->matrix); + break; + + case TRANSLIKE_MIX_AFTER_FULL: + mul_m4_m4m4(cob->matrix, cob->matrix, target_mat); + break; + + /* Aligned Inherit Scale emulation. */ case TRANSLIKE_MIX_BEFORE: - mul_m4_m4m4_aligned_scale(cob->matrix, ct->matrix, cob->matrix); + mul_m4_m4m4_aligned_scale(cob->matrix, target_mat, cob->matrix); break; case TRANSLIKE_MIX_AFTER: - mul_m4_m4m4_aligned_scale(cob->matrix, cob->matrix, ct->matrix); + mul_m4_m4m4_aligned_scale(cob->matrix, cob->matrix, target_mat); + break; + + /* Fully separate handling of channels. */ + case TRANSLIKE_MIX_BEFORE_SPLIT: + mul_m4_m4m4_split_channels(cob->matrix, target_mat, cob->matrix); + break; + + case TRANSLIKE_MIX_AFTER_SPLIT: + mul_m4_m4m4_split_channels(cob->matrix, cob->matrix, target_mat); break; default: - BLI_assert(!"Unknown Copy Transforms mix mode"); + BLI_assert_msg(0, "Unknown Copy Transforms mix mode"); } } } @@ -2901,7 +2991,7 @@ static void actcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ break; default: - BLI_assert(!"Unknown Action mix mode"); + BLI_assert_msg(0, "Unknown Action mix mode"); } } } @@ -3791,7 +3881,7 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar unit_m4(targetMatrix); INIT_MINMAX(curveMin, curveMax); - /* XXX - don't think this is good calling this here - campbell */ + /* XXX(campbell): don't think this is good calling this here. */ BKE_object_minmax(ct->tar, curveMin, curveMax, true); /* get targetmatrix */ @@ -4242,7 +4332,7 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), float mat[4][4]; float no[3] = {0.0f, 0.0f, 0.0f}; - /* TODO should use FLT_MAX.. but normal projection doenst yet supports it */ + /* TODO: should use FLT_MAX.. but normal projection doesn't yet supports it. */ hit.index = -1; hit.dist = (scon->projLimit == 0.0f) ? BVH_RAYCAST_DIST_MAX : scon->projLimit; @@ -5009,7 +5099,7 @@ static void followtrack_project_to_depth_object_if_needed(FollowTrackContext *co } Object *depth_object = context->depth_object; - Mesh *depth_mesh = BKE_object_get_evaluated_mesh(depth_object); + const Mesh *depth_mesh = BKE_object_get_evaluated_mesh(depth_object); if (depth_mesh == NULL) { return; } @@ -6269,7 +6359,7 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, * (T26014 and T25725), since some constraints may not convert the solution back to the input * space before blending but all are guaranteed to end up in good "world-space" result. */ - /* Note: all kind of stuff here before (caused trouble), much easier to just interpolate, + /* NOTE: all kind of stuff here before (caused trouble), much easier to just interpolate, * or did I miss something? -jahka (r.32105) */ if (enf < 1.0f) { float solution[4][4]; diff --git a/source/blender/blenkernel/intern/context.c b/source/blender/blenkernel/intern/context.c index 1028790856c..dced945bea0 100644 --- a/source/blender/blenkernel/intern/context.c +++ b/source/blender/blenkernel/intern/context.c @@ -1448,6 +1448,36 @@ int CTX_data_editable_gpencil_strokes(const bContext *C, ListBase *list) return ctx_data_collection_get(C, "editable_gpencil_strokes", list); } +const AssetLibraryReference *CTX_wm_asset_library(const bContext *C) +{ + return ctx_data_pointer_get(C, "asset_library"); +} + +AssetHandle CTX_wm_asset_handle(const bContext *C, bool *r_is_valid) +{ + AssetHandle *asset_handle_p = + (AssetHandle *)CTX_data_pointer_get_type(C, "asset_handle", &RNA_AssetHandle).data; + if (asset_handle_p) { + *r_is_valid = true; + return *asset_handle_p; + } + + /* If the asset handle was not found in context directly, try if there's an active file with + * asset data there instead. Not nice to have this here, would be better to have this in + * `ED_asset.h`, but we can't include that in BKE. Even better would be not needing this at all + * and being able to have editors return this in the usual `context` callback. But that would + * require returning a non-owning pointer, which we don't have in the Asset Browser (yet). */ + FileDirEntry *file = + (FileDirEntry *)CTX_data_pointer_get_type(C, "active_file", &RNA_FileSelectEntry).data; + if (file && file->asset_data) { + *r_is_valid = true; + return (AssetHandle){.file_data = file}; + } + + *r_is_valid = false; + return (AssetHandle){0}; +} + Depsgraph *CTX_data_depsgraph_pointer(const bContext *C) { Main *bmain = CTX_data_main(C); diff --git a/source/blender/blenkernel/intern/crazyspace.c b/source/blender/blenkernel/intern/crazyspace.c index 4e1ec9ba35e..26894495777 100644 --- a/source/blender/blenkernel/intern/crazyspace.c +++ b/source/blender/blenkernel/intern/crazyspace.c @@ -398,8 +398,7 @@ int BKE_sculpt_get_first_deform_matrices(struct Depsgraph *depsgraph, if (crazyspace_modifier_supports_deform_matrices(md)) { const ModifierTypeInfo *mti = BKE_modifier_get_info(md->type); if (defmats == NULL) { - /* NOTE: Evaluated object si re-set to its original undeformed - * state. */ + /* NOTE: Evaluated object is re-set to its original un-deformed state. */ Mesh *me = object_eval.data; me_eval = BKE_mesh_copy_for_eval(me, true); crazyspace_init_verts_and_matrices(me_eval, &defmats, &deformedVerts); diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c index a5538453248..24615dd8c2b 100644 --- a/source/blender/blenkernel/intern/curve.c +++ b/source/blender/blenkernel/intern/curve.c @@ -2123,8 +2123,8 @@ static void tilt_bezpart(const BezTriple *prevbezt, if (radius_array) { if (nu->radius_interp == KEY_CU_EASE) { /* Support 2.47 ease interp - * Note! - this only takes the 2 points into account, - * giving much more localized results to changes in radius, sometimes you want that */ + * NOTE: this only takes the 2 points into account, + * giving much more localized results to changes in radius, sometimes you want that. */ *radius_array = prevbezt->radius + (bezt->radius - prevbezt->radius) * (3.0f * fac * fac - 2.0f * fac * fac * fac); } @@ -2490,7 +2490,7 @@ static void make_bevel_list_3D_tangent(BevList *bl) cross_v3_v3v3(cross_tmp, bevp1->tan, bevp1->dir); normalize_v3(cross_tmp); - tri_to_quat(bevp1->quat, zero, cross_tmp, bevp1->tan); /* XXX - could be faster */ + tri_to_quat(bevp1->quat, zero, cross_tmp, bevp1->tan); /* XXX: could be faster. */ /* bevp0 = bevp1; */ /* UNUSED */ bevp1 = bevp2; @@ -2559,8 +2559,8 @@ static void make_bevel_list_segment_2D(BevList *bl) static void make_bevel_list_2D(BevList *bl) { - /* note: bevp->dir and bevp->quat are not needed for beveling but are - * used when making a path from a 2D curve, therefore they need to be set - Campbell */ + /* NOTE(campbell): `bevp->dir` and `bevp->quat` are not needed for beveling but are + * used when making a path from a 2D curve, therefore they need to be set. */ BevPoint *bevp0, *bevp1, *bevp2; int nr; @@ -3658,7 +3658,7 @@ static bool tridiagonal_solve_with_limits(float *a, * is affected by all other points of the curve segment, in practice the influence * decreases exponentially with distance. * - * Note: this algorithm assumes that the handle horizontal size is always 1/3 of the + * NOTE: this algorithm assumes that the handle horizontal size is always 1/3 of the * of the interval to the next point. This rule ensures linear interpolation of time. * * ^ height (co 1) diff --git a/source/blender/blenkernel/intern/curve_deform.c b/source/blender/blenkernel/intern/curve_deform.c index 7deac4e4f19..28b7c2dfba0 100644 --- a/source/blender/blenkernel/intern/curve_deform.c +++ b/source/blender/blenkernel/intern/curve_deform.c @@ -168,7 +168,7 @@ static bool calc_curve_deform( * * Now for Neg Up XYZ, the colors are all dark, and ordered clockwise - Campbell * - * note: moved functions into quat_apply_track/vec_apply_track + * NOTE: moved functions into quat_apply_track/vec_apply_track */ copy_qt_qt(quat, new_quat); copy_v3_v3(cent, co); diff --git a/source/blender/blenkernel/intern/curve_eval.cc b/source/blender/blenkernel/intern/curve_eval.cc index 72ee2587c8a..8e1577ab072 100644 --- a/source/blender/blenkernel/intern/curve_eval.cc +++ b/source/blender/blenkernel/intern/curve_eval.cc @@ -335,4 +335,4 @@ void CurveEval::assert_valid_point_attributes() const ATTR_DOMAIN_POINT); } #endif -}
\ No newline at end of file +} diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c index 08d0af45e92..7aa9d1958eb 100644 --- a/source/blender/blenkernel/intern/customdata.c +++ b/source/blender/blenkernel/intern/customdata.c @@ -105,8 +105,10 @@ typedef struct LayerTypeInfo { /** * default layer name. - * note! when NULL this is a way to ensure there is only ever one item - * see: CustomData_layertype_is_singleton() */ + * + * \note when NULL this is a way to ensure there is only ever one item + * see: CustomData_layertype_is_singleton(). + */ const char *defaultname; /** @@ -329,7 +331,7 @@ static void layerInterp_normal(const void **sources, int count, void *dest) { - /* Note: This is linear interpolation, which is not optimal for vectors. + /* NOTE: This is linear interpolation, which is not optimal for vectors. * Unfortunately, spherical interpolation of more than two values is hairy, * so for now it will do... */ float no[3] = {0.0f}; @@ -1594,7 +1596,7 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { /* 14: CD_ORCO */ {sizeof(float[3]), "", 0, NULL, NULL, NULL, NULL, NULL, NULL}, /* 15: CD_MTEXPOLY */ /* DEPRECATED */ - /* note, when we expose the UV Map / TexFace split to the user, + /* NOTE: when we expose the UV Map / TexFace split to the user, * change this back to face Texture. */ {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL}, /* 16: CD_MLOOPUV */ @@ -3555,7 +3557,7 @@ bool CustomData_bmesh_merge(const CustomData *source, totelem = bm->totface; break; default: /* should never happen */ - BLI_assert(!"invalid type given"); + BLI_assert_msg(0, "invalid type given"); iter_type = BM_VERTS_OF_MESH; totelem = bm->totvert; break; @@ -3805,7 +3807,7 @@ void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int return POINTER_OFFSET(block, data->layers[layer_index + n].offset); } -/* Gets from the layer at physical index n, note: doesn't check type. */ +/* Gets from the layer at physical index n, NOTE: doesn't check type. */ void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n) { if (n < 0 || n >= data->totlayer) { @@ -4974,7 +4976,7 @@ void CustomData_data_transfer(const MeshPairRemap *me_remap, size_t tmp_buff_size = 32; const void **tmp_data_src = NULL; - /* Note: NULL data_src may happen and be valid (see vgroups...). */ + /* NOTE: NULL data_src may happen and be valid (see vgroups...). */ if (!data_dst) { return; } @@ -4991,7 +4993,7 @@ void CustomData_data_transfer(const MeshPairRemap *me_remap, else { const LayerTypeInfo *type_info = layerType_getInfo(data_type); - /* Note: we can use 'fake' CDLayers, like e.g. for crease, bweight, etc. :/ */ + /* NOTE: we can use 'fake' CDLayers, like e.g. for crease, bweight, etc. :/. */ data_size = (size_t)type_info->size; data_step = laymap->elem_size ? laymap->elem_size : data_size; data_offset = laymap->data_offset; diff --git a/source/blender/blenkernel/intern/customdata_file.c b/source/blender/blenkernel/intern/customdata_file.c index 314d5f4ff82..ef86a65f47d 100644 --- a/source/blender/blenkernel/intern/customdata_file.c +++ b/source/blender/blenkernel/intern/customdata_file.c @@ -361,9 +361,9 @@ bool cdf_write_open(CDataFile *cdf, const char *filename) cdf->writef = f; - /* fill header */ + /* Fill header. */ header = &cdf->header; - /* strcpy(, "BCDF"); // terminator out of range */ + /* Copy "BCDF" (string terminator out of range). */ header->ID[0] = 'B'; header->ID[1] = 'C'; header->ID[2] = 'D'; diff --git a/source/blender/blenkernel/intern/data_transfer.c b/source/blender/blenkernel/intern/data_transfer.c index 12269cf0d51..605061570b8 100644 --- a/source/blender/blenkernel/intern/data_transfer.c +++ b/source/blender/blenkernel/intern/data_transfer.c @@ -691,7 +691,7 @@ static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map } if (data_dst_to_delete) { - /* Note: + /* NOTE: * This won't affect newly created layers, if any, since tot_dst has not been updated! * Also, looping backward ensures us we do not suffer * from index shifting when deleting a layer. */ @@ -764,7 +764,7 @@ static bool data_transfer_layersmapping_cdlayers(ListBase *r_map, } } else if (fromlayers == DT_LAYERS_ACTIVE_SRC || fromlayers >= 0) { - /* Note: use_delete has not much meaning in this case, ignored. */ + /* NOTE: use_delete has not much meaning in this case, ignored. */ if (fromlayers >= 0) { /* Real-layer index */ idx_src = fromlayers; @@ -1437,7 +1437,7 @@ bool BKE_object_data_transfer_ex(struct Depsgraph *depsgraph, if (vgroup_name) { mdef = CustomData_get_layer(&me_dst->vdata, CD_MDEFORMVERT); if (mdef) { - vg_idx = BKE_object_defgroup_name_index(ob_dst, vgroup_name); + vg_idx = BKE_id_defgroup_name_index(&me_dst->id, vgroup_name); } } diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c index e6ef569d4b9..f7ef84728b6 100644 --- a/source/blender/blenkernel/intern/deform.c +++ b/source/blender/blenkernel/intern/deform.c @@ -29,6 +29,8 @@ #include "MEM_guardedalloc.h" +#include "DNA_gpencil_types.h" +#include "DNA_lattice_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_object_types.h" @@ -64,7 +66,9 @@ bDeformGroup *BKE_object_defgroup_new(Object *ob, const char *name) BLI_strncpy(defgroup->name, name, sizeof(defgroup->name)); - BLI_addtail(&ob->defbase, defgroup); + ListBase *defbase = BKE_object_defgroup_list_mutable(ob); + + BLI_addtail(defbase, defgroup); BKE_object_defgroup_unique_name(defgroup, ob); BKE_object_batch_cache_dirty_tag(ob); @@ -484,18 +488,120 @@ void BKE_defvert_flip_merged(MDeformVert *dvert, const int *flip_map, const int } } +bool BKE_object_supports_vertex_groups(const Object *ob) +{ + const ID *id = (const ID *)ob->data; + if (id == NULL) { + return false; + } + + return ELEM(GS(id->name), ID_ME, ID_LT, ID_GD); +} + +const ListBase *BKE_id_defgroup_list_get(const ID *id) +{ + switch (GS(id->name)) { + case ID_ME: { + const Mesh *me = (const Mesh *)id; + return &me->vertex_group_names; + } + case ID_LT: { + const Lattice *lt = (const Lattice *)id; + return <->vertex_group_names; + } + case ID_GD: { + const bGPdata *gpd = (const bGPdata *)id; + return &gpd->vertex_group_names; + } + default: { + BLI_assert_unreachable(); + } + } + return NULL; +} + +static const int *object_defgroup_active_index_get_p(const Object *ob) +{ + BLI_assert(BKE_object_supports_vertex_groups(ob)); + switch (ob->type) { + case OB_MESH: { + const Mesh *mesh = (const Mesh *)ob->data; + return &mesh->vertex_group_active_index; + } + case OB_LATTICE: { + const Lattice *lattice = (const Lattice *)ob->data; + return &lattice->vertex_group_active_index; + } + case OB_GPENCIL: { + const bGPdata *gpd = (const bGPdata *)ob->data; + return &gpd->vertex_group_active_index; + } + } + return NULL; +} + +ListBase *BKE_id_defgroup_list_get_mutable(ID *id) +{ + /* Cast away const just for the accessor. */ + return (ListBase *)BKE_id_defgroup_list_get(id); +} + bDeformGroup *BKE_object_defgroup_find_name(const Object *ob, const char *name) { - return (name && name[0] != '\0') ? - BLI_findstring(&ob->defbase, name, offsetof(bDeformGroup, name)) : - NULL; + if (name == NULL || name[0] == '\0') { + return NULL; + } + const ListBase *defbase = BKE_object_defgroup_list(ob); + return BLI_findstring(defbase, name, offsetof(bDeformGroup, name)); +} + +int BKE_id_defgroup_name_index(const ID *id, const char *name) +{ + if (name == NULL || name[0] == '\0') { + return -1; + } + const ListBase *defbase = BKE_id_defgroup_list_get(id); + return BLI_findstringindex(defbase, name, offsetof(bDeformGroup, name)); +} + +const ListBase *BKE_object_defgroup_list(const Object *ob) +{ + BLI_assert(BKE_object_supports_vertex_groups(ob)); + return BKE_id_defgroup_list_get((const ID *)ob->data); } int BKE_object_defgroup_name_index(const Object *ob, const char *name) { - return (name && name[0] != '\0') ? - BLI_findstringindex(&ob->defbase, name, offsetof(bDeformGroup, name)) : - -1; + return BKE_id_defgroup_name_index((ID *)ob->data, name); +} + +ListBase *BKE_object_defgroup_list_mutable(Object *ob) +{ + BLI_assert(BKE_object_supports_vertex_groups(ob)); + return BKE_id_defgroup_list_get_mutable((ID *)ob->data); +} + +int BKE_object_defgroup_count(const Object *ob) +{ + return BLI_listbase_count(BKE_object_defgroup_list(ob)); +} + +/** + * \note For historical reasons, the index starts at 1 rather than 0. + */ +int BKE_object_defgroup_active_index_get(const Object *ob) +{ + return *object_defgroup_active_index_get_p(ob); +} + +/** + * \note For historical reasons, the index starts at 1 rather than 0. + */ +void BKE_object_defgroup_active_index_set(Object *ob, const int new_index) +{ + /* Cast away const just for the accessor. */ + int *index = (int *)object_defgroup_active_index_get_p(ob); + *index = new_index; } /** @@ -503,7 +609,8 @@ int BKE_object_defgroup_name_index(const Object *ob, const char *name) */ int *BKE_object_defgroup_flip_map(const Object *ob, int *flip_map_len, const bool use_default) { - int defbase_tot = *flip_map_len = BLI_listbase_count(&ob->defbase); + const ListBase *defbase = BKE_object_defgroup_list(ob); + int defbase_tot = *flip_map_len = BLI_listbase_count(defbase); if (defbase_tot == 0) { return NULL; @@ -517,7 +624,7 @@ int *BKE_object_defgroup_flip_map(const Object *ob, int *flip_map_len, const boo map[i] = -1; } - for (dg = ob->defbase.first, i = 0; dg; dg = dg->next, i++) { + for (dg = defbase->first, i = 0; dg; dg = dg->next, i++) { if (map[i] == -1) { /* may be calculated previously */ /* in case no valid value is found, use this */ @@ -547,7 +654,8 @@ int *BKE_object_defgroup_flip_map_single(const Object *ob, const bool use_default, int defgroup) { - int defbase_tot = *flip_map_len = BLI_listbase_count(&ob->defbase); + const ListBase *defbase = BKE_object_defgroup_list(ob); + int defbase_tot = *flip_map_len = BLI_listbase_count(defbase); if (defbase_tot == 0) { return NULL; @@ -561,7 +669,7 @@ int *BKE_object_defgroup_flip_map_single(const Object *ob, map[i] = use_default ? i : -1; } - dg = BLI_findlink(&ob->defbase, defgroup); + dg = BLI_findlink(defbase, defgroup); BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip)); if (!STREQ(name_flip, dg->name)) { @@ -578,7 +686,8 @@ int *BKE_object_defgroup_flip_map_single(const Object *ob, int BKE_object_defgroup_flip_index(const Object *ob, int index, const bool use_default) { - bDeformGroup *dg = BLI_findlink(&ob->defbase, index); + const ListBase *defbase = BKE_object_defgroup_list(ob); + bDeformGroup *dg = BLI_findlink(defbase, index); int flip_index = -1; if (dg) { @@ -595,9 +704,10 @@ int BKE_object_defgroup_flip_index(const Object *ob, int index, const bool use_d static bool defgroup_find_name_dupe(const char *name, bDeformGroup *dg, Object *ob) { + const ListBase *defbase = BKE_object_defgroup_list(ob); bDeformGroup *curdef; - for (curdef = ob->defbase.first; curdef; curdef = curdef->next) { + for (curdef = defbase->first; curdef; curdef = curdef->next) { if (dg != curdef) { if (STREQ(curdef->name, name)) { return true; @@ -716,7 +826,7 @@ MDeformWeight *BKE_defvert_ensure_index(MDeformVert *dvert, const int defgroup) return dw_new; } -/* TODO. merge with code above! */ +/* TODO: merge with code above! */ /** * Adds the given vertex to the specified vertex group, with given weight. @@ -1189,7 +1299,10 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, { int idx_src; int idx_dst; - int tot_dst = BLI_listbase_count(&ob_dst->defbase); + const ListBase *src_list = BKE_object_defgroup_list(ob_src); + ListBase *dst_defbase = BKE_object_defgroup_list_mutable(ob_dst); + + int tot_dst = BLI_listbase_count(dst_defbase); const size_t elem_size = sizeof(*((MDeformVert *)NULL)); @@ -1218,7 +1331,7 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, } else if (use_delete && idx_dst > idx_src) { while (idx_dst-- > idx_src) { - BKE_object_defgroup_remove(ob_dst, ob_dst->defbase.last); + BKE_object_defgroup_remove(ob_dst, dst_defbase->last); } } if (r_map) { @@ -1255,7 +1368,7 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, if (use_delete) { /* Remove all unused dst vgroups first, simpler in this case. */ - for (dg_dst = ob_dst->defbase.first; dg_dst;) { + for (dg_dst = dst_defbase->first; dg_dst;) { bDeformGroup *dg_dst_next = dg_dst->next; if (BKE_object_defgroup_name_index(ob_src, dg_dst->name) == -1) { @@ -1265,7 +1378,7 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, } } - for (idx_src = 0, dg_src = ob_src->defbase.first; idx_src < num_layers_src; + for (idx_src = 0, dg_src = src_list->first; idx_src < num_layers_src; idx_src++, dg_src = dg_src->next) { if (!use_layers_src[idx_src]) { continue; @@ -1274,7 +1387,7 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, if ((idx_dst = BKE_object_defgroup_name_index(ob_dst, dg_src->name)) == -1) { if (use_create) { BKE_object_defgroup_add_name(ob_dst, dg_src->name); - idx_dst = ob_dst->actdef - 1; + idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1; } else { /* If we are not allowed to create missing dst vgroups, just skip matching src one. */ @@ -1334,14 +1447,18 @@ bool data_transfer_layersmapping_vgroups(ListBase *r_map, const size_t elem_size = sizeof(*((MDeformVert *)NULL)); - /* Note: + /* NOTE: * VGroups are a bit hairy, since their layout is defined on object level (ob->defbase), * while their actual data is a (mesh) CD layer. * This implies we may have to handle data layout itself while having NULL data itself, * and even have to support NULL data_src in transfer data code * (we always create a data_dst, though). + * + * Note: Above comment is outdated, but this function was written when that was true. */ - if (BLI_listbase_is_empty(&ob_src->defbase)) { + + const ListBase *src_defbase = BKE_object_defgroup_list(ob_src); + if (BLI_listbase_is_empty(src_defbase)) { if (use_delete) { BKE_object_defgroup_remove_all(ob_dst); } @@ -1357,39 +1474,41 @@ bool data_transfer_layersmapping_vgroups(ListBase *r_map, } if (fromlayers == DT_LAYERS_ACTIVE_SRC || fromlayers >= 0) { - /* Note: use_delete has not much meaning in this case, ignored. */ + /* NOTE: use_delete has not much meaning in this case, ignored. */ if (fromlayers >= 0) { idx_src = fromlayers; - if (idx_src >= BLI_listbase_count(&ob_src->defbase)) { + if (idx_src >= BLI_listbase_count(src_defbase)) { /* This can happen when vgroups are removed from source object... * Remapping would be really tricky here, we'd need to go over all objects in * Main every time we delete a vgroup... for now, simpler and safer to abort. */ return false; } } - else if ((idx_src = ob_src->actdef - 1) == -1) { + else if ((idx_src = BKE_object_defgroup_active_index_get(ob_src) - 1) == -1) { return false; } if (tolayers >= 0) { - /* Note: in this case we assume layer exists! */ + /* NOTE: in this case we assume layer exists! */ idx_dst = tolayers; - BLI_assert(idx_dst < BLI_listbase_count(&ob_dst->defbase)); + const ListBase *dst_defbase = BKE_object_defgroup_list(ob_dst); + BLI_assert(idx_dst < BLI_listbase_count(dst_defbase)); + UNUSED_VARS_NDEBUG(dst_defbase); } else if (tolayers == DT_LAYERS_ACTIVE_DST) { - if ((idx_dst = ob_dst->actdef - 1) == -1) { + if ((idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1) == -1) { bDeformGroup *dg_src; if (!use_create) { return true; } - dg_src = BLI_findlink(&ob_src->defbase, idx_src); + dg_src = BLI_findlink(src_defbase, idx_src); BKE_object_defgroup_add_name(ob_dst, dg_src->name); - idx_dst = ob_dst->actdef - 1; + idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1; } } else if (tolayers == DT_LAYERS_INDEX_DST) { - int num = BLI_listbase_count(&ob_src->defbase); + int num = BLI_listbase_count(src_defbase); idx_dst = idx_src; if (num <= idx_dst) { if (!use_create) { @@ -1402,13 +1521,13 @@ bool data_transfer_layersmapping_vgroups(ListBase *r_map, } } else if (tolayers == DT_LAYERS_NAME_DST) { - bDeformGroup *dg_src = BLI_findlink(&ob_src->defbase, idx_src); + bDeformGroup *dg_src = BLI_findlink(src_defbase, idx_src); if ((idx_dst = BKE_object_defgroup_name_index(ob_dst, dg_src->name)) == -1) { if (!use_create) { return true; } BKE_object_defgroup_add_name(ob_dst, dg_src->name); - idx_dst = ob_dst->actdef - 1; + idx_dst = BKE_object_defgroup_active_index_get(ob_dst) - 1; } } else { @@ -1531,6 +1650,13 @@ void BKE_defvert_weight_to_rgb(float r_rgb[3], const float weight) /** \name .blend file I/O * \{ */ +void BKE_defbase_blend_write(BlendWriter *writer, const ListBase *defbase) +{ + LISTBASE_FOREACH (bDeformGroup *, defgroup, defbase) { + BLO_write_struct(writer, bDeformGroup, defgroup); + } +} + void BKE_defvert_blend_write(BlendWriter *writer, int count, MDeformVert *dvlist) { if (dvlist == NULL) { diff --git a/source/blender/blenkernel/intern/displist.cc b/source/blender/blenkernel/intern/displist.cc index cfe4701fb69..a4ffaa8b10b 100644 --- a/source/blender/blenkernel/intern/displist.cc +++ b/source/blender/blenkernel/intern/displist.cc @@ -1694,7 +1694,7 @@ static void boundbox_displist_object(Object *ob) ob->runtime.bb = (BoundBox *)MEM_callocN(sizeof(BoundBox), __func__); } - Mesh *mesh_eval = BKE_object_get_evaluated_mesh(ob); + const Mesh *mesh_eval = BKE_object_get_evaluated_mesh(ob); if (mesh_eval) { BKE_object_boundbox_calc_from_mesh(ob, mesh_eval); } diff --git a/source/blender/blenkernel/intern/displist_tangent.c b/source/blender/blenkernel/intern/displist_tangent.c index 88fef1a4cfd..5c969d52aea 100644 --- a/source/blender/blenkernel/intern/displist_tangent.c +++ b/source/blender/blenkernel/intern/displist_tangent.c @@ -171,7 +171,7 @@ static void dlsurf_ts_GetTextureCoordinate(const SMikkTSpaceContext *pContext, int idx = face_to_vert_index(dlt, face_num, vert_index); - /* Note: For some reason the shading U and V are swapped compared to the + /* NOTE: For some reason the shading U and V are swapped compared to the * one described in the surface format. */ r_uv[0] = (idx / dlt->dl->nr) / (float)(dlt->v_len); r_uv[1] = (idx % dlt->dl->nr) / (float)(dlt->u_len); diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c index 2eb18a06799..52996e3bcc7 100644 --- a/source/blender/blenkernel/intern/dynamicpaint.c +++ b/source/blender/blenkernel/intern/dynamicpaint.c @@ -248,7 +248,7 @@ typedef struct PaintAdjData { int *n_target; /** Index to start reading n_target for each point. */ int *n_index; - /** Num of neighs for each point. */ + /** Number of neighbors for each point. */ int *n_num; /** Vertex adjacency flags. */ int *flags; @@ -2288,7 +2288,8 @@ static void dynamic_paint_create_uv_surface_direct_cb( /* Loop through samples, starting from middle point */ for (int sample = 0; sample < 5; sample++) { /* Loop through every face in the mesh */ - /* XXX TODO This is *horrible* with big meshes, should use a 2D BVHTree over UV tris here! */ + /* XXX TODO: This is *horrible* with big meshes, should use a 2D BVHTree over UV tris here! + */ for (int i = 0; i < tottri; i++) { /* Check uv bb */ if ((faceBB[i].min[0] > point[sample][0]) || (faceBB[i].min[1] > point[sample][1]) || @@ -2476,7 +2477,7 @@ static int dynamic_paint_find_neighbor_pixel(const DynamicPaintCreateUVSurfaceDa const int py, const int n_index) { - /* Note: Current method only uses polygon edges to detect neighboring pixels. + /* NOTE: Current method only uses polygon edges to detect neighboring pixels. * -> It doesn't always lead to the optimum pixel but is accurate enough * and faster/simpler than including possible face tip point links) */ @@ -3817,7 +3818,7 @@ static void dynamicPaint_brushMeshCalculateVelocity(Depsgraph *depsgraph, ob, true, SUBFRAME_RECURSION, - BKE_scene_frame_get(scene), + BKE_scene_ctime_get(scene), eModifierType_DynamicPaint); mesh_p = BKE_mesh_copy_for_eval(dynamicPaint_brush_mesh_get(brush), false); numOfVerts_p = mesh_p->totvert; @@ -3833,7 +3834,7 @@ static void dynamicPaint_brushMeshCalculateVelocity(Depsgraph *depsgraph, ob, true, SUBFRAME_RECURSION, - BKE_scene_frame_get(scene), + BKE_scene_ctime_get(scene), eModifierType_DynamicPaint); mesh_c = dynamicPaint_brush_mesh_get(brush); numOfVerts_c = mesh_c->totvert; @@ -3893,7 +3894,7 @@ static void dynamicPaint_brushObjectCalculateVelocity( ob, false, SUBFRAME_RECURSION, - BKE_scene_frame_get(scene), + BKE_scene_ctime_get(scene), eModifierType_DynamicPaint); copy_m4_m4(prev_obmat, ob->obmat); @@ -3905,7 +3906,7 @@ static void dynamicPaint_brushObjectCalculateVelocity( ob, false, SUBFRAME_RECURSION, - BKE_scene_frame_get(scene), + BKE_scene_ctime_get(scene), eModifierType_DynamicPaint); /* calculate speed */ @@ -4190,8 +4191,8 @@ static void dynamic_paint_paint_mesh_cell_point_cb_ex( /* calculate barycentric weights for hit point */ interp_weights_tri_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, hitCoord); - /* simple check based on brush surface velocity, - * todo: perhaps implement something that handles volume movement as well. */ + /* Simple check based on brush surface velocity, + * TODO: perhaps implement something that handles volume movement as well. */ /* interpolate vertex speed vectors to get hit point velocity */ interp_v3_v3v3v3(brushPointVelocity, @@ -4881,7 +4882,7 @@ static void dynamicPaint_prepareAdjacencyData(DynamicPaintSurface *surface, cons 0, sData->total_points, sData, dynamic_paint_prepare_adjacency_cb, &settings); /* calculate average values (single thread). - * Note: tried to put this in threaded callback (using _reduce feature), + * NOTE: tried to put this in threaded callback (using _reduce feature), * but gave ~30% slower result! */ bData->average_dist = 0.0; for (index = 0; index < sData->total_points; index++) { @@ -5521,7 +5522,7 @@ static void dynamicPaint_doEffectStep( if (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP && force) { const float eff_scale = distance_scale * EFF_MOVEMENT_PER_FRAME * timescale / 2.0f; - /* Same as BLI_bitmask, but handled atomicaly as 'ePoint' locks. */ + /* Same as #BLI_bitmask, but handled atomically as 'ePoint' locks. */ const size_t point_locks_size = (sData->total_points / 8) + 1; uint8_t *point_locks = MEM_callocN(sizeof(*point_locks) * point_locks_size, __func__); @@ -6069,7 +6070,7 @@ static bool dynamicPaint_generateBakeData(DynamicPaintSurface *surface, if (bData) { const bool surface_moved = dynamicPaint_surfaceHasMoved(surface, ob); - /* get previous speed for accelertaion */ + /* Get previous speed for acceleration. */ if (do_accel_data && bData->prev_velocity && bData->velocity) { memcpy(bData->prev_velocity, bData->velocity, sData->total_points * sizeof(Vec3f)); } @@ -6270,7 +6271,7 @@ static int dynamicPaint_doStep(Depsgraph *depsgraph, brushObj, true, SUBFRAME_RECURSION, - BKE_scene_frame_get(scene), + BKE_scene_ctime_get(scene), eModifierType_DynamicPaint); } @@ -6311,7 +6312,7 @@ static int dynamicPaint_doStep(Depsgraph *depsgraph, brushObj, true, SUBFRAME_RECURSION, - BKE_scene_frame_get(scene), + BKE_scene_ctime_get(scene), eModifierType_DynamicPaint); } diff --git a/source/blender/blenkernel/intern/editmesh.c b/source/blender/blenkernel/intern/editmesh.c index 49c2a2cbd89..9cae74e4e9a 100644 --- a/source/blender/blenkernel/intern/editmesh.c +++ b/source/blender/blenkernel/intern/editmesh.c @@ -39,15 +39,14 @@ #include "BKE_mesh_wrapper.h" #include "BKE_object.h" -BMEditMesh *BKE_editmesh_create(BMesh *bm, const bool do_tessellate) +/** + * \note The caller is responsible for ensuring triangulation data, + * typically by calling #BKE_editmesh_looptri_calc. + */ +BMEditMesh *BKE_editmesh_create(BMesh *bm) { BMEditMesh *em = MEM_callocN(sizeof(BMEditMesh), __func__); - em->bm = bm; - if (do_tessellate) { - BKE_editmesh_looptri_calc(em); - } - return em; } @@ -209,7 +208,7 @@ void BKE_editmesh_looptri_and_normals_calc_with_partial(BMEditMesh *em, }); } -void BKE_editmesh_free_derivedmesh(BMEditMesh *em) +void BKE_editmesh_free_derived_caches(BMEditMesh *em) { if (em->mesh_eval_cage) { BKE_id_free(NULL, em->mesh_eval_cage); @@ -223,9 +222,9 @@ void BKE_editmesh_free_derivedmesh(BMEditMesh *em) } /* Does not free the #BMEditMesh struct itself. */ -void BKE_editmesh_free(BMEditMesh *em) +void BKE_editmesh_free_data(BMEditMesh *em) { - BKE_editmesh_free_derivedmesh(em); + BKE_editmesh_free_derived_caches(em); if (em->looptris) { MEM_freeN(em->looptris); @@ -330,7 +329,7 @@ void BKE_editmesh_lnorspace_update(BMEditMesh *em, Mesh *me) * otherwise there is no way to edit them. * Similar code to #MESH_OT_customdata_custom_splitnormals_add operator, * we want to keep same shading in case we were using auto-smooth so far. - * Note: there is a problem here, which is that if someone starts a normal editing operation on + * NOTE: there is a problem here, which is that if someone starts a normal editing operation on * previously auto-smooth-ed mesh, and cancel that operation, generated CLNORS data remain, * with related sharp edges (and hence auto-smooth is 'lost'). * Not sure how critical this is, and how to fix that issue? */ diff --git a/source/blender/blenkernel/intern/editmesh_bvh.c b/source/blender/blenkernel/intern/editmesh_bvh.c index 9e0e1933a00..087481b1b5d 100644 --- a/source/blender/blenkernel/intern/editmesh_bvh.c +++ b/source/blender/blenkernel/intern/editmesh_bvh.c @@ -117,7 +117,7 @@ BMBVHTree *BKE_bmbvh_new_ex(BMesh *bm, for (int i = 0; i < looptris_tot; i++) { if (test_fn) { - /* Note: the arrays won't align now! Take care. */ + /* NOTE: the arrays won't align now! Take care. */ f_test = looptris[i][0]->f; if (f_test != f_test_prev) { test_fn_ret = test_fn(f_test, user_data); diff --git a/source/blender/blenkernel/intern/editmesh_tangent.c b/source/blender/blenkernel/intern/editmesh_tangent.c index d849f4ab37d..da4ea742656 100644 --- a/source/blender/blenkernel/intern/editmesh_tangent.c +++ b/source/blender/blenkernel/intern/editmesh_tangent.c @@ -25,6 +25,7 @@ #include "DNA_defs.h" #include "DNA_meshdata_types.h" +#include "BKE_customdata.h" #include "BKE_editmesh.h" #include "BKE_editmesh_tangent.h" #include "BKE_mesh.h" @@ -381,7 +382,7 @@ void BKE_editmesh_loop_tangent_calc(BMEditMesh *em, mesh2tangent->num_face_as_quad_map = num_face_as_quad_map; #endif mesh2tangent->precomputedFaceNormals = poly_normals; - /* Note, we assume we do have tessellated loop normals at this point + /* NOTE: we assume we do have tessellated loop normals at this point * (in case it is object-enabled), have to check this is valid. */ mesh2tangent->precomputedLoopNormals = loop_normals; mesh2tangent->cd_loop_uv_offset = CustomData_get_n_offset(&bm->ldata, CD_MLOOPUV, n); diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c index 97aba5e787d..1b628b16802 100644 --- a/source/blender/blenkernel/intern/effect.c +++ b/source/blender/blenkernel/intern/effect.c @@ -716,7 +716,7 @@ int get_effector_data(EffectorCache *eff, } else if (eff->pd && eff->pd->shape == PFIELD_SHAPE_POINTS) { /* TODO: hair and points object support */ - Mesh *me_eval = BKE_object_get_evaluated_mesh(eff->ob); + const Mesh *me_eval = BKE_object_get_evaluated_mesh(eff->ob); if (me_eval != NULL) { copy_v3_v3(efd->loc, me_eval->mvert[*efd->index].co); normal_short_to_float_v3(efd->nor, me_eval->mvert[*efd->index].no); @@ -830,7 +830,7 @@ static void get_effector_tot( if (eff->pd->shape == PFIELD_SHAPE_POINTS) { /* TODO: hair and points object support */ - Mesh *me_eval = BKE_object_get_evaluated_mesh(eff->ob); + const Mesh *me_eval = BKE_object_get_evaluated_mesh(eff->ob); *tot = me_eval != NULL ? me_eval->totvert : 1; if (*tot && eff->pd->forcefield == PFIELD_HARMONIC && point->index >= 0) { diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c index 7fe7b38e120..8f47a7e75d4 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -2147,7 +2147,7 @@ static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime) * \{ */ /* Evaluate and return the value of the given F-Curve at the specified frame ("evaltime") - * Note: this is also used for drivers. + * NOTE: this is also used for drivers. */ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) { @@ -2194,9 +2194,9 @@ float evaluate_fcurve(FCurve *fcu, float evaltime) float evaluate_fcurve_only_curve(FCurve *fcu, float evaltime) { - /* Can be used to evaluate the (keyframed) fcurve only. - * Also works for driver-fcurves when the driver itself is not relevant. - * E.g. when inserting a keyframe in a driver fcurve. */ + /* Can be used to evaluate the (key-framed) f-curve only. + * Also works for driver-f-curves when the driver itself is not relevant. + * E.g. when inserting a keyframe in a driver f-curve. */ return evaluate_fcurve_ex(fcu, evaltime, 0.0); } diff --git a/source/blender/blenkernel/intern/fluid.c b/source/blender/blenkernel/intern/fluid.c index 947417af55d..2b48683a3a8 100644 --- a/source/blender/blenkernel/intern/fluid.c +++ b/source/blender/blenkernel/intern/fluid.c @@ -1283,10 +1283,10 @@ static void compute_obstaclesemission(Scene *scene, # endif /* Update frame time, this is considering current subframe fraction * BLI_mutex_lock() called in manta_step(), so safe to update subframe here - * TODO(sebbas): Using BKE_scene_frame_get(scene) instead of new DEG_get_ctime(depsgraph) + * TODO(sebbas): Using BKE_scene_ctime_get(scene) instead of new DEG_get_ctime(depsgraph) * as subframes don't work with the latter yet. */ BKE_object_modifier_update_subframe( - depsgraph, scene, effecobj, true, 5, BKE_scene_frame_get(scene), eModifierType_Fluid); + depsgraph, scene, effecobj, true, 5, BKE_scene_ctime_get(scene), eModifierType_Fluid); if (subframes) { obstacles_from_mesh(effecobj, fds, fes, &bb_temp, subframe_dt); @@ -1616,7 +1616,7 @@ static void emit_from_particles(Object *flow_ob, } /* `DEG_get_ctime(depsgraph)` does not give sub-frame time. */ - state.time = BKE_scene_frame_get(scene); + state.time = BKE_scene_ctime_get(scene); if (psys_get_particle_state(&sim, p, &state, 0) == 0) { continue; @@ -2820,10 +2820,10 @@ static void compute_flowsemission(Scene *scene, # endif /* Update frame time, this is considering current subframe fraction * BLI_mutex_lock() called in manta_step(), so safe to update subframe here - * TODO(sebbas): Using BKE_scene_frame_get(scene) instead of new DEG_get_ctime(depsgraph) + * TODO(sebbas): Using BKE_scene_ctime_get(scene) instead of new DEG_get_ctime(depsgraph) * as subframes don't work with the latter yet. */ BKE_object_modifier_update_subframe( - depsgraph, scene, flowobj, true, 5, BKE_scene_frame_get(scene), eModifierType_Fluid); + depsgraph, scene, flowobj, true, 5, BKE_scene_ctime_get(scene), eModifierType_Fluid); /* Emission from particles. */ if (ffs->source == FLUID_FLOW_SOURCE_PARTICLES) { diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c index b9f0b97ab46..641c003d456 100644 --- a/source/blender/blenkernel/intern/fmodifier.c +++ b/source/blender/blenkernel/intern/fmodifier.c @@ -604,7 +604,7 @@ int BKE_fcm_envelope_find_index(FCM_EnvelopeData array[], * NOTE: this needs to be at the start of the stack to be of use, * as it needs to know the extents of the keyframes/sample-data. * - * Possible TODO - store length of cycle information that can be initialized from the extents of + * Possible TODO: store length of cycle information that can be initialized from the extents of * the keyframes/sample-data, and adjusted as appropriate. */ @@ -688,7 +688,7 @@ static float fcm_cycles_time( ofs = lastkey[0]; } } - if ((ELEM(0, side, mode))) { + if (ELEM(0, side, mode)) { return evaltime; } diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c index 8bb2c401b03..d0b9aeefa55 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -984,7 +984,7 @@ static bool vfont_to_curve(Object *ob, } if (dobreak) { if (tb_scale.h == 0.0f) { - /* Note: If underlined text is truncated away, the extra space is also truncated. */ + /* NOTE: If underlined text is truncated away, the extra space is also truncated. */ custrinfo[i + 1].flag |= CU_CHINFO_OVERFLOW; } goto makebreak; @@ -1032,7 +1032,7 @@ static bool vfont_to_curve(Object *ob, current_line_length = 0.0f; } - /* XXX, has been unused for years, need to check if this is useful, r4613 r5282 - campbell */ + /* XXX(campbell): has been unused for years, need to check if this is useful, r4613 r5282. */ #if 0 if (ascii == '\n') { xof = xof_scale; diff --git a/source/blender/blenkernel/intern/geometry_component_mesh.cc b/source/blender/blenkernel/intern/geometry_component_mesh.cc index 28e46aab732..ef93a3f9b3f 100644 --- a/source/blender/blenkernel/intern/geometry_component_mesh.cc +++ b/source/blender/blenkernel/intern/geometry_component_mesh.cc @@ -53,7 +53,6 @@ GeometryComponent *MeshComponent::copy() const if (mesh_ != nullptr) { new_component->mesh_ = BKE_mesh_copy_for_eval(mesh_, false); new_component->ownership_ = GeometryOwnershipType::Owned; - new_component->vertex_group_names_ = blender::Map(vertex_group_names_); } return new_component; } @@ -67,7 +66,6 @@ void MeshComponent::clear() } mesh_ = nullptr; } - vertex_group_names_.clear(); } bool MeshComponent::has_mesh() const @@ -84,23 +82,6 @@ void MeshComponent::replace(Mesh *mesh, GeometryOwnershipType ownership) ownership_ = ownership; } -/* This function exists for the same reason as #vertex_group_names_. Non-nodes modifiers need to - * be able to replace the mesh data without losing the vertex group names, which may have come - * from another object. */ -void MeshComponent::replace_mesh_but_keep_vertex_group_names(Mesh *mesh, - GeometryOwnershipType ownership) -{ - BLI_assert(this->is_mutable()); - if (mesh_ != nullptr) { - if (ownership_ == GeometryOwnershipType::Owned) { - BKE_id_free(nullptr, mesh_); - } - mesh_ = nullptr; - } - mesh_ = mesh; - ownership_ = ownership; -} - /* Return the mesh and clear the component. The caller takes over responsibility for freeing the * mesh (if the component was responsible before). */ Mesh *MeshComponent::release() @@ -111,28 +92,6 @@ Mesh *MeshComponent::release() return mesh; } -void MeshComponent::copy_vertex_group_names_from_object(const Object &object) -{ - BLI_assert(this->is_mutable()); - vertex_group_names_.clear(); - int index = 0; - LISTBASE_FOREACH (const bDeformGroup *, group, &object.defbase) { - vertex_group_names_.add(group->name, index); - index++; - } -} - -const blender::Map<std::string, int> &MeshComponent::vertex_group_names() const -{ - return vertex_group_names_; -} - -/* This is only exposed for the internal attribute API. */ -blender::Map<std::string, int> &MeshComponent::vertex_group_names() -{ - return vertex_group_names_; -} - /* Get the mesh from this component. This method can be used by multiple threads at the same * time. Therefore, the returned mesh should not be modified. No ownership is transferred. */ const Mesh *MeshComponent::get_for_read() const @@ -864,12 +823,15 @@ class VertexGroupsAttributeProvider final : public DynamicAttributesProvider { BLI_assert(component.type() == GEO_COMPONENT_TYPE_MESH); const MeshComponent &mesh_component = static_cast<const MeshComponent &>(component); const Mesh *mesh = mesh_component.get_for_read(); - const int vertex_group_index = mesh_component.vertex_group_names().lookup_default_as( - attribute_name, -1); + if (mesh == nullptr) { + return {}; + } + const int vertex_group_index = BLI_findstringindex( + &mesh->vertex_group_names, attribute_name.data(), offsetof(bDeformGroup, name)); if (vertex_group_index < 0) { return {}; } - if (mesh == nullptr || mesh->dvert == nullptr) { + if (mesh->dvert == nullptr) { static const float default_value = 0.0f; return {std::make_unique<fn::GVArray_For_SingleValueRef>( CPPType::get<float>(), mesh->totvert, &default_value), @@ -889,8 +851,9 @@ class VertexGroupsAttributeProvider final : public DynamicAttributesProvider { if (mesh == nullptr) { return {}; } - const int vertex_group_index = mesh_component.vertex_group_names().lookup_default_as( - attribute_name, -1); + + const int vertex_group_index = BLI_findstringindex( + &mesh->vertex_group_names, attribute_name.data(), offsetof(bDeformGroup, name)); if (vertex_group_index < 0) { return {}; } @@ -913,16 +876,16 @@ class VertexGroupsAttributeProvider final : public DynamicAttributesProvider { { BLI_assert(component.type() == GEO_COMPONENT_TYPE_MESH); MeshComponent &mesh_component = static_cast<MeshComponent &>(component); - - const int vertex_group_index = mesh_component.vertex_group_names().pop_default_as( - attribute_name, -1); - if (vertex_group_index < 0) { - return false; - } Mesh *mesh = mesh_component.get_for_write(); if (mesh == nullptr) { return true; } + + const int vertex_group_index = BLI_findstringindex( + &mesh->vertex_group_names, attribute_name.data(), offsetof(bDeformGroup, name)); + if (vertex_group_index < 0) { + return false; + } if (mesh->dvert == nullptr) { return true; } @@ -938,14 +901,14 @@ class VertexGroupsAttributeProvider final : public DynamicAttributesProvider { { BLI_assert(component.type() == GEO_COMPONENT_TYPE_MESH); const MeshComponent &mesh_component = static_cast<const MeshComponent &>(component); - for (const auto item : mesh_component.vertex_group_names().items()) { - const StringRefNull name = item.key; - const int vertex_group_index = item.value; - if (vertex_group_index >= 0) { - AttributeMetaData meta_data{ATTR_DOMAIN_POINT, CD_PROP_FLOAT}; - if (!callback(name, meta_data)) { - return false; - } + const Mesh *mesh = mesh_component.get_for_read(); + if (mesh == nullptr) { + return true; + } + + LISTBASE_FOREACH (const bDeformGroup *, group, &mesh->vertex_group_names) { + if (!callback(group->name, {ATTR_DOMAIN_POINT, CD_PROP_FLOAT})) { + return false; } } return true; diff --git a/source/blender/blenkernel/intern/geometry_set_instances.cc b/source/blender/blenkernel/intern/geometry_set_instances.cc index 01b51d552a9..90a97264c8f 100644 --- a/source/blender/blenkernel/intern/geometry_set_instances.cc +++ b/source/blender/blenkernel/intern/geometry_set_instances.cc @@ -48,7 +48,6 @@ static void add_final_mesh_as_geometry_component(const Object &object, GeometryS MeshComponent &mesh_component = geometry_set.get_component_for_write<MeshComponent>(); mesh_component.replace(mesh, GeometryOwnershipType::ReadOnly); - mesh_component.copy_vertex_group_names_from_object(object); } } @@ -566,6 +565,7 @@ static PointCloud *join_pointcloud_position_attribute(Span<GeometryInstanceGroup } PointCloud *new_pointcloud = BKE_pointcloud_new_nomain(totpoint); + MutableSpan new_positions{(float3 *)new_pointcloud->co, new_pointcloud->totpoint}; /* Transform each instance's point locations into the new point cloud. */ int offset = 0; @@ -577,9 +577,7 @@ static PointCloud *join_pointcloud_position_attribute(Span<GeometryInstanceGroup } for (const float4x4 &transform : set_group.transforms) { for (const int i : IndexRange(pointcloud->totpoint)) { - const float3 old_position = pointcloud->co[i]; - const float3 new_position = transform * old_position; - copy_v3_v3(new_pointcloud->co[offset + i], new_position); + new_positions[offset + i] = transform * float3(pointcloud->co[i]); } offset += pointcloud->totpoint; } diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index 459fc5e4c68..38397f8f307 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -87,12 +87,14 @@ static void greasepencil_copy_data(Main *UNUSED(bmain), gpd_dst->mat = MEM_dupallocN(gpd_src->mat); } + BKE_defgroup_copy_list(&gpd_dst->vertex_group_names, &gpd_src->vertex_group_names); + /* copy layers */ BLI_listbase_clear(&gpd_dst->layers); LISTBASE_FOREACH (bGPDlayer *, gpl_src, &gpd_src->layers) { /* make a copy of source layer and its data */ - /* TODO here too could add unused flags... */ + /* TODO: here too could add unused flags... */ bGPDlayer *gpl_dst = BKE_gpencil_layer_duplicate(gpl_src, true, true); /* Apply local layer transform to all frames. Calc the active frame is not enough @@ -165,6 +167,8 @@ static void greasepencil_blend_write(BlendWriter *writer, ID *id, const void *id BKE_animdata_blend_write(writer, gpd->adt); } + BKE_defbase_blend_write(writer, &gpd->vertex_group_names); + BLO_write_pointer_array(writer, gpd->totcol, gpd->mat); /* write grease-pencil layers to file */ @@ -227,6 +231,8 @@ void BKE_gpencil_blend_read_data(BlendDataReader *reader, bGPdata *gpd) } } + BLO_read_list(reader, &gpd->vertex_group_names); + /* Materials. */ BLO_read_pointer_array(reader, (void **)&gpd->mat); @@ -498,6 +504,8 @@ void BKE_gpencil_free(bGPdata *gpd, bool free_all) /* materials */ MEM_SAFE_FREE(gpd->mat); + BLI_freelistN(&gpd->vertex_group_names); + /* free all data */ if (free_all) { /* clear cache */ @@ -798,32 +806,6 @@ bGPdata *BKE_gpencil_data_addnew(Main *bmain, const char name[]) /* Utilities for easier bulk-creation of geometry */ /** - * Populate stroke with point data from data buffers. - * \param gps: Grease pencil stroke - * \param array: Flat array of point data values. Each entry has #GP_PRIM_DATABUF_SIZE values. - * \param totpoints: Total of points - * \param mat: 4x4 transform matrix to transform points into the right coordinate space. - */ -void BKE_gpencil_stroke_add_points(bGPDstroke *gps, - const float *array, - const int totpoints, - const float mat[4][4]) -{ - for (int i = 0; i < totpoints; i++) { - bGPDspoint *pt = &gps->points[i]; - const int x = GP_PRIM_DATABUF_SIZE * i; - - pt->x = array[x]; - pt->y = array[x + 1]; - pt->z = array[x + 2]; - mul_m4_v3(mat, &pt->x); - - pt->pressure = array[x + 3]; - pt->strength = array[x + 4]; - } -} - -/** * Create a new stroke, with pre-allocated data buffers. * \param mat_idx: Index of the material * \param totpoints: Total points @@ -2087,8 +2069,9 @@ void BKE_gpencil_vgroup_remove(Object *ob, bDeformGroup *defgroup) { bGPdata *gpd = ob->data; MDeformVert *dvert = NULL; - const int def_nr = BLI_findindex(&ob->defbase, defgroup); - const int totgrp = BLI_listbase_count(&ob->defbase); + + const int def_nr = BLI_findindex(&gpd->vertex_group_names, defgroup); + const int totgrp = BLI_listbase_count(&gpd->vertex_group_names); /* Remove points data */ if (gpd) { @@ -2117,7 +2100,7 @@ void BKE_gpencil_vgroup_remove(Object *ob, bDeformGroup *defgroup) } /* Remove the group */ - BLI_freelinkN(&ob->defbase, defgroup); + BLI_freelinkN(&gpd->vertex_group_names, defgroup); DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY); } @@ -2694,22 +2677,60 @@ static bool gpencil_is_layer_mask(ViewLayer *view_layer, bGPdata *gpd, bGPDlayer } /* -------------------------------------------------------------------- */ -/** \name Iterators +/** \name Iterator * - * Iterate over all visible stroke of all visible layers inside a gpObject. - * Also take into account onion-skinning. + * Iterate over all visible stroke of all visible layers inside a grease pencil datablock. * \{ */ -void BKE_gpencil_visible_stroke_iter(ViewLayer *view_layer, - Object *ob, +void BKE_gpencil_visible_stroke_iter(bGPdata *gpd, gpIterCb layer_cb, gpIterCb stroke_cb, - void *thunk, - bool do_onion, - int cfra) + void *thunk) +{ + LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) { + + if (gpl->flag & GP_LAYER_HIDE) { + continue; + } + + /* If scale to 0 the layer must be invisible. */ + if (is_zero_v3(gpl->scale)) { + continue; + } + + bGPDframe *act_gpf = gpl->actframe; + if (layer_cb) { + layer_cb(gpl, act_gpf, NULL, thunk); + } + + if (act_gpf) { + LISTBASE_FOREACH (bGPDstroke *, gps, &act_gpf->strokes) { + if (gps->totpoints == 0) { + continue; + } + stroke_cb(gpl, act_gpf, gps, thunk); + } + } + } +} + +/* -------------------------------------------------------------------- */ +/** \name Advanced Iterator + * + * Iterate over all visible stroke of all visible layers inside a gpObject. + * Also take into account onion-skinning. + * \{ */ + +void BKE_gpencil_visible_stroke_advanced_iter(ViewLayer *view_layer, + Object *ob, + gpIterCb layer_cb, + gpIterCb stroke_cb, + void *thunk, + bool do_onion, + int cfra) { bGPdata *gpd = (bGPdata *)ob->data; - const bool is_multiedit = ((GPENCIL_MULTIEDIT_SESSIONS_ON(gpd)) && (!GPENCIL_PLAY_ON(gpd))); + const bool is_multiedit = (GPENCIL_MULTIEDIT_SESSIONS_ON(gpd) && (!GPENCIL_PLAY_ON(gpd))); const bool is_onion = do_onion && ((gpd->flag & GP_DATA_STROKE_WEIGHTMODE) == 0); const bool is_drawing = (gpd->runtime.sbuffer_used > 0); diff --git a/source/blender/blenkernel/intern/gpencil_geom.c b/source/blender/blenkernel/intern/gpencil_geom.cc index 53939da08e2..785f63a7ba2 100644 --- a/source/blender/blenkernel/intern/gpencil_geom.c +++ b/source/blender/blenkernel/intern/gpencil_geom.cc @@ -21,22 +21,24 @@ * \ingroup bke */ -#include <math.h> -#include <stddef.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> +#include <cmath> +#include <cstddef> +#include <cstdio> +#include <cstdlib> +#include <cstring> #include "CLG_log.h" #include "MEM_guardedalloc.h" #include "BLI_blenlib.h" +#include "BLI_float3.hh" #include "BLI_ghash.h" #include "BLI_hash.h" #include "BLI_heap.h" #include "BLI_math_vector.h" #include "BLI_polyfill_2d.h" +#include "BLI_span.hh" #include "BLT_translation.h" @@ -61,6 +63,9 @@ #include "DEG_depsgraph_query.h" +using blender::float3; +using blender::Span; + /* GP Object - Boundbox Support */ /** *Get min/max coordinate bounds for single stroke. @@ -75,20 +80,26 @@ bool BKE_gpencil_stroke_minmax(const bGPDstroke *gps, float r_min[3], float r_max[3]) { - const bGPDspoint *pt; - int i; - bool changed = false; - - if (ELEM(NULL, gps, r_min, r_max)) { + if (gps == nullptr) { return false; } - for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) { - if ((use_select == false) || (pt->flag & GP_SPOINT_SELECT)) { - minmax_v3v3_v3(r_min, r_max, &pt->x); + bool changed = false; + if (use_select) { + for (const bGPDspoint &pt : Span(gps->points, gps->totpoints)) { + if (pt.flag & GP_SPOINT_SELECT) { + minmax_v3v3_v3(r_min, r_max, &pt.x); + changed = true; + } + } + } + else { + for (const bGPDspoint &pt : Span(gps->points, gps->totpoints)) { + minmax_v3v3_v3(r_min, r_max, &pt.x); changed = true; } } + return changed; } @@ -105,14 +116,14 @@ bool BKE_gpencil_data_minmax(const bGPdata *gpd, float r_min[3], float r_max[3]) INIT_MINMAX(r_min, r_max); - if (gpd == NULL) { + if (gpd == nullptr) { return changed; } LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) { bGPDframe *gpf = gpl->actframe; - if (gpf != NULL) { + if (gpf != nullptr) { LISTBASE_FOREACH (bGPDstroke *, gps, &gpf->strokes) { changed |= BKE_gpencil_stroke_minmax(gps, false, r_min, r_max); } @@ -129,11 +140,11 @@ bool BKE_gpencil_data_minmax(const bGPdata *gpd, float r_min[3], float r_max[3]) */ void BKE_gpencil_centroid_3d(bGPdata *gpd, float r_centroid[3]) { - float min[3], max[3], tot[3]; - + float3 min; + float3 max; BKE_gpencil_data_minmax(gpd, min, max); - add_v3_v3v3(tot, min, max); + const float3 tot = min + max; mul_v3_v3fl(r_centroid, tot, 0.5f); } @@ -153,20 +164,18 @@ void BKE_gpencil_stroke_boundingbox_calc(bGPDstroke *gps) */ static void boundbox_gpencil(Object *ob) { - BoundBox *bb; - bGPdata *gpd; - float min[3], max[3]; - - if (ob->runtime.bb == NULL) { - ob->runtime.bb = MEM_callocN(sizeof(BoundBox), "GPencil boundbox"); + if (ob->runtime.bb == nullptr) { + ob->runtime.bb = (BoundBox *)MEM_callocN(sizeof(BoundBox), "GPencil boundbox"); } - bb = ob->runtime.bb; - gpd = ob->data; + BoundBox *bb = ob->runtime.bb; + bGPdata *gpd = (bGPdata *)ob->data; + float3 min; + float3 max; if (!BKE_gpencil_data_minmax(gpd, min, max)) { - min[0] = min[1] = min[2] = -1.0f; - max[0] = max[1] = max[2] = 1.0f; + min = float3(-1); + max = float3(1); } BKE_boundbox_init_from_minmax(bb, min, max); @@ -181,8 +190,8 @@ static void boundbox_gpencil(Object *ob) */ BoundBox *BKE_gpencil_boundbox_get(Object *ob) { - if (ELEM(NULL, ob, ob->data)) { - return NULL; + if (ELEM(nullptr, ob, ob->data)) { + return nullptr; } bGPdata *gpd = (bGPdata *)ob->data; @@ -196,9 +205,9 @@ BoundBox *BKE_gpencil_boundbox_get(Object *ob) /* Update orig object's boundbox with re-computed evaluated values. This function can be * called with the evaluated object and need update the original object bound box data * to keep both values synchronized. */ - if (!ELEM(ob_orig, NULL, ob)) { - if (ob_orig->runtime.bb == NULL) { - ob_orig->runtime.bb = MEM_callocN(sizeof(BoundBox), "GPencil boundbox"); + if (!ELEM(ob_orig, nullptr, ob)) { + if (ob_orig->runtime.bb == nullptr) { + ob_orig->runtime.bb = (BoundBox *)MEM_callocN(sizeof(BoundBox), "GPencil boundbox"); } for (int i = 0; i < 8; i++) { copy_v3_v3(ob_orig->runtime.bb->vec[i], ob->runtime.bb->vec[i]); @@ -227,7 +236,7 @@ static int stroke_march_next_point(const bGPDstroke *gps, float step_start[3]; float point[3]; int next_point_index = index_next_pt; - bGPDspoint *pt = NULL; + bGPDspoint *pt = nullptr; if (!(next_point_index < gps->totpoints)) { return -1; @@ -295,7 +304,7 @@ static int stroke_march_next_point_no_interp(const bGPDstroke *gps, float step_start[3]; float point[3]; int next_point_index = index_next_pt; - bGPDspoint *pt = NULL; + bGPDspoint *pt = nullptr; if (!(next_point_index < gps->totpoints)) { return -1; @@ -336,7 +345,7 @@ static int stroke_march_count(const bGPDstroke *gps, const float dist) int point_count = 0; float point[3]; int next_point_index = 1; - bGPDspoint *pt = NULL; + bGPDspoint *pt = nullptr; pt = &gps->points[0]; copy_v3_v3(point, &pt->x); @@ -369,14 +378,14 @@ static void stroke_defvert_create_nr_list(MDeformVert *dv_list, for (j = 0; j < dv->totweight; j++) { bool found = false; dw = &dv->dw[j]; - for (ld = result->first; ld; ld = ld->next) { + for (ld = (LinkData *)result->first; ld; ld = ld->next) { if (ld->data == POINTER_FROM_INT(dw->def_nr)) { found = true; break; } } if (!found) { - ld = MEM_callocN(sizeof(LinkData), "def_nr_item"); + ld = (LinkData *)MEM_callocN(sizeof(LinkData), "def_nr_item"); ld->data = POINTER_FROM_INT(dw->def_nr); BLI_addtail(result, ld); tw++; @@ -391,14 +400,15 @@ static MDeformVert *stroke_defvert_new_count(int count, int totweight, ListBase { int i, j; LinkData *ld; - MDeformVert *dst = MEM_mallocN(count * sizeof(MDeformVert), "new_deformVert"); + MDeformVert *dst = (MDeformVert *)MEM_mallocN(count * sizeof(MDeformVert), "new_deformVert"); for (i = 0; i < count; i++) { - dst[i].dw = MEM_mallocN(sizeof(MDeformWeight) * totweight, "new_deformWeight"); + dst[i].dw = (MDeformWeight *)MEM_mallocN(sizeof(MDeformWeight) * totweight, + "new_deformWeight"); dst[i].totweight = totweight; j = 0; /* re-assign deform groups */ - for (ld = def_nr_list->first; ld; ld = ld->next) { + for (ld = (LinkData *)def_nr_list->first; ld; ld = ld->next) { dst[i].dw[j].def_nr = POINTER_AS_INT(ld->data); j++; } @@ -429,10 +439,10 @@ static void stroke_interpolate_deform_weights( bool BKE_gpencil_stroke_sample(bGPdata *gpd, bGPDstroke *gps, const float dist, const bool select) { bGPDspoint *pt = gps->points; - bGPDspoint *pt1 = NULL; - bGPDspoint *pt2 = NULL; + bGPDspoint *pt1 = nullptr; + bGPDspoint *pt2 = nullptr; LinkData *ld; - ListBase def_nr_list = {0}; + ListBase def_nr_list = {nullptr}; if (gps->totpoints < 2 || dist < FLT_EPSILON) { return false; @@ -440,12 +450,13 @@ bool BKE_gpencil_stroke_sample(bGPdata *gpd, bGPDstroke *gps, const float dist, /* TODO: Implement feature point preservation. */ int count = stroke_march_count(gps, dist); - bGPDspoint *new_pt = MEM_callocN(sizeof(bGPDspoint) * count, "gp_stroke_points_sampled"); - MDeformVert *new_dv = NULL; + bGPDspoint *new_pt = (bGPDspoint *)MEM_callocN(sizeof(bGPDspoint) * count, + "gp_stroke_points_sampled"); + MDeformVert *new_dv = nullptr; int result_totweight; - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { stroke_defvert_create_nr_list(gps->dvert, gps->totpoints, &def_nr_list, &result_totweight); new_dv = stroke_defvert_new_count(count, result_totweight, &def_nr_list); } @@ -513,7 +524,7 @@ bool BKE_gpencil_stroke_sample(bGPdata *gpd, bGPDstroke *gps, const float dist, /* Free original weight data. */ BKE_gpencil_free_stroke_weights(gps); MEM_freeN(gps->dvert); - while ((ld = BLI_pophead(&def_nr_list))) { + while ((ld = (LinkData *)BLI_pophead(&def_nr_list))) { MEM_freeN(ld); } @@ -610,30 +621,32 @@ bool BKE_gpencil_stroke_trim_points(bGPDstroke *gps, const int index_from, const if (new_count == 1) { BKE_gpencil_free_stroke_weights(gps); MEM_freeN(gps->points); - gps->points = NULL; - gps->dvert = NULL; + gps->points = nullptr; + gps->dvert = nullptr; gps->totpoints = 0; return false; } - new_pt = MEM_callocN(sizeof(bGPDspoint) * new_count, "gp_stroke_points_trimmed"); + new_pt = (bGPDspoint *)MEM_callocN(sizeof(bGPDspoint) * new_count, "gp_stroke_points_trimmed"); for (int i = 0; i < new_count; i++) { memcpy(&new_pt[i], &pt[i + index_from], sizeof(bGPDspoint)); } if (gps->dvert) { - new_dv = MEM_callocN(sizeof(MDeformVert) * new_count, "gp_stroke_dverts_trimmed"); + new_dv = (MDeformVert *)MEM_callocN(sizeof(MDeformVert) * new_count, + "gp_stroke_dverts_trimmed"); for (int i = 0; i < new_count; i++) { dv = &gps->dvert[i + index_from]; new_dv[i].flag = dv->flag; new_dv[i].totweight = dv->totweight; - new_dv[i].dw = MEM_callocN(sizeof(MDeformWeight) * dv->totweight, - "gp_stroke_dverts_dw_trimmed"); + new_dv[i].dw = (MDeformWeight *)MEM_callocN(sizeof(MDeformWeight) * dv->totweight, + "gp_stroke_dverts_dw_trimmed"); for (int j = 0; j < dv->totweight; j++) { new_dv[i].dw[j].weight = dv->dw[j].weight; new_dv[i].dw[j].def_nr = dv->dw[j].def_nr; } + BKE_defvert_clear(dv); } MEM_freeN(gps->dvert); gps->dvert = new_dv; @@ -684,18 +697,19 @@ bool BKE_gpencil_stroke_split(bGPdata *gpd, } if (gps->dvert) { - new_dv = MEM_callocN(sizeof(MDeformVert) * new_count, - "gp_stroke_dverts_remaining(MDeformVert)"); + new_dv = (MDeformVert *)MEM_callocN(sizeof(MDeformVert) * new_count, + "gp_stroke_dverts_remaining(MDeformVert)"); for (int i = 0; i < new_count; i++) { dv = &gps->dvert[i + before_index]; new_dv[i].flag = dv->flag; new_dv[i].totweight = dv->totweight; - new_dv[i].dw = MEM_callocN(sizeof(MDeformWeight) * dv->totweight, - "gp_stroke_dverts_dw_remaining(MDeformWeight)"); + new_dv[i].dw = (MDeformWeight *)MEM_callocN(sizeof(MDeformWeight) * dv->totweight, + "gp_stroke_dverts_dw_remaining(MDeformWeight)"); for (int j = 0; j < dv->totweight; j++) { new_dv[i].dw[j].weight = dv->dw[j].weight; new_dv[i].dw[j].def_nr = dv->dw[j].def_nr; } + BKE_defvert_clear(dv); } new_gps->dvert = new_dv; } @@ -1299,11 +1313,12 @@ void BKE_gpencil_stroke_fill_triangulate(bGPDstroke *gps) /* allocate memory for temporary areas */ gps->tot_triangles = gps->totpoints - 2; - uint(*tmp_triangles)[3] = MEM_mallocN(sizeof(*tmp_triangles) * gps->tot_triangles, - "GP Stroke temp triangulation"); - float(*points2d)[2] = MEM_mallocN(sizeof(*points2d) * gps->totpoints, - "GP Stroke temp 2d points"); - float(*uv)[2] = MEM_mallocN(sizeof(*uv) * gps->totpoints, "GP Stroke temp 2d uv data"); + uint(*tmp_triangles)[3] = (uint(*)[3])MEM_mallocN(sizeof(*tmp_triangles) * gps->tot_triangles, + "GP Stroke temp triangulation"); + float(*points2d)[2] = (float(*)[2])MEM_mallocN(sizeof(*points2d) * gps->totpoints, + "GP Stroke temp 2d points"); + float(*uv)[2] = (float(*)[2])MEM_mallocN(sizeof(*uv) * gps->totpoints, + "GP Stroke temp 2d uv data"); int direction = 0; @@ -1324,8 +1339,8 @@ void BKE_gpencil_stroke_fill_triangulate(bGPDstroke *gps) /* Save triangulation data. */ if (gps->tot_triangles > 0) { MEM_SAFE_FREE(gps->triangles); - gps->triangles = MEM_callocN(sizeof(*gps->triangles) * gps->tot_triangles, - "GP Stroke triangulation"); + gps->triangles = (bGPDtriangle *)MEM_callocN(sizeof(*gps->triangles) * gps->tot_triangles, + "GP Stroke triangulation"); for (int i = 0; i < gps->tot_triangles; i++) { memcpy(gps->triangles[i].verts, tmp_triangles[i], sizeof(uint[3])); @@ -1342,7 +1357,7 @@ void BKE_gpencil_stroke_fill_triangulate(bGPDstroke *gps) MEM_freeN(gps->triangles); } - gps->triangles = NULL; + gps->triangles = nullptr; } /* clear memory */ @@ -1357,7 +1372,7 @@ void BKE_gpencil_stroke_fill_triangulate(bGPDstroke *gps) */ void BKE_gpencil_stroke_uv_update(bGPDstroke *gps) { - if (gps == NULL || gps->totpoints == 0) { + if (gps == nullptr || gps->totpoints == 0) { return; } @@ -1377,11 +1392,11 @@ void BKE_gpencil_stroke_uv_update(bGPDstroke *gps) */ void BKE_gpencil_stroke_geometry_update(bGPdata *gpd, bGPDstroke *gps) { - if (gps == NULL) { + if (gps == nullptr) { return; } - if (gps->editcurve != NULL) { + if (gps->editcurve != nullptr) { if (GPENCIL_CURVE_EDIT_SESSIONS_ON(gpd)) { /* curve geometry was updated: stroke needs recalculation */ if (gps->flag & GP_STROKE_NEEDS_CURVE_UPDATE) { @@ -1517,20 +1532,20 @@ bool BKE_gpencil_stroke_trim(bGPdata *gpd, bGPDstroke *gps) if (intersect) { /* save points */ - bGPDspoint *old_points = MEM_dupallocN(gps->points); - MDeformVert *old_dvert = NULL; - MDeformVert *dvert_src = NULL; + bGPDspoint *old_points = (bGPDspoint *)MEM_dupallocN(gps->points); + MDeformVert *old_dvert = nullptr; + MDeformVert *dvert_src = nullptr; - if (gps->dvert != NULL) { - old_dvert = MEM_dupallocN(gps->dvert); + if (gps->dvert != nullptr) { + old_dvert = (MDeformVert *)MEM_dupallocN(gps->dvert); } /* resize gps */ int newtot = end - start + 1; - gps->points = MEM_recallocN(gps->points, sizeof(*gps->points) * newtot); - if (gps->dvert != NULL) { - gps->dvert = MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * newtot); + gps->points = (bGPDspoint *)MEM_recallocN(gps->points, sizeof(*gps->points) * newtot); + if (gps->dvert != nullptr) { + gps->dvert = (MDeformVert *)MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * newtot); } for (int i = 0; i < newtot; i++) { @@ -1538,7 +1553,7 @@ bool BKE_gpencil_stroke_trim(bGPdata *gpd, bGPDstroke *gps) bGPDspoint *pt_src = &old_points[idx]; bGPDspoint *pt_new = &gps->points[i]; memcpy(pt_new, pt_src, sizeof(bGPDspoint)); - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert_src = &old_dvert[idx]; MDeformVert *dvert = &gps->dvert[i]; memcpy(dvert, dvert_src, sizeof(MDeformVert)); @@ -1568,8 +1583,8 @@ bool BKE_gpencil_stroke_trim(bGPdata *gpd, bGPDstroke *gps) */ bool BKE_gpencil_stroke_close(bGPDstroke *gps) { - bGPDspoint *pt1 = NULL; - bGPDspoint *pt2 = NULL; + bGPDspoint *pt1 = nullptr; + bGPDspoint *pt2 = nullptr; /* Only can close a stroke with 3 points or more. */ if (gps->totpoints < 3) { @@ -1603,9 +1618,9 @@ bool BKE_gpencil_stroke_close(bGPDstroke *gps) /* Resize stroke array. */ int old_tot = gps->totpoints; gps->totpoints += tot_newpoints; - gps->points = MEM_recallocN(gps->points, sizeof(*gps->points) * gps->totpoints); - if (gps->dvert != NULL) { - gps->dvert = MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * gps->totpoints); + gps->points = (bGPDspoint *)MEM_recallocN(gps->points, sizeof(*gps->points) * gps->totpoints); + if (gps->dvert != nullptr) { + gps->dvert = (MDeformVert *)MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * gps->totpoints); } /* Generate new points */ @@ -1627,7 +1642,7 @@ bool BKE_gpencil_stroke_close(bGPDstroke *gps) interp_v4_v4v4(pt->vert_color, pt1->vert_color, pt2->vert_color, step); /* Set weights. */ - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { MDeformVert *dvert1 = &gps->dvert[old_tot - 1]; MDeformWeight *dw1 = BKE_defvert_ensure_index(dvert1, 0); float weight_1 = dw1 ? dw1->weight : 0.0f; @@ -1661,7 +1676,7 @@ bool BKE_gpencil_stroke_close(bGPDstroke *gps) void BKE_gpencil_dissolve_points(bGPdata *gpd, bGPDframe *gpf, bGPDstroke *gps, const short tag) { bGPDspoint *pt; - MDeformVert *dvert = NULL; + MDeformVert *dvert = nullptr; int i; int tot = gps->totpoints; /* number of points in new buffer */ @@ -1691,30 +1706,32 @@ void BKE_gpencil_dissolve_points(bGPdata *gpd, bGPDframe *gpf, bGPDstroke *gps, } else { /* just copy all points to keep into a smaller buffer */ - bGPDspoint *new_points = MEM_callocN(sizeof(bGPDspoint) * tot, "new gp stroke points copy"); + bGPDspoint *new_points = (bGPDspoint *)MEM_callocN(sizeof(bGPDspoint) * tot, + "new gp stroke points copy"); bGPDspoint *npt = new_points; - MDeformVert *new_dvert = NULL; - MDeformVert *ndvert = NULL; + MDeformVert *new_dvert = nullptr; + MDeformVert *ndvert = nullptr; - if (gps->dvert != NULL) { - new_dvert = MEM_callocN(sizeof(MDeformVert) * tot, "new gp stroke weights copy"); + if (gps->dvert != nullptr) { + new_dvert = (MDeformVert *)MEM_callocN(sizeof(MDeformVert) * tot, + "new gp stroke weights copy"); ndvert = new_dvert; } - (gps->dvert != NULL) ? dvert = gps->dvert : NULL; + (gps->dvert != nullptr) ? dvert = gps->dvert : nullptr; for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) { if ((pt->flag & tag) == 0) { *npt = *pt; npt++; - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { *ndvert = *dvert; - ndvert->dw = MEM_dupallocN(dvert->dw); + ndvert->dw = (MDeformWeight *)MEM_dupallocN(dvert->dw); ndvert++; } } - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert++; } } @@ -1787,15 +1804,15 @@ void BKE_gpencil_stroke_normal(const bGPDstroke *gps, float r_normal[3]) */ void BKE_gpencil_stroke_simplify_adaptive(bGPdata *gpd, bGPDstroke *gps, float epsilon) { - bGPDspoint *old_points = MEM_dupallocN(gps->points); + bGPDspoint *old_points = (bGPDspoint *)MEM_dupallocN(gps->points); int totpoints = gps->totpoints; - char *marked = NULL; + char *marked = nullptr; char work; int start = 0; int end = gps->totpoints - 1; - marked = MEM_callocN(totpoints, "GP marked array"); + marked = (char *)MEM_callocN(totpoints, "GP marked array"); marked[start] = 1; marked[end] = 1; @@ -1847,11 +1864,11 @@ void BKE_gpencil_stroke_simplify_adaptive(bGPdata *gpd, bGPDstroke *gps, float e } /* adding points marked */ - MDeformVert *old_dvert = NULL; - MDeformVert *dvert_src = NULL; + MDeformVert *old_dvert = nullptr; + MDeformVert *dvert_src = nullptr; - if (gps->dvert != NULL) { - old_dvert = MEM_dupallocN(gps->dvert); + if (gps->dvert != nullptr) { + old_dvert = (MDeformVert *)MEM_dupallocN(gps->dvert); } /* resize gps */ int j = 0; @@ -1861,7 +1878,7 @@ void BKE_gpencil_stroke_simplify_adaptive(bGPdata *gpd, bGPDstroke *gps, float e if ((marked[i]) || (i == 0) || (i == totpoints - 1)) { memcpy(pt, pt_src, sizeof(bGPDspoint)); - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert_src = &old_dvert[i]; MDeformVert *dvert = &gps->dvert[j]; memcpy(dvert, dvert_src, sizeof(MDeformVert)); @@ -1872,7 +1889,7 @@ void BKE_gpencil_stroke_simplify_adaptive(bGPdata *gpd, bGPDstroke *gps, float e j++; } else { - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert_src = &old_dvert[i]; BKE_gpencil_free_point_weights(dvert_src); } @@ -1901,12 +1918,12 @@ void BKE_gpencil_stroke_simplify_fixed(bGPdata *gpd, bGPDstroke *gps) } /* save points */ - bGPDspoint *old_points = MEM_dupallocN(gps->points); - MDeformVert *old_dvert = NULL; - MDeformVert *dvert_src = NULL; + bGPDspoint *old_points = (bGPDspoint *)MEM_dupallocN(gps->points); + MDeformVert *old_dvert = nullptr; + MDeformVert *dvert_src = nullptr; - if (gps->dvert != NULL) { - old_dvert = MEM_dupallocN(gps->dvert); + if (gps->dvert != nullptr) { + old_dvert = (MDeformVert *)MEM_dupallocN(gps->dvert); } /* resize gps */ @@ -1916,9 +1933,9 @@ void BKE_gpencil_stroke_simplify_fixed(bGPdata *gpd, bGPDstroke *gps) } newtot += 2; - gps->points = MEM_recallocN(gps->points, sizeof(*gps->points) * newtot); - if (gps->dvert != NULL) { - gps->dvert = MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * newtot); + gps->points = (bGPDspoint *)MEM_recallocN(gps->points, sizeof(*gps->points) * newtot); + if (gps->dvert != nullptr) { + gps->dvert = (MDeformVert *)MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * newtot); } int j = 0; @@ -1928,7 +1945,7 @@ void BKE_gpencil_stroke_simplify_fixed(bGPdata *gpd, bGPDstroke *gps) if ((i == 0) || (i == gps->totpoints - 1) || ((i % 2) > 0.0)) { memcpy(pt, pt_src, sizeof(bGPDspoint)); - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert_src = &old_dvert[i]; MDeformVert *dvert = &gps->dvert[j]; memcpy(dvert, dvert_src, sizeof(MDeformVert)); @@ -1939,7 +1956,7 @@ void BKE_gpencil_stroke_simplify_fixed(bGPdata *gpd, bGPDstroke *gps) j++; } else { - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert_src = &old_dvert[i]; BKE_gpencil_free_point_weights(dvert_src); } @@ -1964,25 +1981,25 @@ void BKE_gpencil_stroke_simplify_fixed(bGPdata *gpd, bGPDstroke *gps) void BKE_gpencil_stroke_subdivide(bGPdata *gpd, bGPDstroke *gps, int level, int type) { bGPDspoint *temp_points; - MDeformVert *temp_dverts = NULL; - MDeformVert *dvert = NULL; - MDeformVert *dvert_final = NULL; - MDeformVert *dvert_next = NULL; + MDeformVert *temp_dverts = nullptr; + MDeformVert *dvert = nullptr; + MDeformVert *dvert_final = nullptr; + MDeformVert *dvert_next = nullptr; int totnewpoints, oldtotpoints; int i2; for (int s = 0; s < level; s++) { totnewpoints = gps->totpoints - 1; /* duplicate points in a temp area */ - temp_points = MEM_dupallocN(gps->points); + temp_points = (bGPDspoint *)MEM_dupallocN(gps->points); oldtotpoints = gps->totpoints; /* resize the points arrays */ gps->totpoints += totnewpoints; - gps->points = MEM_recallocN(gps->points, sizeof(*gps->points) * gps->totpoints); - if (gps->dvert != NULL) { - temp_dverts = MEM_dupallocN(gps->dvert); - gps->dvert = MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * gps->totpoints); + gps->points = (bGPDspoint *)MEM_recallocN(gps->points, sizeof(*gps->points) * gps->totpoints); + if (gps->dvert != nullptr) { + temp_dverts = (MDeformVert *)MEM_dupallocN(gps->dvert); + gps->dvert = (MDeformVert *)MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * gps->totpoints); } /* move points from last to first to new place */ @@ -2000,7 +2017,7 @@ void BKE_gpencil_stroke_subdivide(bGPdata *gpd, bGPDstroke *gps, int level, int pt_final->runtime.idx_orig = pt->runtime.idx_orig; copy_v4_v4(pt_final->vert_color, pt->vert_color); - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert = &temp_dverts[i]; dvert_final = &gps->dvert[i2]; dvert_final->totweight = dvert->totweight; @@ -2021,17 +2038,17 @@ void BKE_gpencil_stroke_subdivide(bGPdata *gpd, bGPDstroke *gps, int level, int pt_final->strength = interpf(pt->strength, next->strength, 0.5f); CLAMP(pt_final->strength, GPENCIL_STRENGTH_MIN, 1.0f); pt_final->time = interpf(pt->time, next->time, 0.5f); - pt_final->runtime.pt_orig = NULL; + pt_final->runtime.pt_orig = nullptr; pt_final->flag = 0; interp_v4_v4v4(pt_final->vert_color, pt->vert_color, next->vert_color, 0.5f); - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { dvert = &temp_dverts[i]; dvert_next = &temp_dverts[i + 1]; dvert_final = &gps->dvert[i2]; dvert_final->totweight = dvert->totweight; - dvert_final->dw = MEM_dupallocN(dvert->dw); + dvert_final->dw = (MDeformWeight *)MEM_dupallocN(dvert->dw); /* interpolate weight values */ for (int d = 0; d < dvert->totweight; d++) { @@ -2053,7 +2070,7 @@ void BKE_gpencil_stroke_subdivide(bGPdata *gpd, bGPDstroke *gps, int level, int /* Move points to smooth stroke (not simple type). */ if (type != GP_SUBDIV_SIMPLE) { /* duplicate points in a temp area with the new subdivide data */ - temp_points = MEM_dupallocN(gps->points); + temp_points = (bGPDspoint *)MEM_dupallocN(gps->points); /* extreme points are not changed */ for (int i = 0; i < gps->totpoints - 2; i++) { @@ -2091,8 +2108,8 @@ void BKE_gpencil_stroke_merge_distance(bGPdata *gpd, const float threshold, const bool use_unselected) { - bGPDspoint *pt = NULL; - bGPDspoint *pt_next = NULL; + bGPDspoint *pt = nullptr; + bGPDspoint *pt_next = nullptr; float tagged = false; /* Use square distance to speed up loop */ const float th_square = threshold * threshold; @@ -2158,7 +2175,7 @@ void BKE_gpencil_stroke_merge_distance(bGPdata *gpd, BKE_gpencil_stroke_geometry_update(gpd, gps); } -typedef struct GpEdge { +struct GpEdge { uint v1, v2; /* Coordinates. */ float v1_co[3], v2_co[3]; @@ -2167,7 +2184,7 @@ typedef struct GpEdge { /* Direction of the segment. */ float vec[3]; int flag; -} GpEdge; +}; static int gpencil_next_edge( GpEdge *gp_edges, int totedges, GpEdge *gped_init, const float threshold, const bool reverse) @@ -2260,13 +2277,13 @@ static void gpencil_generate_edgeloops(Object *ob, /* Arrays for all edge vertices (forward and backward) that form a edge loop. * This is reused for each edgeloop to create gpencil stroke. */ - uint *stroke = MEM_callocN(sizeof(uint) * me->totedge * 2, __func__); - uint *stroke_fw = MEM_callocN(sizeof(uint) * me->totedge, __func__); - uint *stroke_bw = MEM_callocN(sizeof(uint) * me->totedge, __func__); + uint *stroke = (uint *)MEM_callocN(sizeof(uint) * me->totedge * 2, __func__); + uint *stroke_fw = (uint *)MEM_callocN(sizeof(uint) * me->totedge, __func__); + uint *stroke_bw = (uint *)MEM_callocN(sizeof(uint) * me->totedge, __func__); /* Create array with all edges. */ - GpEdge *gp_edges = MEM_callocN(sizeof(GpEdge) * me->totedge, __func__); - GpEdge *gped = NULL; + GpEdge *gp_edges = (GpEdge *)MEM_callocN(sizeof(GpEdge) * me->totedge, __func__); + GpEdge *gped = nullptr; for (int i = 0; i < me->totedge; i++) { MEdge *ed = &me->medge[i]; gped = &gp_edges[i]; @@ -2319,7 +2336,7 @@ static void gpencil_generate_edgeloops(Object *ob, /* Look backward edges. */ int totbw = gpencil_walk_edge(v_table, gp_edges, me->totedge, stroke_bw, e, angle, true); - BLI_ghash_free(v_table, NULL, NULL); + BLI_ghash_free(v_table, nullptr, nullptr); /* Join both arrays. */ int array_len = 0; @@ -2421,7 +2438,7 @@ static int gpencil_material_find_index_by_name(Object *ob, const char *name) { for (int i = 0; i < ob->totcol; i++) { Material *ma = BKE_object_material_get(ob, i + 1); - if ((ma != NULL) && (ma->gp_style != NULL) && (STREQ(ma->id.name + 2, name))) { + if ((ma != nullptr) && (ma->gp_style != nullptr) && (STREQ(ma->id.name + 2, name))) { return i; } } @@ -2472,7 +2489,7 @@ bool BKE_gpencil_convert_mesh(Main *bmain, const bool use_seams, const bool use_faces) { - if (ELEM(NULL, ob_gp, ob_mesh) || (ob_gp->type != OB_GPENCIL) || (ob_gp->data == NULL)) { + if (ELEM(nullptr, ob_gp, ob_mesh) || (ob_gp->type != OB_GPENCIL) || (ob_gp->data == nullptr)) { return false; } @@ -2480,9 +2497,9 @@ bool BKE_gpencil_convert_mesh(Main *bmain, /* Use evaluated data to get mesh with all modifiers on top. */ Object *ob_eval = (Object *)DEG_get_evaluated_object(depsgraph, ob_mesh); - Mesh *me_eval = BKE_object_get_evaluated_mesh(ob_eval); - MPoly *mp, *mpoly = me_eval->mpoly; - MLoop *mloop = me_eval->mloop; + const Mesh *me_eval = BKE_object_get_evaluated_mesh(ob_eval); + const MPoly *mpoly = me_eval->mpoly; + const MLoop *mloop = me_eval->mloop; int mpoly_len = me_eval->totpoly; char element_name[200]; @@ -2509,23 +2526,24 @@ bool BKE_gpencil_convert_mesh(Main *bmain, make_element_name(ob_mesh->id.name + 2, "Fills", 128, element_name); /* Create Layer and Frame. */ bGPDlayer *gpl_fill = BKE_gpencil_layer_named_get(gpd, element_name); - if (gpl_fill == NULL) { + if (gpl_fill == nullptr) { gpl_fill = BKE_gpencil_layer_addnew(gpd, element_name, true, false); } bGPDframe *gpf_fill = BKE_gpencil_layer_frame_get( gpl_fill, CFRA + frame_offset, GP_GETFRAME_ADD_NEW); int i; - for (i = 0, mp = mpoly; i < mpoly_len; i++, mp++) { - MLoop *ml = &mloop[mp->loopstart]; + for (i = 0; i < mpoly_len; i++) { + const MPoly *mp = &mpoly[i]; + /* Find material. */ int mat_idx = 0; Material *ma = BKE_object_material_get(ob_mesh, mp->mat_nr + 1); make_element_name( - ob_mesh->id.name + 2, (ma != NULL) ? ma->id.name + 2 : "Fill", 64, element_name); + ob_mesh->id.name + 2, (ma != nullptr) ? ma->id.name + 2 : "Fill", 64, element_name); mat_idx = BKE_gpencil_material_find_index_by_name_prefix(ob_gp, element_name); if (mat_idx == -1) { float color[4]; - if (ma != NULL) { + if (ma != nullptr) { copy_v3_v3(color, &ma->r); color[3] = 1.0f; } @@ -2539,8 +2557,10 @@ bool BKE_gpencil_convert_mesh(Main *bmain, gps_fill->flag |= GP_STROKE_CYCLIC; /* Add points to strokes. */ - for (int j = 0; j < mp->totloop; j++, ml++) { - MVert *mv = &me_eval->mvert[ml->v]; + for (int j = 0; j < mp->totloop; j++) { + const MLoop *ml = &mloop[mp->loopstart + j]; + const MVert *mv = &me_eval->mvert[ml->v]; + bGPDspoint *pt = &gps_fill->points[j]; copy_v3_v3(&pt->x, mv->co); mul_m4_v3(matrix, &pt->x); @@ -2562,7 +2582,7 @@ bool BKE_gpencil_convert_mesh(Main *bmain, /* Create Layer and Frame. */ bGPDlayer *gpl_stroke = BKE_gpencil_layer_named_get(gpd, element_name); - if (gpl_stroke == NULL) { + if (gpl_stroke == nullptr) { gpl_stroke = BKE_gpencil_layer_addnew(gpd, element_name, true, false); } bGPDframe *gpf_stroke = BKE_gpencil_layer_frame_get( @@ -2584,7 +2604,7 @@ bool BKE_gpencil_convert_mesh(Main *bmain, */ void BKE_gpencil_transform(bGPdata *gpd, const float mat[4][4]) { - if (gpd == NULL) { + if (gpd == nullptr) { return; } @@ -2620,7 +2640,7 @@ int BKE_gpencil_stroke_point_count(const bGPdata *gpd) { int total_points = 0; - if (gpd == NULL) { + if (gpd == nullptr) { return 0; } @@ -2645,7 +2665,7 @@ int BKE_gpencil_stroke_point_count(const bGPdata *gpd) /* Used for "move only origins" in object_data_transform.c */ void BKE_gpencil_point_coords_get(bGPdata *gpd, GPencilPointCoordinates *elem_data) { - if (gpd == NULL) { + if (gpd == nullptr) { return; } @@ -2676,7 +2696,7 @@ void BKE_gpencil_point_coords_get(bGPdata *gpd, GPencilPointCoordinates *elem_da /* Used for "move only origins" in object_data_transform.c */ void BKE_gpencil_point_coords_apply(bGPdata *gpd, const GPencilPointCoordinates *elem_data) { - if (gpd == NULL) { + if (gpd == nullptr) { return; } @@ -2712,7 +2732,7 @@ void BKE_gpencil_point_coords_apply_with_mat4(bGPdata *gpd, const GPencilPointCoordinates *elem_data, const float mat[4][4]) { - if (gpd == NULL) { + if (gpd == nullptr) { return; } @@ -2813,24 +2833,24 @@ void BKE_gpencil_stroke_flip(bGPDstroke *gps) * that should be kept when splitting up a stroke. Used in: * gpencil_stroke_delete_tagged_points() */ -typedef struct tGPDeleteIsland { +struct tGPDeleteIsland { int start_idx; int end_idx; -} tGPDeleteIsland; +}; static void gpencil_stroke_join_islands(bGPdata *gpd, bGPDframe *gpf, bGPDstroke *gps_first, bGPDstroke *gps_last) { - bGPDspoint *pt = NULL; - bGPDspoint *pt_final = NULL; + bGPDspoint *pt = nullptr; + bGPDspoint *pt_final = nullptr; const int totpoints = gps_first->totpoints + gps_last->totpoints; /* create new stroke */ bGPDstroke *join_stroke = BKE_gpencil_stroke_duplicate(gps_first, false, true); - join_stroke->points = MEM_callocN(sizeof(bGPDspoint) * totpoints, __func__); + join_stroke->points = (bGPDspoint *)MEM_callocN(sizeof(bGPDspoint) * totpoints, __func__); join_stroke->totpoints = totpoints; join_stroke->flag &= ~GP_STROKE_CYCLIC; @@ -2863,17 +2883,17 @@ static void gpencil_stroke_join_islands(bGPdata *gpd, } /* Copy over vertex weight data (if available) */ - if ((gps_first->dvert != NULL) || (gps_last->dvert != NULL)) { - join_stroke->dvert = MEM_callocN(sizeof(MDeformVert) * totpoints, __func__); - MDeformVert *dvert_src = NULL; - MDeformVert *dvert_dst = NULL; + if ((gps_first->dvert != nullptr) || (gps_last->dvert != nullptr)) { + join_stroke->dvert = (MDeformVert *)MEM_callocN(sizeof(MDeformVert) * totpoints, __func__); + MDeformVert *dvert_src = nullptr; + MDeformVert *dvert_dst = nullptr; /* Copy weights (last before). */ e1 = 0; e2 = 0; for (int i = 0; i < totpoints; i++) { dvert_dst = &join_stroke->dvert[i]; - dvert_src = NULL; + dvert_src = nullptr; if (i < gps_last->totpoints) { if (gps_last->dvert) { dvert_src = &gps_last->dvert[e1]; @@ -2888,7 +2908,7 @@ static void gpencil_stroke_join_islands(bGPdata *gpd, } if ((dvert_src) && (dvert_src->dw)) { - dvert_dst->dw = MEM_dupallocN(dvert_src->dw); + dvert_dst->dw = (MDeformWeight *)MEM_dupallocN(dvert_src->dw); } } } @@ -2929,13 +2949,13 @@ bGPDstroke *BKE_gpencil_stroke_delete_tagged_points(bGPdata *gpd, bool select, int limit) { - tGPDeleteIsland *islands = MEM_callocN(sizeof(tGPDeleteIsland) * (gps->totpoints + 1) / 2, - "gp_point_islands"); + tGPDeleteIsland *islands = (tGPDeleteIsland *)MEM_callocN( + sizeof(tGPDeleteIsland) * (gps->totpoints + 1) / 2, "gp_point_islands"); bool in_island = false; int num_islands = 0; - bGPDstroke *new_stroke = NULL; - bGPDstroke *gps_first = NULL; + bGPDstroke *new_stroke = nullptr; + bGPDstroke *gps_first = nullptr; const bool is_cyclic = (bool)(gps->flag & GP_STROKE_CYCLIC); /* First Pass: Identify start/end of islands */ @@ -2977,7 +2997,7 @@ bGPDstroke *BKE_gpencil_stroke_delete_tagged_points(bGPdata *gpd, new_stroke = BKE_gpencil_stroke_duplicate(gps, false, true); /* if cyclic and first stroke, save to join later */ - if ((is_cyclic) && (gps_first == NULL)) { + if ((is_cyclic) && (gps_first == nullptr)) { gps_first = new_stroke; } @@ -2987,17 +3007,17 @@ bGPDstroke *BKE_gpencil_stroke_delete_tagged_points(bGPdata *gpd, new_stroke->totpoints = island->end_idx - island->start_idx + 1; /* Copy over the relevant point data */ - new_stroke->points = MEM_callocN(sizeof(bGPDspoint) * new_stroke->totpoints, - "gp delete stroke fragment"); + new_stroke->points = (bGPDspoint *)MEM_callocN(sizeof(bGPDspoint) * new_stroke->totpoints, + "gp delete stroke fragment"); memcpy(new_stroke->points, gps->points + island->start_idx, sizeof(bGPDspoint) * new_stroke->totpoints); /* Copy over vertex weight data (if available) */ - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { /* Copy over the relevant vertex-weight points */ - new_stroke->dvert = MEM_callocN(sizeof(MDeformVert) * new_stroke->totpoints, - "gp delete stroke fragment weight"); + new_stroke->dvert = (MDeformVert *)MEM_callocN(sizeof(MDeformVert) * new_stroke->totpoints, + "gp delete stroke fragment weight"); memcpy(new_stroke->dvert, gps->dvert + island->start_idx, sizeof(MDeformVert) * new_stroke->totpoints); @@ -3008,7 +3028,7 @@ bGPDstroke *BKE_gpencil_stroke_delete_tagged_points(bGPdata *gpd, MDeformVert *dvert_src = &gps->dvert[e]; MDeformVert *dvert_dst = &new_stroke->dvert[i]; if (dvert_src->dw) { - dvert_dst->dw = MEM_dupallocN(dvert_src->dw); + dvert_dst->dw = (MDeformWeight *)MEM_dupallocN(dvert_src->dw); } e++; } @@ -3042,7 +3062,7 @@ bGPDstroke *BKE_gpencil_stroke_delete_tagged_points(bGPdata *gpd, /* Add new stroke to the frame or delete if below limit */ if ((limit > 0) && (new_stroke->totpoints <= limit)) { if (gps_first == new_stroke) { - gps_first = NULL; + gps_first = nullptr; } BKE_gpencil_free_stroke(new_stroke); } @@ -3059,7 +3079,7 @@ bGPDstroke *BKE_gpencil_stroke_delete_tagged_points(bGPdata *gpd, } } /* if cyclic, need to join last stroke with first stroke */ - if ((is_cyclic) && (gps_first != NULL) && (gps_first != new_stroke)) { + if ((is_cyclic) && (gps_first != nullptr) && (gps_first != new_stroke)) { gpencil_stroke_join_islands(gpd, gpf, gps_first, new_stroke); } } @@ -3081,13 +3101,13 @@ void BKE_gpencil_curve_delete_tagged_points(bGPdata *gpd, bGPDcurve *gpc, int tag_flags) { - if (gpc == NULL) { + if (gpc == nullptr) { return; } const bool is_cyclic = gps->flag & GP_STROKE_CYCLIC; const int idx_last = gpc->tot_curve_points - 1; - bGPDstroke *gps_first = NULL; - bGPDstroke *gps_last = NULL; + bGPDstroke *gps_first = nullptr; + bGPDstroke *gps_last = nullptr; int idx_start = 0; int idx_end = 0; @@ -3118,11 +3138,11 @@ void BKE_gpencil_curve_delete_tagged_points(bGPdata *gpd, } bGPDstroke *new_stroke = BKE_gpencil_stroke_duplicate(gps, false, false); - new_stroke->points = NULL; + new_stroke->points = nullptr; new_stroke->flag &= ~GP_STROKE_CYCLIC; new_stroke->editcurve = BKE_gpencil_stroke_editcurve_new(island_length); - if (gps_first == NULL) { + if (gps_first == nullptr) { gps_first = new_stroke; } @@ -3150,15 +3170,15 @@ void BKE_gpencil_curve_delete_tagged_points(bGPdata *gpd, } /* join first and last stroke if cyclic */ - if (is_cyclic && gps_first != NULL && gps_last != NULL && gps_first != gps_last) { + if (is_cyclic && gps_first != nullptr && gps_last != nullptr && gps_first != gps_last) { bGPDcurve *gpc_first = gps_first->editcurve; bGPDcurve *gpc_last = gps_last->editcurve; int first_tot_points = gpc_first->tot_curve_points; int old_tot_points = gpc_last->tot_curve_points; gpc_last->tot_curve_points = first_tot_points + old_tot_points; - gpc_last->curve_points = MEM_recallocN(gpc_last->curve_points, - sizeof(bGPDcurve_point) * gpc_last->tot_curve_points); + gpc_last->curve_points = (bGPDcurve_point *)MEM_recallocN( + gpc_last->curve_points, sizeof(bGPDcurve_point) * gpc_last->tot_curve_points); /* copy data from first to last */ memcpy(gpc_last->curve_points + old_tot_points, gpc_first->curve_points, @@ -3191,14 +3211,16 @@ static void gpencil_stroke_copy_point(bGPDstroke *gps, { bGPDspoint *newpoint; - gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1)); - if (gps->dvert != NULL) { - gps->dvert = MEM_reallocN(gps->dvert, sizeof(MDeformVert) * (gps->totpoints + 1)); + gps->points = (bGPDspoint *)MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1)); + if (gps->dvert != nullptr) { + gps->dvert = (MDeformVert *)MEM_reallocN(gps->dvert, + sizeof(MDeformVert) * (gps->totpoints + 1)); } else { /* If destination has weight add weight to origin. */ - if (dvert != NULL) { - gps->dvert = MEM_callocN(sizeof(MDeformVert) * (gps->totpoints + 1), __func__); + if (dvert != nullptr) { + gps->dvert = (MDeformVert *)MEM_callocN(sizeof(MDeformVert) * (gps->totpoints + 1), + __func__); } } @@ -3214,16 +3236,16 @@ static void gpencil_stroke_copy_point(bGPDstroke *gps, newpoint->time = point->time + deltatime; copy_v4_v4(newpoint->vert_color, point->vert_color); - if (gps->dvert != NULL) { + if (gps->dvert != nullptr) { MDeformVert *newdvert = &gps->dvert[gps->totpoints - 1]; - if (dvert != NULL) { + if (dvert != nullptr) { newdvert->totweight = dvert->totweight; - newdvert->dw = MEM_dupallocN(dvert->dw); + newdvert->dw = (MDeformWeight *)MEM_dupallocN(dvert->dw); } else { newdvert->totweight = 0; - newdvert->dw = NULL; + newdvert->dw = nullptr; } } } @@ -3241,7 +3263,7 @@ void BKE_gpencil_stroke_join(bGPDstroke *gps_a, float deltatime = 0.0f; /* sanity checks */ - if (ELEM(NULL, gps_a, gps_b)) { + if (ELEM(nullptr, gps_a, gps_b)) { return; } @@ -3303,11 +3325,11 @@ void BKE_gpencil_stroke_join(bGPDstroke *gps_a, point = gps_a->points[gps_a->totpoints - 1]; deltatime = point.time; - gpencil_stroke_copy_point(gps_a, NULL, &point, delta, 0.0f, 0.0f, 0.0f); + gpencil_stroke_copy_point(gps_a, nullptr, &point, delta, 0.0f, 0.0f, 0.0f); /* 2nd: add one head point to finish invisible area */ point = gps_b->points[0]; - gpencil_stroke_copy_point(gps_a, NULL, &point, delta, 0.0f, 0.0f, deltatime); + gpencil_stroke_copy_point(gps_a, nullptr, &point, delta, 0.0f, 0.0f, deltatime); } const float ratio = (fit_thickness && gps_a->thickness > 0.0f) ? @@ -3316,7 +3338,7 @@ void BKE_gpencil_stroke_join(bGPDstroke *gps_a, /* 3rd: add all points */ for (i = 0, pt = gps_b->points; i < gps_b->totpoints && pt; i++, pt++) { - MDeformVert *dvert = (gps_b->dvert) ? &gps_b->dvert[i] : NULL; + MDeformVert *dvert = (gps_b->dvert) ? &gps_b->dvert[i] : nullptr; gpencil_stroke_copy_point( gps_a, dvert, pt, delta, pt->pressure * ratio, pt->strength, deltatime); } @@ -3335,16 +3357,16 @@ void BKE_gpencil_stroke_copy_to_keyframes( if (gpf->framenum != cfra) { bGPDframe *gpf_new = BKE_gpencil_layer_frame_find(gpl, cfra); - if (gpf_new == NULL) { + if (gpf_new == nullptr) { gpf_new = BKE_gpencil_frame_addnew(gpl, cfra); } - if (gpf_new == NULL) { + if (gpf_new == nullptr) { continue; } bGPDstroke *gps_new = BKE_gpencil_stroke_duplicate(gps, true, true); - if (gps_new == NULL) { + if (gps_new == nullptr) { continue; } @@ -3358,38 +3380,38 @@ void BKE_gpencil_stroke_copy_to_keyframes( } /* Free hash table. */ - BLI_ghash_free(frame_list, NULL, NULL); + BLI_ghash_free(frame_list, nullptr, nullptr); } /* Stroke Uniform Subdivide ------------------------------------- */ -typedef struct tSamplePoint { +struct tSamplePoint { struct tSamplePoint *next, *prev; float x, y, z; float pressure, strength, time; float vertex_color[4]; struct MDeformWeight *dw; int totweight; -} tSamplePoint; +}; -typedef struct tSampleEdge { +struct tSampleEdge { float length_sq; tSamplePoint *from; tSamplePoint *to; -} tSampleEdge; +}; /* Helper: creates a tSamplePoint from a bGPDspoint and (optionally) a MDeformVert. */ static tSamplePoint *new_sample_point_from_gp_point(const bGPDspoint *pt, const MDeformVert *dvert) { - tSamplePoint *new_pt = MEM_callocN(sizeof(tSamplePoint), __func__); + tSamplePoint *new_pt = (tSamplePoint *)MEM_callocN(sizeof(tSamplePoint), __func__); copy_v3_v3(&new_pt->x, &pt->x); new_pt->pressure = pt->pressure; new_pt->strength = pt->strength; new_pt->time = pt->time; copy_v4_v4((float *)&new_pt->vertex_color, (float *)&pt->vert_color); - if (dvert != NULL) { + if (dvert != nullptr) { new_pt->totweight = dvert->totweight; - new_pt->dw = MEM_callocN(sizeof(MDeformWeight) * new_pt->totweight, __func__); + new_pt->dw = (MDeformWeight *)MEM_callocN(sizeof(MDeformWeight) * new_pt->totweight, __func__); for (uint i = 0; i < new_pt->totweight; ++i) { MDeformWeight *dw = &new_pt->dw[i]; MDeformWeight *dw_from = &dvert->dw[i]; @@ -3404,7 +3426,7 @@ static tSamplePoint *new_sample_point_from_gp_point(const bGPDspoint *pt, const * the edge. */ static tSampleEdge *new_sample_edge_from_sample_points(tSamplePoint *from, tSamplePoint *to) { - tSampleEdge *new_edge = MEM_callocN(sizeof(tSampleEdge), __func__); + tSampleEdge *new_edge = (tSampleEdge *)MEM_callocN(sizeof(tSampleEdge), __func__); new_edge->from = from; new_edge->to = to; new_edge->length_sq = len_squared_v3v3(&from->x, &to->x); @@ -3426,27 +3448,27 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, const bool select) { /* Stroke needs at least two points and strictly less points than the target number. */ - if (gps == NULL || gps->totpoints < 2 || gps->totpoints >= target_number) { + if (gps == nullptr || gps->totpoints < 2 || gps->totpoints >= target_number) { return; } const int totpoints = gps->totpoints; - const bool has_dverts = (gps->dvert != NULL); + const bool has_dverts = (gps->dvert != nullptr); const bool is_cyclic = (gps->flag & GP_STROKE_CYCLIC); - ListBase points = {NULL, NULL}; + ListBase points = {nullptr, nullptr}; Heap *edges = BLI_heap_new(); /* Add all points into list. */ for (uint32_t i = 0; i < totpoints; ++i) { bGPDspoint *pt = &gps->points[i]; - MDeformVert *dvert = has_dverts ? &gps->dvert[i] : NULL; + MDeformVert *dvert = has_dverts ? &gps->dvert[i] : nullptr; tSamplePoint *sp = new_sample_point_from_gp_point(pt, dvert); BLI_addtail(&points, sp); } /* Iterate over edges and insert them into the heap. */ - for (tSamplePoint *pt = ((tSamplePoint *)points.first)->next; pt != NULL; pt = pt->next) { + for (tSamplePoint *pt = ((tSamplePoint *)points.first)->next; pt != nullptr; pt = pt->next) { tSampleEdge *se = new_sample_edge_from_sample_points(pt->prev, pt); /* BLI_heap is a min-heap, but we need the largest key to be at the top, so we take the * negative of the squared length. */ @@ -3454,8 +3476,8 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, } if (is_cyclic) { - tSamplePoint *sp_first = points.first; - tSamplePoint *sp_last = points.last; + tSamplePoint *sp_first = (tSamplePoint *)points.first; + tSamplePoint *sp_last = (tSamplePoint *)points.last; tSampleEdge *se = new_sample_edge_from_sample_points(sp_last, sp_first); BLI_heap_insert(edges, -(se->length_sq), se); } @@ -3464,12 +3486,12 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, BLI_assert(num_points_needed > 0); while (num_points_needed > 0) { - tSampleEdge *se = BLI_heap_pop_min(edges); + tSampleEdge *se = (tSampleEdge *)BLI_heap_pop_min(edges); tSamplePoint *sp = se->from; tSamplePoint *sp_next = se->to; /* Subdivide the edge. */ - tSamplePoint *new_sp = MEM_callocN(sizeof(tSamplePoint), __func__); + tSamplePoint *new_sp = (tSamplePoint *)MEM_callocN(sizeof(tSamplePoint), __func__); interp_v3_v3v3(&new_sp->x, &sp->x, &sp_next->x, 0.5f); new_sp->pressure = interpf(sp->pressure, sp_next->pressure, 0.5f); new_sp->strength = interpf(sp->strength, sp_next->strength, 0.5f); @@ -3480,7 +3502,8 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, 0.5f); if (sp->dw && sp_next->dw) { new_sp->totweight = MIN2(sp->totweight, sp_next->totweight); - new_sp->dw = MEM_callocN(sizeof(MDeformWeight) * new_sp->totweight, __func__); + new_sp->dw = (MDeformWeight *)MEM_callocN(sizeof(MDeformWeight) * new_sp->totweight, + __func__); for (uint32_t i = 0; i < new_sp->totweight; ++i) { MDeformWeight *dw = &new_sp->dw[i]; MDeformWeight *dw_from = &sp->dw[i]; @@ -3504,13 +3527,13 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, BLI_heap_free(edges, (HeapFreeFP)MEM_freeN); gps->totpoints = target_number; - gps->points = MEM_recallocN(gps->points, sizeof(bGPDspoint) * gps->totpoints); + gps->points = (bGPDspoint *)MEM_recallocN(gps->points, sizeof(bGPDspoint) * gps->totpoints); if (has_dverts) { - gps->dvert = MEM_recallocN(gps->dvert, sizeof(MDeformVert) * gps->totpoints); + gps->dvert = (MDeformVert *)MEM_recallocN(gps->dvert, sizeof(MDeformVert) * gps->totpoints); } /* Convert list back to stroke point array. */ - tSamplePoint *sp = points.first; + tSamplePoint *sp = (tSamplePoint *)points.first; for (uint32_t i = 0; i < gps->totpoints && sp; ++i, sp = sp->next) { bGPDspoint *pt = &gps->points[i]; MDeformVert *dvert = &gps->dvert[i]; @@ -3523,7 +3546,7 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, if (sp->dw) { dvert->totweight = sp->totweight; - dvert->dw = MEM_callocN(sizeof(MDeformWeight) * dvert->totweight, __func__); + dvert->dw = (MDeformWeight *)MEM_callocN(sizeof(MDeformWeight) * dvert->totweight, __func__); for (uint32_t j = 0; j < dvert->totweight; ++j) { MDeformWeight *dw = &dvert->dw[j]; MDeformWeight *dw_from = &sp->dw[j]; @@ -3544,7 +3567,7 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, /* Free the sample points. Important to use the mutable loop here because we are erasing the list * elements. */ LISTBASE_FOREACH_MUTABLE (tSamplePoint *, temp, &points) { - if (temp->dw != NULL) { + if (temp->dw != nullptr) { MEM_freeN(temp->dw); } MEM_SAFE_FREE(temp); @@ -3558,7 +3581,7 @@ void BKE_gpencil_stroke_uniform_subdivide(bGPdata *gpd, * Stroke to view space * Transforms a stroke to view space. This allows for manipulations in 2D but also easy conversion * back to 3D. - * Note: also takes care of parent space transform + * NOTE: also takes care of parent space transform */ void BKE_gpencil_stroke_to_view_space(RegionView3D *rv3d, bGPDstroke *gps, @@ -3577,7 +3600,7 @@ void BKE_gpencil_stroke_to_view_space(RegionView3D *rv3d, * Stroke from view space * Transforms a stroke from view space back to world space. Inverse of * BKE_gpencil_stroke_to_view_space - * Note: also takes care of parent space transform + * NOTE: also takes care of parent space transform */ void BKE_gpencil_stroke_from_view_space(RegionView3D *rv3d, bGPDstroke *gps, @@ -3596,14 +3619,14 @@ void BKE_gpencil_stroke_from_view_space(RegionView3D *rv3d, /* ----------------------------------------------------------------------------- */ /* Stroke to perimeter */ -typedef struct tPerimeterPoint { +struct tPerimeterPoint { struct tPerimeterPoint *next, *prev; float x, y, z; -} tPerimeterPoint; +}; static tPerimeterPoint *new_perimeter_point(const float pt[3]) { - tPerimeterPoint *new_pt = MEM_callocN(sizeof(tPerimeterPoint), __func__); + tPerimeterPoint *new_pt = (tPerimeterPoint *)MEM_callocN(sizeof(tPerimeterPoint), __func__); copy_v3_v3(&new_pt->x, pt); return new_pt; } @@ -3766,14 +3789,14 @@ static ListBase *gpencil_stroke_perimeter_ex(const bGPdata *gpd, { /* sanity check */ if (gps->totpoints < 1) { - return NULL; + return nullptr; } float defaultpixsize = 1000.0f / gpd->pixfactor; float stroke_radius = ((gps->thickness + gpl->line_change) / defaultpixsize) / 2.0f; - ListBase *perimeter_right_side = MEM_callocN(sizeof(ListBase), __func__); - ListBase *perimeter_left_side = MEM_callocN(sizeof(ListBase), __func__); + ListBase *perimeter_right_side = (ListBase *)MEM_callocN(sizeof(ListBase), __func__); + ListBase *perimeter_left_side = (ListBase *)MEM_callocN(sizeof(ListBase), __func__); int num_perimeter_points = 0; bGPDspoint *first = &gps->points[0]; @@ -4013,7 +4036,7 @@ bGPDstroke *BKE_gpencil_stroke_perimeter_from_view(struct RegionView3D *rv3d, const float diff_mat[4][4]) { if (gps->totpoints == 0) { - return NULL; + return nullptr; } bGPDstroke *gps_temp = BKE_gpencil_stroke_duplicate(gps, true, false); const bool cyclic = ((gps_temp->flag & GP_STROKE_CYCLIC) != 0); @@ -4021,8 +4044,8 @@ bGPDstroke *BKE_gpencil_stroke_perimeter_from_view(struct RegionView3D *rv3d, /* If Cyclic, add a new point. */ if (cyclic && (gps_temp->totpoints > 1)) { gps_temp->totpoints++; - gps_temp->points = MEM_recallocN(gps_temp->points, - sizeof(*gps_temp->points) * gps_temp->totpoints); + gps_temp->points = (bGPDspoint *)MEM_recallocN( + gps_temp->points, sizeof(*gps_temp->points) * gps_temp->totpoints); bGPDspoint *pt_src = &gps_temp->points[0]; bGPDspoint *pt_dst = &gps_temp->points[gps_temp->totpoints - 1]; copy_v3_v3(&pt_dst->x, &pt_src->x); @@ -4038,7 +4061,7 @@ bGPDstroke *BKE_gpencil_stroke_perimeter_from_view(struct RegionView3D *rv3d, gpd, gpl, gps_temp, subdivisions, &num_perimeter_points); if (num_perimeter_points == 0) { - return NULL; + return nullptr; } /* Create new stroke. */ diff --git a/source/blender/blenkernel/intern/gpencil_modifier.c b/source/blender/blenkernel/intern/gpencil_modifier.c index 9f5f70ab2ba..4db527e5b42 100644 --- a/source/blender/blenkernel/intern/gpencil_modifier.c +++ b/source/blender/blenkernel/intern/gpencil_modifier.c @@ -257,9 +257,13 @@ bool BKE_gpencil_is_first_lineart_in_stack(const Object *ob, const GpencilModifi return false; } -/* apply time modifiers */ -static int gpencil_time_modifier( - Depsgraph *depsgraph, Scene *scene, Object *ob, bGPDlayer *gpl, int cfra, bool is_render) +/* Get Time modifier frame number. */ +int BKE_gpencil_time_modifier_cfra(Depsgraph *depsgraph, + Scene *scene, + Object *ob, + bGPDlayer *gpl, + const int cfra, + const bool is_render) { bGPdata *gpd = ob->data; const bool is_edit = GPENCIL_ANY_EDIT_MODE(gpd); @@ -269,7 +273,7 @@ static int gpencil_time_modifier( if (GPENCIL_MODIFIER_ACTIVE(md, is_render)) { const GpencilModifierTypeInfo *mti = BKE_gpencil_modifier_get_info(md->type); - if ((GPENCIL_MODIFIER_EDIT(md, is_edit)) && (!is_render)) { + if (GPENCIL_MODIFIER_EDIT(md, is_edit) && (!is_render)) { continue; } @@ -350,7 +354,7 @@ GpencilModifierData *BKE_gpencil_modifier_new(int type) const GpencilModifierTypeInfo *mti = BKE_gpencil_modifier_get_info(type); GpencilModifierData *md = MEM_callocN(mti->struct_size, mti->struct_name); - /* note, this name must be made unique later */ + /* NOTE: this name must be made unique later. */ BLI_strncpy(md->name, DATA_(mti->name), sizeof(md->name)); md->type = type; @@ -665,7 +669,7 @@ static int gpencil_remap_time_get(Depsgraph *depsgraph, Scene *scene, Object *ob int remap_cfra = cfra_eval; if (time_remap) { - remap_cfra = gpencil_time_modifier(depsgraph, scene, ob, gpl, cfra_eval, is_render); + remap_cfra = BKE_gpencil_time_modifier_cfra(depsgraph, scene, ob, gpl, cfra_eval, is_render); } return remap_cfra; @@ -834,7 +838,7 @@ void BKE_gpencil_modifiers_calc(Depsgraph *depsgraph, Scene *scene, Object *ob) if (GPENCIL_MODIFIER_ACTIVE(md, is_render)) { const GpencilModifierTypeInfo *mti = BKE_gpencil_modifier_get_info(md->type); - if ((GPENCIL_MODIFIER_EDIT(md, is_edit)) && (!is_render)) { + if (GPENCIL_MODIFIER_EDIT(md, is_edit) && (!is_render)) { continue; } diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c index a67e78ceea0..7a88a00c44f 100644 --- a/source/blender/blenkernel/intern/idprop.c +++ b/source/blender/blenkernel/intern/idprop.c @@ -186,7 +186,7 @@ void IDP_ResizeIDPArray(IDProperty *prop, int newlen) } } - /* - Note: This code comes from python, here's the corresponding comment. - */ + /* NOTE: This code comes from python, here's the corresponding comment. */ /* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long @@ -240,7 +240,7 @@ void IDP_ResizeArray(IDProperty *prop, int newlen) return; } - /* - Note: This code comes from python, here's the corresponding comment. - */ + /* NOTE: This code comes from python, here's the corresponding comment. */ /* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long @@ -942,7 +942,7 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char * prop = MEM_callocN(sizeof(IDProperty), "IDProperty string"); if (val->string.subtype == IDP_STRING_SUB_BYTE) { - /* note, intentionally not null terminated */ + /* NOTE: Intentionally not null terminated. */ if (st == NULL) { prop->data.pointer = MEM_mallocN(DEFAULT_ALLOC_FOR_NULL_STRINGS, "id property string 1"); *IDP_String(prop) = '\0'; @@ -1183,7 +1183,7 @@ static void IDP_DirectLinkIDPArray(IDProperty *prop, BlendDataReader *reader) IDProperty *array = (IDProperty *)prop->data.pointer; - /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared + /* NOTE:, idp-arrays didn't exist in 2.4x, so the pointer will be cleared * there's not really anything we can do to correct this, at least don't crash */ if (array == NULL) { prop->len = 0; @@ -1274,7 +1274,7 @@ static void IDP_DirectLinkProperty(IDProperty *prop, BlendDataReader *reader) * IDP are way too polymorphic to do it safely. */ printf( "%s: found unknown IDProperty type %d, reset to Integer one !\n", __func__, prop->type); - /* Note: we do not attempt to free unknown prop, we have no way to know how to do that! */ + /* NOTE: we do not attempt to free unknown prop, we have no way to know how to do that! */ prop->type = IDP_INT; prop->subtype = 0; IDP_Int(prop) = 0; diff --git a/source/blender/blenkernel/intern/idprop_utils.c b/source/blender/blenkernel/intern/idprop_utils.c index 433f0e97844..0cc212e1880 100644 --- a/source/blender/blenkernel/intern/idprop_utils.c +++ b/source/blender/blenkernel/intern/idprop_utils.c @@ -96,7 +96,7 @@ static void idp_str_append_escape(struct ReprState *state, static void idp_repr_fn_recursive(struct ReprState *state, const IDProperty *prop) { - /* Note: 'strlen' will be calculated at compile time for literals. */ + /* NOTE: 'strlen' will be calculated at compile time for literals. */ #define STR_APPEND_STR(str) state->str_append_fn(state->user_data, str, (uint)strlen(str)) #define STR_APPEND_STR_QUOTE(str) idp_str_append_escape(state, str, (uint)strlen(str), true) diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index 740c9b3864c..f4ba1ff8b92 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -640,7 +640,7 @@ void BKE_image_merge(Main *bmain, Image *dest, Image *source) } } -/* note, we could be clever and scale all imbuf's but since some are mipmaps its not so simple */ +/* NOTE: We could be clever and scale all imbuf's but since some are mipmaps its not so simple. */ bool BKE_image_scale(Image *image, int width, int height) { ImBuf *ibuf; @@ -1778,7 +1778,7 @@ static bool do_add_image_extension(char *string, } } else { - BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec"); + BLI_assert_msg(0, "Unsupported jp2 codec was specified in im_format->jp2_codec"); } } else { @@ -1949,7 +1949,7 @@ void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *i im_format->jp2_codec = R_IMF_JP2_CODEC_J2K; } else { - BLI_assert(!"Unsupported jp2 codec was specified in file type"); + BLI_assert_msg(0, "Unsupported jp2 codec was specified in file type"); } } #endif @@ -2323,7 +2323,7 @@ void BKE_image_stamp_buf(Scene *scene, stampdata_from_template(&stamp_data, scene, stamp_data_template, do_prefix); } - /* TODO, do_versions */ + /* TODO: do_versions. */ if (scene->r.stamp_font_id < 8) { scene->r.stamp_font_id = 12; } @@ -2867,7 +2867,7 @@ bool BKE_imbuf_alpha_test(ImBuf *ibuf) return false; } -/* note: imf->planes is ignored here, its assumed the image channels +/* NOTE: imf->planes is ignored here, its assumed the image channels * are already set */ void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf) { @@ -3017,7 +3017,7 @@ void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf) ibuf->foptions.flag |= JP2_J2K; } else { - BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec"); + BLI_assert_msg(0, "Unsupported jp2 codec was specified in im_format->jp2_codec"); } } #endif @@ -4540,7 +4540,7 @@ static ImBuf *load_image_single(Image *ima, } /* warning, 'iuser' can be NULL - * note: Image->views was already populated (in image_update_views_format) + * NOTE: Image->views was already populated (in image_update_views_format) */ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra) { @@ -5391,7 +5391,7 @@ void BKE_image_user_frame_calc(Image *ima, ImageUser *iuser, int cfra) } if (ima && ima->gpuframenr != iuser->framenr) { - /* Note: a single texture and refresh doesn't really work when + /* NOTE: a single texture and refresh doesn't really work when * multiple image users may use different frames, this is to * be improved with perhaps a GPU texture cache. */ ima->gpuflag |= IMA_GPU_REFRESH; diff --git a/source/blender/blenkernel/intern/image_save.c b/source/blender/blenkernel/intern/image_save.c index b68cd9e4d2d..9e3d5a162ae 100644 --- a/source/blender/blenkernel/intern/image_save.c +++ b/source/blender/blenkernel/intern/image_save.c @@ -169,7 +169,7 @@ static bool image_save_single(ReportList *reports, } } else { - /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */ + /* TODO: better solution, if a 24bit image is painted onto it may contain alpha. */ if ((opts->im_format.planes == R_IMF_PLANES_RGBA) && /* it has been painted onto */ (ibuf->userflags & IB_BITMAPDIRTY)) { diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index f365e759221..8a70f065e40 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -1135,7 +1135,7 @@ static char *get_rna_access(ID *id, /* special case for rotdiff drivers... we don't need a property for this... */ break; - /* TODO... add other blocktypes... */ + /* TODO: add other block-types. */ default: CLOG_WARN(&LOG, "No path for blocktype %d, adrcode %d yet", blocktype, adrcode); break; @@ -1162,7 +1162,7 @@ static char *get_rna_access(ID *id, /* 'buf' _must_ be initialized in this block */ /* append preceding bits to path */ - /* note, strings are not escapted and they should be! */ + /* NOTE: strings are not escapted and they should be! */ if ((actname && actname[0]) && (constname && constname[0])) { /* Constraint in Pose-Channel */ char actname_esc[sizeof(((bActionChannel *)NULL)->name) * 2]; @@ -1305,7 +1305,7 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) dtar = &dvar->targets[1]; dtar->id = (ID *)idriver->ob; dtar->idtype = ID_OB; - if (idriver->name[0]) { /* xxx... for safety */ + if (idriver->name[0]) { /* XXX: for safety. */ BLI_strncpy( dtar->pchan_name, idriver->name + DRIVER_NAME_OFFS, sizeof(dtar->pchan_name)); } @@ -1358,12 +1358,12 @@ static void fcurve_add_to_list( bActionGroup *agrp = NULL; /* init the temp action */ - memset(&tmp_act, 0, sizeof(bAction)); /* XXX only enable this line if we get errors */ + memset(&tmp_act, 0, sizeof(bAction)); /* XXX: Only enable this line if we get errors. */ tmp_act.groups.first = groups->first; tmp_act.groups.last = groups->last; tmp_act.curves.first = list->first; tmp_act.curves.last = list->last; - /* ... xxx, the other vars don't need to be filled in */ + /* XXX: The other vars don't need to be filled in. */ /* get the group to use */ agrp = BKE_action_group_find_name(&tmp_act, grpname); @@ -2087,7 +2087,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* check if object has any animation data */ if (ob->nlastrips.first) { /* Add AnimData block */ - BKE_animdata_add_id(id); + BKE_animdata_ensure_id(id); /* IPO first to take into any non-NLA'd Object Animation */ if (ob->ipo) { @@ -2109,7 +2109,7 @@ void do_versions_ipos_to_animato(Main *bmain) } else if ((ob->ipo) || (ob->action)) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Action first - so that Action name get conserved */ if (ob->action) { @@ -2133,7 +2133,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* check PoseChannels for constraints with local data */ if (ob->pose) { /* Verify if there's AnimData block */ - BKE_animdata_add_id(id); + BKE_animdata_ensure_id(id); for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { for (con = pchan->constraints.first; con; con = con->next) { @@ -2159,7 +2159,7 @@ void do_versions_ipos_to_animato(Main *bmain) */ if (con->ipo) { /* Verify if there's AnimData block, just in case */ - BKE_animdata_add_id(id); + BKE_animdata_ensure_id(id); /* although this was the constraint's local IPO, we still need to provide con * so that drivers can be added properly... @@ -2176,7 +2176,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* check constraint channels - we need to remove them anyway... */ if (ob->constraintChannels.first) { /* Verify if there's AnimData block */ - BKE_animdata_add_id(id); + BKE_animdata_ensure_id(id); for (conchan = ob->constraintChannels.first; conchan; conchan = conchann) { /* get pointer to next Constraint Channel */ @@ -2217,7 +2217,7 @@ void do_versions_ipos_to_animato(Main *bmain) */ if (key->ipo) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Convert Shapekey data... */ ipo_to_animdata(bmain, id, key->ipo, NULL, NULL, NULL); @@ -2242,7 +2242,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* we're only interested in the IPO */ if (ma->ipo) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Convert Material data... */ ipo_to_animdata(bmain, id, ma->ipo, NULL, NULL, NULL); @@ -2267,7 +2267,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* we're only interested in the IPO */ if (wo->ipo) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Convert World data... */ ipo_to_animdata(bmain, id, wo->ipo, NULL, NULL, NULL); @@ -2288,7 +2288,7 @@ void do_versions_ipos_to_animato(Main *bmain) if (ed && ed->seqbasep) { Sequence *seq; - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); SEQ_ALL_BEGIN (ed, seq) { IpoCurve *icu = (seq->ipo) ? seq->ipo->curve.first : NULL; @@ -2346,7 +2346,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* we're only interested in the IPO */ if (te->ipo) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Convert Texture data... */ ipo_to_animdata(bmain, id, te->ipo, NULL, NULL, NULL); @@ -2371,7 +2371,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* we're only interested in the IPO */ if (ca->ipo) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Convert Camera data... */ ipo_to_animdata(bmain, id, ca->ipo, NULL, NULL, NULL); @@ -2396,7 +2396,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* we're only interested in the IPO */ if (la->ipo) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Convert Light data... */ ipo_to_animdata(bmain, id, la->ipo, NULL, NULL, NULL); @@ -2421,7 +2421,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* we're only interested in the IPO */ if (cu->ipo) { /* Add AnimData block */ - AnimData *adt = BKE_animdata_add_id(id); + AnimData *adt = BKE_animdata_ensure_id(id); /* Convert Curve data... */ ipo_to_animdata(bmain, id, cu->ipo, NULL, NULL, NULL); diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c index 6cc90f86b4a..0f8c9bad798 100644 --- a/source/blender/blenkernel/intern/key.c +++ b/source/blender/blenkernel/intern/key.c @@ -694,7 +694,7 @@ static bool key_pointer_size(const Key *key, const int mode, int *poinsize, int *poinsize = sizeof(float[KEYELEM_ELEM_SIZE_CURVE]); break; default: - BLI_assert(!"invalid 'key->from' ID type"); + BLI_assert_msg(0, "invalid 'key->from' ID type"); return false; } @@ -806,7 +806,7 @@ static void cp_key(const int start, if (freekref) { MEM_freeN(freekref); } - BLI_assert(!"invalid 'cp[1]'"); + BLI_assert_msg(0, "invalid 'cp[1]'"); return; } @@ -984,7 +984,7 @@ static void key_evaluate_relative(const int start, if (freefrom) { MEM_freeN(freefrom); } - BLI_assert(!"invalid 'cp[1]'"); + BLI_assert_msg(0, "invalid 'cp[1]'"); return; } @@ -1204,7 +1204,7 @@ static void do_key(const int start, if (freek4) { MEM_freeN(freek4); } - BLI_assert(!"invalid 'cp[1]'"); + BLI_assert_msg(0, "invalid 'cp[1]'"); return; } @@ -1317,7 +1317,7 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac if (cache) { if (cache->defgroup_weights == NULL) { - int num_defgroup = BLI_listbase_count(&ob->defbase); + int num_defgroup = BKE_object_defgroup_count(ob); cache->defgroup_weights = MEM_callocN(sizeof(*cache->defgroup_weights) * num_defgroup, "cached defgroup weights"); cache->num_defgroup_weights = num_defgroup; @@ -1695,7 +1695,7 @@ void BKE_keyblock_data_set_with_mat4(Key *key, const float mat[4][4]) { if (key->elemsize != sizeof(float[3])) { - BLI_assert(!"Invalid elemsize"); + BLI_assert_msg(0, "Invalid elemsize"); return; } diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c index 1357424d5ff..9875d776d33 100644 --- a/source/blender/blenkernel/intern/lattice.c +++ b/source/blender/blenkernel/intern/lattice.c @@ -87,6 +87,8 @@ static void lattice_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const i lattice_dst->key->from = &lattice_dst->id; } + BKE_defgroup_copy_list(&lattice_dst->vertex_group_names, &lattice_src->vertex_group_names); + if (lattice_src->dvert) { int tot = lattice_src->pntsu * lattice_src->pntsv * lattice_src->pntsw; lattice_dst->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert"); @@ -103,6 +105,8 @@ static void lattice_free_data(ID *id) BKE_lattice_batch_cache_free(lattice); + BLI_freelistN(&lattice->vertex_group_names); + MEM_SAFE_FREE(lattice->def); if (lattice->dvert) { BKE_defvert_array_free(lattice->dvert, lattice->pntsu * lattice->pntsv * lattice->pntsw); @@ -150,6 +154,7 @@ static void lattice_blend_write(BlendWriter *writer, ID *id, const void *id_addr /* direct data */ BLO_write_struct_array(writer, BPoint, lt->pntsu * lt->pntsv * lt->pntsw, lt->def); + BKE_defbase_blend_write(writer, <->vertex_group_names); BKE_defvert_blend_write(writer, lt->pntsu * lt->pntsv * lt->pntsw, lt->dvert); } } @@ -161,6 +166,7 @@ static void lattice_blend_read_data(BlendDataReader *reader, ID *id) BLO_read_data_address(reader, <->dvert); BKE_defvert_blend_read(reader, lt->pntsu * lt->pntsv * lt->pntsw, lt->dvert); + BLO_read_list(reader, <->vertex_group_names); lt->editlatt = NULL; lt->batch_cache = NULL; diff --git a/source/blender/blenkernel/intern/lattice_deform.c b/source/blender/blenkernel/intern/lattice_deform.c index a3133b58a0a..f9437eeaffa 100644 --- a/source/blender/blenkernel/intern/lattice_deform.c +++ b/source/blender/blenkernel/intern/lattice_deform.c @@ -108,11 +108,11 @@ LatticeDeformData *BKE_lattice_deform_data_create(const Object *oblatt, const Ob invert_m4_m4(imat, latmat); } - /* Prefetch latice deform group weights. */ + /* Prefetch lattice deform group weights. */ int defgrp_index = -1; const MDeformVert *dvert = BKE_lattice_deform_verts_get(oblatt); if (lt->vgroup[0] && dvert) { - defgrp_index = BKE_object_defgroup_name_index(oblatt, lt->vgroup); + defgrp_index = BKE_id_defgroup_name_index(<->id, lt->vgroup); if (defgrp_index != -1) { lattice_weights = MEM_malloc_arrayN(sizeof(float), num_points, "lattice_weights"); @@ -364,7 +364,7 @@ static void lattice_deform_coords_impl(const Object *ob_lattice, * We want either a Mesh/Lattice with no derived data, or derived data with deformverts. */ if (defgrp_name && defgrp_name[0] && ob_target && ELEM(ob_target->type, OB_MESH, OB_LATTICE)) { - defgrp_index = BKE_object_defgroup_name_index(ob_target, defgrp_name); + defgrp_index = BKE_id_defgroup_name_index((ID *)ob_target->data, defgrp_name); if (defgrp_index != -1) { /* if there's derived data without deformverts, don't use vgroups */ diff --git a/source/blender/blenkernel/intern/layer.c b/source/blender/blenkernel/intern/layer.c index d49eb0d4da8..730c989abc9 100644 --- a/source/blender/blenkernel/intern/layer.c +++ b/source/blender/blenkernel/intern/layer.c @@ -737,172 +737,193 @@ int BKE_layer_collection_findindex(ViewLayer *view_layer, const LayerCollection * in at least one layer collection. That list is also synchronized here, and * stores state like selection. */ +static void layer_collection_objects_sync(ViewLayer *view_layer, + LayerCollection *layer, + ListBase *r_lb_new_object_bases, + const short collection_restrict, + const short layer_restrict, + const ushort local_collections_bits) +{ + /* No need to sync objects if the collection is excluded. */ + if ((layer->flag & LAYER_COLLECTION_EXCLUDE) != 0) { + return; + } + + LISTBASE_FOREACH (CollectionObject *, cob, &layer->collection->gobject) { + if (cob->ob == NULL) { + continue; + } + + /* Tag linked object as a weak reference so we keep the object + * base pointer on file load and remember hidden state. */ + id_lib_indirect_weak_link(&cob->ob->id); + + void **base_p; + Base *base; + if (BLI_ghash_ensure_p(view_layer->object_bases_hash, cob->ob, &base_p)) { + /* Move from old base list to new base list. Base might have already + * been moved to the new base list and the first/last test ensure that + * case also works. */ + base = *base_p; + if (!ELEM(base, r_lb_new_object_bases->first, r_lb_new_object_bases->last)) { + BLI_remlink(&view_layer->object_bases, base); + BLI_addtail(r_lb_new_object_bases, base); + } + } + else { + /* Create new base. */ + base = object_base_new(cob->ob); + base->local_collections_bits = local_collections_bits; + *base_p = base; + BLI_addtail(r_lb_new_object_bases, base); + } + + if ((collection_restrict & COLLECTION_RESTRICT_VIEWPORT) == 0) { + base->flag_from_collection |= (BASE_ENABLED_VIEWPORT | BASE_VISIBLE_DEPSGRAPH); + if ((layer_restrict & LAYER_COLLECTION_HIDE) == 0) { + base->flag_from_collection |= BASE_VISIBLE_VIEWLAYER; + } + if (((collection_restrict & COLLECTION_RESTRICT_SELECT) == 0)) { + base->flag_from_collection |= BASE_SELECTABLE; + } + } + + if ((collection_restrict & COLLECTION_RESTRICT_RENDER) == 0) { + base->flag_from_collection |= BASE_ENABLED_RENDER; + } + + /* Holdout and indirect only */ + if (layer->flag & LAYER_COLLECTION_HOLDOUT) { + base->flag_from_collection |= BASE_HOLDOUT; + } + if (layer->flag & LAYER_COLLECTION_INDIRECT_ONLY) { + base->flag_from_collection |= BASE_INDIRECT_ONLY; + } + + layer->runtime_flag |= LAYER_COLLECTION_HAS_OBJECTS; + } +} + static void layer_collection_sync(ViewLayer *view_layer, - const ListBase *lb_collections, - ListBase *lb_layer_collections, - ListBase *new_object_bases, - short parent_exclude, - short parent_restrict, - short parent_layer_restrict, - unsigned short parent_local_collections_bits) + const ListBase *lb_children_collections, + ListBase *r_lb_children_layers, + ListBase *r_lb_new_object_bases, + const short parent_layer_flag, + const short parent_collection_restrict, + const short parent_layer_restrict, + const ushort parent_local_collections_bits) { /* TODO: support recovery after removal of intermediate collections, reordering, .. * For local edits we can make editing operating do the appropriate thing, but for * linking we can only sync after the fact. */ /* Remove layer collections that no longer have a corresponding scene collection. */ - LISTBASE_FOREACH_MUTABLE (LayerCollection *, lc, lb_layer_collections) { - /* Note that ID remap can set lc->collection to NULL when deleting collections. */ - Collection *collection = (lc->collection) ? - BLI_findptr(lb_collections, - lc->collection, - offsetof(CollectionChild, collection)) : - NULL; - - if (!collection) { - if (lc == view_layer->active_collection) { + LISTBASE_FOREACH_MUTABLE (LayerCollection *, child_layer, r_lb_children_layers) { + /* Note that ID remap can set child_layer->collection to NULL when deleting collections. */ + Collection *child_collection = (child_layer->collection != NULL) ? + BLI_findptr(lb_children_collections, + child_layer->collection, + offsetof(CollectionChild, collection)) : + NULL; + + if (child_collection == NULL) { + if (child_layer == view_layer->active_collection) { view_layer->active_collection = NULL; } /* Free recursively. */ - layer_collection_free(view_layer, lc); - BLI_freelinkN(lb_layer_collections, lc); + layer_collection_free(view_layer, child_layer); + BLI_freelinkN(r_lb_children_layers, child_layer); } } /* Add layer collections for any new scene collections, and ensure order is the same. */ - ListBase new_lb_layer = {NULL, NULL}; + ListBase lb_new_children_layers = {NULL, NULL}; - LISTBASE_FOREACH (const CollectionChild *, child, lb_collections) { - Collection *collection = child->collection; - LayerCollection *lc = BLI_findptr( - lb_layer_collections, collection, offsetof(LayerCollection, collection)); + LISTBASE_FOREACH (const CollectionChild *, child, lb_children_collections) { + Collection *child_collection = child->collection; + LayerCollection *child_layer = BLI_findptr( + r_lb_children_layers, child_collection, offsetof(LayerCollection, collection)); - if (lc) { - BLI_remlink(lb_layer_collections, lc); - BLI_addtail(&new_lb_layer, lc); + if (child_layer) { + BLI_remlink(r_lb_children_layers, child_layer); + BLI_addtail(&lb_new_children_layers, child_layer); } else { - lc = layer_collection_add(&new_lb_layer, collection); - lc->flag = parent_exclude; + child_layer = layer_collection_add(&lb_new_children_layers, child_collection); + child_layer->flag = parent_layer_flag; } - unsigned short local_collections_bits = parent_local_collections_bits & - lc->local_collections_bits; + const ushort child_local_collections_bits = parent_local_collections_bits & + child_layer->local_collections_bits; /* Tag linked collection as a weak reference so we keep the layer * collection pointer on file load and remember exclude state. */ - id_lib_indirect_weak_link(&collection->id); + id_lib_indirect_weak_link(&child_collection->id); /* Collection restrict is inherited. */ - short child_restrict = parent_restrict; + short child_collection_restrict = parent_collection_restrict; short child_layer_restrict = parent_layer_restrict; - if (!(collection->flag & COLLECTION_IS_MASTER)) { - child_restrict |= collection->flag; - child_layer_restrict |= lc->flag; + if (!(child_collection->flag & COLLECTION_IS_MASTER)) { + child_collection_restrict |= child_collection->flag; + child_layer_restrict |= child_layer->flag; } /* Sync child collections. */ layer_collection_sync(view_layer, - &collection->children, - &lc->layer_collections, - new_object_bases, - lc->flag, - child_restrict, + &child_collection->children, + &child_layer->layer_collections, + r_lb_new_object_bases, + child_layer->flag, + child_collection_restrict, child_layer_restrict, - local_collections_bits); + child_local_collections_bits); - /* Layer collection exclude is not inherited. */ - lc->runtime_flag = 0; - if (lc->flag & LAYER_COLLECTION_EXCLUDE) { + /* Layer collection exclude is not inherited, we can skip the remaining process, including + * object bases synchronization. */ + child_layer->runtime_flag = 0; + if (child_layer->flag & LAYER_COLLECTION_EXCLUDE) { continue; } /* We separate restrict viewport and visible view layer because a layer collection can be * hidden in the view layer yet (locally) visible in a viewport (if it is not restricted). */ - if (child_restrict & COLLECTION_RESTRICT_VIEWPORT) { - lc->runtime_flag |= LAYER_COLLECTION_RESTRICT_VIEWPORT; + if (child_collection_restrict & COLLECTION_RESTRICT_VIEWPORT) { + child_layer->runtime_flag |= LAYER_COLLECTION_RESTRICT_VIEWPORT; } - if (((lc->runtime_flag & LAYER_COLLECTION_RESTRICT_VIEWPORT) == 0) && + if (((child_layer->runtime_flag & LAYER_COLLECTION_RESTRICT_VIEWPORT) == 0) && ((child_layer_restrict & LAYER_COLLECTION_HIDE) == 0)) { - lc->runtime_flag |= LAYER_COLLECTION_VISIBLE_VIEW_LAYER; + child_layer->runtime_flag |= LAYER_COLLECTION_VISIBLE_VIEW_LAYER; } - /* Sync objects, except if collection was excluded. */ - LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) { - if (cob->ob == NULL) { - continue; - } - - /* Tag linked object as a weak reference so we keep the object - * base pointer on file load and remember hidden state. */ - id_lib_indirect_weak_link(&cob->ob->id); - - void **base_p; - Base *base; - if (BLI_ghash_ensure_p(view_layer->object_bases_hash, cob->ob, &base_p)) { - /* Move from old base list to new base list. Base might have already - * been moved to the new base list and the first/last test ensure that - * case also works. */ - base = *base_p; - if (!ELEM(base, new_object_bases->first, new_object_bases->last)) { - BLI_remlink(&view_layer->object_bases, base); - BLI_addtail(new_object_bases, base); - } - } - else { - /* Create new base. */ - base = object_base_new(cob->ob); - base->local_collections_bits = local_collections_bits; - *base_p = base; - BLI_addtail(new_object_bases, base); - } - - if ((child_restrict & COLLECTION_RESTRICT_VIEWPORT) == 0) { - base->flag_from_collection |= (BASE_ENABLED_VIEWPORT | BASE_VISIBLE_DEPSGRAPH); - if ((child_layer_restrict & LAYER_COLLECTION_HIDE) == 0) { - base->flag_from_collection |= BASE_VISIBLE_VIEWLAYER; - } - if (((child_restrict & COLLECTION_RESTRICT_SELECT) == 0)) { - base->flag_from_collection |= BASE_SELECTABLE; - } - } - - if ((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) { - base->flag_from_collection |= BASE_ENABLED_RENDER; - } - - /* Holdout and indirect only */ - if (lc->flag & LAYER_COLLECTION_HOLDOUT) { - base->flag_from_collection |= BASE_HOLDOUT; - } - if (lc->flag & LAYER_COLLECTION_INDIRECT_ONLY) { - base->flag_from_collection |= BASE_INDIRECT_ONLY; - } - - lc->runtime_flag |= LAYER_COLLECTION_HAS_OBJECTS; - } + layer_collection_objects_sync(view_layer, + child_layer, + r_lb_new_object_bases, + child_collection_restrict, + child_layer_restrict, + child_local_collections_bits); } /* Free potentially remaining unused layer collections in old list. * NOTE: While this does not happen in typical situations, some corner cases (like remapping * several different collections to a single one) can lead to this list having extra unused * items. */ - LISTBASE_FOREACH_MUTABLE (LayerCollection *, lc, lb_layer_collections) { + LISTBASE_FOREACH_MUTABLE (LayerCollection *, lc, r_lb_children_layers) { if (lc == view_layer->active_collection) { view_layer->active_collection = NULL; } /* Free recursively. */ layer_collection_free(view_layer, lc); - BLI_freelinkN(lb_layer_collections, lc); + BLI_freelinkN(r_lb_children_layers, lc); } - BLI_assert(BLI_listbase_is_empty(lb_layer_collections)); + BLI_assert(BLI_listbase_is_empty(r_lb_children_layers)); /* Replace layer collection list with new one. */ - *lb_layer_collections = new_lb_layer; - BLI_assert(BLI_listbase_count(lb_collections) == BLI_listbase_count(lb_layer_collections)); + *r_lb_children_layers = lb_new_children_layers; + BLI_assert(BLI_listbase_count(lb_children_collections) == + BLI_listbase_count(r_lb_children_layers)); } /** diff --git a/source/blender/blenkernel/intern/layer_utils.c b/source/blender/blenkernel/intern/layer_utils.c index 10ab0a06dd0..48179e0c3bf 100644 --- a/source/blender/blenkernel/intern/layer_utils.c +++ b/source/blender/blenkernel/intern/layer_utils.c @@ -23,6 +23,7 @@ #include "BLI_array.h" #include "BKE_collection.h" +#include "BKE_customdata.h" #include "BKE_editmesh.h" #include "BKE_layer.h" diff --git a/source/blender/blenkernel/intern/lib_id.c b/source/blender/blenkernel/intern/lib_id.c index 297ee565257..62d29188c5a 100644 --- a/source/blender/blenkernel/intern/lib_id.c +++ b/source/blender/blenkernel/intern/lib_id.c @@ -499,7 +499,7 @@ bool BKE_lib_id_make_local(Main *bmain, ID *id, const bool test, const int flags return false; } - BLI_assert(!"IDType Missing IDTypeInfo"); + BLI_assert_msg(0, "IDType Missing IDTypeInfo"); return false; } @@ -603,7 +603,7 @@ ID *BKE_id_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag) } } else { - BLI_assert(!"IDType Missing IDTypeInfo"); + BLI_assert_msg(0, "IDType Missing IDTypeInfo"); } /* Update ID refcount, remap pointers to self in new ID. */ @@ -667,7 +667,7 @@ ID *BKE_id_copy_for_duplicate(Main *bmain, ID *id, const eDupli_ID_Flags duplica ID_NEW_SET(key, key_new); } - /* Note: embedded data (root nodetrees and master collections) should never be referenced by + /* NOTE: embedded data (root nodetrees and master collections) should never be referenced by * anything else, so we do not need to set their newid pointer and flag. */ BKE_animdata_duplicate_id_action(bmain, id_new, duplicate_flags); @@ -1053,7 +1053,7 @@ void *BKE_libblock_alloc_notest(short type) if (size != 0) { return MEM_callocN(size, name); } - BLI_assert(!"Request to allocate unknown data type"); + BLI_assert_msg(0, "Request to allocate unknown data type"); return NULL; } @@ -1099,7 +1099,7 @@ void *BKE_libblock_alloc(Main *bmain, short type, const char *name, const int fl /* alphabetic insertion: is in new_id */ BKE_main_unlock(bmain); - /* TODO to be removed from here! */ + /* TODO: to be removed from here! */ if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0) { DEG_id_type_tag(bmain, type); } @@ -1134,7 +1134,7 @@ void BKE_libblock_init_empty(ID *id) return; } - BLI_assert(!"IDType Missing IDTypeInfo"); + BLI_assert_msg(0, "IDType Missing IDTypeInfo"); } /* ********** ID session-wise UUID management. ********** */ @@ -1234,11 +1234,11 @@ void BKE_libblock_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int ori if ((flag & LIB_ID_CREATE_NO_ALLOCATE) != 0) { /* r_newid already contains pointer to allocated memory. */ - /* TODO do we want to memset(0) whole mem before filling it? */ + /* TODO: do we want to memset(0) whole mem before filling it? */ BLI_strncpy(new_id->name, id->name, sizeof(new_id->name)); new_id->us = 0; new_id->tag |= LIB_TAG_NOT_ALLOCATED | LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT; - /* TODO Do we want/need to copy more from ID struct itself? */ + /* TODO: Do we want/need to copy more from ID struct itself? */ } else { new_id = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2, flag); @@ -1380,7 +1380,7 @@ void id_sort_by_name(ListBase *lb, ID *id, ID *id_sorting_hint) /* Step one: We go backward over a whole chunk of items at once, until we find a limit item * that is lower than, or equal (should never happen!) to the one we want to insert. */ - /* Note: We start from the end, because in typical 'heavy' case (insertion of lots of IDs at + /* NOTE: We start from the end, because in typical 'heavy' case (insertion of lots of IDs at * once using the same base name), newly inserted items will generally be towards the end * (higher extension numbers). */ bool is_in_library = false; @@ -1450,7 +1450,7 @@ void id_sort_by_name(ListBase *lb, ID *id, ID *id_sorting_hint) #undef ID_SORT_STEP_SIZE } -/* Note: this code assumes and ensures that the suffix number can never go beyond 1 billion. */ +/* NOTE: this code assumes and ensures that the suffix number can never go beyond 1 billion. */ #define MAX_NUMBER 1000000000 /* We do not want to get "name.000", so minimal number is 1. */ #define MIN_NUMBER 1 @@ -1605,7 +1605,7 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name, ID **r_id_sorting_ } /* In case we get an insane initial number suffix in given name. */ - /* Note: BLI_split_name_num() cannot return negative numbers, so we do not have to check for + /* NOTE: BLI_split_name_num() cannot return negative numbers, so we do not have to check for * that here. */ if (number >= MAX_NUMBER || number < MIN_NUMBER) { number = MIN_NUMBER; @@ -1642,9 +1642,8 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name, ID **r_id_sorting_ * already. */ if (!is_orig_name_used) { - /* Don't bother updating prev_ static variables here, this case is not supposed to happen - * that often, and is not straight-forward here, so just ignore and reset them to default. - */ + /* Don't bother updating `prev_*` static variables here, this case is not supposed to happen + * that often, and is not straight-forward here, so just ignore and reset them to default. */ prev_id_type = ID_LINK_PLACEHOLDER; prev_final_base_name[0] = '\0'; prev_number = MIN_NUMBER - 1; @@ -1684,7 +1683,7 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name, ID **r_id_sorting_ continue; } - /* Update prev_ static variables, in case next call is for the same type of IDs and with the + /* Update `prev_*` static variables, in case next call is for the same type of IDs and with the * same initial base name, we can skip a lot of above process. */ prev_id_type = id_type; strcpy(prev_final_base_name, base_name); @@ -1892,7 +1891,7 @@ static void library_make_local_copying_check(ID *id, * \param set_fake: If true, set fake user on all localized data-blocks * (except group and objects ones). */ -/* Note: Old (2.77) version was simply making (tagging) data-blocks as local, +/* NOTE: Old (2.77) version was simply making (tagging) data-blocks as local, * without actually making any check whether they were also indirectly used or not... * * Current version uses regular id_make_local callback, with advanced pre-processing step to @@ -2070,7 +2069,7 @@ void BKE_library_make_local(Main *bmain, * ID in a separated loop, * as lbarray ordering is not enough to ensure us we did catch all dependencies * (e.g. if making local a parent object before its child...). See T48907. */ - /* TODO This is now the biggest step by far (in term of processing time). + /* TODO: This is now the biggest step by far (in term of processing time). * We may be able to gain here by using again main->relations mapping, but... * this implies BKE_libblock_remap & co to be able to update main->relations on the fly. * Have to think about it a bit more, and see whether new code is OK first, anyway. */ diff --git a/source/blender/blenkernel/intern/lib_id_delete.c b/source/blender/blenkernel/intern/lib_id_delete.c index 67b2e4429d6..a9407860c06 100644 --- a/source/blender/blenkernel/intern/lib_id_delete.c +++ b/source/blender/blenkernel/intern/lib_id_delete.c @@ -83,7 +83,7 @@ void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag)) return; } - BLI_assert(!"IDType Missing IDTypeInfo"); + BLI_assert_msg(0, "IDType Missing IDTypeInfo"); } /** @@ -277,7 +277,7 @@ static size_t id_delete(Main *bmain, const bool do_tagged_deletion) for (id = lb->first; id; id = id_next) { id_next = id->next; - /* Note: in case we delete a library, we also delete all its datablocks! */ + /* NOTE: in case we delete a library, we also delete all its datablocks! */ if ((id->tag & tag) || (id->lib != NULL && (id->lib->id.tag & tag))) { BLI_remlink(lb, id); BLI_addtail(&tagged_deleted_ids, id); @@ -331,7 +331,7 @@ static size_t id_delete(Main *bmain, const bool do_tagged_deletion) for (id = lb->first; id; id = id_next) { id_next = id->next; - /* Note: in case we delete a library, we also delete all its datablocks! */ + /* NOTE: in case we delete a library, we also delete all its datablocks! */ if ((id->tag & tag) || (id->lib != NULL && (id->lib->id.tag & tag))) { id->tag |= tag; diff --git a/source/blender/blenkernel/intern/lib_override.c b/source/blender/blenkernel/intern/lib_override.c index 595e470876d..9871bf5dc83 100644 --- a/source/blender/blenkernel/intern/lib_override.c +++ b/source/blender/blenkernel/intern/lib_override.c @@ -94,7 +94,7 @@ BLI_INLINE IDOverrideLibrary *lib_override_get(Main *bmain, ID *id) if (id_type->owner_get != NULL) { return id_type->owner_get(bmain, id)->override_library; } - BLI_assert(!"IDTypeInfo of liboverride-embedded ID with no owner getter"); + BLI_assert_msg(0, "IDTypeInfo of liboverride-embedded ID with no owner getter"); } return id->override_library; } @@ -130,7 +130,7 @@ IDOverrideLibrary *BKE_lib_override_library_init(ID *local_id, ID *reference_id) local_id->override_library->reference = reference_id; id_us_plus(local_id->override_library->reference); local_id->tag &= ~LIB_TAG_OVERRIDE_LIBRARY_REFOK; - /* TODO do we want to add tag or flag to referee to mark it as such? */ + /* TODO: do we want to add tag or flag to referee to mark it as such? */ return local_id->override_library; } @@ -217,7 +217,7 @@ static ID *lib_override_library_create_from(Main *bmain, ID *reference_id, const int lib_id_copy_flags) { - /* Note: We do not want to copy possible override data from reference here (whether it is an + /* NOTE: We do not want to copy possible override data from reference here (whether it is an * override template, or already an override of some other ref data). */ ID *local_id = BKE_id_copy_ex(bmain, reference_id, @@ -232,7 +232,7 @@ static ID *lib_override_library_create_from(Main *bmain, BKE_lib_override_library_init(local_id, reference_id); - /* Note: From liboverride perspective (and RNA one), shape keys are considered as local embedded + /* NOTE: From liboverride perspective (and RNA one), shape keys are considered as local embedded * data-blocks, just like root node trees or master collections. Therefore, we never need to * create overrides for them. We need a way to mark them as overrides though. */ Key *reference_key; @@ -369,7 +369,7 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, /* If `newid` is already set, assume it has been handled by calling code. * Only current use case: re-using proxy ID when converting to liboverride. */ if (reference_id->newid == NULL) { - /* Note: `no main` case is used during resync procedure, to support recursive resync. + /* NOTE: `no main` case is used during resync procedure, to support recursive resync. * This requires extra care further down the resync process, * see: #BKE_lib_override_library_resync. */ reference_id->newid = lib_override_library_create_from( @@ -569,7 +569,7 @@ static void lib_override_linked_group_tag_recursive(LibOverrideGroupTagData *dat /* We tag all collections and objects for override. And we also tag all other data-blocks which * would use one of those. - * Note: missing IDs (aka placeholders) are never overridden. */ + * NOTE: missing IDs (aka placeholders) are never overridden. */ if (ELEM(GS(to_id->name), ID_OB, ID_GR)) { if ((to_id->tag & LIB_TAG_MISSING)) { to_id->tag |= missing_tag; @@ -1347,7 +1347,7 @@ bool BKE_lib_override_library_resync(Main *bmain, if (do_post_process) { /* Essentially ensures that potentially new overrides of new objects will be instantiated. */ - /* Note: Here 'reference' collection and 'newly added' collection are the same, which is fine + /* NOTE: Here 'reference' collection and 'newly added' collection are the same, which is fine * since we already relinked old root override collection to new resync'ed one above. So this * call is not expected to instantiate this new resync'ed collection anywhere, just to ensure * that we do not have any stray objects. */ @@ -2126,7 +2126,7 @@ bool BKE_lib_override_library_property_operation_operands_validate( ATTR_FALLTHROUGH; case IDOVERRIDE_LIBRARY_OP_MULTIPLY: if (ptr_storage == NULL || ptr_storage->data == NULL || prop_storage == NULL) { - BLI_assert(!"Missing data to apply differential override operation."); + BLI_assert_msg(0, "Missing data to apply differential override operation."); return false; } ATTR_FALLTHROUGH; @@ -2137,7 +2137,7 @@ bool BKE_lib_override_library_property_operation_operands_validate( case IDOVERRIDE_LIBRARY_OP_REPLACE: if ((ptr_dst == NULL || ptr_dst->data == NULL || prop_dst == NULL) || (ptr_src == NULL || ptr_src->data == NULL || prop_src == NULL)) { - BLI_assert(!"Missing data to apply override operation."); + BLI_assert_msg(0, "Missing data to apply override operation."); return false; } } @@ -2820,7 +2820,7 @@ void BKE_lib_override_library_update(Main *bmain, ID *local) local->tag |= LIB_TAG_OVERRIDE_LIBRARY_REFOK; - /* Note: Since we reload full content from linked ID here, potentially from edited local + /* NOTE: Since we reload full content from linked ID here, potentially from edited local * override, we do not really have a way to know *what* is changed, so we need to rely on the * massive destruction weapon of `ID_RECALC_ALL` here. */ DEG_id_tag_update_ex(bmain, local, ID_RECALC_ALL); @@ -2907,7 +2907,7 @@ ID *BKE_lib_override_library_operations_store_start(Main *bmain, * other-ID-reference creation/update in that case (since no differential operation is expected * to involve those anyway). */ #if 0 - /* XXX TODO We may also want a specialized handling of things here too, to avoid copying heavy + /* XXX TODO: We may also want a specialized handling of things here too, to avoid copying heavy * never-overridable data (like Mesh geometry etc.)? And also maybe avoid lib * reference-counting completely (shallow copy). */ /* This would imply change in handling of user-count all over RNA diff --git a/source/blender/blenkernel/intern/lib_query.c b/source/blender/blenkernel/intern/lib_query.c index 9d2552777bf..977e53c8474 100644 --- a/source/blender/blenkernel/intern/lib_query.c +++ b/source/blender/blenkernel/intern/lib_query.c @@ -273,7 +273,7 @@ static void library_foreach_ID_link(Main *bmain, continue; } - /* Note: ID.lib pointer is purposefully fully ignored here... + /* NOTE: ID.lib pointer is purposefully fully ignored here... * We may want to add it at some point? */ if (flag & IDWALK_DO_INTERNAL_RUNTIME_POINTERS) { diff --git a/source/blender/blenkernel/intern/lib_remap.c b/source/blender/blenkernel/intern/lib_remap.c index 2641208897e..bba15a3bcdf 100644 --- a/source/blender/blenkernel/intern/lib_remap.c +++ b/source/blender/blenkernel/intern/lib_remap.c @@ -126,7 +126,7 @@ static int foreach_libblock_remap_callback(LibraryIDLinkCallbackData *cb_data) const bool is_reference = (cb_flag & IDWALK_CB_OVERRIDE_LIBRARY_REFERENCE) != 0; const bool is_indirect = (cb_flag & IDWALK_CB_INDIRECT_USAGE) != 0; const bool skip_indirect = (id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0; - /* Note: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct, + /* NOTE: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct, * on the other hand since they get reset to lib data on file open/reload it is indirect too. * Edit Mode is also a 'skip direct' case. */ const bool is_obj = (GS(id_owner->name) == ID_OB); @@ -312,7 +312,7 @@ static void libblock_remap_data_postprocess_collection_update(Main *bmain, /* XXX Complex cases can lead to NULL pointers in other collections than old_collection, * and BKE_main_collection_sync_remap() does not tolerate any of those, so for now always check * whole existing collections for NULL pointers. - * I'd consider optimizing that whole collection remapping process a TODO for later. */ + * I'd consider optimizing that whole collection remapping process a TODO: for later. */ BKE_collections_child_remove_nulls(bmain, owner_collection, NULL /*old_collection*/); } else { @@ -630,7 +630,7 @@ void BKE_libblock_relink_ex( switch (GS(id->name)) { case ID_SCE: case ID_GR: { - /* Note: here we know which collection we have affected, so at lest for NULL children + /* NOTE: here we know which collection we have affected, so at lest for NULL children * detection we can only process that one. * This is also a required fix in case `id` would not be in Main anymore, which can happen * e.g. when called from `id_delete`. */ diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c index 677b9497c98..07a3396ad5f 100644 --- a/source/blender/blenkernel/intern/library.c +++ b/source/blender/blenkernel/intern/library.c @@ -102,10 +102,10 @@ void BKE_library_filepath_set(Main *bmain, Library *lib, const char *filepath) /* Not essential but set `filepath_abs` is an absolute copy of value which * is more useful if its kept in sync. */ if (BLI_path_is_rel(lib->filepath_abs)) { - /* note that the file may be unsaved, in this case, setting the + /* NOTE(campbell): the file may be unsaved, in this case, setting the * `filepath_abs` on an indirectly linked path is not allowed from the * outliner, and its not really supported but allow from here for now - * since making local could cause this to be directly linked - campbell + * since making local could cause this to be directly linked. */ /* Never make paths relative to parent lib - reading code (blenloader) always set *all* * `lib->filepath` relative to current main, not to their parent for indirectly linked ones. */ diff --git a/source/blender/blenkernel/intern/lightprobe.c b/source/blender/blenkernel/intern/lightprobe.c index d872ecf7578..b09aed82921 100644 --- a/source/blender/blenkernel/intern/lightprobe.c +++ b/source/blender/blenkernel/intern/lightprobe.c @@ -131,7 +131,7 @@ void BKE_lightprobe_type_set(LightProbe *probe, const short lightprobe_type) probe->attenuation_type = LIGHTPROBE_SHAPE_ELIPSOID; break; default: - BLI_assert(!"LightProbe type not configured."); + BLI_assert_msg(0, "LightProbe type not configured."); break; } } diff --git a/source/blender/blenkernel/intern/main.c b/source/blender/blenkernel/intern/main.c index 39cc5737ca2..655b6d3732c 100644 --- a/source/blender/blenkernel/intern/main.c +++ b/source/blender/blenkernel/intern/main.c @@ -400,7 +400,7 @@ ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data) } if (data) { - /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, + /* NOTE: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, * which will fail here (we do not want to pass the first two ints!). */ img = IMB_allocImBuf( (unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata); diff --git a/source/blender/blenkernel/intern/mask.c b/source/blender/blenkernel/intern/mask.c index 371af2a95ed..34dd38164c2 100644 --- a/source/blender/blenkernel/intern/mask.c +++ b/source/blender/blenkernel/intern/mask.c @@ -69,7 +69,7 @@ static void mask_copy_data(Main *UNUSED(bmain), BLI_listbase_clear(&mask_dst->masklayers); - /* TODO add unused flag to those as well. */ + /* TODO: add unused flag to those as well. */ BKE_mask_layer_copy_list(&mask_dst->masklayers, &mask_src->masklayers); /* enable fake user by default */ @@ -342,7 +342,7 @@ MaskSplinePoint *BKE_mask_spline_point_array_from_point(MaskSpline *spline, return spline->points_deform; } - BLI_assert(!"wrong array"); + BLI_assert_msg(0, "wrong array"); return NULL; } @@ -372,7 +372,7 @@ MaskLayer *BKE_mask_layer_new(Mask *mask, const char *name) return masklay; } -/* note: may still be hidden, caller needs to check */ +/* NOTE: may still be hidden, caller needs to check. */ MaskLayer *BKE_mask_layer_active(Mask *mask) { return BLI_findlink(&mask->masklayers, mask->masklay_act); @@ -707,7 +707,7 @@ void BKE_mask_point_handle(const MaskSplinePoint *point, copy_v2_v2(r_handle, bezt->vec[2]); } else { - BLI_assert(!"Unknown handle passed to BKE_mask_point_handle"); + BLI_assert_msg(0, "Unknown handle passed to BKE_mask_point_handle"); } } @@ -760,7 +760,7 @@ void BKE_mask_point_set_handle(MaskSplinePoint *point, copy_v2_v2(bezt->vec[2], loc); } else { - BLI_assert(!"unknown handle passed to BKE_mask_point_set_handle"); + BLI_assert_msg(0, "unknown handle passed to BKE_mask_point_set_handle"); } } @@ -1003,7 +1003,7 @@ void BKE_mask_point_select_set_handle(MaskSplinePoint *point, point->bezt.f3 |= SELECT; } else { - BLI_assert(!"Wrong which_handle passed to BKE_mask_point_select_set_handle"); + BLI_assert_msg(0, "Wrong which_handle passed to BKE_mask_point_select_set_handle"); } } else { @@ -1018,7 +1018,7 @@ void BKE_mask_point_select_set_handle(MaskSplinePoint *point, point->bezt.f3 &= ~SELECT; } else { - BLI_assert(!"Wrong which_handle passed to BKE_mask_point_select_set_handle"); + BLI_assert_msg(0, "Wrong which_handle passed to BKE_mask_point_select_set_handle"); } } } @@ -1133,7 +1133,7 @@ MaskSpline *BKE_mask_spline_copy(const MaskSpline *spline) return nspline; } -/* note: does NOT add to the list */ +/* NOTE: Does NOT add to the list. */ MaskLayerShape *BKE_mask_layer_shape_alloc(MaskLayer *masklay, const int frame) { MaskLayerShape *masklay_shape; @@ -1422,7 +1422,7 @@ void BKE_mask_get_handle_point_adjacent(MaskSpline *spline, MaskSplinePoint **r_point_prev, MaskSplinePoint **r_point_next) { - /* TODO, could avoid calling this at such low level */ + /* TODO: could avoid calling this at such low level. */ MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point); *r_point_prev = mask_spline_point_prev(spline, points_array, point); @@ -1472,7 +1472,7 @@ void BKE_mask_calc_handle_adjacent_interp(MaskSpline *spline, MaskSplinePoint *point, const float u) { - /* TODO! - make this interpolate between siblings - not always midpoint! */ + /* TODO: make this interpolate between siblings - not always midpoint! */ int length_tot = 0; float length_average = 0.0f; float weight_average = 0.0f; @@ -1942,7 +1942,7 @@ void BKE_mask_layer_shape_changed_add(MaskLayer *masklay, int tot = BKE_mask_layer_shape_totvert(masklay) - 1; /* for interpolation */ - /* TODO - assumes closed curve for now */ + /* TODO: assumes closed curve for now. */ float uv[3][2]; /* 3x 2D handles */ const int pi_curr = spline_point_index; const int pi_prev = ((spline_point_index - 1) + spline->tot_point) % spline->tot_point; diff --git a/source/blender/blenkernel/intern/mask_evaluate.c b/source/blender/blenkernel/intern/mask_evaluate.c index 69f60ca0384..4584d9e527e 100644 --- a/source/blender/blenkernel/intern/mask_evaluate.c +++ b/source/blender/blenkernel/intern/mask_evaluate.c @@ -545,7 +545,7 @@ static float (*mask_spline_feather_differentiated_points_with_resolution__even( float u = (float)j / resol, weight; float co[2], n[2]; - /* TODO - these calls all calculate similar things + /* TODO: these calls all calculate similar things * could be unified for some speed */ BKE_mask_point_segment_co(spline, point_prev, u, co); BKE_mask_point_normal(spline, point_prev, u, n); @@ -691,7 +691,7 @@ static float (*mask_spline_feather_differentiated_points_with_resolution__double float weight_uw, weight_scalar; float co[2]; - /* TODO - these calls all calculate similar things + /* TODO: these calls all calculate similar things * could be unified for some speed */ BKE_mask_point_segment_co(spline, point_prev, u, co); diff --git a/source/blender/blenkernel/intern/mask_rasterize.c b/source/blender/blenkernel/intern/mask_rasterize.c index d29a6e75954..81c161a4a7d 100644 --- a/source/blender/blenkernel/intern/mask_rasterize.c +++ b/source/blender/blenkernel/intern/mask_rasterize.c @@ -514,7 +514,7 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size) BLI_assert(bucket_index < bucket_tot); /* Check if the bucket intersects with the face. */ - /* Note: there is a trade off here since checking box/tri intersections isn't as + /* NOTE: there is a trade off here since checking box/tri intersections isn't as * optimal as it could be, but checking pixels against faces they will never * intersect with is likely the greater slowdown here - * so check if the cell intersects the face. */ @@ -729,7 +729,7 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, sf_vert_tot++; - /* TODO, an alternate functions so we can avoid double vector copy! */ + /* TODO: an alternate functions so we can avoid double vector copy! */ for (j = 1; j < tot_diff_point; j++) { copy_v2_v2(co, diff_points[j]); sf_vert = BLI_scanfill_vert_add(&sf_ctx, co); @@ -762,7 +762,7 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, BLI_assert(tot_diff_feather_points == tot_diff_point); - /* Note: only added for convenience, we don't in fact use these to scan-fill, + /* NOTE: only added for convenience, we don't in fact use these to scan-fill, * only to create feather faces after scan-fill. */ for (j = 0; j < tot_diff_feather_points; j++) { copy_v2_v2(co_feather, diff_feather_points[j]); @@ -804,7 +804,7 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, open_spline_ranges[open_spline_index].vertex_offset = sf_vert_tot; open_spline_ranges[open_spline_index].vertex_total = tot_diff_point; - /* TODO, an alternate functions so we can avoid double vector copy! */ + /* TODO: an alternate functions so we can avoid double vector copy! */ for (j = 0; j < tot_diff_point; j++) { /* center vert */ @@ -937,7 +937,7 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, ListBase isect_remedgebase = {NULL, NULL}; /* now we have all the splines */ - face_coords = MEM_mallocN((sizeof(float[3])) * sf_vert_tot, "maskrast_face_coords"); + face_coords = MEM_mallocN(sizeof(float[3]) * sf_vert_tot, "maskrast_face_coords"); /* init bounds */ BLI_rctf_init_minmax(&bounds); diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index c5060e16e4d..4f0b2a718ed 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -135,7 +135,7 @@ static void material_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const BLI_listbase_clear(&material_dst->gpumaterial); - /* TODO Duplicate Engine Settings and set runtime to NULL */ + /* TODO: Duplicate Engine Settings and set runtime to NULL. */ } static void material_free_data(ID *id) @@ -864,7 +864,7 @@ void BKE_object_material_resize(Main *bmain, Object *ob, const short totcol, boo ob->mat = newmatar; ob->matbits = newmatbits; } - /* XXX, why not realloc on shrink? - campbell */ + /* XXX(campbell): why not realloc on shrink? */ ob->totcol = totcol; if (ob->totcol && ob->actcol == 0) { @@ -1168,7 +1168,7 @@ void BKE_object_material_from_eval_data(Main *bmain, Object *ob_orig, ID *data_e BKE_object_materials_test(bmain, ob_orig, data_orig); } -/* XXX - this calls many more update calls per object then are needed, could be optimized */ +/* XXX: this calls many more update calls per object then are needed, could be optimized. */ void BKE_object_material_array_assign(Main *bmain, struct Object *ob, struct Material ***matar, @@ -1823,7 +1823,7 @@ void BKE_material_copybuf_copy(Main *bmain, Material *ma) matcopybuf.preview = NULL; BLI_listbase_clear(&matcopybuf.gpumaterial); - /* TODO Duplicate Engine Settings and set runtime to NULL */ + /* TODO: Duplicate Engine Settings and set runtime to NULL. */ matcopied = 1; } diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c index f5d898e801b..6a2b56306d6 100644 --- a/source/blender/blenkernel/intern/mball.c +++ b/source/blender/blenkernel/intern/mball.c @@ -559,7 +559,7 @@ bool BKE_mball_minmax_ex( copy_v3_v3(centroid, &ml->x); } - /* TODO, non circle shapes cubes etc, probably nobody notices - campbell */ + /* TODO(campbell): non circle shapes cubes etc, probably nobody notices. */ for (int i = -1; i != 3; i += 2) { copy_v3_v3(vec, centroid); add_v3_fl(vec, scale_mb * i); diff --git a/source/blender/blenkernel/intern/mball_tessellate.c b/source/blender/blenkernel/intern/mball_tessellate.c index 413cefd2271..760febaca91 100644 --- a/source/blender/blenkernel/intern/mball_tessellate.c +++ b/source/blender/blenkernel/intern/mball_tessellate.c @@ -1336,7 +1336,7 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje } /* untransformed Bounding Box of MetaElem */ - /* TODO, its possible the elem type has been changed and the exp* + /* TODO: its possible the elem type has been changed and the exp* * values can use a fallback. */ copy_v3_fl3(new_ml->bb->vec[0], -expx, -expy, -expz); /* 0 */ copy_v3_fl3(new_ml->bb->vec[1], +expx, -expy, -expz); /* 1 */ @@ -1438,7 +1438,7 @@ void BKE_mball_polygonize(Depsgraph *depsgraph, Scene *scene, Object *ob, ListBa build_bvh_spatial(&process, &process.metaball_bvh, 0, process.totelem, &process.allbb); /* Don't polygonize meta-balls with too high resolution (base mball too small) - * note: Eps was 0.0001f but this was giving problems for blood animation for + * NOTE: Eps was 0.0001f but this was giving problems for blood animation for * the open movie "Sintel", using 0.00001f. */ if (ob->scale[0] > 0.00001f * (process.allbb.max[0] - process.allbb.min[0]) || ob->scale[1] > 0.00001f * (process.allbb.max[1] - process.allbb.min[1]) || diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c index b518f35fac7..b463d903303 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -39,6 +39,7 @@ #include "BLI_ghash.h" #include "BLI_hash.h" #include "BLI_linklist.h" +#include "BLI_listbase.h" #include "BLI_math.h" #include "BLI_memarena.h" #include "BLI_string.h" @@ -125,6 +126,8 @@ static void mesh_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const int mesh_dst->mat = MEM_dupallocN(mesh_src->mat); + BKE_defgroup_copy_list(&mesh_dst->vertex_group_names, &mesh_src->vertex_group_names); + const eCDAllocType alloc_type = (flag & LIB_ID_COPY_CD_REFERENCE) ? CD_REFERENCE : CD_DUPLICATE; CustomData_copy(&mesh_src->vdata, &mesh_dst->vdata, mask.vmask, alloc_type, mesh_dst->totvert); CustomData_copy(&mesh_src->edata, &mesh_dst->edata, mask.emask, alloc_type, mesh_dst->totedge); @@ -143,7 +146,7 @@ static void mesh_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const int mesh_dst->mselect = MEM_dupallocN(mesh_dst->mselect); - /* TODO Do we want to add flag to prevent this? */ + /* TODO: Do we want to add flag to prevent this? */ if (mesh_src->key && (flag & LIB_ID_COPY_SHAPEKEY)) { BKE_id_copy_ex(bmain, &mesh_src->key->id, (ID **)&mesh_dst->key, flag); /* XXX This is not nice, we need to make BKE_id_copy_ex fully re-entrant... */ @@ -155,6 +158,8 @@ static void mesh_free_data(ID *id) { Mesh *mesh = (Mesh *)id; + BLI_freelistN(&mesh->vertex_group_names); + BKE_mesh_runtime_clear_cache(mesh); mesh_clear_geometry(mesh); MEM_SAFE_FREE(mesh->mat); @@ -229,6 +234,8 @@ static void mesh_blend_write(BlendWriter *writer, ID *id, const void *id_address BKE_animdata_blend_write(writer, mesh->adt); } + BKE_defbase_blend_write(writer, &mesh->vertex_group_names); + BLO_write_pointer_array(writer, mesh->totcol, mesh->mat); BLO_write_raw(writer, sizeof(MSelect) * mesh->totselect, mesh->mselect); @@ -288,6 +295,7 @@ static void mesh_blend_read_data(BlendDataReader *reader, ID *id) /* Normally BKE_defvert_blend_read should be called in CustomData_blend_read, * but for backwards compatibility in do_versions to work we do it here. */ BKE_defvert_blend_read(reader, mesh->totvert, mesh->dvert); + BLO_read_list(reader, &mesh->vertex_group_names); CustomData_blend_read(reader, &mesh->vdata, mesh->totvert); CustomData_blend_read(reader, &mesh->edata, mesh->totedge); @@ -304,7 +312,7 @@ static void mesh_blend_read_data(BlendDataReader *reader, ID *id) mesh->totselect = 0; } - if ((BLO_read_requires_endian_switch(reader)) && mesh->tface) { + if (BLO_read_requires_endian_switch(reader) && mesh->tface) { TFace *tf = mesh->tface; for (int i = 0; i < mesh->totface; i++, tf++) { BLI_endian_switch_uint32_array(tf->col, 4); @@ -657,12 +665,12 @@ static void mesh_ensure_tessellation_customdata(Mesh *me) CustomData_from_bmeshpoly(&me->fdata, &me->ldata, me->totface); - /* TODO - add some --debug-mesh option */ + /* TODO: add some `--debug-mesh` option. */ if (G.debug & G_DEBUG) { - /* note: this warning may be un-called for if we are initializing the mesh for the - * first time from bmesh, rather than giving a warning about this we could be smarter + /* NOTE(campbell): this warning may be un-called for if we are initializing the mesh for + * the first time from #BMesh, rather than giving a warning about this we could be smarter * and check if there was any data to begin with, for now just print the warning with - * some info to help troubleshoot what's going on - campbell */ + * some info to help troubleshoot what's going on. */ printf( "%s: warning! Tessellation uvs or vcol data got out of sync, " "had to reset!\n CD_MTFACE: %d != CD_MLOOPUV: %d || CD_MCOL: %d != CD_MLOOPCOL: " @@ -923,6 +931,8 @@ void BKE_mesh_copy_parameters(Mesh *me_dst, const Mesh *me_src) me_dst->texflag = me_src->texflag; copy_v3_v3(me_dst->loc, me_src->loc); copy_v3_v3(me_dst->size, me_src->size); + + me_dst->vertex_group_active_index = me_src->vertex_group_active_index; } /** @@ -938,6 +948,10 @@ void BKE_mesh_copy_parameters_for_eval(Mesh *me_dst, const Mesh *me_src) BKE_mesh_copy_parameters(me_dst, me_src); + /* Copy vertex group names. */ + BLI_assert(BLI_listbase_is_empty(&me_dst->vertex_group_names)); + BKE_defgroup_copy_list(&me_dst->vertex_group_names, &me_src->vertex_group_names); + /* Copy materials. */ if (me_dst->mat != NULL) { MEM_freeN(me_dst->mat); @@ -2126,7 +2140,7 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals) } } - /* Note: after this point mesh is expected to be valid again. */ + /* NOTE: after this point mesh is expected to be valid again. */ /* CD_NORMAL is expected to be temporary only. */ if (free_loop_normals) { diff --git a/source/blender/blenkernel/intern/mesh_boolean_convert.cc b/source/blender/blenkernel/intern/mesh_boolean_convert.cc index c162458ffb9..798d9562150 100644 --- a/source/blender/blenkernel/intern/mesh_boolean_convert.cc +++ b/source/blender/blenkernel/intern/mesh_boolean_convert.cc @@ -38,6 +38,7 @@ #include "BLI_mesh_boolean.hh" #include "BLI_mesh_intersect.hh" #include "BLI_span.hh" +#include "BLI_task.hh" namespace blender::meshintersect { @@ -309,22 +310,38 @@ static IMesh meshes_to_imesh(Span<const Mesh *> meshes, clean_obmat(*obmats[mi]); r_info->to_target_transform[mi] = inv_target_mat * objn_mat; - /* Skip the matrix multiplication for each point when there is no transform for a mesh, - * for example when the first mesh is already in the target space. (Note the logic directly - * above, which uses an identity matrix with a null input transform). */ + Vector<Vert *> verts(me->totvert); + Span<MVert> mverts = Span(me->mvert, me->totvert); + + /* Allocate verts + * Skip the matrix multiplication for each point when there is no transform for a mesh, + * for example when the first mesh is already in the target space. (Note the logic + * directly above, which uses an identity matrix with a null input transform). */ if (obmats[mi] == nullptr) { - for (const MVert &vert : Span(me->mvert, me->totvert)) { - const float3 co = float3(vert.co); - r_info->mesh_to_imesh_vert[v] = arena.add_or_find_vert(mpq3(co.x, co.y, co.z), v); - ++v; - } + threading::parallel_for(mverts.index_range(), 2048, [&](IndexRange range) { + float3 co; + for (int i : range) { + co = float3(mverts[i].co); + mpq3 mco = mpq3(co.x, co.y, co.z); + double3 dco(mco[0].get_d(), mco[1].get_d(), mco[2].get_d()); + verts[i] = new Vert(mco, dco, NO_INDEX, i); + } + }); } else { - for (const MVert &vert : Span(me->mvert, me->totvert)) { - const float3 co = r_info->to_target_transform[mi] * float3(vert.co); - r_info->mesh_to_imesh_vert[v] = arena.add_or_find_vert(mpq3(co.x, co.y, co.z), v); - ++v; - } + threading::parallel_for(mverts.index_range(), 2048, [&](IndexRange range) { + float3 co; + for (int i : range) { + co = r_info->to_target_transform[mi] * float3(mverts[i].co); + mpq3 mco = mpq3(co.x, co.y, co.z); + double3 dco(mco[0].get_d(), mco[1].get_d(), mco[2].get_d()); + verts[i] = new Vert(mco, dco, NO_INDEX, i); + } + }); + } + for (int i : mverts.index_range()) { + r_info->mesh_to_imesh_vert[v] = arena.add_or_find_vert(verts[i]); + ++v; } for (const MPoly &poly : Span(me->mpoly, me->totpoly)) { @@ -611,7 +628,7 @@ static void copy_or_interp_loop_attributes(Mesh *dest_mesh, source_cd, target_cd, source_layer_i, target_layer_i, orig_loop_index, loop_index, 1); } else { - /* Note: although CustomData_bmesh_interp_n function has bmesh in its name, nothing about + /* NOTE: although CustomData_bmesh_interp_n function has bmesh in its name, nothing about * it is BMesh-specific. We can't use CustomData_interp because it assumes that * all source layers exist in the dest. * A non bmesh version could have the benefit of not copying data into src_blocks_ofs - diff --git a/source/blender/blenkernel/intern/mesh_convert.c b/source/blender/blenkernel/intern/mesh_convert.c index cfad5e1100d..e777eb7ffe9 100644 --- a/source/blender/blenkernel/intern/mesh_convert.c +++ b/source/blender/blenkernel/intern/mesh_convert.c @@ -1117,7 +1117,7 @@ static void curve_to_mesh_eval_ensure(Object *object) BKE_displist_make_curveTypes_forRender( NULL, NULL, &remapped_object, &remapped_object.runtime.curve_cache->disp, &mesh_eval); - /* Note: this is to be consistent with `BKE_displist_make_curveTypes()`, however that is not a + /* NOTE: this is to be consistent with `BKE_displist_make_curveTypes()`, however that is not a * real issue currently, code here is broken in more than one way, fix(es) will be done * separately. */ if (mesh_eval != NULL) { @@ -1327,7 +1327,7 @@ static int foreach_libblock_make_usercounts_callback(LibraryIDLinkCallbackData * id_us_plus(*id_p); } else if (cb_flag & IDWALK_CB_USER_ONE) { - /* Note: in that context, that one should not be needed (since there should be at least already + /* NOTE: in that context, that one should not be needed (since there should be at least already * one USER_ONE user of that ID), but better be consistent. */ id_us_ensure_real(*id_p); } @@ -1668,7 +1668,7 @@ void BKE_mesh_nomain_to_mesh(Mesh *mesh_src, } /* object had got displacement layer, should copy this layer to save sculpted data */ - /* NOTE: maybe some other layers should be copied? nazgul */ + /* NOTE(nazgul): maybe some other layers should be copied? */ if (CustomData_has_layer(&mesh_dst->ldata, CD_MDISPS)) { if (totloop == mesh_dst->totloop) { MDisps *mdisps = CustomData_get_layer(&mesh_dst->ldata, CD_MDISPS); diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.cc index 6eac96ba85b..91fd022a316 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.c +++ b/source/blender/blenkernel/intern/mesh_evaluate.cc @@ -23,7 +23,7 @@ * Functions to evaluate mesh data. */ -#include <limits.h> +#include <climits> #include "MEM_guardedalloc.h" @@ -191,7 +191,7 @@ void BKE_mesh_calc_poly_center(const MPoly *mpoly, } } -/* note, passing polynormal is only a speedup so we can skip calculating it */ +/* NOTE: passing poly-normal is only a speedup so we can skip calculating it. */ float BKE_mesh_calc_poly_area(const MPoly *mpoly, const MLoop *loopstart, const MVert *mvarray) { if (mpoly->totloop == 3) { @@ -200,7 +200,7 @@ float BKE_mesh_calc_poly_area(const MPoly *mpoly, const MLoop *loopstart, const } const MLoop *l_iter = loopstart; - float(*vertexcos)[3] = BLI_array_alloca(vertexcos, (size_t)mpoly->totloop); + float(*vertexcos)[3] = (float(*)[3])BLI_array_alloca(vertexcos, (size_t)mpoly->totloop); /* pack vertex cos into an array for area_poly_v3 */ for (int i = 0; i < mpoly->totloop; i++, l_iter++) { @@ -236,7 +236,7 @@ float BKE_mesh_calc_poly_uv_area(const MPoly *mpoly, const MLoopUV *uv_array) int i, l_iter = mpoly->loopstart; float area; - float(*vertexcos)[2] = BLI_array_alloca(vertexcos, (size_t)mpoly->totloop); + float(*vertexcos)[2] = (float(*)[2])BLI_array_alloca(vertexcos, (size_t)mpoly->totloop); /* pack vertex cos into an array for area_poly_v2 */ for (i = 0; i < mpoly->totloop; i++, l_iter++) { @@ -404,7 +404,7 @@ void BKE_mesh_poly_edgehash_insert(EdgeHash *ehash, const MPoly *mp, const MLoop ml = &ml_next[i - 1]; /* last loop */ while (i-- != 0) { - BLI_edgehash_reinsert(ehash, ml->v, ml_next->v, NULL); + BLI_edgehash_reinsert(ehash, ml->v, ml_next->v, nullptr); ml = ml_next; ml_next++; @@ -656,7 +656,7 @@ void BKE_mesh_calc_volume(const MVert *mverts, } } - /* Note: Depending on arbitrary centroid position, + /* NOTE: Depending on arbitrary centroid position, * totvol can become negative even for a valid mesh. * The true value is always the positive value. */ @@ -664,7 +664,7 @@ void BKE_mesh_calc_volume(const MVert *mverts, *r_volume = fabsf(totvol); } if (r_center) { - /* Note: Factor 1/3 is applied once for all vertices here. + /* NOTE: Factor 1/3 is applied once for all vertices here. * This also automatically negates the vector if totvol is negative. */ if (totvol != 0.0f) { @@ -676,7 +676,7 @@ void BKE_mesh_calc_volume(const MVert *mverts, /** \} */ /* -------------------------------------------------------------------- */ -/** \name NGon Tessellation (NGon/Tessface Conversion) +/** \name NGon Tessellation (NGon to MFace Conversion) * \{ */ static void bm_corners_to_loops_ex(ID *id, @@ -692,9 +692,9 @@ static void bm_corners_to_loops_ex(ID *id, MFace *mf = mface + findex; for (int i = 0; i < numTex; i++) { - MTFace *texface = CustomData_get_n(fdata, CD_MTFACE, findex, i); + MTFace *texface = (MTFace *)CustomData_get_n(fdata, CD_MTFACE, findex, i); - MLoopUV *mloopuv = CustomData_get_n(ldata, CD_MLOOPUV, loopstart, i); + MLoopUV *mloopuv = (MLoopUV *)CustomData_get_n(ldata, CD_MLOOPUV, loopstart, i); copy_v2_v2(mloopuv->uv, texface->uv[0]); mloopuv++; copy_v2_v2(mloopuv->uv, texface->uv[1]); @@ -709,8 +709,8 @@ static void bm_corners_to_loops_ex(ID *id, } for (int i = 0; i < numCol; i++) { - MLoopCol *mloopcol = CustomData_get_n(ldata, CD_MLOOPCOL, loopstart, i); - MCol *mcol = CustomData_get_n(fdata, CD_MCOL, findex, i); + MLoopCol *mloopcol = (MLoopCol *)CustomData_get_n(ldata, CD_MLOOPCOL, loopstart, i); + MCol *mcol = (MCol *)CustomData_get_n(fdata, CD_MCOL, findex, i); MESH_MLOOPCOL_FROM_MCOL(mloopcol, &mcol[0]); mloopcol++; @@ -725,8 +725,8 @@ static void bm_corners_to_loops_ex(ID *id, } if (CustomData_has_layer(fdata, CD_TESSLOOPNORMAL)) { - float(*lnors)[3] = CustomData_get(ldata, loopstart, CD_NORMAL); - short(*tlnors)[3] = CustomData_get(fdata, findex, CD_TESSLOOPNORMAL); + float(*lnors)[3] = (float(*)[3])CustomData_get(ldata, loopstart, CD_NORMAL); + short(*tlnors)[3] = (short(*)[3])CustomData_get(fdata, findex, CD_TESSLOOPNORMAL); const int max = mf->v4 ? 4 : 3; for (int i = 0; i < max; i++, lnors++, tlnors++) { @@ -735,8 +735,8 @@ static void bm_corners_to_loops_ex(ID *id, } if (CustomData_has_layer(fdata, CD_MDISPS)) { - MDisps *ld = CustomData_get(ldata, loopstart, CD_MDISPS); - MDisps *fd = CustomData_get(fdata, findex, CD_MDISPS); + MDisps *ld = (MDisps *)CustomData_get(ldata, loopstart, CD_MDISPS); + MDisps *fd = (MDisps *)CustomData_get(fdata, findex, CD_MDISPS); float(*disps)[3] = fd->disps; int tot = mf->v4 ? 4 : 3; int corners; @@ -750,9 +750,9 @@ static void bm_corners_to_loops_ex(ID *id, corners = multires_mdisp_corners(fd); if (corners == 0) { - /* Empty MDisp layers appear in at least one of the sintel.blend files. + /* Empty #MDisp layers appear in at least one of the `sintel.blend` files. * Not sure why this happens, but it seems fine to just ignore them here. - * If (corners == 0) for a non-empty layer though, something went wrong. */ + * If `corners == 0` for a non-empty layer though, something went wrong. */ BLI_assert(fd->totdisp == 0); } else { @@ -767,7 +767,8 @@ static void bm_corners_to_loops_ex(ID *id, MEM_freeN(ld->disps); } - ld->disps = MEM_malloc_arrayN((size_t)side_sq, sizeof(float[3]), "converted loop mdisps"); + ld->disps = (float(*)[3])MEM_malloc_arrayN( + (size_t)side_sq, sizeof(float[3]), "converted loop mdisps"); if (fd->disps) { memcpy(ld->disps, disps, (size_t)side_sq * sizeof(float[3])); } @@ -801,15 +802,16 @@ void BKE_mesh_convert_mfaces_to_mpolys(Mesh *mesh) /** * The same as #BKE_mesh_convert_mfaces_to_mpolys - * but oriented to be used in #do_versions from readfile.c - * the difference is how active/render/clone/stencil indices are handled here + * but oriented to be used in #do_versions from `readfile.c` + * the difference is how active/render/clone/stencil indices are handled here. * - * normally thay're being set from pdata which totally makes sense for meshes which are already - * converted to bmesh structures, but when loading older files indices shall be updated in other - * way around, so newly added pdata and ldata would have this indices set based on fdata layer + * normally they're being set from `pdata` which totally makes sense for meshes which are already + * converted to #BMesh structures, but when loading older files indices shall be updated in other + * way around, so newly added `pdata` and `ldata` would have this indices set + * based on `fdata` layer. * * this is normally only needed when reading older files, - * in all other cases #BKE_mesh_convert_mfaces_to_mpolys shall be always used + * in all other cases #BKE_mesh_convert_mfaces_to_mpolys shall be always used. */ void BKE_mesh_do_versions_convert_mfaces_to_mpolys(Mesh *mesh) { @@ -864,7 +866,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData_free(pdata, totpoly_i); totpoly = totface_i; - mpoly = MEM_calloc_arrayN((size_t)totpoly, sizeof(MPoly), "mpoly converted"); + mpoly = (MPoly *)MEM_calloc_arrayN((size_t)totpoly, sizeof(MPoly), "mpoly converted"); CustomData_add_layer(pdata, CD_MPOLY, CD_ASSIGN, mpoly, totpoly); numTex = CustomData_number_of_layers(fdata, CD_MTFACE); @@ -876,7 +878,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, totloop += mf->v4 ? 4 : 3; } - mloop = MEM_calloc_arrayN((size_t)totloop, sizeof(MLoop), "mloop converted"); + mloop = (MLoop *)MEM_calloc_arrayN((size_t)totloop, sizeof(MLoop), "mloop converted"); CustomData_add_layer(ldata, CD_MLOOP, CD_ASSIGN, mloop, totloop); @@ -900,7 +902,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, me->flag &= ~ME_FGON; } - polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX); + polyindex = (int *)CustomData_get_layer(fdata, CD_ORIGINDEX); j = 0; /* current loop index */ ml = mloop; @@ -943,10 +945,10 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, } } - /* note, we don't convert NGons at all, these are not even real ngons, + /* NOTE: we don't convert NGons at all, these are not even real ngons, * they have their own UV's, colors etc - its more an editing feature. */ - BLI_edgehash_free(eh, NULL); + BLI_edgehash_free(eh, nullptr); *r_totpoly = totpoly; *r_totloop = totloop; @@ -1050,8 +1052,8 @@ void BKE_mesh_polygon_flip_ex(MPoly *mpoly, void BKE_mesh_polygon_flip(MPoly *mpoly, MLoop *mloop, CustomData *ldata) { - MDisps *mdisp = CustomData_get_layer(ldata, CD_MDISPS); - BKE_mesh_polygon_flip_ex(mpoly, mloop, ldata, NULL, mdisp, true); + MDisps *mdisp = (MDisps *)CustomData_get_layer(ldata, CD_MDISPS); + BKE_mesh_polygon_flip_ex(mpoly, mloop, ldata, nullptr, mdisp, true); } /** @@ -1061,12 +1063,12 @@ void BKE_mesh_polygon_flip(MPoly *mpoly, MLoop *mloop, CustomData *ldata) */ void BKE_mesh_polygons_flip(MPoly *mpoly, MLoop *mloop, CustomData *ldata, int totpoly) { - MDisps *mdisp = CustomData_get_layer(ldata, CD_MDISPS); + MDisps *mdisp = (MDisps *)CustomData_get_layer(ldata, CD_MDISPS); MPoly *mp; int i; for (mp = mpoly, i = 0; i < totpoly; mp++, i++) { - BKE_mesh_polygon_flip_ex(mp, mloop, ldata, NULL, mdisp, true); + BKE_mesh_polygon_flip_ex(mp, mloop, ldata, nullptr, mdisp, true); } } @@ -1277,7 +1279,7 @@ void BKE_mesh_calc_relative_deform(const MPoly *mpoly, const MPoly *mp; int i; - int *vert_accum = MEM_calloc_arrayN((size_t)totvert, sizeof(*vert_accum), __func__); + int *vert_accum = (int *)MEM_calloc_arrayN((size_t)totvert, sizeof(*vert_accum), __func__); memset(vert_cos_new, '\0', sizeof(*vert_cos_new) * (size_t)totvert); diff --git a/source/blender/blenkernel/intern/mesh_mapping.c b/source/blender/blenkernel/intern/mesh_mapping.c index c469a65449d..ca6c60557a6 100644 --- a/source/blender/blenkernel/intern/mesh_mapping.c +++ b/source/blender/blenkernel/intern/mesh_mapping.c @@ -776,7 +776,7 @@ static void poly_edge_loop_islands_calc(const MEdge *medge, } if (UNLIKELY(gid_bit > 31)) { /* All bits used in contiguous smooth groups, we can't do much! - * Note: this is *very* unlikely - theoretically, four groups are enough, + * NOTE: this is *very* unlikely - theoretically, four groups are enough, * I don't think we can reach this goal with such a simple algorithm, * but I don't think either we'll never need all 32 groups! */ @@ -998,7 +998,7 @@ void BKE_mesh_loop_islands_add(MeshIslandStore *island_store, } /* TODO: I'm not sure edge seam flag is enough to define UV islands? - * Maybe we should also consider UVmaps values + * Maybe we should also consider UV-maps values * themselves (i.e. different UV-edges for a same mesh-edge => boundary edge too?). * Would make things much more complex though, * and each UVMap would then need its own mesh mapping, not sure we want that at all! @@ -1140,7 +1140,7 @@ static bool mesh_calc_islands_loop_poly_uv(MVert *UNUSED(verts), poly_indices = MEM_mallocN(sizeof(*poly_indices) * (size_t)totpoly, __func__); loop_indices = MEM_mallocN(sizeof(*loop_indices) * (size_t)totloop, __func__); - /* Note: here we ignore '0' invalid group - this should *never* happen in this case anyway? */ + /* NOTE: here we ignore '0' invalid group - this should *never* happen in this case anyway? */ for (grp_idx = 1; grp_idx <= num_poly_groups; grp_idx++) { num_pidx = num_lidx = 0; if (num_edge_borders) { diff --git a/source/blender/blenkernel/intern/mesh_merge.c b/source/blender/blenkernel/intern/mesh_merge.c index 1e51ee73c7c..d3d835378ca 100644 --- a/source/blender/blenkernel/intern/mesh_merge.c +++ b/source/blender/blenkernel/intern/mesh_merge.c @@ -259,7 +259,7 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, STACK_DECLARE(mvert); STACK_DECLARE(oldv); - /* Note: create (totedge + totloop) elements because partially invalid polys due to merge may + /* NOTE: create (totedge + totloop) elements because partially invalid polys due to merge may * require generating new edges, and while in 99% cases we'll still end with less final edges * than totedge, cases can be forged that would end requiring more. */ MEdge *med, *medge = MEM_malloc_arrayN((totedge + totloop), sizeof(*medge), __func__); diff --git a/source/blender/blenkernel/intern/mesh_normals.c b/source/blender/blenkernel/intern/mesh_normals.cc index 9f09ce46e11..2fe132fc684 100644 --- a/source/blender/blenkernel/intern/mesh_normals.c +++ b/source/blender/blenkernel/intern/mesh_normals.cc @@ -25,7 +25,7 @@ * \see bmesh_mesh_normals.c for the equivalent #BMesh functionality. */ -#include <limits.h> +#include <climits> #include "CLG_log.h" @@ -90,15 +90,15 @@ void BKE_mesh_calc_normals_mapping_simple(struct Mesh *mesh) mesh->mpoly, mesh->totloop, mesh->totpoly, - NULL, + nullptr, mesh->mface, mesh->totface, - NULL, - NULL, + nullptr, + nullptr, only_face_normals); } -/* Calculate vertex and face normals, face normals are returned in *r_faceNors if non-NULL +/* Calculate vertex and face normals, face normals are returned in *r_faceNors if non-nullptr * and vertex normals are stored in actual mverts. */ void BKE_mesh_calc_normals_mapping(MVert *mverts, @@ -150,13 +150,13 @@ void BKE_mesh_calc_normals_mapping_ex(MVert *mverts, } /* if we are not calculating verts and no verts were passes then we have nothing to do */ - if ((only_face_normals == true) && (r_polyNors == NULL) && (r_faceNors == NULL)) { + if ((only_face_normals == true) && (r_polyNors == nullptr) && (r_faceNors == nullptr)) { CLOG_WARN(&LOG, "called with nothing to do"); return; } if (!pnors) { - pnors = MEM_calloc_arrayN((size_t)numPolys, sizeof(float[3]), __func__); + pnors = (float(*)[3])MEM_calloc_arrayN((size_t)numPolys, sizeof(float[3]), __func__); } /* NO NEED TO ALLOC YET */ /* if (!fnors) fnors = MEM_calloc_arrayN(numFaces, sizeof(float[3]), "face nors mesh.c"); */ @@ -165,7 +165,7 @@ void BKE_mesh_calc_normals_mapping_ex(MVert *mverts, /* vertex normals are optional, they require some extra calculations, * so make them optional */ BKE_mesh_calc_normals_poly( - mverts, NULL, numVerts, mloop, mpolys, numLoops, numPolys, pnors, false); + mverts, nullptr, numVerts, mloop, mpolys, numLoops, numPolys, pnors, false); } else { /* only calc poly normals */ @@ -177,7 +177,7 @@ void BKE_mesh_calc_normals_mapping_ex(MVert *mverts, if (origIndexFace && /* fnors == r_faceNors */ /* NO NEED TO ALLOC YET */ - fnors != NULL && + fnors != nullptr && numFaces) { const MFace *mf = mfaces; for (int i = 0; i < numFaces; i++, mf++, origIndexFace++) { @@ -196,23 +196,23 @@ void BKE_mesh_calc_normals_mapping_ex(MVert *mverts, } /* if (fnors != r_faceNors) MEM_freeN(fnors); */ /* NO NEED TO ALLOC YET */ - fnors = pnors = NULL; + fnors = pnors = nullptr; } -typedef struct MeshCalcNormalsData { +struct MeshCalcNormalsData { const MPoly *mpolys; const MLoop *mloop; MVert *mverts; float (*pnors)[3]; float (*lnors_weighted)[3]; float (*vnors)[3]; -} MeshCalcNormalsData; +}; static void mesh_calc_normals_poly_cb(void *__restrict userdata, const int pidx, const TaskParallelTLS *__restrict UNUSED(tls)) { - MeshCalcNormalsData *data = userdata; + MeshCalcNormalsData *data = (MeshCalcNormalsData *)userdata; const MPoly *mp = &data->mpolys[pidx]; BKE_mesh_calc_poly_normal(mp, data->mloop + mp->loopstart, data->mverts, data->pnors[pidx]); @@ -222,7 +222,7 @@ static void mesh_calc_normals_poly_prepare_cb(void *__restrict userdata, const int pidx, const TaskParallelTLS *__restrict UNUSED(tls)) { - MeshCalcNormalsData *data = userdata; + MeshCalcNormalsData *data = (MeshCalcNormalsData *)userdata; const MPoly *mp = &data->mpolys[pidx]; const MLoop *ml = &data->mloop[mp->loopstart]; const MVert *mverts = data->mverts; @@ -232,7 +232,7 @@ static void mesh_calc_normals_poly_prepare_cb(void *__restrict userdata, float(*lnors_weighted)[3] = data->lnors_weighted; const int nverts = mp->totloop; - float(*edgevecbuf)[3] = BLI_array_alloca(edgevecbuf, (size_t)nverts); + float(*edgevecbuf)[3] = (float(*)[3])BLI_array_alloca(edgevecbuf, (size_t)nverts); /* Polygon Normal and edge-vector */ /* inline version of #BKE_mesh_calc_poly_normal, also does edge-vectors */ @@ -285,7 +285,7 @@ static void mesh_calc_normals_poly_finalize_cb(void *__restrict userdata, const int vidx, const TaskParallelTLS *__restrict UNUSED(tls)) { - MeshCalcNormalsData *data = userdata; + MeshCalcNormalsData *data = (MeshCalcNormalsData *)userdata; MVert *mv = &data->mverts[vidx]; float *no = data->vnors[vidx]; @@ -315,42 +315,40 @@ void BKE_mesh_calc_normals_poly(MVert *mverts, settings.min_iter_per_thread = 1024; if (only_face_normals) { - BLI_assert((pnors != NULL) || (numPolys == 0)); - BLI_assert(r_vertnors == NULL); - - MeshCalcNormalsData data = { - .mpolys = mpolys, - .mloop = mloop, - .mverts = mverts, - .pnors = pnors, - }; + BLI_assert((pnors != nullptr) || (numPolys == 0)); + BLI_assert(r_vertnors == nullptr); + + MeshCalcNormalsData data; + data.mpolys = mpolys; + data.mloop = mloop; + data.mverts = mverts; + data.pnors = pnors; BLI_task_parallel_range(0, numPolys, &data, mesh_calc_normals_poly_cb, &settings); return; } float(*vnors)[3] = r_vertnors; - float(*lnors_weighted)[3] = MEM_malloc_arrayN( + float(*lnors_weighted)[3] = (float(*)[3])MEM_malloc_arrayN( (size_t)numLoops, sizeof(*lnors_weighted), __func__); bool free_vnors = false; /* first go through and calculate normals for all the polys */ - if (vnors == NULL) { - vnors = MEM_calloc_arrayN((size_t)numVerts, sizeof(*vnors), __func__); + if (vnors == nullptr) { + vnors = (float(*)[3])MEM_calloc_arrayN((size_t)numVerts, sizeof(*vnors), __func__); free_vnors = true; } else { memset(vnors, 0, sizeof(*vnors) * (size_t)numVerts); } - MeshCalcNormalsData data = { - .mpolys = mpolys, - .mloop = mloop, - .mverts = mverts, - .pnors = pnors, - .lnors_weighted = lnors_weighted, - .vnors = vnors, - }; + MeshCalcNormalsData data; + data.mpolys = mpolys; + data.mloop = mloop; + data.mverts = mverts; + data.pnors = pnors; + data.lnors_weighted = lnors_weighted; + data.vnors = vnors; /* Compute poly normals, and prepare weighted loop normals. */ BLI_task_parallel_range(0, numPolys, &data, mesh_calc_normals_poly_prepare_cb, &settings); @@ -400,19 +398,21 @@ void BKE_mesh_ensure_normals_for_display(Mesh *mesh) } } - float(*poly_nors)[3] = CustomData_get_layer(&mesh->pdata, CD_NORMAL); + float(*poly_nors)[3] = (float(*)[3])CustomData_get_layer(&mesh->pdata, CD_NORMAL); const bool do_vert_normals = (mesh->runtime.cd_dirty_vert & CD_MASK_NORMAL) != 0; - const bool do_poly_normals = (mesh->runtime.cd_dirty_poly & CD_MASK_NORMAL || poly_nors == NULL); + const bool do_poly_normals = (mesh->runtime.cd_dirty_poly & CD_MASK_NORMAL || + poly_nors == nullptr); if (do_vert_normals || do_poly_normals) { - const bool do_add_poly_nors_cddata = (poly_nors == NULL); + const bool do_add_poly_nors_cddata = (poly_nors == nullptr); if (do_add_poly_nors_cddata) { - poly_nors = MEM_malloc_arrayN((size_t)mesh->totpoly, sizeof(*poly_nors), __func__); + poly_nors = (float(*)[3])MEM_malloc_arrayN( + (size_t)mesh->totpoly, sizeof(*poly_nors), __func__); } /* calculate poly/vert normals */ BKE_mesh_calc_normals_poly(mesh->mvert, - NULL, + nullptr, mesh->totvert, mesh->mloop, mesh->mpoly, @@ -438,13 +438,13 @@ void BKE_mesh_calc_normals(Mesh *mesh) TIMEIT_START_AVERAGED(BKE_mesh_calc_normals); #endif BKE_mesh_calc_normals_poly(mesh->mvert, - NULL, + nullptr, mesh->totvert, mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, - NULL, + nullptr, false); #ifdef DEBUG_TIME TIMEIT_END_AVERAGED(BKE_mesh_calc_normals); @@ -459,10 +459,10 @@ void BKE_mesh_calc_normals_looptri(MVert *mverts, int looptri_num, float (*r_tri_nors)[3]) { - float(*tnorms)[3] = MEM_calloc_arrayN((size_t)numVerts, sizeof(*tnorms), "tnorms"); - float(*fnors)[3] = (r_tri_nors) ? - r_tri_nors : - MEM_calloc_arrayN((size_t)looptri_num, sizeof(*fnors), "meshnormals"); + float(*tnorms)[3] = (float(*)[3])MEM_calloc_arrayN((size_t)numVerts, sizeof(*tnorms), "tnorms"); + float(*fnors)[3] = (r_tri_nors) ? r_tri_nors : + (float(*)[3])MEM_calloc_arrayN( + (size_t)looptri_num, sizeof(*fnors), "meshnormals"); if (!tnorms || !fnors) { goto cleanup; @@ -519,9 +519,10 @@ void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, lnors_spacearr->mem = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__); } mem = lnors_spacearr->mem; - lnors_spacearr->lspacearr = BLI_memarena_calloc(mem, - sizeof(MLoopNorSpace *) * (size_t)numLoops); - lnors_spacearr->loops_pool = BLI_memarena_alloc(mem, sizeof(LinkNode) * (size_t)numLoops); + lnors_spacearr->lspacearr = (MLoopNorSpace **)BLI_memarena_calloc( + mem, sizeof(MLoopNorSpace *) * (size_t)numLoops); + lnors_spacearr->loops_pool = (LinkNode *)BLI_memarena_alloc( + mem, sizeof(LinkNode) * (size_t)numLoops); lnors_spacearr->num_spaces = 0; } @@ -532,9 +533,9 @@ void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, void BKE_lnor_spacearr_clear(MLoopNorSpaceArray *lnors_spacearr) { lnors_spacearr->num_spaces = 0; - lnors_spacearr->lspacearr = NULL; - lnors_spacearr->loops_pool = NULL; - if (lnors_spacearr->mem != NULL) { + lnors_spacearr->lspacearr = nullptr; + lnors_spacearr->loops_pool = nullptr; + if (lnors_spacearr->mem != nullptr) { BLI_memarena_clear(lnors_spacearr->mem); } } @@ -542,16 +543,16 @@ void BKE_lnor_spacearr_clear(MLoopNorSpaceArray *lnors_spacearr) void BKE_lnor_spacearr_free(MLoopNorSpaceArray *lnors_spacearr) { lnors_spacearr->num_spaces = 0; - lnors_spacearr->lspacearr = NULL; - lnors_spacearr->loops_pool = NULL; + lnors_spacearr->lspacearr = nullptr; + lnors_spacearr->loops_pool = nullptr; BLI_memarena_free(lnors_spacearr->mem); - lnors_spacearr->mem = NULL; + lnors_spacearr->mem = nullptr; } MLoopNorSpace *BKE_lnor_space_create(MLoopNorSpaceArray *lnors_spacearr) { lnors_spacearr->num_spaces++; - return BLI_memarena_calloc(lnors_spacearr->mem, sizeof(MLoopNorSpace)); + return (MLoopNorSpace *)BLI_memarena_calloc(lnors_spacearr->mem, sizeof(MLoopNorSpace)); } /* This threshold is a bit touchy (usual float precision issue), this value seems OK. */ @@ -592,12 +593,12 @@ void BKE_lnor_space_define(MLoopNorSpace *lnor_space, float alpha = 0.0f; int nbr = 0; while (!BLI_stack_is_empty(edge_vectors)) { - const float *vec = BLI_stack_peek(edge_vectors); + const float *vec = (const float *)BLI_stack_peek(edge_vectors); alpha += saacosf(dot_v3v3(vec, lnor)); BLI_stack_discard(edge_vectors); nbr++; } - /* Note: In theory, this could be 'nbr > 2', + /* NOTE: In theory, this could be 'nbr > 2', * but there is one case where we only have two edges for two loops: * a smooth vertex with only two edges and two faces (our Monkey's nose has that, e.g.). */ @@ -637,10 +638,10 @@ void BKE_lnor_space_define(MLoopNorSpace *lnor_space, /** * Add a new given loop to given lnor_space. * Depending on \a lnor_space->data_type, we expect \a bm_loop to be a pointer to BMLoop struct - * (in case of BMLOOP_PTR), or NULL (in case of LOOP_INDEX), loop index is then stored in pointer. - * If \a is_single is set, the BMLoop or loop index is directly stored in \a lnor_space->loops - * pointer (since there is only one loop in this fan), - * else it is added to the linked list of loops in the fan. + * (in case of BMLOOP_PTR), or nullptr (in case of LOOP_INDEX), loop index is then stored in + * pointer. If \a is_single is set, the BMLoop or loop index is directly stored in \a + * lnor_space->loops pointer (since there is only one loop in this fan), else it is added to the + * linked list of loops in the fan. */ void BKE_lnor_space_add_loop(MLoopNorSpaceArray *lnors_spacearr, MLoopNorSpace *lnor_space, @@ -648,17 +649,17 @@ void BKE_lnor_space_add_loop(MLoopNorSpaceArray *lnors_spacearr, void *bm_loop, const bool is_single) { - BLI_assert((lnors_spacearr->data_type == MLNOR_SPACEARR_LOOP_INDEX && bm_loop == NULL) || - (lnors_spacearr->data_type == MLNOR_SPACEARR_BMLOOP_PTR && bm_loop != NULL)); + BLI_assert((lnors_spacearr->data_type == MLNOR_SPACEARR_LOOP_INDEX && bm_loop == nullptr) || + (lnors_spacearr->data_type == MLNOR_SPACEARR_BMLOOP_PTR && bm_loop != nullptr)); lnors_spacearr->lspacearr[ml_index] = lnor_space; - if (bm_loop == NULL) { + if (bm_loop == nullptr) { bm_loop = POINTER_FROM_INT(ml_index); } if (is_single) { - BLI_assert(lnor_space->loops == NULL); + BLI_assert(lnor_space->loops == nullptr); lnor_space->flags |= MLNOR_SPACE_IS_SINGLE; - lnor_space->loops = bm_loop; + lnor_space->loops = (LinkNode *)bm_loop; } else { BLI_assert((lnor_space->flags & MLNOR_SPACE_IS_SINGLE) == 0); @@ -688,8 +689,8 @@ void BKE_lnor_space_custom_data_to_normal(MLoopNorSpace *lnor_space, } { - /* TODO Check whether using sincosf() gives any noticeable benefit - * (could not even get it working under linux though)! */ + /* TODO: Check whether using #sincosf() gives any noticeable benefit + * (could not even get it working under linux though)! */ const float pi2 = (float)(M_PI * 2.0); const float alphafac = unit_short_to_float(clnor_data[0]); const float alpha = (alphafac > 0.0f ? lnor_space->ref_alpha : pi2 - lnor_space->ref_alpha) * @@ -715,7 +716,8 @@ void BKE_lnor_space_custom_normal_to_data(MLoopNorSpace *lnor_space, const float custom_lnor[3], short r_clnor_data[2]) { - /* We use null vector as NOP custom normal (can be simpler than giving auto-computed `lnor`). */ + /* We use nullptr vector as NOP custom normal (can be simpler than giving auto-computed `lnor`). + */ if (is_zero_v3(custom_lnor) || compare_v3v3(lnor_space->vec_lnor, custom_lnor, 1e-4f)) { r_clnor_data[0] = r_clnor_data[1] = 0; return; @@ -765,7 +767,7 @@ void BKE_lnor_space_custom_normal_to_data(MLoopNorSpace *lnor_space, #define LOOP_SPLIT_TASK_BLOCK_SIZE 1024 -typedef struct LoopSplitTaskData { +struct LoopSplitTaskData { /* Specific to each instance (each task). */ /** We have to create those outside of tasks, since #MemArena is not thread-safe. */ @@ -784,9 +786,9 @@ typedef struct LoopSplitTaskData { BLI_Stack *edge_vectors; char pad_c; -} LoopSplitTaskData; +}; -typedef struct LoopSplitTaskDataCommon { +struct LoopSplitTaskDataCommon { /* Read/write. * Note we do not need to protect it, though, since two different tasks will *always* affect * different elements in the arrays. */ @@ -806,7 +808,7 @@ typedef struct LoopSplitTaskDataCommon { int numEdges; int numLoops; int numPolys; -} LoopSplitTaskDataCommon; +}; #define INDEX_UNSET INT_MIN #define INDEX_INVALID -1 @@ -827,13 +829,13 @@ static void mesh_edges_sharp_tag(LoopSplitTaskDataCommon *data, const int numEdges = data->numEdges; const int numPolys = data->numPolys; - float(*loopnors)[3] = data->loopnors; /* Note: loopnors may be NULL here. */ + float(*loopnors)[3] = data->loopnors; /* NOTE: loopnors may be nullptr here. */ const float(*polynors)[3] = data->polynors; int(*edge_to_loops)[2] = data->edge_to_loops; int *loop_to_poly = data->loop_to_poly; - BLI_bitmap *sharp_edges = do_sharp_edges_tag ? BLI_BITMAP_NEW(numEdges, __func__) : NULL; + BLI_bitmap *sharp_edges = do_sharp_edges_tag ? BLI_BITMAP_NEW(numEdges, __func__) : nullptr; const MPoly *mp; int mp_index; @@ -879,7 +881,7 @@ static void mesh_edges_sharp_tag(LoopSplitTaskDataCommon *data, */ if (!(mp->flag & ME_SMOOTH) || (medges[ml_curr->e].flag & ME_SHARP) || ml_curr->v == mloops[e2l[0]].v || is_angle_sharp) { - /* Note: we are sure that loop != 0 here ;) */ + /* NOTE: we are sure that loop != 0 here ;). */ e2l[1] = INDEX_INVALID; /* We want to avoid tagging edges as sharp when it is already defined as such by @@ -943,22 +945,22 @@ void BKE_edges_sharp_from_angle_set(const struct MVert *mverts, } /* Mapping edge -> loops. See BKE_mesh_normals_loop_split() for details. */ - int(*edge_to_loops)[2] = MEM_calloc_arrayN((size_t)numEdges, sizeof(*edge_to_loops), __func__); + int(*edge_to_loops)[2] = (int(*)[2])MEM_calloc_arrayN( + (size_t)numEdges, sizeof(*edge_to_loops), __func__); /* Simple mapping from a loop to its polygon index. */ - int *loop_to_poly = MEM_malloc_arrayN((size_t)numLoops, sizeof(*loop_to_poly), __func__); - - LoopSplitTaskDataCommon common_data = { - .mverts = mverts, - .medges = medges, - .mloops = mloops, - .mpolys = mpolys, - .edge_to_loops = edge_to_loops, - .loop_to_poly = loop_to_poly, - .polynors = polynors, - .numEdges = numEdges, - .numPolys = numPolys, - }; + int *loop_to_poly = (int *)MEM_malloc_arrayN((size_t)numLoops, sizeof(*loop_to_poly), __func__); + + LoopSplitTaskDataCommon common_data; + common_data.mverts = mverts; + common_data.medges = medges; + common_data.mloops = mloops; + common_data.mpolys = mpolys; + common_data.edge_to_loops = edge_to_loops; + common_data.loop_to_poly = loop_to_poly; + common_data.polynors = polynors; + common_data.numEdges = numEdges; + common_data.numPolys = numPolys; mesh_edges_sharp_tag(&common_data, true, split_angle, true); @@ -1065,10 +1067,10 @@ static void split_loop_nor_single_do(LoopSplitTaskDataCommon *common_data, LoopS sub_v3_v3v3(vec_prev, mv_3->co, mv_pivot->co); normalize_v3(vec_prev); - BKE_lnor_space_define(lnor_space, *lnor, vec_curr, vec_prev, NULL); + BKE_lnor_space_define(lnor_space, *lnor, vec_curr, vec_prev, nullptr); /* We know there is only one loop in this space, * no need to create a linklist in this case... */ - BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, ml_curr_index, NULL, true); + BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, ml_curr_index, nullptr, true); if (clnors_data) { BKE_lnor_space_custom_data_to_normal(lnor_space, clnors_data[ml_curr_index], *lnor); @@ -1125,7 +1127,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli /* We validate clnors data on the fly - cheapest way to do! */ int clnors_avg[2] = {0, 0}; - short(*clnor_ref)[2] = NULL; + short(*clnor_ref)[2] = nullptr; int clnors_nbr = 0; bool clnors_invalid = false; @@ -1205,7 +1207,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli if (lnors_spacearr) { /* Assign current lnor space to current 'vertex' loop. */ - BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, mlfan_vert_index, NULL, false); + BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, mlfan_vert_index, nullptr, false); if (me_curr != me_org) { /* We store here all edges-normalized vectors processed. */ BLI_stack_push(edge_vectors, vec_curr); @@ -1261,7 +1263,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli if (G.debug & G_DEBUG) { printf("Invalid clnors in this fan!\n"); } - while ((clnor = BLI_SMALLSTACK_POP(clnors))) { + while ((clnor = (short *)BLI_SMALLSTACK_POP(clnors))) { // print_v2("org clnor", clnor); clnor[0] = (short)clnors_avg[0]; clnor[1] = (short)clnors_avg[1]; @@ -1280,7 +1282,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli /* Copy back the final computed normal into all related loop-normals. */ float *nor; - while ((nor = BLI_SMALLSTACK_POP(normal))) { + while ((nor = (float *)BLI_SMALLSTACK_POP(normal))) { copy_v3_v3(nor, lnor); } } @@ -1295,7 +1297,7 @@ static void loop_split_worker_do(LoopSplitTaskDataCommon *common_data, { BLI_assert(data->ml_curr); if (data->e2l_prev) { - BLI_assert((edge_vectors == NULL) || BLI_stack_is_empty(edge_vectors)); + BLI_assert((edge_vectors == nullptr) || BLI_stack_is_empty(edge_vectors)); data->edge_vectors = edge_vectors; split_loop_nor_fan_do(common_data, data); } @@ -1307,21 +1309,21 @@ static void loop_split_worker_do(LoopSplitTaskDataCommon *common_data, static void loop_split_worker(TaskPool *__restrict pool, void *taskdata) { - LoopSplitTaskDataCommon *common_data = BLI_task_pool_user_data(pool); - LoopSplitTaskData *data = taskdata; + LoopSplitTaskDataCommon *common_data = (LoopSplitTaskDataCommon *)BLI_task_pool_user_data(pool); + LoopSplitTaskData *data = (LoopSplitTaskData *)taskdata; /* Temp edge vectors stack, only used when computing lnor spacearr. */ BLI_Stack *edge_vectors = common_data->lnors_spacearr ? BLI_stack_new(sizeof(float[3]), __func__) : - NULL; + nullptr; #ifdef DEBUG_TIME TIMEIT_START_AVERAGED(loop_split_worker); #endif for (int i = 0; i < LOOP_SPLIT_TASK_BLOCK_SIZE; i++, data++) { - /* A NULL ml_curr is used to tag ended data! */ - if (data->ml_curr == NULL) { + /* A nullptr ml_curr is used to tag ended data! */ + if (data->ml_curr == nullptr) { break; } @@ -1434,12 +1436,12 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common BLI_bitmap *skip_loops = BLI_BITMAP_NEW(numLoops, __func__); - LoopSplitTaskData *data_buff = NULL; + LoopSplitTaskData *data_buff = nullptr; int data_idx = 0; /* Temp edge vectors stack, only used when computing lnor spacearr * (and we are not multi-threading). */ - BLI_Stack *edge_vectors = NULL; + BLI_Stack *edge_vectors = nullptr; #ifdef DEBUG_TIME TIMEIT_START_AVERAGED(loop_split_generator); @@ -1481,7 +1483,7 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge * as 'entry point', otherwise we can skip it. */ - /* Note: In theory, we could make #loop_split_generator_check_cyclic_smooth_fan() store + /* NOTE: In theory, we could make #loop_split_generator_check_cyclic_smooth_fan() store * mlfan_vert_index'es and edge indexes in two stacks, to avoid having to fan again around * the vert during actual computation of `clnor` & `clnorspace`. * However, this would complicate the code, add more memory usage, and despite its logical @@ -1508,7 +1510,7 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common if (pool) { if (data_idx == 0) { - data_buff = MEM_calloc_arrayN( + data_buff = (LoopSplitTaskData *)MEM_calloc_arrayN( LOOP_SPLIT_TASK_BLOCK_SIZE, sizeof(*data_buff), __func__); } data = &data_buff[data_idx]; @@ -1525,7 +1527,7 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common data->ml_curr_index = ml_curr_index; #if 0 /* Not needed for 'single' loop. */ data->ml_prev_index = ml_prev_index; - data->e2l_prev = NULL; /* Tag as 'single' task. */ + data->e2l_prev = nullptr; /* Tag as 'single' task. */ #endif data->mp_index = mp_index; if (lnors_spacearr) { @@ -1559,7 +1561,7 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common if (pool) { data_idx++; if (data_idx == LOOP_SPLIT_TASK_BLOCK_SIZE) { - BLI_task_pool_push(pool, loop_split_worker, data_buff, true, NULL); + BLI_task_pool_push(pool, loop_split_worker, data_buff, true, nullptr); data_idx = 0; } } @@ -1573,10 +1575,10 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common } } - /* Last block of data... Since it is calloc'ed and we use first NULL item as stopper, + /* Last block of data... Since it is calloc'ed and we use first nullptr item as stopper, * everything is fine. */ if (pool && data_idx) { - BLI_task_pool_push(pool, loop_split_worker, data_buff, true, NULL); + BLI_task_pool_push(pool, loop_split_worker, data_buff, true, nullptr); } if (edge_vectors) { @@ -1659,17 +1661,18 @@ void BKE_mesh_normals_loop_split(const MVert *mverts, * However, if needed, we can store the negated value of loop index instead of INDEX_INVALID * to retrieve the real value later in code). * Note also that loose edges always have both values set to 0! */ - int(*edge_to_loops)[2] = MEM_calloc_arrayN((size_t)numEdges, sizeof(*edge_to_loops), __func__); + int(*edge_to_loops)[2] = (int(*)[2])MEM_calloc_arrayN( + (size_t)numEdges, sizeof(*edge_to_loops), __func__); /* Simple mapping from a loop to its polygon index. */ - int *loop_to_poly = r_loop_to_poly ? - r_loop_to_poly : - MEM_malloc_arrayN((size_t)numLoops, sizeof(*loop_to_poly), __func__); + int *loop_to_poly = r_loop_to_poly ? r_loop_to_poly : + (int *)MEM_malloc_arrayN( + (size_t)numLoops, sizeof(*loop_to_poly), __func__); /* When using custom loop normals, disable the angle feature! */ - const bool check_angle = (split_angle < (float)M_PI) && (clnors_data == NULL); + const bool check_angle = (split_angle < (float)M_PI) && (clnors_data == nullptr); - MLoopNorSpaceArray _lnors_spacearr = {NULL}; + MLoopNorSpaceArray _lnors_spacearr = {nullptr}; #ifdef DEBUG_TIME TIMEIT_START_AVERAGED(BKE_mesh_normals_loop_split); @@ -1684,28 +1687,27 @@ void BKE_mesh_normals_loop_split(const MVert *mverts, } /* Init data common to all tasks. */ - LoopSplitTaskDataCommon common_data = { - .lnors_spacearr = r_lnors_spacearr, - .loopnors = r_loopnors, - .clnors_data = clnors_data, - .mverts = mverts, - .medges = medges, - .mloops = mloops, - .mpolys = mpolys, - .edge_to_loops = edge_to_loops, - .loop_to_poly = loop_to_poly, - .polynors = polynors, - .numEdges = numEdges, - .numLoops = numLoops, - .numPolys = numPolys, - }; + LoopSplitTaskDataCommon common_data; + common_data.lnors_spacearr = r_lnors_spacearr; + common_data.loopnors = r_loopnors; + common_data.clnors_data = clnors_data; + common_data.mverts = mverts; + common_data.medges = medges; + common_data.mloops = mloops; + common_data.mpolys = mpolys; + common_data.edge_to_loops = edge_to_loops; + common_data.loop_to_poly = loop_to_poly; + common_data.polynors = polynors; + common_data.numEdges = numEdges; + common_data.numLoops = numLoops; + common_data.numPolys = numPolys; /* This first loop check which edges are actually smooth, and compute edge vectors. */ mesh_edges_sharp_tag(&common_data, check_angle, split_angle, false); if (numLoops < LOOP_SPLIT_TASK_BLOCK_SIZE * 8) { /* Not enough loops to be worth the whole threading overhead... */ - loop_split_generator(NULL, &common_data); + loop_split_generator(nullptr, &common_data); } else { TaskPool *task_pool = BLI_task_pool_create(&common_data, TASK_PRIORITY_HIGH); @@ -1766,10 +1768,10 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, * (and perhaps from some editing tools later?). * So better to keep some simplicity here, and just call BKE_mesh_normals_loop_split() twice! */ - MLoopNorSpaceArray lnors_spacearr = {NULL}; + MLoopNorSpaceArray lnors_spacearr = {nullptr}; BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)numLoops, __func__); - float(*lnors)[3] = MEM_calloc_arrayN((size_t)numLoops, sizeof(*lnors), __func__); - int *loop_to_poly = MEM_malloc_arrayN((size_t)numLoops, sizeof(int), __func__); + float(*lnors)[3] = (float(*)[3])MEM_calloc_arrayN((size_t)numLoops, sizeof(*lnors), __func__); + int *loop_to_poly = (int *)MEM_malloc_arrayN((size_t)numLoops, sizeof(int), __func__); /* In this case we always consider split nors as ON, * and do not want to use angle to define smooth fans! */ const bool use_split_normals = true; @@ -1791,7 +1793,7 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, use_split_normals, split_angle, &lnors_spacearr, - NULL, + nullptr, loop_to_poly); /* Set all given zero vectors to their default value. */ @@ -1823,12 +1825,12 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, for (int i = 0; i < numLoops; i++) { if (!lnors_spacearr.lspacearr[i]) { /* This should not happen in theory, but in some rare case (probably ugly geometry) - * we can get some NULL loopspacearr at this point. :/ + * we can get some nullptr loopspacearr at this point. :/ * Maybe we should set those loops' edges as sharp? */ BLI_BITMAP_ENABLE(done_loops, i); if (G.debug & G_DEBUG) { - printf("WARNING! Getting invalid NULL loop space for loop %d!\n", i); + printf("WARNING! Getting invalid nullptr loop space for loop %d!\n", i); } continue; } @@ -1849,8 +1851,8 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, } LinkNode *loops = lnors_spacearr.lspacearr[i]->loops; - MLoop *prev_ml = NULL; - const float *org_nor = NULL; + MLoop *prev_ml = nullptr; + const float *org_nor = nullptr; while (loops) { const int lidx = POINTER_AS_INT(loops->link); @@ -1916,7 +1918,7 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, use_split_normals, split_angle, &lnors_spacearr, - NULL, + nullptr, loop_to_poly); } else { @@ -1929,7 +1931,8 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, if (!lnors_spacearr.lspacearr[i]) { BLI_BITMAP_DISABLE(done_loops, i); if (G.debug & G_DEBUG) { - printf("WARNING! Still getting invalid NULL loop space in second loop for loop %d!\n", i); + printf("WARNING! Still getting invalid nullptr loop space in second loop for loop %d!\n", + i); } continue; } @@ -1970,7 +1973,7 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, mul_v3_fl(avg_nor, 1.0f / (float)nbr_nors); BKE_lnor_space_custom_normal_to_data(lnors_spacearr.lspacearr[i], avg_nor, clnor_data_tmp); - while ((clnor_data = BLI_SMALLSTACK_POP(clnors_data))) { + while ((clnor_data = (short *)BLI_SMALLSTACK_POP(clnors_data))) { clnor_data[0] = clnor_data_tmp[0]; clnor_data[1] = clnor_data_tmp[1]; } @@ -2041,20 +2044,21 @@ static void mesh_set_custom_normals(Mesh *mesh, float (*r_custom_nors)[3], const short(*clnors)[2]; const int numloops = mesh->totloop; - clnors = CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL); - if (clnors != NULL) { + clnors = (short(*)[2])CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL); + if (clnors != nullptr) { memset(clnors, 0, sizeof(*clnors) * (size_t)numloops); } else { - clnors = CustomData_add_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL, CD_CALLOC, NULL, numloops); + clnors = (short(*)[2])CustomData_add_layer( + &mesh->ldata, CD_CUSTOMLOOPNORMAL, CD_CALLOC, nullptr, numloops); } - float(*polynors)[3] = CustomData_get_layer(&mesh->pdata, CD_NORMAL); + float(*polynors)[3] = (float(*)[3])CustomData_get_layer(&mesh->pdata, CD_NORMAL); bool free_polynors = false; - if (polynors == NULL) { - polynors = MEM_mallocN(sizeof(float[3]) * (size_t)mesh->totpoly, __func__); + if (polynors == nullptr) { + polynors = (float(*)[3])MEM_mallocN(sizeof(float[3]) * (size_t)mesh->totpoly, __func__); BKE_mesh_calc_normals_poly(mesh->mvert, - NULL, + nullptr, mesh->totvert, mesh->mloop, mesh->mpoly, @@ -2119,7 +2123,8 @@ void BKE_mesh_normals_loop_to_vertex(const int numVerts, const float (*clnors)[3], float (*r_vert_clnors)[3]) { - int *vert_loops_nbr = MEM_calloc_arrayN((size_t)numVerts, sizeof(*vert_loops_nbr), __func__); + int *vert_loops_nbr = (int *)MEM_calloc_arrayN( + (size_t)numVerts, sizeof(*vert_loops_nbr), __func__); copy_vn_fl((float *)r_vert_clnors, 3 * numVerts, 0.0f); diff --git a/source/blender/blenkernel/intern/mesh_remap.c b/source/blender/blenkernel/intern/mesh_remap.c index b7cff624a04..c5e8858ea12 100644 --- a/source/blender/blenkernel/intern/mesh_remap.c +++ b/source/blender/blenkernel/intern/mesh_remap.c @@ -216,7 +216,7 @@ static void mesh_calc_eigen_matrix(const MVert *verts, } unit_m4(r_mat); - /* Note: here we apply sample correction to covariance matrix, since we consider the vertices + /* NOTE: here we apply sample correction to covariance matrix, since we consider the vertices * as a sample of the whole 'surface' population of our mesh. */ BLI_covariance_m3_v3n(vcos, numverts, true, covmat, center); @@ -256,7 +256,7 @@ static void mesh_calc_eigen_matrix(const MVert *verts, float evi = eigen_val[i]; /* Protect against 1D/2D degenerated cases! */ - /* Note: not sure why we need square root of eigen values here + /* NOTE: not sure why we need square root of eigen values here * (which are equivalent to singular values, as far as I have understood), * but it seems to heavily reduce (if not completely nullify) * the error due to non-uniform scalings... */ @@ -470,7 +470,7 @@ typedef struct IslandResult { } IslandResult; /** - * \note About all bvh/raycasting stuff below: + * \note About all BVH/ray-casting stuff below: * * * We must use our ray radius as BVH epsilon too, else rays not hitting anything but * 'passing near' an item would be missed (since BVH handling would not detect them, @@ -478,8 +478,8 @@ typedef struct IslandResult { * * However, in 'islands' case where each hit gets a weight, 'precise' hits should have a better * weight than 'approximate' hits. * To address that, we simplify things with: - * * A first raycast with default, given rayradius; - * * If first one fails, we do more raycasting with bigger radius, but if hit is found + * * A first ray-cast with default, given ray-radius; + * * If first one fails, we do more ray-casting with bigger radius, but if hit is found * it will get smaller weight. * * This only concerns loops, currently (because of islands), and 'sampled' edges/polys norproj. @@ -1035,7 +1035,7 @@ void BKE_mesh_remap_calc_edges_from_mesh(const int mode, if (!weights[j]) { continue; } - /* Note: sources_num is always <= j! */ + /* NOTE: sources_num is always <= j! */ weights[sources_num] = weights[j] / totweights; indices[sources_num] = j; sources_num++; @@ -2332,7 +2332,7 @@ void BKE_mesh_remap_calc_polys_from_mesh(const int mode, for (i = 0; i < numpolys_dst; i++) { /* For each dst poly, we sample some rays from it (2D grid in pnor space) * and use their hits to interpolate from source polys. */ - /* Note: dst poly is early-converted into src space! */ + /* NOTE: dst poly is early-converted into src space! */ MPoly *mp = &polys_dst[i]; int tot_rays, done_rays = 0; @@ -2465,7 +2465,7 @@ void BKE_mesh_remap_calc_polys_from_mesh(const int mode, if (!weights[j]) { continue; } - /* Note: sources_num is always <= j! */ + /* NOTE: sources_num is always <= j! */ weights[sources_num] = weights[j] / totweights; indices[sources_num] = j; sources_num++; diff --git a/source/blender/blenkernel/intern/mesh_runtime.c b/source/blender/blenkernel/intern/mesh_runtime.c index 011dd7e25ee..7ac4c29f0ee 100644 --- a/source/blender/blenkernel/intern/mesh_runtime.c +++ b/source/blender/blenkernel/intern/mesh_runtime.c @@ -158,8 +158,12 @@ static void mesh_runtime_looptri_recalc_isolated(void *userdata) BKE_mesh_runtime_looptri_recalc(mesh); } -/* This is a ported copy of dm_getLoopTriArray(dm). */ -const MLoopTri *BKE_mesh_runtime_looptri_ensure(Mesh *mesh) +/** + * \note This function only fills a cache, and therefore the mesh argument can + * be considered logically const. Concurrent access is protected by a mutex. + * \note This is a ported copy of dm_getLoopTriArray(dm). + */ +const MLoopTri *BKE_mesh_runtime_looptri_ensure(const Mesh *mesh) { ThreadMutex *mesh_eval_mutex = (ThreadMutex *)mesh->runtime.eval_mutex; BLI_mutex_lock(mesh_eval_mutex); @@ -171,7 +175,7 @@ const MLoopTri *BKE_mesh_runtime_looptri_ensure(Mesh *mesh) } else { /* Must isolate multithreaded tasks while holding a mutex lock. */ - BLI_task_isolate(mesh_runtime_looptri_recalc_isolated, mesh); + BLI_task_isolate(mesh_runtime_looptri_recalc_isolated, (void *)mesh); looptri = mesh->runtime.looptris.array; } @@ -286,7 +290,7 @@ static void mesh_runtime_debug_info_layers(DynStr *dynstr, CustomData *cd) for (type = 0; type < CD_NUMTYPES; type++) { if (CustomData_has_layer(cd, type)) { - /* note: doesn't account for multiple layers */ + /* NOTE: doesn't account for multiple layers. */ const char *name = CustomData_layertype_name(type); const int size = CustomData_sizeof(type); const void *pt = CustomData_get_layer(cd, type); diff --git a/source/blender/blenkernel/intern/mesh_tangent.c b/source/blender/blenkernel/intern/mesh_tangent.c index 2e22e521a13..e5e971fd574 100644 --- a/source/blender/blenkernel/intern/mesh_tangent.c +++ b/source/blender/blenkernel/intern/mesh_tangent.c @@ -119,7 +119,7 @@ static void set_tspace(const SMikkTSpaceContext *pContext, * Compute simplified tangent space normals, i.e. * tangent vector + sign of bi-tangent one, which combined with * split normals can be used to recreate the full tangent space. - * Note: * The mesh should be made of only tris and quads! + * NOTE: * The mesh should be made of only tris and quads! */ void BKE_mesh_calc_loop_tangent_single_ex(const MVert *mverts, const int UNUSED(numVerts), @@ -675,7 +675,7 @@ void BKE_mesh_calc_loop_tangent_ex(const MVert *mvert, mesh2tangent->mpoly = mpoly; mesh2tangent->mloop = mloop; mesh2tangent->looptri = looptri; - /* Note, we assume we do have tessellated loop normals at this point + /* NOTE: we assume we do have tessellated loop normals at this point * (in case it is object-enabled), have to check this is valid. */ mesh2tangent->precomputedLoopNormals = loop_normals; mesh2tangent->precomputedFaceNormals = poly_normals; diff --git a/source/blender/blenkernel/intern/mesh_validate.c b/source/blender/blenkernel/intern/mesh_validate.c index bfdbf844a26..08668d55cf4 100644 --- a/source/blender/blenkernel/intern/mesh_validate.c +++ b/source/blender/blenkernel/intern/mesh_validate.c @@ -154,7 +154,7 @@ static int search_face_cmp(const void *v1, const void *v2) return 0; } -/* TODO check there is not some standard define of this somewhere! */ +/* TODO: check there is not some standard define of this somewhere! */ static int int_cmp(const void *v1, const void *v2) { return *(int *)v1 > *(int *)v2 ? 1 : *(int *)v1 < *(int *)v2 ? -1 : 0; @@ -819,7 +819,7 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, MDeformWeight *dw; for (j = 0, dw = dv->dw; j < dv->totweight; j++, dw++) { - /* note, greater than max defgroups is accounted for in our code, but not < 0 */ + /* NOTE: greater than max defgroups is accounted for in our code, but not < 0. */ if (!isfinite(dw->weight)) { PRINT_ERR("\tVertex deform %u, group %u has weight: %f", i, dw->def_nr, dw->weight); if (do_fixes) { @@ -1287,7 +1287,7 @@ void BKE_mesh_strip_loose_polysloops(Mesh *me) } /* And now, update polys' start loop index. */ - /* Note: At this point, there should never be any poly using a striped loop! */ + /* NOTE: At this point, there should never be any poly using a striped loop! */ for (a = 0, p = me->mpoly; a < me->totpoly; a++, p++) { p->loopstart = new_idx[p->loopstart]; } diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index e60f0102b9a..2088c4268e6 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -156,7 +156,7 @@ ModifierData *BKE_modifier_new(int type) const ModifierTypeInfo *mti = BKE_modifier_get_info(type); ModifierData *md = MEM_callocN(mti->structSize, mti->structName); - /* note, this name must be made unique later */ + /* NOTE: this name must be made unique later. */ BLI_strncpy(md->name, DATA_(mti->name), sizeof(md->name)); md->type = type; diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c index 3a7910d1a9f..f32b0c434c1 100644 --- a/source/blender/blenkernel/intern/movieclip.c +++ b/source/blender/blenkernel/intern/movieclip.c @@ -287,7 +287,7 @@ static void movieclip_blend_read_data(BlendDataReader *reader, ID *id) clip->tracking_context = NULL; clip->tracking.stats = NULL; - /* TODO we could store those in undo cache storage as well, and preserve them instead of + /* TODO: we could store those in undo cache storage as well, and preserve them instead of * re-creating them... */ BLI_listbase_clear(&clip->runtime.gputextures); @@ -1849,7 +1849,7 @@ static void movieclip_build_proxy_ibuf( IMB_freeImBuf(scaleibuf); } -/* note: currently used by proxy job for movies, threading happens within single frame +/* NOTE: currently used by proxy job for movies, threading happens within single frame * (meaning scaling shall be threaded) */ void BKE_movieclip_build_proxy_frame(MovieClip *clip, @@ -1893,7 +1893,7 @@ void BKE_movieclip_build_proxy_frame(MovieClip *clip, } } -/* note: currently used by proxy job for sequences, threading happens within sequence +/* NOTE: currently used by proxy job for sequences, threading happens within sequence * (different threads handles different frames, no threading within frame is needed) */ void BKE_movieclip_build_proxy_frame_for_ibuf(MovieClip *clip, diff --git a/source/blender/blenkernel/intern/multires_inline.h b/source/blender/blenkernel/intern/multires_inline.h index e85aa12781e..f88b5dd3143 100644 --- a/source/blender/blenkernel/intern/multires_inline.h +++ b/source/blender/blenkernel/intern/multires_inline.h @@ -53,7 +53,7 @@ BLI_INLINE void BKE_multires_construct_tangent_matrix(float tangent_matrix[3][3] mul_v3_fl(tangent_matrix[0], -1.0f); } else { - BLI_assert(!"Unhandled corner index"); + BLI_assert_msg(0, "Unhandled corner index"); } cross_v3_v3v3(tangent_matrix[2], dPdu, dPdv); normalize_v3(tangent_matrix[0]); diff --git a/source/blender/blenkernel/intern/multires_reshape_smooth.c b/source/blender/blenkernel/intern/multires_reshape_smooth.c index aed8c3122a2..9fb158d2f84 100644 --- a/source/blender/blenkernel/intern/multires_reshape_smooth.c +++ b/source/blender/blenkernel/intern/multires_reshape_smooth.c @@ -1354,7 +1354,7 @@ static void evaluate_higher_grid_positions_with_details_callback( { const MultiresReshapeContext *reshape_context = reshape_smooth_context->reshape_context; - /* Position of the original veretx at top level. */ + /* Position of the original vertex at top level. */ float orig_final_P[3]; evaluate_final_original_point(reshape_smooth_context, grid_coord, orig_final_P); diff --git a/source/blender/blenkernel/intern/multires_unsubdivide.c b/source/blender/blenkernel/intern/multires_unsubdivide.c index 4210f26a694..501e3f27389 100644 --- a/source/blender/blenkernel/intern/multires_unsubdivide.c +++ b/source/blender/blenkernel/intern/multires_unsubdivide.c @@ -603,7 +603,7 @@ static void write_loop_in_face_grid( step_y[1] = 0; break; default: - BLI_assert(!"Should never happen"); + BLI_assert_msg(0, "Should never happen"); break; } diff --git a/source/blender/blenkernel/intern/nla.c b/source/blender/blenkernel/intern/nla.c index bf18765aa94..7e524da0f53 100644 --- a/source/blender/blenkernel/intern/nla.c +++ b/source/blender/blenkernel/intern/nla.c @@ -631,10 +631,10 @@ float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) { NlaStrip *strip; - /* sanity checks - * - obviously we've got to have some starting data - * - when not in tweakmode, the active Action does not have any scaling applied :) - * - when in tweakmode, if the no-mapping flag is set, do not map + /* Sanity checks: + * - Obviously we've got to have some starting data. + * - When not in tweak-mode, the active Action does not have any scaling applied :) + * - When in tweak-mode, if the no-mapping flag is set, do not map. */ if ((adt == NULL) || (adt->flag & ADT_NLA_EDIT_ON) == 0 || (adt->flag & ADT_NLA_EDIT_NOMAP)) { return cframe; @@ -2089,9 +2089,8 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) return false; } - /* if block is already in tweakmode, just leave, but we should report - * that this block is in tweakmode (as our returncode) - */ + /* If block is already in tweak-mode, just leave, but we should report + * that this block is in tweak-mode (as our returncode). */ if (adt->flag & ADT_NLA_EDIT_ON) { return true; } @@ -2111,8 +2110,8 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) } } - /* There are situations where we may have multiple strips selected and we want to enter tweakmode - * on all of those at once. Usually in those cases, + /* There are situations where we may have multiple strips selected and we want to enter + * tweak-mode on all of those at once. Usually in those cases, * it will usually just be a single strip per AnimData. * In such cases, compromise and take the last selected track and/or last selected strip, T28468. */ @@ -2142,7 +2141,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) if (ELEM(NULL, activeTrack, activeStrip, activeStrip->act)) { if (G.debug & G_DEBUG) { - printf("NLA tweakmode enter - neither active requirement found\n"); + printf("NLA tweak-mode enter - neither active requirement found\n"); printf("\tactiveTrack = %p, activeStrip = %p\n", (void *)activeTrack, (void *)activeStrip); } return false; @@ -2192,7 +2191,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) return true; } -/* Exit tweakmode for this AnimData block */ +/* Exit tweak-mode for this AnimData block. */ void BKE_nla_tweakmode_exit(AnimData *adt) { NlaStrip *strip; diff --git a/source/blender/blenkernel/intern/node.cc b/source/blender/blenkernel/intern/node.cc index 1b68c38e4ba..79caeaf7617 100644 --- a/source/blender/blenkernel/intern/node.cc +++ b/source/blender/blenkernel/intern/node.cc @@ -69,7 +69,6 @@ #include "BKE_lib_query.h" #include "BKE_main.h" #include "BKE_node.h" -#include "BKE_node_ui_storage.hh" #include "BLI_ghash.h" #include "BLI_threads.h" @@ -220,10 +219,6 @@ static void ntree_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, c /* node tree will generate its own interface type */ ntree_dst->interface_type = nullptr; - - /* Don't copy error messages in the runtime struct. - * They should be filled during execution anyway. */ - ntree_dst->ui_storage = nullptr; } static void ntree_free_data(ID *id) @@ -277,8 +272,6 @@ static void ntree_free_data(ID *id) if (ntree->id.tag & LIB_TAG_LOCALIZED) { BKE_libblock_free_data(&ntree->id, true); } - - delete ntree->ui_storage; } static void library_foreach_node_socket(LibraryForeachIDData *data, bNodeSocket *sock) @@ -365,7 +358,7 @@ static void node_foreach_cache(ID *id, key.offset_in_ID = offsetof(bNodeTree, previews); key.cache_v = nodetree->previews; - /* TODO, see also `direct_link_nodetree()` in readfile.c. */ + /* TODO: see also `direct_link_nodetree()` in readfile.c. */ #if 0 function_callback(id, &key, (void **)&nodetree->previews, 0, user_data); #endif @@ -407,7 +400,7 @@ static ID *node_owner_get(Main *bmain, ID *id) } } - BLI_assert(!"Embedded node tree with no owner. Critical Main inconsistency."); + BLI_assert_msg(0, "Embedded node tree with no owner. Critical Main inconsistency."); return nullptr; } @@ -517,7 +510,7 @@ void ntreeBlendWrite(BlendWriter *writer, bNodeTree *ntree) if (node->storage) { /* could be handlerized at some point, now only 1 exception still */ - if ((ELEM(ntree->type, NTREE_SHADER, NTREE_GEOMETRY)) && + if (ELEM(ntree->type, NTREE_SHADER, NTREE_GEOMETRY) && ELEM(node->type, SH_NODE_CURVE_VEC, SH_NODE_CURVE_RGB)) { BKE_curvemapping_blend_write(writer, (const CurveMapping *)node->storage); } @@ -625,7 +618,6 @@ static void ntree_blend_write(BlendWriter *writer, ID *id, const void *id_addres ntree->interface_type = nullptr; ntree->progress = nullptr; ntree->execdata = nullptr; - ntree->ui_storage = nullptr; BLO_write_id_struct(writer, bNodeTree, id_address, &ntree->id); @@ -649,7 +641,7 @@ static void direct_link_node_socket(BlendDataReader *reader, bNodeSocket *sock) /* ntree itself has been read! */ void ntreeBlendReadData(BlendDataReader *reader, bNodeTree *ntree) { - /* note: writing and reading goes in sync, for speed */ + /* NOTE: writing and reading goes in sync, for speed. */ ntree->init = 0; /* to set callbacks and force setting types */ ntree->is_updating = false; ntree->typeinfo = nullptr; @@ -657,7 +649,6 @@ void ntreeBlendReadData(BlendDataReader *reader, bNodeTree *ntree) ntree->progress = nullptr; ntree->execdata = nullptr; - ntree->ui_storage = nullptr; BLO_read_data_address(reader, &ntree->adt); BKE_animdata_blend_read_data(reader, ntree->adt); @@ -800,7 +791,7 @@ void ntreeBlendReadData(BlendDataReader *reader, bNodeTree *ntree) BLO_read_data_address(reader, &link->tosock); } - /* TODO, should be dealt by new generic cache handling of IDs... */ + /* TODO: should be dealt by new generic cache handling of IDs... */ ntree->previews = nullptr; /* type verification is in lib-link */ @@ -1048,7 +1039,7 @@ static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType } } -/* Note: This function is called to initialize node data based on the type. +/* NOTE: This function is called to initialize node data based on the type. * The bNodeType may not be registered at creation time of the node, * so this can be delayed until the node type gets registered. */ @@ -1070,7 +1061,7 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) node->height = ntype->height; node->color[0] = node->color[1] = node->color[2] = 0.608; /* default theme color */ /* initialize the node name with the node label. - * note: do this after the initfunc so nodes get their data set which may be used in naming + * NOTE: do this after the initfunc so nodes get their data set which may be used in naming * (node groups for example) */ /* XXX Do not use nodeLabel() here, it returns translated content for UI, * which should *only* be used in UI, *never* in data... @@ -1431,6 +1422,12 @@ GHashIterator *nodeSocketTypeGetIterator(void) return BLI_ghashIterator_new(nodesockettypes_hash); } +const char *nodeSocketTypeLabel(const bNodeSocketType *stype) +{ + /* Use socket type name as a fallback if label is undefined. */ + return stype->label[0] != '\0' ? stype->label : RNA_struct_ui_name(stype->ext_socket.srna); +} + struct bNodeSocket *nodeFindSocket(const bNode *node, eNodeSocketInOut in_out, const char *identifier) @@ -1593,13 +1590,15 @@ static void socket_id_user_decrement(bNodeSocket *sock) } } -void nodeModifySocketType( - bNodeTree *ntree, bNode *UNUSED(node), bNodeSocket *sock, int type, int subtype) +void nodeModifySocketType(bNodeTree *ntree, + bNode *UNUSED(node), + bNodeSocket *sock, + const char *idname) { - const char *idname = nodeStaticSocketType(type, subtype); + bNodeSocketType *socktype = nodeSocketTypeFind(idname); - if (!idname) { - CLOG_ERROR(&LOG, "static node socket type %d undefined", type); + if (!socktype) { + CLOG_ERROR(&LOG, "node socket type %s undefined", idname); return; } @@ -1609,9 +1608,21 @@ void nodeModifySocketType( sock->default_value = nullptr; } - sock->type = type; BLI_strncpy(sock->idname, idname, sizeof(sock->idname)); - node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(idname)); + node_socket_set_typeinfo(ntree, sock, socktype); +} + +void nodeModifySocketTypeStatic( + bNodeTree *ntree, bNode *node, bNodeSocket *sock, int type, int subtype) +{ + const char *idname = nodeStaticSocketType(type, subtype); + + if (!idname) { + CLOG_ERROR(&LOG, "static node socket type %d undefined", type); + return; + } + + nodeModifySocketType(ntree, node, sock, idname); } bNodeSocket *nodeAddSocket(bNodeTree *ntree, @@ -1655,6 +1666,15 @@ bNodeSocket *nodeInsertSocket(bNodeTree *ntree, return sock; } +bool nodeIsStaticSocketType(const struct bNodeSocketType *stype) +{ + /* + * Cannot rely on type==SOCK_CUSTOM here, because type is 0 by default + * and can be changed on custom sockets. + */ + return RNA_struct_is_a(stype->ext_socket.srna, &RNA_NodeSocketStandard); +} + const char *nodeStaticSocketType(int type, int subtype) { switch (type) { @@ -1813,6 +1833,39 @@ const char *nodeStaticSocketInterfaceType(int type, int subtype) return nullptr; } +const char *nodeStaticSocketLabel(int type, int UNUSED(subtype)) +{ + switch (type) { + case SOCK_FLOAT: + return "Float"; + case SOCK_INT: + return "Integer"; + case SOCK_BOOLEAN: + return "Boolean"; + case SOCK_VECTOR: + return "Vector"; + case SOCK_RGBA: + return "Color"; + case SOCK_STRING: + return "String"; + case SOCK_SHADER: + return "Shader"; + case SOCK_OBJECT: + return "Object"; + case SOCK_IMAGE: + return "Image"; + case SOCK_GEOMETRY: + return "Geometry"; + case SOCK_COLLECTION: + return "Collection"; + case SOCK_TEXTURE: + return "Texture"; + case SOCK_MATERIAL: + return "Material"; + } + return nullptr; +} + bNodeSocket *nodeAddStaticSocket(bNodeTree *ntree, bNode *node, eNodeSocketInOut in_out, @@ -2895,7 +2948,7 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo BKE_node_instance_hash_insert(to_ntree->previews, key, preview); } - /* Note: null free function here, + /* NOTE: null free function here, * because pointers have already been moved over to to_ntree->previews! */ BKE_node_instance_hash_free(from_ntree->previews, nullptr); from_ntree->previews = nullptr; @@ -3102,7 +3155,7 @@ static void free_localized_node_groups(bNodeTree *ntree) } LISTBASE_FOREACH (bNode *, node, &ntree->nodes) { - if ((ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP)) && node->id) { + if (ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP) && node->id) { bNodeTree *ngroup = (bNodeTree *)node->id; ntreeFreeTree(ngroup); MEM_freeN(ngroup); @@ -3163,8 +3216,8 @@ void ntreeSetOutput(bNodeTree *ntree) if (ntree->type == NTREE_COMPOSIT) { /* same type, exception for viewer */ if (tnode->type == node->type || - (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER) && - ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))) { + (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER, GEO_NODE_VIEWER) && + ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER, GEO_NODE_VIEWER))) { if (tnode->flag & NODE_DO_OUTPUT) { output++; if (output > 1) { @@ -3286,7 +3339,7 @@ bNodeTree *ntreeLocalize(bNodeTree *ntree) { if (ntree) { /* Make full copy outside of Main database. - * Note: previews are not copied here. + * NOTE: previews are not copied here. */ bNodeTree *ltree = (bNodeTree *)BKE_id_copy_ex( nullptr, &ntree->id, nullptr, (LIB_ID_COPY_LOCALIZE | LIB_ID_COPY_NO_ANIMDATA)); @@ -3294,7 +3347,7 @@ bNodeTree *ntreeLocalize(bNodeTree *ntree) ltree->id.tag |= LIB_TAG_LOCALIZED; LISTBASE_FOREACH (bNode *, node, <ree->nodes) { - if ((ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP)) && node->id) { + if (ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP) && node->id) { node->id = (ID *)ntreeLocalize((bNodeTree *)node->id); } } @@ -4763,7 +4816,7 @@ static bool node_undefined_poll(bNodeType *UNUSED(ntype), /* register fallback types used for undefined tree, nodes, sockets */ static void register_undefined_types() { - /* Note: these types are not registered in the type hashes, + /* NOTE: these types are not registered in the type hashes, * they are just used as placeholders in case the actual types are not registered. */ @@ -5057,27 +5110,30 @@ static void registerGeometryNodes() register_node_type_geo_attribute_mix(); register_node_type_geo_attribute_proximity(); register_node_type_geo_attribute_randomize(); + register_node_type_geo_attribute_remove(); register_node_type_geo_attribute_separate_xyz(); register_node_type_geo_attribute_set(); register_node_type_geo_attribute_transfer(); register_node_type_geo_attribute_vector_math(); register_node_type_geo_attribute_vector_rotate(); - register_node_type_geo_attribute_remove(); register_node_type_geo_boolean(); register_node_type_geo_bounding_box(); register_node_type_geo_collection_info(); register_node_type_geo_convex_hull(); + register_node_type_geo_curve_endpoints(); register_node_type_geo_curve_length(); register_node_type_geo_curve_primitive_bezier_segment(); register_node_type_geo_curve_primitive_circle(); + register_node_type_geo_curve_primitive_line(); register_node_type_geo_curve_primitive_quadratic_bezier(); + register_node_type_geo_curve_primitive_quadrilateral(); register_node_type_geo_curve_primitive_spiral(); register_node_type_geo_curve_primitive_star(); - register_node_type_geo_curve_to_mesh(); - register_node_type_geo_curve_to_points(); register_node_type_geo_curve_resample(); register_node_type_geo_curve_reverse(); register_node_type_geo_curve_subdivide(); + register_node_type_geo_curve_to_mesh(); + register_node_type_geo_curve_to_points(); register_node_type_geo_delete_geometry(); register_node_type_geo_edge_split(); register_node_type_geo_input_material(); @@ -5093,6 +5149,7 @@ static void registerGeometryNodes() register_node_type_geo_mesh_primitive_ico_sphere(); register_node_type_geo_mesh_primitive_line(); register_node_type_geo_mesh_primitive_uv_sphere(); + register_node_type_geo_mesh_subdivide(); register_node_type_geo_mesh_to_curve(); register_node_type_geo_object_info(); register_node_type_geo_point_distribute(); @@ -5106,11 +5163,11 @@ static void registerGeometryNodes() register_node_type_geo_sample_texture(); register_node_type_geo_select_by_material(); register_node_type_geo_separate_components(); - register_node_type_geo_subdivide(); register_node_type_geo_subdivision_surface(); register_node_type_geo_switch(); register_node_type_geo_transform(); register_node_type_geo_triangulate(); + register_node_type_geo_viewer(); register_node_type_geo_volume_to_mesh(); } @@ -5118,6 +5175,7 @@ static void registerFunctionNodes() { register_node_type_fn_boolean_math(); register_node_type_fn_float_compare(); + register_node_type_fn_float_to_int(); register_node_type_fn_input_string(); register_node_type_fn_input_vector(); register_node_type_fn_random_float(); diff --git a/source/blender/blenkernel/intern/node_ui_storage.cc b/source/blender/blenkernel/intern/node_ui_storage.cc deleted file mode 100644 index e5e9f00c7c3..00000000000 --- a/source/blender/blenkernel/intern/node_ui_storage.cc +++ /dev/null @@ -1,169 +0,0 @@ -/* - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "CLG_log.h" - -#include <mutex> - -#include "BLI_map.hh" -#include "BLI_string_ref.hh" -#include "BLI_vector.hh" - -#include "DNA_node_types.h" -#include "DNA_object_types.h" - -#include "BKE_context.h" -#include "BKE_node_ui_storage.hh" -#include "BKE_object.h" - -static CLG_LogRef LOG = {"bke.node_ui_storage"}; - -using blender::Map; -using blender::StringRef; -using blender::Vector; - -/* Use a global mutex because otherwise it would have to be stored directly in the - * bNodeTree struct in DNA. This could change if the node tree had a runtime struct. */ -static std::mutex global_ui_storage_mutex; - -static NodeTreeUIStorage &ui_storage_ensure(bNodeTree &ntree) -{ - /* As an optimization, only acquire a lock if the UI storage doesn't exist, - * because it only needs to be allocated once for every node tree. */ - if (ntree.ui_storage == nullptr) { - std::lock_guard<std::mutex> lock(global_ui_storage_mutex); - /* Check again-- another thread may have allocated the storage while this one waited. */ - if (ntree.ui_storage == nullptr) { - ntree.ui_storage = new NodeTreeUIStorage(); - } - } - return *ntree.ui_storage; -} - -const NodeUIStorage *BKE_node_tree_ui_storage_get_from_context(const bContext *C, - const bNodeTree &ntree, - const bNode &node) -{ - const NodeTreeUIStorage *ui_storage = ntree.ui_storage; - if (ui_storage == nullptr) { - return nullptr; - } - - const Object *active_object = CTX_data_active_object(C); - if (active_object == nullptr) { - return nullptr; - } - - const ModifierData *active_modifier = BKE_object_active_modifier(active_object); - if (active_modifier == nullptr) { - return nullptr; - } - - const NodeTreeEvaluationContext context(*active_object, *active_modifier); - const Map<std::string, NodeUIStorage> *storage = ui_storage->context_map.lookup_ptr(context); - if (storage == nullptr) { - return nullptr; - } - - return storage->lookup_ptr_as(StringRef(node.name)); -} - -/** - * Removes only the UI data associated with a particular evaluation context. The same node tree - * can be used for execution in multiple places, but the entire UI storage can't be removed when - * one execution starts, or all of the data associated with the node tree would be lost. - */ -void BKE_nodetree_ui_storage_free_for_context(bNodeTree &ntree, - const NodeTreeEvaluationContext &context) -{ - NodeTreeUIStorage *ui_storage = ntree.ui_storage; - if (ui_storage != nullptr) { - std::lock_guard<std::mutex> lock(ui_storage->mutex); - ui_storage->context_map.remove(context); - } -} - -static void node_error_message_log(bNodeTree &ntree, - const bNode &node, - const StringRef message, - const NodeWarningType type) -{ - switch (type) { - case NodeWarningType::Error: - CLOG_ERROR(&LOG, - "Node Tree: \"%s\", Node: \"%s\", %s", - ntree.id.name + 2, - node.name, - message.data()); - break; - case NodeWarningType::Warning: - CLOG_WARN(&LOG, - "Node Tree: \"%s\", Node: \"%s\", %s", - ntree.id.name + 2, - node.name, - message.data()); - break; - case NodeWarningType::Info: - CLOG_INFO(&LOG, - 2, - "Node Tree: \"%s\", Node: \"%s\", %s", - ntree.id.name + 2, - node.name, - message.data()); - break; - } -} - -static NodeUIStorage &node_ui_storage_ensure(NodeTreeUIStorage &locked_ui_storage, - const NodeTreeEvaluationContext &context, - const bNode &node) -{ - Map<std::string, NodeUIStorage> &node_tree_ui_storage = - locked_ui_storage.context_map.lookup_or_add_default(context); - NodeUIStorage &node_ui_storage = node_tree_ui_storage.lookup_or_add_default_as( - StringRef(node.name)); - return node_ui_storage; -} - -void BKE_nodetree_error_message_add(bNodeTree &ntree, - const NodeTreeEvaluationContext &context, - const bNode &node, - const NodeWarningType type, - std::string message) -{ - NodeTreeUIStorage &ui_storage = ui_storage_ensure(ntree); - std::lock_guard lock{ui_storage.mutex}; - - node_error_message_log(ntree, node, message, type); - - NodeUIStorage &node_ui_storage = node_ui_storage_ensure(ui_storage, context, node); - node_ui_storage.warnings.append({type, std::move(message)}); -} - -void BKE_nodetree_attribute_hint_add(bNodeTree &ntree, - const NodeTreeEvaluationContext &context, - const bNode &node, - const StringRef attribute_name, - const AttributeDomain domain, - const CustomDataType data_type) -{ - NodeTreeUIStorage &ui_storage = ui_storage_ensure(ntree); - std::lock_guard lock{ui_storage.mutex}; - - NodeUIStorage &node_ui_storage = node_ui_storage_ensure(ui_storage, context, node); - node_ui_storage.attribute_hints.add_as( - AvailableAttributeInfo{attribute_name, domain, data_type}); -} diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index a5e16172e75..941db80b76c 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -205,7 +205,8 @@ static void object_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const in } else if (ob_dst->mat != NULL || ob_dst->matbits != NULL) { /* This shall not be needed, but better be safe than sorry. */ - BLI_assert(!"Object copy: non-NULL material pointers with zero counter, should not happen."); + BLI_assert_msg( + 0, "Object copy: non-NULL material pointers with zero counter, should not happen."); ob_dst->mat = NULL; ob_dst->matbits = NULL; } @@ -234,7 +235,7 @@ static void object_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const in BKE_pose_rebuild(bmain, ob_dst, ob_dst->data, do_pose_id_user); } } - BKE_defgroup_copy_list(&ob_dst->defbase, &ob_src->defbase); + BKE_object_facemap_copy_list(&ob_dst->fmaps, &ob_src->fmaps); BKE_constraints_copy_ex(&ob_dst->constraints, &ob_src->constraints, flag_subdata, true); @@ -251,7 +252,7 @@ static void object_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const in BLI_listbase_clear(&ob_dst->modifiers); BLI_listbase_clear(&ob_dst->greasepencil_modifiers); - /* Note: Also takes care of softbody and particle systems copying. */ + /* NOTE: Also takes care of softbody and particle systems copying. */ BKE_object_modifier_stack_copy(ob_dst, ob_src, true, flag_subdata); BLI_listbase_clear((ListBase *)&ob_dst->drawdata); @@ -262,7 +263,7 @@ static void object_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const in /* Do not copy object's preview * (mostly due to the fact renderers create temp copy of objects). */ - if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */ + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO: temp hack. */ BKE_previewimg_id_copy(&ob_dst->id, &ob_src->id); } else { @@ -285,7 +286,6 @@ static void object_free_data(ID *id) MEM_SAFE_FREE(ob->iuser); MEM_SAFE_FREE(ob->runtime.bb); - BLI_freelistN(&ob->defbase); BLI_freelistN(&ob->fmaps); if (ob->pose) { BKE_pose_free_ex(ob->pose, false); @@ -510,13 +510,6 @@ static void object_foreach_id(ID *id, LibraryForeachIDData *data) } } -static void write_defgroups(BlendWriter *writer, ListBase *defbase) -{ - LISTBASE_FOREACH (bDeformGroup *, defgroup, defbase) { - BLO_write_struct(writer, bDeformGroup, defgroup); - } -} - static void write_fmaps(BlendWriter *writer, ListBase *fbase) { LISTBASE_FOREACH (bFaceMap *, fmap, fbase) { @@ -561,7 +554,6 @@ static void object_blend_write(BlendWriter *writer, ID *id, const void *id_addre } BKE_pose_blend_write(writer, ob->pose, arm); - write_defgroups(writer, &ob->defbase); write_fmaps(writer, &ob->fmaps); BKE_constraint_blend_write(writer, &ob->constraints); animviz_motionpath_blend_write(writer, ob->mpath); @@ -644,7 +636,9 @@ static void object_blend_read_data(BlendDataReader *reader, ID *id) animviz_motionpath_blend_read_data(reader, ob->mpath); } + /* Only for versioning, vertex group names are now stored on object data. */ BLO_read_list(reader, &ob->defbase); + BLO_read_list(reader, &ob->fmaps); /* XXX deprecated - old animation system <<< */ direct_link_nlastrips(reader, &ob->nlastrips); @@ -1041,6 +1035,8 @@ static void object_blend_read_expand(BlendExpander *expander, ID *id) BLO_expand(expander, ob->data); + BLO_expand(expander, ob->parent); + /* expand_object_expandModifier() */ if (ob->modifiers.first) { BKE_modifiers_foreach_ID_link(ob, expand_object_expandModifiers, expander); @@ -1537,7 +1533,8 @@ bool BKE_object_modifier_stack_copy(Object *ob_dst, const int flag_subdata) { if ((ob_dst->type == OB_GPENCIL) != (ob_src->type == OB_GPENCIL)) { - BLI_assert(!"Trying to copy a modifier stack between a GPencil object and another type."); + BLI_assert_msg(0, + "Trying to copy a modifier stack between a GPencil object and another type."); return false; } @@ -1758,10 +1755,6 @@ void BKE_object_free_derived_caches(Object *ob) BKE_geometry_set_free(ob->runtime.geometry_set_eval); ob->runtime.geometry_set_eval = NULL; } - if (ob->runtime.geometry_set_previews != NULL) { - BLI_ghash_free(ob->runtime.geometry_set_previews, NULL, (GHashValFreeFP)BKE_geometry_set_free); - ob->runtime.geometry_set_previews = NULL; - } } void BKE_object_free_caches(Object *object) @@ -1812,24 +1805,6 @@ void BKE_object_free_caches(Object *object) } } -/* Can be called from multiple threads. */ -void BKE_object_preview_geometry_set_add(Object *ob, - const uint64_t key, - struct GeometrySet *geometry_set) -{ - static ThreadMutex mutex = BLI_MUTEX_INITIALIZER; - BLI_mutex_lock(&mutex); - if (ob->runtime.geometry_set_previews == NULL) { - ob->runtime.geometry_set_previews = BLI_ghash_int_new(__func__); - } - BLI_ghash_reinsert(ob->runtime.geometry_set_previews, - POINTER_FROM_UINT(key), - geometry_set, - NULL, - (GHashValFreeFP)BKE_geometry_set_free); - BLI_mutex_unlock(&mutex); -} - /** * Actual check for internal data, not context or flags. */ @@ -2380,8 +2355,8 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int f psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, flag); } - /* XXX - from reading existing code this seems correct but intended usage of - * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */ + /* XXX(campbell): from reading existing code this seems correct but intended usage of + * pointcache should /w cloth should be added in 'ParticleSystem'. */ if (psysn->clmd) { psysn->clmd->point_cache = psysn->pointcache; } @@ -2439,7 +2414,7 @@ void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const static void copy_object_pose(Object *obn, const Object *ob, const int flag) { - /* note: need to clear obn->pose pointer first, + /* NOTE: need to clear obn->pose pointer first, * so that BKE_pose_copy_data works (otherwise there's a crash) */ obn->pose = NULL; BKE_pose_copy_data_ex(&obn->pose, ob->pose, flag, true); /* true = copy constraints */ @@ -2833,7 +2808,7 @@ void BKE_object_copy_proxy_drivers(Object *ob, Object *target) /* add new animdata block */ if (!ob->adt) { - ob->adt = BKE_animdata_add_id(&ob->id); + ob->adt = BKE_animdata_ensure_id(&ob->id); } /* make a copy of all the drivers (for now), then correct any links that need fixing */ @@ -2921,9 +2896,6 @@ void BKE_object_make_proxy(Main *bmain, Object *ob, Object *target, Object *cob) ob->data = target->data; id_us_plus((ID *)ob->data); /* ensures lib data becomes LIB_TAG_EXTERN */ - /* copy vertex groups */ - BKE_defgroup_copy_list(&ob->defbase, &target->defbase); - /* copy material and index information */ ob->actcol = ob->totcol = 0; if (ob->mat) { @@ -3365,7 +3337,7 @@ static void give_parvert(Object *par, int nr, float vec[3]) } BLI_mutex_unlock(&vparent_lock); #else - BLI_assert(!"Not safe for threading"); + BLI_assert_msg(0, "Not safe for threading"); BM_mesh_elem_table_ensure(em->bm, BM_VERT); #endif } @@ -3860,7 +3832,7 @@ void BKE_object_boundbox_flag(Object *ob, int flag, const bool set) } } -void BKE_object_boundbox_calc_from_mesh(struct Object *ob, struct Mesh *me_eval) +void BKE_object_boundbox_calc_from_mesh(struct Object *ob, const struct Mesh *me_eval) { float min[3], max[3]; @@ -4089,7 +4061,7 @@ bool BKE_object_empty_image_data_is_visible_in_view3d(const Object *ob, const Re if ((visibility_flag & (OB_EMPTY_IMAGE_HIDE_BACK | OB_EMPTY_IMAGE_HIDE_FRONT)) != 0) { float eps, dot; if (rv3d->is_persp) { - /* Note, we could normalize the 'view_dir' then use 'eps' + /* NOTE: we could normalize the 'view_dir' then use 'eps' * however the issue with empty objects being visible when viewed from the side * is only noticeable in orthographic views. */ float view_dir[3]; @@ -4163,13 +4135,37 @@ bool BKE_object_minmax_dupli(Depsgraph *depsgraph, return ok; } +struct GPencilStrokePointIterData { + const float (*obmat)[4]; + + void (*point_func_cb)(const float co[3], void *user_data); + void *user_data; +}; + +static void foreach_display_point_gpencil_stroke_fn(bGPDlayer *UNUSED(layer), + bGPDframe *UNUSED(frame), + bGPDstroke *stroke, + void *thunk) +{ + struct GPencilStrokePointIterData *iter_data = thunk; + { + bGPDspoint *pt; + int i; + for (i = 0, pt = stroke->points; i < stroke->totpoints; i++, pt++) { + float co[3]; + mul_v3_m4v3(co, iter_data->obmat, &pt->x); + iter_data->point_func_cb(co, iter_data->user_data); + } + } +} + void BKE_object_foreach_display_point(Object *ob, const float obmat[4][4], void (*func_cb)(const float[3], void *), void *user_data) { /* TODO: pointcloud and hair objects support */ - Mesh *mesh_eval = BKE_object_get_evaluated_mesh(ob); + const Mesh *mesh_eval = BKE_object_get_evaluated_mesh(ob); float co[3]; if (mesh_eval != NULL) { @@ -4180,6 +4176,13 @@ void BKE_object_foreach_display_point(Object *ob, func_cb(co, user_data); } } + else if (ob->type == OB_GPENCIL) { + struct GPencilStrokePointIterData iter_data = { + .obmat = obmat, .point_func_cb = func_cb, .user_data = user_data}; + + BKE_gpencil_visible_stroke_iter( + ob->data, NULL, foreach_display_point_gpencil_stroke_fn, &iter_data); + } else if (ob->runtime.curve_cache && ob->runtime.curve_cache->disp.first) { DispList *dl; @@ -5616,7 +5619,7 @@ bool BKE_object_modifier_update_subframe(Depsgraph *depsgraph, } } - /* was originally ID_RECALC_ALL - TODO - which flags are really needed??? */ + /* was originally ID_RECALC_ALL - TODO: which flags are really needed??? */ /* TODO(sergey): What about animation? */ const AnimationEvalContext anim_eval_context = BKE_animsys_eval_context_construct(depsgraph, frame); diff --git a/source/blender/blenkernel/intern/object_deform.c b/source/blender/blenkernel/intern/object_deform.c index 1e7624d0d7d..c69326a23c6 100644 --- a/source/blender/blenkernel/intern/object_deform.c +++ b/source/blender/blenkernel/intern/object_deform.c @@ -33,6 +33,7 @@ #include "DNA_armature_types.h" #include "DNA_cloth_types.h" #include "DNA_curve_types.h" +#include "DNA_gpencil_types.h" #include "DNA_lattice_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" @@ -123,8 +124,7 @@ bDeformGroup *BKE_object_defgroup_add_name(Object *ob, const char *name) } defgroup = BKE_object_defgroup_new(ob, name); - - ob->actdef = BLI_listbase_count(&ob->defbase); + BKE_object_defgroup_active_index_set(ob, BKE_object_defgroup_count(ob)); return defgroup; } @@ -171,7 +171,8 @@ MDeformVert *BKE_object_defgroup_data_create(ID *id) bool BKE_object_defgroup_clear(Object *ob, bDeformGroup *dg, const bool use_selection) { MDeformVert *dv; - const int def_nr = BLI_findindex(&ob->defbase, dg); + const ListBase *defbase = BKE_object_defgroup_list(ob); + const int def_nr = BLI_findindex(defbase, dg); bool changed = false; if (ob->type == OB_MESH) { @@ -249,7 +250,9 @@ bool BKE_object_defgroup_clear_all(Object *ob, const bool use_selection) bDeformGroup *dg; bool changed = false; - for (dg = ob->defbase.first; dg; dg = dg->next) { + const ListBase *defbase = BKE_object_defgroup_list(ob); + + for (dg = defbase->first; dg; dg = dg->next) { if (BKE_object_defgroup_clear(ob, dg, use_selection)) { changed = true; } @@ -265,7 +268,7 @@ bool BKE_object_defgroup_clear_all(Object *ob, const bool use_selection) static void object_defgroup_remove_update_users(Object *ob, const int idx) { - int i, defbase_tot = BLI_listbase_count(&ob->defbase) + 1; + int i, defbase_tot = BKE_object_defgroup_count(ob) + 1; int *map = MEM_mallocN(sizeof(int) * defbase_tot, "vgroup del"); map[idx] = map[0] = 0; @@ -285,15 +288,18 @@ static void object_defgroup_remove_common(Object *ob, bDeformGroup *dg, const in object_defgroup_remove_update_users(ob, def_nr + 1); /* Remove the group */ - BLI_freelinkN(&ob->defbase, dg); + ListBase *defbase = BKE_object_defgroup_list_mutable(ob); + + BLI_freelinkN(defbase, dg); /* Update the active deform index if necessary */ - if (ob->actdef > def_nr) { - ob->actdef--; + const int active_index = BKE_object_defgroup_active_index_get(ob); + if (active_index > def_nr) { + BKE_object_defgroup_active_index_set(ob, active_index - 1); } /* remove all dverts */ - if (BLI_listbase_is_empty(&ob->defbase)) { + if (BLI_listbase_is_empty(defbase)) { if (ob->type == OB_MESH) { Mesh *me = ob->data; CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert); @@ -307,8 +313,9 @@ static void object_defgroup_remove_common(Object *ob, bDeformGroup *dg, const in } } } - else if (ob->actdef < 1) { /* Keep a valid active index if we still have some vgroups. */ - ob->actdef = 1; + else if (BKE_object_defgroup_active_index_get(ob) < 1) { + /* Keep a valid active index if we still have some vgroups. */ + BKE_object_defgroup_active_index_set(ob, 1); } } @@ -316,7 +323,9 @@ static void object_defgroup_remove_object_mode(Object *ob, bDeformGroup *dg) { MDeformVert *dvert_array = NULL; int dvert_tot = 0; - const int def_nr = BLI_findindex(&ob->defbase, dg); + const ListBase *defbase = BKE_object_defgroup_list(ob); + + const int def_nr = BLI_findindex(defbase, dg); BLI_assert(def_nr != -1); @@ -347,7 +356,8 @@ static void object_defgroup_remove_object_mode(Object *ob, bDeformGroup *dg) static void object_defgroup_remove_edit_mode(Object *ob, bDeformGroup *dg) { int i; - const int def_nr = BLI_findindex(&ob->defbase, dg); + const ListBase *defbase = BKE_object_defgroup_list(ob); + const int def_nr = BLI_findindex(defbase, dg); BLI_assert(def_nr != -1); @@ -425,7 +435,9 @@ void BKE_object_defgroup_remove(Object *ob, bDeformGroup *defgroup) */ void BKE_object_defgroup_remove_all_ex(struct Object *ob, bool only_unlocked) { - bDeformGroup *dg = (bDeformGroup *)ob->defbase.first; + ListBase *defbase = BKE_object_defgroup_list_mutable(ob); + + bDeformGroup *dg = (bDeformGroup *)defbase->first; const bool edit_mode = BKE_object_is_in_editmode_vgroup(ob); if (dg) { @@ -444,7 +456,7 @@ void BKE_object_defgroup_remove_all_ex(struct Object *ob, bool only_unlocked) dg = next_dg; } } - else { /* ob->defbase is empty... */ + else { /* defbase is empty... */ /* remove all dverts */ if (ob->type == OB_MESH) { Mesh *me = ob->data; @@ -459,7 +471,7 @@ void BKE_object_defgroup_remove_all_ex(struct Object *ob, bool only_unlocked) } } /* Fix counters/indices */ - ob->actdef = 0; + BKE_object_defgroup_active_index_set(ob, 0); } } @@ -478,20 +490,23 @@ void BKE_object_defgroup_remove_all(struct Object *ob) */ int *BKE_object_defgroup_index_map_create(Object *ob_src, Object *ob_dst, int *r_map_len) { + const ListBase *src_defbase = BKE_object_defgroup_list(ob_src); + const ListBase *dst_defbase = BKE_object_defgroup_list(ob_dst); + /* Build src to merged mapping of vgroup indices. */ - if (BLI_listbase_is_empty(&ob_src->defbase) || BLI_listbase_is_empty(&ob_dst->defbase)) { + if (BLI_listbase_is_empty(src_defbase) || BLI_listbase_is_empty(dst_defbase)) { *r_map_len = 0; return NULL; } bDeformGroup *dg_src; - *r_map_len = BLI_listbase_count(&ob_src->defbase); + *r_map_len = BLI_listbase_count(src_defbase); int *vgroup_index_map = MEM_malloc_arrayN( *r_map_len, sizeof(*vgroup_index_map), "defgroup index map create"); bool is_vgroup_remap_needed = false; int i; - for (dg_src = ob_src->defbase.first, i = 0; dg_src; dg_src = dg_src->next, i++) { + for (dg_src = src_defbase->first, i = 0; dg_src; dg_src = dg_src->next, i++) { vgroup_index_map[i] = BKE_object_defgroup_name_index(ob_dst, dg_src->name); is_vgroup_remap_needed = is_vgroup_remap_needed || (vgroup_index_map[i] != i); } @@ -576,17 +591,17 @@ bool BKE_object_defgroup_array_get(ID *id, MDeformVert **dvert_arr, int *dvert_t /** * gets the status of "flag" for each bDeformGroup - * in ob->defbase and returns an array containing them + * in the object data's vertex group list and returns an array containing them */ bool *BKE_object_defgroup_lock_flags_get(Object *ob, const int defbase_tot) { bool is_locked = false; int i; - // int defbase_tot = BLI_listbase_count(&ob->defbase); + ListBase *defbase = BKE_object_defgroup_list_mutable(ob); bool *lock_flags = MEM_mallocN(defbase_tot * sizeof(bool), "defflags"); bDeformGroup *defgroup; - for (i = 0, defgroup = ob->defbase.first; i < defbase_tot && defgroup; + for (i = 0, defgroup = defbase->first; i < defbase_tot && defgroup; defgroup = defgroup->next, i++) { lock_flags[i] = ((defgroup->flag & DG_LOCK_WEIGHT) != 0); is_locked |= lock_flags[i]; @@ -606,17 +621,17 @@ bool *BKE_object_defgroup_validmap_get(Object *ob, const int defbase_tot) bool *defgroup_validmap; GHash *gh; int i, step1 = 1; - // int defbase_tot = BLI_listbase_count(&ob->defbase); + const ListBase *defbase = BKE_object_defgroup_list(ob); VirtualModifierData virtualModifierData; - if (BLI_listbase_is_empty(&ob->defbase)) { + if (BLI_listbase_is_empty(defbase)) { return NULL; } gh = BLI_ghash_str_new_ex(__func__, defbase_tot); /* add all names to a hash table */ - for (dg = ob->defbase.first; dg; dg = dg->next) { + for (dg = defbase->first; dg; dg = dg->next) { BLI_ghash_insert(gh, dg->name, NULL); } @@ -655,7 +670,7 @@ bool *BKE_object_defgroup_validmap_get(Object *ob, const int defbase_tot) defgroup_validmap = MEM_mallocN(sizeof(*defgroup_validmap) * defbase_tot, "wpaint valid map"); /* add all names to a hash table */ - for (dg = ob->defbase.first, i = 0; dg; dg = dg->next, i++) { + for (dg = defbase->first, i = 0; dg; dg = dg->next, i++) { defgroup_validmap[i] = (BLI_ghash_lookup(gh, dg->name) != NULL); } @@ -676,9 +691,11 @@ bool *BKE_object_defgroup_selected_get(Object *ob, int defbase_tot, int *r_dg_fl Object *armob = BKE_object_pose_armature_get(ob); (*r_dg_flags_sel_tot) = 0; + const ListBase *defbase = BKE_object_defgroup_list(ob); + if (armob) { bPose *pose = armob->pose; - for (i = 0, defgroup = ob->defbase.first; i < defbase_tot && defgroup; + for (i = 0, defgroup = defbase->first; i < defbase_tot && defgroup; defgroup = defgroup->next, i++) { bPoseChannel *pchan = BKE_pose_channel_find_name(pose, defgroup->name); if (pchan && (pchan->bone->flag & BONE_SELECTED)) { @@ -774,11 +791,13 @@ void BKE_object_defgroup_mirror_selection(struct Object *ob, bool *dg_flags_sel, int *r_dg_flags_sel_tot) { + const ListBase *defbase = BKE_object_defgroup_list(ob); + bDeformGroup *defgroup; unsigned int i; int i_mirr; - for (i = 0, defgroup = ob->defbase.first; i < defbase_tot && defgroup; + for (i = 0, defgroup = defbase->first; i < defbase_tot && defgroup; defgroup = defgroup->next, i++) { if (dg_selection[i]) { char name_flip[MAXBONENAME]; @@ -804,11 +823,12 @@ bool *BKE_object_defgroup_subset_from_select_type(Object *ob, int *r_subset_count) { bool *defgroup_validmap = NULL; - *r_defgroup_tot = BLI_listbase_count(&ob->defbase); + + *r_defgroup_tot = BKE_object_defgroup_count(ob); switch (subset_type) { case WT_VGROUP_ACTIVE: { - const int def_nr_active = ob->actdef - 1; + const int def_nr_active = BKE_object_defgroup_active_index_get(ob) - 1; defgroup_validmap = MEM_mallocN(*r_defgroup_tot * sizeof(*defgroup_validmap), __func__); memset(defgroup_validmap, false, *r_defgroup_tot * sizeof(*defgroup_validmap)); if ((def_nr_active >= 0) && (def_nr_active < *r_defgroup_tot)) { diff --git a/source/blender/blenkernel/intern/object_dupli.cc b/source/blender/blenkernel/intern/object_dupli.cc index 768fa9373c1..77969328365 100644 --- a/source/blender/blenkernel/intern/object_dupli.cc +++ b/source/blender/blenkernel/intern/object_dupli.cc @@ -335,14 +335,14 @@ static void make_child_duplis(const DupliContext *ctx, /** \name Internal Data Access Utilities * \{ */ -static Mesh *mesh_data_from_duplicator_object(Object *ob, - BMEditMesh **r_em, - const float (**r_vert_coords)[3], - const float (**r_vert_normals)[3]) +static const Mesh *mesh_data_from_duplicator_object(Object *ob, + BMEditMesh **r_em, + const float (**r_vert_coords)[3], + const float (**r_vert_normals)[3]) { /* Gather mesh info. */ BMEditMesh *em = BKE_editmesh_from_object(ob); - Mesh *me_eval; + const Mesh *me_eval; *r_em = nullptr; *r_vert_coords = nullptr; @@ -603,7 +603,7 @@ static void make_duplis_verts(const DupliContext *ctx) BMEditMesh *em = nullptr; const float(*vert_coords)[3] = nullptr; const float(*vert_normals)[3] = nullptr; - Mesh *me_eval = mesh_data_from_duplicator_object( + const Mesh *me_eval = mesh_data_from_duplicator_object( parent, &em, &vert_coords, use_rotation ? &vert_normals : nullptr); if (em == nullptr && me_eval == nullptr) { return; @@ -1151,7 +1151,7 @@ static void make_duplis_faces(const DupliContext *ctx) /* Gather mesh info. */ BMEditMesh *em = nullptr; const float(*vert_coords)[3] = nullptr; - Mesh *me_eval = mesh_data_from_duplicator_object(parent, &em, &vert_coords, nullptr); + const Mesh *me_eval = mesh_data_from_duplicator_object(parent, &em, &vert_coords, nullptr); if (em == nullptr && me_eval == nullptr) { return; } diff --git a/source/blender/blenkernel/intern/object_update.c b/source/blender/blenkernel/intern/object_update.c index ab247ef5507..7cdea14e9bd 100644 --- a/source/blender/blenkernel/intern/object_update.c +++ b/source/blender/blenkernel/intern/object_update.c @@ -123,7 +123,7 @@ void BKE_object_eval_parent(Depsgraph *depsgraph, Object *ob) void BKE_object_eval_constraints(Depsgraph *depsgraph, Scene *scene, Object *ob) { bConstraintOb *cob; - float ctime = BKE_scene_frame_get(scene); + float ctime = BKE_scene_ctime_get(scene); DEG_debug_print_eval(depsgraph, __func__, ob->id.name, ob); @@ -388,12 +388,31 @@ void BKE_object_batch_cache_dirty_tag(Object *ob) BKE_object_data_batch_cache_dirty_tag(ob->data); } +void BKE_object_data_eval_batch_cache_dirty_tag(Depsgraph *depsgraph, ID *object_data) +{ + DEG_debug_print_eval(depsgraph, __func__, object_data->name, object_data); + BKE_object_data_batch_cache_dirty_tag(object_data); +} + +void BKE_object_data_eval_batch_cache_deform_tag(Depsgraph *depsgraph, ID *object_data) +{ + DEG_debug_print_eval(depsgraph, __func__, object_data->name, object_data); + switch (GS(object_data->name)) { + case ID_ME: + BKE_mesh_batch_cache_dirty_tag((Mesh *)object_data, BKE_MESH_BATCH_DIRTY_DEFORM); + break; + default: + /* Only mesh is currently supported. Fallback to dirty all for other datablocks types. */ + BKE_object_data_batch_cache_dirty_tag(object_data); + break; + } +} + void BKE_object_eval_uber_data(Depsgraph *depsgraph, Scene *scene, Object *ob) { DEG_debug_print_eval(depsgraph, __func__, ob->id.name, ob); BLI_assert(ob->type != OB_ARMATURE); BKE_object_handle_data_update(depsgraph, scene, ob); - BKE_object_batch_cache_dirty_tag(ob); } void BKE_object_eval_ptcache_reset(Depsgraph *depsgraph, Scene *scene, Object *object) diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index 2e7152302c7..3aee5cd639d 100644 --- a/source/blender/blenkernel/intern/ocean.c +++ b/source/blender/blenkernel/intern/ocean.c @@ -62,7 +62,7 @@ static float nextfr(RNG *rng, float min, float max) static float gaussRand(RNG *rng) { - /* Note: to avoid numerical problems with very small numbers, we make these variables + /* NOTE: to avoid numerical problems with very small numbers, we make these variables * singe-precision floats, but later we call the double-precision log() and sqrt() functions * instead of logf() and sqrtf(). */ float x; @@ -1381,9 +1381,9 @@ void BKE_ocean_bake(struct Ocean *o, void (*update_cb)(void *, float progress, int *cancel), void *update_cb_data) { - /* note: some of these values remain uninitialized unless certain options + /* NOTE(campbell): some of these values remain uninitialized unless certain options * are enabled, take care that BKE_ocean_eval_ij() initializes a member - * before use - campbell */ + * before use. */ OceanResult ocr; ImageFormatData imf = {0}; @@ -1437,7 +1437,7 @@ void BKE_ocean_bake(struct Ocean *o, rgb_to_rgba_unit_alpha(&ibuf_disp->rect_float[4 * (res_x * y + x)], ocr.disp); if (o->_do_jacobian) { - /* TODO: cleanup unused code - campbell */ + /* TODO(campbell): cleanup unused code. */ float /* r, */ /* UNUSED */ pr = 0.0f, foam_result; float neg_disp, neg_eplus; diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c index 87239d160b4..78e7e11c248 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -527,7 +527,7 @@ static void unpack_generate_paths(const char *name, BLI_split_dirfile(name, tempdir, tempname, sizeof(tempdir), sizeof(tempname)); if (tempname[0] == '\0') { - /* Note: we generally do not have any real way to re-create extension out of data. */ + /* NOTE: we generally do not have any real way to re-create extension out of data. */ BLI_strncpy(tempname, id->name + 2, sizeof(tempname)); printf("%s\n", tempname); diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c index a7c6dc2deb9..1af66fa090b 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -128,8 +128,8 @@ static void palette_blend_read_data(BlendDataReader *reader, ID *id) static void palette_undo_preserve(BlendLibReader *UNUSED(reader), ID *id_new, ID *id_old) { /* Whole Palette is preserved across undo-steps, and it has no extra pointer, simple. */ - /* Note: We do not care about potential internal references to self here, Palette has none. */ - /* Note: We do not swap IDProperties, as dealing with potential ID pointers in those would be + /* NOTE: We do not care about potential internal references to self here, Palette has none. */ + /* NOTE: We do not swap IDProperties, as dealing with potential ID pointers in those would be * fairly delicate. */ BKE_lib_id_swap(NULL, id_new, id_old); SWAP(IDProperty *, id_new->properties, id_old->properties); @@ -2067,7 +2067,7 @@ void BKE_sculpt_ensure_orig_mesh_data(Scene *scene, Object *object) /* If a sculpt session is active, ensure we have its faceset data porperly up-to-date. */ object->sculpt->face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS); - /* Note: In theory we could add that on the fly when required by sculpt code. + /* NOTE: In theory we could add that on the fly when required by sculpt code. * But this then requires proper update of depsgraph etc. For now we play safe, optimization is * always possible later if it's worth it. */ BKE_sculpt_mask_layers_ensure(object, mmd); diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index d386967bf8b..db1fbb56125 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -2811,7 +2811,7 @@ static void psys_task_init_path(ParticleTask *task, ParticleSimulationData *sim) task->rng_path = BLI_rng_new(seed); } -/* note: this function must be thread safe, except for branching! */ +/* NOTE: this function must be thread safe, except for branching! */ static void psys_thread_create_path(ParticleTask *task, struct ChildParticle *cpa, ParticleCacheKey *child_keys, @@ -3961,7 +3961,7 @@ static ModifierData *object_add_or_copy_particle_system( psys->totpart = 0; psys->flag = PSYS_CURRENT; if (scene != NULL) { - psys->cfra = BKE_scene_frame_to_ctime(scene, CFRA + 1); + psys->cfra = BKE_scene_frame_to_ctime(scene, scene->r.cfra + 1); } DEG_relations_tag_update(bmain); @@ -5400,8 +5400,8 @@ void BKE_particle_system_blend_read_lib(BlendLibReader *reader, BLO_read_id_address(reader, id->lib, &psys->target_ob); if (psys->clmd) { - /* XXX - from reading existing code this seems correct but intended usage of - * pointcache /w cloth should be added in 'ParticleSystem' - campbell */ + /* XXX(campbell): from reading existing code this seems correct but intended usage of + * pointcache /w cloth should be added in 'ParticleSystem'. */ psys->clmd->point_cache = psys->pointcache; psys->clmd->ptcaches.first = psys->clmd->ptcaches.last = NULL; BLO_read_id_address(reader, id->lib, &psys->clmd->coll_parms->group); diff --git a/source/blender/blenkernel/intern/particle_child.c b/source/blender/blenkernel/intern/particle_child.c index 2231731287d..415147fb36a 100644 --- a/source/blender/blenkernel/intern/particle_child.c +++ b/source/blender/blenkernel/intern/particle_child.c @@ -331,7 +331,7 @@ void psys_apply_child_modifiers(ParticleThreadContext *ctx, int totkeys, k; float max_length; - /* TODO for the future: use true particle modifiers that work on the whole curve */ + /* TODO: for the future: use true particle modifiers that work on the whole curve. */ (void)modifiers; (void)mod; diff --git a/source/blender/blenkernel/intern/particle_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c index 1fd99bb2cbd..863476c6638 100644 --- a/source/blender/blenkernel/intern/particle_distribute.c +++ b/source/blender/blenkernel/intern/particle_distribute.c @@ -472,7 +472,7 @@ static int distribute_binary_search(const float *sum, int n, float value) * be sure to keep up to date if this changes */ #define PSYS_RND_DIST_SKIP 3 -/* note: this function must be thread safe, for from == PART_FROM_CHILD */ +/* NOTE: this function must be thread safe, for `from == PART_FROM_CHILD`. */ #define ONLY_WORKING_WITH_PA_VERTS 0 static void distribute_from_verts_exec(ParticleTask *thread, ParticleData *pa, int p) { @@ -1214,7 +1214,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, * It allows us to consider pos as 'midpoint between v and v+1' * (or 'p and p+1', depending whether we have more vertices than particles or not), * and avoid stumbling over float impression in element_sum. - * Note: moved face and volume distribution to this as well (instead of starting at zero), + * NOTE: moved face and volume distribution to this as well (instead of starting at zero), * for the same reasons, see T52682. */ pos = (totpart < totmapped) ? 0.5 / (double)totmapped : step * 0.5; /* We choose the smaller step. */ diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index c35f703b072..06d3daaf4d6 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -447,9 +447,9 @@ void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, Partic MEM_freeN(nodedmelem); } else { - /* TODO PARTICLE, make the following line unnecessary, each function + /* TODO_PARTICLE: make the following line unnecessary, each function * should know to use the num or num_dmcache, set the num_dmcache to - * an invalid value, just in case */ + * an invalid value, just in case. */ LOOP_PARTICLES { @@ -992,9 +992,9 @@ void psys_get_birth_coords( /* (part->rotmode == PART_ROT_NOR_TAN) */ float tmat[3][3]; - /* note: utan_local is not taken from 'utan', we calculate from rot_vec/vtan */ - /* note: it looks like rotation phase may be applied twice (once with vtan, again below) - * however this isn't the case - campbell */ + /* NOTE: utan_local is not taken from 'utan', we calculate from rot_vec/vtan. */ + /* NOTE(campbell): it looks like rotation phase may be applied twice + * (once with vtan, again below) however this isn't the case. */ float *rot_vec_local = tmat[0]; float *vtan_local = tmat[1]; float *utan_local = tmat[2]; @@ -1014,7 +1014,7 @@ void psys_get_birth_coords( cross_v3_v3v3(utan_local, vtan_local, rot_vec_local); cross_v3_v3v3(vtan_local, utan_local, rot_vec_local); - /* note: no need to normalize */ + /* NOTE: no need to normalize. */ mat3_to_quat(q2, tmat); } @@ -2617,7 +2617,7 @@ static float collision_newton_rhapson(ParticleCollision *col, * here. */ if (d1 == d0) { /* If first iteration, try from other end where the gradient may be - * greater. Note: code duplicated below. */ + * greater. NOTE: code duplicated below. */ if (iter == 0) { t0 = 1.0f; collision_interpolate_element(pce, t0, col->f, col); @@ -2638,7 +2638,7 @@ static float collision_newton_rhapson(ParticleCollision *col, t1 -= d1 * dd; /* Particle moving away from plane could also mean a strangely rotating - * face, so check from end. Note: code duplicated above. */ + * face, so check from end. NOTE: code duplicated above. */ if (iter == 0 && t1 < 0.0f) { t0 = 1.0f; collision_interpolate_element(pce, t0, col->f, col); diff --git a/source/blender/blenkernel/intern/pbvh.c b/source/blender/blenkernel/intern/pbvh.c index 0d84022da77..461ffa7765e 100644 --- a/source/blender/blenkernel/intern/pbvh.c +++ b/source/blender/blenkernel/intern/pbvh.c @@ -1053,7 +1053,7 @@ static void pbvh_update_normals_accum_task_cb(void *__restrict userdata, const int v = vtri[j]; if (pbvh->verts[v].flag & ME_VERT_PBVH_UPDATE) { - /* Note: This avoids `lock, add_v3_v3, unlock` + /* NOTE: This avoids `lock, add_v3_v3, unlock` * and is five to ten times quicker than a spin-lock. * Not exact equivalent though, since atomicity is only ensured for one component * of the vector at a time, but here it shall not make any sensible difference. */ @@ -2157,7 +2157,7 @@ static bool pbvh_faces_node_raycast(PBVH *pbvh, const float *co[3]; if (origco) { - /* intersect with backuped original coordinates */ + /* Intersect with backed up original coordinates. */ co[0] = origco[face_verts[0]]; co[1] = origco[face_verts[1]]; co[2] = origco[face_verts[2]]; @@ -2798,7 +2798,7 @@ float (*BKE_pbvh_vert_coords_alloc(PBVH *pbvh))[3] void BKE_pbvh_vert_coords_apply(PBVH *pbvh, const float (*vertCos)[3], const int totvert) { if (totvert != pbvh->totvert) { - BLI_assert(!"PBVH: Given deforming vcos number does not natch PBVH vertex number!"); + BLI_assert_msg(0, "PBVH: Given deforming vcos number does not natch PBVH vertex number!"); return; } diff --git a/source/blender/blenkernel/intern/pbvh_bmesh.c b/source/blender/blenkernel/intern/pbvh_bmesh.c index c2483b265a5..d3d7f02ecad 100644 --- a/source/blender/blenkernel/intern/pbvh_bmesh.c +++ b/source/blender/blenkernel/intern/pbvh_bmesh.c @@ -1324,7 +1324,7 @@ static void pbvh_bmesh_collapse_edge(PBVH *pbvh, /* For all remaining faces of v_del, create a new face that is the * same except it uses v_conn instead of v_del */ - /* Note: this could be done with BM_vert_splice(), but that + /* NOTE: this could be done with BM_vert_splice(), but that * requires handling other issues like duplicate edges, so doesn't * really buy anything. */ BLI_buffer_clear(deleted_faces); diff --git a/source/blender/blenkernel/intern/pbvh_intern.h b/source/blender/blenkernel/intern/pbvh_intern.h index 948b57578dc..84c4ae4dead 100644 --- a/source/blender/blenkernel/intern/pbvh_intern.h +++ b/source/blender/blenkernel/intern/pbvh_intern.h @@ -30,7 +30,7 @@ typedef struct { float bmin[3], bmax[3], bcentroid[3]; } BBC; -/* Note: this structure is getting large, might want to split it into +/* NOTE: this structure is getting large, might want to split it into * union'd structs */ struct PBVHNode { /* Opaque handle for drawing code */ diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index a05eb6962ce..9ed5b0230e6 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -849,7 +849,7 @@ static void ptcache_rigidbody_interpolate(int index, dfra = cfra2 - cfra1; - /* note: keys[0] and keys[3] unused for type < 1 (crappy) */ + /* NOTE: keys[0] and keys[3] unused for type < 1 (crappy). */ psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, &result, true); interp_qt_qtqt(result.rot, keys[1].rot, keys[2].rot, (cfra - cfra1) / dfra); @@ -1837,7 +1837,7 @@ static void ptcache_data_copy(void *from[], void *to[]) { int i; for (i = 0; i < BPHYS_TOT_DATA; i++) { - /* note, durian file 03.4b_comp crashes if to[i] is not tested + /* NOTE: durian file 03.4b_comp crashes if to[i] is not tested * its NULL, not sure if this should be fixed elsewhere but for now its needed */ if (from[i] && to[i]) { memcpy(to[i], from[i], ptcache_data_size[i]); @@ -2807,8 +2807,8 @@ void BKE_ptcache_id_time( cache = pid->cache; if (timescale) { - time = BKE_scene_frame_get(scene); - nexttime = BKE_scene_frame_to_ctime(scene, CFRA + 1.0f); + time = BKE_scene_ctime_get(scene); + nexttime = BKE_scene_frame_to_ctime(scene, scene->r.cfra + 1); *timescale = MAX2(nexttime - time, 0.0f); } diff --git a/source/blender/blenkernel/intern/rigidbody.c b/source/blender/blenkernel/intern/rigidbody.c index 2d4cce4b953..328c54fc21b 100644 --- a/source/blender/blenkernel/intern/rigidbody.c +++ b/source/blender/blenkernel/intern/rigidbody.c @@ -367,7 +367,7 @@ static Mesh *rigidbody_get_mesh(Object *ob) } /* Just return something sensible so that at least Blender won't crash. */ - BLI_assert(!"Unknown mesh source"); + BLI_assert_msg(0, "Unknown mesh source"); return BKE_object_get_evaluated_mesh(ob); } @@ -1787,7 +1787,7 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, rigidbody_update_sim_world(scene, rbw); - /* XXX TODO For rebuild: remove all constraints first. + /* XXX TODO: For rebuild: remove all constraints first. * Otherwise we can end up deleting objects that are still * referenced by constraints, corrupting bullet's internal list. * @@ -1811,11 +1811,12 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, /* validate that we've got valid object set up here... */ RigidBodyOb *rbo = ob->rigidbody_object; - /* TODO remove this whole block once we are sure we never get NULL rbo here anymore. */ + /* TODO: remove this whole block once we are sure we never get NULL rbo here anymore. */ /* This cannot be done in CoW evaluation context anymore... */ if (rbo == NULL) { - BLI_assert(!"CoW object part of RBW object collection without RB object data, " - "should not happen.\n"); + BLI_assert_msg(0, + "CoW object part of RBW object collection without RB object data, " + "should not happen.\n"); /* Since this object is included in the sim group but doesn't have * rigid body settings (perhaps it was added manually), add! * - assume object to be active? That is the default for newly added settings... @@ -1868,11 +1869,12 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, /* validate that we've got valid object set up here... */ RigidBodyCon *rbc = ob->rigidbody_constraint; - /* TODO remove this whole block once we are sure we never get NULL rbo here anymore. */ + /* TODO: remove this whole block once we are sure we never get NULL rbo here anymore. */ /* This cannot be done in CoW evaluation context anymore... */ if (rbc == NULL) { - BLI_assert(!"CoW object part of RBW constraints collection without RB constraint data, " - "should not happen.\n"); + BLI_assert_msg(0, + "CoW object part of RBW constraints collection without RB constraint data, " + "should not happen.\n"); /* Since this object is included in the group but doesn't have * constraint settings (perhaps it was added manually), add! */ diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index 84741038164..cc5a8536a5a 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -192,7 +192,7 @@ static void scene_init_data(ID *id) BLI_strncpy(scene->r.pic, U.renderdir, sizeof(scene->r.pic)); - /* Note; in header_info.c the scene copy happens..., + /* NOTE: in header_info.c the scene copy happens..., * if you add more to renderdata it has to be checked there. */ /* multiview - stereo */ @@ -1045,7 +1045,7 @@ static void scene_blend_write(BlendWriter *writer, ID *id, const void *id_addres static void direct_link_paint_helper(BlendDataReader *reader, const Scene *scene, Paint **paint) { - /* TODO. is this needed */ + /* TODO: is this needed. */ BLO_read_data_address(reader, paint); if (*paint) { @@ -1899,14 +1899,14 @@ void BKE_scene_copy_data_eevee(Scene *sce_dst, const Scene *sce_src) sce_dst->eevee = sce_src->eevee; sce_dst->eevee.light_cache_data = NULL; sce_dst->eevee.light_cache_info[0] = '\0'; - /* TODO Copy the cache. */ + /* TODO: Copy the cache. */ } Scene *BKE_scene_duplicate(Main *bmain, Scene *sce, eSceneCopyMethod type) { Scene *sce_copy; - /* TODO this should/could most likely be replaced by call to more generic code at some point... + /* TODO: this should/could most likely be replaced by call to more generic code at some point... * But for now, let's keep it well isolated here. */ if (type == SCE_COPY_EMPTY) { ListBase rv; @@ -2299,10 +2299,7 @@ Object *BKE_scene_camera_switch_find(Scene *scene) return NULL; } - const int cfra = ((scene->r.images == scene->r.framapto) ? - scene->r.cfra : - (int)(scene->r.cfra * - ((float)scene->r.framapto / (float)scene->r.images))); + const int ctime = (int)BKE_scene_ctime_get(scene); int frame = -(MAXFRAME + 1); int min_frame = MAXFRAME + 1; Object *camera = NULL; @@ -2310,11 +2307,11 @@ Object *BKE_scene_camera_switch_find(Scene *scene) LISTBASE_FOREACH (TimeMarker *, m, &scene->markers) { if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) { - if ((m->frame <= cfra) && (m->frame > frame)) { + if ((m->frame <= ctime) && (m->frame > frame)) { camera = m->camera; frame = m->frame; - if (frame == cfra) { + if (frame == ctime) { break; } } @@ -2396,13 +2393,13 @@ const char *BKE_scene_find_last_marker_name(const Scene *scene, int frame) return best_marker ? best_marker->name : NULL; } -int BKE_scene_frame_snap_by_seconds(Scene *scene, double interval_in_seconds, int cfra) +int BKE_scene_frame_snap_by_seconds(Scene *scene, double interval_in_seconds, int frame) { const int fps = round_db_to_int(FPS * interval_in_seconds); - const int second_prev = cfra - mod_i(cfra, fps); + const int second_prev = frame - mod_i(frame, fps); const int second_next = second_prev + fps; - const int delta_prev = cfra - second_prev; - const int delta_next = second_next - cfra; + const int delta_prev = frame - second_prev; + const int delta_next = second_next - frame; return (delta_prev < delta_next) ? second_prev : second_next; } @@ -2444,16 +2441,17 @@ bool BKE_scene_validate_setscene(Main *bmain, Scene *sce) return true; } -/** - * This function is needed to cope with fractional frames, needed for motion blur & physics. - */ -float BKE_scene_frame_get(const Scene *scene) +/* Return fractional frame number taking into account subframes and time + * remapping. This the time value used by animation, modifiers and physics + * evaluation. */ +float BKE_scene_ctime_get(const Scene *scene) { return BKE_scene_frame_to_ctime(scene, scene->r.cfra); } -/* This function is used to obtain arbitrary fractional frames */ -float BKE_scene_frame_to_ctime(const Scene *scene, const float frame) +/* Convert integer frame number to fractional frame number taking into account + * subframes and time remapping. */ +float BKE_scene_frame_to_ctime(const Scene *scene, const int frame) { float ctime = frame; ctime += scene->r.subframe; @@ -2461,13 +2459,18 @@ float BKE_scene_frame_to_ctime(const Scene *scene, const float frame) return ctime; } -/** - * Sets the frame int/float components. - */ -void BKE_scene_frame_set(struct Scene *scene, double cfra) + +/* Get current fractional frame based on frame and subframe. */ +float BKE_scene_frame_get(const Scene *scene) +{ + return scene->r.cfra + scene->r.subframe; +} + +/* Set current frame and subframe based on a fractional frame. */ +void BKE_scene_frame_set(Scene *scene, float frame) { double intpart; - scene->r.subframe = modf(cfra, &intpart); + scene->r.subframe = modf((double)frame, &intpart); scene->r.cfra = (int)intpart; } @@ -2736,8 +2739,8 @@ void BKE_scene_graph_update_for_newframe_ex(Depsgraph *depsgraph, const bool cle * edits from callback are properly taken into account. Doing a time update on those would * lose any possible unkeyed changes made by the handler. */ if (pass == 0) { - const float ctime = BKE_scene_frame_get(scene); - DEG_evaluate_on_framechange(depsgraph, ctime); + const float frame = BKE_scene_frame_get(scene); + DEG_evaluate_on_framechange(depsgraph, frame); } else { DEG_evaluate_on_refresh(depsgraph); diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c index 608317933f5..c3885b5dcf7 100644 --- a/source/blender/blenkernel/intern/screen.c +++ b/source/blender/blenkernel/intern/screen.c @@ -101,7 +101,7 @@ void BKE_screen_foreach_id_screen_area(LibraryForeachIDData *data, ScrArea *area { BKE_LIB_FOREACHID_PROCESS(data, area->full, IDWALK_CB_NOP); - /* TODO this should be moved to a callback in `SpaceType`, defined in each editor's own code. + /* TODO: this should be moved to a callback in `SpaceType`, defined in each editor's own code. * Will be for a later round of cleanup though... */ LISTBASE_FOREACH (SpaceLink *, sl, &area->spacedata) { switch (sl->spacetype) { @@ -289,7 +289,7 @@ bool BKE_screen_blend_read_data(BlendDataReader *reader, bScreen *screen) return success; } -/* note: file read without screens option G_FILE_NO_UI; +/* NOTE: file read without screens option G_FILE_NO_UI; * check lib pointers in call below */ static void screen_blend_read_lib(BlendLibReader *reader, ID *id) { @@ -682,19 +682,13 @@ void BKE_area_region_free(SpaceType *st, ARegion *region) BKE_area_region_panels_free(®ion->panels); LISTBASE_FOREACH (uiList *, uilst, ®ion->ui_lists) { - if (uilst->dyn_data) { - uiListDyn *dyn_data = uilst->dyn_data; - if (dyn_data->items_filter_flags) { - MEM_freeN(dyn_data->items_filter_flags); - } - if (dyn_data->items_filter_neworder) { - MEM_freeN(dyn_data->items_filter_neworder); - } - MEM_freeN(dyn_data); + if (uilst->dyn_data && uilst->dyn_data->free_runtime_data_fn) { + uilst->dyn_data->free_runtime_data_fn(uilst); } if (uilst->properties) { IDP_FreeProperty(uilst->properties); } + MEM_SAFE_FREE(uilst->dyn_data); } if (region->gizmo_map != NULL) { @@ -1734,6 +1728,12 @@ static void direct_link_area(BlendDataReader *reader, ScrArea *area) sfile->runtime = NULL; BLO_read_data_address(reader, &sfile->params); BLO_read_data_address(reader, &sfile->asset_params); + if (sfile->params) { + sfile->params->rename_id = NULL; + } + if (sfile->asset_params) { + sfile->asset_params->base_params.rename_id = NULL; + } } else if (sl->spacetype == SPACE_ACTION) { SpaceAction *saction = (SpaceAction *)sl; diff --git a/source/blender/blenkernel/intern/shader_fx.c b/source/blender/blenkernel/intern/shader_fx.c index b537bdc5479..29cbe05f4d1 100644 --- a/source/blender/blenkernel/intern/shader_fx.c +++ b/source/blender/blenkernel/intern/shader_fx.c @@ -81,7 +81,7 @@ ShaderFxData *BKE_shaderfx_new(int type) const ShaderFxTypeInfo *fxi = BKE_shaderfx_get_info(type); ShaderFxData *fx = MEM_callocN(fxi->struct_size, fxi->struct_name); - /* note, this name must be made unique later */ + /* NOTE: this name must be made unique later. */ BLI_strncpy(fx->name, DATA_(fxi->name), sizeof(fx->name)); fx->type = type; diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c index aeb8133974e..7c0c28d664e 100644 --- a/source/blender/blenkernel/intern/shrinkwrap.c +++ b/source/blender/blenkernel/intern/shrinkwrap.c @@ -493,7 +493,7 @@ bool BKE_shrinkwrap_project_normal(char options, } if (options & MOD_SHRINKWRAP_CULL_TARGET_MASK) { - /* apply backface */ + /* Apply back-face. */ const float dot = dot_v3v3(dir, hit_tmp.no); if (((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f) || ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f)) { @@ -502,7 +502,7 @@ bool BKE_shrinkwrap_project_normal(char options, } if (transf) { - /* Inverting space transform (TODO make coeherent with the initial dist readjust) */ + /* Inverting space transform (TODO: make coherent with the initial dist readjust). */ BLI_space_transform_invert(transf, hit_tmp.co); #ifdef USE_DIST_CORRECT hit_tmp.dist = len_v3v3(vert, hit_tmp.co); @@ -1440,7 +1440,7 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob_target = DEG_get_evaluated_object(ctx->depsgraph, smd->target); calc.target = BKE_modifier_get_evaluated_mesh_from_evaluated_object(ob_target, false); - /* TODO there might be several "bugs" with non-uniform scales matrices + /* TODO: there might be several "bugs" with non-uniform scales matrices * because it will no longer be nearest surface, not sphere projection * because space has been deformed */ BLI_SPACE_TRANSFORM_SETUP(&calc.local2target, ob, ob_target); @@ -1460,7 +1460,7 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, ssmd.subdivType = ME_CC_SUBSURF; /* catmull clark */ ssmd.levels = smd->subsurfLevels; /* levels */ - /* TODO to be moved to Mesh once we are done with changes in subsurf code. */ + /* TODO: to be moved to Mesh once we are done with changes in subsurf code. */ DerivedMesh *dm = CDDM_from_mesh(mesh); ss_mesh = subsurf_make_derived_from_derived( diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c index 9d871777c61..e4e2ed94b41 100644 --- a/source/blender/blenkernel/intern/softbody.c +++ b/source/blender/blenkernel/intern/softbody.c @@ -901,7 +901,7 @@ static void free_softbody_baked(SoftBody *sb) static void free_scratch(SoftBody *sb) { if (sb->scratch) { - /* todo make sure everything is cleaned up nicly */ + /* TODO: make sure everything is cleaned up nicely. */ if (sb->scratch->colliderhash) { BLI_ghash_free(sb->scratch->colliderhash, NULL, @@ -973,7 +973,7 @@ static void free_softbody_intern(SoftBody *sb) * and need to tell their neighbors exactly what happens via spring forces * unless sbObjectStep( .. ) is called on sub frame timing level * BTW that also questions the use of a 'implicit' solvers on softbodies - * since that would only valid for 'slow' moving collision targets and dito particles + * since that would only valid for 'slow' moving collision targets and ditto particles. */ /* +++ dependency information functions. */ @@ -1907,7 +1907,7 @@ static void sb_spring_force( #endif } else { - /* TODO make this debug option */ + /* TODO: make this debug option. */ CLOG_WARN(&LOG, "bodypoint <bpi> is not attached to spring <*bs>"); return; } @@ -1994,12 +1994,12 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, return 999; } - /* debugerin */ + /* Debugging. */ if (sb->totpoint < ifirst) { printf("Aye 998"); return 998; } - /* debugerin */ + /* Debugging. */ bp = &sb->bpoint[ifirst]; for (bb = number_of_points_here; bb > 0; bb--, bp++) { @@ -2413,9 +2413,9 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float * copy_v3_v3(dx, bp->vec); } - /* so here is (x)'= v(elocity) */ - /* the euler step for location then becomes */ - /* x(t + dt) = x(t) + v(t~) * dt */ + /* So here is: `(x)'= v(elocity)`. + * The euler step for location then becomes: + * `x(t + dt) = x(t) + v(t~) * dt` */ mul_v3_fl(dx, forcetime); /* the freezer coming sooner or later */ @@ -2644,7 +2644,7 @@ static void interpolate_exciter(Object *ob, int timescale, int time) */ /* Resetting a Mesh SB object's springs */ -/* Spring length are caculted from'raw' mesh vertices that are NOT altered by modifier stack. */ +/* Spring length are calculated from 'raw' mesh vertices that are NOT altered by modifier stack. */ static void springs_from_mesh(Object *ob) { SoftBody *sb; @@ -2704,8 +2704,8 @@ static void mesh_to_softbody(Object *ob) bp = sb->bpoint; defgroup_index = me->dvert ? (sb->vertgroup - 1) : -1; - defgroup_index_mass = me->dvert ? BKE_object_defgroup_name_index(ob, sb->namedVG_Mass) : -1; - defgroup_index_spring = me->dvert ? BKE_object_defgroup_name_index(ob, sb->namedVG_Spring_K) : + defgroup_index_mass = me->dvert ? BKE_id_defgroup_name_index(&me->id, sb->namedVG_Mass) : -1; + defgroup_index_spring = me->dvert ? BKE_id_defgroup_name_index(&me->id, sb->namedVG_Spring_K) : -1; for (a = 0; a < me->totvert; a++, bp++) { @@ -2934,8 +2934,8 @@ static void lattice_to_softbody(Object *ob) bp = sb->bpoint; defgroup_index = lt->dvert ? (sb->vertgroup - 1) : -1; - defgroup_index_mass = lt->dvert ? BKE_object_defgroup_name_index(ob, sb->namedVG_Mass) : -1; - defgroup_index_spring = lt->dvert ? BKE_object_defgroup_name_index(ob, sb->namedVG_Spring_K) : + defgroup_index_mass = lt->dvert ? BKE_id_defgroup_name_index(<->id, sb->namedVG_Mass) : -1; + defgroup_index_spring = lt->dvert ? BKE_id_defgroup_name_index(<->id, sb->namedVG_Spring_K) : -1; /* same code used as for mesh vertices */ @@ -3009,7 +3009,7 @@ static void curve_surf_to_softbody(Object *ob) for (nu = cu->nurb.first; nu; nu = nu->next) { if (nu->bezt) { - /* Bezier case; this is nicly said naive; who ever wrote this part, + /* Bezier case; this is nicely said naive; who ever wrote this part, * it was not me (JOW) :). * * a: never ever make tangent handles (sub) and or (ob)ject to collision. @@ -3086,7 +3086,7 @@ static void softbody_to_object(Object *ob, float (*vertexCos)[3], int numVerts, if (sb->solverflags & SBSO_ESTIMATEIPO) { SB_estimate_transform(ob, sb->lcom, sb->lrot, sb->lscale); } - /* inverse matrix is not uptodate... */ + /* Inverse matrix is not up to date. */ invert_m4_m4(ob->imat, ob->obmat); for (a = 0; a < numVerts; a++, bp++) { diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index f4a9d328d86..fcb992e1535 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -824,7 +824,7 @@ void BKE_sound_set_scene_sound_pan(void *handle, float pan, char animated) void BKE_sound_update_sequencer(Main *main, bSound *sound) { - BLI_assert(!"is not supposed to be used, is weird function."); + BLI_assert_msg(0, "is not supposed to be used, is weird function."); Scene *scene; diff --git a/source/blender/blenkernel/intern/spline_base.cc b/source/blender/blenkernel/intern/spline_base.cc index aa0d95d4d61..6234cdf87e2 100644 --- a/source/blender/blenkernel/intern/spline_base.cc +++ b/source/blender/blenkernel/intern/spline_base.cc @@ -512,6 +512,10 @@ void Spline::sample_with_index_factors(const GVArray &src, using T = decltype(dummy); const GVArray_Typed<T> src_typed = src.typed<T>(); MutableSpan<T> dst_typed = dst.typed<T>(); + if (src.size() == 1) { + dst_typed.fill(src_typed[0]); + return; + } blender::threading::parallel_for(dst_typed.index_range(), 1024, [&](IndexRange range) { for (const int i : range) { const LookupResult interp = this->lookup_data_from_index_factor(index_factors[i]); diff --git a/source/blender/blenkernel/intern/spline_bezier.cc b/source/blender/blenkernel/intern/spline_bezier.cc index 02d26ac715b..b6764f65631 100644 --- a/source/blender/blenkernel/intern/spline_bezier.cc +++ b/source/blender/blenkernel/intern/spline_bezier.cc @@ -333,6 +333,46 @@ void BezierSpline::correct_end_tangents() const } } +/** + * De Casteljau Bezier subdivision. + * \param index: The index of the segment's start control point. + * \param next_index: The index of the control point at the end of the segment. Could be 0, + * if the spline is cyclic. + * \param parameter: The factor along the segment, between 0 and 1. Note that this is used + * directly by the calculation, it doesn't correspond to a portion of the evaluated length. + * + * <pre> + * handle_prev handle_next + * x----------------x + * / \ + * / x---O---x \ + * / result \ + * / \ + * O O + * point_prev point_next + * </pre> + */ +BezierSpline::InsertResult BezierSpline::calculate_segment_insertion(const int index, + const int next_index, + const float parameter) +{ + BLI_assert(parameter <= 1.0f && parameter >= 0.0f); + BLI_assert(next_index == 0 || next_index == index + 1); + const float3 &point_prev = positions_[index]; + const float3 &handle_prev = handle_positions_right_[index]; + const float3 &handle_next = handle_positions_left_[next_index]; + const float3 &point_next = positions_[next_index]; + const float3 center_point = float3::interpolate(handle_prev, handle_next, parameter); + + BezierSpline::InsertResult result; + result.handle_prev = float3::interpolate(point_prev, handle_prev, parameter); + result.handle_next = float3::interpolate(handle_next, point_next, parameter); + result.left_handle = float3::interpolate(result.handle_prev, center_point, parameter); + result.right_handle = float3::interpolate(center_point, result.handle_next, parameter); + result.position = float3::interpolate(result.left_handle, result.right_handle, parameter); + return result; +} + static void bezier_forward_difference_3d(const float3 &point_0, const float3 &point_1, const float3 &point_2, diff --git a/source/blender/blenkernel/intern/spline_nurbs.cc b/source/blender/blenkernel/intern/spline_nurbs.cc index 76d046337c0..ac6f1bd082c 100644 --- a/source/blender/blenkernel/intern/spline_nurbs.cc +++ b/source/blender/blenkernel/intern/spline_nurbs.cc @@ -346,7 +346,10 @@ Span<NURBSpline::BasisCache> NURBSpline::calculate_basis_cache() const const int size = this->size(); const int eval_size = this->evaluated_points_size(); - BLI_assert(this->evaluated_edges_size() > 0); + if (eval_size == 0) { + return {}; + } + basis_cache_.resize(eval_size); const int order = this->order(); diff --git a/source/blender/blenkernel/intern/studiolight.c b/source/blender/blenkernel/intern/studiolight.c index 4cc2d101b02..dc5162f201e 100644 --- a/source/blender/blenkernel/intern/studiolight.c +++ b/source/blender/blenkernel/intern/studiolight.c @@ -1352,7 +1352,7 @@ static void studiolight_irradiance_preview(uint *icon_buffer, StudioLight *sl) ITER_PIXELS_END; } -void BKE_studiolight_default(SolidLight lights[4], float light_ambient[4]) +void BKE_studiolight_default(SolidLight lights[4], float light_ambient[3]) { copy_v3_fl3(light_ambient, 0.0, 0.0, 0.0); diff --git a/source/blender/blenkernel/intern/subdiv.c b/source/blender/blenkernel/intern/subdiv.c index e6b51c586c3..fd32f52351a 100644 --- a/source/blender/blenkernel/intern/subdiv.c +++ b/source/blender/blenkernel/intern/subdiv.c @@ -68,7 +68,7 @@ eSubdivFVarLinearInterpolation BKE_subdiv_fvar_interpolation_from_uv_smooth(int case SUBSURF_UV_SMOOTH_ALL: return SUBDIV_FVAR_LINEAR_INTERPOLATION_NONE; } - BLI_assert(!"Unknown uv smooth flag"); + BLI_assert_msg(0, "Unknown uv smooth flag"); return SUBDIV_FVAR_LINEAR_INTERPOLATION_ALL; } @@ -81,7 +81,7 @@ eSubdivVtxBoundaryInterpolation BKE_subdiv_vtx_boundary_interpolation_from_subsu case SUBSURF_BOUNDARY_SMOOTH_ALL: return SUBDIV_VTX_BOUNDARY_EDGE_ONLY; } - BLI_assert(!"Unknown boundary smooth flag"); + BLI_assert_msg(0, "Unknown boundary smooth flag"); return SUBDIV_VTX_BOUNDARY_EDGE_ONLY; } diff --git a/source/blender/blenkernel/intern/subdiv_ccg.c b/source/blender/blenkernel/intern/subdiv_ccg.c index 8b672b2cb49..95f51a72b70 100644 --- a/source/blender/blenkernel/intern/subdiv_ccg.c +++ b/source/blender/blenkernel/intern/subdiv_ccg.c @@ -1509,7 +1509,7 @@ static SubdivCCGCoord coord_step_inside_from_boundary(const SubdivCCG *subdiv_cc ++result.y; } else { - BLI_assert(!"non-boundary element given"); + BLI_assert_msg(0, "non-boundary element given"); } return result; } diff --git a/source/blender/blenkernel/intern/subdiv_converter.c b/source/blender/blenkernel/intern/subdiv_converter.c index d5c75503500..39b701da262 100644 --- a/source/blender/blenkernel/intern/subdiv_converter.c +++ b/source/blender/blenkernel/intern/subdiv_converter.c @@ -44,7 +44,7 @@ int BKE_subdiv_converter_vtx_boundary_interpolation_from_settings(const SubdivSe case SUBDIV_VTX_BOUNDARY_EDGE_AND_CORNER: return OSD_VTX_BOUNDARY_EDGE_AND_CORNER; } - BLI_assert(!"Unknown vtx boundary interpolation"); + BLI_assert_msg(0, "Unknown vtx boundary interpolation"); return OSD_VTX_BOUNDARY_EDGE_ONLY; } @@ -65,6 +65,6 @@ int BKE_subdiv_converter_vtx_boundary_interpolation_from_settings(const SubdivSe case SUBDIV_FVAR_LINEAR_INTERPOLATION_ALL: return OSD_FVAR_LINEAR_INTERPOLATION_ALL; } - BLI_assert(!"Unknown fvar linear interpolation"); + BLI_assert_msg(0, "Unknown fvar linear interpolation"); return OSD_FVAR_LINEAR_INTERPOLATION_NONE; } diff --git a/source/blender/blenkernel/intern/subdiv_eval.c b/source/blender/blenkernel/intern/subdiv_eval.c index 693827f99ac..0001eb8a205 100644 --- a/source/blender/blenkernel/intern/subdiv_eval.c +++ b/source/blender/blenkernel/intern/subdiv_eval.c @@ -137,7 +137,7 @@ bool BKE_subdiv_eval_refine_from_mesh(Subdiv *subdiv, { if (subdiv->evaluator == NULL) { /* NOTE: This situation is supposed to be handled by begin(). */ - BLI_assert(!"Is not supposed to happen"); + BLI_assert_msg(0, "Is not supposed to happen"); return false; } /* Set coordinates of base mesh vertices. */ diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index 0dbfeaaaadb..cff2c5cc562 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -2352,7 +2352,7 @@ struct DerivedMesh *subsurf_make_derived_from_derived(struct DerivedMesh *dm, const bool ignore_simplify = (flags & SUBSURF_IGNORE_SIMPLIFY); CCGDerivedMesh *result; - /* note: editmode calculation can only run once per + /* NOTE: editmode calculation can only run once per * modifier stack evaluation (uses freed cache) T36299. */ if (flags & SUBSURF_FOR_EDIT_MODE) { int levels = (scene != NULL && !ignore_simplify) ? diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c index 74845e3f1b9..80ff8ce9162 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -176,7 +176,7 @@ static void text_blend_write(BlendWriter *writer, ID *id, const void *id_address } Text *text = (Text *)id; - /* Note: we are clearing local temp data here, *not* the flag in the actual 'real' ID. */ + /* NOTE: we are clearing local temp data here, *not* the flag in the actual 'real' ID. */ if ((text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) { text->flags &= ~TXT_ISEXT; } @@ -2397,7 +2397,7 @@ int text_check_bracket(const char ch) return 0; } -/* TODO, have a function for operators - +/* TODO: have a function for operators - * http://docs.python.org/py3k/reference/lexical_analysis.html#operators */ bool text_check_delim(const char ch) { diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c index f3d6bc4a6e3..068d048fd08 100644 --- a/source/blender/blenkernel/intern/tracking.c +++ b/source/blender/blenkernel/intern/tracking.c @@ -1525,7 +1525,7 @@ MovieTrackingMarker *BKE_tracking_marker_get(MovieTrackingTrack *track, int fram const int num_markers = track->markersnr; if (num_markers == 0) { - BLI_assert(!"Detected degenerated track, should never happen."); + BLI_assert_msg(0, "Detected degenerated track, should never happen."); return NULL; } diff --git a/source/blender/blenkernel/intern/tracking_region_tracker.c b/source/blender/blenkernel/intern/tracking_region_tracker.c index ef36acdc3d5..179def0a6f2 100644 --- a/source/blender/blenkernel/intern/tracking_region_tracker.c +++ b/source/blender/blenkernel/intern/tracking_region_tracker.c @@ -155,7 +155,7 @@ static ImBuf *tracking_context_get_keyframed_ibuf(MovieClip *clip, return tracking_context_get_frame_ibuf(clip, user, clip_flag, keyed_framenr); } -/* Get image buffer which si used as reference for track. */ +/* Get image buffer which is used as reference for track. */ static ImBuf *tracking_context_get_reference_ibuf(MovieClip *clip, MovieClipUser *user, int clip_flag, diff --git a/source/blender/blenkernel/intern/tracking_stabilize.c b/source/blender/blenkernel/intern/tracking_stabilize.c index 3dff750edfb..d5585116f7e 100644 --- a/source/blender/blenkernel/intern/tracking_stabilize.c +++ b/source/blender/blenkernel/intern/tracking_stabilize.c @@ -376,7 +376,7 @@ static MovieTrackingMarker *get_tracking_data_point(StabContext *ctx, * always guesswork. * * As a simple default, we use the weighted average of the location markers - * of the current frame as pivot point. TODO It is planned to add further + * of the current frame as pivot point. TODO: It is planned to add further * options, like e.g. anchoring the pivot point at the canvas. Moreover, * it is planned to allow for a user controllable offset. */ @@ -661,7 +661,7 @@ static void average_marker_positions(StabContext *ctx, int framenr, float r_ref_ int next_higher = MAXFRAME; use_values_from_fcurves(ctx, true); LISTBASE_FOREACH (MovieTrackingTrack *, track, &tracking->tracks) { - /* Note: we deliberately do not care if this track + /* NOTE: we deliberately do not care if this track * is already initialized for stabilization. */ if (track->flag & TRACK_USE_2D_STAB) { int startpoint = search_closest_marker_index(track, framenr); diff --git a/source/blender/blenkernel/intern/tracking_util.c b/source/blender/blenkernel/intern/tracking_util.c index ea0d92cf78e..16b36e94328 100644 --- a/source/blender/blenkernel/intern/tracking_util.c +++ b/source/blender/blenkernel/intern/tracking_util.c @@ -523,7 +523,7 @@ static void distortion_model_parameters_from_options( /* Libmv returned distortion model which is not known to Blender. This is a logical error in code * and Blender side is to be updated to match Libmv. */ - BLI_assert(!"Unknown distortion model"); + BLI_assert_msg(0, "Unknown distortion model"); } /* Fill in Libmv C-API camera intrinsics options from tracking structure. */ diff --git a/source/blender/blenkernel/intern/undo_system.c b/source/blender/blenkernel/intern/undo_system.c index 14dd286a315..e524bd254bb 100644 --- a/source/blender/blenkernel/intern/undo_system.c +++ b/source/blender/blenkernel/intern/undo_system.c @@ -140,7 +140,7 @@ static void undosys_id_ref_store(void *UNUSED(user_data), UndoRefID *id_ref) static void undosys_id_ref_resolve(void *user_data, UndoRefID *id_ref) { - /* Note: we could optimize this, + /* NOTE: we could optimize this, * for now it's not too bad since it only runs when we access undo! */ Main *bmain = user_data; ListBase *lb = which_libbase(bmain, GS(id_ref->name)); @@ -717,11 +717,31 @@ eUndoStepDir BKE_undosys_step_calc_direction(const UndoStack *ustack, } } - BLI_assert(!"Target undo step not found, this should not happen and may indicate an undo stack corruption"); + BLI_assert_msg(0, + "Target undo step not found, this should not happen and may indicate an undo " + "stack corruption"); return STEP_INVALID; } /** + * When reading undo steps for undo/redo, + * some extra checks are needed when so the correct undo step is decoded. + */ +static UndoStep *undosys_step_iter_first(UndoStep *us_reference, const eUndoStepDir undo_dir) +{ + if (us_reference->type->flags & UNDOTYPE_FLAG_DECODE_ACTIVE_STEP) { + /* Reading this step means an undo action reads undo twice. + * This should be avoided where possible, however some undo systems require it. + * + * Redo skips the current state as this represents the currently loaded state. */ + return (undo_dir == -1) ? us_reference : us_reference->next; + } + + /* Typical case, skip reading the current undo step. */ + return (undo_dir == -1) ? us_reference->prev : us_reference->next; +} + +/** * Undo/Redo until the given `us_target` step becomes the active (currently loaded) one. * * \note Unless `us_target` is a 'skipped' one and `use_skip` is true, `us_target` will become the @@ -786,15 +806,10 @@ bool BKE_undosys_step_load_data_ex(UndoStack *ustack, us_target->type->name, undo_dir); - /* Undo/Redo steps until we reach given target step (or beyond if it has to be skipped), from - * given reference step. - * - * NOTE: Unlike with redo case, where we can expect current active step to fully reflect current - * data status, in undo case we also do reload the active step. - * FIXME: this feels weak, and should probably not be actually needed? Or should also be done in - * redo case? */ + /* Undo/Redo steps until we reach given target step (or beyond if it has to be skipped), + * from given reference step. */ bool is_processing_extra_skipped_steps = false; - for (UndoStep *us_iter = (undo_dir == -1) ? us_reference : us_reference->next; us_iter != NULL; + for (UndoStep *us_iter = undosys_step_iter_first(us_reference, undo_dir); us_iter != NULL; us_iter = (undo_dir == -1) ? us_iter->prev : us_iter->next) { BLI_assert(us_iter != NULL); diff --git a/source/blender/blenkernel/intern/unit.c b/source/blender/blenkernel/intern/unit.c index 290b880934e..d9f02ce4c75 100644 --- a/source/blender/blenkernel/intern/unit.c +++ b/source/blender/blenkernel/intern/unit.c @@ -833,7 +833,7 @@ static char *find_next_op(const char *str, char *remaining_str, int len_max) return remaining_str + i; } } - BLI_assert(!"String should be NULL terminated"); + BLI_assert_msg(0, "String should be NULL terminated"); return remaining_str + i; } @@ -917,7 +917,7 @@ static int unit_scale_str(char *str, return 0; } - /* XXX - investigate, does not respect len_max properly. */ + /* XXX: investigate, does not respect len_max properly. */ char *str_found = (char *)unit_find_str(str, replace_str, case_sensitive); if (str_found == NULL) { @@ -931,7 +931,7 @@ static int unit_scale_str(char *str, /* Deal with unit bias for temperature units. Order of operations is important, so we * have to add parentheses, add the bias, then multiply by the scalar like usual. * - * Note: If these changes don't fit in the buffer properly unit evaluation has failed, + * NOTE: If these changes don't fit in the buffer properly unit evaluation has failed, * just try not to destroy anything while failing. */ if (unit->bias != 0.0) { /* Add the open parenthesis. */ diff --git a/source/blender/blenkernel/intern/volume.cc b/source/blender/blenkernel/intern/volume.cc index 272ecc71833..b28d17df814 100644 --- a/source/blender/blenkernel/intern/volume.cc +++ b/source/blender/blenkernel/intern/volume.cc @@ -197,7 +197,7 @@ static struct VolumeFileCache { Entry &entry = (Entry &)*it; entry.num_metadata_users++; - /* Note: pointers to unordered_set values are not invalidated when adding + /* NOTE: pointers to unordered_set values are not invalidated when adding * or removing other values. */ return &entry; } diff --git a/source/blender/blenkernel/intern/workspace.c b/source/blender/blenkernel/intern/workspace.c index 533107b2bf6..5cac149c503 100644 --- a/source/blender/blenkernel/intern/workspace.c +++ b/source/blender/blenkernel/intern/workspace.c @@ -29,6 +29,7 @@ #include "BLT_translation.h" +#include "BKE_asset.h" #include "BKE_global.h" #include "BKE_idprop.h" #include "BKE_idtype.h" @@ -53,6 +54,13 @@ /* -------------------------------------------------------------------- */ +static void workspace_init_data(ID *id) +{ + WorkSpace *workspace = (WorkSpace *)id; + + BKE_asset_library_reference_init_default(&workspace->active_asset_library); +} + static void workspace_free_data(ID *id) { WorkSpace *workspace = (WorkSpace *)id; @@ -180,7 +188,7 @@ IDTypeInfo IDType_ID_WS = { .translation_context = BLT_I18NCONTEXT_ID_WORKSPACE, .flags = IDTYPE_FLAGS_NO_COPY | IDTYPE_FLAGS_NO_MAKELOCAL | IDTYPE_FLAGS_NO_ANIMDATA, - .init_data = NULL, + .init_data = workspace_init_data, .copy_data = NULL, .free_data = workspace_free_data, .make_local = NULL, |