Blender V5.3
node_geo_sample_nearest.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 "DNA_mesh_types.h"
7
8#include "BLI_math_vector.hh"
9
10#include "BKE_bvh.hh"
11#include "BKE_pointcloud.hh"
12
13#include "NOD_rna_define.hh"
14
16#include "UI_resources.hh"
17
18#include "RNA_enum_types.hh"
19
20#include "node_geometry_util.hh"
21
23
25{
26 b.add_input<decl::Geometry>("Geometry"_ustr)
28 .description("Mesh or point cloud to find the nearest point on");
29 auto &sample_position = b.add_input<decl::Vector>("Sample Position"_ustr)
30 .default_input_type(NODE_DEFAULT_INPUT_POSITION_FIELD)
31 .structure_type(StructureType::Dynamic);
32 const std::array<int, 1> dynamic_inputs = {sample_position.index()};
33 b.add_output<decl::Int>("Index"_ustr)
34 .inferred_structure_type(dynamic_inputs)
35 .propagate_references(dynamic_inputs);
36}
37
38static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
39{
40 layout.prop(ptr, "domain", UI_ITEM_NONE, "", ICON_NONE);
41}
42
43static void node_init(bNodeTree * /*tree*/, bNode *node)
44{
45 node->custom1 = CD_PROP_FLOAT;
46 node->custom2 = int(AttrDomain::Point);
47}
48
49static void get_closest_pointcloud_points(const PointCloud &pointcloud,
50 const VArray<float3> &positions,
51 const IndexMask &mask,
52 MutableSpan<int> r_indices,
53 MutableSpan<float> r_distances_sq)
54{
55 BLI_assert(positions.size() >= r_indices.size());
56 if (pointcloud.totpoint == 0) {
57 r_indices.fill(0);
58 r_distances_sq.fill(0.0f);
59 return;
60 }
61 const bke::bvh::Tree &tree = pointcloud.bvh_tree();
62
63 mask.foreach_index([&](const int i) {
64 const float3 position = positions[i];
66 r_indices[i] = nearest.index;
67 if (!r_distances_sq.is_empty()) {
68 r_distances_sq[i] = math::distance_squared(position, nearest.position);
69 }
70 });
71}
72
74 const VArray<float3> &positions,
75 const IndexMask &mask,
76 const MutableSpan<int> r_point_indices,
77 const MutableSpan<float> r_distances_sq,
78 const MutableSpan<float3> r_positions)
79{
80 BLI_assert(mesh.verts_num > 0);
81 const bke::bvh::Tree &tree = mesh.bvh_verts();
82 mask.foreach_index([&](const int i) {
83 const float3 position = positions[i];
85 if (!r_point_indices.is_empty()) {
86 r_point_indices[i] = nearest.index;
87 }
88 if (!r_distances_sq.is_empty()) {
89 r_distances_sq[i] = math::distance_squared(position, nearest.position);
90 }
91 if (!r_positions.is_empty()) {
92 r_positions[i] = nearest.position;
93 }
94 });
95}
96
97static void get_closest_mesh_edges(const Mesh &mesh,
98 const VArray<float3> &positions,
99 const IndexMask &mask,
100 const MutableSpan<int> r_edge_indices,
101 const MutableSpan<float> r_distances_sq,
102 const MutableSpan<float3> r_positions)
103{
104 BLI_assert(mesh.edges_num > 0);
105 const bke::bvh::Tree &tree = mesh.bvh_edges();
106 mask.foreach_index([&](const int i) {
107 const float3 position = positions[i];
109 if (!r_edge_indices.is_empty()) {
110 r_edge_indices[i] = nearest.index;
111 }
112 if (!r_distances_sq.is_empty()) {
113 r_distances_sq[i] = math::distance_squared(position, nearest.position);
114 }
115 if (!r_positions.is_empty()) {
116 r_positions[i] = nearest.position;
117 }
118 });
119}
120
121static void get_closest_mesh_tris(const Mesh &mesh,
122 const VArray<float3> &positions,
123 const IndexMask &mask,
124 const MutableSpan<int> r_tri_indices,
125 const MutableSpan<float> r_distances_sq,
126 const MutableSpan<float3> r_positions)
127{
128 BLI_assert(mesh.faces_num > 0);
129 const bke::bvh::Tree &tree = mesh.bvh_tris();
130 mask.foreach_index([&](const int i) {
131 const float3 position = positions[i];
133 if (!r_tri_indices.is_empty()) {
134 r_tri_indices[i] = nearest.index;
135 }
136 if (!r_distances_sq.is_empty()) {
137 r_distances_sq[i] = math::distance_squared(position, nearest.position);
138 }
139 if (!r_positions.is_empty()) {
140 r_positions[i] = nearest.position;
141 }
142 });
143}
144
146 const VArray<float3> &positions,
147 const IndexMask &mask,
148 const MutableSpan<int> r_face_indices,
149 const MutableSpan<float> r_distances_sq,
150 const MutableSpan<float3> r_positions)
151{
152 BLI_assert(mesh.faces_num > 0);
153
154 const bool mesh_is_triangles = mesh.corners_num == mesh.faces_num * 3;
155 if (mesh_is_triangles) {
156 get_closest_mesh_tris(mesh, positions, mask, r_face_indices, r_distances_sq, r_positions);
157 }
158 else {
159 Array<int> tri_indices(positions.size());
160 get_closest_mesh_tris(mesh, positions, mask, tri_indices, r_distances_sq, r_positions);
161 const Span<int> tri_faces = mesh.corner_tri_faces();
162 mask.foreach_index([&](const int i) { r_face_indices[i] = tri_faces[tri_indices[i]]; });
163 }
164}
165
166/* The closest corner is defined to be the closest corner on the closest face. */
168 const VArray<float3> &positions,
169 const IndexMask &mask,
170 const MutableSpan<int> r_corner_indices,
171 const MutableSpan<float> r_distances_sq,
172 const MutableSpan<float3> r_positions)
173{
174 const Span<float3> vert_positions = mesh.vert_positions();
175 const OffsetIndices faces = mesh.faces();
176 const Span<int> corner_verts = mesh.corner_verts();
177
178 BLI_assert(mesh.corners_num > 0);
179 Array<int> face_indices(positions.size());
180 get_closest_mesh_faces(mesh, positions, mask, face_indices, {}, {});
181
182 mask.foreach_index([&](const int i) {
183 const float3 position = positions[i];
184 const int face_index = face_indices[i];
185
186 /* Find the closest vertex in the face. */
187 float min_distance_sq = FLT_MAX;
188 int closest_vert = 0;
189 int closest_corner = 0;
190 for (const int corner : faces[face_index]) {
191 const int vert = corner_verts[corner];
192 const float distance_sq = math::distance_squared(position, vert_positions[vert]);
193 if (distance_sq < min_distance_sq) {
194 min_distance_sq = distance_sq;
195 closest_corner = corner;
196 closest_vert = vert;
197 }
198 }
199 if (!r_corner_indices.is_empty()) {
200 r_corner_indices[i] = closest_corner;
201 }
202 if (!r_positions.is_empty()) {
203 r_positions[i] = vert_positions[closest_vert];
204 }
205 if (!r_distances_sq.is_empty()) {
206 r_distances_sq[i] = min_distance_sq;
207 }
208 });
209}
210
212 const GeometryComponent::Type type,
213 const AttrDomain domain)
214{
215 if (!geometry.has(type)) {
216 return false;
217 }
218 const GeometryComponent &component = *geometry.get_component(type);
219 return component.attribute_domain_size(domain) != 0;
220}
221
223 const AttrDomain domain)
224{
225 /* Choose the other component based on a consistent order, rather than some more complicated
226 * heuristic. This is the same order visible in the spreadsheet and used in the ray-cast node. */
227 static const Array<GeometryComponent::Type> supported_types = {
229 for (const GeometryComponent::Type src_type : supported_types) {
230 if (component_is_available(geometry, src_type, domain)) {
231 return geometry.get_component(src_type);
232 }
233 }
234
235 return nullptr;
236}
237
238class SampleNearestFunction : public mf::MultiFunction {
239 GeometrySet source_;
240 AttrDomain domain_;
241
242 const GeometryComponent *src_component_;
243
244 mf::Signature signature_;
245
246 public:
248 : source_(std::move(geometry)), domain_(domain)
249 {
250 source_.ensure_owns_direct_data();
251 this->src_component_ = find_source_component(source_, domain_);
252
253 mf::SignatureBuilder builder{"Sample Nearest", signature_};
254 builder.single_input<float3>("Position");
255 builder.single_output<int>("Index");
256 this->set_signature(&signature_);
257 }
258
259 void call(const IndexMask &mask, mf::Params params, mf::Context /*context*/) const override
260 {
261 const VArray<float3> &positions = params.readonly_single_input<float3>(0, "Position");
262 MutableSpan<int> indices = params.uninitialized_single_output<int>(1, "Index");
263 if (!src_component_) {
264 index_mask::masked_fill(indices, 0, mask);
265 return;
266 }
267
268 switch (src_component_->type()) {
270 const auto &component = *static_cast<const MeshComponent *>(src_component_);
271 const Mesh &mesh = *component.get();
272 switch (domain_) {
273 case AttrDomain::Point:
274 get_closest_mesh_points(mesh, positions, mask, indices, {}, {});
275 break;
276 case AttrDomain::Edge:
277 get_closest_mesh_edges(mesh, positions, mask, indices, {}, {});
278 break;
279 case AttrDomain::Face:
280 get_closest_mesh_faces(mesh, positions, mask, indices, {}, {});
281 break;
282 case AttrDomain::Corner:
283 get_closest_mesh_corners(mesh, positions, mask, indices, {}, {});
284 break;
285 default:
286 break;
287 }
288 break;
289 }
291 const auto &component = *static_cast<const bke::PointCloudComponent *>(src_component_);
292 const PointCloud &pointcloud = *component.get();
293 get_closest_pointcloud_points(pointcloud, positions, mask, indices, {});
294 break;
295 }
296 default:
297 break;
298 }
299 }
300
301 void hash_unique(UniqueHashBytes &hash) const override
302 {
303 static constexpr int8_t id = 0;
304 hash.add(&id);
305 hash.add(domain_);
306 hash.add(src_component_);
307 }
308};
309
311{
312 GeometrySet geometry = params.extract_input<GeometrySet>("Geometry"_ustr);
313 const AttrDomain domain = AttrDomain(params.node().custom2);
314 if (geometry.has_curves() && !geometry.has_mesh() && !geometry.has_pointcloud()) {
316 TIP_("The source geometry must contain a mesh or a point cloud"));
318 return;
319 }
320
321 auto sample_position = params.extract_input<bke::SocketValueVariant>("Sample Position"_ustr);
322
323 std::string error_message;
326 std::make_shared<SampleNearestFunction>(std::move(geometry), domain),
327 {&sample_position},
328 {&index},
329 params.user_data(),
330 error_message))
331 {
333 params.error_message_add(NodeWarningType::Error, std::move(error_message));
334 return;
335 }
336
337 params.set_output("Index"_ustr, std::move(index));
338}
339
340static void node_rna(StructRNA *srna)
341{
343 "domain",
344 "Domain",
345 "",
348 int(AttrDomain::Point));
349}
350
351static void node_register()
352{
353 static bke::bNodeType ntype;
354
355 geo_node_type_base(&ntype, "GeometryNodeSampleNearest"_ustr, GEO_NODE_SAMPLE_NEAREST);
356 ntype.ui_name = "Sample Nearest";
357 ntype.ui_description =
358 "Find the element of a geometry closest to a position. Similar to the \"Index of Nearest\" "
359 "node";
360 ntype.enum_name_legacy = "SAMPLE_NEAREST";
362 ntype.initfunc = node_init;
363 ntype.declare = node_declare;
367
368 node_rna(ntype.rna_ext.srna);
369}
371
372} // namespace blender::nodes::node_geo_sample_nearest_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
#define GEO_NODE_SAMPLE_NEAREST
General operations for point clouds.
#define TIP_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
#define UI_ITEM_NONE
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr bool is_empty() const
Definition BLI_span.hh:515
constexpr void fill(const T &value) const
Definition BLI_span.hh:523
int attribute_domain_size(AttrDomain domain) const
std::optional< ClosestPointResult > closest_point(const float3 &point, float radius=std::numeric_limits< float >::max()) const
Definition bvh.cc:709
void set_signature(const Signature *signature)
void error_message_add(const NodeWarningType type, StringRef message) const
T extract_input(const UString identifier)
GeoNodesUserData * user_data() const
void set_output(const UString identifier, T &&value)
void call(const IndexMask &mask, mf::Params params, mf::Context) const override
#define FLT_MAX
#define position
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
void masked_fill(MutableSpan< T > data, const T &value, const IndexMask &mask)
T distance_squared(const VecBase< T, Size > &a, const VecBase< T, Size > &b)
static void get_closest_mesh_faces(const Mesh &mesh, const VArray< float3 > &positions, const IndexMask &mask, const MutableSpan< int > r_face_indices, const MutableSpan< float > r_distances_sq, const MutableSpan< float3 > r_positions)
static void get_closest_mesh_edges(const Mesh &mesh, const VArray< float3 > &positions, const IndexMask &mask, const MutableSpan< int > r_edge_indices, const MutableSpan< float > r_distances_sq, const MutableSpan< float3 > r_positions)
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
static void get_closest_mesh_points(const Mesh &mesh, const VArray< float3 > &positions, const IndexMask &mask, const MutableSpan< int > r_point_indices, const MutableSpan< float > r_distances_sq, const MutableSpan< float3 > r_positions)
static void get_closest_mesh_corners(const Mesh &mesh, const VArray< float3 > &positions, const IndexMask &mask, const MutableSpan< int > r_corner_indices, const MutableSpan< float > r_distances_sq, const MutableSpan< float3 > r_positions)
static void node_init(bNodeTree *, bNode *node)
static void node_declare(NodeDeclarationBuilder &b)
static void node_geo_exec(GeoNodeExecParams params)
static bool component_is_available(const GeometrySet &geometry, const GeometryComponent::Type type, const AttrDomain domain)
static const GeometryComponent * find_source_component(const GeometrySet &geometry, const AttrDomain domain)
static void get_closest_mesh_tris(const Mesh &mesh, const VArray< float3 > &positions, const IndexMask &mask, const MutableSpan< int > r_tri_indices, const MutableSpan< float > r_distances_sq, const MutableSpan< float3 > r_positions)
static void get_closest_pointcloud_points(const PointCloud &pointcloud, const VArray< float3 > &positions, const IndexMask &mask, MutableSpan< int > r_indices, MutableSpan< float > r_distances_sq)
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)
bool execute_multi_function_on_value_variant(const MultiFunction &fn, const std::shared_ptr< MultiFunction > &owned_fn, const Span< SocketValueVariant * > input_values, const Span< SocketValueVariant * > output_values, GeoNodesUserData *user_data, std::string &r_error_message)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
const EnumPropertyItem rna_enum_attribute_domain_only_mesh_items[]
VecBase< float, 3 > float3
void geo_node_type_base(bke::bNodeType *ntype, UString idname, const std::optional< int16_t > legacy_type)
signed char int8_t
Definition BKE_text.h:76
#define hash
Definition noise_c.cc:156
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
NodeDeclareFunction declare
Definition BKE_node.hh:393
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)