Blender V5.3
node_geo_field_average.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2025 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
6
7#include "BLI_array.hh"
8#include "BLI_array_utils.hh"
10#include "BLI_math_vector_c.hh"
11#include "BLI_vector.hh"
12#include "BLI_virtual_array.hh"
13
14#include "NOD_rna_define.hh"
16
17#include "RNA_enum_types.hh"
18
19#include "node_geometry_util.hh"
20
22#include "UI_resources.hh"
23
25
27{
28 const bNode *node = b.node_or_null();
29
30 if (node != nullptr) {
31 const eCustomDataType data_type = eCustomDataType(node->custom1);
32 b.add_input(data_type, "Value"_ustr)
33 .structure_type(StructureType::Field)
34 .description("The values the mean and median will be calculated from");
35 }
36
37 b.add_input<decl::Int>("Group ID"_ustr, "Group Index"_ustr)
38 .structure_type(StructureType::Field)
39 .hide_value()
40 .description("An index used to group values together for multiple separate operations");
41
42 if (node != nullptr) {
43 const eCustomDataType data_type = eCustomDataType(node->custom1);
44 b.add_output(data_type, "Mean"_ustr)
45 .structure_type(StructureType::Field)
46 .propagate_references()
47 .description("The sum of all values in each group divided by the size of said group");
48 b.add_output(data_type, "Median"_ustr)
49 .translation_context(BLT_I18NCONTEXT_ID_NODETREE)
50 .structure_type(StructureType::Field)
51 .propagate_references()
52 .description(
53 "The middle value in each group when all values are sorted from lowest to highest");
54 }
55}
56
57static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
58{
59 layout.prop(ptr, "data_type", UI_ITEM_NONE, "", ICON_NONE);
60 layout.prop(ptr, "domain", UI_ITEM_NONE, "", ICON_NONE);
61}
62
63static void node_init(bNodeTree * /*tree*/, bNode *node)
64{
65 node->custom1 = CD_PROP_FLOAT;
66 node->custom2 = int16_t(AttrDomain::Point);
67}
68
69enum class Operation { Mean = 0, Median = 1 };
70
71static std::optional<eCustomDataType> node_type_from_other_socket(const bNodeSocket &socket)
72{
73 switch (socket.type) {
74 case SOCK_FLOAT:
75 case SOCK_BOOLEAN:
76 case SOCK_INT:
77 return CD_PROP_FLOAT;
78 case SOCK_VECTOR:
79 case SOCK_RGBA:
80 return CD_PROP_FLOAT3;
81 default:
82 return std::nullopt;
83 }
84}
85
87{
88 const NodeDeclaration &declaration = *params.node_type().static_declaration;
89 search_link_ops_for_declarations(params, declaration.inputs);
90
91 const std::optional<eCustomDataType> type = node_type_from_other_socket(params.other_socket());
92 if (!type) {
93 return;
94 }
95 if (params.in_out() == SOCK_OUT) {
96 params.add_item(
97 IFACE_("Mean"),
98 [type](LinkSearchOpParams &params) {
99 bNode &node = params.add_node("GeometryNodeFieldAverage"_ustr);
100 node.custom1 = *type;
101 params.update_and_connect_available_socket(node, "Mean"_ustr);
102 },
103 0);
104 params.add_item(
106 [type](LinkSearchOpParams &params) {
107 bNode &node = params.add_node("GeometryNodeFieldAverage"_ustr);
108 node.custom1 = *type;
109 params.update_and_connect_available_socket(node, "Median"_ustr);
110 },
111 -1);
112 }
113 else {
114 params.add_item(
115 IFACE_("Value"),
116 [type](LinkSearchOpParams &params) {
117 bNode &node = params.add_node("GeometryNodeFieldAverage"_ustr);
118 node.custom1 = *type;
119 params.update_and_connect_available_socket(node, "Value"_ustr);
120 },
121 0);
122 }
123}
124
125template<typename T> static T calculate_median(MutableSpan<T> values)
126{
127 if constexpr (std::is_same<T, float3>::value) {
128 Array<float> x_vals(values.size()), y_vals(values.size()), z_vals(values.size());
129
130 for (const int i : values.index_range()) {
131 float3 value = values[i];
132 x_vals[i] = value.x;
133 y_vals[i] = value.y;
134 z_vals[i] = value.z;
135 }
136
137 return float3(calculate_median<float>(x_vals),
140 }
141 else {
142 const auto middle_itr = values.begin() + values.size() / 2;
143 std::nth_element(values.begin(), middle_itr, values.end());
144 if (values.size() % 2 == 0) {
145 auto *const left_middle_itr = std::max_element(values.begin(), middle_itr);
146 return math::midpoint<T>(*left_middle_itr, *middle_itr);
147 }
148 return *middle_itr;
149 }
150}
151
153 private:
154 GField input_;
155 Field<int> group_index_;
156 AttrDomain source_domain_;
157 Operation operation_;
158
159 public:
160 FieldAverageInput(const AttrDomain source_domain,
161 GField input,
162 Field<int> group_index,
163 Operation operation)
164 : bke::GeometryFieldInput(input.cpp_type(), "Calculation"),
165 input_(std::move(input)),
166 group_index_(std::move(group_index)),
167 source_domain_(source_domain),
168 operation_(operation)
169 {
170 }
171
173 const IndexMask & /*mask*/) const final
174 {
175 const AttributeAccessor attributes = *context.attributes();
176 const int64_t domain_size = attributes.domain_size(source_domain_);
177 if (domain_size == 0) {
178 return {};
179 }
180
181 const bke::GeometryFieldContext source_context{context, source_domain_};
182 fn::FieldEvaluator evaluator{source_context, domain_size};
183 evaluator.add(input_);
184 evaluator.add(group_index_);
185 evaluator.evaluate();
186 const GVArray g_values = evaluator.get_evaluated(0);
187 const VArray<int> group_indices = evaluator.get_evaluated<int>(1);
188
189 GVArray g_outputs;
190
191 g_values.type().to_static_type<int, float, float3>([&]<typename T>() {
192 const VArraySpan<T> values = g_values.typed<T>();
193
194 if (operation_ == Operation::Mean) {
195 if (group_indices.is_single()) {
196 const T mean = array_utils::compute_sum<T>(values) / domain_size;
197 g_outputs = VArray<T>::from_single(mean, domain_size);
198 }
199 else {
200 Map<int, std::pair<T, int>> sum_and_counts;
201 for (const int i : values.index_range()) {
202 auto &pair = sum_and_counts.lookup_or_add(group_indices[i], std::make_pair(T(), 0));
203 pair.first = pair.first + values[i];
204 pair.second = pair.second + 1;
205 }
206
207 Array<T> outputs(domain_size);
208 for (const int i : values.index_range()) {
209 const auto &pair = sum_and_counts.lookup(group_indices[i]);
210 outputs[i] = pair.first / pair.second;
211 }
212 g_outputs = VArray<T>::from_container(std::move(outputs));
213 }
214 }
215 else {
216 if (group_indices.is_single()) {
217 Array<T> sorted_values(values);
218 T median = calculate_median<T>(sorted_values);
219 g_outputs = VArray<T>::from_single(median, domain_size);
220 }
221 else {
222 Map<int, Vector<T>> groups;
223 for (const int i : values.index_range()) {
224 groups.lookup_or_add(group_indices[i], Vector<T>()).append(values[i]);
225 }
226
227 Map<int, T> medians;
228 for (MutableMapItem<int, Vector<T>> group : groups.items()) {
229 medians.add(group.key, calculate_median<T>(group.value));
230 }
231
232 Array<T> outputs(domain_size);
233 for (const int i : values.index_range()) {
234 outputs[i] = medians.lookup(group_indices[i]);
235 }
236 g_outputs = VArray<T>::from_container(std::move(outputs));
237 }
238 }
239 });
240
241 return attributes.adapt_domain(std::move(g_outputs), source_domain_, context.domain());
242 }
243
244 void foreach_recursive_field(FunctionRef<void(const GField &)> fn) const final
245 {
246 fn(input_);
247 fn(group_index_);
248 }
249
250 void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep &deep_hash_cache) const override
251 {
252 static constexpr int8_t id = 0;
253 hash.add(&id);
254 hash.add(deep_hash_cache.ensure(input_));
255 hash.add(deep_hash_cache.ensure(group_index_));
256 hash.add(source_domain_);
257 hash.add(operation_);
258 }
259
260 std::optional<AttrDomain> preferred_domain(
261 const GeometryComponent & /*component*/) const override
262 {
263 return source_domain_;
264 }
265};
266
268{
269 const AttrDomain source_domain = AttrDomain(params.node().custom2);
270
271 const Field<int> group_index_field = params.extract_input<Field<int>>("Group Index"_ustr);
272 const GField input_field = params.extract_input<GField>("Value"_ustr);
273 if (params.output_is_required("Mean"_ustr)) {
274 params.set_output<GField>("Mean"_ustr,
276 source_domain, input_field, group_index_field, Operation::Mean));
277 }
278 if (params.output_is_required("Median"_ustr)) {
279 params.set_output<GField>(
280 "Median"_ustr,
282 source_domain, input_field, group_index_field, Operation::Median));
283 }
284}
285
286static void node_rna(StructRNA *srna)
287{
288 static EnumPropertyItem items[] = {
289 {CD_PROP_FLOAT, "FLOAT", ICON_NODE_SOCKET_FLOAT, "Float", "Floating-point value"},
291 "FLOAT_VECTOR",
292 ICON_NODE_SOCKET_VECTOR,
293 "Vector",
294 "3D vector with floating-point values"},
295 {0, nullptr, 0, nullptr, nullptr},
296 };
297
299 "data_type",
300 "Data Type",
301 "Type of data the outputs are calculated from",
302 items,
305
307 "domain",
308 "Domain",
309 "",
312 int(AttrDomain::Point),
313 nullptr,
314 true);
315}
316
317static void node_register()
318{
319 static bke::bNodeType ntype;
320
321 geo_node_type_base(&ntype, "GeometryNodeFieldAverage"_ustr);
322 ntype.ui_name = "Field Average";
323 ntype.ui_description = "Calculate the mean and median of a given field";
326 ntype.initfunc = node_init;
328 ntype.declare = node_declare;
331 node_rna(ntype.rna_ext.srna);
332}
334
335} // namespace blender::nodes::node_geo_field_average_cc
#define NODE_CLASS_CONVERTER
Definition BKE_node.hh:484
#define final(a, b, c)
Definition BLI_hash_c.hh:21
#define BLT_I18NCONTEXT_ID_NODETREE
#define CTX_IFACE_(context, msgid)
#define IFACE_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
#define UI_ITEM_NONE
const T & first() const
Definition BLI_array.hh:292
void to_static_type(Fn &&fn) const
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
const Value & lookup(const Key &key) const
Definition BLI_map.hh:545
ItemIterator items() const &
Definition BLI_map.hh:902
Value & lookup_or_add(const Key &key, const Value &value)
Definition BLI_map.hh:588
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr T * end() const
Definition BLI_span.hh:554
constexpr T * begin() const
Definition BLI_span.hh:550
constexpr IndexRange index_range() const
Definition BLI_span.hh:676
static VArray from_single(T value, const int64_t size)
static VArray from_container(ContainerT container)
GVArray adapt_domain(const GVArray &varray, const AttrDomain from_domain, const AttrDomain to_domain) const
int domain_size(const AttrDomain domain) const
constexpr IndexRange index_range() const
int add(GField field, GVArray *varray_ptr)
const GVArray & get_evaluated(const int field_index) const
uint64_t hash() const
Definition field.cc:185
const CPPType & cpp_type() const
Definition FN_field.hh:559
static GField from_input(Args &&...args)
Definition FN_field.hh:482
const bke::bNodeType & node_type() const
void add_item(std::string socket_name, SocketLinkOperation::LinkSocketFn fn, int weight=0)
T extract_input(const UString identifier)
bool output_is_required(const UString identifier) const
void set_output(const UString identifier, T &&value)
void update_and_connect_available_socket(bNode &new_node, UString socket_name)
Vector< SocketDeclaration * > inputs
void foreach_recursive_field(FunctionRef< void(const GField &)> fn) const final
void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep &deep_hash_cache) const override
FieldAverageInput(const AttrDomain source_domain, GField input, Field< int > group_index, Operation operation)
GVArray get_varray_for_context(const bke::GeometryFieldContext &context, const IndexMask &) const final
std::optional< AttrDomain > preferred_domain(const GeometryComponent &) const override
#define T
T compute_sum(const Span< T > data)
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
T midpoint(const T &a, const T &b)
static void node_init(bNodeTree *, bNode *node)
static void node_gather_link_searches(GatherLinkSearchOpParams &params)
static void node_geo_exec(GeoNodeExecParams params)
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
static std::optional< eCustomDataType > node_type_from_other_socket(const bNodeSocket &socket)
static void node_declare(NodeDeclarationBuilder &b)
static T calculate_median(MutableSpan< T > values)
void search_link_ops_for_declarations(GatherLinkSearchOpParams &params, Span< SocketDeclaration * > declarations)
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)
__int64 int64_t
Definition BKE_text.h:90
VecBase< float, 3 > float3
void geo_node_type_base(bke::bNodeType *ntype, UString idname, const std::optional< int16_t > legacy_type)
const EnumPropertyItem rna_enum_attribute_domain_items[]
signed char int8_t
Definition BKE_text.h:76
signed short int16_t
Definition BKE_text.h:77
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
eNodeSocketDatatype type
Defines a node type.
Definition BKE_node.hh:265
void(*) draw_buttons(ui::Layout &, bContext *C, PointerRNA *ptr)
Definition BKE_node.hh:290
std::string ui_description
Definition BKE_node.hh:271
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:385
void(*) initfunc(bNodeTree *ntree, bNode *node)
Definition BKE_node.hh:320
NodeGatherSocketLinkOperationsFunction gather_link_search_ops
Definition BKE_node.hh:409
NodeDeclareFunction declare
Definition BKE_node.hh:393
nodes::NodeDeclaration * static_declaration
Definition BKE_node.hh:402
UniqueHash ensure(const GFieldRef &field)
Definition field.cc:113
void prop(PointerRNA *ptr, PropertyRNA *prop, int index, int value, eUI_Item_Flag flag, std::optional< StringRef > name_opt, int icon, std::optional< StringRef > placeholder=std::nullopt)