Blender V4.5
node_geo_proximity.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_task.hh"
6
7#include "BKE_bvhutils.hh"
8#include "BKE_geometry_set.hh"
9#include "BKE_mesh.hh"
10
12
13#include "NOD_rna_define.hh"
14
15#include "UI_interface.hh"
16#include "UI_resources.hh"
17
18#include "node_geometry_util.hh"
19
21
23
25{
26 b.add_input<decl::Geometry>("Geometry", "Target")
28 .supported_type({GeometryComponent::Type::Mesh, GeometryComponent::Type::PointCloud});
29 b.add_input<decl::Int>("Group ID")
30 .hide_value()
31 .field_on_all()
32 .description(
33 "Splits the elements of the input geometry into groups which can be sampled "
34 "individually");
35 b.add_input<decl::Vector>("Sample Position", "Source Position")
36 .implicit_field(NODE_DEFAULT_INPUT_POSITION_FIELD);
37 b.add_input<decl::Int>("Sample Group ID").hide_value().supports_field();
38 b.add_output<decl::Vector>("Position").dependent_field({2, 3}).reference_pass_all();
39 b.add_output<decl::Float>("Distance").dependent_field({2, 3}).reference_pass_all();
40 b.add_output<decl::Bool>("Is Valid")
41 .dependent_field({2, 3})
43 "Whether the sampling was successful. It can fail when the sampled group is empty");
44}
45
46static void node_layout(uiLayout *layout, bContext * /*C*/, PointerRNA *ptr)
47{
48 layout->prop(ptr, "target_element", UI_ITEM_NONE, "", ICON_NONE);
49}
50
51static void geo_proximity_init(bNodeTree * /*tree*/, bNode *node)
52{
55 node->storage = node_storage;
56}
57
58class ProximityFunction : public mf::MultiFunction {
59 private:
60 struct BVHTrees {
61 bke::BVHTreeFromMesh mesh_bvh = {};
62 bke::BVHTreeFromPointCloud pointcloud_bvh = {};
63 };
64
65 GeometrySet target_;
67 Vector<BVHTrees> bvh_trees_;
68 VectorSet<int> group_indices_;
69
70 public:
73 const Field<int> &group_id_field)
74 : target_(std::move(target)), type_(type)
75 {
76 static const mf::Signature signature = []() {
77 mf::Signature signature;
78 mf::SignatureBuilder builder{"Geometry Proximity", signature};
79 builder.single_input<float3>("Source Position");
80 builder.single_input<int>("Sample ID");
81 builder.single_output<float3>("Position", mf::ParamFlag::SupportsUnusedOutput);
82 builder.single_output<float>("Distance", mf::ParamFlag::SupportsUnusedOutput);
83 builder.single_output<bool>("Is Valid", mf::ParamFlag::SupportsUnusedOutput);
84 return signature;
85 }();
86 this->set_signature(&signature);
87
88 if (target_.has_pointcloud() && type_ == GEO_NODE_PROX_TARGET_POINTS) {
89 const PointCloud &pointcloud = *target_.get_pointcloud();
90 this->init_for_pointcloud(pointcloud, group_id_field);
91 }
92 if (target_.has_mesh()) {
93 const Mesh &mesh = *target_.get_mesh();
94 this->init_for_mesh(mesh, group_id_field);
95 }
96 }
97
98 ~ProximityFunction() override = default;
99
100 void init_for_pointcloud(const PointCloud &pointcloud, const Field<int> &group_id_field)
101 {
102 /* Compute group ids. */
103 bke::PointCloudFieldContext field_context{pointcloud};
104 FieldEvaluator field_evaluator{field_context, pointcloud.totpoint};
105 field_evaluator.add(group_id_field);
106 field_evaluator.evaluate();
107 const VArray<int> group_ids = field_evaluator.get_evaluated<int>(0);
108
109 IndexMaskMemory memory;
110 Vector<IndexMask> group_masks = IndexMask::from_group_ids(group_ids, memory, group_indices_);
111 const int groups_num = group_masks.size();
112
113 /* Construct BVH tree for each group. */
114 bvh_trees_.resize(groups_num);
116 IndexRange(groups_num),
117 512,
118 [&](const IndexRange range) {
119 for (const int group_i : range) {
120 const IndexMask &group_mask = group_masks[group_i];
121 if (group_mask.is_empty()) {
122 continue;
123 }
124 bvh_trees_[group_i].pointcloud_bvh = bke::bvhtree_from_pointcloud_get(pointcloud,
125 group_mask);
126 }
127 },
129 [&](const int group_i) { return group_masks[group_i].size(); }, pointcloud.totpoint));
130 }
131
132 void init_for_mesh(const Mesh &mesh, const Field<int> &group_id_field)
133 {
134 /* Compute group ids. */
135 const bke::AttrDomain domain = this->get_domain_on_mesh();
136 const int domain_size = mesh.attributes().domain_size(domain);
137 bke::MeshFieldContext field_context{mesh, domain};
138 FieldEvaluator field_evaluator{field_context, domain_size};
139 field_evaluator.add(group_id_field);
140 field_evaluator.evaluate();
141 const VArray<int> group_ids = field_evaluator.get_evaluated<int>(0);
142
143 IndexMaskMemory memory;
144 Vector<IndexMask> group_masks = IndexMask::from_group_ids(group_ids, memory, group_indices_);
145 const int groups_num = group_masks.size();
146
147 /* Construct BVH tree for each group. */
148 bvh_trees_.resize(groups_num);
150 IndexRange(groups_num),
151 512,
152 [&](const IndexRange range) {
153 for (const int group_i : range) {
154 const IndexMask &group_mask = group_masks[group_i];
155 if (group_mask.is_empty()) {
156 continue;
157 }
158 switch (type_) {
160 bvh_trees_[group_i].mesh_bvh = bke::bvhtree_from_mesh_verts_init(mesh, group_mask);
161 break;
163 bvh_trees_[group_i].mesh_bvh = bke::bvhtree_from_mesh_edges_init(mesh, group_mask);
164 break;
166 bvh_trees_[group_i].mesh_bvh = bke::bvhtree_from_mesh_tris_init(mesh, group_mask);
167 break;
168 }
169 }
170 },
172 [&](const int group_i) { return group_masks[group_i].size(); }, domain_size));
173 }
174
188
189 void call(const IndexMask &mask, mf::Params params, mf::Context /*context*/) const override
190 {
191 const VArray<float3> &sample_positions = params.readonly_single_input<float3>(
192 0, "Source Position");
193 const VArray<int> &sample_ids = params.readonly_single_input<int>(1, "Sample ID");
194 MutableSpan<float3> positions = params.uninitialized_single_output_if_required<float3>(
195 2, "Position");
196 MutableSpan<float> distances = params.uninitialized_single_output_if_required<float>(
197 3, "Distance");
198 MutableSpan<bool> is_valid_span = params.uninitialized_single_output_if_required<bool>(
199 4, "Is Valid");
200
201 mask.foreach_index([&](const int i) {
202 const float3 sample_position = sample_positions[i];
203 const int sample_id = sample_ids[i];
204 const int group_index = group_indices_.index_of_try(sample_id);
205 if (group_index == -1) {
206 if (!positions.is_empty()) {
207 positions[i] = float3(0, 0, 0);
208 }
209 if (!is_valid_span.is_empty()) {
210 is_valid_span[i] = false;
211 }
212 if (!distances.is_empty()) {
213 distances[i] = 0.0f;
214 }
215 return;
216 }
217 const BVHTrees &trees = bvh_trees_[group_index];
218 BVHTreeNearest nearest;
219 /* Take mesh and pointcloud bvh tree into account. The final result is the closer of the two.
220 * The first bvhtree query will set `nearest.dist_sq` which is then passed into the second
221 * query as a maximum distance. */
222 nearest.dist_sq = FLT_MAX;
223 if (trees.mesh_bvh.tree != nullptr) {
224 BLI_bvhtree_find_nearest(trees.mesh_bvh.tree,
225 sample_position,
226 &nearest,
227 trees.mesh_bvh.nearest_callback,
228 const_cast<bke::BVHTreeFromMesh *>(&trees.mesh_bvh));
229 }
230 if (trees.pointcloud_bvh.tree != nullptr) {
231 BLI_bvhtree_find_nearest(trees.pointcloud_bvh.tree,
232 sample_position,
233 &nearest,
234 trees.pointcloud_bvh.nearest_callback,
235 const_cast<bke::BVHTreeFromPointCloud *>(&trees.pointcloud_bvh));
236 }
237
238 if (!positions.is_empty()) {
239 positions[i] = nearest.co;
240 }
241 if (!is_valid_span.is_empty()) {
242 is_valid_span[i] = true;
243 }
244 if (!distances.is_empty()) {
245 distances[i] = std::sqrt(nearest.dist_sq);
246 }
247 });
248 }
249};
250
252{
253 GeometrySet target = params.extract_input<GeometrySet>("Target");
255
256 if (!target.has_mesh() && !target.has_pointcloud()) {
257 params.set_default_remaining_outputs();
258 return;
259 }
260
261 const NodeGeometryProximity &storage = node_storage(params.node());
262 Field<int> group_id_field = params.extract_input<Field<int>>("Group ID");
263 Field<float3> position_field = params.extract_input<Field<float3>>("Source Position");
264 Field<int> sample_id_field = params.extract_input<Field<int>>("Sample Group ID");
265
266 auto proximity_fn = std::make_unique<ProximityFunction>(
267 std::move(target), GeometryNodeProximityTargetType(storage.target_element), group_id_field);
268 auto proximity_op = FieldOperation::Create(
269 std::move(proximity_fn), {std::move(position_field), std::move(sample_id_field)});
270
271 params.set_output("Position", Field<float3>(proximity_op, 0));
272 params.set_output("Distance", Field<float>(proximity_op, 1));
273 params.set_output("Is Valid", Field<bool>(proximity_op, 2));
274}
275
276static void node_rna(StructRNA *srna)
277{
278 static const EnumPropertyItem target_element_items[] = {
280 "POINTS",
281 ICON_NONE,
282 "Points",
283 "Calculate the proximity to the target's points (faster than the other modes)"},
285 "EDGES",
286 ICON_NONE,
287 "Edges",
288 "Calculate the proximity to the target's edges"},
290 "FACES",
291 ICON_NONE,
292 "Faces",
293 "Calculate the proximity to the target's faces"},
294 {0, nullptr, 0, nullptr, nullptr},
295 };
296
298 "target_element",
299 "Target Geometry",
300 "Element of the target geometry to calculate the distance from",
301 target_element_items,
302 NOD_storage_enum_accessors(target_element),
304}
305
306static void node_register()
307{
308 static blender::bke::bNodeType ntype;
309
310 geo_node_type_base(&ntype, "GeometryNodeProximity", GEO_NODE_PROXIMITY);
311 ntype.ui_name = "Geometry Proximity";
312 ntype.ui_description = "Compute the closest location on the target geometry";
313 ntype.enum_name_legacy = "PROXIMITY";
317 ntype, "NodeGeometryProximity", node_free_standard_storage, node_copy_standard_storage);
318 ntype.declare = node_declare;
322
323 node_rna(ntype.rna_ext.srna);
324}
326
327} // namespace blender::nodes::node_geo_proximity_cc
#define NODE_STORAGE_FUNCS(StorageT)
Definition BKE_node.hh:1215
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:447
#define GEO_NODE_PROXIMITY
#define BLI_assert_unreachable()
Definition BLI_assert.h:93
int BLI_bvhtree_find_nearest(const BVHTree *tree, const float co[3], BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
@ NODE_DEFAULT_INPUT_POSITION_FIELD
GeometryNodeProximityTargetType
@ GEO_NODE_PROX_TARGET_EDGES
@ GEO_NODE_PROX_TARGET_POINTS
@ GEO_NODE_PROX_TARGET_FACES
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_storage_enum_accessors(member)
#define UI_ITEM_NONE
AttributeSet attributes
static Vector< IndexMask, 4 > from_group_ids(const VArray< int > &group_ids, IndexMaskMemory &memory, VectorSet< int > &r_index_by_group_id)
int64_t size() const
int add(GField field, GVArray *varray_ptr)
Definition field.cc:751
const GVArray & get_evaluated(const int field_index) const
Definition FN_field.hh:448
void set_signature(const Signature *signature)
static std::shared_ptr< FieldOperation > Create(std::shared_ptr< const mf::MultiFunction > function, Vector< GField > inputs={})
Definition FN_field.hh:242
void init_for_pointcloud(const PointCloud &pointcloud, const Field< int > &group_id_field)
ProximityFunction(GeometrySet target, GeometryNodeProximityTargetType type, const Field< int > &group_id_field)
void call(const IndexMask &mask, mf::Params params, mf::Context) const override
void init_for_mesh(const Mesh &mesh, const Field< int > &group_id_field)
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
void * MEM_callocN(size_t len, const char *str)
Definition mallocn.cc:118
ccl_device_inline float2 mask(const MaskType mask, const float2 a)
void node_register_type(bNodeType &ntype)
Definition node.cc:2748
BVHTreeFromMesh bvhtree_from_mesh_edges_init(const Mesh &mesh, const IndexMask &edges_mask)
Definition bvhutils.cc:793
BVHTreeFromMesh bvhtree_from_mesh_tris_init(const Mesh &mesh, const IndexMask &faces_mask)
Definition bvhutils.cc:784
BVHTreeFromMesh bvhtree_from_mesh_verts_init(const Mesh &mesh, const IndexMask &verts_mask)
Definition bvhutils.cc:801
BVHTreeFromPointCloud bvhtree_from_pointcloud_get(const PointCloud &pointcloud, const IndexMask &points_mask)
Definition bvhutils.cc:842
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:5603
static void node_geo_exec(GeoNodeExecParams params)
static void node_declare(NodeDeclarationBuilder &b)
static void node_layout(uiLayout *layout, bContext *, PointerRNA *ptr)
static void node_rna(StructRNA *srna)
static void geo_proximity_init(bNodeTree *, bNode *node)
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)
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:93
auto individual_task_sizes(Fn &&fn, const std::optional< int64_t > full_size=std::nullopt)
VecBase< float, 3 > float3
void geo_node_type_base(blender::bke::bNodeType *ntype, std::string idname, const std::optional< int16_t > legacy_type)
void node_free_standard_storage(bNode *node)
Definition node_util.cc:42
void node_copy_standard_storage(bNodeTree *, bNode *dest_node, const bNode *src_node)
Definition node_util.cc:54
#define FLT_MAX
Definition stdcycles.h:14
StructRNA * srna
Definition RNA_types.hh:909
void * storage
BVHTree_NearestPointCallback nearest_callback
BVHTree_NearestPointCallback nearest_callback
Defines a node type.
Definition BKE_node.hh:226
std::string ui_description
Definition BKE_node.hh:232
void(* initfunc)(bNodeTree *ntree, bNode *node)
Definition BKE_node.hh:277
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:347
const char * enum_name_legacy
Definition BKE_node.hh:235
void(* draw_buttons)(uiLayout *, bContext *C, PointerRNA *ptr)
Definition BKE_node.hh:247
NodeDeclareFunction declare
Definition BKE_node.hh:355
void prop(PointerRNA *ptr, PropertyRNA *prop, int index, int value, eUI_Item_Flag flag, std::optional< blender::StringRef > name_opt, int icon, std::optional< blender::StringRef > placeholder=std::nullopt)
i
Definition text_draw.cc:230
PointerRNA * ptr
Definition wm_files.cc:4226