Blender V5.3
blenkernel/intern/mesh_mirror.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BLI_array.hh"
10#include "BLI_math_geom_c.hh"
11#include "BLI_math_matrix_c.hh"
12#include "BLI_math_vector_c.hh"
13
14#include "DNA_meshdata_types.h"
15#include "DNA_object_types.h"
16
17#include "BKE_attribute.hh"
19#include "BKE_deform.hh"
20#include "BKE_lib_id.hh"
21#include "BKE_mesh.hh"
22#include "BKE_mesh_mirror.hh"
23#include "BKE_modifier.hh"
24
25#include "bmesh.hh"
26#include "bmesh_tools.hh"
27
28#include "MEM_guardedalloc.h"
29
30namespace blender {
31
33 const Mesh *mesh,
34 int axis,
35 const float plane_co[3],
36 float plane_no[3])
37{
38 bool do_bisect_flip_axis = ((axis == 0 && mmd->flag & MOD_MIR_BISECT_FLIP_AXIS_X) ||
39 (axis == 1 && mmd->flag & MOD_MIR_BISECT_FLIP_AXIS_Y) ||
40 (axis == 2 && mmd->flag & MOD_MIR_BISECT_FLIP_AXIS_Z));
41
42 const float bisect_distance = mmd->bisect_threshold;
43
44 Mesh *result;
45 BMesh *bm;
46 BMIter viter;
47 BMVert *v, *v_next;
48
49 BMeshCreateParams bmesh_create_params{false};
50
51 BMeshFromMeshParams bmesh_from_mesh_params{};
52 bmesh_from_mesh_params.calc_face_normal = true;
53 bmesh_from_mesh_params.calc_vert_normal = true;
54 bmesh_from_mesh_params.cd_mask_extra.vmask = CD_MASK_ORIGINDEX;
55 bmesh_from_mesh_params.cd_mask_extra.emask = CD_MASK_ORIGINDEX;
56 bmesh_from_mesh_params.cd_mask_extra.pmask = CD_MASK_ORIGINDEX;
57
58 bm = BKE_mesh_to_bmesh_ex(mesh, &bmesh_create_params, &bmesh_from_mesh_params);
59
60 /* Define bisecting plane (aka mirror plane). */
61 float plane[4];
62 if (!do_bisect_flip_axis) {
63 /* That reversed condition is a little weird, but for some reason that's how you keep
64 * the part of the mesh which is on the non-mirrored side when flip option is disabled.
65 * I think this is the expected behavior. */
66 negate_v3(plane_no);
67 }
68 plane_from_point_normal_v3(plane, plane_co, plane_no);
69
70 BM_mesh_bisect_plane(bm, plane, true, false, 0, 0, bisect_distance);
71
72 /* Plane definitions for vert killing. */
73 float plane_offset[4];
74 copy_v3_v3(plane_offset, plane);
75 plane_offset[3] = plane[3] - bisect_distance;
76
77 /* Delete verts across the mirror plane. */
78 BM_ITER_MESH_MUTABLE (v, v_next, &viter, bm, BM_VERTS_OF_MESH) {
79 if (plane_point_side_v3(plane_offset, v->co) > 0.0f) {
81 }
82 }
83
86
87 return result;
88}
89
91 Mesh *mesh,
92 const int axis,
93 const float dist)
94{
95 BMeshCreateParams bmesh_create_params{};
96 bmesh_create_params.use_toolflags = true;
97
98 BMeshFromMeshParams bmesh_from_mesh_params{};
99 bmesh_from_mesh_params.calc_face_normal = true;
100 bmesh_from_mesh_params.calc_vert_normal = true;
101 bmesh_from_mesh_params.cd_mask_extra.vmask = CD_MASK_SHAPEKEY;
102
103 BMesh *bm = BKE_mesh_to_bmesh_ex(mesh, &bmesh_create_params, &bmesh_from_mesh_params);
106 "symmetrize input=%avef direction=%i dist=%f use_shapekey=%b",
107 axis,
108 dist,
109 true);
110
111 BMeshToMeshParams bmesh_to_mesh_params{};
112 bmesh_to_mesh_params.calc_object_remap = true;
113
114 BM_mesh_bm_to_me(bmain, bm, mesh, &bmesh_to_mesh_params);
116}
117
119 Object *ob,
120 const Mesh *mesh,
121 const int axis,
122 const bool use_correct_order_on_merge,
123 int **r_vert_merge_map,
124 int *r_vert_merge_map_len)
125{
126 using namespace blender::bke;
127 const float tolerance_sq = mmd->tolerance * mmd->tolerance;
128 const bool do_vtargetmap = (mmd->flag & MOD_MIR_NO_MERGE) == 0 && r_vert_merge_map != nullptr;
129
130 const bool do_bisect = ((axis == 0 && mmd->flag & MOD_MIR_BISECT_AXIS_X) ||
131 (axis == 1 && mmd->flag & MOD_MIR_BISECT_AXIS_Y) ||
132 (axis == 2 && mmd->flag & MOD_MIR_BISECT_AXIS_Z));
133
134 float mtx[4][4];
135 float plane_co[3], plane_no[3];
136 int a, totshape;
137 int *vtmap_a = nullptr, *vtmap_b = nullptr;
138
139 /* mtx is the mirror transformation */
140 unit_m4(mtx);
141 mtx[axis][axis] = -1.0f;
142
143 Object *mirror_ob = mmd->mirror_ob;
144 if (mirror_ob != nullptr) {
145 float tmp[4][4];
146 float itmp[4][4];
147
148 /* tmp is a transform from coords relative to the object's own origin,
149 * to coords relative to the mirror object origin */
150 invert_m4_m4(tmp, mirror_ob->object_to_world().ptr());
151 mul_m4_m4m4(tmp, tmp, ob->object_to_world().ptr());
152
153 /* itmp is the reverse transform back to origin-relative coordinates */
154 invert_m4_m4(itmp, tmp);
155
156 /* combine matrices to get a single matrix that translates coordinates into
157 * mirror-object-relative space, does the mirror, and translates back to
158 * origin-relative space */
159 mul_m4_series(mtx, itmp, mtx, tmp);
160
161 if (do_bisect) {
162 copy_v3_v3(plane_co, itmp[3]);
163 copy_v3_v3(plane_no, itmp[axis]);
164
165 /* Account for non-uniform scale in `ob`, see: #87592. */
166 float ob_scale[3] = {
167 len_squared_v3(ob->object_to_world().ptr()[0]),
168 len_squared_v3(ob->object_to_world().ptr()[1]),
169 len_squared_v3(ob->object_to_world().ptr()[2]),
170 };
171 /* Scale to avoid precision loss with extreme values. */
172 const float ob_scale_max = std::max({UNPACK3(ob_scale)});
173 if (ob_scale_max != 0.0f) [[likely]] {
174 mul_v3_fl(ob_scale, 1.0f / ob_scale_max);
175 mul_v3_v3(plane_no, ob_scale);
176 }
177 }
178 }
179 else if (do_bisect) {
180 copy_v3_v3(plane_co, mtx[3]);
181 /* Need to negate here, since that axis is inverted (for mirror transform). */
182 negate_v3_v3(plane_no, mtx[axis]);
183 }
184
185 Mesh *mesh_bisect = nullptr;
186 if (do_bisect) {
188 mmd, mesh, axis, plane_co, plane_no);
189 mesh = mesh_bisect;
190 }
191
192 const int src_verts_num = mesh->verts_num;
193 const int src_edges_num = mesh->edges_num;
194 const OffsetIndices src_faces = mesh->faces();
195 const int src_loops_num = mesh->corners_num;
196
198 mesh, src_verts_num * 2, src_edges_num * 2, src_faces.size() * 2, src_loops_num * 2);
199
204
205 /* Copy custom-data to original geometry. */
206
207 vert_interp.copy(0, 0, src_verts_num);
208 edge_interp.copy(0, 0, src_edges_num);
209 face_interp.copy(0, 0, src_faces.size());
210 corner_interp.copy(0, 0, src_loops_num);
211
212 /* Copy custom data to mirrored geometry. */
213 vert_interp.copy(0, src_verts_num, src_verts_num);
214 edge_interp.copy(0, src_edges_num, src_edges_num);
215 face_interp.copy(0, src_faces.size(), src_faces.size());
216 corner_interp.copy(0, src_loops_num, src_loops_num);
217
218 if (do_vtargetmap) {
219 /* second half is filled with -1 */
220 *r_vert_merge_map = MEM_new_array_uninitialized<int>(2 * size_t(src_verts_num),
221 "MOD_mirror tarmap");
222
223 vtmap_a = *r_vert_merge_map;
224 vtmap_b = *r_vert_merge_map + src_verts_num;
225
226 *r_vert_merge_map_len = 0;
227 }
228
229 /* mirror vertex coordinates */
230 MutableSpan<float3> positions = result->vert_positions_for_write();
231 for (int i = 0; i < src_verts_num; i++) {
232 const int vert_index_prev = i;
233 const int vert_index = src_verts_num + i;
234 mul_m4_v3(mtx, positions[vert_index]);
235
236 if (do_vtargetmap) {
237 /* Compare location of the original and mirrored vertex,
238 * to see if they should be mapped for merging.
239 *
240 * Always merge from the copied into the original vertices so it's possible to
241 * generate a 1:1 mapping by scanning vertices from the beginning of the array
242 * as is done in #BKE_editmesh_vert_coords_when_deformed. Without this,
243 * the coordinates returned will sometimes point to the copied vertex locations, see:
244 * #91444.
245 *
246 * However, such a change also affects non-versionable things like some modifiers binding, so
247 * we cannot enforce that behavior on existing modifiers, in which case we keep using the
248 * old, incorrect behavior of merging the source vertex into its copy.
249 */
250 const bool merge = len_squared_v3v3(positions[vert_index_prev], positions[vert_index]) <
251 tolerance_sq;
252 if (merge) [[unlikely]] {
253 (*r_vert_merge_map_len)++;
254
255 /* average location */
256 mid_v3_v3v3(positions[vert_index], positions[vert_index_prev], positions[vert_index]);
257 copy_v3_v3(positions[vert_index_prev], positions[vert_index]);
258
259 const int target = use_correct_order_on_merge ? vert_index_prev : vert_index;
260 *vtmap_a = target;
261 /* Fill here to avoid 2x loops. */
262 *vtmap_b = target;
263 }
264 else {
265 /* Vertices that aren't merged point at themselves. */
266 *vtmap_a = vert_index_prev;
267 *vtmap_b = vert_index;
268 }
269
270 vtmap_a++;
271 vtmap_b++;
272 }
273 }
274
275 /* handle shape keys */
276 totshape = CustomData_number_of_layers(&result->vert_data, CD_SHAPEKEY);
277 for (a = 0; a < totshape; a++) {
278 float (*cos)[3] = static_cast<float (*)[3]>(
279 CustomData_get_layer_n_for_write(&result->vert_data, CD_SHAPEKEY, a, result->verts_num));
280 for (int i = src_verts_num; i < result->verts_num; i++) {
281 mul_m4_v3(mtx, cos[i]);
282 }
283 }
284
285 MutableSpan<int2> result_edges = result->edges_for_write();
286 MutableSpan<int> result_face_offsets = result->face_offsets_for_write();
287 MutableSpan<int> result_corner_verts = result->corner_verts_for_write();
288 MutableSpan<int> result_corner_edges = result->corner_edges_for_write();
289
290 /* adjust mirrored edge vertex indices */
291 for (const int i : result_edges.index_range().drop_front(src_edges_num)) {
292 result_edges[i] += src_verts_num;
293 }
294
295 result_face_offsets.take_front(src_faces.size()).copy_from(mesh->face_offsets().drop_back(1));
296 for (const int i : src_faces.index_range()) {
297 result_face_offsets[src_faces.size() + i] = src_faces[i].start() + src_loops_num;
298 }
299 const OffsetIndices result_faces = result->faces();
300
301 /* adjust mirrored loop vertex and edge indices */
302 for (const int i : result_corner_verts.index_range().drop_front(src_loops_num)) {
303 result_corner_verts[i] += src_verts_num;
304 }
305 for (const int i : result_corner_edges.index_range().drop_front(src_loops_num)) {
306 result_corner_edges[i] += src_edges_num;
307 }
308
309 bke::mesh_flip_faces(*result, result_faces.index_range().drop_front(src_faces.size()));
310
311 if (!mesh->runtime->subsurf_optimal_display_edges.is_empty()) {
312 const BoundedBitSpan src = mesh->runtime->subsurf_optimal_display_edges;
313 result->runtime->subsurf_optimal_display_edges.resize(result->edges_num);
314 MutableBoundedBitSpan dst = result->runtime->subsurf_optimal_display_edges;
315 dst.take_front(src.size()).copy_from(src);
316 dst.take_back(src.size()).copy_from(src);
317 }
318
319 bke::MutableAttributeAccessor attributes = result->attributes_for_write();
320
321 /* handle uvs,
322 * let tessface recalc handle updating the MTFace data */
323 if (mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V) ||
324 (is_zero_v2(mmd->uv_offset_copy) == false))
325 {
326 const bool do_mirr_u = (mmd->flag & MOD_MIR_MIRROR_U) != 0;
327 const bool do_mirr_v = (mmd->flag & MOD_MIR_MIRROR_V) != 0;
328 /* If set, flip around center of each tile. */
329 const bool do_mirr_udim = (mmd->flag & MOD_MIR_MIRROR_UDIM) != 0;
330
331 for (const StringRef name : result->uv_map_names()) {
332 bke::SpanAttributeWriter uv_map_attr = attributes.lookup_for_write_span<float2>(name);
333 float (*uv_map)[2] = reinterpret_cast<float (*)[2]>(uv_map_attr.span.data());
334 int j = src_loops_num;
335 uv_map += j; /* second set of loops only */
336 for (; j-- > 0; uv_map++) {
337 if (do_mirr_u) {
338 float u = (*uv_map)[0];
339 if (do_mirr_udim) {
340 (*uv_map)[0] = ceilf(u) - fmodf(u, 1.0f) + mmd->uv_offset[0];
341 }
342 else {
343 (*uv_map)[0] = 1.0f - u + mmd->uv_offset[0];
344 }
345 }
346 if (do_mirr_v) {
347 float v = (*uv_map)[1];
348 if (do_mirr_udim) {
349 (*uv_map)[1] = ceilf(v) - fmodf(v, 1.0f) + mmd->uv_offset[1];
350 }
351 else {
352 (*uv_map)[1] = 1.0f - v + mmd->uv_offset[1];
353 }
354 }
355 (*uv_map)[0] += mmd->uv_offset_copy[0];
356 (*uv_map)[1] += mmd->uv_offset_copy[1];
357 }
358 uv_map_attr.finish();
359 }
360 }
361
362 /* handle custom normals */
363 bke::GAttributeWriter custom_normals = attributes.lookup_for_write("custom_normal");
364 if (ob->type == OB_MESH && custom_normals && custom_normals.domain == bke::AttrDomain::Corner &&
365 custom_normals.varray.type().is<short2>() && result->faces_num > 0)
366 {
367 Array<float3> corner_normals(result_corner_verts.size());
368 MutableVArraySpan clnors(custom_normals.varray.typed<short2>());
370
371 /* The transform matrix of a normal must be
372 * the transpose of inverse of transform matrix of the geometry... */
373 float mtx_nor[4][4];
374 invert_m4_m4(mtx_nor, mtx);
375 transpose_m4(mtx_nor);
376
377 /* calculate custom normals into corner_normals, then mirror first half into second half */
378 const VArraySpan sharp_edges = *attributes.lookup<bool>("sharp_edge", AttrDomain::Edge);
379 const VArraySpan sharp_faces = *attributes.lookup<bool>("sharp_face", AttrDomain::Face);
380 bke::mesh::normals_calc_corners(result->vert_positions(),
381 result_faces,
382 result_corner_verts,
383 result_corner_edges,
384 result->vert_to_face_map(),
385 result->face_normals_true(),
386 sharp_edges,
387 sharp_faces,
388 clnors,
389 &lnors_spacearr,
390 corner_normals);
391
392 /* mirroring has to account for loops being reversed in faces in second half */
393 for (const int i : src_faces.index_range()) {
394 const IndexRange src_face = src_faces[i];
395 const int mirror_i = src_faces.size() + i;
396
397 for (const int j : src_face) {
398 int mirrorj = result_faces[mirror_i].start();
399 if (j > src_face.start()) {
400 mirrorj += result_faces[mirror_i].size() - (j - src_face.start());
401 }
402
403 copy_v3_v3(corner_normals[mirrorj], corner_normals[j]);
404 mul_m4_v3(mtx_nor, corner_normals[mirrorj]);
405
406 const int space_index = lnors_spacearr.corner_space_indices[mirrorj];
408 lnors_spacearr.spaces[space_index], corner_normals[mirrorj]);
409 }
410 }
411
412 clnors.save();
413 }
414 custom_normals.finish();
415
416 /* handle vgroup stuff */
418 if ((mmd->flag & MOD_MIR_VGROUP) && !result->deform_verts().is_empty()) {
419 MDeformVert *dvert = result->deform_verts_for_write().data() + src_verts_num;
420 int flip_map_len = 0;
421 int *flip_map = BKE_object_defgroup_flip_map(ob, false, &flip_map_len);
422 if (flip_map) {
423 for (int i = 0; i < src_verts_num; dvert++, i++) {
424 /* merged vertices get both groups, others get flipped */
425 /* A vertex that isn't merged points at itself. */
426 if (use_correct_order_on_merge && do_vtargetmap &&
427 ((*r_vert_merge_map)[i + src_verts_num] != i + src_verts_num))
428 {
429 BKE_defvert_flip_merged(dvert - src_verts_num, flip_map, flip_map_len);
430 }
431 else if (!use_correct_order_on_merge && do_vtargetmap && ((*r_vert_merge_map)[i] != i)) {
432 BKE_defvert_flip_merged(dvert, flip_map, flip_map_len);
433 }
434 else {
435 BKE_defvert_flip(dvert, flip_map, flip_map_len);
436 }
437 }
438
439 MEM_delete(flip_map);
440 }
441 }
442 }
443
444 if (mesh_bisect != nullptr) {
445 BKE_id_free(nullptr, mesh_bisect);
446 }
447 return result;
448}
449
450} // namespace blender
support for deformation groups and hooks.
#define mul_m4_series(...)
Object is a sort of wrapper for general info.
Read Blender memory allocation and freeing.
#define UNPACK3(a)
#define BM_ITER_MESH_MUTABLE(ele, ele_next, iter, bm, itype)
#define BMO_FLAG_DEFAULTS
#define CD_MASK_ORIGINDEX
#define CD_MASK_SHAPEKEY
bool is() const
VMutableArray< T > typed() const
constexpr int64_t start() const
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr IndexRange index_range() const
Definition BLI_span.hh:676
constexpr MutableSpan take_front(const int64_t n) const
Definition BLI_span.hh:635
void copy_from(const BitSpan other)
Definition bit_span.cc:66
MutableBitSpan take_back(const int64_t n) const
MutableBoundedBitSpan take_front(const int64_t n) const
void copy_from(const BitSpan other)
Definition bit_span.cc:78
GAttributeReader lookup(const StringRef name) const
void copy(int src_index, int dst_index, int count) const
GAttributeWriter lookup_for_write(StringRef name)
GSpanAttributeWriter lookup_for_write_span(StringRef name)
constexpr IndexRange drop_front(int64_t n) const
constexpr void copy_from(Span< T > values) const
#define fmodf(x, y)
#define cos
OrientationBounds merge(const OrientationBounds &cone_a, const OrientationBounds &cone_b)
void normals_calc_corners(Span< float3 > vert_positions, OffsetIndices< int > faces, Span< int > corner_verts, Span< int > corner_edges, GroupedSpan< int > vert_to_face_map, Span< float3 > face_normals, Span< bool > sharp_edges, Span< bool > sharp_faces, Span< short2 > custom_normals, CornerNormalSpaceArray *r_fan_spaces, MutableSpan< float3 > r_corner_normals)
short2 corner_space_custom_normal_to_data(const CornerNormalSpace &lnor_space, const float3 &custom_lnor)
void mesh_flip_faces(Mesh &mesh, const IndexMask &selection)
BMesh Iterators.
MINLINE float len_squared_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
MINLINE void negate_v3_v3(float r[3], const float a[3])
MINLINE bool is_zero_v2(const float v[2]) ATTR_WARN_UNUSED_RESULT
int CustomData_number_of_layers(const CustomData *data, eCustomDataType type)
void BM_mesh_free(BMesh *bm)
BMesh Free Mesh.
MINLINE void copy_v3_v3(float r[3], const float a[3])
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
void * CustomData_get_layer_n_for_write(CustomData *data, eCustomDataType type, int n, int totelem)
void BM_vert_kill(BMesh *bm, BMVert *v)
void BKE_defvert_flip_merged(MDeformVert *dvert, const int *flip_map, int flip_map_num)
Definition deform.cc:432
bool invert_m4_m4(float inverse[4][4], const float mat[4][4])
void mul_m4_m4m4(float R[4][4], const float A[4][4], const float B[4][4])
ATTR_WARN_UNUSED_RESULT const BMVert * v
int * BKE_object_defgroup_flip_map(const Object *ob, bool use_default, int *r_flip_map_num)
Definition deform.cc:673
void plane_from_point_normal_v3(float r_plane[4], const float plane_co[3], const float plane_no[3])
Definition math_geom.cc:225
MINLINE void mul_v3_fl(float r[3], float f)
void BM_mesh_bisect_plane(BMesh *bm, const float plane[4], const bool use_snap_center, const bool use_tag, const short oflag_center, const short oflag_new, const float eps)
void mul_m4_v3(const float M[4][4], float r[3])
bool BKE_object_supports_vertex_groups(const Object *ob)
Definition deform.cc:465
VecBase< float, 2 > float2
MINLINE void mul_v3_v3(float r[3], const float a[3])
BMesh * BKE_mesh_to_bmesh_ex(const Mesh *mesh, const BMeshCreateParams *create_params, const BMeshFromMeshParams *convert_params)
Mesh * BKE_mesh_mirror_bisect_on_mirror_plane_for_modifier(MirrorModifierData *mmd, const Mesh *mesh, int axis, const float plane_co[3], float plane_no[3])
Mesh * BKE_mesh_mirror_apply_mirror_on_axis_for_modifier(MirrorModifierData *mmd, Object *ob, const Mesh *mesh, int axis, bool use_correct_order_on_merge, int **r_vert_merge_map, int *r_vert_merge_map_len)
MINLINE void negate_v3(float r[3])
MINLINE float plane_point_side_v3(const float plane[4], const float co[3])
void unit_m4(float m[4][4])
bool BMO_op_callf(BMesh *bm, int flag, const char *fmt,...)
void BKE_id_free(Main *bmain, void *idv)
void BKE_defvert_flip(MDeformVert *dvert, const int *flip_map, int flip_map_num)
Definition deform.cc:418
void BKE_mesh_mirror_apply_mirror_on_axis(Main *bmain, Mesh *mesh, int axis, float dist)
void mid_v3_v3v3(float r[3], const float a[3], const float b[3])
void transpose_m4(float R[4][4])
VecBase< int16_t, 2 > short2
Mesh * BKE_mesh_from_bmesh_for_eval_nomain(BMesh *bm, const CustomData_MeshMasks *cd_mask_extra, const Mesh *me_settings)
MINLINE float len_squared_v3(const float v[3]) ATTR_WARN_UNUSED_RESULT
Mesh * BKE_mesh_new_nomain_from_template(const Mesh *me_src, int verts_num, int edges_num, int faces_num, int corners_num)
void BM_mesh_bm_to_me(Main *bmain, BMesh *bm, Mesh *mesh, const BMeshToMeshParams *params)
#define ceilf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
struct CustomData_MeshMasks cd_mask_extra
Vector< CornerNormalSpace > spaces
Definition BKE_mesh.hh:165