Blender V5.3
node_geo_sample_uv_surface.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"
6
7#include "BKE_mesh_sample.hh"
9
10#include "NOD_rna_define.hh"
12
14#include "UI_resources.hh"
15
17
18#include "RNA_enum_types.hh"
19
20#include "node_geometry_util.hh"
21
23
25
27{
28 const bNode *node = b.node_or_null();
29
30 b.add_input<decl::Geometry>("Mesh"_ustr)
31 .supported_type(GeometryComponent::Type::Mesh)
32 .description("Mesh whose UV map is used");
33 if (node != nullptr) {
34 const eCustomDataType data_type = eCustomDataType(node->custom1);
35 b.add_input(data_type, "Value"_ustr).hide_value().evaluated_geometry_field();
36 }
37 b.add_input<decl::Vector>("UV Map"_ustr, "Source UV Map"_ustr)
38 .hide_value()
39 .evaluated_geometry_field()
40 .description("The mesh UV map to sample. Should not have overlapping faces");
41 auto &sample_uv = b.add_input<decl::Vector>("Sample UV"_ustr)
42 .description("The coordinates to sample within the UV map")
43 .structure_type(StructureType::Dynamic);
44
45 std::array<int, 1> dynamic_inputs = {sample_uv.index()};
46 if (node != nullptr) {
47 const eCustomDataType data_type = eCustomDataType(node->custom1);
48 b.add_output(data_type, "Value"_ustr)
49 .inferred_structure_type(dynamic_inputs)
50 .propagate_references(dynamic_inputs);
51 }
52 b.add_output<decl::Bool>("Is Valid"_ustr)
53 .inferred_structure_type(dynamic_inputs)
54 .propagate_references(dynamic_inputs)
55 .description("Whether the node could find a single face to sample at the UV coordinate");
56}
57
58static void node_layout(ui::Layout &layout, bContext * /*C*/, PointerRNA *ptr)
59{
60 layout.prop(ptr, "data_type", UI_ITEM_NONE, "", ICON_NONE);
61}
62
63static void node_init(bNodeTree * /*tree*/, bNode *node)
64{
65 node->custom1 = CD_PROP_FLOAT;
66}
67
69{
70 const NodeDeclaration &declaration = *params.node_type().static_declaration;
71 search_link_ops_for_declarations(params, declaration.inputs);
72 search_link_ops_for_declarations(params, declaration.outputs);
73
74 const std::optional<eCustomDataType> type = bke::socket_type_to_custom_data_type(
75 params.other_socket().type);
76 if (type && *type != CD_PROP_STRING) {
77 /* The input and output sockets have the same name. */
78 params.add_item(IFACE_("Value"), [type](LinkSearchOpParams &params) {
79 bNode &node = params.add_node("GeometryNodeSampleUVSurface"_ustr);
80 node.custom1 = *type;
81 params.update_and_connect_available_socket(node, "Value"_ustr);
82 });
83 }
84}
85
86class ReverseUVSampleFunction : public mf::MultiFunction {
87 GeometrySet source_;
88 Field<float2> src_uv_map_field_;
89
90 mutable CacheMutex mutex_;
91 mutable std::optional<bke::MeshFieldContext> source_context_;
92 mutable std::unique_ptr<FieldEvaluator> source_evaluator_;
93 mutable VArraySpan<float2> source_uv_map_;
94 mutable std::optional<ReverseUVSampler> reverse_uv_sampler_;
95
96 public:
98 : source_(std::move(geometry)), src_uv_map_field_(std::move(src_uv_map_field))
99 {
100 source_.ensure_owns_direct_data();
101
102 static const mf::Signature signature = []() {
103 mf::Signature signature;
104 mf::SignatureBuilder builder{"Sample UV Surface", signature};
105 builder.single_input<float2>("Sample UV");
106 builder.single_output<bool>("Is Valid", mf::ParamFlag::SupportsUnusedOutput);
107 builder.single_output<int>("Triangle Index", mf::ParamFlag::SupportsUnusedOutput);
108 builder.single_output<float3>("Barycentric Weights", mf::ParamFlag::SupportsUnusedOutput);
109 return signature;
110 }();
111 this->set_signature(&signature);
112 }
113
114 void call(const IndexMask &mask, mf::Params params, mf::Context /*context*/) const override
115 {
116 const VArraySpan<float2> sample_uvs = params.readonly_single_input<float2>(0, "Sample UV");
117 MutableSpan<bool> is_valid = params.uninitialized_single_output_if_required<bool>(1,
118 "Is Valid");
119 MutableSpan<int> tri_index = params.uninitialized_single_output_if_required<int>(
120 2, "Triangle Index");
121 MutableSpan<float3> bary_weights = params.uninitialized_single_output_if_required<float3>(
122 3, "Barycentric Weights");
123
124 mask.foreach_index([&](const int i) {
125 const ReverseUVSampler::Result result = reverse_uv_sampler_->sample(sample_uvs[i]);
126 if (!is_valid.is_empty()) {
127 is_valid[i] = result.type == ReverseUVSampler::ResultType::Ok;
128 }
129 if (!tri_index.is_empty()) {
130 tri_index[i] = result.tri_index;
131 }
132 if (!bary_weights.is_empty()) {
133 bary_weights[i] = result.bary_weights;
134 }
135 });
136 }
137
138 void hash_unique(UniqueHashBytes &hash) const override
139 {
140 static constexpr int8_t id = 0;
141 hash.add(&id);
142 hash.add(source_.get_mesh());
143 fn::FieldHashDeep field_hash;
144 hash.add(field_hash.ensure(src_uv_map_field_));
145 }
146
147 void prepare_for_execution() const override
148 {
149 mutex_.ensure([&]() {
150 const Mesh &mesh = *source_.get_mesh();
151 source_context_.emplace(bke::MeshFieldContext{mesh, AttrDomain::Corner});
152 source_evaluator_ = std::make_unique<FieldEvaluator>(*source_context_, mesh.corners_num);
153 source_evaluator_->add(src_uv_map_field_);
154 source_evaluator_->evaluate();
155 source_uv_map_ = source_evaluator_->get_evaluated<float2>(0);
156
157 reverse_uv_sampler_.emplace(source_uv_map_, mesh.corner_tris());
158 });
159 }
160};
161
163{
164 GeometrySet geometry = params.extract_input<GeometrySet>("Mesh"_ustr);
165 const Mesh *mesh = geometry.get_mesh();
166 if (mesh == nullptr) {
168 return;
169 }
170 if (mesh->faces_num == 0 && mesh->verts_num != 0) {
171 params.error_message_add(NodeWarningType::Error, TIP_("The source mesh must have faces"));
173 return;
174 }
175
176 /* Do reverse sampling of the UV map first. */
178 Field<float2> source_uv_map = *conversions.try_convert<float2>(
179 params.extract_input<Field<float3>>("Source UV Map"_ustr));
180
181 auto sample_uv_value = params.extract_input<bke::SocketValueVariant>("Sample UV"_ustr);
182 if (sample_uv_value.is_list()) {
184 "Lists are not supported for \"Sample UV\" input");
185 }
186 if (sample_uv_value.is_volume_grid()) {
188 "Volume grids are not supported for \"Sample UV\" input");
189 }
190 Field<float2> sample_uvs = *conversions.try_convert<float2>(
191 sample_uv_value.extract<Field<float3>>());
192
193 auto uv_op = FieldOperation::from(
194 std::make_shared<ReverseUVSampleFunction>(geometry, std::move(source_uv_map)),
195 {std::move(sample_uvs)});
196 params.set_output("Is Valid"_ustr, Field<bool>(uv_op, 0));
197
198 /* Use the output of the UV sampling to interpolate the mesh attribute. */
199 GField field = params.extract_input<GField>("Value"_ustr);
200
201 auto sample_op = FieldOperation::from(
202 std::make_shared<bke::mesh_surface_sample::BaryWeightSampleFn>(std::move(geometry),
203 std::move(field)),
204 {Field<int>(uv_op, 1), Field<float3>(uv_op, 2)});
205 params.set_output("Value"_ustr, GField(sample_op, 0));
206}
207
208static void node_rna(StructRNA *srna)
209{
211 "data_type",
212 "Data Type",
213 "",
218}
219
220static void node_register()
221{
222 static bke::bNodeType ntype;
223
224 geo_node_type_base(&ntype, "GeometryNodeSampleUVSurface"_ustr, GEO_NODE_SAMPLE_UV_SURFACE);
225 ntype.ui_name = "Sample UV Surface";
226 ntype.ui_description =
227 "Calculate the interpolated values of a mesh attribute at a UV coordinate";
228 ntype.enum_name_legacy = "SAMPLE_UV_SURFACE";
230 ntype.initfunc = node_init;
231 ntype.declare = node_declare;
236
237 node_rna(ntype.rna_ext.srna);
238}
240
241} // namespace blender::nodes::node_geo_sample_uv_surface_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
#define GEO_NODE_SAMPLE_UV_SURFACE
#define TIP_(msgid)
#define IFACE_(msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
#define UI_ITEM_NONE
GVArray try_convert(GVArray varray, const CPPType &to_type) const
void set_signature(const Signature *signature)
static FieldOperationPtr from(std::shared_ptr< const mf::MultiFunction > fn, Vector< GField > inputs)
Definition field.cc:252
const bke::bNodeType & node_type() const
void add_item(std::string socket_name, SocketLinkOperation::LinkSocketFn fn, int weight=0)
void error_message_add(const NodeWarningType type, StringRef message) const
T extract_input(const UString identifier)
void set_output(const UString identifier, T &&value)
void update_and_connect_available_socket(bNode &new_node, UString socket_name)
Vector< SocketDeclaration * > inputs
Vector< SocketDeclaration * > outputs
ReverseUVSampleFunction(GeometrySet geometry, Field< float2 > src_uv_map_field)
void call(const IndexMask &mask, mf::Params params, mf::Context) const override
const DataTypeConversions & get_implicit_type_conversions()
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
std::optional< eCustomDataType > socket_type_to_custom_data_type(eNodeSocketDatatype type)
Definition node.cc:5911
const EnumPropertyItem * attribute_type_type_with_socket_fn(bContext *, PointerRNA *, PropertyRNA *, bool *r_free)
static void node_layout(ui::Layout &layout, bContext *, PointerRNA *ptr)
static void node_geo_exec(GeoNodeExecParams params)
static void node_declare(NodeDeclarationBuilder &b)
static void node_gather_link_searches(GatherLinkSearchOpParams &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)
VecBase< float, 2 > float2
const EnumPropertyItem rna_enum_attribute_type_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
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)