Blender V5.3
node_geo_accumulate_field.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
6
7#include "BLI_array.hh"
10
11#include "NOD_rna_define.hh"
13
14#include "RNA_enum_types.hh"
15
16#include "node_geometry_util.hh"
17
19#include "UI_resources.hh"
20
22
24
26{
27 const bNode *node = b.node_or_null();
28
29 if (node != nullptr) {
30 const eCustomDataType data_type = eCustomDataType(node_storage(*node).data_type);
31 BaseSocketDeclarationBuilder *value_declaration = nullptr;
32 switch (data_type) {
33 case CD_PROP_FLOAT3:
34 value_declaration =
35 &b.add_input<decl::Vector>("Value"_ustr).default_value({1.0f, 1.0f, 1.0f});
36 break;
37 case CD_PROP_FLOAT:
38 value_declaration = &b.add_input<decl::Float>("Value"_ustr).default_value(1.0f);
39 break;
40 case CD_PROP_INT32:
41 value_declaration = &b.add_input<decl::Int>("Value"_ustr).default_value(1);
42 break;
44 value_declaration = &b.add_input<decl::Matrix>("Value"_ustr);
45 break;
46 default:
48 break;
49 }
50 value_declaration->structure_type(StructureType::Field)
51 .description("The values to be accumulated");
52 }
53
54 b.add_input<decl::Int>("Group ID"_ustr, "Group Index"_ustr)
55 .structure_type(StructureType::Field)
56 .hide_value()
57 .description("An index used to group values together for multiple separate accumulations");
58
59 if (node != nullptr) {
60 const eCustomDataType data_type = eCustomDataType(node_storage(*node).data_type);
61 b.add_output(data_type, "Leading"_ustr)
62 .structure_type(StructureType::Field)
63 .propagate_references()
64 .description(
65 "The running total of values in the corresponding group, starting at the first value");
66 b.add_output(data_type, "Trailing"_ustr)
67 .structure_type(StructureType::Field)
68 .propagate_references()
69 .description("The running total of values in the corresponding group, starting at zero");
70 b.add_output(data_type, "Total"_ustr)
71 .structure_type(StructureType::Field)
72 .propagate_references()
73 .description("The total of all of the values in the corresponding group");
74 }
75}
76
77static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
78{
79 layout.prop(ptr, "data_type", UI_ITEM_NONE, "", ICON_NONE);
80 layout.prop(ptr, "domain", UI_ITEM_NONE, "", ICON_NONE);
81}
82
83static void node_init(bNodeTree * /*tree*/, bNode *node)
84{
85 NodeAccumulateField *data = MEM_new<NodeAccumulateField>(__func__);
86 data->data_type = CD_PROP_FLOAT;
87 data->domain = int16_t(AttrDomain::Point);
88 node->storage = data;
89}
90
91enum class AccumulationMode { Leading = 0, Trailing = 1 };
92
93static std::optional<eCustomDataType> node_type_from_other_socket(const bNodeSocket &socket)
94{
95 switch (socket.type) {
96 case SOCK_FLOAT:
97 return CD_PROP_FLOAT;
98 case SOCK_BOOLEAN:
99 case SOCK_INT:
100 return CD_PROP_INT32;
101 case SOCK_VECTOR:
102 case SOCK_RGBA:
103 case SOCK_ROTATION:
104 return CD_PROP_FLOAT3;
105 case SOCK_MATRIX:
106 return CD_PROP_FLOAT4X4;
107 default:
108 return std::nullopt;
109 }
110}
111
113{
114 const NodeDeclaration &declaration = *params.node_type().static_declaration;
115 search_link_ops_for_declarations(params, declaration.inputs);
116
117 const std::optional<eCustomDataType> type = node_type_from_other_socket(params.other_socket());
118 if (!type) {
119 return;
120 }
121 if (params.in_out() == SOCK_OUT) {
122 params.add_item(
123 IFACE_("Leading"),
124 [type](LinkSearchOpParams &params) {
125 bNode &node = params.add_node("GeometryNodeAccumulateField"_ustr);
126 node_storage(node).data_type = *type;
127 params.update_and_connect_available_socket(node, "Leading"_ustr);
128 },
129 0);
130 params.add_item(
131 IFACE_("Trailing"),
132 [type](LinkSearchOpParams &params) {
133 bNode &node = params.add_node("GeometryNodeAccumulateField"_ustr);
134 node_storage(node).data_type = *type;
135 params.update_and_connect_available_socket(node, "Trailing"_ustr);
136 },
137 -1);
138 params.add_item(
139 IFACE_("Total"),
140 [type](LinkSearchOpParams &params) {
141 bNode &node = params.add_node("GeometryNodeAccumulateField"_ustr);
142 node_storage(node).data_type = *type;
143 params.update_and_connect_available_socket(node, "Total"_ustr);
144 },
145 -2);
146 }
147 else {
148 params.add_item(
149 IFACE_("Value"),
150 [type](LinkSearchOpParams &params) {
151 bNode &node = params.add_node("GeometryNodeAccumulateField"_ustr);
152 node_storage(node).data_type = *type;
153 params.update_and_connect_available_socket(node, "Value"_ustr);
154 },
155 0);
156 }
157}
158
159template<typename T> struct AccumulationInfo {
160 static inline const T initial_value = []() {
161 if constexpr (std::is_same_v<T, float4x4>) {
162 return float4x4::identity();
163 }
164 else {
165 return T();
166 }
167 }();
168
169 static T accumulate(const T &a, const T &b)
170 {
171 if constexpr (std::is_same_v<T, float4x4>) {
172 return a * b;
173 }
174 else {
175 return a + b;
176 }
177 }
178};
179
181 private:
182 GField input_;
183 Field<int> group_index_;
184 AttrDomain source_domain_;
185 AccumulationMode accumulation_mode_;
186
187 public:
188 AccumulateFieldInput(const AttrDomain source_domain,
189 GField input,
190 Field<int> group_index,
191 AccumulationMode accumulation_mode)
192 : bke::GeometryFieldInput(input.cpp_type(), "Accumulation"),
193 input_(std::move(input)),
194 group_index_(std::move(group_index)),
195 source_domain_(source_domain),
196 accumulation_mode_(accumulation_mode)
197 {
198 }
199
201 const IndexMask & /*mask*/) const final
202 {
203 const AttributeAccessor attributes = *context.attributes();
204 const int64_t domain_size = attributes.domain_size(source_domain_);
205 if (domain_size == 0) {
206 return {};
207 }
208
209 const bke::GeometryFieldContext source_context{context, source_domain_};
210 fn::FieldEvaluator evaluator{source_context, domain_size};
211 evaluator.add(input_);
212 evaluator.add(group_index_);
213 evaluator.evaluate();
214 const GVArray g_values = evaluator.get_evaluated(0);
215 const VArray<int> group_indices = evaluator.get_evaluated<int>(1);
216
217 GVArray g_output;
218
219 g_values.type().to_static_type<int, float, float3, float4x4>([&]<typename T>() {
220 Array<T> outputs(domain_size);
221 const VArray<T> values = g_values.typed<T>();
222
223 if (group_indices.is_single()) {
225 if (accumulation_mode_ == AccumulationMode::Leading) {
226 for (const int i : values.index_range()) {
227 accumulation = AccumulationInfo<T>::accumulate(accumulation, values[i]);
228 outputs[i] = accumulation;
229 }
230 }
231 else {
232 for (const int i : values.index_range()) {
233 outputs[i] = accumulation;
234 accumulation = AccumulationInfo<T>::accumulate(accumulation, values[i]);
235 }
236 }
237 }
238 else {
239 Map<int, T> accumulations;
240 if (accumulation_mode_ == AccumulationMode::Leading) {
241 for (const int i : values.index_range()) {
242 T &accumulation_value = accumulations.lookup_or_add(
243 group_indices[i], AccumulationInfo<T>::initial_value);
244 accumulation_value = AccumulationInfo<T>::accumulate(accumulation_value, values[i]);
245 outputs[i] = accumulation_value;
246 }
247 }
248 else {
249 for (const int i : values.index_range()) {
250 T &accumulation_value = accumulations.lookup_or_add(
251 group_indices[i], AccumulationInfo<T>::initial_value);
252 outputs[i] = accumulation_value;
253 accumulation_value = AccumulationInfo<T>::accumulate(accumulation_value, values[i]);
254 }
255 }
256 }
257
258 g_output = VArray<T>::from_container(std::move(outputs));
259 });
260
261 return attributes.adapt_domain(std::move(g_output), source_domain_, context.domain());
262 }
263
264 void foreach_recursive_field(FunctionRef<void(const GField &)> fn) const override
265 {
266 fn(input_);
267 fn(group_index_);
268 }
269
270 void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep &deep_hash_cache) const override
271 {
272 static constexpr int8_t id = 0;
273 hash.add(&id);
274 hash.add(deep_hash_cache.ensure(input_));
275 hash.add(deep_hash_cache.ensure(group_index_));
276 hash.add(source_domain_);
277 hash.add(accumulation_mode_);
278 }
279
280 std::optional<AttrDomain> preferred_domain(
281 const GeometryComponent & /*component*/) const override
282 {
283 return source_domain_;
284 }
285};
286
288 private:
289 GField input_;
290 Field<int> group_index_;
291 AttrDomain source_domain_;
292
293 public:
294 TotalFieldInput(const AttrDomain source_domain, GField input, Field<int> group_index)
295 : bke::GeometryFieldInput(input.cpp_type(), "Total Value"),
296 input_(std::move(input)),
297 group_index_(std::move(group_index)),
298 source_domain_(source_domain)
299 {
300 }
301
303 const IndexMask & /*mask*/) const final
304 {
305 const AttributeAccessor attributes = *context.attributes();
306 const int64_t domain_size = attributes.domain_size(source_domain_);
307 if (domain_size == 0) {
308 return {};
309 }
310
311 const bke::GeometryFieldContext source_context{context, source_domain_};
312 fn::FieldEvaluator evaluator{source_context, domain_size};
313 evaluator.add(input_);
314 evaluator.add(group_index_);
315 evaluator.evaluate();
316 const GVArray g_values = evaluator.get_evaluated(0);
317 const VArray<int> group_indices = evaluator.get_evaluated<int>(1);
318
319 GVArray g_outputs;
320
321 g_values.type().to_static_type<int, float, float3, float4x4>([&]<typename T>() {
322 const VArray<T> values = g_values.typed<T>();
323 if (group_indices.is_single()) {
325 for (const int i : values.index_range()) {
326 accumulation = AccumulationInfo<T>::accumulate(accumulation, values[i]);
327 }
328 g_outputs = VArray<T>::from_single(accumulation, domain_size);
329 }
330 else {
331 Map<int, T> accumulations;
332 for (const int i : values.index_range()) {
333 T &value = accumulations.lookup_or_add(group_indices[i],
335 value = AccumulationInfo<T>::accumulate(value, values[i]);
336 }
337 Array<T> outputs(domain_size);
338 for (const int i : values.index_range()) {
339 outputs[i] = accumulations.lookup(group_indices[i]);
340 }
341 g_outputs = VArray<T>::from_container(std::move(outputs));
342 }
343 });
344
345 return attributes.adapt_domain(std::move(g_outputs), source_domain_, context.domain());
346 }
347
348 void foreach_recursive_field(FunctionRef<void(const GField &)> fn) const override
349 {
350 fn(input_);
351 fn(group_index_);
352 }
353
354 void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep &deep_hash_cache) const override
355 {
356 static constexpr int8_t id = 0;
357 hash.add(&id);
358 hash.add(deep_hash_cache.ensure(input_));
359 hash.add(deep_hash_cache.ensure(group_index_));
360 hash.add(source_domain_);
361 }
362
363 std::optional<AttrDomain> preferred_domain(
364 const GeometryComponent & /*component*/) const override
365 {
366 return source_domain_;
367 }
368};
369
371{
372 const NodeAccumulateField &storage = node_storage(params.node());
373 const AttrDomain source_domain = AttrDomain(storage.domain);
374
375 const Field<int> group_index_field = params.extract_input<Field<int>>("Group Index"_ustr);
376 const GField input_field = params.extract_input<GField>("Value"_ustr);
377 if (params.output_is_required("Leading"_ustr)) {
378 params.set_output<GField>(
379 "Leading"_ustr,
381 source_domain, input_field, group_index_field, AccumulationMode::Leading));
382 }
383 if (params.output_is_required("Trailing"_ustr)) {
384 params.set_output<GField>(
385 "Trailing"_ustr,
387 source_domain, input_field, group_index_field, AccumulationMode::Trailing));
388 }
389 if (params.output_is_required("Total"_ustr)) {
390 params.set_output<GField>(
391 "Total"_ustr,
392 GField::from_input<TotalFieldInput>(source_domain, input_field, group_index_field));
393 }
394}
395
396static void node_rna(StructRNA *srna)
397{
398 static EnumPropertyItem items[] = {
399 {CD_PROP_FLOAT, "FLOAT", ICON_NODE_SOCKET_FLOAT, "Float", "Add floating point values"},
400 {CD_PROP_INT32, "INT", ICON_NODE_SOCKET_INT, "Integer", "Add integer values"},
401 {CD_PROP_FLOAT3, "FLOAT_VECTOR", ICON_NODE_SOCKET_VECTOR, "Vector", "Add 3D vector values"},
403 "TRANSFORM",
404 ICON_NODE_SOCKET_MATRIX,
405 "Transform",
406 "Multiply transformation matrices"},
407 {0, nullptr, 0, nullptr, nullptr},
408 };
409
411 "data_type",
412 "Data Type",
413 "Type of data that is accumulated",
414 items,
417
419 "domain",
420 "Domain",
421 "",
424 int(AttrDomain::Point),
425 nullptr,
426 true);
427}
428
429static void node_register()
430{
431 static bke::bNodeType ntype;
432 geo_node_type_base(&ntype, "GeometryNodeAccumulateField"_ustr, GEO_NODE_ACCUMULATE_FIELD);
433 ntype.ui_name = "Accumulate Field";
434 ntype.ui_description =
435 "Add the values of an evaluated field together and output the running total for each "
436 "element";
437 ntype.enum_name_legacy = "ACCUMULATE_FIELD";
440 ntype.initfunc = node_init;
442 ntype.declare = node_declare;
445 ntype, "NodeAccumulateField", node_free_standard_storage, node_copy_standard_storage);
447
448 node_rna(ntype.rna_ext.srna);
449}
451
452} // namespace blender::nodes::node_geo_accumulate_field_cc
#define NODE_CLASS_CONVERTER
Definition BKE_node.hh:484
#define NODE_STORAGE_FUNCS(StorageT)
Definition BKE_node.hh:1353
#define GEO_NODE_ACCUMULATE_FIELD
#define final(a, b, c)
Definition BLI_hash_c.hh:21
#define IFACE_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_storage_enum_accessors(member)
#define UI_ITEM_NONE
#define BLI_assert_unreachable()
void to_static_type(Fn &&fn) const
const Value & lookup(const Key &key) const
Definition BLI_map.hh:545
Value & lookup_or_add(const Key &key, const Value &value)
Definition BLI_map.hh:588
IndexRange index_range() const
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
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
BaseSocketDeclarationBuilder & structure_type(StructureType structure_type)
BaseSocketDeclarationBuilder & description(std::string value="")
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
AccumulateFieldInput(const AttrDomain source_domain, GField input, Field< int > group_index, AccumulationMode accumulation_mode)
GVArray get_varray_for_context(const bke::GeometryFieldContext &context, const IndexMask &) const final
void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep &deep_hash_cache) const override
std::optional< AttrDomain > preferred_domain(const GeometryComponent &) const override
void foreach_recursive_field(FunctionRef< void(const GField &)> fn) const override
void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep &deep_hash_cache) const override
std::optional< AttrDomain > preferred_domain(const GeometryComponent &) const override
TotalFieldInput(const AttrDomain source_domain, GField input, Field< int > group_index)
GVArray get_varray_for_context(const bke::GeometryFieldContext &context, const IndexMask &) const final
void foreach_recursive_field(FunctionRef< void(const GField &)> fn) const override
#define storage(slot, qualifiers)
#define T
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
void node_type_storage(bNodeType &ntype, std::optional< StringRefNull > storagename, void(*freefunc)(bNode *node), void(*copyfunc)(bNodeTree *dest_ntree, bNode *dest_node, const bNode *src_node))
Definition node.cc:6166
static void node_declare(NodeDeclarationBuilder &b)
static std::optional< eCustomDataType > node_type_from_other_socket(const bNodeSocket &socket)
static void node_init(bNodeTree *, bNode *node)
static void node_gather_link_searches(GatherLinkSearchOpParams &params)
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
static void node_geo_exec(GeoNodeExecParams params)
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
MatBase< float, 4, 4 > float4x4
BMesh const char void * data
void node_copy_standard_storage(bNodeTree *, bNode *dest_node, const bNode *src_node)
Definition node_util.cc:57
void node_free_standard_storage(bNode *node)
Definition node_util.cc:45
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
const char * enum_name_legacy
Definition BKE_node.hh:274
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)