Blender V5.3
node_geo_instance_on_points.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
5#include "BLI_array_utils.hh"
6#include "BLI_math_matrix.hh"
8#include "BLI_task.hh"
9
10#include "BKE_curves.hh"
11#include "BKE_grease_pencil.hh"
12#include "BKE_instances.hh"
13
16
17#include "node_geometry_util.hh"
18
20
22{
23 b.add_input<decl::Geometry>("Points"_ustr).description("Points to instance on");
24 b.add_input<decl::Bool>("Selection"_ustr)
25 .default_value(true)
26 .evaluated_geometry_field({0})
27 .hide_value();
28 b.add_input<decl::Geometry>("Instance"_ustr)
29 .description("Geometry that is instanced on the points");
30 b.add_input<decl::Bool>("Pick Instance"_ustr)
31 .evaluated_geometry_field({0})
32 .description(
33 "Choose instances from the \"Instance\" input at each point instead of instancing the "
34 "entire geometry");
35 b.add_input<decl::Int>("Instance Index"_ustr)
36 .evaluated_geometry_field({0})
37 .default_input_type(NODE_DEFAULT_INPUT_ID_INDEX_FIELD)
39 "Index of the instance used for each point. This is only used when Pick Instances "
40 "is on. By default the point index is used");
41 b.add_input<decl::Rotation>("Rotation"_ustr)
42 .evaluated_geometry_field({0})
43 .description("Rotation of the instances");
44 b.add_input<decl::Vector>("Scale"_ustr)
45 .default_value({1.0f, 1.0f, 1.0f})
46 .subtype(PROP_XYZ)
47 .evaluated_geometry_field({0})
48 .description("Scale of the instances");
49
50 b.add_output<decl::Geometry>("Instances"_ustr).propagate_all_geometry();
51}
52
53static std::unique_ptr<bke::Instances> add_instances_from_component(
54 const AttributeAccessor &src_attributes,
55 const GeometrySet &instance,
56 const fn::FieldContext &field_context,
57 const GeoNodeExecParams &params,
58 const bke::AttributeFilter &attribute_filter)
59{
60 const AttrDomain domain = AttrDomain::Point;
61 const int domain_num = src_attributes.domain_size(domain);
62
63 VArray<bool> pick_instance;
64 VArray<int> indices;
66 VArray<float3> scales;
67
68 const Field<bool> selection_field = params.get_input<Field<bool>>("Selection"_ustr);
69 fn::FieldEvaluator evaluator{field_context, domain_num};
70 evaluator.set_selection(selection_field);
71 /* The evaluator could use the component's stable IDs as a destination directly, but only the
72 * selected indices should be copied. */
73 evaluator.add(params.get_input<Field<bool>>("Pick Instance"_ustr), &pick_instance);
74 evaluator.add(params.get_input<Field<int>>("Instance Index"_ustr), &indices);
75 evaluator.add(params.get_input<Field<math::Quaternion>>("Rotation"_ustr), &rotations);
76 evaluator.add(params.get_input<Field<float3>>("Scale"_ustr), &scales);
77 evaluator.evaluate();
78
79 const IndexMask selection = evaluator.get_evaluated_selection_as_mask();
80 if (selection.is_empty()) {
81 return {};
82 }
83
84 auto dst_component = std::make_unique<bke::Instances>(selection.size());
85
86 MutableSpan<int> dst_handles = dst_component->reference_handles_for_write();
87 MutableSpan<float4x4> dst_transforms = dst_component->transforms_for_write();
88
89 const VArraySpan positions = *src_attributes.lookup<float3>("position");
90
91 const bke::Instances *src_instances = instance.get_instances();
92
93 /* Maps handles from the source instances to handles on the new instance. */
94 Array<int> handle_mapping;
95 /* Only fill #handle_mapping when it may be used below. */
96 if (src_instances != nullptr &&
97 (!pick_instance.is_single() || pick_instance.get_internal_single()))
98 {
99 Span<bke::InstanceReference> src_references = src_instances->references();
100 handle_mapping.reinitialize(src_references.size());
101 for (const int src_instance_handle : src_references.index_range()) {
102 const bke::InstanceReference &reference = src_references[src_instance_handle];
103 const int dst_instance_handle = dst_component->add_reference(reference);
104 handle_mapping[src_instance_handle] = dst_instance_handle;
105 }
106 }
107
108 const int full_instance_handle = dst_component->add_reference(instance);
109 /* Add this reference last, because it is the most likely one to be removed later on. */
110 const int empty_reference_handle = dst_component->add_reference(bke::InstanceReference());
111
112 selection.foreach_index(
113 [&](const int64_t i, const int64_t range_i) {
114 /* Compute base transform for every instances. */
115 float4x4 &dst_transform = dst_transforms[range_i];
116 dst_transform = math::from_loc_rot_scale<float4x4>(positions[i], rotations[i], scales[i]);
117
118 /* Reference that will be used by this new instance. */
119 int dst_handle = empty_reference_handle;
120
121 const bool use_individual_instance = pick_instance[i];
122 if (use_individual_instance) {
123 if (src_instances != nullptr) {
124 const int src_instances_num = src_instances->instances_num();
125 const int original_index = indices[i];
126 /* Use #mod_i instead of `%` to get the desirable wrap around behavior where -1
127 * refers to the last element. */
128 const int index = mod_i(original_index, std::max(src_instances_num, 1));
129 if (index < src_instances_num) {
130 /* Get the reference to the source instance. */
131 const int src_handle = src_instances->reference_handles()[index];
132 dst_handle = handle_mapping[src_handle];
133
134 /* Take transforms of the source instance into account. */
135 mul_m4_m4_post(dst_transform.ptr(), src_instances->transforms()[index].ptr());
136 }
137 }
138 }
139 else {
140 /* Use entire source geometry as instance. */
141 dst_handle = full_instance_handle;
142 }
143 /* Set properties of new instance. */
144 dst_handles[range_i] = dst_handle;
145 },
147
148 if (pick_instance.is_single()) {
149 if (pick_instance.get_internal_single()) {
150 if (instance.has_realized_data()) {
151 params.error_message_add(
153 TIP_("Realized geometry is not used when pick instances is true"));
154 }
155 }
156 }
157
158 bke::MutableAttributeAccessor dst_attributes = dst_component->attributes_for_write();
159 src_attributes.foreach_attribute([&](const bke::AttributeIter &iter) {
160 if (ELEM(iter.name, "position", ".reference_index")) {
161 return;
162 }
163 if (attribute_filter.allow_skip(iter.name)) {
164 return;
165 }
166 if (iter.is_builtin) {
167 if (!dst_attributes.is_builtin(iter.name)) {
168 return;
169 }
170 }
172 if (!src) {
173 /* Domain interpolation can fail if the source domain is empty. */
174 return;
175 }
176 const CommonVArrayInfo info = src.varray.common_info();
179 dst_attributes.add(iter.name, bke::AttrDomain::Instance, iter.data_type, init);
180 return;
181 }
183 if (src.sharing_info && selection.size() == domain_num) {
185 dst_attributes.add(iter.name, AttrDomain::Instance, iter.data_type, init);
186 return;
187 }
188 }
191 array_utils::gather(src.varray, selection, dst.span);
192 dst.finish();
193 });
194
195 return dst_component;
196}
197
199{
200 GeometrySet geometry_set = params.extract_input<GeometrySet>("Points"_ustr);
201 GeometrySet instance = params.get_input<GeometrySet>("Instance"_ustr);
202 instance.ensure_owns_direct_data();
203 const NodeAttributeFilter &attribute_filter = params.get_attribute_filter("Instances"_ustr);
204
205 geometry::foreach_real_geometry(geometry_set, [&](GeometrySet &geometry_set) {
206 Vector<bke::GeometrySet> component_instances;
210 {
211 if (geometry_set.has(type)) {
212 const GeometryComponent &component = *geometry_set.get_component(type);
213 const bke::GeometryFieldContext field_context{component, AttrDomain::Point};
214 if (std::unique_ptr<bke::Instances> instances = add_instances_from_component(
215 *component.attributes(), instance, field_context, params, attribute_filter))
216 {
217 component_instances.append(GeometrySet::from_instances(std::move(instances)));
218 }
219 }
220 }
221 if (geometry_set.has_grease_pencil()) {
222 using namespace bke::greasepencil;
223 const GreasePencil &grease_pencil = *geometry_set.get_grease_pencil();
224 auto instances_per_layer = std::make_unique<bke::Instances>();
225
226 Vector<int> handles;
227 Vector<float4x4> transforms;
228 for (const int layer_index : grease_pencil.layers().index_range()) {
229 const Layer &layer = grease_pencil.layer(layer_index);
230 const Drawing *drawing = grease_pencil.get_eval_drawing(layer);
231 if (drawing == nullptr) {
232 continue;
233 }
234 const float4x4 &layer_transform = layer.local_transform();
235 const bke::CurvesGeometry &src_curves = drawing->strokes();
236 if (src_curves.is_empty()) {
237 /* Add an empty reference so the number of layers and instances match.
238 * This makes it easy to reconstruct the layers afterwards and keep their attributes.
239 * Although in this particular case we don't propagate the attributes. */
240 handles.append(instances_per_layer->add_reference(bke::InstanceReference()));
241 transforms.append(layer_transform);
242 continue;
243 }
244 /* TODO: Attributes are not propagating from the curves or the points. */
245 const bke::GreasePencilLayerFieldContext field_context(
246 grease_pencil, AttrDomain::Point, layer_index);
247 if (std::unique_ptr<bke::Instances> layer_instances = add_instances_from_component(
248 src_curves.attributes(), instance, field_context, params, attribute_filter))
249 {
250 GeometrySet temp_set = GeometrySet::from_instances(std::move(layer_instances));
251 handles.append(instances_per_layer->add_reference(bke::InstanceReference{temp_set}));
252 transforms.append(layer_transform);
253 }
254 }
255
256 instances_per_layer->resize(handles.size());
257 instances_per_layer->reference_handles_for_write().copy_from(handles);
258 instances_per_layer->transforms_for_write().copy_from(transforms);
259
260 bke::copy_attributes(geometry_set.get_grease_pencil()->attributes(),
263 attribute_filter,
264 instances_per_layer->attributes_for_write());
265
266 component_instances.append(GeometrySet::from_instances(std::move(instances_per_layer)));
267 }
268
269 GeometrySet dst_instances = geometry::join_geometries(component_instances, attribute_filter);
270
272 geometry_set.replace_instances(
274 });
275
276 /* Unused references may have been added above. Remove those now so that other nodes don't
277 * process them needlessly.
278 * This should eventually be moved into the loop above, but currently this is quite tricky
279 * because it might remove references that the loop still wants to iterate over. */
280 if (bke::Instances *instances = geometry_set.get_instances_for_write()) {
281 instances->remove_unused_references();
282 }
283
284 params.set_output("Instances"_ustr, std::move(geometry_set));
285}
286
287static void node_register()
288{
289 static bke::bNodeType ntype;
290
291 geo_node_type_base(&ntype, "GeometryNodeInstanceOnPoints"_ustr, GEO_NODE_INSTANCE_ON_POINTS);
292 ntype.ui_name = "Instance on Points";
293 ntype.ui_description =
294 "Generate a reference to geometry at each of the input points, without duplicating its "
295 "underlying data";
296 ntype.enum_name_legacy = "INSTANCE_ON_POINTS";
298 ntype.declare = node_declare;
301}
303
304} // namespace blender::nodes::node_geo_instance_on_points_cc
Low-level operations for curves.
Low-level operations for grease pencil.
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
#define GEO_NODE_INSTANCE_ON_POINTS
#define TIP_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define ELEM(...)
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:430
GPointer()=default
CommonVArrayInfo common_info() const
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
int64_t size() const
void append(const T &value)
void resize(const int64_t new_size)
void foreach_attribute(const FunctionRef< void(const AttributeIter &)> fn) const
GAttributeReader lookup(const StringRef name) const
int domain_size(const AttrDomain domain) const
bool is_builtin(const StringRef name) const
GAttributeReader get() const
AttributeAccessor attributes() const
virtual std::optional< AttributeAccessor > attributes() const
bool add(const StringRef name, const AttrDomain domain, const AttrType data_type, const AttributeInit &initializer)
GSpanAttributeWriter lookup_or_add_for_write_only_span(StringRef name, AttrDomain domain, AttrType data_type)
const bke::CurvesGeometry & strokes() const
void foreach_index(Fn &&fn, Mode mode=exec_mode::serial) const
void error_message_add(const NodeWarningType type, StringRef message) const
NodeAttributeFilter get_attribute_filter(const UString output_identifier) const
T extract_input(const UString identifier)
T get_input(const UString identifier) const
void set_output(const UString identifier, T &&value)
#define layer
void gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
void copy_attributes(const AttributeAccessor src_attributes, AttrDomain src_domain, AttrDomain dst_domain, const AttributeFilter &attribute_filter, MutableAttributeAccessor dst_attributes)
constexpr ParallelGrainSize grain_size(int grain_size)
bke::GeometrySet join_geometries(Span< bke::GeometrySet > geometries, const bke::AttributeFilter &attribute_filter, const std::optional< Span< bke::GeometryComponent::Type > > &component_types_to_join=std::nullopt, bool allow_merging_instance_references=true)
void foreach_real_geometry(bke::GeometrySet &geometry, FunctionRef< void(bke::GeometrySet &geometry_set)> fn)
MatT from_loc_rot_scale(const typename MatT::loc_type &location, const RotationT &rotation, const VecBase< typename MatT::base_type, ScaleDim > &scale)
static std::unique_ptr< bke::Instances > add_instances_from_component(const AttributeAccessor &src_attributes, const GeometrySet &instance, const fn::FieldContext &field_context, const GeoNodeExecParams &params, const bke::AttributeFilter &attribute_filter)
static void node_declare(NodeDeclarationBuilder &b)
MINLINE int mod_i(int i, int n)
__int64 int64_t
Definition BKE_text.h:90
MatBase< float, 4, 4 > float4x4
void mul_m4_m4_post(float R[4][4], const float B[4][4])
VecBase< float, 3 > float3
void geo_node_type_base(bke::bNodeType *ntype, UString idname, const std::optional< int16_t > legacy_type)
const c_style_mat & ptr() const
bool allow_skip(const StringRef name) const
const ImplicitSharingInfo * sharing_info
void keep_only(Span< GeometryComponent::Type > component_types)
GeometryComponent & get_component_for_write(GeometryComponent::Type component_type)
void replace_instances(Instances *instances, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
Instances * get_instances_for_write()
const GreasePencil * get_grease_pencil() const
bool has(const GeometryComponent::Type component_type) const
const GeometryComponent * get_component(GeometryComponent::Type component_type) const
const Instances * get_instances() const
Defines a node type.
Definition BKE_node.hh:265
std::string ui_description
Definition BKE_node.hh:271
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:385
const char * enum_name_legacy
Definition BKE_node.hh:274
NodeDeclareFunction declare
Definition BKE_node.hh:393
static GeometrySet from_instances(std::unique_ptr< Instances > instances)