Blender V5.3
MOD_correctivesmooth.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2005 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
10
11#include <algorithm>
12
13#include "BLI_math_base.hh"
14#include "BLI_math_matrix_c.hh"
15#include "BLI_math_vector_c.hh"
16#include "BLI_utildefines.hh"
17
18#include "BLT_translation.hh"
19
20#include "DNA_mesh_types.h"
21#include "DNA_meshdata_types.h"
22#include "DNA_object_types.h"
23#include "DNA_screen_types.h"
24
25#include "MEM_guardedalloc.h"
26
27#include "BKE_deform.hh"
28#include "BKE_editmesh.hh"
29#include "BKE_mesh_wrapper.hh"
30
32#include "UI_resources.hh"
33
34#include "RNA_access.hh"
35#include "RNA_prototypes.hh"
36
37#include "MOD_modifiertypes.hh"
38#include "MOD_ui_common.hh"
39#include "MOD_util.hh"
40
41#include "BLO_read_write.hh"
42
44
45// #define DEBUG_TIME
46
47#ifdef DEBUG_TIME
48# include "BLI_time.hh"
50#endif
51
52#include "BLI_strict_flags.hh" /* IWYU pragma: keep. Keep last. */
53
54namespace blender {
55
56static void init_data(ModifierData *md)
57{
58 CorrectiveSmoothModifierData *csmd = reinterpret_cast<CorrectiveSmoothModifierData *>(md);
60
61 csmd->delta_cache.deltas = nullptr;
62}
63
64static void copy_data(const ModifierData *md, ModifierData *target, const int flag)
65{
67 reinterpret_cast<const CorrectiveSmoothModifierData *>(md);
68 CorrectiveSmoothModifierData *tcsmd = reinterpret_cast<CorrectiveSmoothModifierData *>(target);
69
70 BKE_modifier_copydata_generic(md, target, flag);
71
74 &tcsmd->bind_coords,
76
77 tcsmd->delta_cache.deltas = nullptr;
78 tcsmd->delta_cache.deltas_num = 0;
79}
80
82{
84 MEM_SAFE_DELETE(csmd->delta_cache.deltas);
85
86 csmd->bind_coords_num = 0;
87}
88
89static void free_data(ModifierData *md)
90{
91 CorrectiveSmoothModifierData *csmd = reinterpret_cast<CorrectiveSmoothModifierData *>(md);
92 freeBind(csmd);
93}
94
95static void required_data_mask(ModifierData *md, CustomData_MeshMasks *r_cddata_masks)
96{
97 CorrectiveSmoothModifierData *csmd = reinterpret_cast<CorrectiveSmoothModifierData *>(md);
98
99 /* ask for vertex groups if we need them */
100 if (csmd->defgrp_name[0] != '\0') {
101 r_cddata_masks->vmask |= CD_MASK_MDEFORMVERT;
102 }
103}
104
105/* check individual weights for changes and cache values */
106static void mesh_get_weights(const MDeformVert *dvert,
107 const int defgrp_index,
108 const uint verts_num,
109 const bool use_invert_vgroup,
110 float *smooth_weights)
111{
112 uint i;
113
114 for (i = 0; i < verts_num; i++, dvert++) {
115 const float w = BKE_defvert_find_weight(dvert, defgrp_index);
116
117 if (use_invert_vgroup == false) {
118 smooth_weights[i] = w;
119 }
120 else {
121 smooth_weights[i] = 1.0f - w;
122 }
123 }
124}
125
126static void mesh_get_boundaries(Mesh *mesh, float *smooth_weights)
127{
128 const Span<int2> edges = mesh->edges();
129 const OffsetIndices faces = mesh->faces();
130 const Span<int> corner_edges = mesh->corner_edges();
131
132 /* Flag boundary edges so only boundaries are set to 1. */
133 uint8_t *boundaries = MEM_new_array_zeroed<uint8_t>(size_t(edges.size()), __func__);
134
135 for (const int64_t i : faces.index_range()) {
136 for (const int edge : corner_edges.slice(faces[i])) {
137 uint8_t *e_value = &boundaries[edge];
138 *e_value |= uint8_t((*e_value) + 1);
139 }
140 }
141
142 for (const int64_t i : edges.index_range()) {
143 if (boundaries[i] == 1) {
144 smooth_weights[edges[i][0]] = 0.0f;
145 smooth_weights[edges[i][1]] = 0.0f;
146 }
147 }
148
149 MEM_delete(boundaries);
150}
151
152/* -------------------------------------------------------------------- */
153/* Simple Weighted Smoothing
154 *
155 * (average of surrounding verts)
156 */
158 Mesh *mesh,
159 MutableSpan<float3> vertexCos,
160 const float *smooth_weights,
161 uint iterations)
162{
163 const float lambda = csmd->lambda;
164 int i;
165
166 const int edges_num = mesh->edges_num;
167 const Span<int2> edges = mesh->edges();
168
169 struct SmoothingData_Simple {
170 float delta[3];
171 };
172 SmoothingData_Simple *smooth_data = MEM_new_array_zeroed<SmoothingData_Simple>(
173 size_t(vertexCos.size()), __func__);
174
175 float *vertex_edge_count_div = MEM_new_array_zeroed<float>(size_t(vertexCos.size()), __func__);
176
177 /* calculate as floats to avoid int->float conversion in #smooth_iter */
178 for (i = 0; i < edges_num; i++) {
179 vertex_edge_count_div[edges[i][0]] += 1.0f;
180 vertex_edge_count_div[edges[i][1]] += 1.0f;
181 }
182
183 /* a little confusing, but we can include 'lambda' and smoothing weight
184 * here to avoid multiplying for every iteration */
185 if (smooth_weights == nullptr) {
186 for (i = 0; i < vertexCos.size(); i++) {
187 vertex_edge_count_div[i] = lambda * (vertex_edge_count_div[i] ?
188 (1.0f / vertex_edge_count_div[i]) :
189 1.0f);
190 }
191 }
192 else {
193 for (i = 0; i < vertexCos.size(); i++) {
194 vertex_edge_count_div[i] = smooth_weights[i] * lambda *
195 (vertex_edge_count_div[i] ? (1.0f / vertex_edge_count_div[i]) :
196 1.0f);
197 }
198 }
199
200 /* -------------------------------------------------------------------- */
201 /* Main Smoothing Loop */
202
203 while (iterations--) {
204 for (i = 0; i < edges_num; i++) {
205 SmoothingData_Simple *sd_v1;
206 SmoothingData_Simple *sd_v2;
207 float edge_dir[3];
208
209 sub_v3_v3v3(edge_dir, vertexCos[edges[i][1]], vertexCos[edges[i][0]]);
210
211 sd_v1 = &smooth_data[edges[i][0]];
212 sd_v2 = &smooth_data[edges[i][1]];
213
214 add_v3_v3(sd_v1->delta, edge_dir);
215 sub_v3_v3(sd_v2->delta, edge_dir);
216 }
217
218 for (i = 0; i < vertexCos.size(); i++) {
219 SmoothingData_Simple *sd = &smooth_data[i];
220 madd_v3_v3fl(vertexCos[i], sd->delta, vertex_edge_count_div[i]);
221 /* zero for the next iteration (saves memset on entire array) */
222 memset(sd, 0, sizeof(*sd));
223 }
224 }
225
226 MEM_delete(vertex_edge_count_div);
227 MEM_delete(smooth_data);
228}
229
230/* -------------------------------------------------------------------- */
231/* Edge-Length Weighted Smoothing
232 */
234 Mesh *mesh,
235 MutableSpan<float3> vertexCos,
236 const float *smooth_weights,
237 uint iterations)
238{
239 const float eps = FLT_EPSILON * 10.0f;
240 const uint edges_num = uint(mesh->edges_num);
241 /* NOTE: the way this smoothing method works, its approx half as strong as the simple-smooth,
242 * and 2.0 rarely spikes, double the value for consistent behavior. */
243 const float lambda = csmd->lambda * 2.0f;
244 const Span<int2> edges = mesh->edges();
245 uint i;
246
247 struct SmoothingData_Weighted {
248 float delta[3];
249 float edge_length_sum;
250 };
251 SmoothingData_Weighted *smooth_data = MEM_new_array_zeroed<SmoothingData_Weighted>(
252 size_t(vertexCos.size()), __func__);
253
254 /* calculate as floats to avoid int->float conversion in #smooth_iter */
255 float *vertex_edge_count = MEM_new_array_zeroed<float>(size_t(vertexCos.size()), __func__);
256 for (i = 0; i < edges_num; i++) {
257 vertex_edge_count[edges[i][0]] += 1.0f;
258 vertex_edge_count[edges[i][1]] += 1.0f;
259 }
260
261 /* -------------------------------------------------------------------- */
262 /* Main Smoothing Loop */
263
264 while (iterations--) {
265 for (i = 0; i < edges_num; i++) {
266 SmoothingData_Weighted *sd_v1;
267 SmoothingData_Weighted *sd_v2;
268 float edge_dir[3];
269 float edge_dist;
270
271 sub_v3_v3v3(edge_dir, vertexCos[edges[i][1]], vertexCos[edges[i][0]]);
272 edge_dist = len_v3(edge_dir);
273
274 /* weight by distance */
275 mul_v3_fl(edge_dir, edge_dist);
276
277 sd_v1 = &smooth_data[edges[i][0]];
278 sd_v2 = &smooth_data[edges[i][1]];
279
280 add_v3_v3(sd_v1->delta, edge_dir);
281 sub_v3_v3(sd_v2->delta, edge_dir);
282
283 sd_v1->edge_length_sum += edge_dist;
284 sd_v2->edge_length_sum += edge_dist;
285 }
286
287 if (smooth_weights == nullptr) {
288 /* fast-path */
289 for (i = 0; i < vertexCos.size(); i++) {
290 SmoothingData_Weighted *sd = &smooth_data[i];
291 /* Divide by sum of all neighbor distances (weighted) and amount of neighbors,
292 * (mean average). */
293 const float div = sd->edge_length_sum * vertex_edge_count[i];
294 if (div > eps) {
295#if 0
296 /* first calculate the new location */
297 mul_v3_fl(sd->delta, 1.0f / div);
298 /* then interpolate */
299 madd_v3_v3fl(vertexCos[i], sd->delta, lambda);
300#else
301 /* do this in one step */
302 madd_v3_v3fl(vertexCos[i], sd->delta, lambda / div);
303#endif
304 }
305 /* zero for the next iteration (saves memset on entire array) */
306 memset(sd, 0, sizeof(*sd));
307 }
308 }
309 else {
310 for (i = 0; i < vertexCos.size(); i++) {
311 SmoothingData_Weighted *sd = &smooth_data[i];
312 const float div = sd->edge_length_sum * vertex_edge_count[i];
313 if (div > eps) {
314 const float lambda_w = lambda * smooth_weights[i];
315 madd_v3_v3fl(vertexCos[i], sd->delta, lambda_w / div);
316 }
317
318 memset(sd, 0, sizeof(*sd));
319 }
320 }
321 }
322
323 MEM_delete(vertex_edge_count);
324 MEM_delete(smooth_data);
325}
326
328 Mesh *mesh,
329 MutableSpan<float3> vertexCos,
330 const float *smooth_weights,
331 uint iterations)
332{
333 switch (csmd->smooth_type) {
335 smooth_iter__length_weight(csmd, mesh, vertexCos, smooth_weights, iterations);
336 break;
337
338 /* case MOD_CORRECTIVESMOOTH_SMOOTH_SIMPLE: */
339 default:
340 smooth_iter__simple(csmd, mesh, vertexCos, smooth_weights, iterations);
341 break;
342 }
343}
344
346 Mesh *mesh,
347 const MDeformVert *dvert,
348 const int defgrp_index,
349 MutableSpan<float3> vertexCos)
350{
351 float *smooth_weights = nullptr;
352
353 if (dvert || (csmd->flag & MOD_CORRECTIVESMOOTH_PIN_BOUNDARY)) {
354
355 smooth_weights = MEM_new_array_uninitialized<float>(size_t(vertexCos.size()), __func__);
356
357 if (dvert) {
358 mesh_get_weights(dvert,
359 defgrp_index,
360 uint(vertexCos.size()),
362 smooth_weights);
363 }
364 else {
365 std::fill_n(smooth_weights, int(vertexCos.size()), 1.0f);
366 }
367
369 mesh_get_boundaries(mesh, smooth_weights);
370 }
371 }
372
373 smooth_iter(csmd, mesh, vertexCos, smooth_weights, uint(csmd->repeat));
374
375 if (smooth_weights) {
376 MEM_delete(smooth_weights);
377 }
378}
379
384static bool calc_tangent_loop(const float v_dir_prev[3],
385 const float v_dir_next[3],
386 float r_tspace[3][3])
387{
388 if (compare_v3v3(v_dir_prev, v_dir_next, FLT_EPSILON * 10.0f)) [[unlikely]] {
389 /* As there are no weights, the value doesn't matter just initialize it. */
390 unit_m3(r_tspace);
391 return false;
392 }
393
394 copy_v3_v3(r_tspace[0], v_dir_prev);
395 copy_v3_v3(r_tspace[1], v_dir_next);
396
397 cross_v3_v3v3(r_tspace[2], v_dir_prev, v_dir_next);
398 normalize_v3(r_tspace[2]);
399
400 /* Make orthogonal using `r_tspace[2]` as a basis.
401 *
402 * NOTE: while it seems more logical to use `v_dir_prev` & `v_dir_next` as separate X/Y axis
403 * (instead of combining them as is done here). It's not necessary as the directions of the
404 * axis aren't important as long as the difference between tangent matrices is equivalent.
405 * Some computations can be skipped by combining the two directions,
406 * using the cross product for the 3rd axes. */
407 add_v3_v3(r_tspace[0], r_tspace[1]);
408 normalize_v3(r_tspace[0]);
409 cross_v3_v3v3(r_tspace[1], r_tspace[2], r_tspace[0]);
410
411 return true;
412}
413
420static void calc_tangent_spaces(const Mesh *mesh,
421 Span<float3> vertexCos,
422 float (*r_tangent_spaces)[3][3],
423 float *r_tangent_weights,
424 float *r_tangent_weights_per_vertex)
425{
426 const uint mvert_num = uint(mesh->verts_num);
427 const OffsetIndices faces = mesh->faces();
428 Span<int> corner_verts = mesh->corner_verts();
429
430 if (r_tangent_weights_per_vertex != nullptr) {
431 std::fill_n(r_tangent_weights_per_vertex, int(mvert_num), 0.0f);
432 }
433
434 for (const int64_t i : faces.index_range()) {
435 const IndexRange face = faces[i];
436 int next_corner = int(face.start());
437 int term_corner = next_corner + int(face.size());
438 int prev_corner = term_corner - 2;
439 int curr_corner = term_corner - 1;
440
441 /* loop directions */
442 float v_dir_prev[3], v_dir_next[3];
443
444 /* needed entering the loop */
446 v_dir_prev, vertexCos[corner_verts[prev_corner]], vertexCos[corner_verts[curr_corner]]);
447 normalize_v3(v_dir_prev);
448
449 for (; next_corner != term_corner;
450 prev_corner = curr_corner, curr_corner = next_corner, next_corner++)
451 {
452 float (*ts)[3] = r_tangent_spaces[curr_corner];
453
454 /* re-use the previous value */
455#if 0
457 v_dir_prev, vertexCos[corner_verts[prev_corner]], vertexCos[corner_verts[curr_corner]]);
458 normalize_v3(v_dir_prev);
459#endif
461 v_dir_next, vertexCos[corner_verts[curr_corner]], vertexCos[corner_verts[next_corner]]);
462 normalize_v3(v_dir_next);
463
464 if (calc_tangent_loop(v_dir_prev, v_dir_next, ts)) {
465 if (r_tangent_weights != nullptr) {
466 const float weight = fabsf(math::safe_acos_approx(dot_v3v3(v_dir_next, v_dir_prev)));
467 r_tangent_weights[curr_corner] = weight;
468 r_tangent_weights_per_vertex[corner_verts[curr_corner]] += weight;
469 }
470 }
471 else {
472 if (r_tangent_weights != nullptr) {
473 r_tangent_weights[curr_corner] = 0;
474 }
475 }
476
477 copy_v3_v3(v_dir_prev, v_dir_next);
478 }
479 }
480}
481
483{
484 csmd->delta_cache.lambda = csmd->lambda;
485 csmd->delta_cache.repeat = csmd->repeat;
486 csmd->delta_cache.flag = csmd->flag;
487 csmd->delta_cache.smooth_type = csmd->smooth_type;
488 csmd->delta_cache.rest_source = csmd->rest_source;
489}
490
492{
493 return (csmd->delta_cache.lambda == csmd->lambda && csmd->delta_cache.repeat == csmd->repeat &&
494 csmd->delta_cache.flag == csmd->flag &&
495 csmd->delta_cache.smooth_type == csmd->smooth_type &&
496 csmd->delta_cache.rest_source == csmd->rest_source);
497}
498
504 Mesh *mesh,
505 const MDeformVert *dvert,
506 const int defgrp_index,
507 const Span<float3> rest_coords)
508{
509 const Span<int> corner_verts = mesh->corner_verts();
510
511 Array<float3> smooth_vertex_coords(rest_coords);
512
513 uint l_index;
514
515 float (*tangent_spaces)[3][3] = MEM_new_array_uninitialized<float[3][3]>(
516 size_t(corner_verts.size()), __func__);
517
518 if (csmd->delta_cache.deltas_num != uint(corner_verts.size())) {
519 MEM_SAFE_DELETE(csmd->delta_cache.deltas);
520 }
521
522 /* allocate deltas if they have not yet been allocated, otherwise we will just write over them */
523 if (!csmd->delta_cache.deltas) {
524 csmd->delta_cache.deltas_num = uint(corner_verts.size());
525 csmd->delta_cache.deltas = MEM_new_array_uninitialized<float[3]>(size_t(corner_verts.size()),
526 __func__);
527 }
528
529 smooth_verts(csmd, mesh, dvert, defgrp_index, smooth_vertex_coords);
530
531 calc_tangent_spaces(mesh, smooth_vertex_coords, tangent_spaces, nullptr, nullptr);
532
533 std::fill_n(&csmd->delta_cache.deltas[0][0], int(corner_verts.size()) * 3, 0.0f);
534
535 for (l_index = 0; l_index < corner_verts.size(); l_index++) {
536 const int v_index = corner_verts[l_index];
537 float delta[3];
538 sub_v3_v3v3(delta, rest_coords[v_index], smooth_vertex_coords[v_index]);
539
540 float imat[3][3];
541 if (!invert_m3_m3(imat, tangent_spaces[l_index])) [[unlikely]] {
542 transpose_m3_m3(imat, tangent_spaces[l_index]);
543 }
544 mul_v3_m3v3(csmd->delta_cache.deltas[l_index], imat, delta);
545 }
546
547 MEM_SAFE_DELETE(tangent_spaces);
548}
549
551 Depsgraph *depsgraph,
552 Object *ob,
553 Mesh *mesh,
554 MutableSpan<float3> vertexCos,
555 BMEditMesh *em)
556{
557 CorrectiveSmoothModifierData *csmd = reinterpret_cast<CorrectiveSmoothModifierData *>(md);
558
559 const bool force_delta_cache_update =
560 /* XXX, take care! if mesh data itself changes we need to forcefully recalculate deltas */
561 !cache_settings_equal(csmd) ||
563 (ob->data->recalc & ID_RECALC_ALL));
564
565 Span<int> corner_verts = mesh->corner_verts();
566
567 bool use_only_smooth = (csmd->flag & MOD_CORRECTIVESMOOTH_ONLY_SMOOTH) != 0;
568 const MDeformVert *dvert = nullptr;
569 int defgrp_index;
570
571 MOD_get_vgroup(ob, mesh, csmd->defgrp_name, &dvert, &defgrp_index);
572
573 /* if rest bind_coords not are defined, set them (only run during bind) */
575 /* signal to recalculate, whoever sets MUST also free bind coords */
576 (csmd->bind_coords_num == uint(-1)))
577 {
578 if (DEG_is_active(depsgraph)) {
579 BLI_assert(csmd->bind_coords == nullptr);
580 csmd->bind_coords = MEM_new_array_uninitialized<float[3]>(size_t(vertexCos.size()),
581 __func__);
583 memcpy(csmd->bind_coords, vertexCos.data(), size_t(vertexCos.size_in_bytes()));
584 csmd->bind_coords_num = uint(vertexCos.size());
585 BLI_assert(csmd->bind_coords != nullptr);
586
587 /* Copy bound data to the original modifier. */
588 CorrectiveSmoothModifierData *csmd_orig = reinterpret_cast<CorrectiveSmoothModifierData *>(
592 &csmd_orig->bind_coords,
593 &csmd_orig->bind_coords_sharing_info);
594
595 csmd_orig->bind_coords_num = csmd->bind_coords_num;
596 }
597 else {
598 BKE_modifier_set_error(ob, md, "Attempt to bind from inactive dependency graph");
599 }
600 }
601
602 if (use_only_smooth) [[unlikely]] {
603 smooth_verts(csmd, mesh, dvert, defgrp_index, vertexCos);
604 return;
605 }
606
608 (csmd->bind_coords == nullptr))
609 {
610 BKE_modifier_set_error(ob, md, "Bind data required");
611 goto error;
612 }
613
614 /* If the number of verts has changed, the bind is invalid, so we do nothing */
616 if (csmd->bind_coords_num != vertexCos.size()) {
618 md,
619 "Bind vertex count mismatch: %u to %u",
620 csmd->bind_coords_num,
621 uint(vertexCos.size()));
622 goto error;
623 }
624 }
625 else {
626 /* MOD_CORRECTIVESMOOTH_RESTSOURCE_ORCO */
627 if (ob->type != OB_MESH) {
628 BKE_modifier_set_error(ob, md, "Object is not a mesh");
629 goto error;
630 }
631 else {
632 const Mesh *orig_mesh = id_cast<const Mesh *>(ob->data);
633 const BMesh *orig_bm = BKE_editmesh_bmesh_get(orig_mesh);
634 const int orig_verts_num = orig_bm ? orig_bm->totvert : orig_mesh->verts_num;
635
636 if (orig_verts_num != vertexCos.size()) {
638 md,
639 "Original vertex count mismatch: %u to %u",
640 uint(orig_verts_num),
641 uint(vertexCos.size()));
642 goto error;
643 }
644 }
645 }
646
647 /* check to see if our deltas are still valid */
648 if (!csmd->delta_cache.deltas || (csmd->delta_cache.deltas_num != corner_verts.size()) ||
649 force_delta_cache_update)
650 {
651 Array<float3> rest_coords_alloc;
652 Span<float3> rest_coords;
653
655
657 /* caller needs to do sanity check here */
658 csmd->bind_coords_num = uint(vertexCos.size());
659 rest_coords = {reinterpret_cast<const float3 *>(csmd->bind_coords), csmd->bind_coords_num};
660 }
661 else {
662 if (em) {
664 rest_coords_alloc = BKE_editmesh_vert_coords_alloc_orco(bm);
665 rest_coords = rest_coords_alloc;
666 }
667 else {
668 const Mesh *object_mesh = id_cast<const Mesh *>(ob->data);
669 rest_coords = object_mesh->vert_positions();
670 }
671 }
672
673#ifdef DEBUG_TIME
674 TIMEIT_START(corrective_smooth_deltas);
675#endif
676
677 calc_deltas(csmd, mesh, dvert, defgrp_index, rest_coords);
678
679#ifdef DEBUG_TIME
680 TIMEIT_END(corrective_smooth_deltas);
681#endif
682 }
683
685 /* this could be a check, but at this point it _must_ be valid */
686 BLI_assert(csmd->bind_coords_num == vertexCos.size() && csmd->delta_cache.deltas);
687 }
688
689#ifdef DEBUG_TIME
690 TIMEIT_START(corrective_smooth);
691#endif
692
693 /* do the actual delta mush */
694 smooth_verts(csmd, mesh, dvert, defgrp_index, vertexCos);
695
696 {
697
698 const float scale = csmd->scale;
699
700 float (*tangent_spaces)[3][3] = MEM_new_array_uninitialized<float[3][3]>(
701 size_t(corner_verts.size()), __func__);
702 float *tangent_weights = MEM_new_array_uninitialized<float>(size_t(corner_verts.size()),
703 __func__);
704 float *tangent_weights_per_vertex = MEM_new_array_uninitialized<float>(
705 size_t(vertexCos.size()), __func__);
706
708 mesh, vertexCos, tangent_spaces, tangent_weights, tangent_weights_per_vertex);
709
710 for (const int64_t l_index : corner_verts.index_range()) {
711 const int v_index = corner_verts[l_index];
712 const float weight = tangent_weights[l_index] / tangent_weights_per_vertex[v_index];
713 if (!(weight > 0.0f)) [[unlikely]] {
714 /* Catches zero & divide by zero. */
715 continue;
716 }
717
718 float delta[3];
719 mul_v3_m3v3(delta, tangent_spaces[l_index], csmd->delta_cache.deltas[l_index]);
720 mul_v3_fl(delta, weight);
721 madd_v3_v3fl(vertexCos[v_index], delta, scale);
722 }
723
724 MEM_delete(tangent_spaces);
725 MEM_delete(tangent_weights);
726 MEM_delete(tangent_weights_per_vertex);
727 }
728
729#ifdef DEBUG_TIME
730 TIMEIT_END(corrective_smooth);
731#endif
732
733 return;
734
735 /* when the modifier fails to execute */
736error:
737 MEM_SAFE_DELETE(csmd->delta_cache.deltas);
738 csmd->delta_cache.deltas_num = 0;
739}
740
742 const ModifierEvalContext *ctx,
743 Mesh *mesh,
744 MutableSpan<float3> positions)
745{
746 correctivesmooth_modifier_do(md, ctx->depsgraph, ctx->object, mesh, positions, nullptr);
747}
748
749static void panel_draw(const bContext * /*C*/, Panel *panel)
750{
751 ui::Layout &layout = *panel->layout;
752
753 PointerRNA ob_ptr;
755
756 layout.use_property_split_set(true);
757
758 layout.prop(ptr, "factor", UI_ITEM_NONE, IFACE_("Factor"), ICON_NONE);
759 layout.prop(ptr, "iterations", UI_ITEM_NONE, std::nullopt, ICON_NONE);
760 layout.prop(ptr, "scale", UI_ITEM_NONE, std::nullopt, ICON_NONE);
761 layout.prop(ptr, "smooth_type", UI_ITEM_NONE, std::nullopt, ICON_NONE);
762
763 modifier_vgroup_ui(layout, ptr, &ob_ptr, "vertex_group", "invert_vertex_group", std::nullopt);
764
765 layout.prop(ptr, "use_only_smooth", UI_ITEM_NONE, std::nullopt, ICON_NONE);
766 layout.prop(ptr, "use_pin_boundary", UI_ITEM_NONE, std::nullopt, ICON_NONE);
767
768 layout.prop(ptr, "rest_source", UI_ITEM_NONE, std::nullopt, ICON_NONE);
769 if (RNA_enum_get(ptr, "rest_source") == MOD_CORRECTIVESMOOTH_RESTSOURCE_BIND) {
770 layout.op("OBJECT_OT_correctivesmooth_bind",
771 (RNA_boolean_get(ptr, "is_bind") ? IFACE_("Unbind") : IFACE_("Bind")),
772 ICON_NONE);
773 }
774
775 modifier_error_message_draw(layout, ptr);
776}
777
782
783static void blend_write(BlendWriter *writer, const ID *id_owner, const ModifierData *md)
784{
785 const CorrectiveSmoothModifierData *csmd =
786 reinterpret_cast<const CorrectiveSmoothModifierData *>(md);
787 const bool is_undo = writer->is_undo();
788 const bool without_bind_data = ID_IS_OVERRIDE_LIBRARY(id_owner) && !is_undo &&
790 if (without_bind_data) {
791 /* Modifier coming from linked data cannot be bound from an override, so we can remove all
792 * binding data, can save a significant amount of memory. */
793 BLI_assert(!ID_IS_LINKED(id_owner));
794 writer->write_struct(csmd, [](BlendStructWriter<CorrectiveSmoothModifierData> &struct_writer) {
795 struct_writer.shallow_data.bind_coords_num = 0;
796 struct_writer.shallow_data.bind_coords = nullptr;
797 struct_writer.shallow_data.bind_coords_sharing_info = nullptr;
798 });
799 return;
800 }
801
802 if (csmd->bind_coords != nullptr) {
803 writer->write_shared(csmd->bind_coords,
804 sizeof(float[3]) * csmd->bind_coords_num,
806 [&]() {
807 writer->write_float3_array(
808 csmd->bind_coords_num,
809 reinterpret_cast<const float *>(csmd->bind_coords));
810 });
811 }
812
813 writer->write_struct(csmd);
814}
815
816static void blend_read(BlendDataReader *reader, ModifierData *md)
817{
818 CorrectiveSmoothModifierData *csmd = reinterpret_cast<CorrectiveSmoothModifierData *>(md);
819
820 if (csmd->bind_coords) {
821 csmd->bind_coords_sharing_info = BLO_read_shared(reader, &csmd->bind_coords, [&]() {
822 BLO_read_array_and_validate_size(
823 reader, reinterpret_cast<float **>(&csmd->bind_coords), &csmd->bind_coords_num, 3);
824 return csmd->bind_coords ? implicit_sharing::info_for_mem_free(csmd->bind_coords) : nullptr;
825 });
826 }
827
828 /* runtime only */
829 csmd->delta_cache.deltas = nullptr;
830 csmd->delta_cache.deltas_num = 0;
831}
832
834 /*idname*/ "CorrectiveSmooth",
835 /*name*/ N_("CorrectiveSmooth"),
836 /*struct_name*/ "CorrectiveSmoothModifierData",
837 /*struct_size*/ sizeof(CorrectiveSmoothModifierData),
838 /*srna*/ &RNA_CorrectiveSmoothModifier,
841 /*icon*/ ICON_MOD_SMOOTH,
842
843 /*copy_data*/ copy_data,
844
845 /*deform_verts*/ deform_verts,
846 /*deform_matrices*/ nullptr,
847 /*deform_verts_EM*/ nullptr,
848 /*deform_matrices_EM*/ nullptr,
849 /*modify_mesh*/ nullptr,
850 /*modify_geometry_set*/ nullptr,
851
852 /*init_data*/ init_data,
853 /*required_data_mask*/ required_data_mask,
854 /*free_data*/ free_data,
855 /*is_disabled*/ nullptr,
856 /*update_depsgraph*/ nullptr,
857 /*depends_on_time*/ nullptr,
858 /*depends_on_normals*/ nullptr,
859 /*foreach_ID_link*/ nullptr,
860 /*foreach_tex_link*/ nullptr,
861 /*free_runtime_data*/ nullptr,
862 /*panel_register*/ panel_register,
863 /*blend_write*/ blend_write,
864 /*blend_read*/ blend_read,
865 /*foreach_cache*/ nullptr,
866 /*foreach_working_space_color*/ nullptr,
867};
868
869} // namespace blender
support for deformation groups and hooks.
Platform independent time functions.
Utility defines for timing/benchmarks.
#define TIMEIT_START(var)
#define TIMEIT_END(var)
#define IFACE_(msgid)
#define ID_IS_LINKED(_id)
Definition DNA_ID.h:697
#define ID_IS_OVERRIDE_LIBRARY(_id)
Definition DNA_ID.h:736
Object is a sort of wrapper for general info.
Read Blender memory allocation and freeing.
#define UI_ITEM_NONE
#define INIT_DEFAULT_STRUCT_AFTER(struct_dst, member)
#define CD_MASK_MDEFORMVERT
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
constexpr int64_t size() const
constexpr int64_t start() const
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr T * data() const
Definition BLI_span.hh:545
constexpr int64_t size_in_bytes() const
Definition BLI_span.hh:507
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
#define FLT_EPSILON
float3x3 scale(float3x3 mat, float2 scale)
void copy_shared_pointer(T *src_ptr, const ImplicitSharingInfo *src_sharing_info, T **r_dst_ptr, const ImplicitSharingInfo **r_dst_sharing_info)
void free_shared_data(T **data, const ImplicitSharingInfo **sharing_info)
const ImplicitSharingInfo * info_for_mem_free(T *data)
float safe_acos_approx(float x)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static void correctivesmooth_modifier_do(ModifierData *md, Depsgraph *depsgraph, Object *ob, Mesh *mesh, MutableSpan< float3 > vertexCos, BMEditMesh *em)
static void copy_data(const ModifierData *md, ModifierData *target, const int flag)
static void calc_deltas(CorrectiveSmoothModifierData *csmd, Mesh *mesh, const MDeformVert *dvert, const int defgrp_index, const Span< float3 > rest_coords)
@ MOD_CORRECTIVESMOOTH_SMOOTH_LENGTH_WEIGHT
__int64 int64_t
Definition BKE_text.h:90
static void mesh_get_weights(const MDeformVert *dvert, const int defgrp_index, const uint verts_num, const bool use_invert_vgroup, float *smooth_weights)
const ImplicitSharingInfo * BLO_read_shared(BlendDataReader *reader, T **data_ptr, FunctionRef< const ImplicitSharingInfo *()> read_fn)
int RNA_enum_get(PointerRNA *ptr, const char *name)
static void blend_write(BlendWriter *writer, const ID *, const ModifierData *md)
Definition MOD_bevel.cc:454
void BKE_modifier_set_error(const Object *ob, ModifierData *md, const char *format,...) ATTR_PRINTF_FORMAT(3
PointerRNA * modifier_panel_get_property_pointers(Panel *panel, PointerRNA *r_ob_ptr)
static void store_cache_settings(CorrectiveSmoothModifierData *csmd)
static void calc_tangent_spaces(const Mesh *mesh, Span< float3 > vertexCos, float(*r_tangent_spaces)[3][3], float *r_tangent_weights, float *r_tangent_weights_per_vertex)
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
bool DEG_is_active(const Depsgraph *depsgraph)
Definition depsgraph.cc:324
ModifierTypeInfo modifierType_CorrectiveSmooth
bool invert_m3_m3(float inverse[3][3], const float mat[3][3])
static bool cache_settings_equal(CorrectiveSmoothModifierData *csmd)
void MOD_get_vgroup(const Object *ob, const Mesh *mesh, const char *name, const MDeformVert **dvert, int *defgrp_index)
Definition MOD_util.cc:158
@ MOD_CORRECTIVESMOOTH_RESTSOURCE_BIND
@ MOD_CORRECTIVESMOOTH_RESTSOURCE_ORCO
@ eModifierType_CorrectiveSmooth
static void init_data(ModifierData *md)
static bool calc_tangent_loop(const float v_dir_prev[3], const float v_dir_next[3], float r_tspace[3][3])
static void smooth_iter__length_weight(CorrectiveSmoothModifierData *csmd, Mesh *mesh, MutableSpan< float3 > vertexCos, const float *smooth_weights, uint iterations)
MINLINE void mul_v3_fl(float r[3], float f)
static void required_data_mask(ModifierData *, CustomData_MeshMasks *r_cddata_masks)
MINLINE void sub_v3_v3(float r[3], const float a[3])
static void mesh_get_boundaries(Mesh *mesh, float *smooth_weights)
void transpose_m3_m3(float R[3][3], const float M[3][3])
MINLINE void madd_v3_v3fl(float r[3], const float a[3], float f)
void modifier_error_message_draw(ui::Layout &layout, PointerRNA *ptr)
float BKE_defvert_find_weight(const MDeformVert *dvert, int defgroup)
Definition deform.cc:779
void modifier_vgroup_ui(ui::Layout &layout, PointerRNA *ptr, PointerRNA *ob_ptr, const StringRefNull vgroup_prop, const std::optional< StringRefNull > invert_vgroup_prop, const std::optional< StringRefNull > text)
MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3])
static void free_data(ModifierData *md)
static void panel_register(ARegionType *region_type)
unsigned char uint8_t
Definition BKE_text.h:79
MINLINE float len_v3(const float a[3]) ATTR_WARN_UNUSED_RESULT
bool RNA_boolean_get(PointerRNA *ptr, const char *name)
@ eModifierTypeFlag_SupportsEditmode
@ eModifierTypeFlag_AcceptsMesh
static void blend_read(BlendDataReader *, ModifierData *md)
MINLINE float normalize_v3(float n[3])
static void smooth_iter__simple(CorrectiveSmoothModifierData *csmd, Mesh *mesh, MutableSpan< float3 > vertexCos, const float *smooth_weights, uint iterations)
MINLINE void add_v3_v3(float r[3], const float a[3])
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
MINLINE bool compare_v3v3(const float v1[3], const float v2[3], float limit) ATTR_WARN_UNUSED_RESULT
void unit_m3(float m[3][3])
PanelType * modifier_panel_register(ARegionType *region_type, ModifierType type, PanelDrawFn draw)
@ ID_RECALC_ALL
Definition DNA_ID.h:1190
@ eModifierFlag_OverrideLibrary_Local
const BMesh * BKE_editmesh_bmesh_get(const Object *ob)
Definition editmesh.cc:65
static void panel_draw(const bContext *, Panel *panel)
@ MOD_CORRECTIVESMOOTH_ONLY_SMOOTH
@ MOD_CORRECTIVESMOOTH_PIN_BOUNDARY
@ MOD_CORRECTIVESMOOTH_INVERT_VGROUP
static void deform_verts(ModifierData *md, const ModifierEvalContext *ctx, Mesh *mesh, MutableSpan< float3 > positions)
Array< float3 > BKE_editmesh_vert_coords_alloc_orco(const BMesh *bm)
Definition editmesh.cc:248
VecBase< float, 3 > float3
static void freeBind(CorrectiveSmoothModifierData *csmd)
static void smooth_verts(CorrectiveSmoothModifierData *csmd, Mesh *mesh, const MDeformVert *dvert, const int defgrp_index, MutableSpan< float3 > vertexCos)
void mul_v3_m3v3(float r[3], const float M[3][3], const float a[3])
ModifierData * BKE_modifier_get_original(const Object *object, ModifierData *md)
MINLINE float dot_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
static void smooth_iter(CorrectiveSmoothModifierData *csmd, Mesh *mesh, MutableSpan< float3 > vertexCos, const float *smooth_weights, uint iterations)
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
void BKE_modifier_copydata_generic(const ModifierData *md, ModifierData *md_dst, int flag)
const btScalar eps
Definition poly34.cpp:11
#define fabsf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
void write_shared(const void *data, size_t approximate_size_in_bytes, const ImplicitSharingInfo *sharing_info, FunctionRef< void()> write_fn)
void write_struct(const T *data, BlendStructWriterTypedFn< T > fn=nullptr)
bool is_undo() const
CorrectiveSmoothModifierType smooth_type
const ImplicitSharingInfoHandle * bind_coords_sharing_info
unsigned int recalc
Definition DNA_ID.h:446
ui::Layout * layout
void use_property_split_set(bool is_sep)
PointerRNA op(wmOperatorType *ot, std::optional< StringRef > name, int icon, wm::OpCallContext context, eUI_Item_Flag flag)
void prop(PointerRNA *ptr, PropertyRNA *prop, int index, int value, eUI_Item_Flag flag, std::optional< StringRef > name_opt, int icon, std::optional< StringRef > placeholder=std::nullopt)
#define N_(msgid)