Blender V5.3
mesh_bevel.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <algorithm>
10#include <memory>
11#include <optional>
12#include <utility>
13
14#include <fmt/format.h>
15
16#include "BLI_array.hh"
17#include "BLI_array_utils.hh"
18#include "BLI_index_mask.hh"
19#include "BLI_map.hh"
20#include "BLI_math_base.hh"
21#include "BLI_math_base_c.hh"
22#include "BLI_math_geom.hh"
23#include "BLI_math_matrix.hh"
24#include "BLI_math_rotation.hh"
25#include "BLI_math_vector.hh"
26#include "BLI_math_vector_c.hh"
27#include "BLI_offset_indices.hh"
28#include "BLI_ordered_edge.hh"
29#include "BLI_span.hh"
30#include "BLI_vector.hh"
31
32#include "BKE_attribute.hh"
34#include "BKE_attribute_math.hh"
35
36#include "BKE_mesh.hh"
37#include "BKE_mesh_mapping.hh"
38
39#include "GEO_mesh_bevel.hh"
40#include "GEO_mesh_selection.hh"
41
42// #define DEBUG_TIME
43#ifdef DEBUG_TIME
44# include "BLI_timeit.hh"
45#endif
46
47namespace blender::geometry {
48
49enum class FKind {
50 Orig = 0,
51 Edge = 1,
52 Vert = 2,
54};
55
56enum class AngleKind {
57 Smaller = -1,
59 Larger = 1,
60};
61
70
71struct UVFace {
72 int f;
74};
75
78
79enum class MeshKind {
80 None = 0,
85};
86
87enum class VMeshMethod {
90};
91
92struct NewVert {
93 int v = -1;
94 float3 co = float3(0.0f);
95};
96
110
111struct BoundVert;
112
113struct EdgeHalf {
114 EdgeHalf *next = nullptr;
115 EdgeHalf *prev = nullptr;
116
117 int e = -1;
118 int fprev = -1;
119 int fnext = -1;
120
121 BoundVert *leftv = nullptr;
122 BoundVert *rightv = nullptr;
123
125 int seg = 0;
126
127 float offset_l = 0.0f;
128 float offset_r = 0.0f;
129 float offset_l_spec = 0.0f;
130 float offset_r_spec = 0.0f;
131
132 bool is_bev = false;
133 bool is_rev = false;
134 bool is_seam = false;
135 bool visited_rpo = false;
136};
137
138struct BoundVert {
139 BoundVert *next = nullptr;
140 BoundVert *prev = nullptr;
141
143
144 EdgeHalf *efirst = nullptr;
145 EdgeHalf *elast = nullptr;
146 EdgeHalf *ebev = nullptr;
147
148 int index = 0;
150
151 bool any_seam = false;
152 bool visited = false;
153 bool is_arc_start = false;
154 bool is_patch_start = false;
155 bool is_profile_start = false;
156
157 int seam_len = 0;
158 int sharp_len = 0;
159};
160
168
169struct BevVert {
170 int v = -1;
171 int edgecount = 0;
172 int selcount = 0;
173 int wirecount = 0;
174 float offset = 0.0f;
175
176 bool any_seam = false;
177 bool visited = false;
178
180
182
183 std::unique_ptr<VMesh> vmesh;
184
186};
187
189enum class NewFaceKind : uint8_t {
190 Other = 0,
195};
196
198enum class NewEdgeKind : uint8_t {
199 Other = 0,
204};
205
207 public:
208 const Mesh &mesh;
209
215
218
223
224 private:
225 Vector<float3> new_vert_positions_;
226 Vector<int> new_face_offsets_;
227 Vector<int> new_corner_verts_;
228 Vector<int> new_corner_edges_;
229
230 /* Representative original element indices for attribute propagation (-1 = unknown). */
231 Vector<int> new_vert_examples_;
232 Vector<int> new_edge_examples_;
233 /* Per-new-edge seam/sharp overrides: -1=inherit, 0=force false, 1=force true. */
234 Vector<int8_t> new_edge_seam_overrides_;
235 Vector<int8_t> new_edge_sharp_overrides_;
236 Vector<int> new_face_examples_;
237 Vector<NewFaceKind> new_face_kinds_;
238 Vector<NewEdgeKind> new_edge_kinds_;
239
240 /* Per-corner UV face representative (-1 = use face-level new_face_examples_). */
241 Vector<int> new_corner_face_reps_;
242 /* Per-corner snap-edge index (-1 = no snap). Set by #face_set_corner_reps. */
243 Vector<int> new_corner_snap_edges_;
244
245 /* Per-UV-layer float2 values for new corners, indexed [layer][new_corner]. */
246 Vector<Vector<float2>> new_corner_uvs_;
247
252 Map<int, Vector<int>> new_vert_to_new_corners_;
253
258 Map<int, int> new_vert_bev_origin_;
259
260 Array<bool> kill_verts_;
261 Array<bool> kill_edges_;
262 Array<bool> kill_faces_;
263 Array<bool> kill_corners_;
264
265 using EdgeMap = VectorSet<OrderedEdge,
266 32,
272 EdgeMap edge_lookup_;
273
274 IndexMaskMemory memory_;
275 Array<int> vert_to_edge_offsets_;
276 Array<int> vert_to_edge_indices_;
277 Array<int> edge_to_face_map_offsets_;
278 Array<int> edge_to_face_map_indices_;
279
280 public:
281 explicit ExtendableMesh(const Mesh &mesh);
282
283 float3 vert_position(const int v) const;
284 int2 edge_verts(const int e) const;
285 IndexRange face_corners(const int f) const;
286 int corner_vert(const int c) const;
287 int corner_edge(const int c) const;
288
289 /* Creates a new vertex at `co`. `example_vert` is the index of an original vertex
290 * whose non-positional attributes will be copied to this new vertex at output time;
291 * pass -1 when no representative is known. */
292 int vert_create(const float3 &co, int example_vert = -1);
293 /* Creates (or looks up) the edge between v1 and v2. `example_edge` is the original
294 * edge index to use for attribute copying; pass -1 when unknown. */
295 int edge_create(const int v1, const int v2, int example_edge = -1);
296 /* Creates a new face from the given vertex ring. `example_face` is the original face
297 * whose attributes will be copied; pass -1 when unknown (deferred). */
298 int face_create(Span<int> verts, int example_face = -1);
299
308 void face_set_corner_reps(int face_idx, Span<int> face_reps, Span<int> snap_edges);
309
310 /* Returns the index of any existing edge (original or newly created) between v1 and v2,
311 * or -1 if no such edge exists yet. */
312 int find_edge(const int v1, const int v2) const
313 {
314 return edge_lookup_.index_of_try(OrderedEdge(v1, v2));
315 }
316
317 /* Sets the example edge of a previously created new edge.
318 * `edge_index` must be a new edge (>= mesh.edges_num) returned by #edge_create or #find_edge.
319 * Has no effect on original mesh edges (edge_index < mesh.edges_num). */
320 void edge_set_example(const int edge_index, const int example_edge)
321 {
322 const int new_idx = edge_index - mesh.edges_num;
323 if (new_idx >= 0 && new_idx < int(new_edge_examples_.size())) {
324 new_edge_examples_[new_idx] = example_edge;
325 }
326 }
327
328 /* Override the `uv_seam` attribute for a new edge, independent of its example edge.
329 * `value` = 0 -> force false, 1 -> force true. -1 (default) = inherit from example.
330 * Applied after attribute gathering in #build_output_mesh. */
331 void edge_set_seam_override(const int edge_index, int8_t value)
332 {
333 const int new_idx = edge_index - mesh.edges_num;
334 if (new_idx >= 0 && new_idx < int(new_edge_seam_overrides_.size())) {
335 new_edge_seam_overrides_[new_idx] = value;
336 }
337 }
338
339 /* Override the `sharp_edge` attribute for a new edge, independent of its example edge. */
340 void edge_set_sharp_override(const int edge_index, int8_t value)
341 {
342 const int new_idx = edge_index - mesh.edges_num;
343 if (new_idx >= 0 && new_idx < int(new_edge_sharp_overrides_.size())) {
344 new_edge_sharp_overrides_[new_idx] = value;
345 }
346 }
347
348 /* Allocates per-UV-layer float2 storage for new corners. Must be called after
349 * UVMapInfo is initialized and before any face_create call. */
350 void init_uv_storage(int uv_layers_num);
351
352 /* Per-UV-layer float2 values for new corners (one per layer, parallel to new_corner_verts_). */
354 {
355 return new_corner_uvs_[layer_index].as_mutable_span();
356 }
357 Span<float2> new_corner_uvs(int layer_index) const
358 {
359 return new_corner_uvs_[layer_index].as_span();
360 }
361
368 {
369 return new_vert_to_new_corners_;
370 }
371
379 {
380 return new_vert_bev_origin_;
381 }
382
383 void vert_kill(const int v);
384 void edge_kill(const int e);
385 void face_kill(const int f);
386 void corner_kill(const int c);
387
388 bool is_vert_killed(const int v) const;
389 bool is_edge_killed(const int e) const;
390 bool is_face_killed(const int f) const;
391 bool is_corner_killed(const int c) const;
392
394 int new_faces_num() const
395 {
396 /* new_face_offsets_ starts with a sentinel 0 at index 0 and gains one entry per face_create
397 * call, so the number of new faces is new_face_offsets_.size() - 1. */
398 return int(new_face_offsets_.size()) - 1;
399 }
400
402 {
403 return new_vert_positions_;
404 }
406 {
407 return edge_lookup_.as_span().cast<int2>().drop_front(src_edges.size());
408 }
409
411 {
412 return new_face_offsets_;
413 }
415 {
416 return new_corner_verts_;
417 }
419 {
420 return new_corner_edges_;
421 }
422
423 /* Per-new-element representative (example) original indices for attribute propagation.
424 * -1 means no representative is known. */
426 {
427 return new_vert_examples_;
428 }
430 {
431 return new_edge_examples_;
432 }
434 {
435 return new_edge_seam_overrides_;
436 }
438 {
439 return new_edge_sharp_overrides_;
440 }
442 {
443 return new_face_examples_;
444 }
446 {
447 return new_face_kinds_;
448 }
450 {
451 return new_face_kinds_.as_mutable_span();
452 }
454 {
455 return new_edge_kinds_;
456 }
457
458 void tag_last_face(const NewFaceKind kind)
459 {
460 if (!new_face_kinds_.is_empty()) {
461 new_face_kinds_.last() = kind;
462 }
463 }
464
468 void tag_edge_kind(const int edge_index, const NewEdgeKind kind)
469 {
470 const int ni = edge_index - mesh.edges_num;
471 if (ni >= 0 && ni < int(new_edge_kinds_.size())) {
472 new_edge_kinds_[ni] = kind;
473 }
474 }
475
478 {
479 return new_corner_face_reps_;
480 }
481
483 {
484 return new_corner_snap_edges_;
485 }
487 {
488 return kill_verts_;
489 }
491 {
492 return kill_edges_;
493 }
495 {
496 return kill_faces_;
497 }
499 {
500 return kill_corners_;
501 }
502};
503
505 : mesh(mesh),
506 src_positions(mesh.vert_positions()),
507 src_edges(mesh.edges()),
508 src_faces(mesh.faces()),
509 src_corner_verts(mesh.corner_verts()),
510 src_corner_edges(mesh.corner_edges()),
511 src_vert_normals(mesh.vert_normals()),
512 src_face_normals(mesh.face_normals())
513{
515 this->src_edges, mesh.verts_num, vert_to_edge_offsets_, vert_to_edge_indices_);
517 this->src_corner_edges,
519 edge_to_face_map_indices_,
520 edge_to_face_map_offsets_);
521 this->src_vert_to_corner = mesh.vert_to_corner_map();
523
524 kill_verts_ = Array<bool>(mesh.verts_num, false);
525 kill_edges_ = Array<bool>(mesh.edges_num, false);
526 kill_faces_ = Array<bool>(mesh.faces_num, false);
527 kill_corners_ = Array<bool>(mesh.corners_num, false);
528
529 edge_lookup_.reserve(mesh.edges_num);
530 for (const int e : this->src_edges.index_range()) {
531 edge_lookup_.add_new(OrderedEdge(this->src_edges[e]));
532 }
533
534 new_face_offsets_.append(0);
535}
536
538{
539 if (v < mesh.verts_num) {
540 return this->src_positions[v];
541 }
542 return new_vert_positions_[v - mesh.verts_num];
543}
544
546{
547 if (e < mesh.edges_num) {
548 return this->src_edges[e];
549 }
550 return int2(edge_lookup_[e].v_low, edge_lookup_[e].v_high);
551}
552
554{
555 if (f < mesh.faces_num) {
556 return this->src_faces[f];
557 }
558 const int f_new = f - mesh.faces_num;
559 const int start = new_face_offsets_[f_new];
560 const int size = new_face_offsets_[f_new + 1] - start;
561 return IndexRange(mesh.corners_num + start, size);
562}
563
564int ExtendableMesh::corner_vert(const int c) const
565{
566 if (c < mesh.corners_num) {
567 return this->src_corner_verts[c];
568 }
569 return new_corner_verts_[c - mesh.corners_num];
570}
571
572int ExtendableMesh::corner_edge(const int c) const
573{
574 if (c < mesh.corners_num) {
575 return this->src_corner_edges[c];
576 }
577 return new_corner_edges_[c - mesh.corners_num];
578}
579
580int ExtendableMesh::vert_create(const float3 &co, const int example_vert)
581{
582 const int index = mesh.verts_num + new_vert_positions_.size();
583 new_vert_positions_.append(co);
584 new_vert_examples_.append(example_vert);
585 if (example_vert >= 0) {
586 new_vert_bev_origin_.add_overwrite(index, example_vert);
587 }
588 return index;
589}
590
591int ExtendableMesh::edge_create(const int v1, const int v2, const int example_edge)
592{
593 const int start_size = edge_lookup_.size();
594 const int index = edge_lookup_.index_of_or_add(OrderedEdge(v1, v2));
595 if (edge_lookup_.size() != start_size) {
596 new_edge_examples_.append(example_edge);
597 new_edge_seam_overrides_.append(-1);
598 new_edge_sharp_overrides_.append(-1);
599 new_edge_kinds_.append(NewEdgeKind::Other);
600 }
601 return index;
602}
603
604int ExtendableMesh::face_create(const Span<int> verts, const int example_face)
605{
606 const int face_index = mesh.faces_num + new_face_offsets_.size() - 1;
607
608 for (const int i : verts.index_range()) {
609 const int v1 = verts[i];
610 const int v2 = verts[(i + 1) % verts.size()];
611 /* Edges created inside face_create have no single representative edge; use -1. */
612 const int e = this->edge_create(v1, v2, -1);
613
614 const int nc = int(new_corner_verts_.size());
615 new_corner_verts_.append(v1);
616 new_corner_edges_.append(e);
617 /* Per-corner face rep and snap edge: -1 until overridden by face_set_corner_reps. */
618 new_corner_face_reps_.append(-1);
619 new_corner_snap_edges_.append(-1);
620 /* Grow UV storage to match (values initialized to zero). */
621 for (Vector<float2> &layer_uvs : new_corner_uvs_) {
622 layer_uvs.append(float2(0.0f));
623 }
624 /* Record v1 -> new corner for the UV merge pass. */
625 new_vert_to_new_corners_.lookup_or_add_default(v1).append(nc);
626 }
627
628 new_face_offsets_.append(int(new_corner_verts_.size()));
629 new_face_examples_.append(example_face);
630 new_face_kinds_.append(NewFaceKind::Other);
631
632 return face_index;
633}
634
635void ExtendableMesh::init_uv_storage(const int uv_layers_num)
636{
637 new_corner_uvs_.resize(uv_layers_num);
638}
639
641 const Span<int> face_reps,
642 const Span<int> snap_edges)
643{
644 const int f_new = face_idx - mesh.faces_num;
645 BLI_assert(f_new >= 0 && f_new < new_faces_num());
646 /* The corner range for this face in the new_corner_* arrays is:
647 * [new_face_offsets_[f_new], new_face_offsets_[f_new+1]). */
648 const int c_start = new_face_offsets_[f_new];
649 const int c_end = new_face_offsets_[f_new + 1];
650 const int n = c_end - c_start;
651 for (int i = 0; i < n; i++) {
652 if (!face_reps.is_empty()) {
653 new_corner_face_reps_[c_start + i] = face_reps[i];
654 }
655 if (!snap_edges.is_empty()) {
656 new_corner_snap_edges_[c_start + i] = snap_edges[i];
657 }
658 }
659}
660
662{
663 if (v < mesh.verts_num) {
664 kill_verts_[v] = true;
665 /* Also kill all edges incident to this vertex, matching BMesh's BM_vert_kill semantics. */
666 for (const int e : this->src_vert_to_edge[v]) {
667 kill_edges_[e] = true;
668 }
669 }
670}
671
673{
674 if (e < mesh.edges_num) {
675 kill_edges_[e] = true;
676 }
677}
678
680{
681 if (f < mesh.faces_num) {
682 kill_faces_[f] = true;
683 /* Also kill all corners of this face, matching BMesh's BM_face_kill semantics. */
684 for (const int c : this->src_faces[f]) {
685 kill_corners_[c] = true;
686 }
687 }
688}
689
691{
692 if (c < mesh.corners_num) {
693 kill_corners_[c] = true;
694 }
695}
696
698{
699 return v < mesh.verts_num ? kill_verts_[v] : false;
700}
701
703{
704 return e < mesh.edges_num ? kill_edges_[e] : false;
705}
706
707bool ExtendableMesh::is_face_killed(const int f) const
708{
709 return f < mesh.faces_num ? kill_faces_[f] : false;
710}
711
712bool ExtendableMesh::is_corner_killed(const int c) const
713{
714 return c < mesh.corners_num ? kill_corners_[c] : false;
715}
716
717namespace uv {
718
720 public:
721 bool has_uv_maps = false;
723
724 struct UVLayer {
725 std::string name;
727 };
729
730 void init(const Mesh &mesh);
731
736 void find_components(const ExtendableMesh &emesh);
737
739 bool contig_uv_maps_across_edge(const ExtendableMesh &mesh, int e, int f1, int f2) const;
740
746 bool contig_uv_maps_around_vert(const ExtendableMesh &emesh, int v) const;
747};
748
750{
751 has_uv_maps = false;
752 const bke::AttributeAccessor attrs = mesh.attributes();
753 attrs.foreach_attribute([&](const bke::AttributeIter &iter) {
755 return;
756 }
757 const bke::AttributeReader<float2> uv_reader = iter.get<float2>();
758 if (uv_reader) {
759 this->uv_maps.append(UVLayer{
760 .name = iter.name,
761 .values = VArraySpan<float2>(*uv_reader),
762 });
763 this->has_uv_maps = true;
764 }
765 });
766}
767
769 const int e,
770 const int f1,
771 const int f2) const
772{
773 if (!has_uv_maps) {
774 return true;
775 }
776
777 const int2 edge_verts = emesh.src_edges[e];
778 const int v1 = edge_verts[0];
779 const int v2 = edge_verts[1];
780
781 const Span<int> corner_verts = emesh.src_corner_verts;
782 const IndexRange f1_corners = emesh.src_faces[f1];
783 const IndexRange f2_corners = emesh.src_faces[f2];
784
785 const int c1_v1 = bke::mesh::face_find_corner_from_vert(f1_corners, corner_verts, v1);
786 const int c1_v2 = bke::mesh::face_find_corner_from_vert(f1_corners, corner_verts, v2);
787 const int c2_v1 = bke::mesh::face_find_corner_from_vert(f2_corners, corner_verts, v1);
788 const int c2_v2 = bke::mesh::face_find_corner_from_vert(f2_corners, corner_verts, v2);
789
790 if (c1_v1 == -1 || c1_v2 == -1 || c2_v1 == -1 || c2_v2 == -1) {
791 return false;
792 }
793
794 for (const UVLayer &attr : uv_maps) {
795 if (attr.values[c1_v1] != attr.values[c2_v1]) {
796 return false;
797 }
798 if (attr.values[c1_v2] != attr.values[c2_v2]) {
799 return false;
800 }
801 }
802
803 return true;
804}
805
807{
808 if (!has_uv_maps) {
809 return;
810 }
811
812 const Span<float3> positions = emesh.src_positions;
813 const OffsetIndices<int> faces = emesh.src_faces;
814 const Span<int> corner_verts = emesh.src_corner_verts;
815 const Span<int> corner_edges = emesh.src_corner_edges;
816 this->face_component = Array<int>(faces.size(), -1);
817 if (faces.is_empty()) {
818 return;
819 }
820
821 const GroupedSpan<int> edge_faces = emesh.src_edge_to_face;
822
823 Array<bool> in_stack(faces.size(), false);
824 Vector<int> stack;
825 stack.reserve(faces.size());
826
827 int current_component = -1;
828 for (const int f : faces.index_range()) {
829 if (this->face_component[f] == -1 && !in_stack[f]) {
830 current_component++;
831 stack.append(f);
832 in_stack[f] = true;
833
834 while (!stack.is_empty()) {
835 int f_curr = stack.pop_last();
836 in_stack[f_curr] = false;
837
838 if (this->face_component[f_curr] != -1) {
839 continue;
840 }
841 this->face_component[f_curr] = current_component;
842
843 /* Find neighbors via edges. */
844 const Span<int> face_edges = corner_edges.slice(faces[f_curr]);
845 for (const int e_index : face_edges) {
846 const Span<int> adj_faces = edge_faces[e_index];
847 for (const int f_other : adj_faces) {
848 if (f_other != f_curr) {
849 if (face_component[f_other] != -1 || in_stack[f_other]) {
850 continue;
851 }
852 if (contig_uv_maps_across_edge(emesh, e_index, f_curr, f_other)) {
853 stack.append(f_other);
854 in_stack[f_other] = true;
855 }
856 }
857 }
858 }
859 }
860 }
861 }
862
863 /* We can usually get more pleasing result if components 0 and 1
864 * are the topmost and bottom-most (in z-coordinate) components,
865 * so adjust component indices to make that so. */
866 if (current_component <= 0) {
867 /* Only one component, so no need to do this. */
868 return;
869 }
870
871 float top_face_z = -1e30f;
872 int top_face_component = -1;
873 float bot_face_z = 1e30f;
874 int bot_face_component = -1;
875
876 for (const int f : faces.index_range()) {
877 float min_z = 1e30f;
878 float max_z = -1e30f;
879 for (const int corner : faces[f]) {
880 const float fz = positions[corner_verts[corner]].z;
881 min_z = std::min(min_z, fz);
882 max_z = std::max(max_z, fz);
883 }
884 const float fz = (min_z + max_z) * 0.5f;
885
886 if (fz > top_face_z) {
887 top_face_z = fz;
888 top_face_component = this->face_component[f];
889 }
890 if (fz < bot_face_z) {
891 bot_face_z = fz;
892 bot_face_component = this->face_component[f];
893 }
894 }
895
896 auto swap_face_components = [&](int c1, int c2) {
897 if (c1 == c2) {
898 return;
899 }
900 for (int &c : this->face_component) {
901 if (c == c1) {
902 c = c2;
903 }
904 else if (c == c2) {
905 c = c1;
906 }
907 }
908 };
909
910 swap_face_components(this->face_component[0], top_face_component);
911 if (bot_face_component != top_face_component) {
912 if (bot_face_component == 0) {
913 /* It was swapped with old top_face_component. */
914 bot_face_component = top_face_component;
915 }
916 swap_face_components(this->face_component[1], bot_face_component);
917 }
918}
919
920bool UVMapInfo::contig_uv_maps_around_vert(const ExtendableMesh &emesh, const int v) const
921{
922 if (!has_uv_maps) {
923 return true;
924 }
925 /* Gather all corners at v. */
926 const Span<int> corners = emesh.src_vert_to_corner[v];
927 if (corners.size() < 2) {
928 return true;
929 }
930 const int c_first = corners[0];
931 for (const UVLayer &attr : uv_maps) {
932 const float2 &uv_ref = attr.values[c_first];
933 for (const int c : corners.drop_front(1)) {
934 if (attr.values[c] != uv_ref) {
935 return false;
936 }
937 }
938 }
939 return true;
940}
941
942} // namespace uv
943
945 /* Input parameters. */
947
948 /* Input selection. */
950
951 /* Bevel affected vertices mask and its memory. */
956
957 /* The encapsulated extendable mesh. */
959
960 /* Memory Ownership. */
963
965
969
970 /* Additional State mimicking bmesh_bevel that isn't fully contained in BevelParameters. */
973
974 /* Fast-path miter flags: true when all corners have the same miter setting.
975 * These avoid per-corner lookups in the common cases. */
978
979 /* Feature flags and parameters that the node version might use or we keep to mimic bmesh_bevel.
980 */
984
990
992
994 float3 face_center(const int f) const;
996 void uv_init();
997};
998
1001{
1003 this->bevel_affected_vertices = selection;
1004 }
1005 else {
1006 /* Mirror the BMesh operator's manifold filter (see #bmo_bevel_exec): only edges with
1007 * exactly two incident faces can be beveled. Boundary edges (one face) and wire edges
1008 * (zero faces) are silently excluded, matching the behavior of the bevel operator. */
1009 const GroupedSpan<int> edge_faces = emesh.src_edge_to_face;
1010 this->selection = IndexMask::from_predicate(
1011 selection, memory, [&](const int i) { return edge_faces[i].size() == 2; });
1012
1013 const Span<int2> src_edges = mesh.edges();
1014 this->bevel_affected_vertices = vert_selection_from_edge(
1015 src_edges, this->selection, mesh.verts_num, memory);
1016 }
1017
1018 /* Calculate affected faces and their centers. */
1019 Array<bool> is_vert_affected(mesh.verts_num, false);
1020 this->bevel_affected_vertices.to_bools(is_vert_affected.as_mutable_span());
1021
1022 const Span<int> corner_verts = mesh.corner_verts();
1023 const OffsetIndices faces = mesh.faces();
1024 this->bevel_affected_faces = IndexMask::from_predicate(
1025 faces.index_range(), memory, [&](const int i) {
1026 return std::ranges::any_of(corner_verts.slice(faces[i]),
1027 [&](const int v) { return is_vert_affected[v]; });
1028 });
1029
1030 this->face_centers = Array<float3>(mesh.faces_num, float3(0.0f));
1031 const Span<float3> positions = mesh.vert_positions();
1032 this->bevel_affected_faces.foreach_index(
1033 [&](const int f) {
1034 this->face_centers[f] = bke::mesh::face_center_calc(positions,
1035 corner_verts.slice(faces[f]));
1036 },
1037 exec_mode::grain_size(1024));
1038
1039 this->affect_vertices_odd = false;
1040 this->limit_offset = false;
1041 this->mark_seam = false;
1042 this->mark_sharp = false;
1043 this->vmesh_method = VMeshMethod::Adj;
1044 if (this->vmesh_method == VMeshMethod::Cutoff) {
1045 /* ignoring miters */
1046 this->params.miter.fill(false);
1047 }
1048
1049 /* Precompute fast-path miter flags. */
1051 VArray<bool>::from_span(this->params.miter));
1052 this->all_miters_off = this->params.miter.is_empty() ||
1054 this->all_miters_on = !this->params.miter.is_empty() &&
1056}
1057
1058namespace geom {
1059
1060constexpr float BEVEL_EPSILON_D = 1e-6f;
1061constexpr float BEVEL_EPSILON_SQ = 1e-12f;
1062constexpr float BEVEL_EPSILON_BIG = 1e-4f;
1063constexpr float BEVEL_EPSILON_ANG = DEG2RADF(2.0f);
1064constexpr float BEVEL_SMALL_ANG = DEG2RADF(10.0f);
1065const float BEVEL_SMALL_ANG_DOT = (1.0f - std::cos(BEVEL_SMALL_ANG));
1066const float BEVEL_EPSILON_ANG_DOT = (1.0f - std::cos(BEVEL_EPSILON_ANG));
1067
1068static int edge_other_vert(const ExtendableMesh &emesh, int e, int v)
1069{
1070 int2 verts = emesh.edge_verts(e);
1071 return verts[0] == v ? verts[1] : verts[0];
1072}
1073
1074/* Returns coordinates of a point a distance d from v along edge e. */
1075static float3 slide_dist(const ExtendableMesh &emesh, int e, int v, float d)
1076{
1077 float3 v_co = emesh.vert_position(v);
1078 float3 other_co = emesh.vert_position(geom::edge_other_vert(emesh, e, v));
1079 float len;
1080 const float3 dir = math::normalize_and_get_length(other_co - v_co, len);
1081
1082 if (d > len) {
1083 d = len - 50.0f * BEVEL_EPSILON_D;
1084 }
1085 return v_co + dir * d;
1086}
1087
1088/* Is co not on the edge e? If not, return the closer end of e in ret_closer_v. */
1089static bool is_outside_edge(const ExtendableMesh &emesh,
1090 EdgeHalf *eh,
1091 const float co[3],
1092 int *ret_closer_v)
1093{
1094 // Actually, BMesh's is_outside_edge uses e->v1 and e->v2.
1095 int v1 = emesh.src_edges[eh->e][0];
1096 int v2 = emesh.src_edges[eh->e][1];
1097 float3 l1 = emesh.vert_position(v1);
1098 float3 u_dir = emesh.vert_position(v2) - l1;
1099 float3 h = float3(co[0], co[1], co[2]) - l1;
1100 float lenu = math::length(u_dir);
1101 u_dir /= lenu;
1102 float lambda = math::dot(u_dir, h);
1103 if (lambda <= -BEVEL_EPSILON_BIG * lenu) {
1104 *ret_closer_v = v1;
1105 return true;
1106 }
1107 if (lambda >= (1.0f + BEVEL_EPSILON_BIG) * lenu) {
1108 *ret_closer_v = v2;
1109 return true;
1110 }
1111 return false;
1112}
1113
1114/* co should be approximately on the plane between e1 and e2, which share common vert v and common
1115 * face f (which cannot be -1). Is it between those edges, sweeping CCW? */
1117 const ExtendableMesh &emesh, const float co[3], int v, int f, EdgeHalf *e1, EdgeHalf *e2)
1118{
1119 int v1 = geom::edge_other_vert(emesh, e1->e, v);
1120 int v2 = geom::edge_other_vert(emesh, e2->e, v);
1121 float3 dir1 = emesh.vert_position(v) - emesh.vert_position(v1);
1122 float3 dir2 = emesh.vert_position(v) - emesh.vert_position(v2);
1123 float3 dirco = emesh.vert_position(v) - float3(co[0], co[1], co[2]);
1124 dir1 = math::normalize(dir1);
1125 dir2 = math::normalize(dir2);
1126 dirco = math::normalize(dirco);
1127 float ang11 = float(math::angle_between(dir1, dir2));
1128 float ang1co = float(math::angle_between(dir1, dirco));
1129 float3 no = math::cross(dir1, dir2);
1130 if (math::dot(no, emesh.src_face_normals[f]) < 0.0f) {
1131 ang11 = float(M_PI * 2.0) - ang11;
1132 }
1133 no = math::cross(dir1, dirco);
1134 if (math::dot(no, emesh.src_face_normals[f]) < 0.0f) {
1135 ang1co = float(M_PI * 2.0) - ang1co;
1136 }
1137 return (ang11 - ang1co > -BEVEL_EPSILON_ANG);
1138}
1139
1141 EdgeHalf *e1,
1142 EdgeHalf *e2,
1143 int v,
1144 int f,
1145 bool edges_between,
1146 const EdgeHalf *e_in_plane)
1147{
1148 float3 v_co = emesh.vert_position(v);
1149 /* `dir1` points from e1's far end toward `v`; `dir2` points from `v` away along e2.
1150 * This asymmetry matches the BMesh convention and ensures that `cross(dir1, norm_v1)`
1151 * gives a perpendicular that points into the face (i.e. toward the bevel offset). */
1152 float3 dir1 = v_co - emesh.vert_position(geom::edge_other_vert(emesh, e1->e, v));
1153 float3 dir2 = emesh.vert_position(geom::edge_other_vert(emesh, e2->e, v)) - v_co;
1154
1155 float3 dir1n = float3(0.0f);
1156 float3 dir2p = float3(0.0f);
1157 if (edges_between) {
1158 EdgeHalf *e1next = e1->next;
1159 EdgeHalf *e2prev = e2->prev;
1160 dir1n = emesh.vert_position(geom::edge_other_vert(emesh, e1next->e, v)) - v_co;
1161 dir2p = v_co - emesh.vert_position(geom::edge_other_vert(emesh, e2prev->e, v));
1162 }
1163
1164 float ang = float(math::angle_between(math::normalize(dir1), math::normalize(dir2)));
1165 float3 norm_perp1;
1166 float3 meetco;
1167 if (ang < BEVEL_EPSILON_ANG) {
1168 /* Special case: e1 and e2 are parallel; put offset point perp to both, from v.
1169 * Need to find a suitable plane.
1170 * Use the average of the two directions and the offset formula for angle bisector.
1171 * If offsets are different, use the max (so get consistent looking results if the same
1172 * situation arises elsewhere but with opposite roles for e1 and e2). */
1173 float3 norm_v = float3(0.0f);
1174 if (f != -1) {
1175 norm_v = emesh.src_face_normals[f];
1176 }
1177 else {
1178 int fcount = 0;
1179 for (EdgeHalf *eloop = e1; eloop != e2; eloop = eloop->next) {
1180 if (eloop->fnext != -1) {
1181 norm_v += emesh.src_face_normals[eloop->fnext];
1182 fcount++;
1183 }
1184 }
1185 if (fcount == 0) {
1186 norm_v = emesh.src_vert_normals[v];
1187 }
1188 else {
1189 norm_v /= float(fcount);
1190 }
1191 }
1192 float3 dir_sum = dir1 + dir2;
1193 norm_perp1 = math::normalize(math::cross(dir_sum, norm_v));
1194 float d = math::max(e1->offset_r, e2->offset_l);
1195 d = d / math::cos(ang / 2.0f);
1196 meetco = v_co + norm_perp1 * d;
1197 }
1198 else if (math::abs(ang - float(M_PI)) < BEVEL_EPSILON_ANG) {
1199 /* Special case: e1 and e2 are anti-parallel, so bevel is into a zero-area face.
1200 * Just make the offset point on the common line, at offset distance from v. */
1201 float d = math::max(e1->offset_r, e2->offset_l);
1202 meetco = slide_dist(emesh, e2->e, v, d);
1203 }
1204 else {
1205 /* Get normal to plane where meet point should be, using cross product instead of the face
1206 * normal in case f is non-planar.
1207 * Except: sometimes locally there can be a small angle between dir1 and dir2 that leads
1208 * to a normal almost perpendicular to the face normal; in this case it looks wrong to use
1209 * the local (cross-product) normal, so use the face normal if the angle is small.
1210 * If e1-v-e2 is a reflex angle (viewed from vertex normal side), need to flip.
1211 * Use the face normal to figure out which side to look at angle from. */
1212 float3 norm_v1, norm_v2;
1213 if (f != -1 && ang < BEVEL_SMALL_ANG) {
1214 norm_v1 = norm_v2 = emesh.src_face_normals[f];
1215 }
1216 else if (!edges_between) {
1217 /* Get normal as cross product of the two edge directions. */
1218 norm_v1 = math::normalize(math::cross(dir2, dir1));
1219 if (math::dot(norm_v1, f != -1 ? emesh.src_face_normals[f] : emesh.src_vert_normals[v]) <
1220 0.0f)
1221 {
1222 norm_v1 = -norm_v1;
1223 }
1224 norm_v2 = norm_v1;
1225 }
1226 else {
1227 /* Separate faces; get face normals at corners for each edge separately. */
1228 norm_v1 = math::normalize(math::cross(dir1n, dir1));
1229 int f_curr = e1->fnext;
1230 if (math::dot(norm_v1,
1231 f_curr != -1 ? emesh.src_face_normals[f_curr] : emesh.src_vert_normals[v]) <
1232 0.0f)
1233 {
1234 norm_v1 = -norm_v1;
1235 }
1236 norm_v2 = math::normalize(math::cross(dir2, dir2p));
1237 f_curr = e2->fprev;
1238 if (math::dot(norm_v2,
1239 f_curr != -1 ? emesh.src_face_normals[f_curr] : emesh.src_vert_normals[v]) <
1240 0.0f)
1241 {
1242 norm_v2 = -norm_v2;
1243 }
1244 }
1245
1246 /* Get vectors perp to each edge, perp to norm_v, pointing into face. */
1247 float3 norm_perp2;
1248 norm_perp1 = math::normalize(math::cross(dir1, norm_v1));
1249 norm_perp2 = math::normalize(math::cross(dir2, norm_v2));
1250
1251 float3 off1a = v_co + norm_perp1 * e1->offset_r;
1252 float3 off1b = off1a + dir1;
1253 float3 off2a = v_co + norm_perp2 * e2->offset_l;
1254 float3 off2b = off2a + dir2;
1255
1256 float3 isect2;
1257 /* Intersect the offset lines. */
1258 int isect_kind = math::isect_line_line(off1a, off1b, off2a, off2b, meetco, isect2);
1259 if (isect_kind == 0) {
1260 /* Lines are collinear: we already tested for this, but with a different epsilon. */
1261 meetco = off1a;
1262 }
1263 else {
1264 /* The lines intersect, but check that the intersection is at a reasonable place.
1265 * One problem: if one of the offsets is 0, don't want an intersection outside that
1266 * edge itself. This can happen if the angle between them is > 180 degrees, or if
1267 * the offset amount is > the edge length. */
1268 int closer_v;
1269 if (e1->offset_r == 0.0f && is_outside_edge(emesh, e1, meetco, &closer_v)) {
1270 meetco = emesh.vert_position(closer_v);
1271 }
1272 if (e2->offset_l == 0.0f && is_outside_edge(emesh, e2, meetco, &closer_v)) {
1273 meetco = emesh.vert_position(closer_v);
1274 }
1275 if (edges_between && e1->offset_r > 0.0f && e2->offset_l > 0.0f) {
1276 /* Try to drop meetco to a face between e1 and e2. */
1277 if (isect_kind == 2) {
1278 /* Lines didn't meet in 3D: get average of meetco and isect2. */
1279 meetco = math::midpoint(meetco, isect2);
1280 }
1281 for (EdgeHalf *e_loop = e1; e_loop != e2; e_loop = e_loop->next) {
1282 int fnext = e_loop->fnext;
1283 if (fnext == -1) {
1284 continue;
1285 }
1286 float3 no = emesh.src_face_normals[fnext];
1287 float4 plane = math::plane_from_point_normal(v_co, no);
1288 float3 dropco = math::closest_to_plane_normalized(plane, meetco);
1289 /* Don't drop to faces next to the in-plane edge. */
1290 if (e_in_plane) {
1291 float ang = float(math::angle_between(no, emesh.src_face_normals[e_in_plane->fnext]));
1292 if ((math::abs(ang) < BEVEL_SMALL_ANG) ||
1293 (math::abs(ang - float(M_PI)) < BEVEL_SMALL_ANG))
1294 {
1295 continue;
1296 }
1297 }
1298 if (point_between_edges(emesh, dropco, v, fnext, e_loop, e_loop->next)) {
1299 meetco = dropco;
1300 break;
1301 }
1302 }
1303 }
1304 }
1305 }
1306 return meetco;
1307}
1308
1309/* -------------------------------------------------------------------- */
1312
1318static NewVert *mesh_vert(VMesh *vm, int i, int j, int k)
1319{
1320 const int nk = vm->seg + 1;
1321 const int nj = vm->seg / 2 + 1;
1322 return &vm->mesh[i * nj * nk + j * nk + k];
1323}
1324
1331static NewVert *mesh_vert_canon(VMesh *vm, int i, int j, int k)
1332{
1333 const int n = vm->count;
1334 const int ns = vm->seg;
1335 const int ns2 = ns / 2;
1336 const int odd = ns % 2;
1337 BLI_assert(0 <= i && i <= n && 0 <= j && j <= ns && 0 <= k && k <= ns);
1338
1339 if (!odd && j == ns2 && k == ns2) {
1340 return mesh_vert(vm, 0, j, k);
1341 }
1342 if (j <= ns2 - 1 + odd && k <= ns2) {
1343 return mesh_vert(vm, i, j, k);
1344 }
1345 if (k <= ns2) {
1346 return mesh_vert(vm, (i + n - 1) % n, k, ns - j);
1347 }
1348 return mesh_vert(vm, (i + 1) % n, ns - k, j);
1349}
1350
1351/* Returns true when (i, j, k) is the canonical representative of its equivalence class. */
1352static bool is_canon(const VMesh *vm, int i, int j, int k)
1353{
1354 const int ns2 = vm->seg / 2;
1355 if (vm->seg % 2 == 1) {
1356 return (j <= ns2 && k <= ns2);
1357 }
1358 return ((j < ns2 && k <= ns2) || (j == ns2 && k == ns2 && i == 0));
1359}
1360
1361/* Copies coordinates and vertex indices from canonical grid positions to all equivalent ones. */
1363{
1364 const int n = vm->count;
1365 const int ns = vm->seg;
1366 const int ns2 = ns / 2;
1367 for (int i = 0; i < n; i++) {
1368 for (int j = 0; j <= ns2; j++) {
1369 for (int k = 0; k <= ns; k++) {
1370 if (is_canon(vm, i, j, k)) {
1371 continue;
1372 }
1373 NewVert *v1 = mesh_vert(vm, i, j, k);
1374 NewVert *v0 = mesh_vert_canon(vm, i, j, k);
1375 v1->co = v0->co;
1376 v1->v = v0->v;
1377 }
1378 }
1379 }
1380}
1381
1382/* Returns the centroid of the center polygon of vm. */
1384{
1385 const int n = vm->count;
1386 const int ns2 = vm->seg / 2;
1387 if (vm->seg % 2) {
1388 float3 cent(0.0f);
1389 for (int i = 0; i < n; i++) {
1390 cent += mesh_vert(vm, i, ns2, ns2)->co;
1391 }
1392 return cent * (1.0f / float(n));
1393 }
1394 return mesh_vert(vm, 0, ns2, ns2)->co;
1395}
1396
1397/* Returns the average of four NewVert positions. */
1398static float3 avg4(const NewVert *v0, const NewVert *v1, const NewVert *v2, const NewVert *v3)
1399{
1400 return (v0->co + v1->co + v2->co + v3->co) * 0.25f;
1401}
1402
1404
1405/* -------------------------------------------------------------------- */
1408
1410static bool nearly_parallel(const float3 &d1, const float3 &d2)
1411{
1412 const float ang = float(math::angle_between(math::normalize(d1), math::normalize(d2)));
1413 return (math::abs(ang) < BEVEL_EPSILON_ANG) ||
1414 (math::abs(ang - float(M_PI)) < BEVEL_EPSILON_ANG);
1415}
1416
1421static bool make_unit_square_map(const float3 &va,
1422 const float3 &vmid,
1423 const float3 &vb,
1424 float4x4 &r_mat)
1425{
1426 const float3 va_vmid = vmid - va;
1427 const float3 vb_vmid = vmid - vb;
1428
1429 if (math::is_zero(va_vmid) || math::is_zero(vb_vmid)) {
1430 return false;
1431 }
1432 if (math::abs(float(math::angle_between(math::normalize(va_vmid), math::normalize(vb_vmid))) -
1433 float(M_PI)) <= BEVEL_EPSILON_ANG)
1434 {
1435 return false;
1436 }
1437
1438 const float3 vo = va - vb_vmid;
1439 const float3 vddir = math::normalize(math::cross(vb_vmid, va_vmid));
1440 const float3 vd = vo + vddir;
1441
1442 /* Columns of the 4x4 map matrix (column-major, same layout as legacy float[4][4]). */
1443 r_mat[0] = float4(vmid - va, 0.0f);
1444 r_mat[1] = float4(vmid - vb, 0.0f);
1445 r_mat[2] = float4(vmid + vd - va - vb, 0.0f);
1446 r_mat[3] = float4(va + vb - vmid, 1.0f);
1447
1448 return true;
1449}
1450
1455static float sabin_gamma(int n)
1456{
1457 if (n < 3) {
1458 return 0.0f;
1459 }
1460 if (n == 3) {
1461 return 0.065247584f;
1462 }
1463 if (n == 4) {
1464 return 0.25f;
1465 }
1466 if (n == 5) {
1467 return 0.401983447f;
1468 }
1469 if (n == 6) {
1470 return 0.523423277f;
1471 }
1472 const double k = cos(M_PI / double(n));
1473 const double k2 = k * k;
1474 const double k4 = k2 * k2;
1475 const double k6 = k4 * k2;
1476 const double y = pow(M_SQRT3 * sqrt(64.0 * k6 - 144.0 * k4 + 135.0 * k2 - 27.0) + 9.0 * k,
1477 1.0 / 3.0);
1478 const double x = 0.480749856769136 * y - (0.231120424783545 * (12.0 * k2 - 9.0)) / y;
1479 return float((k * x + 2.0 * k2 - 1.0) / (x * x * (k * x + 1.0)));
1480}
1481
1483
1484} // namespace geom
1485
1486/* -------------------------------------------------------------------- */
1489
1490namespace debug {
1491
1492/* Prints a Span of a printable type, 10 items per line.
1493 * Each line is prefixed with the starting index in brackets.
1494 * A label line is printed before the span. */
1495template<typename T> [[maybe_unused]] static void print_span(Span<T> span, const char *label)
1496{
1497 if (span.size() == 0) {
1498 return;
1499 }
1500 fmt::print("{}:", label);
1501 for (const int i : span.index_range()) {
1502 if (i % 10 == 0) {
1503 fmt::print("\n[{}] ", i);
1504 }
1505 fmt::print("{} ", span[i]);
1506 }
1507 fmt::println("");
1508}
1509
1510/* Prints a single float3 as "(x,y,z)" with no trailing newline. */
1511[[maybe_unused]] static void print_float3(const float3 &v)
1512{
1513 fmt::print("({},{},{})", v[0], v[1], v[2]);
1514}
1515
1516/* Prints a Span<float3>, 10 items per line, preceded by a label. */
1517[[maybe_unused]] static void print_float3_span(Span<float3> span, const char *label)
1518{
1519 if (span.size() == 0) {
1520 return;
1521 }
1522 fmt::print("{}:", label);
1523 for (const int i : span.index_range()) {
1524 if (i % 10 == 0) {
1525 fmt::print("\n[{}] ", i);
1526 }
1527 print_float3(span[i]);
1528 fmt::print(" ");
1529 }
1530 fmt::println("");
1531}
1532
1533/* Prints a single int2 pair as "(a,b)" with no trailing newline. */
1534[[maybe_unused]] static void print_int2(const int2 pair)
1535{
1536 fmt::print("({},{})", pair[0], pair[1]);
1537}
1538
1539/* Prints a Span<int2>, 10 items per line, preceded by a label. */
1540[[maybe_unused]] static void print_int2_span(Span<int2> span, const char *label)
1541{
1542 if (span.size() == 0) {
1543 return;
1544 }
1545 fmt::print("{}:", label);
1546 for (const int i : span.index_range()) {
1547 if (i % 10 == 0) {
1548 fmt::print("\n[{}] ", i);
1549 }
1550 print_int2(span[i]);
1551 fmt::print(" ");
1552 }
1553 fmt::println("");
1554}
1555
1556/* Prints a single IndexRange as "[first..last]" or "[]" if empty, with no trailing newline. */
1557[[maybe_unused]] static void print_indexrange(const IndexRange &range)
1558{
1559 if (range.size() == 0) {
1560 fmt::print("[]");
1561 }
1562 else {
1563 fmt::print("[{}..{}]", range.first(), range.last());
1564 }
1565}
1566
1567/* Prints a GroupedSpan<int>, one group per line, preceded by a label. */
1568[[maybe_unused]] static void print_groupedspan(const GroupedSpan<int> &groupedspan,
1569 const char *label)
1570{
1571 if (groupedspan.size() == 0) {
1572 return;
1573 }
1574 fmt::println("{}:", label);
1575 for (const int i : groupedspan.index_range()) {
1576 fmt::print("[{}] ", i);
1577 for (int v : groupedspan[i]) {
1578 fmt::print("{} ", v);
1579 }
1580 fmt::println("");
1581 }
1582}
1583
1584/* Returns a human-readable name for a #MeshKind value. */
1585[[maybe_unused]] static const char *mesh_kind_name(MeshKind kind)
1586{
1587 switch (kind) {
1588 case MeshKind::None:
1589 return "NONE";
1590 case MeshKind::Poly:
1591 return "POLY";
1592 case MeshKind::Adj:
1593 return "ADJ";
1594 case MeshKind::TriFan:
1595 return "TRI_FAN";
1596 case MeshKind::Cutoff:
1597 return "CUTOFF";
1598 default:
1599 return "?";
1600 }
1601}
1602
1603/* Prints a single #Profile's key parameters. */
1604[[maybe_unused]] static void dump_profile(const Profile &prof)
1605{
1606 fmt::print(" Profile: super_r={} height={} special_params={}\n",
1607 prof.super_r,
1608 prof.height,
1609 prof.special_params);
1610 fmt::print(" start=");
1611 print_float3(prof.start);
1612 fmt::print(" middle=");
1613 print_float3(prof.middle);
1614 fmt::print(" end=");
1615 print_float3(prof.end);
1616 fmt::println("");
1617 fmt::print(" plane_no=");
1618 print_float3(prof.plane_no);
1619 fmt::print(" plane_co=");
1620 print_float3(prof.plane_co);
1621 fmt::print(" proj_dir=");
1622 print_float3(prof.proj_dir);
1623 fmt::println("");
1624 if (!prof.prof_co.is_empty()) {
1625 print_float3_span(prof.prof_co, " prof_co");
1626 }
1627}
1628
1629/* Prints a single #EdgeHalf's fields. */
1630[[maybe_unused]] static void dump_edge_half(const EdgeHalf &eh, const int index)
1631{
1632 fmt::println(" EdgeHalf[{}]: e={} fprev={} fnext={}", index, eh.e, eh.fprev, eh.fnext);
1633 fmt::println(" offset_l={} offset_r={} offset_l_spec={} offset_r_spec={}",
1634 eh.offset_l,
1635 eh.offset_r,
1636 eh.offset_l_spec,
1637 eh.offset_r_spec);
1638 fmt::println(" is_bev={} is_rev={} is_seam={} visited_rpo={}",
1639 eh.is_bev,
1640 eh.is_rev,
1641 eh.is_seam,
1642 eh.visited_rpo);
1643 fmt::println(" leftv={} rightv={}",
1644 eh.leftv ? eh.leftv->index : -1,
1645 eh.rightv ? eh.rightv->index : -1);
1646}
1647
1648/* Prints a single #BoundVert's fields. */
1649[[maybe_unused]] static void dump_bound_vert(const BoundVert &bndv)
1650{
1651 fmt::print(" BoundVert[{}]: co=", bndv.index);
1652 print_float3(bndv.nv.co);
1653 fmt::println("");
1654 fmt::println(" efirst={} elast={} ebev={}",
1655 bndv.efirst ? bndv.efirst->e : -1,
1656 bndv.elast ? bndv.elast->e : -1,
1657 bndv.ebev ? bndv.ebev->e : -1);
1658 fmt::println(" any_seam={} visited={}", bndv.any_seam, bndv.visited);
1659 fmt::println(" is_arc_start={} is_patch_start={} is_profile_start={}",
1660 bndv.is_arc_start,
1661 bndv.is_patch_start,
1662 bndv.is_profile_start);
1663 fmt::println(" seam_len={} sharp_len={}", bndv.seam_len, bndv.sharp_len);
1664 dump_profile(bndv.profile);
1665}
1666
1667/* Prints a #VMesh and all its #BoundVert chain, plus the full #NewVert grid. */
1668[[maybe_unused]] static void dump_vmesh(const VMesh &vm)
1669{
1670 fmt::println(
1671 " VMesh: count={} seg={} mesh_kind={}", vm.count, vm.seg, mesh_kind_name(vm.mesh_kind));
1672 if (vm.boundstart == nullptr) {
1673 fmt::println(" (no boundverts)");
1674 return;
1675 }
1676 /* Walk the circular linked list of BoundVerts. */
1677 const BoundVert *bndv = vm.boundstart;
1678 do {
1679 dump_bound_vert(*bndv);
1680 bndv = bndv->next;
1681 } while (bndv != vm.boundstart);
1682
1683 /* Print the NewVert grid if it has been allocated. */
1684 if (!vm.mesh.is_empty()) {
1685 const int n = vm.count;
1686 const int ns = vm.seg;
1687 const int ns2 = ns / 2;
1688 /* Non-const pointer needed by mesh_vert (accessor is not const-qualified). */
1689 VMesh *vmp = const_cast<VMesh *>(&vm);
1690 fmt::println(" NewVerts (i, j, k) for 0<=i<{} 0<=j<={} 0<=k<{}:", n, ns2, ns);
1691 for (int i = 0; i < n; i++) {
1692 for (int j = 0; j <= ns2; j++) {
1693 fmt::print(" ({},{}): ", i, j);
1694 for (int k = 0; k < ns; k++) {
1695 const NewVert *nv = geom::mesh_vert(vmp, i, j, k);
1696 fmt::print("({},({:.3f},{:.3f},{:.3f})) ", nv->v, nv->co[0], nv->co[1], nv->co[2]);
1697 }
1698 fmt::println("");
1699 }
1700 }
1701 }
1702}
1703
1704/* Dumps a full #BevVert, including its #EdgeHalf array, wire edges, and #VMesh. */
1705[[maybe_unused]] static void dump_bev_vert(const BevVert &bv)
1706{
1707 fmt::println("BevVert: v={} edgecount={} selcount={} wirecount={}",
1708 bv.v,
1709 bv.edgecount,
1710 bv.selcount,
1711 bv.wirecount);
1712 fmt::println(" offset={} any_seam={} visited={}", bv.offset, bv.any_seam, bv.visited);
1713
1714 /* Print the EdgeHalf array. */
1715 fmt::println(" edges ({}):", bv.edges.size());
1716 for (const int i : bv.edges.index_range()) {
1717 dump_edge_half(bv.edges[i], i);
1718 }
1719
1720 /* Print wire edges. */
1721 if (!bv.wire_edges.is_empty()) {
1722 print_span<int>(bv.wire_edges, " wire_edges");
1723 }
1724
1725 /* Print the VMesh if present. */
1726 if (bv.vmesh) {
1727 dump_vmesh(*bv.vmesh);
1728 }
1729 else {
1730 fmt::println(" (no vmesh)");
1731 }
1732}
1733
1745[[maybe_unused]] static void dump_edge_polygons(const BevelState &state, const BevVert &bv)
1746{
1747 const ExtendableMesh &emesh = state.emesh;
1748 VMesh *vm = bv.vmesh.get();
1749 if (!vm) {
1750 return;
1751 }
1752 const int ns = vm->seg;
1753
1754 fmt::println(" Edge polygons for bv={}:", bv.v);
1755
1756 for (int ei = 0; ei < bv.edgecount; ei++) {
1757 const EdgeHalf &eh = bv.edges[ei];
1758 if (!eh.is_bev || !eh.leftv) {
1759 continue;
1760 }
1761 const int i = eh.leftv->index;
1762 fmt::println(" EdgeHalf[{}] e={} i={}:", ei, eh.e, i);
1763
1764 for (int k = 0; k < ns; k++) {
1765 /* The two boundary verts on this endpoint's ring. */
1766 const int va = geom::mesh_vert(vm, i, 0, k)->v;
1767 const int vb = geom::mesh_vert(vm, i, 0, k + 1)->v;
1768 if (va < 0 || vb < 0) {
1769 continue;
1770 }
1771 /* Search new faces for a quad containing va and vb in reverse order (vb before va).
1772 * new_faces_num() gives the count of faces added by face_create. */
1773 bool found = false;
1774 const int first_new_face = emesh.mesh.faces_num;
1775 const int past_new_face = first_new_face + emesh.new_faces_num();
1776
1777 for (int fi = first_new_face; fi < past_new_face && !found; fi++) {
1778 const IndexRange corners = emesh.face_corners(fi);
1779
1780 /* Check if va and vb appear in this face in the order (vb, va). */
1781 const int sz = int(corners.size());
1782 int pos_va = -1, pos_vb = -1;
1783 for (int ci = 0; ci < sz; ci++) {
1784 const int cv = emesh.corner_vert(corners[ci]);
1785 if (cv == va) {
1786 pos_va = ci;
1787 }
1788 if (cv == vb) {
1789 pos_vb = ci;
1790 }
1791 }
1792 if (pos_va >= 0 && pos_vb >= 0 && (pos_vb + 1) % sz == pos_va) {
1793 found = true;
1794 fmt::print(" k={} face={} corners:", k, fi);
1795 for (int ci = 0; ci < sz; ci++) {
1796 const int c = corners[ci];
1797 const int cv = emesh.corner_vert(c);
1798 const int ce = emesh.corner_edge(c);
1799 fmt::print(" [c={} v={} e={}]", c, cv, ce);
1800 }
1801 fmt::println("");
1802 }
1803 }
1804 if (!found) {
1805 fmt::println(" k={} va={} vb={}: no matching face found", k, va, vb);
1806 }
1807 }
1808 }
1809}
1810
1815[[maybe_unused]] static void dump_rebuilt_face(const BevelState &state, const int face_idx)
1816{
1817 const ExtendableMesh &emesh = state.emesh;
1818 const IndexRange corners = emesh.face_corners(face_idx);
1819 fmt::print(" Rebuilt face={} ({} verts):", face_idx, corners.size());
1820 for (const int c : corners) {
1821 const int v = emesh.corner_vert(c);
1822 const int e = emesh.corner_edge(c);
1823 const float3 co = emesh.vert_position(v);
1824 fmt::print(" [v={} e={} co=({:.3f},{:.3f},{:.3f})]", v, e, co[0], co[1], co[2]);
1825 }
1826 fmt::println("");
1827}
1828
1834[[maybe_unused]] static void dump_new_face_examples(const BevelState &state)
1835{
1836 const ExtendableMesh &emesh = state.emesh;
1837 const int n_new = emesh.new_faces_num();
1838 fmt::println("MESH new face examples ({} new faces):", n_new);
1839 const Span<int> exs = emesh.new_face_examples();
1840 const uv::UVMapInfo &uvi = state.uv_layer_info;
1841 for (int i = 0; i < n_new; i++) {
1842 const int face_idx = emesh.mesh.faces_num + i;
1843 const int ex = (i < int(exs.size())) ? exs[i] : -1;
1844 if (ex >= 0 && ex < emesh.mesh.faces_num) {
1845 const int comp = (!uvi.face_component.is_empty()) ? uvi.face_component[ex] : -1;
1846 const float3 cent = state.face_center(ex);
1847 fmt::println(" new_face={} example={} comp={} center=({:.3f},{:.3f},{:.3f})",
1848 face_idx,
1849 ex,
1850 comp,
1851 cent[0],
1852 cent[1],
1853 cent[2]);
1854 }
1855 else {
1856 fmt::println(" new_face={} example={}", face_idx, ex);
1857 }
1858 }
1859}
1860
1866[[maybe_unused]] static void dump_new_edge_examples(const BevelState &state)
1867{
1868 const ExtendableMesh &emesh = state.emesh;
1869 const Span<int2> new_edges = emesh.new_edges();
1870 const int n_new = int(new_edges.size());
1871 fmt::println("MESH new edge examples ({} new edges):", n_new);
1872 const Span<int> exs = emesh.new_edge_examples();
1873 for (int i = 0; i < n_new; i++) {
1874 const int edge_idx = emesh.mesh.edges_num + i;
1875 const int ex = (i < int(exs.size())) ? exs[i] : -1;
1876 fmt::println(
1877 " new_edge={} (v{}--v{}) example={}", edge_idx, new_edges[i][0], new_edges[i][1], ex);
1878 }
1879}
1880
1881} // namespace debug
1882
1884
1885/* Forward declarations for profile:: helpers needed in the first construct:: block. */
1886namespace profile {
1887static void set_profile_params(const BevelState &state, const BevVert *bv, BoundVert *bndv);
1888static void move_profile_plane(BoundVert *bndv, float3 bmvert_co);
1889} // namespace profile
1890
1891namespace construct {
1892
1893/* Forward declarations for miter adjustment functions defined after build_boundary. */
1894static void adjust_miter_coords(const BevelState &state, BevVert *bv, EdgeHalf *emiter);
1895static void adjust_miter_inner_coords(const BevelState &state, BevVert *bv, EdgeHalf *emiter);
1896
1897/* Assume e1 and e2 both share some vert. Do they share a face?
1898 * If they share a face then there is some corner around e1 that is in a face
1899 * where the next or previous edge in the face must be e2. */
1900static bool edges_face_connected_at_vert(const ExtendableMesh &emesh, const int e1, const int e2)
1901{
1902 const GroupedSpan<int> edge_faces = emesh.src_edge_to_face;
1903 const Span<int> e1_faces = edge_faces[e1];
1904 const Span<int> e2_faces = edge_faces[e2];
1905 for (const int f1 : e1_faces) {
1906 if (e2_faces.contains(f1)) {
1907 return true;
1908 }
1909 }
1910 return false;
1911}
1912
1913/* Return 1 if a and b are in CCW order on the normal side of f,
1914 * and -1 if they are reversed, and 0 if there is no shared face f. */
1915static int bev_ccw_test(const ExtendableMesh &emesh, const int a, const int b, const int f)
1916{
1917 if (f == -1) {
1918 return 0;
1919 }
1920 const IndexRange corners = emesh.face_corners(f);
1921 int ca = -1;
1922 int cb = -1;
1923 for (const int c : corners) {
1924 if (emesh.corner_edge(c) == a) {
1925 ca = c - corners.start();
1926 }
1927 if (emesh.corner_edge(c) == b) {
1928 cb = c - corners.start();
1929 }
1930 }
1931 if (ca == -1 || cb == -1) {
1932 return 0;
1933 }
1934 return ((cb + 1) % corners.size() == ca) ? 1 : -1;
1935}
1936
1937/* See if we have usual case for bevel edge order:
1938 * there is an ordering such that all the faces are between
1939 * successive edges and form a manifold "cap" at bv.
1940 * If this is the case, set bv->edges to such an order
1941 * and return true; else unmark any partial path and return false.
1942 * Assume the first edge is already in bv->edges[0].e.
1943 *
1944 * Add edges to bv->edges in order that keeps adjacent edges sharing
1945 * a unique face, if possible. */
1946static bool fast_bevel_edge_order(const ExtendableMesh &emesh, BevVert *bv, bool is_edge_bevel)
1947{
1948 int ntot = bv->edgecount;
1949
1950 EdgeHalf *eh = &bv->edges[0];
1951 int e = eh->e;
1952 if (emesh.src_edge_to_face[e].is_empty()) {
1953 return false;
1954 }
1955
1956 for (int i = 1; i < ntot; i++) {
1957 int num_shared_face = 0;
1958 int first_suc = -1;
1959 for (const int e2 : emesh.src_vert_to_edge[bv->v]) {
1960 bool used = false;
1961 for (int k = 0; k < i; k++) {
1962 if (bv->edges[k].e == e2) {
1963 used = true;
1964 break;
1965 }
1966 }
1967 /* In edge-bevel mode, wire edges are stored separately and excluded from the ring.
1968 * In vertex-bevel mode, wire edges participate in the ring ordering like BMesh does. */
1969 if (used || (is_edge_bevel && bv->wire_edges.as_span().contains(e2))) {
1970 continue;
1971 }
1972
1973 for (const int f : emesh.src_edge_to_face[e2]) {
1974 if (emesh.src_edge_to_face[e].contains(f)) {
1975 num_shared_face++;
1976 if (first_suc == -1) {
1977 first_suc = e2;
1978 }
1979 }
1980 }
1981 if (num_shared_face >= 3) {
1982 break;
1983 }
1984 }
1985 if (num_shared_face == 1 || (i == 1 && num_shared_face == 2)) {
1986 eh = &bv->edges[i];
1987 eh->e = e = first_suc;
1988 }
1989 else {
1990 for (int k = 1; k < i; k++) {
1991 bv->edges[k].e = -1;
1992 }
1993 return false;
1994 }
1995 }
1996 return true;
1997}
1998
1999/* Do a depth first search to try to find a path that orders the rest of the edges
2000 * (after i) around a vertex bv, such that successive edges share a face.
2001 * Also prefer paths where the last edge shares a face with the first edge (bv->edges[0].e),
2002 * but will accept a path that doesn't close if it is the longest one found.
2003 * This is needed to handle cases where there are multiple faces between edges, or "shells"
2004 * of "internal faces" at a vertex -- i.e., faces that bridge between the edges that naturally
2005 * form a manifold cap around bv. It is rare to have more than one of these, so unlikely
2006 * that the exponential time case will be hit in practice.
2007 * Returns the new index i' where bv->edges[i'] ends the best path found.
2008 * The path will be recorded in bv->edges and used edges will be marked.
2009 */
2011 BevVert *bv,
2012 int i,
2013 bool is_edge_bevel)
2014{
2015 Vector<int, 4> sucs;
2016 Vector<int, 16> save_path;
2017
2018 int e = bv->edges[i].e;
2019
2020 for (const int e2 : emesh.src_vert_to_edge[bv->v]) {
2021 bool used = false;
2022 for (int k = 0; k <= i; k++) {
2023 if (bv->edges[k].e == e2) {
2024 used = true;
2025 break;
2026 }
2027 }
2028 /* Exclude wire edges from the face-connected successor search only in edge-bevel mode.
2029 * In vertex-bevel mode they remain in the ring and the face search simply finds nothing. */
2030 if (!used && !(is_edge_bevel && bv->wire_edges.as_span().contains(e2))) {
2031 if (edges_face_connected_at_vert(emesh, e, e2)) {
2032 sucs.append(e2);
2033 }
2034 }
2035 }
2036
2037 const int nsucs = sucs.size();
2038
2039 int bestj = i;
2040 int j = i;
2041 for (int sucindex = 0; sucindex < nsucs; sucindex++) {
2042 int nexte = sucs[sucindex];
2043 bv->edges[j + 1].e = nexte;
2044 int tryj = bevel_edge_order_extend(emesh, bv, j + 1, is_edge_bevel);
2045 if (tryj > bestj ||
2046 (tryj == bestj && edges_face_connected_at_vert(emesh, bv->edges[tryj].e, bv->edges[0].e)))
2047 {
2048 bestj = tryj;
2049 save_path.clear();
2050 for (int k = j + 1; k <= bestj; k++) {
2051 save_path.append(bv->edges[k].e);
2052 }
2053 }
2054 for (int k = j + 1; k <= tryj; k++) {
2055 bv->edges[k].e = -1;
2056 }
2057 }
2058
2059 if (bestj > j) {
2060 for (int k = j + 1; k <= bestj; k++) {
2061 bv->edges[k].e = save_path[k - (j + 1)];
2062 }
2063 }
2064 return bestj;
2065}
2066
2067/* Fill in bv->edges with a good ordering of non-wire edges around bv->v.
2068 * Use only edges where wire_edges is not set (if edge beveling, others are wire).
2069 * first_e is a good edge to start with. */
2071{
2072 auto new_bv = std::make_unique<BoundVert>();
2073 BoundVert *v = new_bv.get();
2074 bv->owned_bound_verts.append(std::move(new_bv));
2075 v->nv.co = co;
2076 if (!bv->vmesh) {
2077 bv->vmesh = std::make_unique<VMesh>();
2078 }
2079 VMesh *vm = bv->vmesh.get();
2080 if (vm->boundstart == nullptr) {
2081 vm->boundstart = v;
2082 v->next = v->prev = v;
2083 }
2084 else {
2085 v->prev = vm->boundstart->prev;
2086 v->next = vm->boundstart;
2087 v->prev->next = v;
2088 vm->boundstart->prev = v;
2089 }
2090 v->index = vm->count++;
2091 /* `profile.super_r` of 1.0 is the PRO_LINE_R (straight-line profile) value. */
2092 v->profile.super_r = 1.0f;
2093 return v;
2094}
2095
2096static void adjust_bound_vert(BoundVert *bndv, const float3 &co)
2097{
2098 bndv->nv.co = co;
2099}
2100
2101/* If a beveled edge has a seam (check_seam == true) or a sharp (check_sharp == true),
2102 * then we may need to correct for discontinuities in those edge flags after beveling.
2103 * The code will automatically make the outer edges of a multi-segment beveled edge have
2104 * the same flags. So beveled edges next to each other will not lead to discontinuities.
2105 * But if there are beveled edges that do NOT have a seam (or sharp), then we need to mark
2106 * all the edge segments of such beveled edges with seam (or sharp) until we hit the next
2107 * beveled edge that has such a mark. This routine sets, for each rightv of a beveled edge
2108 * that has seam (or sharp), how many edges follow without the corresponding property.
2109 * The count is put in the seam_len field for seams and the sharp_len field for sharps.
2110 *
2111 * TODO: This approach doesn't work for terminal edges or miters. */
2113 BevVert *bv,
2114 bool check_seam,
2115 bool check_sharp)
2116{
2117 /* Read the uv_seam and sharp_edge edge attributes from the original mesh. */
2118 const bke::AttributeAccessor attrs = state.emesh.mesh.attributes();
2119 VArraySpan<bool> uv_seam_attr;
2120 VArraySpan<bool> sharp_edge_attr;
2121 {
2122 bke::AttributeReader<bool> seam_reader = attrs.lookup<bool>("uv_seam", bke::AttrDomain::Edge);
2123 if (seam_reader) {
2124 uv_seam_attr = VArraySpan<bool>(seam_reader.varray);
2125 }
2126 bke::AttributeReader<bool> sharp_reader = attrs.lookup<bool>("sharp_edge",
2128 if (sharp_reader) {
2129 sharp_edge_attr = VArraySpan<bool>(sharp_reader.varray);
2130 }
2131 }
2132
2133 /* Returns true when the edge half lacks the flag being checked.
2134 * For seams: the original mesh edge has no `uv_seam` attribute or the attribute is false.
2135 * For sharps: the original mesh edge has no `sharp_edge` attribute or the attribute is false. */
2136 auto hasnot = [&](const EdgeHalf *e) -> bool {
2137 if (check_seam) {
2138 if (uv_seam_attr.is_empty() || e->e < 0 || e->e >= int(uv_seam_attr.size())) {
2139 return true; /* No uv_seam attribute -> no seams. */
2140 }
2141 return !uv_seam_attr[e->e];
2142 }
2143 if (check_sharp) {
2144 if (sharp_edge_attr.is_empty() || e->e < 0 || e->e >= int(sharp_edge_attr.size())) {
2145 return true; /* No sharp_edge attribute -> no sharps. */
2146 }
2147 return !sharp_edge_attr[e->e];
2148 }
2149 return true;
2150 };
2151
2152 EdgeHalf *e = &bv->edges[0];
2153 EdgeHalf *efirst = &bv->edges[0];
2154
2155 /* Get to first edge with the seam or sharp property. */
2156 while (hasnot(e)) {
2157 e = e->next;
2158 if (e == efirst) {
2159 break;
2160 }
2161 }
2162
2163 /* If no such edge found, return. */
2164 if (hasnot(e)) {
2165 return;
2166 }
2167
2168 /* Set efirst to this first encountered edge. */
2169 efirst = e;
2170
2171 do {
2172 int flag_count = 0;
2173 EdgeHalf *ne = e->next;
2174
2175 while (hasnot(ne) && ne != efirst) {
2176 if (ne->is_bev) {
2177 flag_count++;
2178 }
2179 ne = ne->next;
2180 }
2181 if (ne == e || (ne == efirst && hasnot(efirst))) {
2182 break;
2183 }
2184 /* Set seam_len / sharp_len of starting edge's rightv. */
2185 if (check_seam) {
2186 e->rightv->seam_len = flag_count;
2187 }
2188 else {
2189 e->rightv->sharp_len = flag_count;
2190 }
2191 e = ne;
2192 } while (e != efirst);
2193}
2194
2195/* Sets the #any_seam property for a #BevVert and all its #BoundVert's. */
2197 BevVert *bv,
2198 bool mark_seam,
2199 bool mark_sharp)
2200{
2201 bv->any_seam = false;
2202 BoundVert *v = bv->vmesh->boundstart;
2203 do {
2204 v->any_seam = false;
2205 for (EdgeHalf *e = v->efirst; e; e = e->next) {
2206 v->any_seam |= e->is_seam;
2207 if (e == v->elast) {
2208 break;
2209 }
2210 }
2211 bv->any_seam |= v->any_seam;
2212 } while ((v = v->next) != bv->vmesh->boundstart);
2213
2214 if (mark_seam) {
2215 check_edge_data_seam_sharp_edges(state, bv, true, false);
2216 }
2217 if (mark_sharp) {
2218 check_edge_data_seam_sharp_edges(state, bv, false, true);
2219 }
2220}
2221
2223 EdgeHalf *e,
2224 const float3 *plane_no,
2225 bool left)
2226{
2227 int v = e->is_rev ? emesh.src_edges[e->e][1] : emesh.src_edges[e->e][0];
2228 float3 v_co = emesh.vert_position(v);
2229 float3 other_co = emesh.vert_position(geom::edge_other_vert(emesh, e->e, v));
2230 float3 dir = math::normalize(other_co - v_co);
2231 float3 no;
2232 if (plane_no) {
2233 no = *plane_no;
2234 }
2235 else {
2236 no = float3(0.0f);
2237 if (math::abs(dir[0]) < math::abs(dir[1])) {
2238 no[0] = 1.0f;
2239 }
2240 else {
2241 no[1] = 1.0f;
2242 }
2243 }
2244
2245 float3 fdir = left ? math::normalize(math::cross(dir, no)) :
2246 math::normalize(math::cross(no, dir));
2247 return v_co + fdir * (left ? e->offset_l : e->offset_r);
2248}
2249
2251{
2252 BLI_assert(state.params.affect_type == BevelAffect::Vertices);
2253
2254 EdgeHalf *efirst = &bv->edges[0];
2255 EdgeHalf *e = efirst;
2256 do {
2257 const float3 co = geom::slide_dist(state.emesh, e->e, bv->v, e->offset_l);
2258 if (construct) {
2259 BoundVert *v = add_new_bound_vert(bv, co);
2260 v->efirst = v->elast = e;
2261 e->leftv = e->rightv = v;
2262 }
2263 else {
2264 adjust_bound_vert(e->leftv, co);
2265 }
2266 } while ((e = e->next) != efirst);
2267
2268 if (construct) {
2269 set_bound_vert_seams(state, bv, state.mark_seam, state.mark_sharp);
2270 /* Also check for UV seams at the vertex itself, matching BMesh's #build_boundary_vertex_only.
2271 * Only needed when the segment count is odd (the "affect_vertices_odd" condition), since
2272 * `uv_layer_info.face_component` is only populated for odd segment counts. */
2273 if (state.params.segments % 2 == 1) {
2274 if (!bv->any_seam && !state.uv_layer_info.contig_uv_maps_around_vert(state.emesh, bv->v)) {
2275 bv->any_seam = true;
2276 }
2277 }
2278 VMesh *vm = bv->vmesh.get();
2279 if (vm->count == 2) {
2281 }
2282 else if (state.params.segments == 1) {
2284 }
2285 else {
2287 }
2288 }
2289}
2290
2292 BevVert *bv,
2293 EdgeHalf *efirst,
2294 const bool construct)
2295{
2296 const ExtendableMesh &emesh = state.emesh;
2297 EdgeHalf *e = efirst;
2298 if (bv->edgecount == 2) {
2299 /* Only 2 edges in, so terminate the edge with an artificial vertex on the unbeveled edge. */
2300 const float3 *no = e->fprev != -1 ?
2301 &emesh.src_face_normals[e->fprev] :
2302 (e->fnext != -1 ? &emesh.src_face_normals[e->fnext] : nullptr);
2303 const float3 co1 = offset_in_plane(emesh, e, no, true);
2304 if (construct) {
2305 BoundVert *bndv = add_new_bound_vert(bv, co1);
2306 bndv->efirst = bndv->elast = bndv->ebev = e;
2307 e->leftv = bndv;
2308 }
2309 else {
2310 adjust_bound_vert(e->leftv, co1);
2311 }
2312 no = e->fnext != -1 ? &emesh.src_face_normals[e->fnext] :
2313 (e->fprev != -1 ? &emesh.src_face_normals[e->fprev] : nullptr);
2314 const float3 co2 = offset_in_plane(emesh, e, no, false);
2315 if (construct) {
2316 BoundVert *bndv = add_new_bound_vert(bv, co2);
2317 bndv->efirst = bndv->elast = e;
2318 e->rightv = bndv;
2319 }
2320 else {
2321 adjust_bound_vert(e->rightv, co2);
2322 }
2323 /* Make artificial extra point along unbeveled edge, and form triangle. */
2324 const float3 co_slide = geom::slide_dist(emesh, e->next->e, bv->v, e->offset_l);
2325 if (construct) {
2326 BoundVert *bndv = add_new_bound_vert(bv, co_slide);
2327 bndv->efirst = bndv->elast = e->next;
2328 e->next->leftv = e->next->rightv = bndv;
2329 set_bound_vert_seams(state, bv, state.mark_seam, state.mark_sharp);
2330 }
2331 else {
2332 adjust_bound_vert(e->next->leftv, co_slide);
2333 }
2334 }
2335 else {
2336 /* More than 2 edges in. Put on-edge verts on all the other edges and join with the beveled
2337 * edge to make a poly or adj mesh, because e->prev has offset 0 and offset_meet will put
2338 * co on that edge. */
2339 const float3 co1 = geom::offset_meet(emesh, e->prev, e, bv->v, e->fprev, false, nullptr);
2340 if (construct) {
2341 BoundVert *bndv = add_new_bound_vert(bv, co1);
2342 bndv->efirst = e->prev;
2343 bndv->elast = bndv->ebev = e;
2344 e->leftv = bndv;
2345 e->prev->leftv = e->prev->rightv = bndv;
2346 }
2347 else {
2348 adjust_bound_vert(e->leftv, co1);
2349 }
2350 e = e->next;
2351 const float3 co2 = geom::offset_meet(emesh, e->prev, e, bv->v, e->fprev, false, nullptr);
2352 if (construct) {
2353 BoundVert *bndv = add_new_bound_vert(bv, co2);
2354 bndv->efirst = e->prev;
2355 bndv->elast = e;
2356 e->leftv = e->rightv = bndv;
2357 e->prev->rightv = bndv;
2358 }
2359 else {
2360 adjust_bound_vert(e->leftv, co2);
2361 }
2362 float d = efirst->offset_l_spec;
2363 if (!state.params.custom_profile_samples.is_empty() || state.params.shape < 0.25f) {
2364 d *= math::sqrt(2.0f);
2365 }
2366 for (e = e->next; e->next != efirst; e = e->next) {
2367 const float3 co = geom::slide_dist(emesh, e->e, bv->v, d);
2368 if (construct) {
2369 BoundVert *bndv = add_new_bound_vert(bv, co);
2370 bndv->efirst = bndv->elast = e;
2371 e->leftv = e->rightv = bndv;
2372 }
2373 else {
2374 adjust_bound_vert(e->leftv, co);
2375 }
2376 }
2377 if (bv->edgecount >= 3) {
2378 /* Special case: snap profile to the plane of the adjacent two edges.
2379 * Mirrors the BMesh #build_boundary_terminal_edge logic (BMesh lines 3441-3447).
2380 * This is intentionally outside the `if (construct)` block so that it also
2381 * runs on adjustment passes, matching BMesh behavior. */
2382 BoundVert *bndv = bv->vmesh->boundstart;
2383 BLI_assert(bndv->ebev != nullptr);
2385 profile::move_profile_plane(bndv, state.emesh.src_positions[bv->v]);
2386 }
2387 if (construct) {
2388 set_bound_vert_seams(state, bv, state.mark_seam, state.mark_sharp);
2389
2390 /* Set the mesh kind for the terminal face, mirroring BMesh's
2391 * #build_boundary_terminal_edge (BMesh lines 3452-3471). */
2392 VMesh *vm = bv->vmesh.get();
2393 if (vm->count == 2 && bv->edgecount == 3) {
2395 }
2396 else if (vm->count == 3) {
2397 /* Use TRI_FAN unless the extra point is coplanar with the profile
2398 * (custom-profile case), in which case POLY avoids overhanging edges. */
2399 bool use_tri_fan = true;
2400 if (!state.params.custom_profile_samples.is_empty()) {
2401 BoundVert *bndv = efirst->leftv;
2403 bndv->profile.plane_no);
2404 /* The extra BoundVert placed along the non-adjacent edge. */
2405 bndv = efirst->rightv->next;
2406 if (math::dist_squared_to_plane(bndv->nv.co, profile_plane) < geom::BEVEL_EPSILON_BIG) {
2407 use_tri_fan = false;
2408 }
2409 }
2410 vm->mesh_kind = use_tri_fan ? MeshKind::TriFan : MeshKind::Poly;
2411 }
2412 else {
2414 }
2415 }
2416 }
2417}
2418
2419/* Return the next EdgeHalf after from_e that is beveled.
2420 * If from_e is nullptr, find the first beveled edge. */
2421static EdgeHalf *next_bev(BevVert *bv, EdgeHalf *from_e)
2422{
2423 if (from_e == nullptr) {
2424 from_e = &bv->edges.last();
2425 }
2426 EdgeHalf *e = from_e;
2427 do {
2428 if (e->is_bev) {
2429 return e;
2430 }
2431 } while ((e = e->next) != from_e);
2432 return nullptr;
2433}
2434
2435/* Returns true when two normalized direction vectors are nearly parallel or anti-parallel.
2436 * Ported from #nearly_parallel_normalized in `bmesh_bevel.cc`. */
2437static bool nearly_parallel_normalized(const float3 &d1, const float3 &d2)
2438{
2439 const float direction_dot = math::dot(d1, d2);
2440 return math::abs(math::abs(direction_dot) - 1.0f) <= geom::BEVEL_EPSILON_ANG_DOT;
2441}
2442
2444
2445/* Return whether the angle swept from e1 to e2 around v is less than, equal to,
2446 * or larger than 180 degrees. */
2447static AngleKind edges_angle_kind(const ExtendableMesh &emesh, EdgeHalf *e1, EdgeHalf *e2, int v)
2448{
2449 int v1 = geom::edge_other_vert(emesh, e1->e, v);
2450 int v2 = geom::edge_other_vert(emesh, e2->e, v);
2451 float3 dir1 = emesh.vert_position(v) - emesh.vert_position(v1);
2452 float3 dir2 = emesh.vert_position(v) - emesh.vert_position(v2);
2453 dir1 = math::normalize(dir1);
2454 dir2 = math::normalize(dir2);
2455
2456 /* First check for in-line edges using a simpler test. */
2457 if (nearly_parallel_normalized(dir1, dir2)) {
2458 return ANGLE_STRAIGHT;
2459 }
2460
2461 /* Angles are in [0, pi]. Need to compare cross product with normal to see if reflex. */
2462 float3 cross = math::normalize(math::cross(dir1, dir2));
2463 float3 no;
2464 if (e1->fnext != -1) {
2465 no = emesh.src_face_normals[e1->fnext];
2466 }
2467 else if (e2->fprev != -1) {
2468 no = emesh.src_face_normals[e2->fprev];
2469 }
2470 else {
2471 no = emesh.src_vert_normals[v];
2472 }
2473
2474 if (math::dot(cross, no) < 0.0f) {
2475 return ANGLE_LARGER;
2476 }
2477 return ANGLE_SMALLER;
2478}
2479
2480/* Returns true when a miter is requested at edge `e`'s outgoing corner at vertex `v`.
2481 * The relevant corner is the one in `e->fnext` (the face to the right of `e` when
2482 * traversing outward from the bevel vertex) that contains `v`.
2483 * Mirrors the role of #BevelParams::miter_outer / #BevelParams::miter_inner in
2484 * `bmesh_bevel.cc` but using a per-corner bool instead of global mode enums. */
2485static bool edge_has_miter(const BevelState &state, const EdgeHalf *e, int v)
2486{
2487 if (state.all_miters_off) {
2488 return false;
2489 }
2490 if (state.all_miters_on) {
2491 return true;
2492 }
2493 /* Per-corner lookup: find the corner in e->fnext at vertex v. */
2494 if (e->fnext == -1) {
2495 return false;
2496 }
2497 const IndexRange face = state.emesh.src_faces[e->fnext];
2498 const Span<int> face_verts = state.emesh.src_corner_verts.slice(face);
2499 for (const int i : face_verts.index_range()) {
2500 if (face_verts[i] == v) {
2501 const int corner = face.start() + i;
2502 return (corner < int(state.params.miter.size())) && state.params.miter[corner];
2503 }
2504 }
2505 return false;
2506}
2507
2508static void build_boundary(const BevelState &state, BevVert *bv, bool construct)
2509{
2510 const ExtendableMesh &emesh = state.emesh;
2511 if (bv->edgecount <= 1) {
2512 return;
2513 }
2514
2515 if (state.params.affect_type == BevelAffect::Vertices) {
2517 return;
2518 }
2519
2520 VMesh *vm = bv->vmesh.get();
2521
2522 EdgeHalf *efirst = next_bev(bv, nullptr);
2523 BLI_assert(efirst->is_bev);
2524
2525 if (bv->selcount == 1) {
2526 /* Special case: only one beveled edge in. */
2528 return;
2529 }
2530
2531 EdgeHalf *emiter = nullptr;
2532
2533 /* There is more than one beveled edge.
2534 * We make BoundVerts to connect the sides of the beveled edges.
2535 * Non-beveled edges in between will just join to the appropriate juncture point. */
2536 EdgeHalf *e = efirst;
2537 EdgeHalf *e2;
2538 do {
2539 BLI_assert(e->is_bev);
2540 /* Make the BoundVert for the right side of e; the other side will be made when the beveled
2541 * edge to the left of e is handled. */
2542 int between = 0; /* Count of edges between e and the next beveled edge. */
2543 for (e2 = e->next; !e2->is_bev; e2 = e2->next) {
2544 between++;
2545 }
2546
2547 float3 co;
2548 if (between == 0) {
2549 co = geom::offset_meet(emesh, e, e2, bv->v, e->fnext, false, nullptr);
2550 }
2551 else {
2552 co = geom::offset_meet(emesh, e, e2, bv->v, -1, true, nullptr);
2553 }
2554
2555 if (construct) {
2556 BoundVert *v = add_new_bound_vert(bv, co);
2557 v->efirst = e;
2558 v->elast = e2;
2559 v->ebev = e2;
2560 e->rightv = v;
2561 e2->leftv = v;
2562 for (EdgeHalf *e3 = e->next; e3 != e2; e3 = e3->next) {
2563 e3->leftv = e3->rightv = v;
2564 }
2565 AngleKind ang_kind = edges_angle_kind(emesh, e, e2, bv->v);
2566
2567 /* Are we doing special mitering?
2568 * There can only be one outer (reflex) miter; `emiter` is set to its edge.
2569 * Outer corners (ANGLE_LARGER) -> patch miter; inner (ANGLE_SMALLER) -> arc miter.
2570 * No miter is added when #edge_has_miter returns false for this edge. */
2571 const bool want_miter = edge_has_miter(state, e, bv->v);
2572 const bool do_outer_miter = (want_miter && !emiter && ang_kind == ANGLE_LARGER);
2573 const bool do_inner_miter = (want_miter && ang_kind == ANGLE_SMALLER);
2574
2575 if (do_outer_miter || do_inner_miter) {
2576 if (ang_kind == ANGLE_LARGER) {
2577 emiter = e;
2578 }
2579 BoundVert *v1 = v;
2580 v1->ebev = nullptr;
2581 BoundVert *v2 = nullptr;
2582 if (do_outer_miter) {
2583 /* Patch miter: insert extra BoundVert v2 between the two bevel offsets. */
2584 v2 = add_new_bound_vert(bv, co);
2585 }
2586 BoundVert *v3 = add_new_bound_vert(bv, co);
2587 v3->ebev = e2;
2588 v3->efirst = e2;
2589 v3->elast = e2;
2590 e2->leftv = v3;
2591 if (do_outer_miter) {
2592 /* Wire v2 as the middle patch vertex. Mirrors BMesh lines 3699-3717. */
2593 v1->is_patch_start = true;
2594 v2->ebev = nullptr;
2595 v1->elast = e;
2596 if (e->next == e2) {
2597 v2->efirst = nullptr;
2598 v2->elast = nullptr;
2599 }
2600 else {
2601 v2->efirst = e->next;
2602 for (EdgeHalf *e3 = e->next; e3 != e2; e3 = e3->next) {
2603 e3->leftv = e3->rightv = v2;
2604 v2->elast = e3;
2605 }
2606 }
2607 }
2608 else {
2609 /* Arc miter: v1 is the arc start, v3 carries the left bevel. Mirrors BMesh lines
2610 * 3720-3745. */
2611 v1->is_arc_start = true;
2612 v1->profile.middle = co;
2613 if (e->next == e2) {
2614 v1->elast = v1->efirst;
2615 }
2616 else {
2617 int bet2 = between / 2;
2618 bool betodd = (between % 2) == 1;
2619 int i = 0;
2620 /* Put first half of in-between edges at profile index 0, second half at index seg.
2621 * If between is odd, the middle one goes at seg/2. */
2622 for (EdgeHalf *e3 = e->next; e3 != e2; e3 = e3->next) {
2623 v1->elast = e3;
2624 if (i < bet2) {
2625 e3->profile_index = 0;
2626 }
2627 else if (betodd && i == bet2) {
2628 e3->profile_index = state.params.segments / 2;
2629 }
2630 else {
2631 e3->profile_index = state.params.segments;
2632 }
2633 i++;
2634 }
2635 }
2636 }
2637 }
2638 }
2639 else {
2640 AngleKind ang_kind = edges_angle_kind(emesh, e, e2, bv->v);
2641 const bool want_miter = edge_has_miter(state, e, bv->v);
2642 const bool do_outer_miter = (want_miter && !emiter && ang_kind == ANGLE_LARGER);
2643 const bool do_inner_miter = (want_miter && ang_kind == ANGLE_SMALLER);
2644 if (do_outer_miter || do_inner_miter) {
2645 if (ang_kind == ANGLE_LARGER) {
2646 emiter = e;
2647 }
2648 BoundVert *v1 = e->rightv;
2649 BoundVert *v2 = nullptr;
2650 BoundVert *v3;
2651 if (do_outer_miter) {
2652 v2 = v1->next;
2653 v3 = v2->next;
2654 }
2655 else {
2656 v3 = v1->next;
2657 }
2658 adjust_bound_vert(v1, co);
2659 if (v2) {
2660 adjust_bound_vert(v2, co);
2661 }
2662 adjust_bound_vert(v3, co);
2663 }
2664 else {
2665 adjust_bound_vert(e->rightv, co);
2666 }
2667 }
2668 } while ((e = e2) != efirst);
2669
2670 /* Adjust miter BoundVert positions now that the full ring of BoundVerts is known.
2671 * Mirrors #adjust_miter_inner_coords and #adjust_miter_coords in `bmesh_bevel.cc`. */
2672 if (!state.all_miters_off) {
2673 adjust_miter_inner_coords(state, bv, emiter);
2674 }
2675 if (emiter) {
2676 adjust_miter_coords(state, bv, emiter);
2677 }
2678
2679 if (construct) {
2680 set_bound_vert_seams(state, bv, state.mark_seam, state.mark_sharp);
2681
2682 if (vm->count == 2) {
2684 }
2685 else if (efirst->seg == 1) {
2687 }
2688 else {
2689 switch (state.vmesh_method) {
2690 case VMeshMethod::Adj:
2692 break;
2695 break;
2696 }
2697 }
2698 }
2699}
2700
2701/* Adjusts the positions of the outer (patch) miter BoundVerts v1 and v3 so they lie on
2702 * the planes through the adjacent BoundVerts. Ported from #adjust_miter_coords in
2703 * `bmesh_bevel.cc`. */
2704static void adjust_miter_coords(const BevelState &state, BevVert *bv, EdgeHalf *emiter)
2705{
2706 BoundVert *v1 = emiter->rightv;
2707 BoundVert *v3;
2708 if (v1->is_patch_start) {
2709 /* Patch miter: v2 is between v1 and v3. */
2710 v3 = v1->next->next;
2711 }
2712 else {
2713 /* Arc miter: no v2. */
2714 v3 = v1->next;
2715 }
2716 BoundVert *v1prev = v1->prev;
2717 BoundVert *v3next = v3->next;
2718
2719 float3 co2 = v1->nv.co;
2720 if (v1->is_arc_start) {
2721 v1->profile.middle = co2;
2722 }
2723
2724 /* Fallback slide distance: offset divided by half-segment-count.
2725 * Matches BMesh's `d = bp->offset / (bp->seg / 2.0f)`. */
2726 const float d = emiter->offset_l / (float(state.params.segments) / 2.0f);
2727
2728 /* co1: intersection of the line through co2 in the direction of emiter->e
2729 * with the plane whose normal is that direction and which passes through v1prev. */
2730 int vother = geom::edge_other_vert(state.emesh, emiter->e, bv->v);
2731 float3 edge_dir = math::normalize(state.emesh.src_positions[bv->v] -
2732 state.emesh.src_positions[vother]);
2733 float3 line_p = co2 + d * edge_dir;
2734 float3 co1 = math::isect_line_plane(co2, line_p, v1prev->nv.co, edge_dir).value_or(line_p);
2735 adjust_bound_vert(v1, co1);
2736
2737 /* co3: same idea but using the other side of the miter (edge of v3). */
2738 EdgeHalf *emiter_other = v3->elast;
2739 vother = geom::edge_other_vert(state.emesh, emiter_other->e, bv->v);
2740 edge_dir = math::normalize(state.emesh.src_positions[bv->v] - state.emesh.src_positions[vother]);
2741 line_p = co2 + d * edge_dir;
2742 float3 co3 = math::isect_line_plane(co2, line_p, v3next->nv.co, edge_dir).value_or(line_p);
2743 adjust_bound_vert(v3, co3);
2744}
2745
2746/* Adjusts the positions of inner (arc) miter BoundVerts by spreading them along the edge
2747 * directions according to the per-corner spread value. Ported from
2748 * #adjust_miter_inner_coords in `bmesh_bevel.cc`. */
2750{
2751 BoundVert *vstart = bv->vmesh->boundstart;
2752 BoundVert *v = vstart;
2753 do {
2754 if (v->is_arc_start) {
2755 BoundVert *v3 = v->next;
2756 EdgeHalf *e = v->efirst;
2757 if (e != emiter) {
2758 float3 co = v->nv.co;
2759
2760 /* Spread: use per-corner value from params if available; fall back to 0. */
2761 int corner = -1;
2762 if (e->fnext != -1) {
2763 const IndexRange face = state.emesh.src_faces[e->fnext];
2764 const Span<int> face_verts = state.emesh.src_corner_verts.slice(face);
2765 for (const int i : face_verts.index_range()) {
2766 if (face_verts[i] == bv->v) {
2767 corner = face.start() + i;
2768 break;
2769 }
2770 }
2771 }
2772 const float spread = (corner >= 0 && corner < int(state.params.spread.size())) ?
2773 state.params.spread[corner] :
2774 0.0f;
2775
2776 int vother = geom::edge_other_vert(state.emesh, e->e, bv->v);
2777 float3 edge_dir = math::normalize(state.emesh.src_positions[vother] -
2778 state.emesh.src_positions[bv->v]);
2779 v->nv.co = co + edge_dir * spread;
2780
2781 e = v3->elast;
2782 vother = geom::edge_other_vert(state.emesh, e->e, bv->v);
2783 edge_dir = math::normalize(state.emesh.src_positions[vother] -
2784 state.emesh.src_positions[bv->v]);
2785 v3->nv.co = co + edge_dir * spread;
2786 }
2787 v = v3->next;
2788 }
2789 else {
2790 v = v->next;
2791 }
2792 } while (v != vstart);
2793}
2794
2795static void find_bevel_edge_order(const ExtendableMesh &emesh,
2796 BevVert *bv,
2797 int first_e,
2798 bool is_edge_bevel)
2799{
2800 int ntot = bv->edgecount;
2801 for (int i = 0;;) {
2802 bv->edges[i].e = first_e;
2803 if (i == 0 && fast_bevel_edge_order(emesh, bv, is_edge_bevel)) {
2804 break;
2805 }
2806 i = bevel_edge_order_extend(emesh, bv, i, is_edge_bevel);
2807 i++;
2808 if (i >= bv->edgecount) {
2809 break;
2810 }
2811 first_e = -1;
2812 for (const int e : emesh.src_vert_to_edge[bv->v]) {
2813 bool used = false;
2814 for (int k = 0; k < i; k++) {
2815 if (bv->edges[k].e == e) {
2816 used = true;
2817 break;
2818 }
2819 }
2820 /* In edge-bevel mode, skip wire edges (they are in wire_edges, not the ring).
2821 * In vertex-bevel mode, all edges including wires participate in the ring. */
2822 if (used || (is_edge_bevel && bv->wire_edges.as_span().contains(e))) {
2823 continue;
2824 }
2825 if (first_e == -1) {
2826 first_e = e;
2827 }
2828 if (emesh.src_edge_to_face[e].size() == 1) {
2829 first_e = e;
2830 break;
2831 }
2832 }
2833 }
2834 for (int i = 0; i < ntot; i++) {
2835 EdgeHalf *eh = &bv->edges[i];
2836 EdgeHalf *eh2 = (i == bv->edgecount - 1) ? &bv->edges[0] : &bv->edges[i + 1];
2837 int e = eh->e;
2838 int e2 = eh2->e;
2839 if (eh->fnext != -1 || eh2->fprev != -1) {
2840 continue;
2841 }
2842 int bestf = -1;
2843 bool bestf_is_directional = false;
2844 for (const int f : emesh.src_edge_to_face[e]) {
2845 if (!emesh.src_edge_to_face[e2].contains(f)) {
2846 continue;
2847 }
2848 const IndexRange corners = emesh.face_corners(f);
2849 for (const int c : corners) {
2850 if (emesh.corner_vert(c) != bv->v) {
2851 continue;
2852 }
2853 /* Mirror BMesh's `l->v == bv->v` preference: prefer the face where the corner
2854 * at bv->v has its outgoing edge equal to e (the "fnext" direction).
2855 * Without this, for 2-edge vertices where both edges share both adjacent faces,
2856 * both loop iterations may select the same face, causing wrong BoundVert positions. */
2857 if (emesh.corner_edge(c) == e) {
2858 /* Directionally correct face: always prefer this and stop searching. */
2859 bestf = f;
2860 bestf_is_directional = true;
2861 break;
2862 }
2863 if (bestf == -1) {
2864 /* Fall back: accept any face containing bv->v if no directional match yet. */
2865 bestf = f;
2866 }
2867 }
2868 if (bestf_is_directional) {
2869 break;
2870 }
2871 }
2872 if (bestf != -1) {
2873 eh->fnext = eh2->fprev = bestf;
2874 }
2875 }
2876}
2877
2878/* -------------------------------------------------------------------- */
2884
2885/* Forward declaration (defined in the second construct block). */
2886static EdgeHalf *find_edge_half_for_edge(BevVert *bv, int edge_index);
2887
2888/* Given an #EdgeHalf `e`, find the #EdgeHalf at the other end of its edge.
2889 * If the other end has a #BevVert, return that #EdgeHalf (and set `r_bvother`). */
2891 EdgeHalf *e,
2892 BevVert **r_bvother)
2893{
2894 const int2 verts = state.emesh.src_edges[e->e];
2895 int vother = e->is_rev ? verts[0] : verts[1];
2896 BevVert *bvo = state.vert_hash.lookup_default(vother, nullptr);
2897 if (bvo) {
2898 if (r_bvother) {
2899 *r_bvother = bvo;
2900 }
2901 EdgeHalf *eother = find_edge_half_for_edge(bvo, e->e);
2902 BLI_assert(eother != nullptr);
2903 return eother;
2904 }
2905 if (r_bvother) {
2906 *r_bvother = nullptr;
2907 }
2908 return nullptr;
2909}
2910
2924 EdgeHalf *start_edge,
2925 bool toward_bv,
2926 BevVert **r_bv)
2927{
2928 /* Case 1: The next EdgeHalf is the other side of the original edge. */
2929 if (!toward_bv) {
2930 return find_other_end_edge_half(state, start_edge, r_bv);
2931 }
2932
2933 /* Case 2: The next EdgeHalf is across a BevVert from the current EdgeHalf. */
2934 if ((*r_bv)->selcount == 1) {
2935 return nullptr; /* No other edges to go to. */
2936 }
2937
2938 if ((*r_bv)->selcount == 2) {
2939 EdgeHalf *new_edge = start_edge;
2940 do {
2941 new_edge = new_edge->next;
2942 } while (!new_edge->is_bev);
2943 return new_edge;
2944 }
2945
2946 const int2 start_e_verts = state.emesh.src_edges[start_edge->e];
2947 const float3 v1_co = state.emesh.src_positions[start_e_verts[0]];
2948 const float3 v2_co = state.emesh.src_positions[start_e_verts[1]];
2949
2950 float3 dir_start_edge;
2951 if (start_e_verts[0] == (*r_bv)->v) {
2952 dir_start_edge = math::normalize(v1_co - v2_co);
2953 }
2954 else {
2955 dir_start_edge = math::normalize(v2_co - v1_co);
2956 }
2957
2958 EdgeHalf *new_edge = start_edge->next;
2959 float second_best_dot = 0.0f, best_dot = 0.0f;
2960 EdgeHalf *next_edge = nullptr;
2961 while (new_edge != start_edge) {
2962 if (!new_edge->is_bev) {
2963 new_edge = new_edge->next;
2964 continue;
2965 }
2966
2967 const int2 new_e_verts = state.emesh.edge_verts(new_edge->e);
2968 const float3 nv1_co = state.emesh.vert_position(new_e_verts[0]);
2969 const float3 nv2_co = state.emesh.vert_position(new_e_verts[1]);
2970
2971 float3 dir_new_edge;
2972 if (new_e_verts[1] == (*r_bv)->v) {
2973 dir_new_edge = math::normalize(nv1_co - nv2_co);
2974 }
2975 else {
2976 dir_new_edge = math::normalize(nv2_co - nv1_co);
2977 }
2978
2979 float new_dot = math::dot(dir_new_edge, dir_start_edge);
2980 if (new_dot > best_dot) {
2981 second_best_dot = best_dot;
2982 best_dot = new_dot;
2983 next_edge = new_edge;
2984 }
2985 else if (new_dot > second_best_dot) {
2986 second_best_dot = new_dot;
2987 }
2988
2989 new_edge = new_edge->next;
2990 }
2991
2992 if ((next_edge != nullptr) && std::abs(best_dot - second_best_dot) <= geom::BEVEL_SMALL_ANG_DOT)
2993 {
2994 return nullptr;
2995 }
2996 return next_edge;
2997}
2998
3006static void regularize_profile_orientation(const BevelState &state, int edge_index)
3007{
3008 const int2 ev = state.emesh.edge_verts(edge_index);
3009 BevVert *start_bv = state.vert_hash.lookup_default(ev[0], nullptr);
3010 if (!start_bv) {
3011 start_bv = state.vert_hash.lookup_default(ev[1], nullptr);
3012 }
3013 if (!start_bv) {
3014 return;
3015 }
3016 EdgeHalf *start_edgehalf = find_edge_half_for_edge(start_bv, edge_index);
3017 if (!start_edgehalf || !start_edgehalf->is_bev || start_edgehalf->visited_rpo) {
3018 return;
3019 }
3020
3021 /* Pick a BoundVert on one side of the profile to use for the starting side. Use the one highest
3022 * on the Z axis because even any rule is better than an arbitrary decision. */
3023 bool right_highest = start_edgehalf->leftv->nv.co[2] < start_edgehalf->rightv->nv.co[2];
3024 start_edgehalf->leftv->is_profile_start = right_highest;
3025 start_edgehalf->visited_rpo = true;
3026
3027 /* First loop starts in the away from BevVert direction and the second starts toward it. */
3028 for (int i = 0; i < 2; i++) {
3029 EdgeHalf *edgehalf = start_edgehalf;
3030 BevVert *bv = start_bv;
3031 bool toward_bv = (i == 0);
3032 edgehalf = next_edgehalf_bev(state, edgehalf, toward_bv, &bv);
3033
3034 /* Keep traveling until there is no unvisited beveled edgehalf to visit next. */
3035 while (edgehalf && !edgehalf->visited_rpo) {
3036 /* Mark the correct BoundVert as the start of the newly visited profile.
3037 * The direction relative to the BevVert switches every step, so also switch
3038 * the orientation every step. */
3039 if (i == 0) {
3040 edgehalf->leftv->is_profile_start = toward_bv ^ right_highest;
3041 }
3042 else {
3043 /* The opposite side as the first direction because we're moving the other way. */
3044 edgehalf->leftv->is_profile_start = (!toward_bv) ^ right_highest;
3045 }
3046
3047 /* The next jump will in the opposite direction relative to the BevVert. */
3048 toward_bv = !toward_bv;
3049
3050 edgehalf->visited_rpo = true;
3051 edgehalf = next_edgehalf_bev(state, edgehalf, toward_bv, &bv);
3052 }
3053 }
3054}
3055
3057
3058} // namespace construct
3059
3060namespace profile {
3061
3062constexpr float PRO_SQUARE_R = 1e4f;
3063constexpr float PRO_CIRCLE_R = 2.0f;
3064constexpr float PRO_LINE_R = 1.0f;
3065constexpr float PRO_SQUARE_IN_R = 0.0f;
3066
3073static double superellipse_co(double x, float r, bool rbig)
3074{
3075 BLI_assert(r > 0.0f);
3076 double dr = r;
3077 if (rbig) {
3078 return math::pow((1.0 - math::pow(x, dr)), (1.0 / dr));
3079 }
3080 return 1.0 - math::pow((1.0 - math::pow(1.0 - x, dr)), (1.0 / dr));
3081}
3082
3083/* Find xnew > x0 so that distance((x0,y0), (xnew, ynew)) = dtarget.
3084 * False position Illinois method used because the function is somewhat linear
3085 * -> linear interpolation converges fast.
3086 * Assumes that the gradient is always between 1 and -1 for x in [x0, x0+dtarget]. */
3087static double find_superellipse_chord_endpoint(double x0, double dtarget, float r, bool rbig)
3088{
3089 double y0 = superellipse_co(x0, r, rbig);
3090 const double tol = 1e-13;
3091 const int maxiter = 10;
3092
3093 double xmin = x0 + std::numbers::sqrt2 / 2.0 * dtarget;
3094 xmin = std::min(xmin, 1.0);
3095 double xmax = x0 + dtarget;
3096 xmax = std::min(xmax, 1.0);
3097 double ymin = superellipse_co(xmin, r, rbig);
3098 double ymax = superellipse_co(xmax, r, rbig);
3099
3100 double dmaxerr = math::sqrt(math::pow((xmax - x0), 2.0) + math::pow((ymax - y0), 2.0)) - dtarget;
3101 double dminerr = math::sqrt(math::pow((xmin - x0), 2.0) + math::pow((ymin - y0), 2.0)) - dtarget;
3102
3103 double xnew = xmax - dmaxerr * (xmax - xmin) / (dmaxerr - dminerr);
3104 bool lastupdated_upper = true;
3105
3106 for (int iter = 0; iter < maxiter; iter++) {
3107 double ynew = superellipse_co(xnew, r, rbig);
3108 double dnewerr = math::sqrt(math::pow((xnew - x0), 2.0) + math::pow((ynew - y0), 2.0)) -
3109 dtarget;
3110 if (abs(dnewerr) < tol) {
3111 break;
3112 }
3113 if (dnewerr < 0) {
3114 xmin = xnew;
3115 ymin = ynew;
3116 dminerr = dnewerr;
3117 if (!lastupdated_upper) {
3118 xnew = (dmaxerr / 2 * xmin - dminerr * xmax) / (dmaxerr / 2 - dminerr);
3119 }
3120 else {
3121 xnew = xmax - dmaxerr * (xmax - xmin) / (dmaxerr - dminerr);
3122 }
3123 lastupdated_upper = false;
3124 }
3125 else {
3126 xmax = xnew;
3127 ymax = ynew;
3128 dmaxerr = dnewerr;
3129 if (lastupdated_upper) {
3130 xnew = (dmaxerr * xmin - dminerr / 2 * xmax) / (dmaxerr - dminerr / 2);
3131 }
3132 else {
3133 xnew = xmax - dmaxerr * (xmax - xmin) / (dmaxerr - dminerr);
3134 }
3135 lastupdated_upper = true;
3136 }
3137 }
3138 return xnew;
3139}
3140
3151 float r,
3152 MutableSpan<double> xvals,
3153 MutableSpan<double> yvals)
3154{
3155 const int smoothitermax = 10;
3156 const double error_tol = 1e-7;
3157 int imax = (seg + 1) / 2 - 1;
3158
3159 bool seg_odd = seg % 2;
3160
3161 bool rbig;
3162 double mx;
3163 if (r > 1.0f) {
3164 rbig = true;
3165 mx = math::pow(0.5, 1.0 / r);
3166 }
3167 else {
3168 rbig = false;
3169 mx = 1 - math::pow(0.5, 1.0 / r);
3170 }
3171
3172 for (int i = 0; i <= imax; i++) {
3173 xvals[i] = i * mx / seg * 2;
3174 yvals[i] = superellipse_co(xvals[i], r, rbig);
3175 }
3176 yvals[0] = 1;
3177
3178 for (int iter = 0; iter < smoothitermax; iter++) {
3179 double sum = 0.0;
3180 double dmin = 2.0;
3181 double dmax = 0.0;
3182 for (int i = 0; i < imax; i++) {
3183 double d = math::sqrt(math::pow((xvals[i + 1] - xvals[i]), 2.0) +
3184 math::pow((yvals[i + 1] - yvals[i]), 2.0));
3185 sum += d;
3186 dmax = std::max(d, dmax);
3187 dmin = std::min(d, dmin);
3188 }
3189 double davg;
3190 if (seg_odd) {
3191 sum += std::numbers::sqrt2 / 2 * (yvals[imax] - xvals[imax]);
3192 davg = sum / (imax + 0.5);
3193 }
3194 else {
3195 sum += math::sqrt(math::pow((xvals[imax] - mx), 2.0) + math::pow((yvals[imax] - mx), 2.0));
3196 davg = sum / (imax + 1.0);
3197 }
3198 bool precision_reached = true;
3199 if (dmax - davg > error_tol) {
3200 precision_reached = false;
3201 }
3202 if (dmin - davg < error_tol) {
3203 precision_reached = false;
3204 }
3205 if (precision_reached) {
3206 break;
3207 }
3208
3209 for (int i = 1; i <= imax; i++) {
3210 xvals[i] = find_superellipse_chord_endpoint(xvals[i - 1], davg, r, rbig);
3211 yvals[i] = superellipse_co(xvals[i], r, rbig);
3212 }
3213 }
3214
3215 if (!seg_odd) {
3216 xvals[imax + 1] = mx;
3217 yvals[imax + 1] = mx;
3218 }
3219 for (int i = imax + 1; i <= seg; i++) {
3220 yvals[i] = xvals[seg - i];
3221 xvals[i] = yvals[seg - i];
3222 }
3223
3224 if (!rbig) {
3225 for (int i = 0; i <= seg; i++) {
3226 double temp = xvals[i];
3227 xvals[i] = 1.0 - yvals[i];
3228 yvals[i] = 1.0 - temp;
3229 }
3230 }
3231}
3232
3242 float r,
3243 MutableSpan<double> xvals,
3244 MutableSpan<double> yvals)
3245{
3246 bool seg_odd = n % 2;
3247 int n2 = n / 2;
3248
3249 if (r == PRO_LINE_R) {
3250 for (int i = 0; i <= n; i++) {
3251 xvals[i] = double(i) / n;
3252 yvals[i] = 1.0 - double(i) / n;
3253 }
3254 return;
3255 }
3256 if (r == PRO_CIRCLE_R) {
3257 double temp = M_PI_2 / n;
3258 for (int i = 0; i <= n; i++) {
3259 xvals[i] = math::sin(i * temp);
3260 yvals[i] = math::cos(i * temp);
3261 }
3262 return;
3263 }
3264 if (r == PRO_SQUARE_IN_R) {
3265 if (!seg_odd) {
3266 for (int i = 0; i <= n2; i++) {
3267 xvals[i] = 0.0;
3268 yvals[i] = 1.0 - double(i) / n2;
3269 xvals[n - i] = yvals[i];
3270 yvals[n - i] = xvals[i];
3271 }
3272 }
3273 else {
3274 double temp = 1.0 / (n2 + std::numbers::sqrt2 / 2.0);
3275 for (int i = 0; i <= n2; i++) {
3276 xvals[i] = 0.0;
3277 yvals[i] = 1.0 - double(i) * temp;
3278 xvals[n - i] = yvals[i];
3279 yvals[n - i] = xvals[i];
3280 }
3281 }
3282 return;
3283 }
3284 if (r == PRO_SQUARE_R) {
3285 if (!seg_odd) {
3286 for (int i = 0; i <= n2; i++) {
3287 xvals[i] = double(i) / n2;
3288 yvals[i] = 1.0;
3289 xvals[n - i] = yvals[i];
3290 yvals[n - i] = xvals[i];
3291 }
3292 }
3293 else {
3294 double temp = 1.0 / (n2 + std::numbers::sqrt2 / 2.0);
3295 for (int i = 0; i <= n2; i++) {
3296 xvals[i] = double(i) * temp;
3297 yvals[i] = 1.0;
3298 xvals[n - i] = yvals[i];
3299 yvals[n - i] = xvals[i];
3300 }
3301 }
3302 return;
3303 }
3304 find_even_superellipse_chords_general(n, r, xvals, yvals);
3305}
3306
3313{
3314 int nseg = bs->params.segments;
3315 constexpr int circle_fullness_segs = 11;
3316 static const float circle_fullness[circle_fullness_segs] = {
3317 0.0f,
3318 0.559f,
3319 0.642f,
3320 0.551f,
3321 0.646f,
3322 0.624f,
3323 0.646f,
3324 0.619f,
3325 0.647f,
3326 0.639f,
3327 0.647f,
3328 };
3329
3330 float fullness;
3331 if (!bs->params.custom_profile_samples.is_empty()) {
3332 fullness = 0.0f;
3333 for (int i = 0; i < nseg; i++) {
3334 fullness += float(bs->pro_spacing.xvals[i] + bs->pro_spacing.yvals[i]) / (2.0f * nseg);
3335 }
3336 }
3337 else {
3338 if (bs->pro_super_r == PRO_LINE_R) {
3339 fullness = 0.0f;
3340 }
3341 else if (bs->pro_super_r == PRO_CIRCLE_R && nseg > 0 && nseg <= circle_fullness_segs) {
3342 fullness = circle_fullness[nseg - 1];
3343 }
3344 else {
3345 if (nseg % 2 == 0) {
3346 fullness = 2.4506f * bs->params.shape - 0.00000300f * nseg - 0.6266f;
3347 }
3348 else {
3349 fullness = 2.3635f * bs->params.shape + 0.000152f * nseg - 0.6060f;
3350 }
3351 }
3352 }
3353 return fullness;
3354}
3355
3367static void set_profile_spacing(BevelState *bs, ProfileSpacing *pro_spacing, bool custom)
3368{
3369 int segments = bs->params.segments;
3370
3371 if (segments <= 1) {
3372 pro_spacing->seg_2 = 0;
3373 return;
3374 }
3375
3376 int seg_2 = std::max(power_of_2_max_i(bs->params.segments), 4);
3377 bs->pro_spacing.seg_2 = seg_2;
3378
3385 auto fill_from_custom = [&](Array<double> &r_xvals, Array<double> &r_yvals, int n) {
3386 const Span<float2> src = bs->params.custom_profile_samples.as_span();
3387 const int src_n = int(src.size()) - 1; /* Number of source segments. */
3388 r_xvals = Array<double>(n + 1);
3389 r_yvals = Array<double>(n + 1);
3390 for (const int i : IndexRange(n + 1)) {
3391 /* Map output index i in [0, n] -> source parameter t in [0, src_n]. */
3392 const float t = float(i) * float(src_n) / float(n);
3393 const int lo = std::min(int(t), src_n - 1);
3394 const int hi = lo + 1;
3395 const float f = t - float(lo);
3396 const float x = (1.0f - f) * src[lo].x + f * src[hi].x;
3397 const float y = (1.0f - f) * src[lo].y + f * src[hi].y;
3398 /* The GN curve uses (x=position-along-strip, y=profile-height) directly,
3399 * with x going from 0 (strip start) to 1 (strip end). Unlike the legacy
3400 * CurveProfile widget (which stores path[0] at x=1 and path[last] at x=0,
3401 * requiring an x<->y swap), the GN curve's coordinate space already matches
3402 * what calculate_profile_segments expects, so no swap is needed. */
3403 r_xvals[i] = double(x);
3404 r_yvals[i] = double(y);
3405 }
3406 };
3407
3408 /* Sample the seg_2 segments used during vertex mesh subdivision. */
3409 if (seg_2 != segments) {
3410 if (custom) {
3411 fill_from_custom(pro_spacing->xvals_2, pro_spacing->yvals_2, seg_2);
3412 }
3413 else {
3414 pro_spacing->xvals_2 = Array<double>(seg_2 + 1);
3415 pro_spacing->yvals_2 = Array<double>(seg_2 + 1);
3417 seg_2, bs->pro_super_r, pro_spacing->xvals_2, pro_spacing->yvals_2);
3418 }
3419 }
3420
3421 /* Sample the input number of segments. */
3422 if (custom) {
3423 fill_from_custom(pro_spacing->xvals, pro_spacing->yvals, segments);
3424 }
3425 else {
3426 pro_spacing->xvals = Array<double>(segments + 1);
3427 pro_spacing->yvals = Array<double>(segments + 1);
3429 segments, bs->pro_super_r, pro_spacing->xvals, pro_spacing->yvals);
3430 }
3431
3432 if (seg_2 == segments) {
3433 pro_spacing->xvals_2 = pro_spacing->xvals;
3434 pro_spacing->yvals_2 = pro_spacing->yvals;
3435 }
3436}
3437
3438/* -------------------------------------------------------------------- */
3441
3442/* Find the closest point (`projco`) on edge `e_idx` to the line through `co_a` and `co_b`.
3443 * Mirrors BMesh's #project_to_edge. */
3445 int e_idx,
3446 const float3 &co_a,
3447 const float3 &co_b)
3448{
3449 const int2 everts = emesh.edge_verts(e_idx);
3450 float3 projco, otherco;
3451 if (!math::isect_line_line(emesh.vert_position(everts[0]),
3452 emesh.vert_position(everts[1]),
3453 co_a,
3454 co_b,
3455 projco,
3456 otherco))
3457 {
3458 return emesh.vert_position(everts[0]);
3459 }
3460 return projco;
3461}
3462
3467static void set_profile_params(const BevelState &state, const BevVert *bv, BoundVert *bndv)
3468{
3469 bool do_linear_interp = true;
3470 const EdgeHalf *e = bndv->ebev;
3471 Profile &pro = bndv->profile;
3472 const ExtendableMesh &emesh = state.emesh;
3473
3474 const float3 start = bndv->nv.co;
3475 const float3 end = bndv->next->nv.co;
3476
3477 if (e) {
3478 do_linear_interp = false;
3479 pro.super_r = state.pro_super_r;
3480 /* Projection direction is along the beveled edge. */
3481 const int2 everts = emesh.src_edges[e->e];
3482 pro.proj_dir = emesh.vert_position(everts[0]) - emesh.vert_position(everts[1]);
3483 if (e->is_rev) {
3484 pro.proj_dir = -pro.proj_dir;
3485 }
3487
3488 /* Middle = closest point on the edge line to the segment start-end. */
3489 pro.middle = project_to_edge(emesh, e->e, start, end);
3490
3491 pro.start = start;
3492 pro.end = end;
3493
3494 float3 d1 = math::normalize(float3(pro.middle) - start);
3495 float3 d2 = math::normalize(float3(pro.middle) - end);
3496 pro.plane_no = math::normalize(math::cross(d1, d2));
3497
3498 if (geom::nearly_parallel(d1, d2)) {
3499 /* Start, middle, end are collinear. */
3500 const float3 v_co = emesh.src_positions[bv->v];
3501 pro.middle = v_co;
3502
3503 if (e->prev->is_bev && e->next->is_bev && bv->selcount >= 3) {
3504 const int2 eprev_verts = emesh.src_edges[e->prev->e];
3505 const int2 enext_verts = emesh.src_edges[e->next->e];
3506 float3 d3 = math::normalize(emesh.vert_position(eprev_verts[0]) -
3507 emesh.vert_position(eprev_verts[1]));
3508 float3 d4 = math::normalize(emesh.vert_position(enext_verts[0]) -
3509 emesh.vert_position(enext_verts[1]));
3510 if (geom::nearly_parallel(d3, d4)) {
3511 pro.middle = math::midpoint(start, end);
3512 do_linear_interp = true;
3513 }
3514 else {
3515 const float3 co3 = start + d3;
3516 const float3 co4 = end + d4;
3517 float3 meetco;
3518 float3 isect2;
3519 if (math::isect_line_line(start, co3, end, co4, meetco, isect2) != 0) {
3520 pro.middle = meetco;
3521 }
3522 else {
3523 pro.middle = math::midpoint(start, end);
3524 do_linear_interp = true;
3525 }
3526 }
3527 }
3528 pro.end = end;
3529 d1 = math::normalize(float3(pro.middle) - start);
3530 d2 = math::normalize(float3(pro.middle) - end);
3531 pro.plane_no = math::normalize(math::cross(d1, d2));
3532 if (geom::nearly_parallel(d1, d2)) {
3533 do_linear_interp = true;
3534 }
3535 else {
3536 pro.plane_co = v_co;
3537 pro.proj_dir = pro.plane_no;
3538 }
3539 }
3540 pro.plane_co = start;
3541 }
3542 else if (bndv->is_arc_start) {
3543 pro.start = start;
3544 pro.end = end;
3545 pro.super_r = PRO_CIRCLE_R;
3546 pro.plane_co = float3(0.0f);
3547 pro.plane_no = float3(0.0f);
3548 pro.proj_dir = float3(0.0f);
3549 do_linear_interp = false;
3550 }
3551 else if (state.params.affect_type == BevelAffect::Vertices) {
3552 pro.start = start;
3553 pro.middle = emesh.src_positions[bv->v];
3554 pro.end = end;
3555 pro.super_r = state.pro_super_r;
3556 pro.plane_co = float3(0.0f);
3557 pro.plane_no = float3(0.0f);
3558 pro.proj_dir = float3(0.0f);
3559 do_linear_interp = false;
3560 }
3561
3562 if (do_linear_interp) {
3563 pro.super_r = PRO_LINE_R;
3564 pro.start = start;
3565 pro.end = end;
3566 pro.middle = math::midpoint(start, end);
3567 pro.plane_co = float3(0.0f);
3568 pro.plane_no = float3(0.0f);
3569 pro.proj_dir = float3(0.0f);
3570 }
3571}
3572
3580static void move_profile_plane(BoundVert *bndv, const float3 bmvert_co)
3581{
3582 Profile &pro = bndv->profile;
3583
3584 /* Only do this if projecting, and start, end, and proj_dir are not coplanar. */
3585 if (math::is_zero(float3(pro.proj_dir))) {
3586 return;
3587 }
3588
3589 const float3 d1 = math::normalize(bmvert_co - float3(pro.start));
3590 const float3 d2 = math::normalize(bmvert_co - float3(pro.end));
3591 float3 no = math::cross(d1, d2);
3592 float3 no2 = math::cross(d1, float3(pro.proj_dir));
3593 float3 no3 = math::cross(d2, float3(pro.proj_dir));
3594
3595 float l1, l2, l3;
3596 no = math::normalize_and_get_length(no, l1);
3597 no2 = math::normalize_and_get_length(no2, l2);
3598 no3 = math::normalize_and_get_length(no3, l3);
3599
3601 {
3602 const float dot2 = math::dot(no, no2);
3603 const float dot3 = math::dot(no, no3);
3604 if (math::abs(dot2) < (1.0f - geom::BEVEL_EPSILON_BIG) &&
3606 {
3607 pro.plane_no = no;
3608 }
3609 }
3610
3611 /* Parameters are now non-default; prevent recalculation later. */
3612 pro.special_params = true;
3613}
3614
3621static void move_weld_profile_planes(BoundVert *bndv1, BoundVert *bndv2, const float3 v_co)
3622{
3623 /* Only do this if projecting. */
3624 if (math::is_zero(float3(bndv1->profile.proj_dir)) ||
3626 {
3627 return;
3628 }
3629 const float3 d1 = v_co - float3(bndv1->nv.co);
3630 const float3 d2 = v_co - float3(bndv2->nv.co);
3631 float3 no = math::cross(d1, d2);
3632 float l1;
3633 no = math::normalize_and_get_length(no, l1);
3634
3635 float3 no2 = math::cross(d1, float3(bndv1->profile.proj_dir));
3636 float l2;
3637 no2 = math::normalize_and_get_length(no2, l2);
3638 float3 no3 = math::cross(d2, float3(bndv2->profile.proj_dir));
3639 float l3;
3640 no3 = math::normalize_and_get_length(no3, l3);
3641
3642 if (l1 != 0.0f && (l2 != 0.0f || l3 != 0.0f)) {
3643 const float dot1 = math::abs(math::dot(no, no2));
3644 const float dot2 = math::abs(math::dot(no, no3));
3645 if (math::abs(dot1 - 1.0f) > geom::BEVEL_EPSILON_D) {
3646 bndv1->profile.plane_no = no;
3647 }
3648 if (math::abs(dot2 - 1.0f) > geom::BEVEL_EPSILON_D) {
3649 bndv2->profile.plane_no = no;
3650 }
3651 }
3652
3653 bndv1->profile.special_params = true;
3654 bndv2->profile.special_params = true;
3655}
3656
3662 const float4x4 &map,
3663 const bool use_map,
3664 const bool reversed,
3665 const int ns,
3666 const double *xvals,
3667 const double *yvals,
3668 MutableSpan<float3> r_prof_co)
3669{
3670 for (int k = 0; k <= ns; k++) {
3671 float3 co;
3672 if (k == 0) {
3673 co = pro.start;
3674 }
3675 else if (k == ns) {
3676 co = pro.end;
3677 }
3678 else {
3679 if (use_map) {
3680 const float3 p = {
3681 reversed ? float(yvals[ns - k]) : float(xvals[k]),
3682 reversed ? float(xvals[ns - k]) : float(yvals[k]),
3683 0.0f,
3684 };
3685 co = math::transform_point(map, p);
3686 }
3687 else {
3688 co = math::interpolate(pro.start, pro.end, float(k) / float(ns));
3689 }
3690 }
3691 /* Project onto the profile plane along proj_dir. */
3692 if (!math::is_zero(float3(pro.proj_dir))) {
3693 const float3 co2 = co + float3(pro.proj_dir);
3694 r_prof_co[k] =
3695 math::isect_line_plane(co, co2, float3(pro.plane_co), float3(pro.plane_no)).value_or(co);
3696 }
3697 else {
3698 r_prof_co[k] = co;
3699 }
3700 }
3701}
3702
3708static void calculate_profile(BevelState &state, BoundVert *bndv, bool reversed, bool /*miter*/)
3709{
3710 Profile &pro = bndv->profile;
3711 const ProfileSpacing &pro_spacing = state.pro_spacing;
3712
3713 if (state.params.segments <= 1) {
3714 return;
3715 }
3716
3717 const bool need_2 = (state.params.segments != pro_spacing.seg_2);
3718
3719 if (pro.prof_co.is_empty()) {
3720 pro.prof_co = Array<float3>(state.params.segments + 1);
3721 if (need_2) {
3722 pro.prof_co_2 = Array<float3>(pro_spacing.seg_2 + 1);
3723 }
3724 /* prof_co_2 alias is set below after prof_co is filled. */
3725 }
3726
3727 /* Mirror the BMesh logic: skip the map only for a superellipse line profile.
3728 * When a custom profile is active the xvals/yvals in pro_spacing already encode the
3729 * custom shape, but they still need to be mapped through the unit-square-to-3D transform,
3730 * so use_map must be true in that case. */
3731 bool use_map;
3732 float4x4 map;
3733 if (state.params.custom_profile_samples.is_empty() && pro.super_r == PRO_LINE_R) {
3734 use_map = false;
3735 }
3736 else {
3737 use_map = geom::make_unit_square_map(pro.start, pro.middle, pro.end, map);
3738 }
3739
3741 map,
3742 use_map,
3743 reversed,
3744 state.params.segments,
3745 pro_spacing.xvals.data(),
3746 pro_spacing.yvals.data(),
3747 pro.prof_co.as_mutable_span());
3748 if (need_2) {
3750 map,
3751 use_map,
3752 reversed,
3753 pro_spacing.seg_2,
3754 pro_spacing.xvals_2.data(),
3755 pro_spacing.yvals_2.data(),
3757 }
3758 else {
3759 /* When seg_2 == segments, prof_co_2 is a copy of the now-filled prof_co. */
3760 pro.prof_co_2 = pro.prof_co;
3761 }
3762}
3763
3769static float3 get_profile_point(const BevelState &state, const Profile *pro, int i, int nseg)
3770{
3771 if (state.params.segments == 1) {
3772 return (i == 0 ? pro->start : pro->end);
3773 }
3774 if (nseg == state.params.segments) {
3775 BLI_assert(!pro->prof_co.is_empty());
3776 return pro->prof_co[i];
3777 }
3778 BLI_assert(is_power_of_2_i(nseg) && nseg <= state.pro_spacing.seg_2);
3779 const int subsample_spacing = state.pro_spacing.seg_2 / nseg;
3780 return pro->prof_co_2[i * subsample_spacing];
3781}
3782
3788{
3789 BoundVert *bndv = vm->boundstart;
3790 do {
3791 if (!bndv->profile.special_params) {
3792 set_profile_params(state, bv, bndv);
3793 }
3794 bool miter_profile = false;
3795 bool reverse_profile = false;
3796 if (!state.params.custom_profile_samples.is_empty()) {
3797 /* Use the miter profile spacing struct if the default is filled with the custom profile. */
3798 miter_profile = (bndv->is_arc_start || bndv->is_patch_start);
3799 /* Don't bother reversing the profile if it's a miter profile. */
3800 reverse_profile = !bndv->is_profile_start && !miter_profile;
3801 }
3802 calculate_profile(state, bndv, reverse_profile, miter_profile);
3803 } while ((bndv = bndv->next) != vm->boundstart);
3804}
3805
3807
3808} // namespace profile
3809
3811{
3812 BLI_assert(f >= 0 && f < this->face_centers.size());
3813 return this->face_centers[f];
3814}
3815
3817{
3818 const float psr = -std::numbers::ln2_v<float> /
3819 std::log(math::sqrt(this->params.shape > 0 ? this->params.shape : 1e-20f));
3820 this->pro_super_r = psr;
3821
3822 if (this->params.shape >= 0.950f) {
3824 }
3825 else if (abs(psr - profile::PRO_CIRCLE_R) < 1e-4f) {
3827 }
3828 else if (abs(psr - profile::PRO_LINE_R) < 1e-4f) {
3830 }
3831 else if (abs(psr) < 1e-4f) {
3833 }
3834
3836 this, &this->pro_spacing, !this->params.custom_profile_samples.is_empty());
3837
3838 if (this->params.segments > 1) {
3839 this->pro_spacing.fullness = profile::find_profile_fullness(this);
3840 }
3841}
3842
3844{
3845 this->uv_layer_info.init(this->emesh.mesh);
3846 if (this->params.segments % 2 != 0) {
3847 this->uv_layer_info.find_components(this->emesh);
3848 }
3849
3850 this->uv_vert_maps.clear();
3851 this->uv_vert_maps.resize(this->uv_layer_info.uv_maps.size());
3852
3853 /* Allocate per-UV-attr storage for new corner UV values. */
3854 this->emesh.init_uv_storage(int(this->uv_layer_info.uv_maps.size()));
3855}
3856
3857namespace construct {
3858
3859/* Forward declaration -- defined in the ADJ vmesh subdivision section below. */
3860static VMesh adj_vmesh(BevelState &state, BevVert *bv);
3861
3862/* -------------------------------------------------------------------- */
3869
3870/* === Helpers for is_bad_uv_poly === */
3871
3877static bool face_point_inside_test(const ExtendableMesh &emesh, const int f, const float3 co)
3878{
3879 const float3 no = emesh.src_face_normals[f];
3880 const float3x3 axis_mat = math::axis_dominant_to_m3(no);
3881
3882 /* Project the test point. */
3883 const float2 co_2d = float2(axis_mat * co);
3884
3885 /* Project every corner of the face. */
3886 const OffsetIndices faces = emesh.src_faces;
3887 const Span<float3> positions = emesh.src_positions;
3888 const Span<int> corner_verts = emesh.src_corner_verts;
3889 const Span<int> face_verts = corner_verts.slice(faces[f]);
3890 Array<float2, 16> projverts(face_verts.size());
3891 for (const int i : face_verts.index_range()) {
3892 const int vert = face_verts[i];
3893 projverts[i] = float2(axis_mat * positions[vert]);
3894 }
3895
3896 return math::isect_point_poly(co_2d, projverts);
3897}
3898
3905 const ExtendableMesh &emesh, const int f, const int v_idx, int *r_e1, int *r_e2)
3906{
3907 *r_e1 = -1;
3908 *r_e2 = -1;
3909 if (f < 0) {
3910 return;
3911 }
3912 const Span<int2> edges = emesh.src_edges;
3913 const OffsetIndices faces = emesh.src_faces;
3914 const Span<int> corner_edges = emesh.src_corner_edges;
3915 for (const int e : corner_edges.slice(faces[f])) {
3916 const int2 &ev = edges[e];
3917 if (ev[0] == v_idx || ev[1] == v_idx) {
3918 if (*r_e1 < 0) {
3919 *r_e1 = e;
3920 }
3921 else if (*r_e2 < 0) {
3922 *r_e2 = e;
3923 }
3924 }
3925 }
3926}
3927
3936 const BevVert *bv,
3937 const int f,
3938 BoundVert *(r_internal[3]))
3939{
3940 if (f < 0) {
3941 r_internal[0] = r_internal[1] = r_internal[2] = nullptr;
3942 return 0;
3943 }
3944 int n_internal = 0;
3945 VMesh *vm = bv->vmesh.get();
3946 BLI_assert(vm != nullptr);
3947 BoundVert *v = vm->boundstart;
3948 do {
3949 if (face_point_inside_test(emesh, f, float3(v->nv.co))) {
3950 r_internal[n_internal++] = v;
3951 if (n_internal == 3) {
3952 break;
3953 }
3954 }
3955 } while ((v = v->next) != vm->boundstart);
3956 for (int i = n_internal; i < 3; i++) {
3957 r_internal[i] = nullptr;
3958 }
3959 return n_internal;
3960}
3961
3968static float projected_boundary_area(const BevelState &state, BevVert *bv, const int f)
3969{
3970 const ExtendableMesh &emesh = state.emesh;
3971 VMesh *vm = bv->vmesh.get();
3972 BLI_assert(vm != nullptr);
3973
3974 const float3 no = emesh.src_face_normals[f];
3975 const float3x3 axis_mat = math::axis_dominant_to_m3(no);
3976
3977 int e1 = -1, e2 = -1;
3978 get_incident_edges(emesh, f, bv->v, &e1, &e2);
3979 BLI_assert(e1 >= 0 && e2 >= 0);
3980
3981 BoundVert *unsnapped[3];
3982 find_face_internal_boundverts(emesh, bv, f, unsnapped);
3983
3984 const Span<float3> positions = emesh.src_positions;
3985 const int2 &ev1 = emesh.src_edges[e1];
3986 const int2 &ev2 = emesh.src_edges[e2];
3987 const float3 e1v1 = positions[ev1[0]];
3988 const float3 e1v2 = positions[ev1[1]];
3989 const float3 e2v1 = positions[ev2[0]];
3990 const float3 e2v2 = positions[ev2[1]];
3991
3992 const int count = vm->count;
3993 Array<float2, 16> proj_co(count);
3994 BoundVert *v = vm->boundstart;
3995 int i = 0;
3996 do {
3997 const float3 co = v->nv.co;
3998 if (ELEM(v, unsnapped[0], unsnapped[1], unsnapped[2])) {
3999 proj_co[i] = float2(axis_mat * co);
4000 }
4001 else {
4002 const float3 snap1 = math::closest_to_line_segment(co, e1v1, e1v2);
4003 const float3 snap2 = math::closest_to_line_segment(co, e2v1, e2v2);
4004 const float d1_sq = math::dist_squared_to_line_segment(co, e1v1, e1v2);
4005 const float d2_sq = math::dist_squared_to_line_segment(co, e2v1, e2v2);
4006 proj_co[i] = float2(axis_mat * (d1_sq <= d2_sq ? snap1 : snap2));
4007 }
4008 ++i;
4009 } while ((v = v->next) != vm->boundstart);
4010
4011 return area_poly_v2(reinterpret_cast<const float (*)[2]>(proj_co.data()), count);
4012}
4013
4019static bool is_bad_uv_poly(const BevelState &state, BevVert *bv, const int frep)
4020{
4021 BLI_assert(bv->vmesh != nullptr);
4022 const float area = projected_boundary_area(state, bv, frep);
4023 return area < 1e-4f; /* BEVEL_EPSILON_BIG */
4024}
4025
4039static int choose_rep_face(const BevelState &state, const Span<int> faces)
4040{
4041 constexpr int VEC_VALUE_LEN = 6;
4042
4043 const int nfaces = int(faces.size());
4044 if (nfaces == 0) {
4045 return -1;
4046 }
4047
4048 /* Read optional per-face attributes once. */
4049 const uv::UVMapInfo &uvi = state.uv_layer_info;
4050 const Mesh &mesh = state.emesh.mesh;
4051 const bke::AttributeAccessor attrs = mesh.attributes();
4052 VArraySpan<int> mat_span;
4053 {
4054 bke::AttributeReader<int> mat_reader = attrs.lookup<int>("material_index",
4056 if (mat_reader) {
4057 mat_span = VArraySpan<int>(mat_reader.varray);
4058 }
4059 }
4060
4061 /* Build score vectors for each non-null candidate. */
4062 Array<float[VEC_VALUE_LEN]> value_vecs(nfaces);
4063 Array<bool> still_viable(nfaces, false);
4064 int num_viable = 0;
4065
4066 for (int fi = 0; fi < nfaces; fi++) {
4067 const int f = faces[fi];
4068 if (f < 0 || f >= mesh.faces_num) {
4069 continue;
4070 }
4071 still_viable[fi] = true;
4072 num_viable++;
4073
4074 int vi = 0;
4075 /* 0: UV-island component. */
4076 value_vecs[fi][vi++] = (!uvi.face_component.is_empty()) ? float(uvi.face_component[f]) : 0.0f;
4077 /* 1: Selected-face placeholder (always 0; no face-selection concept in mesh path). */
4078 value_vecs[fi][vi++] = 0.0f;
4079 /* 2: Material index. */
4080 value_vecs[fi][vi++] = mat_span.is_empty() ? 0.0f : float(mat_span[f]);
4081 /* 3-5: Face center coordinates. Lower z wins (matches BMesh's un-negated cent[2]). */
4082 const float3 cent = state.face_center(f);
4083 value_vecs[fi][vi++] = cent.z;
4084 value_vecs[fi][vi++] = cent.x;
4085 value_vecs[fi][vi++] = cent.y;
4087 }
4088
4089 if (num_viable == 0) {
4090 return -1;
4091 }
4092
4093 /* Lexicographic elimination: find unique minimum at each criterion. */
4094 int best_fi = -1;
4095 for (int vi = 0; num_viable > 1 && vi < VEC_VALUE_LEN; vi++) {
4096 for (int fi = 0; fi < nfaces; fi++) {
4097 if (!still_viable[fi] || fi == best_fi) {
4098 continue;
4099 }
4100 if (best_fi == -1) {
4101 best_fi = fi;
4102 continue;
4103 }
4104 if (value_vecs[fi][vi] < value_vecs[best_fi][vi]) {
4105 best_fi = fi;
4106 /* Eliminate all previous viable candidates. */
4107 for (int j = fi - 1; j >= 0; j--) {
4108 if (still_viable[j]) {
4109 still_viable[j] = false;
4110 num_viable--;
4111 }
4112 }
4113 }
4114 else if (value_vecs[fi][vi] > value_vecs[best_fi][vi]) {
4115 still_viable[fi] = false;
4116 num_viable--;
4117 }
4118 }
4119 }
4120 if (best_fi == -1) {
4121 best_fi = 0;
4122 }
4123 return faces[best_fi];
4124}
4125
4132static int boundvert_rep_face(const BoundVert *v, int *r_fother)
4133{
4134 int frep;
4135 int frep2 = -1;
4136
4137 if (v->ebev) {
4138 frep = v->ebev->fprev;
4139 if (v->efirst->fprev != frep) {
4140 frep2 = v->efirst->fprev;
4141 }
4142 }
4143 else if (v->efirst) {
4144 frep = v->efirst->fprev;
4145 if (frep >= 0) {
4146 if (v->elast->fnext != frep) {
4147 frep2 = v->elast->fnext;
4148 }
4149 else if (v->efirst->fnext != frep) {
4150 frep2 = v->efirst->fnext;
4151 }
4152 else if (v->elast->fprev != frep) {
4153 frep2 = v->elast->fprev;
4154 }
4155 }
4156 else if (v->efirst->fnext >= 0) {
4157 frep = v->efirst->fnext;
4158 if (v->elast->fnext != frep) {
4159 frep2 = v->elast->fnext;
4160 }
4161 }
4162 else if (v->elast->fprev >= 0) {
4163 frep = v->elast->fprev;
4164 }
4165 }
4166 else if (v->prev->elast) {
4167 frep = v->prev->elast->fnext;
4168 if (v->next->efirst) {
4169 if (frep >= 0) {
4170 frep2 = v->next->efirst->fprev;
4171 }
4172 else {
4173 frep = v->next->efirst->fprev;
4174 }
4175 }
4176 }
4177 else {
4178 frep = -1;
4179 }
4180
4181 if (r_fother) {
4182 *r_fother = frep2;
4183 }
4184 return frep;
4185}
4186
4191static int find_closer_edge(const ExtendableMesh &emesh,
4192 const float3 &co,
4193 const int e1,
4194 const int e2)
4195{
4196 BLI_assert(e1 >= 0 && e2 >= 0);
4197 const int2 ev1 = emesh.edge_verts(e1);
4198 const int2 ev2 = emesh.edge_verts(e2);
4199 const float dsq1 = math::dist_squared_to_line_segment(
4200 co, emesh.vert_position(ev1[0]), emesh.vert_position(ev1[1]));
4201 const float dsq2 = math::dist_squared_to_line_segment(
4202 co, emesh.vert_position(ev2[0]), emesh.vert_position(ev2[1]));
4203 return (dsq1 <= dsq2) ? e1 : e2;
4204}
4205
4211static int snap_edge_for_center_vmesh_vert(const int i,
4212 const int n_bndv,
4213 const int eprev,
4214 const int enext,
4215 const Span<int> bndv_rep_faces,
4216 const int center_frep,
4217 const Span<bool> frep_beats_next)
4218{
4219 const int previ = (i + n_bndv - 1) % n_bndv;
4220 const int nexti = (i + 1) % n_bndv;
4221 if (frep_beats_next[previ] && bndv_rep_faces[previ] == center_frep) {
4222 return eprev;
4223 }
4224 if (!frep_beats_next[i] && bndv_rep_faces[nexti] == center_frep) {
4225 return enext;
4226 }
4227 return -1;
4228}
4229
4235static void snap_edges_for_vmesh_vert(const int i,
4236 const int j,
4237 const int k,
4238 const int ns,
4239 const int ns2,
4240 const int n_bndv,
4241 const int eprev,
4242 const int enext,
4243 const int enextnext,
4244 const Span<int> bndv_rep_faces,
4245 const int center_frep,
4246 const Span<bool> frep_beats_next,
4247 int r_snap_edges[4])
4248{
4249 BLI_assert(0 <= i && i < n_bndv && 0 <= j && j < ns2 && 0 <= k && k <= ns2);
4250 for (int corner = 0; corner < 4; corner++) {
4251 r_snap_edges[corner] = -1;
4252 if (ns % 2 == 0) {
4253 continue;
4254 }
4255 const int previ = (i + n_bndv - 1) % n_bndv;
4256 /* jj and kk are the j and k indices for this corner. */
4257 const int jj = corner < 2 ? j : j + 1;
4258 const int kk = ELEM(corner, 0, 3) ? k : k + 1;
4259 if (jj < ns2 && kk < ns2) {
4260 /* No snap. */
4261 }
4262 else if (jj < ns2 && kk == ns2) {
4263 if (!frep_beats_next[i]) {
4264 r_snap_edges[corner] = enext;
4265 }
4266 }
4267 else if (jj < ns2 && kk == ns2 + 1) {
4268 if (frep_beats_next[i]) {
4269 r_snap_edges[corner] = enext;
4270 }
4271 }
4272 else if (jj == ns2 && kk < ns2) {
4273 if (frep_beats_next[previ]) {
4274 r_snap_edges[corner] = eprev;
4275 }
4276 }
4277 else if (jj == ns2 && kk == ns2) {
4278 r_snap_edges[corner] = snap_edge_for_center_vmesh_vert(
4279 i, n_bndv, eprev, enext, bndv_rep_faces, center_frep, frep_beats_next);
4280 }
4281 else if (jj == ns2 && kk == ns2 + 1) {
4282 const int nexti = (i + 1) % n_bndv;
4283 r_snap_edges[corner] = snap_edge_for_center_vmesh_vert(
4284 nexti, n_bndv, enext, enextnext, bndv_rep_faces, center_frep, frep_beats_next);
4285 }
4286 }
4287}
4288
4295static int frep_for_center_poly(const BevelState &state, const BevVert *bv)
4296{
4297 const bool consider_all_faces = (bv->selcount == 1 || state.affect_vertices_odd);
4298
4299 /* Collect candidates (at most edgecount, one per edge). */
4300 Array<int> fchoices(bv->edgecount, -1);
4301 int fcount = 0;
4302 int any_f = -1;
4303
4304 for (int i = 0; i < bv->edgecount; i++) {
4305 const EdgeHalf &e = bv->edges[i];
4306 if (!e.is_bev && !consider_all_faces) {
4307 continue;
4308 }
4309 const int candidates[2] = {e.fprev, e.fnext};
4310 const int bmf = choose_rep_face(state, Span<int>(candidates, 2));
4311 if (bmf < 0) {
4312 continue;
4313 }
4314 if (any_f < 0) {
4315 any_f = bmf;
4316 }
4317 /* Skip duplicates. */
4318 bool already_there = false;
4319 for (int j = fcount - 1; j >= 0; j--) {
4320 if (fchoices[j] == bmf) {
4321 already_there = true;
4322 break;
4323 }
4324 }
4325 if (!already_there) {
4326 if (state.uv_layer_info.has_uv_maps) {
4327 /* Skip candidates that would produce a degenerate UV polygon. */
4328 if (is_bad_uv_poly(state, const_cast<BevVert *>(bv), bmf)) {
4329 continue;
4330 }
4331 }
4332 fchoices[fcount++] = bmf;
4333 }
4334 }
4335
4336 if (fcount == 0) {
4337 return any_f;
4338 }
4339 return choose_rep_face(state, fchoices.as_span().take_front(fcount));
4340}
4341
4343
4344/* -------------------------------------------------------------------- */
4347
4354{
4355 VMesh *vm = bv->vmesh.get();
4356 const int ns = vm->seg;
4357
4358 /* Gather per-boundvert data for UV snap: frep, its two incident edges, and unsnapped verts. */
4359 const ExtendableMesh &emesh = state.emesh;
4360 const int frep = frep_for_center_poly(state, bv);
4361 int frep_e1 = -1, frep_e2 = -1;
4362 BoundVert *frep_unsnapped[3] = {nullptr, nullptr, nullptr};
4363 if (bv->any_seam && frep >= 0) {
4364 get_incident_edges(emesh, frep, bv->v, &frep_e1, &frep_e2);
4365 find_face_internal_boundverts(emesh, bv, frep, frep_unsnapped);
4366 }
4367
4368 Vector<int, 32> verts;
4369 Vector<int, 32> corner_reps;
4370 Vector<int, 32> corner_snaps;
4371
4372 BoundVert *bndv = vm->boundstart;
4373 do {
4374 const int bndv_i = bndv->index;
4375 /* Lambda to append one corner's data. */
4376 auto append_corner = [&](int vert_idx) {
4377 verts.append(vert_idx);
4378 if (frep >= 0 && bv->any_seam) {
4379 /* With a seam-adjacent frep: snap to the closer incident edge, unless this
4380 * boundvert is in frep_unsnapped (internal to the face). */
4381 corner_reps.append(frep);
4382 const bool is_unsnapped = ELEM(
4383 bndv, frep_unsnapped[0], frep_unsnapped[1], frep_unsnapped[2]);
4384 if (is_unsnapped || frep_e1 < 0 || frep_e2 < 0) {
4385 corner_snaps.append(-1);
4386 }
4387 else {
4388 const float3 co = emesh.vert_position(vert_idx);
4389 corner_snaps.append(find_closer_edge(emesh, co, frep_e1, frep_e2));
4390 }
4391 }
4392 else {
4393 /* No seam: each boundvert uses its own rep face, no snapping. */
4394 corner_reps.append(boundvert_rep_face(bndv, nullptr));
4395 corner_snaps.append(-1);
4396 }
4397 };
4398 (void)bndv_i;
4399
4400 append_corner(geom::mesh_vert(vm, bndv_i, 0, 0)->v);
4401 if (bndv->ebev && ns > 1) {
4402 for (int k = 1; k < ns; k++) {
4403 /* Profile-arc intermediate verts: use the same snap rules as the boundvert corner. */
4404 const int pv = geom::mesh_vert(vm, bndv_i, 0, k)->v;
4405 verts.append(pv);
4406 if (frep >= 0 && bv->any_seam) {
4407 corner_reps.append(frep);
4408 if (frep_e1 >= 0 && frep_e2 >= 0) {
4409 const float3 co = emesh.vert_position(pv);
4410 /* For profile-arc intermediates, snap according to which half they're in
4411 * (mirrors BMesh lines 6353-6362). */
4412 const int snap_e = (k < ns / 2) ? -1 : find_closer_edge(emesh, co, frep_e1, frep_e2);
4413 corner_snaps.append(snap_e);
4414 }
4415 else {
4416 corner_snaps.append(-1);
4417 }
4418 }
4419 else {
4420 corner_reps.append(boundvert_rep_face(bndv, nullptr));
4421 corner_snaps.append(-1);
4422 }
4423 }
4424 }
4425 } while ((bndv = bndv->next) != vm->boundstart);
4426
4427 if (verts.size() < 3) {
4428 return -1;
4429 }
4430 const int new_face = state.emesh.face_create(verts.as_span(), frep);
4431 state.emesh.face_set_corner_reps(new_face, corner_reps.as_span(), corner_snaps.as_span());
4432#ifdef BEVEL_DEBUG
4433 {
4434 fmt::println("bevel_build_poly: bv->v={} any_seam={} frep={} ns={} n_verts={}",
4435 bv->v,
4436 bv->any_seam,
4437 frep,
4438 ns,
4439 int(verts.size()));
4440 for (int ci = 0; ci < int(verts.size()); ci++) {
4441 fmt::println(
4442 " corner[{}] v={} rep={} snap={}", ci, verts[ci], corner_reps[ci], corner_snaps[ci]);
4443 }
4444 }
4445#endif
4446 return new_face;
4447}
4448
4455{
4456 VMesh *vm = bv->vmesh.get();
4457 const int ns = vm->seg;
4458 BLI_assert(ns == 1 || bv->selcount == 1);
4459
4460 /* Build the same per-corner data as bevel_build_poly. */
4461 const ExtendableMesh &emesh = state.emesh;
4462 const int frep = (bv->any_seam) ? frep_for_center_poly(state, bv) : -1;
4463 int frep_e1 = -1, frep_e2 = -1;
4464 BoundVert *frep_unsnapped[3] = {nullptr, nullptr, nullptr};
4465 if (bv->any_seam && frep >= 0) {
4466 get_incident_edges(emesh, frep, bv->v, &frep_e1, &frep_e2);
4467 find_face_internal_boundverts(emesh, bv, frep, frep_unsnapped);
4468 }
4469
4470 /* Collect all verts/reps/snaps for the fan polygon, then split into tris. */
4471 Vector<int, 32> ring;
4472 Vector<int, 32> ring_reps;
4473 Vector<int, 32> ring_snaps;
4474
4475 BoundVert *bndv = vm->boundstart;
4476 do {
4477 const int bndv_i = bndv->index;
4478 auto append_ring_corner = [&](int vert_idx) {
4479 ring.append(vert_idx);
4480 if (frep >= 0 && bv->any_seam) {
4481 ring_reps.append(frep);
4482 const bool is_unsnapped = ELEM(
4483 bndv, frep_unsnapped[0], frep_unsnapped[1], frep_unsnapped[2]);
4484 if (is_unsnapped || frep_e1 < 0 || frep_e2 < 0) {
4485 ring_snaps.append(-1);
4486 }
4487 else {
4488 const float3 co = emesh.vert_position(vert_idx);
4489 ring_snaps.append(find_closer_edge(emesh, co, frep_e1, frep_e2));
4490 }
4491 }
4492 else {
4493 ring_reps.append(boundvert_rep_face(bndv, nullptr));
4494 ring_snaps.append(-1);
4495 }
4496 };
4497 append_ring_corner(geom::mesh_vert(vm, bndv_i, 0, 0)->v);
4498 if (bndv->ebev && ns > 1) {
4499 for (int k = 1; k < ns; k++) {
4500 ring.append(geom::mesh_vert(vm, bndv_i, 0, k)->v);
4501 ring_reps.append(frep >= 0 && bv->any_seam ? frep : boundvert_rep_face(bndv, nullptr));
4502 ring_snaps.append(-1);
4503 }
4504 }
4505 } while ((bndv = bndv->next) != vm->boundstart);
4506
4507 if (ring.size() < 3) {
4508 return;
4509 }
4510
4511 /* Mirror BMesh: the fan apex is the last loop vertex of the polygon built by bevel_build_poly,
4512 * which is BM_FACE_FIRST_LOOP(f)->prev->v - i.e. the last element in the ring. */
4513 const int n = int(ring.size());
4514 const int v_fan_idx = n - 1;
4515 const int v_fan = ring[v_fan_idx];
4516 for (int i = 0; i + 1 < v_fan_idx; i++) {
4517 const int tri[3] = {v_fan, ring[i], ring[i + 1]};
4518 const int tri_reps[3] = {ring_reps[v_fan_idx], ring_reps[i], ring_reps[i + 1]};
4519 const int tri_snaps[3] = {ring_snaps[v_fan_idx], ring_snaps[i], ring_snaps[i + 1]};
4520 /* Use frep as the face example only when there is a seam-adjacent rep face, mirroring
4521 * BMesh's bev_create_ngon call in bevel_build_poly which passes repface only when
4522 * bv->any_seam is true. Otherwise use the representative face of the leading edge. */
4523 const int face_example = (frep >= 0) ? frep : tri_reps[1];
4524 const int new_face = state.emesh.face_create(Span<int>(tri, 3), face_example);
4525 state.emesh.face_set_corner_reps(new_face, Span<int>(tri_reps, 3), Span<int>(tri_snaps, 3));
4526 }
4527}
4528
4534{
4535 VMesh *vm = bv->vmesh.get();
4536 BLI_assert(vm->count == 2 && state.params.affect_type == BevelAffect::Vertices);
4537
4538 const int ns = vm->seg;
4539 const int v1 = geom::mesh_vert(vm, 0, 0, 0)->v;
4540 const int v2 = geom::mesh_vert(vm, 1, 0, 0)->v;
4541
4542 if (ns > 1) {
4543 /* Set up a linear profile from v1 to v2 through the original vert. */
4544 BoundVert *bndv0 = vm->boundstart;
4545 Profile &pro = bndv0->profile;
4546 pro.super_r = state.pro_super_r;
4547 pro.start = geom::mesh_vert(vm, 0, 0, 0)->co;
4548 pro.end = geom::mesh_vert(vm, 1, 0, 0)->co;
4549 pro.middle = state.emesh.src_positions[bv->v];
4550 pro.plane_co = float3(0.0f);
4551 pro.plane_no = float3(0.0f);
4552 pro.proj_dir = float3(0.0f);
4553 profile::calculate_profile(state, bndv0, false, false);
4554
4555 for (int k = 1; k < ns; k++) {
4556 const float3 co = profile::get_profile_point(state, &pro, k, ns);
4557 const int nv = state.emesh.vert_create(co, bv->v);
4558 geom::mesh_vert(vm, 0, 0, k)->co = co;
4559 geom::mesh_vert(vm, 0, 0, k)->v = nv;
4560 }
4561 geom::mesh_vert(vm, 0, 0, ns)->co = geom::mesh_vert(vm, 1, 0, 0)->co;
4562 geom::mesh_vert(vm, 0, 0, ns)->v = v2;
4563
4564 /* Mirror to the second BoundVert arc (reversed). */
4565 for (int k = 1; k < ns; k++) {
4566 geom::mesh_vert(vm, 1, 0, ns - k)->co = geom::mesh_vert(vm, 0, 0, k)->co;
4567 geom::mesh_vert(vm, 1, 0, ns - k)->v = geom::mesh_vert(vm, 0, 0, k)->v;
4568 }
4569 }
4570
4571 /* Create edges between successive arc verts if the original vertex had no faces. */
4572 for (int k = 0; k < ns; k++) {
4573 const int va = geom::mesh_vert(vm, 0, 0, k)->v;
4574 const int vb = geom::mesh_vert(vm, 0, 0, k + 1)->v;
4575 if (va >= 0 && vb >= 0) {
4576 state.emesh.edge_create(va, vb);
4577 }
4578 }
4579 (void)v1;
4580}
4581
4590{
4591 VMesh *vm = bv->vmesh.get();
4592 const int n_bndv = vm->count;
4593 const int ns = vm->seg;
4594 const int ns2 = ns / 2;
4595 const int odd = ns % 2;
4596 BLI_assert(n_bndv >= 3 && ns > 1);
4597
4598 /* Compute the representative face for each BoundVert sector. */
4599 Array<int> bndv_rep_faces(n_bndv, -1);
4600 {
4601 BoundVert *bv_iter = vm->boundstart;
4602 do {
4603 bndv_rep_faces[bv_iter->index] = boundvert_rep_face(bv_iter, nullptr);
4604 } while ((bv_iter = bv_iter->next) != vm->boundstart);
4605 }
4606
4607 /* For odd segment counts, pre-compute which rep wins the center-line tie-break
4608 * and the center polygon representative, mirroring BMesh's frep_beats_next logic. */
4609 Array<bool> frep_beats_next;
4610 int center_frep = -1;
4611 /* Per-bndv center-vertex snap edges accumulated during the ring quad loop. */
4612 Array<int> center_snap_edges(n_bndv, -1);
4613 if (odd && state.params.affect_type != BevelAffect::Vertices) {
4614 frep_beats_next = Array<bool>(n_bndv, false);
4615 center_frep = frep_for_center_poly(state, bv);
4616 for (int i = 0; i < n_bndv; i++) {
4617 const int inext = (i + 1) % n_bndv;
4618 const int candidates[2] = {bndv_rep_faces[i], bndv_rep_faces[inext]};
4619 const int winner = choose_rep_face(state, Span<int>(candidates, 2));
4620 frep_beats_next[i] = (winner == bndv_rep_faces[i]);
4621 }
4622 }
4623
4624 BoundVert *bndv = vm->boundstart;
4625 do {
4626 const int i = bndv->index;
4627 const int inext = bndv->next->index;
4628 const int iprev = bndv->prev->index;
4629 const int f = bndv_rep_faces[i];
4630 const int f2 = bndv_rep_faces[inext];
4631 const int fc = (odd && state.params.affect_type != BevelAffect::Vertices) ?
4632 (frep_beats_next[i] ? f : f2) :
4633 -1;
4634
4635 /* Bevel-edge indices for snap purposes (-1 when not applicable). */
4636 const EdgeHalf *ebev = (state.params.affect_type != BevelAffect::Vertices) ? bndv->ebev :
4637 bndv->efirst;
4638 const EdgeHalf *ebev_prev = (state.params.affect_type != BevelAffect::Vertices) ?
4639 bndv->prev->ebev :
4640 bndv->prev->efirst;
4641 const EdgeHalf *ebev_next = (state.params.affect_type != BevelAffect::Vertices) ?
4642 bndv->next->ebev :
4643 bndv->next->efirst;
4644 const int bme = ebev ? ebev->e : -1;
4645 const int bmeprev = ebev_prev ? ebev_prev->e : -1;
4646 const int bmenext = ebev_next ? ebev_next->e : -1;
4647
4648 for (int j = 0; j < ns2; j++) {
4649 for (int k = 0; k < ns2 + odd; k++) {
4650 /* Quad with lower-left corner at (i, j, k). */
4651 const int va = geom::mesh_vert(vm, i, j, k)->v;
4652 const int vb = geom::mesh_vert(vm, i, j, k + 1)->v;
4653 const int vc = geom::mesh_vert(vm, i, j + 1, k + 1)->v;
4654 const int vd = geom::mesh_vert(vm, i, j + 1, k)->v;
4655 if (va < 0 || vb < 0 || vc < 0 || vd < 0) {
4656 continue;
4657 }
4658
4659 /* Choose face rep and per-corner snap edges, mirroring BMesh's bevel_build_rings
4660 * (lines 6063-6127 of bmesh_bevel.cc). */
4661 int face_rep = f;
4662 int se[4] = {-1, -1, -1, -1};
4663 /* Per-corner face reps (-1 = use face_rep fallback). */
4664 int cr[4] = {-1, -1, -1, -1};
4665
4666 if (state.params.affect_type == BevelAffect::Vertices) {
4667 /* Vertex bevel: all corners start as f2. */
4668 face_rep = f2;
4669 if (j < k) {
4670 if (k == ns2 && j == ns2 - 1) {
4671 se[2] = bmenext;
4672 se[3] = bme;
4673 }
4674 }
4675 else if (j == k) {
4676 se[0] = se[2] = bme;
4677 if (!ebev || !ebev->is_seam) {
4678 /* Non-seam diagonal: corner 3 uses f instead of f2.
4679 * Mirrors BMesh bevel_build_rings line 6077: fr[3] = f. */
4680 cr[3] = f;
4681 }
4682 }
4683 }
4684 else {
4685 /* Edge bevel: default all to f. */
4686 face_rep = f;
4687 if (odd) {
4688 /* Compute snap edges for odd-segment ring quads. */
4689 const int b1 = (ebev_prev && ebev_prev->is_seam) ? bmeprev : -1;
4690 const int b2 = (ebev && ebev->is_seam) ? bme : -1;
4691 const int b3 = (ebev_next && ebev_next->is_seam) ? bmenext : -1;
4693 j,
4694 k,
4695 ns,
4696 ns2,
4697 n_bndv,
4698 b1,
4699 b2,
4700 b3,
4701 bndv_rep_faces.as_span(),
4702 center_frep,
4703 frep_beats_next.as_span(),
4704 se);
4705 if (k == ns2) {
4706 if (!ebev || ebev->is_seam) {
4707 face_rep = fc;
4708 }
4709 else {
4710 /* Non-seam center-column: corners 0,3 use f, corners 1,2 use f2.
4711 * Mirrors BMesh bevel_build_rings lines 6105-6106:
4712 * fr[0] = fr[3] = f; fr[1] = fr[2] = f2. */
4713 cr[1] = cr[2] = f2;
4714 }
4715 if (j == ns2 - 1) {
4716 /* Record center-vert snap for the center ngon. */
4717 center_snap_edges[i] = se[3];
4718 }
4719 }
4720 }
4721 else {
4722 /* Even-segment ring quads: snap adjacent to center line. */
4723 if (k == ns2 - 1) {
4724 se[1] = bme;
4725 }
4726 if (j == ns2 - 1 && ebev_prev) {
4727 se[3] = bmeprev;
4728 }
4729 se[2] = (se[1] >= 0) ? se[1] : se[3];
4730 }
4731 }
4732
4733 const int quad[4] = {va, vb, vc, vd};
4734 const int new_face = state.emesh.face_create(Span<int>(quad, 4), face_rep);
4735 /* Apply per-corner snap edges and face reps when any are non-default. */
4736 const bool any_snaps = se[0] >= 0 || se[1] >= 0 || se[2] >= 0 || se[3] >= 0;
4737 const bool any_corner_reps = cr[0] >= 0 || cr[1] >= 0 || cr[2] >= 0 || cr[3] >= 0;
4738 if (any_snaps || any_corner_reps) {
4739 state.emesh.face_set_corner_reps(new_face,
4740 any_corner_reps ? Span<int>(cr, 4) : Span<int>{},
4741 any_snaps ? Span<int>(se, 4) : Span<int>{});
4742 }
4743 }
4744 }
4745 (void)inext;
4746 (void)iprev;
4747 (void)fc;
4748 } while ((bndv = bndv->next) != vm->boundstart);
4749
4750 /* Center ngon for odd segment count. */
4751 if (odd) {
4752 Vector<int, 16> center_verts_vec;
4753 Vector<int, 16> center_reps_vec;
4754 Vector<int, 16> center_snaps_vec;
4755
4756 /* For edge bevel, collect the per-bndv center-vertex data recorded during the ring
4757 * quad loop above. For vertex bevel, fall back to build_center_ngon style logic. */
4758 if (state.params.affect_type != BevelAffect::Vertices) {
4759 /* center_vert_snap_edge and center_face_interp were accumulated per bndv. */
4760 const bool have_seam = bv->any_seam;
4761 const int cfrep = center_frep;
4762 bndv = vm->boundstart;
4763 do {
4764 const int ci = bndv->index;
4765 center_verts_vec.append(geom::mesh_vert(vm, ci, ns2, ns2)->v);
4766 center_reps_vec.append(have_seam ? cfrep : bndv_rep_faces[ci]);
4767 center_snaps_vec.append(center_snap_edges[ci]);
4768 } while ((bndv = bndv->next) != vm->boundstart);
4769 }
4770 else {
4771 /* Vertex bevel center poly: same as build_center_ngon. */
4772 bndv = vm->boundstart;
4773 do {
4774 center_verts_vec.append(geom::mesh_vert(vm, bndv->index, ns2, ns2)->v);
4775 center_reps_vec.append(-1);
4776 center_snaps_vec.append(-1);
4777 } while ((bndv = bndv->next) != vm->boundstart);
4778 }
4779
4780 if (center_verts_vec.size() >= 3) {
4781 const int cface = state.emesh.face_create(center_verts_vec.as_span(), center_frep);
4782 state.emesh.face_set_corner_reps(
4783 cface, center_reps_vec.as_span(), center_snaps_vec.as_span());
4784 }
4785 }
4786
4787 /* Tag the vmesh center-column edges as #NewEdgeKind::MidEdge. */
4788 bndv = vm->boundstart;
4789 do {
4790 const int i = bndv->index;
4791 for (int j = 0; j < ns2; j++) {
4792 const int va = geom::mesh_vert(vm, i, j, ns2)->v;
4793 const int vb = geom::mesh_vert(vm, i, j + 1, ns2)->v;
4794 if (va >= 0 && vb >= 0) {
4795 const int mid_edge = state.emesh.find_edge(va, vb);
4796 if (mid_edge >= 0) {
4797 state.emesh.tag_edge_kind(mid_edge, NewEdgeKind::MidEdge);
4798 }
4799 }
4800 }
4801 } while ((bndv = bndv->next) != vm->boundstart);
4802}
4803
4805
4806/* -------------------------------------------------------------------- */
4809
4814static int count_ccw_edges_between(const EdgeHalf *e1, const EdgeHalf *e2)
4815{
4816 int count = 0;
4817 const EdgeHalf *e = e1;
4818 do {
4819 if (e == e2) {
4820 break;
4821 }
4822 e = e->next;
4823 count++;
4824 } while (e != e1);
4825 return count;
4826}
4827
4834static int bev_rebuild_polygon(BevelState &state, const int f_idx)
4835{
4836 const ExtendableMesh &emesh = state.emesh;
4837 const IndexRange corners = emesh.src_faces[f_idx];
4838 if (corners.size() < 3) {
4839 return false;
4840 }
4841
4842 bool do_rebuild = false;
4843 /* New vertex indices for the rebuilt face. */
4844 Vector<int, 32> vv;
4845 /* Representative original vertex for each vv entry.
4846 * For non-beveled vertices this equals vv[i] (the original vertex).
4847 * For VMesh arc vertices this equals bv->v (the original beveled
4848 * vertex whose VMesh produced the arc). Used to identify the
4849 * best-matching original edge example for each rebuilt edge. */
4850 Vector<int, 32> orig_v;
4851 /* Original edge example for the segment from vv[i] to vv[i+1].
4852 * Mirrors BMesh's `ee[]` array in #bev_rebuild_polygon.
4853 * For arc edges within a beveled vertex, this is the original beveled
4854 * edge (e->e). For non-beveled vertex edges, this is the face loop's
4855 * edge (e_prev_idx). -1 if no suitable example is known. */
4856 Vector<int, 32> orig_e;
4857
4858 const int sz = int(corners.size());
4859 for (int ci = 0; ci < sz; ci++) {
4860 const int c = corners[ci];
4861 const int v_idx = emesh.src_corner_verts[c];
4862 const int e_idx = emesh.src_corner_edges[c];
4863 const int c_prev = corners[(ci + sz - 1) % sz];
4864 const int e_prev_idx = emesh.src_corner_edges[c_prev];
4865
4866 BevVert *bv = state.vert_hash.lookup_default(v_idx, nullptr);
4867 if (bv && bv->vmesh) {
4868 /* This corner's vertex is a beveled vertex.
4869 * Replace it with the arc of new boundary ring vertices. */
4870 EdgeHalf *e = find_edge_half_for_edge(bv, e_idx);
4871 EdgeHalf *eprev = find_edge_half_for_edge(bv, e_prev_idx);
4872 BLI_assert(e && eprev);
4873
4874 /* The original beveled edge used as the example for arc segments,
4875 * matching BMesh's `bme = e->e` and `ee.append(bme)`. */
4876 const int bme = e->e;
4877
4878 /* Determine CCW vs CW traversal (matching BMesh go_ccw logic). */
4879 bool go_ccw;
4880 if (e->prev == eprev) {
4881 if (eprev->prev == e) {
4882 /* Valence-2 vertex: break tie using face membership. */
4883 go_ccw = (e->fnext != f_idx);
4884 }
4885 else {
4886 go_ccw = true;
4887 }
4888 }
4889 else if (eprev->prev == e) {
4890 go_ccw = false;
4891 }
4892 else {
4893 /* Non-contiguous ordering: pick the shorter arc. */
4894 go_ccw = count_ccw_edges_between(eprev, e) < count_ccw_edges_between(e, eprev);
4895 }
4896
4897 VMesh *vm = bv->vmesh.get();
4898 BoundVert *vstart;
4899 BoundVert *vend;
4900 if (go_ccw) {
4901 vstart = eprev->rightv;
4902 vend = e->leftv;
4903 /* profile_index > 0 handling is a TODO (miters not yet implemented). */
4904 }
4905 else {
4906 vstart = eprev->leftv;
4907 vend = e->rightv;
4908 }
4909 BLI_assert(vstart && vend);
4910
4911 /* Emit the starting corner vertex. */
4912 vv.append(geom::mesh_vert(vm, vstart->index, 0, 0)->v);
4913 orig_v.append(bv->v);
4914 orig_e.append(bme);
4915
4916 BoundVert *v = vstart;
4917 while (v != vend) {
4918 if (go_ccw) {
4919 const int i = v->index;
4920 for (int k = 1; k <= vm->seg; k++) {
4921 const int nv = geom::mesh_vert(vm, i, 0, k)->v;
4922 if (nv >= 0) {
4923 vv.append(nv);
4924 orig_v.append(bv->v);
4925 orig_e.append(bme);
4926 }
4927 }
4928 v = v->next;
4929 }
4930 else {
4931 const int i = v->prev->index;
4932 for (int k = vm->seg - 1; k >= 0; k--) {
4933 const int nv = geom::mesh_vert(vm, i, 0, k)->v;
4934 if (nv >= 0) {
4935 vv.append(nv);
4936 orig_v.append(bv->v);
4937 orig_e.append(bme);
4938 }
4939 }
4940 v = v->prev;
4941 }
4942 }
4943 do_rebuild = true;
4944 }
4945 else {
4946 /* Non-beveled vertex: keep as-is. */
4947 vv.append(v_idx);
4948 orig_v.append(v_idx);
4949 orig_e.append(e_idx);
4950 }
4951 }
4952
4953 if (do_rebuild && vv.size() >= 3) {
4954 /* Pre-create edges with example original edges so that face_create's internal
4955 * edge_create calls inherit the correct example via the dedup lookup.
4956 * Only needed for cross-vertex edges (ov_a != ov_b). */
4957 const int n = int(vv.size());
4958 for (int i = 0; i < n; i++) {
4959 const int ov_a = orig_v[i];
4960 const int ov_b = orig_v[(i + 1) % n];
4961 if (ov_a != ov_b) {
4962 const int example_edge = emesh.find_edge(ov_a, ov_b);
4963 if (example_edge >= 0 && example_edge < emesh.mesh.edges_num) {
4964 state.emesh.edge_create(vv[i], vv[(i + 1) % n], example_edge);
4965 }
4966 }
4967 }
4968
4969 const int new_face_idx = state.emesh.face_create(vv.as_span(), f_idx);
4970
4971 /* Post-hoc: set example edges for ALL rebuilt edges, mirroring BMesh's
4972 * `BM_elem_attrs_copy(bm, ee[k], bme_new)` in #bev_rebuild_polygon.
4973 * This is necessary because arc edges within a beveled vertex's boundary ring
4974 * may already have been created (during vertex mesh construction) with example=-1.
4975 * The edge_set_example call overwrites the example, propagating attributes like
4976 * bevel_weight_edge and uv_seam from the original beveled edge. */
4977 for (int i = 0; i < n; i++) {
4978 const int ov_a = orig_v[i];
4979 const int ov_b = orig_v[(i + 1) % n];
4980 int example_edge;
4981 if (ov_a != ov_b) {
4982 example_edge = emesh.find_edge(ov_a, ov_b);
4983 if (example_edge < 0 || example_edge >= emesh.mesh.edges_num) {
4984 example_edge = -1;
4985 }
4986 }
4987 else {
4988 /* Arc edge within the same beveled vertex: use orig_e (the beveled edge). */
4989 example_edge = orig_e[i];
4990 }
4991 if (example_edge >= 0) {
4992 const int new_edge = state.emesh.find_edge(vv[i], vv[(i + 1) % n]);
4993 if (new_edge >= 0) {
4994 state.emesh.edge_set_example(new_edge, example_edge);
4995 }
4996 }
4997 }
4998
4999 /* Corner-segment seam/sharp fixup, matching BMesh's #bev_rebuild_polygon (lines 7316-7332).
5000 * When consecutive edges in the rebuilt face share the same original edge (i.e. they are
5001 * adjacent arc segments within the same beveled vertex), undo seam/sharp if it is not
5002 * contiguous with the previous original edge in the face ring.
5003 *
5004 * Specifically: if orig_e[k] == orig_e[k+1] (corner segment), and orig_e[k] has seam=True
5005 * but the previous *different* original edge (bme_prev) does NOT, then clear seam on the
5006 * new edge. This prevents arc edges from spuriously inheriting seam from the beveled edge
5007 * when the seam is not supposed to continue around that side of the vertex. */
5008 {
5009 const bke::AttributeAccessor src_attrs_check = emesh.mesh.attributes();
5010 const bke::AttributeReader<bool> seam_reader = src_attrs_check.lookup<bool>(
5011 "uv_seam", bke::AttrDomain::Edge);
5012 const bke::AttributeReader<bool> sharp_reader = src_attrs_check.lookup<bool>(
5013 "sharp_edge", bke::AttrDomain::Edge);
5014
5015 auto orig_has_seam = [&](int e_idx) -> bool {
5016 if (!seam_reader || e_idx < 0 || e_idx >= int(emesh.mesh.edges_num)) {
5017 return false;
5018 }
5019 return bool(seam_reader.varray[e_idx]);
5020 };
5021 auto orig_has_sharp = [&](int e_idx) -> bool {
5022 if (!sharp_reader || e_idx < 0 || e_idx >= int(emesh.mesh.edges_num)) {
5023 return false;
5024 }
5025 return bool(sharp_reader.varray[e_idx]);
5026 };
5027
5028 int bme_prev_idx = orig_e[(n - 1) % n];
5029 for (int k = 0; k < n; k++) {
5030 const int oe_k = orig_e[k];
5031 const int new_edge = state.emesh.find_edge(vv[k], vv[(k + 1) % n]);
5032 if (new_edge < 0 || oe_k < 0) {
5033 bme_prev_idx = oe_k;
5034 continue;
5035 }
5036
5037 if (k < n - 1 && oe_k == orig_e[k + 1]) {
5038 /* Corner segment: oe_k == oe_{k+1}. */
5039 if (orig_has_seam(oe_k) && !orig_has_seam(bme_prev_idx)) {
5040 state.emesh.edge_set_seam_override(new_edge, 0);
5041 }
5042 /* For sharp: reverse test (smooth flag is inverted relative to sharp). */
5043 if (orig_has_sharp(oe_k) && !orig_has_sharp(bme_prev_idx)) {
5044 state.emesh.edge_set_sharp_override(new_edge, 0);
5045 }
5046 }
5047 else {
5048 bme_prev_idx = oe_k;
5049 }
5050 }
5051 }
5052
5053 return new_face_idx;
5054 }
5055 return -1;
5056}
5057
5063 Vector<int> &r_rebuilt_orig_faces,
5064 int &r_rebuilt_face_0)
5065{
5066 const ExtendableMesh &emesh = state.emesh;
5067 const int orig_faces_num = emesh.mesh.faces_num;
5068
5069 /* Track which original faces have already been rebuilt to avoid processing them twice
5070 * when multiple beveled vertices share a face. */
5071 Array<bool> rebuilt(orig_faces_num, false);
5072 r_rebuilt_face_0 = -1;
5073
5074 state.bevel_affected_vertices.foreach_index([&](const int v) {
5075 for (const int c : emesh.src_vert_to_corner[v]) {
5076 const int f_idx = emesh.src_corner_to_face[c];
5077 if (f_idx < orig_faces_num && !rebuilt[f_idx]) {
5078 const int new_f = bev_rebuild_polygon(state, f_idx);
5079 if (new_f >= 0) {
5080 rebuilt[f_idx] = true;
5081 r_rebuilt_orig_faces.append(f_idx);
5082 if (f_idx == 0) {
5083 r_rebuilt_face_0 = new_f;
5084 }
5085 }
5086 }
5087 }
5088 });
5089}
5090
5092
5093/* -------------------------------------------------------------------- */
5096
5101static EdgeHalf *find_edge_half_for_edge(BevVert *bv, const int edge_index)
5102{
5103 for (int i = 0; i < bv->edgecount; i++) {
5104 if (bv->edges[i].e == edge_index) {
5105 return &bv->edges[i];
5106 }
5107 }
5108 return nullptr;
5109}
5110
5115static bool bevvert_is_weld_cross(const BevVert *bv)
5116{
5117 return (bv->edgecount == 4 && bv->selcount == 2 &&
5118 ((bv->edges[0].is_bev && bv->edges[2].is_bev) ||
5119 (bv->edges[1].is_bev && bv->edges[3].is_bev)));
5120}
5121
5139static void bevel_build_edge_polygons(BevelState &state, const int edge_index)
5140{
5141 const ExtendableMesh &emesh = state.emesh;
5142 const int2 edge_verts = emesh.edge_verts(edge_index);
5143 const int v1_idx = edge_verts[0];
5144 const int v2_idx = edge_verts[1];
5145
5146 /* Skip non-manifold edges (those with != 2 adjacent faces). */
5147 const GroupedSpan<int> edge_faces = emesh.src_edge_to_face;
5148 if (edge_index >= emesh.mesh.edges_num || edge_faces[edge_index].size() != 2) {
5149 return;
5150 }
5151
5152 BevVert *bv1 = state.vert_hash.lookup_default(v1_idx, nullptr);
5153 BevVert *bv2 = state.vert_hash.lookup_default(v2_idx, nullptr);
5154 if (!bv1 || !bv2) {
5155 return;
5156 }
5157
5158 EdgeHalf *e1 = find_edge_half_for_edge(bv1, edge_index);
5159 EdgeHalf *e2 = find_edge_half_for_edge(bv2, edge_index);
5160 if (!e1 || !e2) {
5161 return;
5162 }
5163
5164 const int nseg = e1->seg;
5165 BLI_assert(nseg > 0 && nseg == e2->seg);
5166
5167 /* Corner boundary-ring vertex indices at both endpoints. */
5168 const int i1 = e1->leftv->index;
5169 const int i2 = e2->leftv->index;
5170 VMesh *vm1 = bv1->vmesh.get();
5171 VMesh *vm2 = bv2->vmesh.get();
5172
5173 /* The two adjacent original faces for this edge.
5174 * Strips on the left half (k <= mid) use f1; strips on the right half use f2. */
5175 const int f1 = e1->fprev; /* -1 on a boundary edge. */
5176 const int f2 = e1->fnext; /* -1 on a boundary edge. */
5177
5178 const int odd = nseg % 2;
5179 const int mid = nseg / 2;
5180
5181 /* For odd nseg with a seam at e1, choose the winner once via #choose_rep_face.
5182 * Also compute center_adj_k: the strip index adjacent to the center strip,
5183 * on the other UV-island side. This mirrors BMesh exactly. */
5184 int f_choice = -1;
5185 int center_adj_k = -1;
5186 if (odd && e1->is_seam) {
5187 const int candidates[2] = {f1, f2};
5188 f_choice = choose_rep_face(state, Span<int>(candidates, 2));
5189 if (nseg > 1) {
5190 center_adj_k = (f_choice == f1) ? mid + 2 : mid;
5191 }
5192 }
5193
5194 /* Starting vertices at k=0 on bv1's end and k=nseg on bv2's end.
5195 * bv2's ring is traversed in reverse (nseg->0), matching BMesh's use of e2->rightv as the
5196 * starting corner (e2->rightv corresponds to mesh_vert(vm2, i2, 0, nseg)).
5197 * Save the first-strip boundary verts (v1/v2 in the BMesh diagram) so that after the loop we
5198 * can look up the first outer long edge and set its example. */
5199 const int v_bme1 = geom::mesh_vert(vm1, i1, 0, 0)->v; /* v1 in BMesh diagram. */
5200 const int v_bme2 = geom::mesh_vert(vm2, i2, 0, nseg)->v; /* v2 in BMesh diagram. */
5201 int v_prev_1 = v_bme1;
5202 int v_prev_2 = v_bme2;
5203
5204 for (int k = 1; k <= nseg; k++) {
5205 /* Next boundary verts along the ring: vm1 goes forward (k), vm2 goes backward (nseg-k). */
5206 const int v_next_1 = geom::mesh_vert(vm1, i1, 0, k)->v; /* v4 in BMesh diagram. */
5207 const int v_next_2 = geom::mesh_vert(vm2, i2, 0, nseg - k)->v; /* v3 in BMesh diagram. */
5208
5209 /* Choose face rep and per-corner face reps / snap edges, mirroring BMesh's
5210 * #bevel_build_edge_polygons exactly.
5211 *
5212 * The quad winds: [0]=v_prev_1, [1]=v_prev_2, [2]=v_next_2, [3]=v_next_1. */
5213 int face_rep;
5214 int corner_reps[4] = {-1, -1, -1, -1};
5215 int corner_snaps[4] = {-1, -1, -1, -1};
5216
5217 if (odd && k == mid + 1) {
5218 /* Center strip of an odd-segment bevel. */
5219 if (e1->is_seam) {
5220 /* Straddles a seam: interpolate in f_choice and snap the verts on
5221 * the non-chosen side to bme for interpolation purposes. */
5222 face_rep = f_choice;
5223 if (f_choice == f1) {
5224 corner_snaps[2] = corner_snaps[3] = edge_index;
5225 }
5226 else {
5227 corner_snaps[0] = corner_snaps[1] = edge_index;
5228 }
5229 corner_reps[0] = corner_reps[1] = corner_reps[2] = corner_reps[3] = f_choice;
5230 }
5231 else {
5232 /* Straddles but not a seam: interpolate left half in f1, right half in f2.
5233 * f_choice is -1 here; face_rep uses f1 but per-corner reps override it. */
5234 face_rep = f1;
5235 corner_reps[0] = corner_reps[1] = f1;
5236 corner_reps[2] = corner_reps[3] = f2;
5237 }
5238 }
5239 else if (odd && k == center_adj_k && e1->is_seam) {
5240 /* The strip adjacent to the center one, in another UV island.
5241 * Snap the edge near the seam to bme to match what happens in the bevel rings. */
5242 if (k == mid) {
5243 face_rep = f1;
5244 corner_snaps[2] = corner_snaps[3] = edge_index;
5245 }
5246 else {
5247 face_rep = f2;
5248 corner_snaps[0] = corner_snaps[1] = edge_index;
5249 }
5250 }
5251 else if (!odd && k == mid) {
5252 /* Left poly that touches an even center line on right. */
5253 face_rep = f1;
5254 corner_snaps[2] = corner_snaps[3] = edge_index;
5255 }
5256 else if (!odd && k == mid + 1) {
5257 /* Right poly that touches an even center line on left. */
5258 face_rep = f2;
5259 corner_snaps[0] = corner_snaps[1] = edge_index;
5260 }
5261 else {
5262 /* Doesn't cross or touch the center line, so interpolate in appropriate f1 or f2. */
5263 face_rep = (k <= mid) ? f1 : f2;
5264 }
5265
5266 /* The quad winds as: v_prev_1 -> v_prev_2 -> v_next_2 -> v_next_1. */
5267 const int quad[4] = {v_prev_1, v_prev_2, v_next_2, v_next_1};
5268 const int new_face = state.emesh.face_create(Span<int>(quad, 4), face_rep);
5269 state.emesh.tag_last_face(NewFaceKind::EdgeFace);
5270
5271 /* Tag the mid-ring edge: the shared boundary between quads k and k+1 at k == mid,
5272 * i.e. the ring at index mid in the strip. Only applies when nseg >= 2.
5273 * For even nseg the mid boundary is between k==mid and k==mid+1 quads.
5274 * For odd nseg the center strip straddles the mid, so tag at k == mid (the boundary
5275 * between mid and the center quad). */
5276 if (nseg >= 2 && k == mid) {
5277 const int mid_edge = state.emesh.find_edge(v_next_1, v_next_2);
5278 if (mid_edge >= 0) {
5279 state.emesh.tag_edge_kind(mid_edge, NewEdgeKind::MidEdge);
5280 }
5281 }
5282
5283 /* Set per-corner face reps and snap edges when any are non-default. */
5284 const bool any_corner_reps = corner_reps[0] >= 0 || corner_reps[1] >= 0 ||
5285 corner_reps[2] >= 0 || corner_reps[3] >= 0;
5286 const bool any_corner_snaps = corner_snaps[0] >= 0 || corner_snaps[1] >= 0 ||
5287 corner_snaps[2] >= 0 || corner_snaps[3] >= 0;
5288 if (any_corner_reps || any_corner_snaps) {
5289 state.emesh.face_set_corner_reps(new_face,
5290 any_corner_reps ? Span<int>(corner_reps, 4) : Span<int>{},
5291 any_corner_snaps ? Span<int>(corner_snaps, 4) :
5292 Span<int>{});
5293 }
5294#ifdef BEVEL_DEBUG
5295 {
5296 fmt::println(
5297 "bevel_build_edge_polygons: edge={} k={}/{} f1={} f2={} is_seam={} face_rep={} "
5298 "verts=[{},{},{},{}] creps=[{},{},{},{}] csnaps=[{},{},{},{}]",
5299 edge_index,
5300 k,
5301 nseg,
5302 f1,
5303 f2,
5304 e1->is_seam,
5305 face_rep,
5306 quad[0],
5307 quad[1],
5308 quad[2],
5309 quad[3],
5310 corner_reps[0],
5311 corner_reps[1],
5312 corner_reps[2],
5313 corner_reps[3],
5314 corner_snaps[0],
5315 corner_snaps[1],
5316 corner_snaps[2],
5317 corner_snaps[3]);
5318 }
5319#endif
5320
5321 v_prev_1 = v_next_1;
5322 v_prev_2 = v_next_2;
5323 }
5324
5325 /* Copy edge attributes to the first and last "long" edges of the strip (those that run
5326 * parallel to the original beveled edge), mirroring BMesh's post-loop
5327 * `BM_elem_attrs_copy(bm, bme, bme1)` / `BM_elem_attrs_copy(bm, bme, bme2)`.
5328 * After the loop: v_prev_1 = v4, v_prev_2 = v3 (BMesh diagram).
5329 * The first outer edge is between v1 (v_bme1) and v2 (v_bme2).
5330 * The last outer edge is between v3 (v_prev_2) and v4 (v_prev_1). */
5331 const int outer_edge1 = state.emesh.find_edge(v_bme1, v_bme2);
5332 const int outer_edge2 = state.emesh.find_edge(v_prev_2, v_prev_1);
5333 if (outer_edge1 >= 0) {
5334 state.emesh.edge_set_example(outer_edge1, edge_index);
5335 state.emesh.tag_edge_kind(outer_edge1, NewEdgeKind::OuterEdge);
5336 state.outer_edge_src_indices.append(edge_index);
5337 }
5338 if (outer_edge2 >= 0) {
5339 state.emesh.edge_set_example(outer_edge2, edge_index);
5340 state.emesh.tag_edge_kind(outer_edge2, NewEdgeKind::OuterEdge);
5341 if (outer_edge2 != outer_edge1) {
5342 /* Only record once if both outer edges are the same (nseg == 1 degenerate case). */
5343 state.outer_edge_src_indices.append(edge_index);
5344 }
5345 }
5346
5347 /* If either end is a "weld cross", want continuity of edge attributes across
5348 * the boundary arc edges. Mirrors BMesh's #weld_cross_attrs_copy:
5349 * For a weld-cross vertex (4 edges, 2 beveled, the beveled pair opposite each other),
5350 * find the adjacent non-beveled edges (bme_prev, bme_next). If their seam status
5351 * disagrees, clear seam on all arc edges. Then set the example for each arc edge
5352 * to bme_prev so that other attributes (bevel weight, sharp, etc.) propagate. */
5353 auto weld_cross_attrs_copy = [&](BevVert *bv, VMesh *vm, int vmindex, EdgeHalf *e) {
5354 int e_prev = -1;
5355 int e_next = -1;
5356 for (int i = 0; i < 4; i++) {
5357 if (&bv->edges[i] == e) {
5358 e_prev = bv->edges[(i + 3) % 4].e;
5359 e_next = bv->edges[(i + 1) % 4].e;
5360 break;
5361 }
5362 }
5363 BLI_assert(e_prev >= 0 && e_next >= 0);
5364
5365 /* Want seams to cross only if that way on both sides.
5366 * Look up the `uv_seam` edge attribute via the attribute API. */
5367 const bke::AttributeAccessor attrs = emesh.mesh.attributes();
5368 const bke::AttributeReader<bool> seam_reader = attrs.lookup<bool>("uv_seam",
5370 const bool prev_seam = seam_reader ? bool(seam_reader.varray[e_prev]) : false;
5371 const bool next_seam = seam_reader ? bool(seam_reader.varray[e_next]) : false;
5372 const bool disable_seam = (prev_seam != next_seam);
5373
5374 for (int i = 0; i < nseg; i++) {
5375 const int va = geom::mesh_vert(vm, vmindex, 0, i)->v;
5376 const int vb = geom::mesh_vert(vm, vmindex, 0, i + 1)->v;
5377 const int arc_edge = state.emesh.find_edge(va, vb);
5378 if (arc_edge >= 0) {
5379 state.emesh.edge_set_example(arc_edge, e_prev);
5380 /* TODO: if disable_seam is true, the seam attribute on the arc edge should be
5381 * cleared after attribute propagation. This requires post-processing support
5382 * not yet available. Similarly for enable_smooth (sharp disagree). */
5383 (void)disable_seam;
5384 }
5385 }
5386 };
5387
5388 if (bevvert_is_weld_cross(bv1)) {
5389 weld_cross_attrs_copy(bv1, vm1, i1, e1);
5390 }
5391 if (bevvert_is_weld_cross(bv2)) {
5392 weld_cross_attrs_copy(bv2, vm2, i2, e2);
5393 }
5394}
5395
5397
5398/* -------------------------------------------------------------------- */
5401
5402static BoundVert *pipe_test(const BevelState &state, BevVert *bv);
5403static VMesh pipe_adj_vmesh(BevelState &state, BevVert *bv, BoundVert *vpipe);
5404static VMesh square_out_adj_vmesh(BevelState &state, BevVert *bv);
5405
5412{
5413 VMesh *vm = bv->vmesh.get();
5414 const int n = vm->count;
5415 const int ns = vm->seg;
5416 const int ns2 = ns / 2;
5417
5418 /* Allocate the grid. */
5419 vm->mesh = Array<NewVert>(n * (ns2 + 1) * (ns + 1), NewVert{-1, float3(0.0f)});
5420
5421 /* Detect the weld case: exactly two beveled edges welding together. */
5422 const bool weld = (bv->selcount == 2) && (vm->count == 2);
5423 BoundVert *weld1 = nullptr;
5424 BoundVert *weld2 = nullptr;
5425
5426 /* Create mesh vertices for each BoundVert's (i, 0, 0) position. */
5427 BoundVert *bndv = vm->boundstart;
5428 do {
5429 const int i = bndv->index;
5430 geom::mesh_vert(vm, i, 0, 0)->co = bndv->nv.co;
5431 geom::mesh_vert(vm, i, 0, 0)->v = state.emesh.vert_create(float3(bndv->nv.co), bv->v);
5432 bndv->nv.v = geom::mesh_vert(vm, i, 0, 0)->v;
5433
5434 if (weld && bndv->ebev) {
5435 if (!weld1) {
5436 weld1 = bndv;
5437 }
5438 else {
5439 weld2 = bndv;
5440 }
5441 }
5442 } while ((bndv = bndv->next) != vm->boundstart);
5443
5444 /* For the weld case, set profile parameters and move the profile planes before
5445 * calculate_vm_profiles runs (which skips BoundVerts with special_params == true).
5446 * Mirrors BMesh's build_vmesh (BMesh lines 6484-6486). */
5447 if (weld && weld1 && weld2) {
5450 profile::move_weld_profile_planes(weld1, weld2, state.emesh.src_positions[bv->v]);
5451 }
5452
5453 /* Calculate profiles for non-ADJ kinds; ADJ computes its own via adj_vmesh. */
5455
5456 /* Fill boundary arc verts (j=0, k=1..ns-1) for non-ADJ. */
5457 bndv = vm->boundstart;
5458 do {
5459 const int i = bndv->index;
5460 /* Last arc vert shares with the next BoundVert's first. */
5461 geom::mesh_vert(vm, i, 0, ns)->co = bndv->next->nv.co;
5462 geom::mesh_vert(vm, i, 0, ns)->v = bndv->next->nv.v;
5463
5464 if (vm->mesh_kind != MeshKind::Adj) {
5465 for (int k = 1; k < ns; k++) {
5466 if (bndv->ebev) {
5467 const float3 co = profile::get_profile_point(state, &bndv->profile, k, ns);
5468 geom::mesh_vert(vm, i, 0, k)->co = co;
5469 if (!weld) {
5470 geom::mesh_vert(vm, i, 0, k)->v = state.emesh.vert_create(co, bv->v);
5471 }
5472 }
5473 else if (n == 2 && !bndv->ebev) {
5474 /* Non-beveled side of a weld: mirror from the other BoundVert. */
5475 geom::mesh_vert(vm, i, 0, k)->co = geom::mesh_vert(vm, 1 - i, 0, ns - k)->co;
5476 geom::mesh_vert(vm, i, 0, k)->v = geom::mesh_vert(vm, 1 - i, 0, ns - k)->v;
5477 }
5478 }
5479 }
5480 } while ((bndv = bndv->next) != vm->boundstart);
5481
5482 /* Weld case: build a blended profile between the two weld BoundVerts. */
5483 if (weld) {
5485 for (int k = 1; k < ns; k++) {
5486 const float3 &v_w1 = geom::mesh_vert(vm, weld1->index, 0, k)->co;
5487 const float3 &v_w2 = geom::mesh_vert(vm, weld2->index, 0, ns - k)->co;
5488 float3 co;
5489 /* TODO: handle BEVEL_PROFILE_CUSTOM weld blending. */
5490 if (weld1->profile.super_r == profile::PRO_LINE_R &&
5492 {
5493 co = v_w2;
5494 }
5495 else if (weld2->profile.super_r == profile::PRO_LINE_R &&
5497 {
5498 co = v_w1;
5499 }
5500 else {
5501 co = (v_w1 + v_w2) * 0.5f;
5502 }
5503 const int nv = state.emesh.vert_create(co, bv->v);
5504 geom::mesh_vert(vm, weld1->index, 0, k)->co = co;
5505 geom::mesh_vert(vm, weld1->index, 0, k)->v = nv;
5506 }
5507 for (int k = 1; k < ns; k++) {
5508 geom::mesh_vert(vm, weld2->index, 0, ns - k)->co =
5509 geom::mesh_vert(vm, weld1->index, 0, k)->co;
5510 geom::mesh_vert(vm, weld2->index, 0, ns - k)->v = geom::mesh_vert(vm, weld1->index, 0, k)->v;
5511 }
5512 }
5513
5514 switch (vm->mesh_kind) {
5515 case MeshKind::None:
5516 if (n == 2 && state.params.affect_type == BevelAffect::Vertices) {
5518 }
5519 break;
5520 case MeshKind::Poly:
5522 break;
5523 case MeshKind::TriFan:
5525 break;
5526 case MeshKind::Adj: {
5527 /* Compute the ADJ interior coordinates via cubic subdivision. */
5528 VMesh vm_adj;
5529 BoundVert *vpipe = pipe_test(state, bv);
5530 if (state.pro_super_r == profile::PRO_SQUARE_R && bv->selcount >= 3 && (ns % 2 == 0) &&
5531 state.params.custom_profile_samples.is_empty())
5532 {
5533 vm_adj = square_out_adj_vmesh(state, bv);
5534 }
5535 else if (vpipe) {
5536 vm_adj = pipe_adj_vmesh(state, bv, vpipe);
5537 }
5538 else {
5539 vm_adj = adj_vmesh(state, bv);
5540 }
5541 /* Copy final positions into vm->mesh and create ExtendableMesh verts. */
5542 for (int i = 0; i < n; i++) {
5543 for (int j = 0; j <= ns2; j++) {
5544 for (int k = 0; k <= ns; k++) {
5545 if (j == 0 && ELEM(k, 0, ns)) {
5546 continue; /* Boundary corners already created. */
5547 }
5548 if (!geom::is_canon(vm, i, j, k)) {
5549 continue;
5550 }
5551 const float3 co = geom::mesh_vert(&vm_adj, i, j, k)->co;
5552 const int nv = state.emesh.vert_create(co, bv->v);
5553 geom::mesh_vert(vm, i, j, k)->co = co;
5554 geom::mesh_vert(vm, i, j, k)->v = nv;
5555 }
5556 }
5557 }
5560 break;
5561 }
5562 case MeshKind::Cutoff:
5563 /* TODO: implement M_CUTOFF. */
5564 break;
5565 }
5566}
5567
5569
5579{
5580 const int num_uv_layers = int(state.uv_layer_info.uv_maps.size());
5581 BLI_assert(int(state.uv_vert_maps.size()) == num_uv_layers);
5582
5583 for (int i = 0; i < num_uv_layers; i++) {
5584 const Span<float2> uv_vals = state.uv_layer_info.uv_maps[i].values;
5585 Vector<UVVertBucket> uv_vert_buckets;
5586
5587 for (const int c : state.emesh.src_vert_to_corner[v]) {
5588 const float2 &luv = uv_vals[c];
5589 bool is_overlap_found = false;
5590 for (UVVertBucket &bucket : uv_vert_buckets) {
5591 for (const int c2 : bucket) {
5592 if (compare_v2v2(luv, uv_vals[c2], STD_UV_CONNECT_LIMIT)) {
5593 bucket.add(c);
5594 is_overlap_found = true;
5595 break;
5596 }
5597 }
5598 if (is_overlap_found) {
5599 break;
5600 }
5601 }
5602 if (!is_overlap_found) {
5603 uv_vert_buckets.append(UVVertBucket{c});
5604 }
5605 }
5606
5607 BLI_assert(state.uv_vert_maps[i].contains(v) == false);
5608 state.uv_vert_maps[i].add_new(v, uv_vert_buckets);
5609 }
5610}
5611
5612/* -------------------------------------------------------------------- */
5615
5616/* Allocates a VMesh with a zeroed NewVert grid of size count*(seg/2+1)*(seg+1). */
5617static VMesh new_adj_vmesh(int count, int seg, BoundVert *bounds)
5618{
5619 VMesh vm;
5620 vm.count = count;
5621 vm.seg = seg;
5622 vm.boundstart = bounds;
5623 vm.mesh = Array<NewVert>(count * (seg / 2 + 1) * (seg + 1), NewVert{-1, float3(0.0f)});
5625 return vm;
5626}
5627
5628/* Fills frac[0..ns] with cumulative arc-length fractions along ring 0 of vmesh row i. */
5630{
5631 const int ns = vm->seg;
5632 frac[0] = 0.0f;
5633 float total = 0.0f;
5634 for (int k = 0; k < ns; k++) {
5635 total += math::distance(geom::mesh_vert(vm, i, 0, k)->co,
5636 geom::mesh_vert(vm, i, 0, k + 1)->co);
5637 frac[k + 1] = total;
5638 }
5639 if (total > 0.0f) {
5640 for (int k = 1; k <= ns; k++) {
5641 frac[k] /= total;
5642 }
5643 }
5644 else {
5645 frac[ns] = 1.0f;
5646 }
5647}
5648
5649/* Fills frac[0..ns] with cumulative arc-length fractions along bndv's profile. */
5651 const BoundVert *bndv,
5653 const int ns)
5654{
5655 frac[0] = 0.0f;
5656 float total = 0.0f;
5657 float3 co = bndv->nv.co;
5658 for (int k = 0; k < ns; k++) {
5659 const float3 nextco = profile::get_profile_point(state, &bndv->profile, k + 1, ns);
5660 total += math::distance(co, nextco);
5661 frac[k + 1] = total;
5662 co = nextco;
5663 }
5664 if (total > 0.0f) {
5665 for (int k = 1; k <= ns; k++) {
5666 frac[k] /= total;
5667 }
5668 }
5669 else {
5670 frac[ns] = 1.0f;
5671 }
5672}
5673
5674/* Returns index i such that frac[i] <= f <= frac[i+1], and sets r_rest to the remainder. */
5675static int interp_range(const Span<float> frac, const int n, const float f, float *r_rest)
5676{
5677 for (int i = 0; i < n; i++) {
5678 if (f <= frac[i + 1]) {
5679 float rest = f - frac[i];
5680 *r_rest = (rest == 0.0f) ? 0.0f : rest / (frac[i + 1] - frac[i]);
5681 if (i == n - 1 && *r_rest == 1.0f) {
5682 i = n;
5683 *r_rest = 0.0f;
5684 }
5685 return i;
5686 }
5687 }
5688 *r_rest = 0.0f;
5689 return n;
5690}
5691
5692/* Re-samples vm_in to produce a VMesh with nseg boundary segments. */
5693static VMesh interp_vmesh(const BevelState &state, VMesh &vm_in, int nseg)
5694{
5695 const int n_bndv = vm_in.count;
5696 const int ns_in = vm_in.seg;
5697 const int nseg2 = nseg / 2;
5698 const int odd = nseg % 2;
5699 VMesh vm_out = new_adj_vmesh(n_bndv, nseg, vm_in.boundstart);
5700
5701 Array<float, 8> prev_frac(ns_in + 1);
5702 Array<float, 8> frac(ns_in + 1);
5703 Array<float, 8> new_frac(nseg + 1);
5704 Array<float, 8> prev_new_frac(nseg + 1);
5705
5706 fill_vmesh_fracs(&vm_in, prev_frac, n_bndv - 1);
5707 BoundVert *bndv = vm_in.boundstart;
5708 fill_profile_fracs(state, bndv->prev, prev_new_frac, nseg);
5709
5710 for (int i = 0; i < n_bndv; i++) {
5711 fill_vmesh_fracs(&vm_in, frac, i);
5712 fill_profile_fracs(state, bndv, new_frac, nseg);
5713 for (int j = 0; j <= nseg2 - 1 + odd; j++) {
5714 for (int k = 0; k <= nseg2; k++) {
5715 float restk, restkprev;
5716 int k_in = interp_range(frac, ns_in, new_frac[k], &restk);
5717 int k_in_prev = interp_range(prev_frac, ns_in, prev_new_frac[nseg - j], &restkprev);
5718 int j_in = ns_in - k_in_prev;
5719 float restj = -restkprev;
5720 if (restj > -geom::BEVEL_EPSILON_D) {
5721 restj = 0.0f;
5722 }
5723 else {
5724 j_in--;
5725 restj = 1.0f + restj;
5726 }
5727 float3 co;
5728 if (restj < geom::BEVEL_EPSILON_D && restk < geom::BEVEL_EPSILON_D) {
5729 co = geom::mesh_vert_canon(&vm_in, i, j_in, k_in)->co;
5730 }
5731 else {
5732 const int j0inc = (restj < geom::BEVEL_EPSILON_D || j_in == ns_in) ? 0 : 1;
5733 const int k0inc = (restk < geom::BEVEL_EPSILON_D || k_in == ns_in) ? 0 : 1;
5734 float3 quad[4];
5735 quad[0] = geom::mesh_vert_canon(&vm_in, i, j_in, k_in)->co;
5736 quad[1] = geom::mesh_vert_canon(&vm_in, i, j_in, k_in + k0inc)->co;
5737 quad[2] = geom::mesh_vert_canon(&vm_in, i, j_in + j0inc, k_in + k0inc)->co;
5738 quad[3] = geom::mesh_vert_canon(&vm_in, i, j_in + j0inc, k_in)->co;
5739 interp_bilinear_quad_v3(reinterpret_cast<float (*)[3]>(quad), restk, restj, co);
5740 }
5741 geom::mesh_vert(&vm_out, i, j, k)->co = co;
5742 }
5743 }
5744 bndv = bndv->next;
5745 prev_frac = frac;
5746 prev_new_frac = new_frac;
5747 }
5748 if (!odd) {
5749 geom::mesh_vert(&vm_out, 0, nseg2, nseg2)->co = geom::vmesh_center(&vm_in);
5750 }
5752 return vm_out;
5753}
5754
5760{
5761 const int n_boundary = vm_in.count;
5762 const int ns_in = vm_in.seg;
5763 const int ns_in2 = ns_in / 2;
5764 BLI_assert(ns_in % 2 == 0);
5765 const int ns_out = 2 * ns_in;
5766 VMesh vm_out = new_adj_vmesh(n_boundary, ns_out, vm_in.boundstart);
5767
5768 /* Adjust even boundary vertices. */
5769 for (int i = 0; i < n_boundary; i++) {
5770 geom::mesh_vert(&vm_out, i, 0, 0)->co = geom::mesh_vert(&vm_in, i, 0, 0)->co;
5771 for (int k = 1; k < ns_in; k++) {
5772 float3 co = geom::mesh_vert(&vm_in, i, 0, k)->co;
5773 /* Smooth boundary (not for custom profile). */
5774 if (state.params.custom_profile_samples.is_empty()) {
5775 float3 acc = geom::mesh_vert(&vm_in, i, 0, k - 1)->co +
5776 geom::mesh_vert(&vm_in, i, 0, k + 1)->co;
5777 acc += co * -2.0f;
5778 co += acc * (-1.0f / 6.0f);
5779 }
5780 geom::mesh_vert_canon(&vm_out, i, 0, 2 * k)->co = co;
5781 }
5782 }
5783
5784 /* Adjust odd boundary vertices from profile. */
5785 BoundVert *bndv = vm_out.boundstart;
5786 for (int i = 0; i < n_boundary; i++) {
5787 for (int k = 1; k < ns_out; k += 2) {
5788 float3 co = profile::get_profile_point(state, &bndv->profile, k, ns_out);
5789 if (state.params.custom_profile_samples.is_empty()) {
5790 float3 acc = geom::mesh_vert_canon(&vm_out, i, 0, k - 1)->co +
5791 geom::mesh_vert_canon(&vm_out, i, 0, k + 1)->co;
5792 acc += co * -2.0f;
5793 co += acc * (-1.0f / 6.0f);
5794 }
5795 geom::mesh_vert_canon(&vm_out, i, 0, k)->co = co;
5796 }
5797 bndv = bndv->next;
5798 }
5800
5801 /* Copy adjusted boundary back into vm_in. */
5802 for (int i = 0; i < n_boundary; i++) {
5803 for (int k = 0; k < ns_in; k++) {
5804 geom::mesh_vert(&vm_in, i, 0, k)->co = geom::mesh_vert(&vm_out, i, 0, 2 * k)->co;
5805 }
5806 }
5808
5809 /* New face vertices. */
5810 for (int i = 0; i < n_boundary; i++) {
5811 for (int j = 0; j < ns_in2; j++) {
5812 for (int k = 0; k < ns_in2; k++) {
5813 geom::mesh_vert(&vm_out, i, 2 * j + 1, 2 * k + 1)->co = geom::avg4(
5814 geom::mesh_vert(&vm_in, i, j, k),
5815 geom::mesh_vert(&vm_in, i, j, k + 1),
5816 geom::mesh_vert(&vm_in, i, j + 1, k),
5817 geom::mesh_vert(&vm_in, i, j + 1, k + 1));
5818 }
5819 }
5820 }
5821
5822 /* New vertical edge vertices. */
5823 for (int i = 0; i < n_boundary; i++) {
5824 for (int j = 0; j < ns_in2; j++) {
5825 for (int k = 1; k <= ns_in2; k++) {
5826 geom::mesh_vert(&vm_out, i, 2 * j + 1, 2 * k)->co = geom::avg4(
5827 geom::mesh_vert(&vm_in, i, j, k),
5828 geom::mesh_vert(&vm_in, i, j + 1, k),
5829 geom::mesh_vert_canon(&vm_out, i, 2 * j + 1, 2 * k - 1),
5830 geom::mesh_vert_canon(&vm_out, i, 2 * j + 1, 2 * k + 1));
5831 }
5832 }
5833 }
5834
5835 /* New horizontal edge vertices. */
5836 for (int i = 0; i < n_boundary; i++) {
5837 for (int j = 1; j < ns_in2; j++) {
5838 for (int k = 0; k < ns_in2; k++) {
5839 geom::mesh_vert(&vm_out, i, 2 * j, 2 * k + 1)->co = geom::avg4(
5840 geom::mesh_vert(&vm_in, i, j, k),
5841 geom::mesh_vert(&vm_in, i, j, k + 1),
5842 geom::mesh_vert_canon(&vm_out, i, 2 * j - 1, 2 * k + 1),
5843 geom::mesh_vert_canon(&vm_out, i, 2 * j + 1, 2 * k + 1));
5844 }
5845 }
5846 }
5847
5848 /* New interior vertices (not on boundary). */
5849 constexpr float gamma_interior = 0.25f;
5850 constexpr float beta_interior = -gamma_interior;
5851 for (int i = 0; i < n_boundary; i++) {
5852 for (int j = 1; j < ns_in2; j++) {
5853 for (int k = 1; k <= ns_in2; k++) {
5854 const float3 co1 = geom::avg4(geom::mesh_vert_canon(&vm_out, i, 2 * j, 2 * k - 1),
5855 geom::mesh_vert_canon(&vm_out, i, 2 * j, 2 * k + 1),
5856 geom::mesh_vert_canon(&vm_out, i, 2 * j - 1, 2 * k),
5857 geom::mesh_vert_canon(&vm_out, i, 2 * j + 1, 2 * k));
5858 const float3 co2 = geom::avg4(geom::mesh_vert_canon(&vm_out, i, 2 * j - 1, 2 * k - 1),
5859 geom::mesh_vert_canon(&vm_out, i, 2 * j + 1, 2 * k - 1),
5860 geom::mesh_vert_canon(&vm_out, i, 2 * j - 1, 2 * k + 1),
5861 geom::mesh_vert_canon(&vm_out, i, 2 * j + 1, 2 * k + 1));
5862 const float3 co = co1 + co2 * beta_interior +
5863 geom::mesh_vert(&vm_in, i, j, k)->co * gamma_interior;
5864 geom::mesh_vert(&vm_out, i, 2 * j, 2 * k)->co = co;
5865 }
5866 }
5867 }
5868
5870
5871 /* Special center vertex (Sabin modification). */
5872 const float gamma_c = geom::sabin_gamma(n_boundary);
5873 const float beta_c = -gamma_c;
5874 float3 co1(0.0f), co2(0.0f);
5875 for (int i = 0; i < n_boundary; i++) {
5876 co1 += geom::mesh_vert(&vm_out, i, ns_in, ns_in - 1)->co;
5877 co2 += geom::mesh_vert(&vm_out, i, ns_in - 1, ns_in - 1)->co;
5878 co2 += geom::mesh_vert(&vm_out, i, ns_in - 1, ns_in + 1)->co;
5879 }
5880 const float3 co = co1 * (1.0f / float(n_boundary)) +
5881 co2 * (beta_c / (2.0f * float(n_boundary))) +
5882 geom::mesh_vert(&vm_in, 0, ns_in2, ns_in2)->co * gamma_c;
5883 for (int i = 0; i < n_boundary; i++) {
5884 geom::mesh_vert(&vm_out, i, ns_in, ns_in)->co = co;
5885 }
5886
5887 /* Restore final profile boundary. */
5888 bndv = vm_out.boundstart;
5889 for (int i = 0; i < n_boundary; i++) {
5890 const int inext = (i + 1) % n_boundary;
5891 for (int k = 0; k <= ns_out; k++) {
5892 const float3 pco = profile::get_profile_point(state, &bndv->profile, k, ns_out);
5893 geom::mesh_vert(&vm_out, i, 0, k)->co = pco;
5894 if (k >= ns_in && k < ns_out) {
5895 geom::mesh_vert(&vm_out, inext, ns_out - k, 0)->co = pco;
5896 }
5897 }
5898 bndv = bndv->next;
5899 }
5900
5901 return vm_out;
5902}
5903
5909static void snap_to_superellipsoid(float3 &co, const float super_r, const bool midline)
5910{
5911 const float r = super_r;
5912 if (r == profile::PRO_CIRCLE_R) {
5913 co = math::normalize(co);
5914 return;
5915 }
5916
5917 float a = math::max(0.0f, co[0]);
5918 float b = math::max(0.0f, co[1]);
5919 float c = math::max(0.0f, co[2]);
5920 float x = a, y = b, z = c;
5923 z = 0.0f;
5924 x = math::min(1.0f, x);
5925 y = math::min(1.0f, y);
5926 if (r == profile::PRO_SQUARE_R) {
5927 const float dx = 1.0f - x;
5928 const float dy = 1.0f - y;
5929 if (dx < dy) {
5930 x = 1.0f;
5931 y = midline ? 1.0f : y;
5932 }
5933 else {
5934 y = 1.0f;
5935 x = midline ? 1.0f : x;
5936 }
5937 }
5938 else {
5939 if (x < y) {
5940 x = 0.0f;
5941 y = midline ? 0.0f : y;
5942 }
5943 else {
5944 y = 0.0f;
5945 x = midline ? 0.0f : x;
5946 }
5947 }
5948 }
5949 else {
5950 const float rinv = 1.0f / r;
5951 if (a == 0.0f) {
5952 if (b == 0.0f) {
5953 x = 0.0f;
5954 y = 0.0f;
5955 z = powf(c, rinv);
5956 }
5957 else {
5958 x = 0.0f;
5959 y = powf(1.0f / (1.0f + powf(c / b, r)), rinv);
5960 z = c * y / b;
5961 }
5962 }
5963 else {
5964 x = powf(1.0f / (1.0f + powf(b / a, r) + powf(c / a, r)), rinv);
5965 y = b * x / a;
5966 z = c * x / a;
5967 }
5968 }
5969 co[0] = x;
5970 co[1] = y;
5971 co[2] = z;
5972}
5973
5980 const float3 &vb,
5981 const float3 &vc,
5982 const float3 &vd)
5983{
5984 float4x4 mat;
5985 /* Columns of the 4x4 column-major matrix. */
5986 mat[0] = float4((va - vb - vc + vd) * 0.5f, 0.0f);
5987 mat[1] = float4((vb - va - vc + vd) * 0.5f, 0.0f);
5988 mat[2] = float4((vc - va - vb + vd) * 0.5f, 0.0f);
5989 mat[3] = float4((va + vb + vc - vd) * 0.5f, 1.0f);
5990 return mat;
5991}
5992
5999static VMesh make_cube_corner_square(const int nseg)
6000{
6001 const int ns2 = nseg / 2;
6002
6003 /* Build 3 BoundVerts at unit-axis corners. */
6004 BoundVert bvs[3] = {};
6005 for (int i = 0; i < 3; i++) {
6006 bvs[i].next = &bvs[(i + 1) % 3];
6007 bvs[i].prev = &bvs[(i + 2) % 3];
6008 bvs[i].index = i;
6009 bvs[i].nv.co[i] = 1.0f;
6010 }
6011
6012 VMesh vm = new_adj_vmesh(3, nseg, &bvs[0]);
6013
6014 for (int i = 0; i < 3; i++) {
6015 for (int j = 0; j <= ns2; j++) {
6016 for (int k = 0; k <= ns2; k++) {
6017 if (!geom::is_canon(&vm, i, j, k)) {
6018 continue;
6019 }
6020 float3 co;
6021 co[i] = 1.0f;
6022 co[(i + 1) % 3] = float(k) * 2.0f / float(nseg);
6023 co[(i + 2) % 3] = float(j) * 2.0f / float(nseg);
6024 geom::mesh_vert(&vm, i, j, k)->co = co;
6025 }
6026 }
6027 }
6029 return vm;
6030}
6031
6037static VMesh make_cube_corner_square_in(const int nseg)
6038{
6039 const int ns2 = nseg / 2;
6040 const int odd = nseg % 2;
6041
6042 BoundVert bvs[3] = {};
6043 for (int i = 0; i < 3; i++) {
6044 bvs[i].next = &bvs[(i + 1) % 3];
6045 bvs[i].prev = &bvs[(i + 2) % 3];
6046 bvs[i].index = i;
6047 bvs[i].nv.co[i] = 1.0f;
6048 }
6049
6050 VMesh vm = new_adj_vmesh(3, nseg, &bvs[0]);
6051
6052 const float b = odd ? 2.0f / (2.0f * float(ns2) + float(M_SQRT2)) : 2.0f / float(nseg);
6053
6054 for (int i = 0; i < 3; i++) {
6055 for (int k = 0; k <= ns2; k++) {
6056 float3 co(0.0f);
6057 co[i] = 1.0f - float(k) * b;
6058 geom::mesh_vert(&vm, i, 0, k)->co = co;
6059 co[i] = 0.0f;
6060 co[(i + 1) % 3] = 1.0f - float(k) * b;
6061 geom::mesh_vert(&vm, i, 0, nseg - k)->co = co;
6062 }
6063 }
6064 return vm;
6065}
6066
6081{
6082 const float r = state.pro_super_r;
6083 const int nseg = state.params.segments;
6084
6085 /* Short-circuit for square profiles: the superellipsoid snap path below assumes z ~= 0
6086 * only for the general superellipse case; for the two square extremes BMesh calls
6087 * dedicated helpers that never invoke snap_to_superellipsoid. */
6088 if (state.params.custom_profile_samples.is_empty()) {
6089 if (r == profile::PRO_SQUARE_R) {
6090 return make_cube_corner_square(nseg);
6091 }
6092 if (r == profile::PRO_SQUARE_IN_R) {
6093 return make_cube_corner_square_in(nseg);
6094 }
6095 }
6096
6097 /* Create 3 BoundVerts for the unit simplex corners (1,0,0), (0,1,0), (0,0,1).
6098 * They are stack-allocated here and remain live for the entire subdivision.
6099 * cubic_subdiv and interp_vmesh access bndv->profile via vm->boundstart, so
6100 * these must not go out of scope until vm1 is returned. */
6101 BoundVert unit_bv[3] = {};
6102
6103 for (int i = 0; i < 3; i++) {
6104 float3 co_start(0.0f);
6105 float3 co_end(0.0f);
6106 float3 co_mid(0.0f);
6107 co_start[i] = 1.0f;
6108 co_end[(i + 1) % 3] = 1.0f;
6109 co_mid[i] = 1.0f;
6110 co_mid[(i + 1) % 3] = 1.0f;
6111
6112 /* Circular-list links. */
6113 unit_bv[i].next = &unit_bv[(i + 1) % 3];
6114 unit_bv[i].prev = &unit_bv[(i + 2) % 3];
6115 unit_bv[i].index = i;
6116 unit_bv[i].nv.co = co_start;
6117
6118 /* Set up the profile for the arc from corner i to corner i+1. */
6119 Profile &pro = unit_bv[i].profile;
6120 pro.start = co_start;
6121 pro.end = co_end;
6122 pro.middle = co_mid;
6123 pro.plane_co = co_start;
6124 pro.plane_no = math::normalize(math::cross(co_start, co_end));
6125 pro.proj_dir = pro.plane_no;
6126 pro.super_r = r;
6127 pro.height = 0.0f;
6128 pro.special_params = false;
6129
6130 /* Build the 2D->3D map and fill prof_co / prof_co_2. */
6131 float4x4 map;
6132 const bool use_map = (r != profile::PRO_LINE_R) &&
6133 geom::make_unit_square_map(pro.start, pro.middle, pro.end, map);
6134
6135 const ProfileSpacing &ps = state.pro_spacing;
6136 pro.prof_co = Array<float3>(nseg + 1);
6138 map,
6139 use_map,
6140 false,
6141 nseg,
6142 ps.xvals.data(),
6143 ps.yvals.data(),
6144 pro.prof_co.as_mutable_span());
6145
6146 const bool need_2 = (nseg != ps.seg_2);
6147 if (need_2) {
6148 pro.prof_co_2 = Array<float3>(ps.seg_2 + 1);
6150 map,
6151 use_map,
6152 false,
6153 ps.seg_2,
6154 ps.xvals_2.data(),
6155 ps.yvals_2.data(),
6157 }
6158 else {
6159 /* prof_co_2 is a copy of the now-filled prof_co (seg_2 == nseg). */
6160 pro.prof_co_2 = pro.prof_co;
6161 }
6162 }
6163
6164 /* Build the seg=2 seed vmesh using the unit-simplex BoundVerts as the boundary ring. */
6165 VMesh vm0 = new_adj_vmesh(3, 2, &unit_bv[0]);
6166
6167 for (int i = 0; i < 3; i++) {
6168 geom::mesh_vert(&vm0, i, 0, 0)->co = unit_bv[i].nv.co;
6169 /* Sample the profile midpoint at k=1 out of seg=2. */
6170 const float3 pt = profile::get_profile_point(state, &unit_bv[i].profile, 1, 2);
6171 geom::mesh_vert(&vm0, i, 0, 1)->co = pt;
6172 }
6173
6174 /* Center vertex: place it on the (1,1,1) diagonal scaled by 1/sqrt(3),
6175 * then adjust slightly based on super_r to match BMesh. */
6176 float3 cen(float(M_SQRT1_3));
6177 if (nseg > 2) {
6178 if (r > 1.5f) {
6179 cen *= 1.4f;
6180 }
6181 else if (r < 0.75f) {
6182 cen *= 0.6f;
6183 }
6184 }
6185 geom::mesh_vert(&vm0, 0, 1, 1)->co = cen;
6187
6188 /* Subdivide until seg >= nseg, then resample. */
6189 VMesh vm1 = std::move(vm0);
6190 while (vm1.seg < nseg) {
6191 VMesh next = cubic_subdiv(state, vm1);
6192 vm1 = std::move(next);
6193 }
6194 if (vm1.seg != nseg) {
6195 VMesh resampled = interp_vmesh(state, vm1, nseg);
6196 vm1 = std::move(resampled);
6197 }
6198
6199 /* Snap every grid point onto the superellipsoid `x^r + y^r + z^r = 1`. */
6200 const int ns2 = nseg / 2;
6201 for (int i = 0; i < 3; i++) {
6202 for (int j = 0; j <= ns2; j++) {
6203 for (int k = 0; k <= nseg; k++) {
6204 snap_to_superellipsoid(geom::mesh_vert(&vm1, i, j, k)->co, r, false);
6205 }
6206 }
6207 }
6208 return vm1;
6209}
6210
6214static float3 closer_v3_v3v3v3(const float3 &a, const float3 &b, const float3 &v)
6215{
6216 return (math::distance_squared(a, v) <= math::distance_squared(b, v)) ? a : b;
6217}
6218
6225{
6226 VMesh *vm = bv->vmesh.get();
6227 if (vm->count < 3 || vm->count > 4 || bv->selcount < 3 || bv->selcount > 4) {
6228 return nullptr;
6229 }
6230
6231 const float3 bv_co = state.emesh.src_positions[bv->v];
6232
6233 /* Find v1, v2, v3 all with beveled edges, where v1 and v3 have collinear edges. */
6234 EdgeHalf *epipe = nullptr;
6235 BoundVert *v1 = vm->boundstart;
6236 float3 dir1, dir3;
6237 do {
6238 BoundVert *v2 = v1->next;
6239 BoundVert *v3 = v2->next;
6240 if (v1->ebev && v2->ebev && v3->ebev) {
6241 const int other_v1 = geom::edge_other_vert(state.emesh, v1->ebev->e, bv->v);
6242 const int other_v3 = geom::edge_other_vert(state.emesh, v3->ebev->e, bv->v);
6243 const float3 co_v1 = state.emesh.src_positions[other_v1];
6244 const float3 co_v3 = state.emesh.src_positions[other_v3];
6245
6246 dir1 = math::normalize(bv_co - co_v1);
6247 dir3 = math::normalize(co_v3 - bv_co);
6248 if (float(math::angle_between(dir1, dir3)) < geom::BEVEL_EPSILON_ANG) {
6249 epipe = v1->ebev;
6250 break;
6251 }
6252 }
6253 } while ((v1 = v1->next) != vm->boundstart);
6254
6255 if (!epipe) {
6256 return nullptr;
6257 }
6258
6259 /* Check face planes: all should have normals perpendicular to epipe. */
6260 for (int i = 0; i < bv->edgecount; i++) {
6261 EdgeHalf *e = &bv->edges[i];
6262 if (e->fnext >= 0) {
6263 const float3 face_no = state.emesh.src_face_normals[e->fnext];
6264 if (math::abs(math::dot(dir1, face_no)) > geom::BEVEL_EPSILON_BIG) {
6265 return nullptr;
6266 }
6267 }
6268 }
6269 return v1;
6270}
6271
6277 const BevelState &state, BevVert *bv, BoundVert *vpipe, bool midline, const float3 &co)
6278{
6279 Profile *pro = &vpipe->profile;
6280 EdgeHalf *e = vpipe->ebev;
6281
6282 if (math::is_equal(pro->start, pro->end, geom::BEVEL_EPSILON_D)) {
6283 return pro->start;
6284 }
6285
6286 /* Get a plane with the normal pointing along the beveled edge. */
6287 const int other_v = geom::edge_other_vert(state.emesh, e->e, bv->v);
6288 const float3 v_co = state.emesh.src_positions[bv->v];
6289 const float3 other_co = state.emesh.src_positions[other_v];
6290 const float3 edir = v_co - other_co;
6291 const float4 plane = math::plane_from_point_normal(co, edir);
6292
6293 const float3 start_plane = math::closest_to_plane(plane, pro->start);
6294 const float3 end_plane = math::closest_to_plane(plane, pro->end);
6295 const float3 middle_plane = math::closest_to_plane(plane, pro->middle);
6296
6297 float4x4 m;
6298 if (geom::make_unit_square_map(start_plane, middle_plane, end_plane, m)) {
6299 bool invert_ok;
6300 const float4x4 minv = math::invert(m, invert_ok);
6301 if (invert_ok) {
6302 /* Transform co and project it onto superellipse. */
6303 float3 p = math::transform_point(minv, co);
6304 snap_to_superellipsoid(p, pro->super_r, midline);
6305 return math::transform_point(m, p);
6306 }
6307 }
6308 /* Planar case: just snap to line start_plane--end_plane. */
6309 return math::closest_to_line_segment(co, start_plane, end_plane);
6310}
6311
6318{
6319 /* Some unnecessary overhead running this subdivision with custom profile snapping later on. */
6320 VMesh vm = adj_vmesh(state, bv);
6321
6322 /* Now snap all interior coordinates to be on the epipe profile. */
6323 const int n_bndv = bv->vmesh->count;
6324 const int ns = bv->vmesh->seg;
6325 const int half_ns = ns / 2;
6326 const int ipipe1 = vpipe->index;
6327 const int ipipe2 = vpipe->next->next->index;
6328
6329 for (int i = 0; i < n_bndv; i++) {
6330 for (int j = 1; j <= half_ns; j++) {
6331 for (int k = 0; k <= half_ns; k++) {
6332 if (!geom::is_canon(&vm, i, j, k)) {
6333 continue;
6334 }
6335 /* With a custom profile just copy the shape of the profile at each ring. */
6336 if (!state.params.custom_profile_samples.is_empty()) {
6337 /* Find both profile vertices that correspond to this point. */
6338 float3 *profile_point_pipe1, *profile_point_pipe2;
6339 float f;
6340 if (ELEM(i, ipipe1, ipipe2)) {
6341 if (n_bndv == 3 && i == ipipe1) {
6342 /* This part of the vmesh is the triangular corner between the two pipe profiles. */
6343 const int ring = std::max(j, k);
6344 profile_point_pipe2 = &geom::mesh_vert(&vm, i, 0, ring)->co;
6345 profile_point_pipe1 = &geom::mesh_vert(&vm, i, ring, 0)->co;
6346 /* End profile index increases with k on one side and j on the other. */
6347 f = ((k < j) ? std::min(j, k) : ((2.0f * ring) - j)) / (2.0f * ring);
6348 }
6349 else {
6350 /* This is part of either pipe profile boundvert area in the 4-way intersection. */
6351 profile_point_pipe1 = &geom::mesh_vert(&vm, i, 0, k)->co;
6352 profile_point_pipe2 =
6353 &geom::mesh_vert(&vm, (i == ipipe1) ? ipipe2 : ipipe1, 0, ns - k)->co;
6354 f = float(j) / float(ns); /* The ring index brings us closer to the other side. */
6355 }
6356 }
6357 else {
6358 /* The profile vertices are on both ends of each of the side profile's rings. */
6359 profile_point_pipe1 = &geom::mesh_vert(&vm, i, j, 0)->co;
6360 profile_point_pipe2 = &geom::mesh_vert(&vm, i, j, ns)->co;
6361 f = float(k) / float(ns); /* Ring runs along the pipe, so segment is used here. */
6362 }
6363
6364 /* Place the vertex by interpolating between the two profile points using the factor. */
6365 geom::mesh_vert(&vm, i, j, k)->co = math::interpolate(
6366 *profile_point_pipe1, *profile_point_pipe2, f);
6367 }
6368 else {
6369 /* A tricky case is for the 'square' profiles and an even nseg: we want certain
6370 * vertices to snap to the midline on the pipe, not just to one plane or the other. */
6371 const bool even = (ns % 2) == 0;
6372 const bool midline = even && k == half_ns &&
6373 ((i == 0 && j == half_ns) || ELEM(i, ipipe1, ipipe2));
6374 geom::mesh_vert(&vm, i, j, k)->co = snap_to_pipe_profile(
6375 state, bv, vpipe, midline, geom::mesh_vert(&vm, i, j, k)->co);
6376 }
6377 }
6378 }
6379 }
6380 return vm;
6381}
6382
6396{
6397 const int n_bndv = bv->vmesh->count;
6398 const int ns = bv->vmesh->seg;
6399 const int ns2 = ns / 2;
6400 const int odd = ns % 2;
6401 float ns2inv = 1.0f / float(ns2);
6402 VMesh vm = new_adj_vmesh(n_bndv, ns, bv->vmesh->boundstart);
6403 const int clstride = ns2 + 1;
6404 Array<float3, 8> centerline(clstride * n_bndv);
6405 Array<bool, 8> cset(n_bndv, false);
6406
6407 const float3 bv_co = state.emesh.src_positions[bv->v];
6408
6409 /* Find on_edge, place on bndv[i]'s elast where offset line would meet,
6410 * taking min-distance-to bv->v with position where next sector's offset line would meet. */
6411 BoundVert *bndv = vm.boundstart;
6412 for (int i = 0; i < n_bndv; i++) {
6413 const float3 bndco = bndv->nv.co;
6414 EdgeHalf *e1 = bndv->efirst;
6415 EdgeHalf *e2 = bndv->elast;
6416 AngleKind ang_kind = ANGLE_STRAIGHT;
6417 if (e1 && e2) {
6418 ang_kind = edges_angle_kind(state.emesh, e1, e2, bv->v);
6419 }
6420 if (bndv->is_patch_start) {
6421 centerline[clstride * i] = math::midpoint(bndv->nv.co, bndv->next->nv.co);
6422 cset[i] = true;
6423 bndv = bndv->next;
6424 i++;
6425 centerline[clstride * i] = math::midpoint(bndv->nv.co, bndv->next->nv.co);
6426 cset[i] = true;
6427 bndv = bndv->next;
6428 i++;
6429 /* Leave cset[i] where it was - probably false, unless i == n - 1. */
6430 }
6431 else if (bndv->is_arc_start) {
6432 e1 = bndv->efirst;
6433 e2 = bndv->next->efirst;
6434 centerline[clstride * i] = bndv->profile.middle;
6435 bndv = bndv->next;
6436 cset[i] = true;
6437 i++;
6438 /* Leave cset[i] where it was - probably false, unless i == n - 1. */
6439 }
6440 else if (ang_kind == ANGLE_SMALLER) {
6441 const int e1_other_v = geom::edge_other_vert(state.emesh, e1->e, bv->v);
6442 const int e2_other_v = geom::edge_other_vert(state.emesh, e2->e, bv->v);
6443 const float3 e1_other_co = state.emesh.src_positions[e1_other_v];
6444 const float3 e2_other_co = state.emesh.src_positions[e2_other_v];
6445 const float3 dir1 = float3(bv_co) - e1_other_co;
6446 const float3 dir2 = float3(bv_co) - e2_other_co;
6447 const float3 co1 = float3(bndco) + dir1;
6448 const float3 co2 = float3(bndco) + dir2;
6449 /* Intersect e1 with line through bndv parallel to e2 to get v1co. */
6450 float3 meet1, meet2;
6451 int ikind = math::isect_line_line(
6452 float3(bv_co), e1_other_co, float3(bndco), co2, meet1, meet2);
6453 float3 v1co;
6454 bool v1set;
6455 if (ikind == 0) {
6456 v1set = false;
6457 }
6458 else {
6459 /* If the lines are skew (ikind == 2), want meet1 which is on e1. */
6460 v1co = meet1;
6461 v1set = true;
6462 }
6463 /* Intersect e2 with line through bndv parallel to e1 to get v2co. */
6464 ikind = math::isect_line_line(float3(bv_co), e2_other_co, float3(bndco), co1, meet1, meet2);
6465 float3 v2co;
6466 bool v2set;
6467 if (ikind == 0) {
6468 v2set = false;
6469 }
6470 else {
6471 v2set = true;
6472 v2co = meet1;
6473 }
6474
6475 /* We want on_edge[i] to be min dist to bv->v of v2co and the v1co of next iteration. */
6476 float3 &on_edge_cur = centerline[clstride * i];
6477 int iprev = (i == 0) ? n_bndv - 1 : i - 1;
6478 float3 &on_edge_prev = centerline[clstride * iprev];
6479 if (v2set) {
6480 if (cset[i]) {
6481 on_edge_cur = closer_v3_v3v3v3(on_edge_cur, v2co, bv_co);
6482 }
6483 else {
6484 on_edge_cur = v2co;
6485 cset[i] = true;
6486 }
6487 }
6488 if (v1set) {
6489 if (cset[iprev]) {
6490 on_edge_prev = closer_v3_v3v3v3(on_edge_prev, v1co, bv_co);
6491 }
6492 else {
6493 on_edge_prev = v1co;
6494 cset[iprev] = true;
6495 }
6496 }
6497 }
6498 bndv = bndv->next;
6499 }
6500 /* Maybe not everything was set by the previous loop. */
6501 bndv = vm.boundstart;
6502 for (int i = 0; i < n_bndv; i++) {
6503 if (!cset[i]) {
6504 float3 &on_edge_cur = centerline[clstride * i];
6505 EdgeHalf *e1 = bndv->next->efirst;
6506 float3 co1 = bndv->nv.co;
6507 float3 co2 = bndv->next->nv.co;
6508 if (e1) {
6509 const int e1_other_v = geom::edge_other_vert(state.emesh, e1->e, bv->v);
6510 const float3 e1_other_co = state.emesh.src_positions[e1_other_v];
6511 if (bndv->prev->is_arc_start && bndv->next->is_arc_start) {
6512 float3 meet1, meet2;
6513 int ikind = math::isect_line_line(bv_co, e1_other_co, co1, co2, meet1, meet2);
6514 if (ikind != 0) {
6515 on_edge_cur = meet1;
6516 cset[i] = true;
6517 }
6518 }
6519 else {
6520 if (bndv->prev->is_arc_start) {
6521 on_edge_cur = math::closest_to_line_segment(co1, bv_co, e1_other_co);
6522 }
6523 else {
6524 on_edge_cur = math::closest_to_line_segment(co2, bv_co, e1_other_co);
6525 }
6526 cset[i] = true;
6527 }
6528 }
6529 if (!cset[i]) {
6530 on_edge_cur = math::midpoint(co1, co2);
6531 cset[i] = true;
6532 }
6533 }
6534 bndv = bndv->next;
6535 }
6536
6537 /* Fill in rest of center-lines by interpolation. */
6538 const float3 co2 = bv_co;
6539 bndv = vm.boundstart;
6540 for (int i = 0; i < n_bndv; i++) {
6541 if (odd) {
6542 float ang = 0.5f * float(math::angle_between(math::normalize(bndv->nv.co - co2),
6543 math::normalize(bndv->next->nv.co - co2)));
6544 float finalfrac;
6545 if (ang > geom::BEVEL_SMALL_ANG) {
6546 /* finalfrac is the length along arms of isosceles triangle with top angle 2*ang
6547 * such that the base of the triangle is 1.
6548 * This is used in interpolation along center-line in odd case.
6549 * To avoid too big a drop from bv, cap finalfrac a 0.8 arbitrarily */
6550 finalfrac = 0.5f / sinf(ang);
6551 finalfrac = std::min(finalfrac, 0.8f);
6552 }
6553 else {
6554 finalfrac = 0.8f;
6555 }
6556 ns2inv = 1.0f / (ns2 + finalfrac);
6557 }
6558
6559 const float3 co1 = centerline[clstride * i];
6560 for (int j = 1; j <= ns2; j++) {
6561 centerline[clstride * i + j] = math::interpolate(co1, co2, float(j) * ns2inv);
6562 }
6563 bndv = bndv->next;
6564 }
6565
6566 /* Coords of edges and mid or near-mid line. */
6567 bndv = vm.boundstart;
6568 for (int i = 0; i < n_bndv; i++) {
6569 const float3 co1 = bndv->nv.co;
6570 const float3 &prev_cl = centerline[clstride * (i == 0 ? n_bndv - 1 : i - 1)];
6571 for (int j = 0; j < ns2 + odd; j++) {
6572 geom::mesh_vert(&vm, i, j, 0)->co = math::interpolate(co1, prev_cl, float(j) * ns2inv);
6573 }
6574 const float3 &cur_cl = centerline[clstride * i];
6575 for (int k = 1; k <= ns2; k++) {
6576 geom::mesh_vert(&vm, i, 0, k)->co = math::interpolate(co1, cur_cl, float(k) * ns2inv);
6577 }
6578 bndv = bndv->next;
6579 }
6580 if (!odd) {
6581 geom::mesh_vert(&vm, 0, ns2, ns2)->co = bv_co;
6582 }
6584
6585 /* Fill in interior points by interpolation from edges to center-lines. */
6586 bndv = vm.boundstart;
6587 for (int i = 0; i < n_bndv; i++) {
6588 int im1 = (i == 0) ? n_bndv - 1 : i - 1;
6589 for (int j = 1; j < ns2 + odd; j++) {
6590 for (int k = 1; k <= ns2; k++) {
6591 float3 meet1, meet2;
6592 int ikind = math::isect_line_line(geom::mesh_vert(&vm, i, 0, k)->co,
6593 centerline[clstride * im1 + k],
6594 geom::mesh_vert(&vm, i, j, 0)->co,
6595 centerline[clstride * i + j],
6596 meet1,
6597 meet2);
6598 if (ikind == 0) {
6599 /* How can this happen? fall back on interpolation in one direction if it does. */
6600 geom::mesh_vert(&vm, i, j, k)->co = math::interpolate(geom::mesh_vert(&vm, i, 0, k)->co,
6601 centerline[clstride * im1 + k],
6602 float(j) * ns2inv);
6603 }
6604 else if (ikind == 1) {
6605 geom::mesh_vert(&vm, i, j, k)->co = meet1;
6606 }
6607 else {
6608 geom::mesh_vert(&vm, i, j, k)->co = math::midpoint(meet1, meet2);
6609 }
6610 }
6611 }
6612 bndv = bndv->next;
6613 }
6614
6616 return vm;
6617}
6618
6625static int tri_corner_test(const BevelState &state, const BevVert *bv)
6626{
6627 /* Custom profiles and vertex-only mode skip this path. */
6628 if (state.params.affect_type == BevelAffect::Vertices ||
6629 !state.params.custom_profile_samples.is_empty())
6630 {
6631 return -1;
6632 }
6633 if (bv->vmesh->count != 3) {
6634 return 0;
6635 }
6636
6637 const float offset = bv->edges[0].offset_l;
6638 int in_plane_e = 0;
6639 float totang = 0.0f;
6640 const ExtendableMesh &emesh = state.emesh;
6641
6642 for (int i = 0; i < bv->edgecount; i++) {
6643 const EdgeHalf &e = bv->edges[i];
6644 /* Compute the signed dihedral angle of this edge from its two adjacent face normals. */
6645 float ang = 0.0f;
6646 if (e.fprev >= 0 && e.fnext >= 0) {
6647 const float3 no_prev = emesh.src_face_normals[e.fprev];
6648 const float3 no_next = emesh.src_face_normals[e.fnext];
6649 ang = float(math::angle_between(no_prev, no_next));
6650 /* Negate for concave (the dihedral is > PI). */
6651 if (math::dot(math::cross(no_prev, no_next),
6652 emesh.src_positions[bv->v] - state.face_center(e.fprev)) < 0.0f)
6653 {
6654 ang = -ang;
6655 }
6656 }
6657
6658 const float absang = math::abs(ang);
6659 if (absang <= float(M_PI_4)) {
6660 in_plane_e++;
6661 }
6662 else if (absang >= 3.0f * float(M_PI_4)) {
6663 return -1;
6664 }
6665
6666 if (e.is_bev && math::abs(e.offset_l - offset) > geom::BEVEL_EPSILON_D) {
6667 return -1;
6668 }
6669 totang += ang;
6670 }
6671
6672 if (in_plane_e != bv->edgecount - 3) {
6673 return -1;
6674 }
6675 const float angdiff = math::abs(math::abs(totang) - 3.0f * float(M_PI_2));
6676 if ((state.pro_super_r == profile::PRO_SQUARE_R && angdiff > float(M_PI) / 16.0f) ||
6677 (angdiff > float(M_PI_4)))
6678 {
6679 return -1;
6680 }
6681 if (bv->edgecount != 3 || bv->selcount != 3) {
6682 return 0;
6683 }
6684 return 1;
6685}
6686
6692{
6693 BoundVert *bndv = bv->vmesh->boundstart;
6694 const float3 co0 = bndv->nv.co;
6695 bndv = bndv->next;
6696 const float3 co1 = bndv->nv.co;
6697 bndv = bndv->next;
6698 const float3 co2 = bndv->nv.co;
6699
6700 const float3 v_co = state.emesh.src_positions[bv->v];
6701 const float4x4 mat = make_unit_cube_map(co0, co1, co2, v_co);
6702
6704 /* Set the correct BoundVert ring (the canonical helper builds with nullptr). */
6705 vm.boundstart = bv->vmesh->boundstart;
6706
6707 const int ns = vm.seg;
6708 const int ns2 = ns / 2;
6709 for (int i = 0; i < 3; i++) {
6710 for (int j = 0; j <= ns2; j++) {
6711 for (int k = 0; k <= ns; k++) {
6712 geom::mesh_vert(&vm, i, j, k)->co = math::transform_point(
6713 mat, geom::mesh_vert(&vm, i, j, k)->co);
6714 }
6715 }
6716 }
6717 return vm;
6718}
6719
6727{
6728 const int n_bndv = bv->vmesh->count;
6729 const int nseg = bv->vmesh->seg;
6730
6731 /* Same as the bevel of 3 edges of a vertex in a cube: use the superellipsoid snap path. */
6732 if (n_bndv == 3 && tri_corner_test(state, bv) != -1 &&
6733 state.pro_super_r != profile::PRO_SQUARE_IN_R)
6734 {
6735 return tri_corner_adj_vmesh(state, bv);
6736 }
6737
6738 VMesh vm0 = new_adj_vmesh(n_bndv, 2, bv->vmesh->boundstart);
6739
6740 /* Seed mesh: boundary from BoundVert coords, mid-arc from profile at k=1. */
6741 float3 center(0.0f);
6742 BoundVert *bndv = vm0.boundstart;
6743 for (int i = 0; i < n_bndv; i++) {
6744 geom::mesh_vert(&vm0, i, 0, 0)->co = bndv->nv.co;
6745 const float3 pt = profile::get_profile_point(state, &bndv->profile, 1, 2);
6746 geom::mesh_vert(&vm0, i, 0, 1)->co = pt;
6747 center += float3(bndv->nv.co);
6748 bndv = bndv->next;
6749 }
6750 center /= float(n_bndv);
6751
6752 /* Center vertex position using fullness. */
6753 const float3 v_co = state.emesh.src_positions[bv->v];
6754 const float3 center_dir = v_co - center;
6755 if (math::length_squared(center_dir) > geom::BEVEL_EPSILON_SQ) {
6756 const float fullness = state.pro_spacing.fullness;
6757 geom::mesh_vert(&vm0, 0, 1, 1)->co = center + center_dir * fullness;
6758 }
6759 else {
6760 geom::mesh_vert(&vm0, 0, 1, 1)->co = center;
6761 }
6763
6764 /* Subdivide until seg >= nseg.
6765 * Use do..while so that cubic_subdiv always runs at least once, matching bmesh_bevel.cc.
6766 * This is necessary because the seed mesh's center vertex is placed using the fullness
6767 * heuristic, which can be > 1.0 for high shape values, overshooting the original vertex.
6768 * The first cubic_subdiv step applies the Sabin-formula correction that pulls the center
6769 * back toward the bevel boundary regardless of nseg. */
6770 VMesh vm1 = std::move(vm0);
6771 do {
6772 VMesh next = cubic_subdiv(state, vm1);
6773 vm1 = std::move(next);
6774 } while (vm1.seg < nseg);
6775 if (vm1.seg != nseg) {
6776 VMesh resampled = interp_vmesh(state, vm1, nseg);
6777 vm1 = std::move(resampled);
6778 }
6779 return vm1;
6780}
6781
6783
6784/* Construction around the vertex. */
6786{
6787 int nsel = 0;
6788 int tot_edges = 0;
6789 int tot_wire = 0;
6790 int first_e = -1;
6791
6792 const ExtendableMesh &emesh = state.emesh;
6793
6794 /* Current bevel does nothing if only one edge into a vertex (handled below).
6795 *
6796 * Gather input selected edges.
6797 * Only bevel selected edges that have exactly two incident faces.
6798 * Want edges to be ordered so that they share faces.
6799 * There may be one or more chains of shared faces broken by
6800 * gaps where there are no faces.
6801 * Want to ignore wire edges completely for edge beveling.
6802 * TODO: make following work when more than one gap. */
6803
6804 for (const int e : emesh.src_vert_to_edge[v]) {
6805 int face_count = emesh.src_edge_to_face[e].size();
6806
6807 bool is_selected = (state.params.affect_type != BevelAffect::Vertices &&
6808 state.selection.contains(e));
6809 if (is_selected) {
6810 BLI_assert(face_count == 2);
6811 nsel++;
6812 if (first_e == -1) {
6813 first_e = e;
6814 }
6815 }
6816 if (face_count == 1) {
6817 first_e = e;
6818 }
6819 if (face_count > 0 || state.params.affect_type == BevelAffect::Vertices) {
6820 tot_edges++;
6821 }
6822 if (face_count == 0) {
6823 tot_wire++;
6824 }
6825 }
6826
6827 if (first_e == -1 && !emesh.src_vert_to_edge[v].is_empty()) {
6828 first_e = emesh.src_vert_to_edge[v].first();
6829 }
6830
6831 if ((nsel == 0 && state.params.affect_type != BevelAffect::Vertices) ||
6832 (tot_edges < 2 && state.params.affect_type == BevelAffect::Vertices))
6833 {
6834 return;
6835 }
6836
6837 state.bev_verts.append({});
6838 BevVert *bv = &state.bev_verts.last();
6839 bv->v = v;
6840 bv->edgecount = tot_edges;
6841 bv->selcount = nsel;
6842 bv->wirecount = tot_wire;
6843 /* bv->offset holds the representative slide distance for this vertex.
6844 * In vertex bevel mode, offsets[0] is a per-vertex array, so index by v.
6845 * In edge bevel mode, offsets[0] is a per-edge array; use the first selected
6846 * edge as an approximation (exact when all edges share a uniform offset). */
6847 if (state.params.affect_type == BevelAffect::Vertices) {
6848 bv->offset = state.params.offsets[0][v];
6849 }
6850 else {
6851 bv->offset = (first_e != -1) ? state.params.offsets[0][first_e] : 1.0f;
6852 }
6853
6854 bv->edges = Array<EdgeHalf>(tot_edges);
6855
6856 if (tot_wire > 0) {
6857 bv->wire_edges = Array<int>(tot_wire);
6858 int i = 0;
6859 for (const int e : emesh.src_vert_to_edge[v]) {
6860 if (emesh.src_edge_to_face[e].is_empty()) {
6861 bv->wire_edges[i++] = e;
6862 }
6863 }
6864 }
6865
6866 bv->vmesh = std::make_unique<VMesh>();
6867 bv->vmesh->seg = state.params.segments;
6868
6869 const bool is_edge_bevel = (state.params.affect_type != BevelAffect::Vertices);
6870 find_bevel_edge_order(emesh, bv, first_e, is_edge_bevel);
6871
6872 for (int i = 0; i < tot_edges; i++) {
6873 EdgeHalf *eh = &bv->edges[i];
6874 int e = eh->e;
6875 bool is_selected = (state.params.affect_type != BevelAffect::Vertices &&
6876 state.selection.contains(e));
6877 if (is_selected) {
6878 eh->is_bev = true;
6879 eh->seg = state.params.segments;
6880 }
6881
6882 const int2 edge_verts = emesh.edge_verts(e);
6883 eh->is_rev = (edge_verts[1] == v);
6884 }
6885
6886 if (tot_edges > 1) {
6887 /* Test if the winding order of edges around the vertex is CCW as seen from the
6888 * vertex normal side. If not, reverse the order and swap fprev/fnext on each EdgeHalf. */
6889 int ccw_test_sum = 0;
6890 for (int i = 0; i < tot_edges; i++) {
6891 ccw_test_sum += bev_ccw_test(
6892 emesh, bv->edges[i].e, bv->edges[(i + 1) % tot_edges].e, bv->edges[i].fnext);
6893 }
6894 if (ccw_test_sum < 0) {
6895 for (int i = 0; i <= (tot_edges / 2) - 1; i++) {
6896 std::swap(bv->edges[i], bv->edges[tot_edges - i - 1]);
6897 std::swap(bv->edges[i].fprev, bv->edges[i].fnext);
6898 std::swap(bv->edges[tot_edges - i - 1].fprev, bv->edges[tot_edges - i - 1].fnext);
6899 }
6900 if (tot_edges % 2 == 1) {
6901 int i = tot_edges / 2;
6902 std::swap(bv->edges[i].fprev, bv->edges[i].fnext);
6903 }
6904 }
6905 }
6906
6907 /* Link the next/prev ring and compute offsets and seam flags for each EdgeHalf. */
6908 for (int i = 0; i < tot_edges; i++) {
6909 EdgeHalf *eh = &bv->edges[i];
6910 eh->next = &bv->edges[(i + 1) % tot_edges];
6911 eh->prev = &bv->edges[(i + tot_edges - 1) % tot_edges];
6912
6913 if (eh->is_bev) {
6914 /* Determine which end of the edge contains this vertex.
6915 * `edges()[e][0]` is the source end and `[1]` is the destination end.
6916 * Left and right offsets are selected from the corresponding index pair.
6917 * Internally we use the convention that "left" and "right" are as seen
6918 * looking towards the vertex of the edge half.
6919 * The external convention, maybe more intuitive to users, is to
6920 * stand looking from source to destination (on the positive normal side),
6921 * so we switch "left" and "right" at the source end.
6922 */
6923 const int2 &ev = emesh.src_edges[eh->e];
6924 const bool at_src = (ev[0] == v);
6925 if (at_src) {
6926 eh->offset_l = state.params.offsets[1][eh->e];
6927 eh->offset_r = state.params.offsets[0][eh->e];
6928 }
6929 else {
6930 eh->offset_l = state.params.offsets[2][eh->e];
6931 eh->offset_r = state.params.offsets[3][eh->e];
6932 }
6933 eh->offset_l_spec = eh->offset_l;
6934 eh->offset_r_spec = eh->offset_r;
6935 }
6936 else if (state.params.affect_type == BevelAffect::Vertices) {
6937 /* Vertex bevel: all edges incident to the selected vertex slide by the same amount.
6938 * offsets[0] is a per-vertex array; index by v to get the slide distance for this vertex.
6939 * offset_r is not used in vertex bevel mode. */
6940 eh->offset_l = eh->offset_l_spec = state.params.offsets[0][v];
6941 eh->offset_r = eh->offset_r_spec = 0.0f;
6942 }
6943 else {
6944 eh->offset_l = eh->offset_l_spec = 0.0f;
6945 eh->offset_r = eh->offset_r_spec = 0.0f;
6946 }
6947
6948 /* An edge half is a seam when its two adjacent faces have discontinuous UV data,
6949 * or when one of those faces is absent (boundary edge). Mirrors the BMesh logic
6950 * in #bev_vert_construct. */
6951 if (eh->fprev != -1 && eh->fnext != -1) {
6952 eh->is_seam = !state.uv_layer_info.contig_uv_maps_across_edge(
6953 emesh, eh->e, eh->fprev, eh->fnext);
6954 }
6955 else {
6956 eh->is_seam = true;
6957 }
6958 }
6959
6960 state.vert_hash.add_new(v, bv);
6961}
6962
6963/* -------------------------------------------------------------------- */
6966
6980 int src_face = -1;
6982};
6983
7000
7006static std::optional<NewCornerInterpData> resolve_new_corner_interp_data(
7007 const ExtendableMesh &emesh, const int nc, const int new_face_fallback)
7008{
7009 const Span<int> face_reps = emesh.new_corner_face_reps();
7010 const int f_src = (face_reps[nc] >= 0) ? face_reps[nc] : new_face_fallback;
7011 if (f_src < 0 || f_src >= emesh.mesh.faces_num) {
7012 return std::nullopt;
7013 }
7014 float3 co = emesh.vert_position(emesh.new_corner_verts()[nc]);
7015 const int snap_e = emesh.new_corner_snap_edges()[nc];
7016 if (snap_e >= 0) {
7017 const int2 ev = emesh.edge_verts(snap_e);
7018 co = math::closest_to_line_segment(co, emesh.vert_position(ev[0]), emesh.vert_position(ev[1]));
7019 }
7020 return NewCornerInterpData{f_src, co};
7021}
7022
7028 const int f_src,
7029 const float3 &co,
7030 MutableSpan<float> weights)
7031{
7032 const IndexRange face_corners = emesh.src_faces[f_src];
7033 BLI_assert(weights.size() == face_corners.size());
7034 const Span<int> face_verts = emesh.src_corner_verts.slice(face_corners);
7035 const float3x3 axis_mat = math::axis_dominant_to_m3(emesh.src_face_normals[f_src]);
7036
7037 Array<float2, 16> cos_2d(face_corners.size());
7038 for (const int i : face_corners.index_range()) {
7039 cos_2d[i] = float2(axis_mat * emesh.src_positions[face_verts[i]]);
7040 }
7041 const float2 co_2d = float2(axis_mat * co);
7042
7043 math::interp_weights_poly(weights, cos_2d, co_2d);
7044}
7045
7047{
7048 const int n_new_corners = int(emesh.new_corner_verts().size());
7050 data.src_faces = Array<int>(n_new_corners, -1);
7051 data.offsets = Array<int>(n_new_corners + 1, 0);
7052 Array<float3> co(n_new_corners, float3(0.0f));
7053
7054 const OffsetIndices new_faces(emesh.new_face_offsets());
7055
7056 /* Pass 1: resolve src_face + query position per corner, and record each corner's weight
7057 * count, so the flattened weights array can be allocated exactly once below. */
7058 for (const int nf : IndexRange(emesh.new_faces_num())) {
7059 const int face_fallback = emesh.new_face_examples()[nf];
7060 for (const int nc : new_faces[nf]) {
7061 const std::optional<NewCornerInterpData> interp_data = resolve_new_corner_interp_data(
7062 emesh, nc, face_fallback);
7063 if (interp_data) {
7064 data.src_faces[nc] = interp_data->src_face;
7065 co[nc] = interp_data->co;
7066 data.offsets[nc] = int(emesh.src_faces[interp_data->src_face].size());
7067 }
7068 }
7069 }
7070
7072 data.offsets);
7073 data.src_corners = Array<int>(corner_offsets.total_size());
7074 data.weights = Array<float>(corner_offsets.total_size());
7075
7076 /* Pass 2: compute weights directly into each corner's slice of the flattened array. */
7077 for (const int nc : IndexRange(n_new_corners)) {
7078 if (data.src_faces[nc] == -1) {
7079 continue;
7080 }
7082 data.src_corners.as_mutable_span().slice(corner_offsets[nc]),
7083 emesh.src_faces[data.src_faces[nc]].start());
7085 data.src_faces[nc],
7086 co[nc],
7087 data.weights.as_mutable_span().slice(corner_offsets[nc]));
7088 }
7089
7090 return data;
7091}
7092
7094 const NewCornerInterpWeights &interp_weights, const GSpan src, GMutableSpan dst)
7095{
7097 OffsetIndices<int>(interp_weights.offsets),
7098 interp_weights.src_corners,
7099 interp_weights.weights.as_span(),
7100 dst);
7101
7102 IndexMaskMemory memory;
7103 const IndexMask corners_no_src = IndexMask::from_predicate(
7104 interp_weights.src_faces.index_range(),
7105 memory,
7106 [&](const int64_t corner) { return interp_weights.src_faces[corner] == -1; },
7107 exec_mode::grain_size(4096));
7108 const CPPType &type = src.type();
7109 type.fill_assign_indices(type.default_value(), dst.data(), corners_no_src);
7110}
7111
7117{
7118 const int num_uv_layers = int(state.uv_layer_info.uv_maps.size());
7119 if (num_uv_layers == 0) {
7120 return;
7121 }
7122 ExtendableMesh &emesh = state.emesh;
7123
7124 Array<Span<float2>> src_uv_layers(num_uv_layers);
7125 Array<MutableSpan<float2>> dst_uv_layers(num_uv_layers);
7126 for (int i = 0; i < num_uv_layers; i++) {
7127 src_uv_layers[i] = state.uv_layer_info.uv_maps[i].values;
7128 dst_uv_layers[i] = emesh.new_corner_uvs(i);
7129 }
7130
7131 for (const int nc : interp_weights.src_faces.index_range()) {
7132 const int src_face = interp_weights.src_faces[nc];
7133 if (src_face == -1) {
7134 continue;
7135 }
7136 const IndexRange face_corners = emesh.src_faces[src_face];
7137 const Span<float> weights = interp_weights.weights_for(nc);
7138 BLI_assert(weights.size() == face_corners.size());
7139 for (const int uv_i : IndexRange(num_uv_layers)) {
7140 float2 result(0.0f);
7141 for (const int i : face_corners.index_range()) {
7142 result += weights[i] * src_uv_layers[uv_i][face_corners[i]];
7143 }
7144 dst_uv_layers[uv_i][nc] = result;
7145 }
7146 }
7147}
7148
7168{
7169 const int num_uv_layers = int(state.uv_layer_info.uv_maps.size());
7170 if (num_uv_layers == 0) {
7171 return;
7172 }
7173
7174 ExtendableMesh &emesh = state.emesh;
7175 const Map<int, Vector<int>> &vert_nc_map = emesh.vert_to_new_corners();
7176 const Map<int, int> &bev_origin = emesh.vert_bev_origin();
7177
7178 /* Build a flat array: nc_face_rep[nc] = representative original face index for new corner nc.
7179 * Used in pass 3 to determine which UV bucket a new corner belongs to. */
7180 const int n_new_corners = int(emesh.new_corner_verts().size());
7181 Array<int> nc_face_rep(n_new_corners, -1);
7182 {
7183 const OffsetIndices new_faces(emesh.new_face_offsets());
7184 const Span<int> new_face_exs = emesh.new_face_examples();
7185 for (const int nf : IndexRange(emesh.new_faces_num())) {
7186 const int f_src = new_face_exs[nf];
7187 for (const int nc : new_faces[nf]) {
7188 nc_face_rep[nc] = f_src;
7189 }
7190 }
7191 }
7192
7193 /* Build a map: (original_face, original_vertex) -> source corner index.
7194 * Used to look up which bucket a new corner's representative face corner at origin_v is in. */
7195 const OffsetIndices src_faces = emesh.src_faces;
7196 const Span<int> src_corner_verts = emesh.src_corner_verts;
7197 /* key = face_idx * mesh.verts_num + vert_idx; value = source corner index. */
7198 Map<int64_t, int> face_vert_to_src_corner;
7199 face_vert_to_src_corner.reserve(emesh.mesh.corners_num);
7200 for (const int f : IndexRange(emesh.mesh.faces_num)) {
7201 for (const int sc : src_faces[f]) {
7202 const int64_t key = int64_t(f) * emesh.mesh.verts_num + src_corner_verts[sc];
7203 face_vert_to_src_corner.add_new(key, sc);
7204 }
7205 }
7206
7207 for (int uv_i = 0; uv_i < num_uv_layers; uv_i++) {
7208 MutableSpan<float2> src_uv_vals = state.uv_layer_info.uv_maps[uv_i].values.as_mutable_span();
7209 MutableSpan<float2> new_uv_vals = emesh.new_corner_uvs(uv_i);
7210
7211 /* --- Pass 1: source corners at original bevel vertices ------------------- */
7212 for (auto item : state.uv_vert_maps[uv_i].items()) {
7213 Vector<UVVertBucket> &uv_vert_buckets = item.value;
7214 for (UVVertBucket &bucket : uv_vert_buckets) {
7215 if (bucket.size() <= 1) {
7216 continue;
7217 }
7218 float2 avg(0.0f);
7219 for (const int src_c : bucket) {
7220 avg += src_uv_vals[src_c];
7221 }
7222 avg /= float(bucket.size());
7223 for (const int src_c : bucket) {
7224 src_uv_vals[src_c] = avg;
7225 }
7226 }
7227 }
7228
7229 /* --- Pass 3: new (profile-arc) vertices ---------------------------------- */
7230 for (const auto &[nv, new_corners] : vert_nc_map.items()) {
7231 if (nv < emesh.mesh.verts_num) {
7232 continue;
7233 }
7234 if (new_corners.size() <= 1) {
7235 continue;
7236 }
7237
7238 /* Find the parent bevel vertex for this arc vertex. */
7239 const int *origin_v_ptr = bev_origin.lookup_ptr(nv);
7240 if (origin_v_ptr == nullptr) {
7241 continue;
7242 }
7243 const int origin_v = *origin_v_ptr;
7244
7245 /* Look up the UV buckets for the parent vertex on this layer. */
7246 const Vector<UVVertBucket> *buckets = state.uv_vert_maps[uv_i].lookup_ptr(origin_v);
7247 if (buckets == nullptr) {
7248 continue;
7249 }
7250
7251 /* For each new corner, determine which bucket its face representative's source corner
7252 * at origin_v belongs to. Use a simple scan since bucket count is tiny (<= valence). */
7253 for (const UVVertBucket &bucket : *buckets) {
7254 /* Collect new corners in this bucket: their face rep has a source corner at origin_v
7255 * that is in this bucket. */
7256 Vector<int> matching;
7257 for (const int nc : new_corners) {
7258 const int f_rep = nc_face_rep[nc];
7259 if (f_rep < 0 || f_rep >= emesh.mesh.faces_num) {
7260 continue;
7261 }
7262 const int64_t key = int64_t(f_rep) * emesh.mesh.verts_num + origin_v;
7263 const int *src_c_ptr = face_vert_to_src_corner.lookup_ptr(key);
7264 if (src_c_ptr == nullptr) {
7265 continue;
7266 }
7267 if (bucket.contains(*src_c_ptr)) {
7268 matching.append(nc);
7269 }
7270 }
7271 if (matching.size() <= 1) {
7272 continue;
7273 }
7274 float2 avg(0.0f);
7275 for (const int nc : matching) {
7276 avg += new_uv_vals[nc];
7277 }
7278 avg /= float(matching.size());
7279 for (const int nc : matching) {
7280 new_uv_vals[nc] = avg;
7281 }
7282 }
7283 }
7284 }
7285}
7286
7287/* Extend edge data (seam, sharp, bevel_weight) to boundary arc edges.
7288 * Mirrors BMesh's #bevel_extend_edge_data / #bevel_extend_edge_data_ex.
7289 *
7290 * For each BevVert, walk the BoundVert ring. When a BoundVert has seam_len > 0
7291 * (or sharp_len > 0), the boundary arc edges for the next `seam_len` BoundVerts
7292 * need to be marked. We do this by setting their example edge to the original
7293 * beveled edge that has the corresponding property (seam, bevel_weight, etc.).
7294 *
7295 * BMesh does this by directly setting BM_ELEM_SEAM / BM_ELEM_SMOOTH flags.
7296 * In the GN system, we use edge_set_example to propagate all edge attributes
7297 * from the original edge that carries the flag. */
7299{
7300 for (auto bv_entry : state.vert_hash.items()) {
7301 BevVert *bv = bv_entry.value;
7302 if (!bv || !bv->vmesh) {
7303 continue;
7304 }
7305 VMesh *vm = bv->vmesh.get();
7306 if (vm->mesh_kind == MeshKind::TriFan || bv->selcount < 2) {
7307 continue;
7308 }
7309
7310 /* Find an original edge with the seam property to use as example.
7311 * This is the edge e such that e->rightv == bcur (the BoundVert with seam_len > 0).
7312 * In #check_edge_data_seam_sharp_edges, seam_len is set on e->rightv,
7313 * where e is the EdgeHalf that HAS the seam property. So the example edge is e->e. */
7314 auto find_example_edge_for_flag = [&](BoundVert *bcur, bool is_seam_flag) -> int {
7315 for (int ei = 0; ei < bv->edgecount; ei++) {
7316 EdgeHalf *eh = &bv->edges[ei];
7317 if (eh->rightv == bcur) {
7318 return eh->e;
7319 }
7320 }
7321 (void)is_seam_flag;
7322 return -1;
7323 };
7324
7325 /* Helper: walk boundary arcs from `bcur` for `extend_len` BoundVerts,
7326 * setting the example edge on each arc and spoke edge. */
7327 auto extend_arcs = [&](BoundVert *&bcur, int extend_len, int example) {
7328 const int idx_end = bcur->index + extend_len;
7329 for (int i = bcur->index; i < idx_end; i++) {
7330 for (int k = 0; k < vm->seg; k++) {
7331 const int va = geom::mesh_vert(vm, i % vm->count, 0, k)->v;
7332 const int vb = geom::mesh_vert(vm, i % vm->count, 0, k + 1)->v;
7333 if (va >= 0 && vb >= 0) {
7334 const int arc_edge = state.emesh.find_edge(va, vb);
7335 if (arc_edge >= 0 && example >= 0) {
7336 state.emesh.edge_set_example(arc_edge, example);
7337 }
7338 }
7339 }
7340 const int va = geom::mesh_vert(vm, i % vm->count, 0, vm->seg)->v;
7341 const int vb = geom::mesh_vert(vm, (i + 1) % vm->count, 0, 0)->v;
7342 if (va >= 0 && vb >= 0) {
7343 const int spoke_edge = state.emesh.find_edge(va, vb);
7344 if (spoke_edge >= 0 && example >= 0) {
7345 state.emesh.edge_set_example(spoke_edge, example);
7346 }
7347 }
7348 bcur = bcur->next;
7349 }
7350 };
7351
7352 /* Process seam extension. */
7353 BoundVert *bcur = vm->boundstart;
7354 BoundVert *start = bcur;
7355 do {
7356 const int extend_len = bcur->seam_len;
7357 if (extend_len > 0) {
7358 if (!vm->boundstart->seam_len && start == vm->boundstart) {
7359 start = bcur;
7360 }
7361 const int example = find_example_edge_for_flag(bcur, true);
7362 extend_arcs(bcur, extend_len, example);
7363 }
7364 else {
7365 bcur = bcur->next;
7366 }
7367 } while (bcur != start);
7368
7369 /* Process sharp extension (analogous, using sharp_len). */
7370 bcur = vm->boundstart;
7371 start = bcur;
7372 do {
7373 const int extend_len = bcur->sharp_len;
7374 if (extend_len > 0) {
7375 if (!vm->boundstart->sharp_len && start == vm->boundstart) {
7376 start = bcur;
7377 }
7378 const int example = find_example_edge_for_flag(bcur, false);
7379 extend_arcs(bcur, extend_len, example);
7380 }
7381 else {
7382 bcur = bcur->next;
7383 }
7384 } while (bcur != start);
7385 }
7386}
7387
7389 const GVArray &src,
7390 const IndexMask &edges_new_no_src,
7392{
7393 const CommonVArrayInfo src_info = src.common_info();
7394 if (src_info.type != CommonVArrayInfo::Type::Single) {
7395 return false;
7396 }
7397
7398 if (iter.domain == bke::AttrDomain::Edge && !edges_new_no_src.is_empty()) {
7399 /* A non-default single edge value cannot be kept when source-less new edges must get the
7400 * type default value. */
7401 const CPPType &type = src.type();
7402 if (!type.is_equal_or_false(src_info.data, type.default_value())) {
7403 return false;
7404 }
7405 }
7406
7407 const GPointer value(src.type(), src_info.data);
7408 dst_attrs.add(iter.name, iter.domain, iter.data_type, bke::AttributeInitValue(value));
7409 return true;
7410}
7411
7412static std::optional<Mesh *> build_output_mesh(const BevelState &state,
7413 const NewCornerInterpWeights &interp_weights,
7414 const bke::AttributeFilter &attribute_filter)
7415{
7416 const ExtendableMesh &emesh = state.emesh;
7417 const Mesh &src_mesh = emesh.mesh;
7418
7419 /* Collect surviving original element masks from the kill arrays. */
7420 IndexMaskMemory memory;
7421 const IndexMask src_survive_verts = IndexMask::from_bools(emesh.kill_verts_array(), memory)
7422 .complement(IndexMask(src_mesh.verts_num), memory);
7423 const IndexMask src_survive_edges = IndexMask::from_bools(emesh.kill_edges_array(), memory)
7424 .complement(IndexMask(src_mesh.edges_num), memory);
7425 const IndexMask src_survive_faces = IndexMask::from_bools(emesh.kill_faces_array(), memory)
7426 .complement(IndexMask(src_mesh.faces_num), memory);
7427
7428 /* Build old->new index maps for surviving original elements; -1 for killed entries. */
7429 Array<int> src_vert_map(src_mesh.verts_num, -1);
7430 index_mask::build_reverse_map(src_survive_verts, src_vert_map.as_mutable_span());
7431 Array<int> src_edge_map(src_mesh.edges_num, -1);
7432 index_mask::build_reverse_map(src_survive_edges, src_edge_map.as_mutable_span());
7433
7434 /* Count surviving corners: only corners in surviving original faces are kept. */
7435 const Span<float3> src_positions = src_mesh.vert_positions();
7436 const Span<int2> src_edges = src_mesh.edges();
7437 const OffsetIndices<int> src_faces = src_mesh.faces();
7438 const Span<int> src_corner_verts = src_mesh.corner_verts();
7439 const Span<int> src_corner_edges = src_mesh.corner_edges();
7440
7441 const int n_surv_verts = src_survive_verts.size();
7442 const int n_surv_edges = src_survive_edges.size();
7443 const int n_surv_faces = src_survive_faces.size();
7444 const int n_surv_corners = offset_indices::sum_group_sizes(src_faces, src_survive_faces);
7445
7446 const Span<float3> new_positions = emesh.new_vert_positions();
7447 const Span<int2> new_edge_data = emesh.new_edges();
7448 const Span<int> new_face_offs = emesh.new_face_offsets(); /* size = new_faces_num + 1 */
7449 const Span<int> new_corner_verts = emesh.new_corner_verts();
7450 const Span<int> new_corner_edges = emesh.new_corner_edges();
7451 const int n_new_verts = int(new_positions.size());
7452 const int n_new_edges = int(new_edge_data.size());
7453 const int n_new_faces = emesh.new_faces_num();
7454 const int n_new_corners = int(new_corner_verts.size());
7455
7456 Mesh *dst = BKE_mesh_new_nomain(n_surv_verts + n_new_verts,
7457 n_surv_edges + n_new_edges,
7458 n_surv_faces + n_new_faces,
7459 n_surv_corners + n_new_corners);
7460 BKE_mesh_copy_parameters_for_eval(dst, &src_mesh);
7461
7462 MutableSpan<float3> dst_positions = dst->vert_positions_for_write();
7463 MutableSpan<int2> dst_edges = dst->edges_for_write();
7464 MutableSpan<int> dst_face_offsets = dst->face_offsets_for_write();
7465 MutableSpan<int> dst_corner_verts = dst->corner_verts_for_write();
7466 MutableSpan<int> dst_corner_edges = dst->corner_edges_for_write();
7467
7468 /* Maps any combined (original + new) vertex index to the destination index. */
7469 auto mixed_vert_map = [&](const int v) -> int {
7470 if (v < src_mesh.verts_num) {
7471 return src_vert_map[v];
7472 }
7473 return n_surv_verts + (v - src_mesh.verts_num);
7474 };
7475 /* Maps any combined (original + new) edge index to the destination index. */
7476 auto mixed_edge_map = [&](const int e) -> int {
7477 if (e < src_mesh.edges_num) {
7478 return src_edge_map[e];
7479 }
7480 return n_surv_edges + (e - src_mesh.edges_num);
7481 };
7482
7483 /* Surviving original vert positions and new positions. */
7485 src_positions, src_survive_verts, dst_positions.take_front(src_survive_verts.size()));
7486 dst_positions.take_back(new_positions.size()).copy_from(new_positions);
7487
7488 /* Surviving original edges (vertex pairs remapped to destination indices) and new edges. */
7489 src_survive_edges.foreach_index([&](const int64_t src_e, const int64_t dst_e) {
7490 dst_edges[dst_e][0] = src_vert_map[src_edges[src_e][0]];
7491 dst_edges[dst_e][1] = src_vert_map[src_edges[src_e][1]];
7492 });
7493 for (const int ne : IndexRange(n_new_edges)) {
7494 dst_edges[n_surv_edges + ne][0] = mixed_vert_map(new_edge_data[ne][0]);
7495 dst_edges[n_surv_edges + ne][1] = mixed_vert_map(new_edge_data[ne][1]);
7496 }
7497
7498 /* Face offsets. */
7500 src_faces, src_survive_faces, dst_face_offsets.take_front(src_survive_faces.size() + 1));
7501 for (const int nf : IndexRange(n_new_faces)) {
7502 dst_face_offsets[n_surv_faces + nf] = n_surv_corners + new_face_offs[nf];
7503 }
7504 /* Sentinel at the end (Blender stores offsets as face_offsets[face_num] = corners_num). */
7505 if (!dst_face_offsets.is_empty()) {
7506 dst_face_offsets[n_surv_faces + n_new_faces] = n_surv_corners + new_face_offs[n_new_faces];
7507 }
7508
7509 const OffsetIndices<int> dst_faces(dst_face_offsets);
7510
7511 /* Corner data. */
7512 src_survive_faces.foreach_index(
7513 [&](const int64_t src_f, const int64_t dst_f) {
7514 const IndexRange src_face = src_faces[src_f];
7515 const IndexRange dst_face = dst_faces[dst_f];
7516 for (const int i : src_face.index_range()) {
7517 dst_corner_verts[dst_face[i]] = src_vert_map[src_corner_verts[src_face[i]]];
7518 dst_corner_edges[dst_face[i]] = src_edge_map[src_corner_edges[src_face[i]]];
7519 }
7520 },
7522 for (const int nc : IndexRange(n_new_corners)) {
7523 dst_corner_verts[n_surv_corners + nc] = mixed_vert_map(new_corner_verts[nc]);
7524 dst_corner_edges[n_surv_corners + nc] = mixed_edge_map(new_corner_edges[nc]);
7525 }
7526
7527 const bke::AttributeAccessor src_attrs = src_mesh.attributes();
7528 bke::MutableAttributeAccessor dst_attrs = dst->attributes_for_write();
7529 const VectorSet<StringRefNull> uv_names = src_mesh.uv_map_names();
7530
7531 const Span<int> vert_src_by_dst = emesh.new_vert_examples();
7532 const IndexMask verts_new_with_src = array_utils::indices_non_negative(
7533 vert_src_by_dst.index_range(), vert_src_by_dst, memory);
7534 const IndexMask verts_new_no_src = verts_new_with_src.complement(vert_src_by_dst.index_range(),
7535 memory);
7536
7537 const Span<int> edge_src_by_dst = emesh.new_edge_examples();
7538 const IndexMask edges_new_with_src = array_utils::indices_non_negative(
7539 edge_src_by_dst.index_range(), edge_src_by_dst, memory);
7540 const IndexMask edges_new_no_src = edges_new_with_src.complement(edge_src_by_dst.index_range(),
7541 memory);
7542
7543 const Span<int> face_src_by_dst = emesh.new_face_examples();
7544 const IndexMask faces_new_with_src = array_utils::indices_non_negative(
7545 face_src_by_dst.index_range(), face_src_by_dst, memory);
7546 const IndexMask face_new_no_src = faces_new_with_src.complement(face_src_by_dst.index_range(),
7547 memory);
7548
7549 src_attrs.foreach_attribute([&](const bke::AttributeIter &iter) {
7550 if (iter.data_type == bke::AttrType::String) {
7551 return;
7552 }
7553 if (ELEM(iter.name, "position", ".edge_verts", ".corner_vert", ".corner_edge")) {
7554 return;
7555 }
7556 if (uv_names.contains(iter.name)) {
7557 return;
7558 }
7559 if (attribute_filter.allow_skip(iter.name)) {
7560 return;
7561 }
7562 const GVArray src = *iter.get();
7563 const CPPType &type = src.type();
7564 if (try_propagate_single_value(iter, src, edges_new_no_src, dst_attrs)) {
7565 return;
7566 }
7568 iter.name, iter.domain, iter.data_type);
7569 switch (iter.domain) {
7571 GMutableSpan surv_values = dst.span.take_front(n_surv_verts);
7572 GMutableSpan new_values = dst.span.take_back(n_new_verts);
7573 array_utils::gather(src, src_survive_verts, surv_values);
7574 bke::attribute_math::gather(src, vert_src_by_dst, verts_new_with_src, new_values);
7575 type.fill_assign_indices(type.default_value(), new_values.data(), verts_new_no_src);
7576 break;
7577 }
7578 case bke::AttrDomain::Edge: {
7579 GMutableSpan surv_values = dst.span.take_front(n_surv_edges);
7580 GMutableSpan new_values = dst.span.take_back(n_new_edges);
7581 array_utils::gather(src, src_survive_edges, surv_values);
7582 bke::attribute_math::gather(src, edge_src_by_dst, edges_new_with_src, new_values);
7583 type.fill_assign_indices(type.default_value(), new_values.data(), edges_new_no_src);
7584 break;
7585 }
7586 case bke::AttrDomain::Face: {
7587 GMutableSpan surv_values = dst.span.take_front(n_surv_faces);
7588 GMutableSpan new_values = dst.span.take_back(n_new_faces);
7589 array_utils::gather(src, src_survive_faces, surv_values);
7590 bke::attribute_math::gather(src, face_src_by_dst, faces_new_with_src, new_values);
7591 type.fill_assign_indices(type.default_value(), new_values.data(), face_new_no_src);
7592 break;
7593 }
7595 const GVArraySpan src_span(src);
7596 GMutableSpan surv_values = dst.span.take_front(n_surv_corners);
7597 GMutableSpan new_values = dst.span.take_back(n_new_corners);
7598
7600 src_faces, dst_faces, src_survive_faces, src_span, surv_values);
7601
7602 interpolate_new_corner_attribute_from_faces(interp_weights, src_span, new_values);
7603
7604 break;
7605 }
7606 default:
7608 break;
7609 }
7610
7611 dst.finish();
7612 });
7613
7614 /* Apply per-edge seam/sharp overrides, matching BMesh's post-copy fixup
7615 * that undoes seam/smooth on corner segments where those flags are not contiguous.
7616 * Only apply if the attribute already exists (created by gather_attributes above). */
7617
7618 if (bke::SpanAttributeWriter<bool> seam_writer = dst_attrs.lookup_for_write_span<bool>(
7619 "uv_seam"))
7620 {
7621 MutableSpan<bool> seam_span = seam_writer.span;
7622 for (const int ni : IndexRange(n_new_edges)) {
7623 const int8_t ov = emesh.new_edge_seam_overrides()[ni];
7624 if (ov >= 0) {
7625 seam_span[n_surv_edges + ni] = (ov == 1);
7626 }
7627 }
7628 seam_writer.finish();
7629 }
7630
7631 if (bke::SpanAttributeWriter<bool> sharp_writer = dst_attrs.lookup_for_write_span<bool>(
7632 "sharp_edge"))
7633 {
7634 MutableSpan<bool> sharp_span = sharp_writer.span;
7635 for (const int ni : IndexRange(n_new_edges)) {
7636 const int8_t ov = emesh.new_edge_sharp_overrides()[ni];
7637 if (ov >= 0) {
7638 sharp_span[n_surv_edges + ni] = (ov == 1);
7639 }
7640 }
7641 sharp_writer.finish();
7642 }
7643
7644 /* Write precomputed UV values for new corners into the output mesh. */
7645 for (const int i : state.uv_layer_info.uv_maps.index_range()) {
7646 const StringRef name = state.uv_layer_info.uv_maps[i].name;
7647 const VArraySpan src_uvs = *src_attrs.lookup<float2>(name, bke::AttrDomain::Corner);
7650 if (!dst_uvs) {
7651 continue;
7652 }
7654 src_faces, dst_faces, src_survive_faces, src_uvs, dst_uvs.span.take_front(n_surv_corners));
7655 array_utils::copy(emesh.new_corner_uvs(i), dst_uvs.span.take_back(n_new_corners));
7656 dst_uvs.finish();
7657 }
7658
7659 /* Write #BevelAttributeOutputs fields into the output mesh.
7660 *
7661 * Each output is guarded by the optional attribute ID: if the GN output socket is not
7662 * connected, `get_output_anonymous_attribute_id_if_needed` returns `std::nullopt` and no
7663 * memory is allocated or written here.
7664 *
7665 * - vertex_face_id : Face domain - true for every new face tagged VERTEX_FACE.
7666 * - edge_face_id : Face domain - true for every new face tagged EDGE_FACE.
7667 * - outer_edge_id : Edge domain - true for the two outermost edges of each bevel strip.
7668 * - mid_edge_id : Edge domain - true for the mid-ring edge of each strip (nseg >= 2 only). */
7669 const BevelAttributeOutputs &ao = state.params.attribute_outputs;
7670
7671 if (ao.vertex_face_id || ao.edge_face_id) {
7672 const Span<NewFaceKind> face_kinds = emesh.new_face_kinds();
7673 if (ao.vertex_face_id) {
7676 for (const int nf : IndexRange(n_new_faces)) {
7677 writer.span[n_surv_faces + nf] = (face_kinds[nf] == NewFaceKind::VertexFace);
7678 }
7679 writer.finish();
7680 }
7681 if (ao.edge_face_id) {
7684 for (const int nf : IndexRange(n_new_faces)) {
7685 writer.span[n_surv_faces + nf] = (face_kinds[nf] == NewFaceKind::EdgeFace);
7686 }
7687 writer.finish();
7688 }
7689 }
7690
7691 if (ao.outer_edge_id) {
7694 /* Outer edges are surviving original edges, identified via src_edge_map. */
7695 for (const int se : state.outer_edge_src_indices) {
7696 const int dst_e = src_edge_map[se];
7697 if (dst_e >= 0) {
7698 writer.span[dst_e] = true;
7699 }
7700 }
7701 /* Also check new edges tagged as OUTER_EDGE (can happen when the outer edge is new). */
7702 const Span<NewEdgeKind> edge_kinds = emesh.new_edge_kinds();
7703 for (const int ne : IndexRange(n_new_edges)) {
7704 if (edge_kinds[ne] == NewEdgeKind::OuterEdge) {
7705 writer.span[n_surv_edges + ne] = true;
7706 }
7707 }
7708 writer.finish();
7709 }
7710
7711 if (ao.mid_edge_id) {
7714 const Span<NewEdgeKind> edge_kinds = emesh.new_edge_kinds();
7715 for (const int ne : IndexRange(n_new_edges)) {
7716 if (edge_kinds[ne] == NewEdgeKind::MidEdge) {
7717 writer.span[n_surv_edges + ne] = true;
7718 }
7719 }
7720 writer.finish();
7721 }
7722
7724 return dst;
7725}
7726
7728
7729} // namespace construct
7730
7731std::optional<Mesh *> mesh_bevel(const Mesh &src_mesh,
7732 const IndexMask &selection,
7733 const BevelParameters &params,
7734 const bke::AttributeFilter &attribute_filter)
7735{
7736 auto all_non_positive = [](const Span<float> span) {
7737 return std::ranges::all_of(span, [](float value) { return value <= 0.0f; });
7738 };
7739 if (all_non_positive(params.offsets[0]) && all_non_positive(params.offsets[1]) &&
7740 all_non_positive(params.offsets[2]) && all_non_positive(params.offsets[3]))
7741 {
7742 return std::nullopt;
7743 }
7744
7745#ifdef DEBUG_TIME
7746 fmt::println("BEVEL NODE starts");
7747 const timeit::TimePoint start_time = timeit::Clock::now();
7748#endif
7749 BevelState state(src_mesh, params, selection);
7750 if (state.bevel_affected_vertices.size() == 0) {
7751 return std::nullopt;
7752 }
7753 state.initialize_profile_data();
7754 state.uv_init();
7755
7756 state.bev_verts.reserve(state.bevel_affected_vertices.size());
7757#ifdef DEBUG_TIME
7758 const timeit::TimePoint init_time = timeit::Clock::now();
7759 fmt::println("BEVEL NODE initialization, {:.4} ms", (init_time - start_time).count() / 1.0e6f);
7760#endif
7761
7762 /* Phase 1: construct BevVerts and build initial boundaries. */
7763 state.bevel_affected_vertices.foreach_index([&](const int v) {
7765 BevVert *bv = state.vert_hash.lookup_default(v, nullptr);
7766 if (bv) {
7768 }
7769 });
7770
7771#ifdef DEBUG_TIME
7772 const timeit::TimePoint vert_and_boundaries_time = timeit::Clock::now();
7773 fmt::println("BEVEL NODE bevel construct and build boundaries,{:.4} ms",
7774 (vert_and_boundaries_time - init_time).count() / 1.0e6f);
7775#endif
7776
7777 /* Maintain consistent orientations for the asymmetrical custom profiles. */
7778 if (!params.custom_profile_samples.is_empty() && params.affect_type != BevelAffect::Vertices) {
7779 state.selection.foreach_index(
7780 [&](const int e) { construct::regularize_profile_orientation(state, e); });
7781 }
7782
7783#ifdef DEBUG_TIME
7784 const timeit::TimePoint adjust_time = timeit::Clock::now();
7785 fmt::println("BEVEL NODE adjust offsets, {:.4} ms",
7786 (adjust_time - vert_and_boundaries_time).count() / 1.0e6f);
7787#endif
7788
7789 /* Phase 3: UV connectivity and vmesh construction (depends on final BoundVert positions). */
7790 state.bevel_affected_vertices.foreach_index([&](const int v) {
7791 BevVert *bv = state.vert_hash.lookup_default(v, nullptr);
7792 if (!bv) {
7793 return;
7794 }
7796 /* Record the number of new faces before build_vmesh so that all faces it creates can
7797 * be tagged as #NewFaceKind::VERTEX_FACE for the #BevelAttributeOutputs output field. */
7798 const int faces_before = state.emesh.new_faces_num();
7800 const int faces_after = state.emesh.new_faces_num();
7801 MutableSpan<NewFaceKind> kinds = state.emesh.new_face_kinds();
7802 for (int nf = faces_before; nf < faces_after; nf++) {
7803 kinds[nf] = NewFaceKind::VertexFace;
7804 }
7805 });
7806
7807#ifdef DEBUG_TIME
7808 const timeit::TimePoint vmesh_and_uv_time = timeit::Clock::now();
7809 fmt::println("BEVEL NODE vmesh and uv connectivity, {:.4} ms",
7810 (vmesh_and_uv_time - vert_and_boundaries_time).count() / 1.0e6f);
7811#endif
7812
7813 /* Build edge-strip polygons along each beveled edge. */
7814 if (params.affect_type != BevelAffect::Vertices) {
7815 state.selection.foreach_index(
7816 [&](const int e) { construct::bevel_build_edge_polygons(state, e); });
7817 }
7818
7819#ifdef DEBUG_TIME
7820 const timeit::TimePoint edge_time = timeit::Clock::now();
7821 fmt::println("BEVEL NODE edge mesh, {:.4} ms", (edge_time - vmesh_and_uv_time).count() / 1.0e6f);
7822#endif
7823
7824 /* Rebuild original faces that touch beveled vertices. */
7825 Vector<int> rebuilt_orig_faces;
7826 int rebuilt_face_0 = -1;
7827 construct::bevel_rebuild_existing_polygons(state, rebuilt_orig_faces, rebuilt_face_0);
7828
7829#ifdef DEBUG_TIME
7830 const timeit::TimePoint face_time = timeit::Clock::now();
7831 fmt::println("BEVEL NODE face mesh, {:.4} ms", (face_time - edge_time).count() / 1.0e6f);
7832#endif
7833
7834 /* Kill the original faces that were rebuilt, mirroring BMesh's deferred kill pattern. */
7835 for (const int f : rebuilt_orig_faces) {
7836 state.emesh.face_kill(f);
7837 }
7838
7839 /* Kill original beveled vertices. */
7840 state.bevel_affected_vertices.foreach_index([&](const int v) { state.emesh.vert_kill(v); });
7841
7842 const construct::NewCornerInterpWeights new_corner_interp_weights =
7844
7845 /* Interpolate UV values for new corners, then merge at seam vertices. */
7846 if (state.uv_layer_info.has_uv_maps) {
7847 construct::fill_new_corner_uvs(state, new_corner_interp_weights);
7848#ifdef BEVEL_DEBUG
7849 {
7850 /* After fill, before merge: dump per-corner UV values for all new faces. */
7851 const OffsetIndices new_faces(state.emesh.new_face_offsets());
7852 const Span<int> ncv = state.emesh.new_corner_verts();
7853 for (int nf = 0; nf < state.emesh.new_faces_num(); nf++) {
7854 const IndexRange nc_range = new_faces[nf];
7855 fmt::println("new_face[{}] (corners {}-{}):",
7856 nf + state.emesh.mesh.faces_num,
7857 nc_range.start(),
7858 nc_range.last());
7859 for (const int uv_i : state.uv_layer_info.uv_maps.index_range()) {
7860 const Span<float2> new_uv = state.emesh.new_corner_uvs(uv_i);
7861 for (const int nc : nc_range) {
7862 fmt::println(" uv_i={} corner={} v={} uv=({:.5f},{:.5f})",
7863 uv_i,
7864 nc,
7865 ncv[nc],
7866 new_uv[nc].x,
7867 new_uv[nc].y);
7868 }
7869 }
7870 }
7871 }
7872#endif
7873#ifndef BEVEL_DEBUG_SKIP_MERGE_UVS
7875#else
7876 fmt::println("merge_uvs SKIPPED (BEVEL_DEBUG_SKIP_MERGE_UVS)");
7877#endif
7878 }
7879
7881
7882#ifdef DEBUG_TIME
7883 const timeit::TimePoint uv_edge_data_time = timeit::Clock::now();
7884 fmt::println("BEVEL NODE uvs and edge data, {:.4} ms",
7885 (uv_edge_data_time - face_time).count() / 1.0e6f);
7886#endif
7887
7888 std::optional<Mesh *> ans = construct::build_output_mesh(
7889 state, new_corner_interp_weights, attribute_filter);
7890
7891#ifdef DEBUG_TIME
7892 const timeit::TimePoint end_time = timeit::Clock::now();
7893 fmt::println("BEVEL NODE construct output mesh, {:.4} ms",
7894 (end_time - uv_edge_data_time).count() / 1.0e6f);
7895 fmt::println("BEVEL NODE total, {:5} ms", (end_time - start_time).count() / 1.0e6f);
7896#endif
7897
7898 return ans;
7899}
7900
7901} // namespace blender::geometry
#define STD_UV_CONNECT_LIMIT
#define M_SQRT3
#define DEG2RADF(_deg)
#define M_SQRT2
#define M_SQRT1_3
#define M_PI_2
#define M_PI
#define M_PI_4
#define BLI_assert_unreachable()
#define ELEM(...)
#define VEC_VALUE_LEN
SIMD_FORCE_INLINE const btScalar & z() const
Return the z value.
Definition btQuadWord.h:117
SIMD_FORCE_INLINE btVector3 dot3(const btVector3 &v0, const btVector3 &v1, const btVector3 &v2) const
Definition btVector3.h:720
Span< T > as_span() const
Definition BLI_array.hh:254
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
const T * data() const
Definition BLI_array.hh:323
IndexRange index_range() const
Definition BLI_array.hh:371
bool is_empty() const
Definition BLI_array.hh:275
void fill_assign_indices(const void *value, void *dst, const IndexMask &mask) const
bool is_equal_or_false(const void *a, const void *b) const
const void * default_value() const
GMutableSpan take_front(const int64_t n) const
GMutableSpan take_back(const int64_t n) const
const CPPType & type() const
CommonVArrayInfo common_info() const
static IndexMask from_predicate(const IndexMask &universe, LinearAllocator<> &memory, Fn &&predicate, exec_mode::Mode mode=exec_mode::parallel)
static IndexMask from_bools(Span< bool > bools, LinearAllocator<> &memory)
constexpr int64_t first() const
constexpr int64_t last(const int64_t n=0) const
constexpr int64_t size() const
constexpr IndexRange()=default
constexpr int64_t start() const
constexpr IndexRange index_range() const
const Value * lookup_ptr(const Key &key) const
Definition BLI_map.hh:508
void add_new(const Key &key, const Value &value)
Definition BLI_map.hh:265
void reserve(int64_t n)
Definition BLI_map.hh:1028
ItemIterator items() const &
Definition BLI_map.hh:902
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr bool is_empty() const
Definition BLI_span.hh:515
constexpr MutableSpan take_back(const int64_t n) const
Definition BLI_span.hh:646
constexpr void copy_from(Span< T > values) const
Definition BLI_span.hh:745
constexpr MutableSpan take_front(const int64_t n) const
Definition BLI_span.hh:635
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
constexpr bool is_empty() const
Definition BLI_span.hh:264
constexpr bool contains(const T &value) const
Definition BLI_span.hh:281
static VArray from_span(Span< T > values)
bool contains(const Key &key) const
int64_t size() const
void append(const T &value)
bool is_empty() const
void reserve(const int64_t min_capacity)
Span< T > as_span() const
void foreach_attribute(const FunctionRef< void(const AttributeIter &)> fn) const
GAttributeReader lookup(const StringRef name) const
GAttributeReader get() const
bool add(const StringRef name, const AttrDomain domain, const AttrType data_type, const AttributeInit &initializer)
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
GSpanAttributeWriter lookup_or_add_for_write_only_span(StringRef name, AttrDomain domain, AttrType data_type)
GSpanAttributeWriter lookup_for_write_span(StringRef name)
constexpr bool is_empty() const
constexpr Span take_front(int64_t n) const
constexpr int64_t size() const
GroupedSpan< int > src_edge_to_face
void tag_last_face(const NewFaceKind kind)
void face_set_corner_reps(int face_idx, Span< int > face_reps, Span< int > snap_edges)
Span< NewFaceKind > new_face_kinds() const
Span< int > new_corner_snap_edges() const
GroupedSpan< int > src_vert_to_corner
void edge_set_sharp_override(const int edge_index, int8_t value)
void edge_set_example(const int edge_index, const int example_edge)
Span< bool > kill_edges_array() const
bool is_corner_killed(const int c) const
void edge_set_seam_override(const int edge_index, int8_t value)
int corner_vert(const int c) const
Span< int8_t > new_edge_sharp_overrides() const
void init_uv_storage(int uv_layers_num)
int2 edge_verts(const int e) const
Span< bool > kill_faces_array() const
Span< float3 > new_vert_positions() const
OffsetIndices< int > src_faces
Span< int > new_corner_verts() const
Span< bool > kill_verts_array() const
Span< float2 > new_corner_uvs(int layer_index) const
int face_create(Span< int > verts, int example_face=-1)
MutableSpan< NewFaceKind > new_face_kinds()
Span< int > new_edge_examples() const
Span< int2 > new_edges() const
int vert_create(const float3 &co, int example_vert=-1)
IndexRange face_corners(const int f) const
Span< int > new_face_offsets() const
int find_edge(const int v1, const int v2) const
bool is_edge_killed(const int e) const
const Map< int, Vector< int > > & vert_to_new_corners() const
void tag_edge_kind(const int edge_index, const NewEdgeKind kind)
Span< int > new_vert_examples() const
Span< int > new_corner_face_reps() const
bool is_vert_killed(const int v) const
const Map< int, int > & vert_bev_origin() const
Span< int > new_corner_edges() const
Span< int > new_face_examples() const
GroupedSpan< int > src_vert_to_edge
Span< int8_t > new_edge_seam_overrides() const
MutableSpan< float2 > new_corner_uvs(int layer_index)
float3 vert_position(const int v) const
int corner_edge(const int c) const
Span< NewEdgeKind > new_edge_kinds() const
bool is_face_killed(const int f) const
int edge_create(const int v1, const int v2, int example_edge=-1)
Span< bool > kill_corners_array() const
bool contig_uv_maps_across_edge(const ExtendableMesh &mesh, int e, int f1, int f2) const
bool contig_uv_maps_around_vert(const ExtendableMesh &emesh, int v) const
void init(const Mesh &mesh)
void find_components(const ExtendableMesh &emesh)
void foreach_index(Fn &&fn, Mode mode=exec_mode::serial) const
IndexMask complement(const IndexMask &universe, LinearAllocator<> &memory) const
CCL_NAMESPACE_BEGIN ccl_device_inline float frac(const float x, ccl_private int *ix)
#define powf(x, y)
#define pow
#define cos
#define abs
VecBase< float, 3 > cross(VecOp< float, 3 >, VecOp< float, 3 >) RET
const int state
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
void gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
IndexMask indices_non_negative(const IndexMask &universe, Span< int > values, LinearAllocator<> &memory)
void copy(const GVArray &src, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
BooleanMix booleans_mix_calc(const VArray< bool > &varray, IndexRange range_to_check)
void fill_index_range(MutableSpan< T > span, const T start=0)
void gather(GSpan src, Span< int > map, GMutableSpan dst)
void gather_group_to_group(OffsetIndices< int > src_offsets, OffsetIndices< int > dst_offsets, const IndexMask &selection, GSpan src, GMutableSpan dst)
void mix_groups(GSpan src, OffsetIndices< int > groups, Span< int > all_indices, std::optional< Span< float > > all_weights, GMutableSpan dst)
GroupedSpan< int > build_edge_to_face_map(OffsetIndices< int > faces, Span< int > corner_edges, int edges_num, Array< int > &r_offsets, Array< int > &r_indices)
int face_find_corner_from_vert(const IndexRange face, const Span< int > corner_verts, const int vert)
Definition BKE_mesh.hh:327
bool is_uv_map(const AttributeMetaData &meta_data)
Array< int > build_corner_to_face_map(OffsetIndices< int > faces)
float3 face_center_calc(Span< float3 > vert_positions, Span< int > face_verts)
GroupedSpan< int > build_vert_to_edge_map(Span< int2 > edges, int verts_num, Array< int > &r_offsets, Array< int > &r_indices)
bool mesh_is_valid(const Mesh &mesh, bool verbose=true)
constexpr ParallelGrainSize grain_size(int grain_size)
static void snap_to_superellipsoid(float3 &co, const float super_r, const bool midline)
static VMesh tri_corner_adj_vmesh(BevelState &state, BevVert *bv)
static EdgeHalf * next_bev(BevVert *bv, EdgeHalf *from_e)
static void merge_uvs(BevelState &state)
static bool face_point_inside_test(const ExtendableMesh &emesh, const int f, const float3 co)
static bool edge_has_miter(const BevelState &state, const EdgeHalf *e, int v)
static int choose_rep_face(const BevelState &state, const Span< int > faces)
static int tri_corner_test(const BevelState &state, const BevVert *bv)
static void find_bevel_edge_order(const ExtendableMesh &emesh, BevVert *bv, int first_e, bool is_edge_bevel)
static int find_closer_edge(const ExtendableMesh &emesh, const float3 &co, const int e1, const int e2)
static void fill_vmesh_fracs(VMesh *vm, MutableSpan< float > frac, int i)
static VMesh new_adj_vmesh(int count, int seg, BoundVert *bounds)
static void bevel_build_edge_polygons(BevelState &state, const int edge_index)
static VMesh make_cube_corner_adj_vmesh(BevelState &state)
static float4x4 make_unit_cube_map(const float3 &va, const float3 &vb, const float3 &vc, const float3 &vd)
static BoundVert * pipe_test(const BevelState &state, BevVert *bv)
static void get_incident_edges(const ExtendableMesh &emesh, const int f, const int v_idx, int *r_e1, int *r_e2)
static VMesh square_out_adj_vmesh(BevelState &state, BevVert *bv)
static int bevel_build_poly(BevelState &state, BevVert *bv)
static VMesh cubic_subdiv(const BevelState &state, VMesh &vm_in)
static float3 offset_in_plane(const ExtendableMesh &emesh, EdgeHalf *e, const float3 *plane_no, bool left)
static float3 snap_to_pipe_profile(const BevelState &state, BevVert *bv, BoundVert *vpipe, bool midline, const float3 &co)
static bool edges_face_connected_at_vert(const ExtendableMesh &emesh, const int e1, const int e2)
static void compute_face_interp_weights(const ExtendableMesh &emesh, const int f_src, const float3 &co, MutableSpan< float > weights)
static void build_boundary_vertex_only(const BevelState &state, BevVert *bv, bool construct)
static std::optional< Mesh * > build_output_mesh(const BevelState &state, const NewCornerInterpWeights &interp_weights, const bke::AttributeFilter &attribute_filter)
static AngleKind edges_angle_kind(const ExtendableMesh &emesh, EdgeHalf *e1, EdgeHalf *e2, int v)
static VMesh make_cube_corner_square(const int nseg)
static NewCornerInterpWeights compute_new_corner_interp_weights(const ExtendableMesh &emesh)
static bool is_bad_uv_poly(const BevelState &state, BevVert *bv, const int frep)
static void bevel_build_rings(BevelState &state, BevVert *bv)
static int bev_ccw_test(const ExtendableMesh &emesh, const int a, const int b, const int f)
static void fill_new_corner_uvs(BevelState &state, const NewCornerInterpWeights &interp_weights)
static int find_face_internal_boundverts(const ExtendableMesh &emesh, const BevVert *bv, const int f, BoundVert *(r_internal[3]))
static int interp_range(const Span< float > frac, const int n, const float f, float *r_rest)
static VMesh interp_vmesh(const BevelState &state, VMesh &vm_in, int nseg)
static int bev_rebuild_polygon(BevelState &state, const int f_idx)
static EdgeHalf * next_edgehalf_bev(const BevelState &state, EdgeHalf *start_edge, bool toward_bv, BevVert **r_bv)
static void build_vmesh(BevelState &state, BevVert *bv)
static void set_bound_vert_seams(const BevelState &state, BevVert *bv, bool mark_seam, bool mark_sharp)
static void adjust_bound_vert(BoundVert *bndv, const float3 &co)
static bool fast_bevel_edge_order(const ExtendableMesh &emesh, BevVert *bv, bool is_edge_bevel)
static VMesh pipe_adj_vmesh(BevelState &state, BevVert *bv, BoundVert *vpipe)
static int count_ccw_edges_between(const EdgeHalf *e1, const EdgeHalf *e2)
static int bevel_edge_order_extend(const ExtendableMesh &emesh, BevVert *bv, int i, bool is_edge_bevel)
static void bevel_extend_edge_data(BevelState &state)
static void bevel_rebuild_existing_polygons(BevelState &state, Vector< int > &r_rebuilt_orig_faces, int &r_rebuilt_face_0)
static EdgeHalf * find_other_end_edge_half(const BevelState &state, EdgeHalf *e, BevVert **r_bvother)
static bool bevvert_is_weld_cross(const BevVert *bv)
static void bevel_vert_construct(BevelState &state, int v)
static int frep_for_center_poly(const BevelState &state, const BevVert *bv)
static void adjust_miter_coords(const BevelState &state, BevVert *bv, EdgeHalf *emiter)
static void bevel_vert_two_edges(BevelState &state, BevVert *bv)
static float projected_boundary_area(const BevelState &state, BevVert *bv, const int f)
static void build_boundary_terminal_edge(const BevelState &state, BevVert *bv, EdgeHalf *efirst, const bool construct)
static VMesh make_cube_corner_square_in(const int nseg)
static void snap_edges_for_vmesh_vert(const int i, const int j, const int k, const int ns, const int ns2, const int n_bndv, const int eprev, const int enext, const int enextnext, const Span< int > bndv_rep_faces, const int center_frep, const Span< bool > frep_beats_next, int r_snap_edges[4])
static float3 closer_v3_v3v3v3(const float3 &a, const float3 &b, const float3 &v)
static void determine_uv_vert_connectivity(BevelState &state, const int v)
static int boundvert_rep_face(const BoundVert *v, int *r_fother)
static void adjust_miter_inner_coords(const BevelState &state, BevVert *bv, EdgeHalf *emiter)
static void bevel_build_trifan(BevelState &state, BevVert *bv)
static void build_boundary(const BevelState &state, BevVert *bv, bool construct)
static bool try_propagate_single_value(const bke::AttributeIter &iter, const GVArray &src, const IndexMask &edges_new_no_src, bke::MutableAttributeAccessor &dst_attrs)
static void fill_profile_fracs(const BevelState &state, const BoundVert *bndv, MutableSpan< float > frac, const int ns)
static bool nearly_parallel_normalized(const float3 &d1, const float3 &d2)
static int snap_edge_for_center_vmesh_vert(const int i, const int n_bndv, const int eprev, const int enext, const Span< int > bndv_rep_faces, const int center_frep, const Span< bool > frep_beats_next)
static VMesh adj_vmesh(BevelState &state, BevVert *bv)
static void regularize_profile_orientation(const BevelState &state, int edge_index)
static EdgeHalf * find_edge_half_for_edge(BevVert *bv, int edge_index)
static BoundVert * add_new_bound_vert(BevVert *bv, const float3 &co)
static std::optional< NewCornerInterpData > resolve_new_corner_interp_data(const ExtendableMesh &emesh, const int nc, const int new_face_fallback)
static void check_edge_data_seam_sharp_edges(const BevelState &state, BevVert *bv, bool check_seam, bool check_sharp)
static void interpolate_new_corner_attribute_from_faces(const NewCornerInterpWeights &interp_weights, const GSpan src, GMutableSpan dst)
static void dump_edge_half(const EdgeHalf &eh, const int index)
static void dump_bound_vert(const BoundVert &bndv)
static void dump_profile(const Profile &prof)
static void dump_new_edge_examples(const BevelState &state)
static void print_float3_span(Span< float3 > span, const char *label)
static void dump_bev_vert(const BevVert &bv)
static void print_groupedspan(const GroupedSpan< int > &groupedspan, const char *label)
static void dump_edge_polygons(const BevelState &state, const BevVert &bv)
static void dump_new_face_examples(const BevelState &state)
static void print_int2(const int2 pair)
static const char * mesh_kind_name(MeshKind kind)
static void print_float3(const float3 &v)
static void dump_vmesh(const VMesh &vm)
static void print_indexrange(const IndexRange &range)
static void dump_rebuilt_face(const BevelState &state, const int face_idx)
static void print_int2_span(Span< int2 > span, const char *label)
static void print_span(Span< T > span, const char *label)
constexpr float BEVEL_EPSILON_BIG
constexpr float BEVEL_SMALL_ANG
const float BEVEL_SMALL_ANG_DOT
static bool nearly_parallel(const float3 &d1, const float3 &d2)
static float3 vmesh_center(VMesh *vm)
static NewVert * mesh_vert_canon(VMesh *vm, int i, int j, int k)
constexpr float BEVEL_EPSILON_SQ
static bool is_outside_edge(const ExtendableMesh &emesh, EdgeHalf *eh, const float co[3], int *ret_closer_v)
static float3 avg4(const NewVert *v0, const NewVert *v1, const NewVert *v2, const NewVert *v3)
constexpr float BEVEL_EPSILON_ANG
static bool point_between_edges(const ExtendableMesh &emesh, const float co[3], int v, int f, EdgeHalf *e1, EdgeHalf *e2)
const float BEVEL_EPSILON_ANG_DOT
static int edge_other_vert(const ExtendableMesh &emesh, int e, int v)
constexpr float BEVEL_EPSILON_D
static float3 slide_dist(const ExtendableMesh &emesh, int e, int v, float d)
static bool make_unit_square_map(const float3 &va, const float3 &vmid, const float3 &vb, float4x4 &r_mat)
static float3 offset_meet(const ExtendableMesh &emesh, EdgeHalf *e1, EdgeHalf *e2, int v, int f, bool edges_between, const EdgeHalf *e_in_plane)
static void vmesh_copy_equiv_verts(VMesh *vm)
static bool is_canon(const VMesh *vm, int i, int j, int k)
static NewVert * mesh_vert(VMesh *vm, int i, int j, int k)
static float sabin_gamma(int n)
static float3 get_profile_point(const BevelState &state, const Profile *pro, int i, int nseg)
static void set_profile_params(const BevelState &state, const BevVert *bv, BoundVert *bndv)
static void calculate_profile(BevelState &state, BoundVert *bndv, bool reversed, bool)
static void calculate_vm_profiles(BevelState &state, BevVert *bv, VMesh *vm)
static void find_even_superellipse_chords_general(int seg, float r, MutableSpan< double > xvals, MutableSpan< double > yvals)
static float3 project_to_edge(const ExtendableMesh &emesh, int e_idx, const float3 &co_a, const float3 &co_b)
static float find_profile_fullness(BevelState *bs)
static void move_weld_profile_planes(BoundVert *bndv1, BoundVert *bndv2, const float3 v_co)
static double superellipse_co(double x, float r, bool rbig)
static void calculate_profile_segments(const Profile &pro, const float4x4 &map, const bool use_map, const bool reversed, const int ns, const double *xvals, const double *yvals, MutableSpan< float3 > r_prof_co)
constexpr float PRO_SQUARE_R
constexpr float PRO_SQUARE_IN_R
static void find_even_superellipse_chords(int n, float r, MutableSpan< double > xvals, MutableSpan< double > yvals)
static void set_profile_spacing(BevelState *bs, ProfileSpacing *pro_spacing, bool custom)
static void move_profile_plane(BoundVert *bndv, float3 bmvert_co)
constexpr float PRO_CIRCLE_R
static double find_superellipse_chord_endpoint(double x0, double dtarget, float r, bool rbig)
Map< int, Vector< UVVertBucket > > UVVertMap
Definition mesh_bevel.cc:77
Set< int > UVVertBucket
Definition mesh_bevel.cc:76
std::optional< Mesh * > mesh_bevel(const Mesh &src_mesh, const IndexMask &selection, const BevelParameters &params, const bke::AttributeFilter &attribute_filter)
IndexMask vert_selection_from_edge(Span< int2 > edges, const IndexMask &edge_mask, int verts_num, IndexMaskMemory &memory)
void build_reverse_map(const IndexMask &mask, MutableSpan< T > r_map)
Definition index_mask.cc:36
T length_squared(const VecBase< T, Size > &a)
float3x3 axis_dominant_to_m3(const float3 &normal)
T cos(const AngleRadianBase< T > &a)
T pow(const T &x, const T &power)
T dist_squared_to_line_segment(const VecBase< T, Size > &p, const VecBase< T, Size > &l1, const VecBase< T, Size > &l2)
VecBase< T, Size > closest_to_line_segment(const VecBase< T, Size > &p, const VecBase< T, Size > &l1, const VecBase< T, Size > &l2)
T sqrt(const T &a)
T dist_squared_to_plane(const VecBase< T, 3 > &p, const VecBase< T, 4 > &plane)
std::optional< float3 > isect_line_plane(const float3 &l1, const float3 &l2, const float3 &plane_co, const float3 &plane_no)
T distance(const T &a, const T &b)
T length(const VecBase< T, Size > &a)
AngleRadianBase< T > angle_between(const QuaternionBase< T > &a, const QuaternionBase< T > &b)
QuaternionBase< T > normalize_and_get_length(const QuaternionBase< T > &q, T &out_length)
T dot(const QuaternionBase< T > &a, const QuaternionBase< T > &b)
T min(const T &a, const T &b)
bool is_zero(const T &a)
CartesianBasis invert(const CartesianBasis &basis)
T midpoint(const T &a, const T &b)
AxisSigned cross(const AxisSigned a, const AxisSigned b)
T interpolate(const T &a, const T &b, const FactorT &t)
VecBase< T, 3 > closest_to_plane_normalized(const VecBase< T, 4 > &plane, const VecBase< T, 3 > &pt)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
T distance_squared(const VecBase< T, Size > &a, const VecBase< T, Size > &b)
bool is_equal(const MatBase< T, NumCol, NumRow > &a, const MatBase< T, NumCol, NumRow > &b, const T epsilon=T(0))
T sin(const AngleRadianBase< T > &a)
T max(const T &a, const T &b)
T abs(const T &a)
int isect_line_line(const float3 &v1, const float3 &v2, const float3 &v3, const float3 &v4, float3 &r_i1, float3 &r_i2)
VecBase< T, 4 > plane_from_point_normal(const VecBase< T, 3 > &co, const VecBase< T, 3 > &no)
VecBase< T, 3 > closest_to_plane(const VecBase< T, 4 > &plane, const VecBase< T, 3 > &pt)
void interp_weights_poly(MutableSpan< float > r_weights, Span< float2 > verts, const float2 &co)
bool isect_point_poly(const float2 &pt, Span< float2 > verts)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
OffsetIndices< int > accumulate_counts_to_offsets(MutableSpan< int > counts_to_offsets, int start_offset=0)
int sum_group_sizes(OffsetIndices< int > offsets, const IndexMask &mask)
OffsetIndices< int > gather_selected_offsets(OffsetIndices< int > src_offsets, const IndexMask &selection, int start_offset, MutableSpan< int > dst_offsets)
Clock::time_point TimePoint
Definition BLI_timeit.hh:20
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
__int64 int64_t
Definition BKE_text.h:90
MINLINE int power_of_2_max_i(int n)
ATTR_WARN_UNUSED_RESULT const BMVert * v
MatBase< float, 4, 4 > float4x4
VecBase< float, 4 > float4
float area_poly_v2(const float verts[][2], unsigned int nr)
Definition math_geom.cc:186
void BKE_mesh_copy_parameters_for_eval(Mesh *me_dst, const Mesh *me_src)
VecBase< int32_t, 2 > int2
VecBase< float, 2 > float2
BMesh const char void * data
unsigned char uint8_t
Definition BKE_text.h:79
Mesh * BKE_mesh_new_nomain(int verts_num, int edges_num, int faces_num, int corners_num)
sqrt(x)+1/max(0
MatBase< float, 3, 3 > float3x3
ATTR_WARN_UNUSED_RESULT const BMVert * v2
void interp_bilinear_quad_v3(float data[4][3], float u, float v, float res[3])
PythonProbingStrategy<> DefaultProbingStrategy
VecBase< float, 3 > float3
MINLINE int is_power_of_2_i(int n)
ATTR_WARN_UNUSED_RESULT const BMVert const BMEdge * e
signed char int8_t
Definition BKE_text.h:76
MINLINE bool compare_v2v2(const float v1[2], const float v2[2], float limit) ATTR_WARN_UNUSED_RESULT
#define sinf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
struct BMEdge * e
OrderedEdge(const int v1, const int v2)
bool allow_skip(const StringRef name) const
Vector< std::unique_ptr< BoundVert > > owned_bound_verts
std::unique_ptr< VMesh > vmesh
Array< EdgeHalf > edges
std::optional< std::string > edge_face_id
std::optional< std::string > vertex_face_id
std::optional< std::string > mid_edge_id
std::optional< std::string > outer_edge_id
std::array< Array< float >, 4 > offsets
index_mask::IndexMaskMemory memory
float3 face_center(const int f) const
Vector< BevVert > bev_verts
Vector< UVVertMap > uv_vert_maps
BevelState(const Mesh &mesh, const BevelParameters &params, const IndexMask &selection)
Map< int, BevVert * > vert_hash
Vector< int > outer_edge_src_indices
Array< float3 > prof_co_2
Array< NewVert > mesh
Span< float > weights_for(const int nc) const