Blender V4.5
node_geo_sort_elements.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include <atomic>
6
7#include "BKE_attribute.hh"
8#include "BKE_instances.hh"
9
10#include "BLI_array_utils.hh"
11#include "BLI_index_mask.hh"
12#include "BLI_sort.hh"
13#include "BLI_task.hh"
14
15#include "GEO_reorder.hh"
16
17#include "NOD_rna_define.hh"
18
19#include "RNA_enum_types.hh"
20
21#include "UI_interface.hh"
22#include "UI_resources.hh"
23
24#include "node_geometry_util.hh"
25
27
29{
30 b.use_custom_socket_order();
31 b.allow_any_socket_order();
32 b.add_default_layout();
33 b.add_input<decl::Geometry>("Geometry");
34 b.add_output<decl::Geometry>("Geometry").propagate_all().align_with_previous();
35 b.add_input<decl::Bool>("Selection").default_value(true).field_on_all().hide_value();
36 b.add_input<decl::Int>("Group ID").field_on_all().hide_value();
37 b.add_input<decl::Float>("Sort Weight").field_on_all().hide_value();
38}
39
40static void node_layout(uiLayout *layout, bContext * /*C*/, PointerRNA *ptr)
41{
42 layout->prop(ptr, "domain", UI_ITEM_NONE, "", ICON_NONE);
43}
44
45static void node_init(bNodeTree * /*tree*/, bNode *node)
46{
48}
49
50static void grouped_sort(const OffsetIndices<int> offsets,
51 const Span<float> weights,
53{
54 const auto comparator = [&](const int index_a, const int index_b) {
55 const float weight_a = weights[index_a];
56 const float weight_b = weights[index_b];
57 if (UNLIKELY(weight_a == weight_b)) {
58 /* Approach to make it stable. */
59 return index_a < index_b;
60 }
61 return weight_a < weight_b;
62 };
63
64 threading::parallel_for(offsets.index_range(), 250, [&](const IndexRange range) {
65 for (const int group_index : range) {
66 MutableSpan<int> group = indices.slice(offsets[group_index]);
67 parallel_sort(group.begin(), group.end(), comparator);
68 }
69 });
70}
71
73 MutableSpan<int> r_offsets,
74 MutableSpan<int> r_indices)
75{
77 Array<int> counts(r_offsets.size(), 0);
78
79 for (const int64_t index : indices.index_range()) {
80 const int curve_index = indices[index];
81 r_indices[r_offsets[curve_index] + counts[curve_index]] = int(index);
82 counts[curve_index]++;
83 }
84}
85
86template<typename T, typename Func>
87static void parallel_transform(MutableSpan<T> values, const int64_t grain_size, const Func &func)
88{
89 threading::parallel_for(values.index_range(), grain_size, [&](const IndexRange range) {
90 MutableSpan<T> values_range = values.slice(range);
91 std::transform(values_range.begin(), values_range.end(), values_range.begin(), func);
92 });
93}
94
95static Array<int> invert_permutation(const Span<int> permutation)
96{
97 Array<int> data(permutation.size());
98 threading::parallel_for(permutation.index_range(), 2048, [&](const IndexRange range) {
99 for (const int64_t i : range) {
100 data[permutation[i]] = i;
101 }
102 });
103 return data;
104}
105
106static int identifiers_to_indices(MutableSpan<int> r_identifiers_to_indices)
107{
108 const VectorSet<int> deduplicated_identifiers(r_identifiers_to_indices);
109 parallel_transform(r_identifiers_to_indices, 2048, [&](const int identifier) {
110 return deduplicated_identifiers.index_of(identifier);
111 });
112
113 Array<int> indices(deduplicated_identifiers.size());
115 parallel_sort(indices.begin(), indices.end(), [&](const int index_a, const int index_b) {
116 return deduplicated_identifiers[index_a] < deduplicated_identifiers[index_b];
117 });
120 r_identifiers_to_indices, 4096, [&](const int index) { return permutation[index]; });
121 return deduplicated_identifiers.size();
122}
123
124static std::optional<Array<int>> sorted_indices(const fn::FieldContext &field_context,
125 const int domain_size,
126 const Field<bool> selection_field,
127 const Field<int> group_id_field,
128 const Field<float> weight_field)
129{
130 if (domain_size == 0) {
131 return std::nullopt;
132 }
133
134 FieldEvaluator evaluator(field_context, domain_size);
135 evaluator.set_selection(selection_field);
136 evaluator.add(group_id_field);
137 evaluator.add(weight_field);
138 evaluator.evaluate();
140 const VArray<int> group_id = evaluator.get_evaluated<int>(0);
141 const VArray<float> weight = evaluator.get_evaluated<float>(1);
142
143 if (group_id.is_single() && weight.is_single()) {
144 return std::nullopt;
145 }
146 if (mask.is_empty()) {
147 return std::nullopt;
148 }
149
150 Array<int> gathered_indices(mask.size());
151
152 if (group_id.is_single()) {
153 mask.to_indices<int>(gathered_indices);
154 Array<float> weight_span(domain_size);
155 array_utils::copy(weight, mask, weight_span.as_mutable_span());
156 grouped_sort(Span({0, int(mask.size())}), weight_span, gathered_indices);
157 }
158 else {
159 Array<int> gathered_group_id(mask.size());
160 array_utils::gather(group_id, mask, gathered_group_id.as_mutable_span());
161 const int total_groups = identifiers_to_indices(gathered_group_id);
162 Array<int> offsets_to_sort(total_groups + 1, 0);
163 find_points_by_group_index(gathered_group_id, offsets_to_sort, gathered_indices);
164 if (!weight.is_single()) {
165 Array<float> weight_span(mask.size());
166 array_utils::gather(weight, mask, weight_span.as_mutable_span());
167 grouped_sort(offsets_to_sort.as_span(), weight_span, gathered_indices);
168 }
169 parallel_transform<int>(gathered_indices, 2048, [&](const int pos) { return mask[pos]; });
170 }
171
172 if (array_utils::indices_are_range(gathered_indices, IndexRange(domain_size))) {
173 return std::nullopt;
174 }
175
176 if (mask.size() == domain_size) {
177 return gathered_indices;
178 }
179
180 IndexMaskMemory memory;
181 const IndexMask unselected = mask.complement(IndexRange(domain_size), memory);
182
183 Array<int> indices(domain_size);
184
185 array_utils::scatter<int>(gathered_indices, mask, indices);
186 unselected.foreach_index_optimized<int>(GrainSize(2048),
187 [&](const int index) { indices[index] = index; });
188
189 if (array_utils::indices_are_range(indices, indices.index_range())) {
190 return std::nullopt;
191 }
192
193 return indices;
194}
195
197{
198 GeometrySet geometry_set = params.extract_input<GeometrySet>("Geometry");
199 const Field<bool> selection_field = params.extract_input<Field<bool>>("Selection");
200 const Field<int> group_id_field = params.extract_input<Field<int>>("Group ID");
201 const Field<float> weight_field = params.extract_input<Field<float>>("Sort Weight");
202 const bke::AttrDomain domain = bke::AttrDomain(params.node().custom1);
203
204 const NodeAttributeFilter attribute_filter = params.get_attribute_filter("Geometry");
205
207
208 std::atomic<bool> has_reorder = false;
209 std::atomic<bool> has_unsupported = false;
210 if (domain == bke::AttrDomain::Instance) {
211 if (const bke::Instances *instances = geometry_set.get_instances()) {
212 if (const std::optional<Array<int>> indices = sorted_indices(
213 bke::InstancesFieldContext(*instances),
214 instances->instances_num(),
215 selection_field,
216 group_id_field,
217 weight_field))
218 {
220 *instances, *indices, attribute_filter);
221 geometry_set.replace_instances(result);
222 has_reorder = true;
223 }
224 }
225 }
226 else {
227 geometry_set.modify_geometry_sets([&](GeometrySet &geometry_set) {
228 for (const auto [type, domains] : geometry::components_supported_reordering().items()) {
229 const bke::GeometryComponent *src_component = geometry_set.get_component(type);
230 if (src_component == nullptr || src_component->is_empty()) {
231 continue;
232 }
233 if (!domains.contains(domain)) {
234 has_unsupported = true;
235 continue;
236 }
237 has_reorder = true;
238 const std::optional<Array<int>> indices = sorted_indices(
239 bke::GeometryFieldContext(*src_component, domain),
240 src_component->attribute_domain_size(domain),
241 selection_field,
242 group_id_field,
243 weight_field);
244 if (!indices.has_value()) {
245 continue;
246 }
248 *src_component, *indices, domain, attribute_filter);
249 geometry_set.remove(type);
250 geometry_set.add(*dst_component.get());
251 }
252 });
253 }
254
255 if (has_unsupported && !has_reorder) {
256 params.error_message_add(NodeWarningType::Info,
257 TIP_("Domain and geometry type combination is unsupported"));
258 }
259
260 params.set_output("Geometry", std::move(geometry_set));
261}
262
263template<typename T>
265 const EnumPropertyItem *src_items)
266{
268 for (const EnumPropertyItem *item = src_items; item->identifier != nullptr; item++) {
269 if (values.contains(T(item->value))) {
270 items.append(*item);
271 }
272 }
273 items.append({0, nullptr, 0, nullptr, nullptr});
274 return items;
275}
276
277static void node_rna(StructRNA *srna)
278{
279 static const Vector<EnumPropertyItem> supported_items = items_value_in<bke::AttrDomain>(
286
288 "domain",
289 "Domain",
290 "",
291 supported_items.data(),
294}
295
296static void node_register()
297{
298 static blender::bke::bNodeType ntype;
299
300 geo_node_type_base(&ntype, "GeometryNodeSortElements", GEO_NODE_SORT_ELEMENTS);
301 ntype.ui_name = "Sort Elements";
302 ntype.ui_description = "Rearrange geometry elements, changing their indices";
303 ntype.enum_name_legacy = "SORT_ELEMENTS";
305 ntype.declare = node_declare;
306 ntype.initfunc = node_init;
310
311 node_rna(ntype.rna_ext.srna);
312}
313NOD_REGISTER_NODE(node_register)
314
315} // namespace blender::nodes::node_geo_sort_elements_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:447
#define GEO_NODE_SORT_ELEMENTS
#define UNLIKELY(x)
#define TIP_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
#define UI_ITEM_NONE
BMesh const char void * data
long long int int64_t
Span< T > as_span() const
Definition BLI_array.hh:232
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:237
constexpr int64_t size() const
Definition BLI_span.hh:493
constexpr IndexRange index_range() const
Definition BLI_span.hh:670
constexpr int64_t size() const
Definition BLI_span.hh:252
constexpr IndexRange index_range() const
Definition BLI_span.hh:401
constexpr bool contains(const T &value) const
Definition BLI_span.hh:277
int64_t size() const
int64_t index_of(const Key &key) const
void append(const T &value)
int attribute_domain_size(AttrDomain domain) const
virtual bool is_empty() const
void set_selection(Field< bool > selection)
Definition FN_field.hh:383
int add(GField field, GVArray *varray_ptr)
Definition field.cc:751
IndexMask get_evaluated_selection_as_mask() const
Definition field.cc:817
const GVArray & get_evaluated(const int field_index) const
Definition FN_field.hh:448
void foreach_index_optimized(Fn &&fn) const
static void remember_deformed_positions_if_necessary(GeometrySet &geometry)
static ushort indices[]
uint pos
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
ccl_device_inline float2 mask(const MaskType mask, const float2 a)
#define T
void copy(const GVArray &src, GMutableSpan dst, int64_t grain_size=4096)
bool indices_are_range(Span< int > indices, IndexRange range)
void scatter(const Span< T > src, const Span< IndexT > indices, MutableSpan< T > dst, const int64_t grain_size=4096)
void gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, int64_t grain_size=4096)
void fill_index_range(MutableSpan< T > span, const T start=0)
ImplicitSharingPtr< GeometryComponent > GeometryComponentPtr
void node_register_type(bNodeType &ntype)
Definition node.cc:2748
const MultiValueMap< bke::GeometryComponent::Type, bke::AttrDomain > & components_supported_reordering()
Definition reorder.cc:29
bke::GeometryComponentPtr reordered_component(const bke::GeometryComponent &src_component, Span< int > old_by_new_map, bke::AttrDomain domain, const bke::AttributeFilter &attribute_filter)
Definition reorder.cc:379
bke::Instances * reorder_instaces(const bke::Instances &src_instances, Span< int > old_by_new_map, const bke::AttributeFilter &attribute_filter)
Definition reorder.cc:370
static void node_declare(NodeDeclarationBuilder &b)
static int identifiers_to_indices(MutableSpan< int > r_identifiers_to_indices)
static void node_layout(uiLayout *layout, bContext *, PointerRNA *ptr)
static void parallel_transform(MutableSpan< T > values, const int64_t grain_size, const Func &func)
static void node_geo_exec(GeoNodeExecParams params)
static Vector< EnumPropertyItem > items_value_in(const Span< T > values, const EnumPropertyItem *src_items)
static Array< int > invert_permutation(const Span< int > permutation)
static std::optional< Array< int > > sorted_indices(const fn::FieldContext &field_context, const int domain_size, const Field< bool > selection_field, const Field< int > group_id_field, const Field< float > weight_field)
static void grouped_sort(const OffsetIndices< int > offsets, const Span< float > weights, MutableSpan< int > indices)
static void find_points_by_group_index(const Span< int > indices, MutableSpan< int > r_offsets, MutableSpan< int > r_indices)
static void node_init(bNodeTree *, bNode *node)
PropertyRNA * RNA_def_node_enum(StructRNA *srna, const char *identifier, const char *ui_name, const char *ui_description, const EnumPropertyItem *static_items, const EnumRNAAccessors accessors, std::optional< int > default_value, const EnumPropertyItemFunc item_func, const bool allow_animation)
void build_reverse_offsets(Span< int > indices, MutableSpan< int > offsets)
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:93
void parallel_sort(RandomAccessIterator begin, RandomAccessIterator end)
Definition BLI_sort.hh:23
void geo_node_type_base(blender::bke::bNodeType *ntype, std::string idname, const std::optional< int16_t > legacy_type)
const EnumPropertyItem rna_enum_attribute_domain_items[]
const char * identifier
Definition RNA_types.hh:623
StructRNA * srna
Definition RNA_types.hh:909
int16_t custom1
void replace_instances(Instances *instances, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
const GeometryComponent * get_component(GeometryComponent::Type component_type) const
const Instances * get_instances() const
void remove(const GeometryComponent::Type component_type)
void modify_geometry_sets(ForeachSubGeometryCallback callback)
void add(const GeometryComponent &component)
Defines a node type.
Definition BKE_node.hh:226
std::string ui_description
Definition BKE_node.hh:232
void(* initfunc)(bNodeTree *ntree, bNode *node)
Definition BKE_node.hh:277
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:347
const char * enum_name_legacy
Definition BKE_node.hh:235
void(* draw_buttons)(uiLayout *, bContext *C, PointerRNA *ptr)
Definition BKE_node.hh:247
NodeDeclareFunction declare
Definition BKE_node.hh:355
void prop(PointerRNA *ptr, PropertyRNA *prop, int index, int value, eUI_Item_Flag flag, std::optional< blender::StringRef > name_opt, int icon, std::optional< blender::StringRef > placeholder=std::nullopt)
PointerRNA * ptr
Definition wm_files.cc:4227