Blender V5.3
field.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 "BLI_set.hh"
10#include "BLI_stack.hh"
11
12#include "FN_field.hh"
14
15#include <xxhash.h>
16
17namespace blender::fn {
18
19FieldInput::FieldInput(const CPPType &type, std::string debug_name)
20 : type_(&type), debug_name_(std::move(debug_name))
21{
22}
23
24GField GField::from_constant(const CPPType &type, const void *value)
25{
27 TrivialInlineConstant constant;
28 constant.type = &type;
29 type.copy_construct(value, constant.value.ptr());
30 return GField(constant);
31 }
32 void *new_value = MEM_new_uninitialized_aligned(type.size, type.alignment, __func__);
33 type.copy_construct(value, new_value);
34 return GField(OwnedConstant{&type, new_value});
35}
36
37bool operator==(const GField &a, const GField &b)
38{
39 const GField &a_ref = a.deref_field_ref();
40 const GField &b_ref = b.deref_field_ref();
41
42 return std::visit(
43 [&]<typename T>(const T &v_a) -> bool {
44 if constexpr (std::is_same_v<T, GField::Input>) {
45 if (const auto *v_b = std::get_if<GField::Input>(&b_ref.variant_)) {
46 return v_a.node == v_b->node;
47 }
48 return false;
49 }
50 else if constexpr (std::is_same_v<T, GField::MultiFn>) {
51 if (const auto *v_b = std::get_if<GField::MultiFn>(&b_ref.variant_)) {
52 return v_a.node == v_b->node && v_a.output_i == v_b->output_i;
53 }
54 return false;
55 }
56 else if constexpr (std::is_same_v<T, GField::FieldRef>) {
57 /* Should not exist due to #deref_field_ref above. */
59 return false;
60 }
61 else if constexpr (GField::is_constant_value_v<T>) {
62 const CPPType &type_a = *v_a.type;
63 const void *constant_a = v_a.value;
64 return std::visit(
65 [&]<typename U>(const U &v_b) -> bool {
66 if constexpr (GField::is_constant_value_v<U>) {
67 const CPPType &type_b = *v_b.type;
68 if (type_a != type_b) {
69 return false;
70 }
71 const void *constant_b = v_b.value;
72 return type_a.is_equal_or_false(constant_a, constant_b);
73 }
74 else {
75 return false;
76 }
77 },
78 b_ref.variant_);
79 }
80 else {
82 }
83 },
84 a_ref.variant_);
85}
86
88{
89 const GField &ref = this->deref_field_ref();
90 return std::visit(
91 [&]<typename T>(const T &v) -> uint64_t {
92 if constexpr (std::is_same_v<T, Input>) {
93 return get_default_hash(v.node);
94 }
95 else if constexpr (std::is_same_v<T, MultiFn>) {
96 return get_default_hash(v.node, v.output_i);
97 }
98 else if constexpr (std::is_same_v<T, FieldRef>) {
99 /* Should not exist due to #deref_field_ref above. */
101 return 0;
102 }
103 else if constexpr (is_constant_value_v<T>) {
104 return v.type->hash_or_fallback(v.value, uint64_t(v.type));
105 }
106 else {
108 }
109 },
110 ref.variant_);
111}
112
114{
115 if (const UniqueHash *cached = this->cache.lookup_ptr(field)) {
116 return *cached;
117 }
118
119 /* With a post-order DFS traversal, push each node twice. On the first pop (not yet in
120 * `visited`), push a field's children. On the second pop (already in `visited`), all children
121 * will be in `cache`, so compute and store the hash. Checking the cache for a hash avoids
122 * duplicate work when the same sub-field is reached via multiple paths (e.g. diamond-shaped
123 * graphs). */
124 Set<GFieldRef, 8> visited;
126 stack.push(field);
127 while (!stack.is_empty()) {
128 GFieldRef current = stack.pop();
129 if (this->cache.contains(current)) {
130 continue;
131 }
132 if (visited.contains(current)) {
133 UniqueHashBytes hash_context;
134 std::visit(
135 [&]<typename T>(const T &v) {
136 if constexpr (std::is_same_v<T, GFieldRef::Value>) {
137 v.type->hash_unique(v.value, hash_context);
138 hash_context.add(v.type);
139 }
140 else if constexpr (std::is_same_v<T, GFieldRef::Input>) {
141 v.node->hash_unique(hash_context, *this);
142 }
143 else if constexpr (std::is_same_v<T, GFieldRef::MultiFn>) {
144 v.node->multi_function().hash_unique(hash_context);
145 hash_context.add(v.output_i);
146 for (const GField &input_field : v.node->inputs()) {
147 hash_context.add(this->cache.lookup(input_field));
148 }
149 }
150 else {
152 }
153 },
154 current.variant());
155 const Span bytes = hash_context.data.as_span();
157 const XXH128_hash_t xxhash = XXH3_128bits(bytes.data(), bytes.size());
158 static_assert(sizeof(UniqueHash) == sizeof(xxhash));
159 memcpy(static_cast<void *>(&hash), &xxhash, sizeof(xxhash));
160 this->cache.add_new(current, hash);
161 continue;
162 }
163 visited.add(current);
164 stack.push(current);
165 if (const auto *multi_fn = std::get_if<GFieldRef::MultiFn>(&current.variant())) {
166 for (const GField &input : multi_fn->node->inputs()) {
167 stack.push(input);
168 }
169 }
170 }
171
172 return this->cache.lookup(field);
173}
174
176{
178 FieldInputs *inputs = MEM_new<FieldInputs>("field_inputs");
179 inputs->inputs.add(*this);
181 });
182 return field_inputs_;
183}
184
186{
187 UniqueHashBytes hash_context;
188 FieldHashDeep deep_hash_cache;
189 this->hash_unique(hash_context, deep_hash_cache);
190 return get_default_hash(hash_context.data);
191}
192
193FieldInput::~FieldInput() = default;
194
195void FieldInput::foreach_recursive_field(FunctionRef<void(const GField &)> /*fn*/) const {}
196
198{
199 hash.add(this);
200}
201
203{
204 MultiFn *multi_fn = std::get_if<MultiFn>(&variant_);
205 if (!multi_fn || !multi_fn->node) {
206 return nullptr;
207 }
208 return std::move(multi_fn->node);
209}
210
212{
213 MEM_delete(this);
214}
215
217{
218 this->delete_input_fields();
219 MEM_delete(this);
220}
221
222void FieldOperation::delete_input_fields()
223{
224 BLI_assert(this->is_expired());
225 /* Some input fields are freed iteratively instead of recursively to avoid a potentially very
226 * deep call stack. */
228 for (GField &input : inputs_) {
229 if (FieldOperationPtr input_op = input.try_extract_operation()) {
230 remaining.append(std::move(input_op));
231 }
232 }
233 while (!remaining.is_empty()) {
234 FieldOperationPtr op = remaining.pop_last();
235 if (!op->is_mutable()) {
236 continue;
237 }
238 FieldOperation &op_ref = const_cast<FieldOperation &>(*op);
239 for (GField &input : op_ref.inputs_) {
240 if (FieldOperationPtr input_op = input.try_extract_operation()) {
241 remaining.append(std::move(input_op));
242 }
243 }
244 }
245}
246
248{
249 MEM_delete(this);
250}
251
252FieldOperationPtr FieldOperation::from(std::shared_ptr<const mf::MultiFunction> fn,
254{
255 return FieldOperationPtr(MEM_new<FieldOperation>(__func__, std::move(fn), std::move(inputs)));
256}
257
259{
260 return FieldOperationPtr(MEM_new<FieldOperation>(__func__, fn, std::move(inputs)));
261}
262
267{
268 /* Try to find an existing #FieldInputsPtr that covers all given fields. */
269 bool candidate_valid = true;
270 const FieldInputsPtr *candidate = nullptr;
271 for (const GField &field : fields) {
272 const FieldInputsPtr &field_inputs_ptr = field.field_inputs();
273 if (!field_inputs_ptr) {
274 continue;
275 }
276 if (!candidate) {
277 candidate = &field_inputs_ptr;
278 continue;
279 }
280 if (field_inputs_ptr == *candidate) {
281 continue;
282 }
283 const FieldInputsPtr *smaller_candidate = candidate;
284 const FieldInputsPtr *larger_candidate = &field_inputs_ptr;
285 if ((*smaller_candidate)->inputs.size() > (*larger_candidate)->inputs.size()) {
286 std::swap(smaller_candidate, larger_candidate);
287 }
288 /* Check if the smaller candidate is fully contained in the larger one. */
289 for (const FieldInput &field_input : (*smaller_candidate)->inputs) {
290 if (!(*larger_candidate)->inputs.contains(field_input)) {
291 candidate_valid = false;
292 break;
293 }
294 }
295 if (!candidate_valid) {
296 break;
297 }
298 candidate = larger_candidate;
299 }
300 if (candidate_valid) {
301 if (candidate) {
302 return *candidate;
303 }
304 return {};
305 }
306 /* None of the existing #FieldInputs can be reused, create a new #FieldInputs and add all the
307 * inputs to it. */
308 FieldInputs *new_field_inputs = MEM_new<FieldInputs>(__func__);
309 for (const GField &field : fields) {
310 const FieldInputsPtr &field_inputs_ptr = field.field_inputs();
311 if (!field_inputs_ptr) {
312 continue;
313 }
314 for (const FieldInput &field_input : field_inputs_ptr->inputs) {
315 new_field_inputs->inputs.add(field_input);
316 }
317 }
318 return FieldInputsPtr(new_field_inputs);
319}
320
321GField::GField(const GField &other) : variant_(other.variant_)
322{
323 std::visit(
324 [&]<typename T>(T &v) {
325 if constexpr (std::is_same_v<T, OwnedConstant>) {
326 void *new_value = MEM_new_uninitialized_aligned(
327 v.type->size, v.type->alignment, "GField::GField()");
328 v.type->copy_construct(v.value, new_value);
329 v.value = new_value;
330 }
331 },
332 variant_);
333}
334
335GField::GField(GField &&other) noexcept : variant_(std::move(other.variant_))
336{
337 const CPPType &type = this->cpp_type();
338 other.variant_ = ConstantRef{&type, type.default_value()};
339}
340
342{
343 if (this == &other) {
344 return *this;
345 }
346 this->~GField();
347 new (this) GField(other);
348 return *this;
349}
350
353 if (this == &other) {
354 return *this;
355 }
356 this->~GField();
357 new (this) GField(std::move(other));
358 return *this;
359}
360
362{
363 std::visit(
364 [&]<typename T>(T &v) {
365 if constexpr (std::is_same_v<T, OwnedConstant>) {
366 v.type->destruct(v.value);
367 MEM_delete_void(v.value);
368 }
369 },
370 variant_);
371}
372
374 : variant_(std::visit(
375 []<typename T>(const T &v) -> Variant {
376 if constexpr (std::is_same_v<T, GField::Input>) {
377 return Input{v.node.get()};
378 }
379 else if constexpr (std::is_same_v<T, GField::MultiFn>) {
380 return MultiFn{v.node.get(), v.output_i};
381 }
382 else if constexpr (std::is_same_v<T, GField::FieldRef>) {
383 /* Should not exist due to #deref_field_ref. */
385 return Value{};
386 }
387 else if constexpr (GField::is_constant_value_v<T>) {
388 return Value{v.type, v.value};
389 }
390 else {
392 }
393 },
394 field.deref_field_ref().variant()))
395{
396}
397
399{
400 static const ImplicitSharingPtr<FieldInputs> empty_inputs;
401 return std::visit(
402 [&]<typename T>(const T &v) -> const FieldInputsPtr & {
403 if constexpr (std::is_same_v<T, Input>) {
404 return v.node->field_inputs();
405 }
406 else if constexpr (std::is_same_v<T, MultiFn>) {
407 return v.node->field_inputs();
408 }
409 else if constexpr (std::is_same_v<T, Value>) {
410 return empty_inputs;
411 }
412 else {
414 }
415 },
416 variant_);
417}
418
419bool operator==(const GFieldRef &a, const GFieldRef &b)
420{
421 return std::visit(
422 [&]<typename T>(const T &v_a) -> bool {
423 if constexpr (std::is_same_v<T, GFieldRef::Value>) {
424 if (const auto *v_b = std::get_if<GFieldRef::Value>(&b.variant())) {
425 if (v_a.type != v_b->type) {
426 return false;
427 }
428 if (v_a.value == v_b->value) {
429 /* This may return true even if the values don't compare equal, e.g. due to NaN
430 * values. */
431 return true;
432 }
433 return v_a.type->is_equal_or_false(v_a.value, v_b->value);
434 }
435 return false;
436 }
437 else if constexpr (std::is_same_v<T, GFieldRef::Input>) {
438 if (const auto *v_b = std::get_if<GFieldRef::Input>(&b.variant())) {
439 return v_a.node == v_b->node;
440 }
441 return false;
442 }
443 else if constexpr (std::is_same_v<T, GFieldRef::MultiFn>) {
444 if (const auto *v_b = std::get_if<GFieldRef::MultiFn>(&b.variant())) {
445 return v_a.node == v_b->node && v_a.output_i == v_b->output_i;
446 }
447 return false;
448 }
449 else {
451 }
452 },
453 a.variant());
454}
455
457{
458 return std::visit(
459 [&]<typename T>(const T &v) -> uint64_t {
460 if constexpr (std::is_same_v<T, Value>) {
461 return v.type->hash_or_fallback(v.value, uint64_t(v.type));
462 }
463 else if constexpr (std::is_same_v<T, Input>) {
464 return get_default_hash(v.node);
465 }
466 else if constexpr (std::is_same_v<T, MultiFn>) {
467 return get_default_hash(v.node, v.output_i);
468 }
469 else {
471 }
472 },
473 variant_);
474}
475
476FieldOperation::FieldOperation(std::shared_ptr<const mf::MultiFunction> fn, Vector<GField> inputs)
477 : FieldOperation(*fn, std::move(inputs))
478{
479 owned_fn_ = std::move(fn);
480}
481
483 : inputs_(inputs), fn_(&fn)
484{
485 field_inputs_ = combine_field_inputs(inputs_);
486}
487
488const CPPType &FieldOperation::output_cpp_type(const int output_i) const
489{
490 int count = 0;
491 for (const int param_index : fn_->param_indices()) {
492 const mf::ParamType param_type = fn_->param_type(param_index);
493 if (param_type.is_output()) {
494 if (count == output_i) {
495 return param_type.data_type().single_type();
496 }
497 count++;
498 }
499 }
501 return CPPType::get<float>();
502}
503
505{
506 static const ImplicitSharingPtr<FieldInputs> empty_inputs;
507 return std::visit(
508 []<typename T>(const T &v) -> const FieldInputsPtr & {
509 if constexpr (is_same_any_v<T, Input, MultiFn>) {
510 return v.node->field_inputs();
511 }
512 else if constexpr (std::is_same_v<T, FieldRef>) {
513 return v.field_ref->field_inputs();
514 }
516 return empty_inputs;
517 }
518 else {
520 }
521 },
522 this->variant_);
523}
524
526 const IndexMask &mask,
527 ResourceScope &scope) const
528{
529 /* By default ask the field input to create the varray. Another field context might overwrite
530 * the context here. */
531 return field_input.get_varray_for_context(*this, mask, scope);
532}
533
535
537{
538 auto index_func = [](int i) { return i; };
539 return VArray<int>::from_func(mask.min_array_size(), index_func);
540}
541
543 const IndexMask &mask,
544 ResourceScope & /*scope*/) const
545{
546 /* TODO: Investigate a similar method to IndexRange::as_span() */
547 return get_index_varray(mask);
548}
549
551 fn::FieldHashDeep & /*deep_hash_cache*/) const
552{
553 static constexpr int8_t id = 0;
554 hash.add(&id);
555}
556
558{
560 static const Field<int> field_ref = Field<int>::from_non_owning_ref(field);
561 return field_ref;
562}
563
565{
566 const mf::MultiFunction &not_fn = fn::multi_function::registry::lookup("!bool"_ustr);
567 auto not_op = FieldOperation::from(not_fn, {field});
568 return GField(not_op, 0).typed<bool>();
569}
570
571} // namespace blender::fn
#define BLI_assert_unreachable()
#define BLI_assert_unreachable_static_t(T)
static const CPPType & get()
bool is_equal_or_false(const void *a, const void *b) const
void copy_construct(const void *src, void *dst) const
const void * default_value() const
void ensure(const FunctionRef< void()> compute_cache)
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
constexpr const T * data() const
Definition BLI_span.hh:219
constexpr int64_t size() const
Definition BLI_span.hh:256
bool is_empty() const
Definition BLI_stack.hh:310
void push(const T &value)
Definition BLI_stack.hh:215
static VArray from_func(const int64_t size, GetFunc get_func)
void append(const T &value)
bool is_empty() const
virtual GVArray get_varray_for_input(const FieldInput &field_input, const IndexMask &mask, ResourceScope &scope) const
Definition field.cc:525
FieldInput(const CPPType &type, std::string debug_name="")
Definition field.cc:19
std::string debug_name_
Definition FN_field.hh:342
StringRefNull debug_name() const
Definition FN_field.hh:569
FieldInputsPtr field_inputs_
Definition FN_field.hh:349
virtual void hash_unique(UniqueHashBytes &hash, FieldHashDeep &deep_hash_cache) const
Definition field.cc:197
const FieldInputsPtr & field_inputs() const
Definition field.cc:175
void delete_self() override
Definition field.cc:211
uint64_t hash() const
Definition field.cc:185
virtual void foreach_recursive_field(FunctionRef< void(const GField &)> fn) const
Definition field.cc:195
CacheMutex field_inputs_mutex_
Definition FN_field.hh:348
const CPPType * type_
Definition FN_field.hh:341
virtual GVArray get_varray_for_context(const FieldContext &context, const IndexMask &mask, ResourceScope &scope) const =0
void delete_self() override
Definition field.cc:247
VectorSet< std::reference_wrapper< const FieldInput > > inputs
Definition FN_field.hh:327
static FieldOperationPtr from(std::shared_ptr< const mf::MultiFunction > fn, Vector< GField > inputs)
Definition field.cc:252
void delete_self() override
Definition field.cc:216
const CPPType & output_cpp_type(int output_i) const
Definition field.cc:488
Span< GField > inputs() const
Definition FN_field.hh:654
FieldOperation(std::shared_ptr< const mf::MultiFunction > fn, Vector< GField > inputs)
Definition field.cc:476
static Field from_non_owning_ref(const Field &field)
Definition FN_field.hh:477
static Field from_input(Args &&...args)
const FieldInputsPtr & field_inputs() const
Definition field.cc:398
std::variant< Value, Input, MultiFn > Variant
Definition FN_field.hh:260
uint64_t hash() const
Definition field.cc:456
const Variant & variant() const
Definition FN_field.hh:678
GFieldRef(const GField &field)
Definition field.cc:373
static GField from_constant(const CPPType &type, const void *value)
Definition field.cc:24
static constexpr bool is_constant_value_v
Definition FN_field.hh:107
uint64_t hash() const
Definition field.cc:87
friend bool operator==(const GField &a, const GField &b)
Definition field.cc:37
const FieldInputsPtr & field_inputs() const
Definition field.cc:504
GField & operator=(const GField &other)
Definition field.cc:341
FieldOperationPtr try_extract_operation()
Definition field.cc:202
const CPPType & cpp_type() const
Definition FN_field.hh:518
const GField & deref_field_ref() const
Definition FN_field.hh:541
static GVArray get_index_varray(const IndexMask &mask)
Definition field.cc:536
GVArray get_varray_for_context(const FieldContext &context, const IndexMask &mask, ResourceScope &scope) const final
Definition field.cc:542
static const Field< int > & get_field()
Definition field.cc:557
void hash_unique(UniqueHashBytes &hash, FieldHashDeep &deep_hash_cache) const override
Definition field.cc:550
#define T
const MultiFunction & lookup(UString id)
ImplicitSharingPtr< FieldOperation > FieldOperationPtr
Definition FN_field.hh:44
ImplicitSharingPtr< FieldInputs > FieldInputsPtr
Definition FN_field.hh:45
static FieldInputsPtr combine_field_inputs(const Span< GField > &fields)
Definition field.cc:266
bool operator==(const GField &a, const GField &b)
Definition field.cc:37
Field< bool > invert_boolean_field(const Field< bool > &field)
Definition field.cc:564
UserDef U
Definition blender.cc:58
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
unsigned __int64 uint64_t
Definition BKE_text.h:91
constexpr bool is_same_any_v
ATTR_WARN_UNUSED_RESULT const BMVert * v
void MEM_delete_void(void *vmemh)
void * MEM_new_uninitialized_aligned(size_t len, size_t alignment, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(3)
constexpr uint64_t get_default_hash(const T &v, const Args &...args)
Definition BLI_hash.hh:252
signed char int8_t
Definition BKE_text.h:76
#define hash
Definition noise_c.cc:156
Vector< std::byte, 256 > data
void add(const T &value)
Map< GFieldRef, UniqueHash > cache
Definition FN_field.hh:307
UniqueHash ensure(const GFieldRef &field)
Definition field.cc:113
FieldOperationPtr node
Definition FN_field.hh:62
static bool cpp_type_supported(const CPPType &type)
Definition FN_field.hh:466
AlignedBuffer< inline_size, inline_alignment > value
Definition FN_field.hh:96