Blender V4.5
node_geo_distribute_points_in_volume.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#ifdef WITH_OPENVDB
6# include <openvdb/openvdb.h>
7# include <openvdb/tools/Interpolation.h>
8# include <openvdb/tools/PointScatter.h>
9
10# include <algorithm>
11#endif
12
13#include "DNA_node_types.h"
15
16#include "BKE_pointcloud.hh"
17#include "BKE_volume.hh"
18#include "BKE_volume_grid.hh"
19
20#include "NOD_rna_define.hh"
21
22#include "UI_interface.hh"
23#include "UI_resources.hh"
24
25#include "GEO_randomize.hh"
26
27#include "node_geometry_util.hh"
28
30
32
34{
35 b.add_input<decl::Geometry>("Volume")
36 .supported_type(GeometryComponent::Type::Volume)
37 .translation_context(BLT_I18NCONTEXT_ID_ID);
38 auto &density = b.add_input<decl::Float>("Density")
39 .default_value(1.0f)
40 .min(0.0f)
41 .max(100000.0f)
42 .subtype(PROP_NONE)
43 .description("Number of points to sample per unit volume");
44 auto &seed = b.add_input<decl::Int>("Seed").min(-10000).max(10000).description(
45 "Seed used by the random number generator to generate random points");
46 auto &spacing = b.add_input<decl::Vector>("Spacing")
47 .default_value({0.3, 0.3, 0.3})
48 .min(0.0001f)
49 .subtype(PROP_XYZ)
50 .description("Spacing between grid points");
51 auto &threshold = b.add_input<decl::Float>("Threshold")
52 .default_value(0.1f)
53 .min(0.0f)
54 .max(FLT_MAX)
55 .description("Minimum density of a volume cell to contain a grid point");
56 b.add_output<decl::Geometry>("Points").propagate_all();
57
58 const bNode *node = b.node_or_null();
59 if (node != nullptr) {
60 const NodeGeometryDistributePointsInVolume &storage = node_storage(*node);
62 storage.mode);
63
67 threshold.available(mode == GEO_NODE_DISTRIBUTE_POINTS_IN_VOLUME_DENSITY_GRID);
68 }
69}
70
71static void node_layout(uiLayout *layout, bContext * /*C*/, PointerRNA *ptr)
72{
73 layout->prop(ptr, "mode", UI_ITEM_NONE, "", ICON_NONE);
74}
75
83
84#ifdef WITH_OPENVDB
85/* Implements the interface required by #openvdb::tools::NonUniformPointScatter. */
86class PositionsVDBWrapper {
87 private:
88 float3 offset_fix_;
89 Vector<float3> &vector_;
90
91 public:
92 PositionsVDBWrapper(Vector<float3> &vector, const float3 offset_fix)
93 : offset_fix_(offset_fix), vector_(vector)
94 {
95 }
96 PositionsVDBWrapper(const PositionsVDBWrapper &wrapper) = default;
97
98 void add(const openvdb::Vec3R &pos)
99 {
100 vector_.append(float3(float(pos[0]), float(pos[1]), float(pos[2])) + offset_fix_);
101 }
102};
103
104/* Use #std::mt19937 as a random number generator,
105 * it has a very long period and thus there should be no visible patterns in the generated points.
106 */
107using RNGType = std::mt19937;
108/* Non-uniform scatter allows the amount of points to be scaled with the volume's density. */
109using NonUniformPointScatterVDB =
110 openvdb::tools::NonUniformPointScatter<PositionsVDBWrapper, RNGType>;
111
112static void point_scatter_density_random(const openvdb::FloatGrid &grid,
113 const float density,
114 const int seed,
115 Vector<float3> &r_positions)
116{
117 /* Offset points by half a voxel so that grid points are aligned with world grid points. */
118 const float3 offset_fix = {0.5f * float(grid.voxelSize().x()),
119 0.5f * float(grid.voxelSize().y()),
120 0.5f * float(grid.voxelSize().z())};
121 /* Setup and call into OpenVDB's point scatter API. */
122 PositionsVDBWrapper vdb_position_wrapper = PositionsVDBWrapper(r_positions, offset_fix);
123 RNGType random_generator(seed);
124 NonUniformPointScatterVDB point_scatter(vdb_position_wrapper, density, random_generator);
125 point_scatter(grid);
126}
127
128static void point_scatter_density_grid(const openvdb::FloatGrid &grid,
129 const float3 spacing,
130 const float threshold,
131 Vector<float3> &r_positions)
132{
133 const openvdb::Vec3d half_voxel(0.5, 0.5, 0.5);
134 const openvdb::Vec3d voxel_spacing(double(spacing.x) / grid.voxelSize().x(),
135 double(spacing.y) / grid.voxelSize().y(),
136 double(spacing.z) / grid.voxelSize().z());
137
138 /* Abort if spacing is zero. */
139 const double min_spacing = std::min({voxel_spacing.x(), voxel_spacing.y(), voxel_spacing.z()});
140 if (std::abs(min_spacing) < 0.0001) {
141 return;
142 }
143
144 /* Iterate through tiles and voxels on the grid. */
145 for (openvdb::FloatGrid::ValueOnCIter cell = grid.cbeginValueOn(); cell; ++cell) {
146 /* Check if the cell's value meets the minimum threshold. */
147 if (cell.getValue() < threshold) {
148 continue;
149 }
150 /* Compute the bounding box of each tile/voxel. */
151 const openvdb::CoordBBox bbox = cell.getBoundingBox();
152 const openvdb::Vec3d box_min = bbox.min().asVec3d() - half_voxel;
153 const openvdb::Vec3d box_max = bbox.max().asVec3d() + half_voxel;
154
155 /* Pick a starting point rounded up to the nearest possible point. */
156 double abs_spacing_x = std::abs(voxel_spacing.x());
157 double abs_spacing_y = std::abs(voxel_spacing.y());
158 double abs_spacing_z = std::abs(voxel_spacing.z());
159 const openvdb::Vec3d start(ceil(box_min.x() / abs_spacing_x) * abs_spacing_x,
160 ceil(box_min.y() / abs_spacing_y) * abs_spacing_y,
161 ceil(box_min.z() / abs_spacing_z) * abs_spacing_z);
162
163 /* Iterate through all possible points in box. */
164 for (double x = start.x(); x < box_max.x(); x += abs_spacing_x) {
165 for (double y = start.y(); y < box_max.y(); y += abs_spacing_y) {
166 for (double z = start.z(); z < box_max.z(); z += abs_spacing_z) {
167 /* Transform with grid matrix and add point. */
168 const openvdb::Vec3d idx_pos(x, y, z);
169 const openvdb::Vec3d local_pos = grid.indexToWorld(idx_pos + half_voxel);
170 r_positions.append({float(local_pos.x()), float(local_pos.y()), float(local_pos.z())});
171 }
172 }
173 }
174 }
175}
176
177#endif /* WITH_OPENVDB */
178
180{
181#ifdef WITH_OPENVDB
182 GeometrySet geometry_set = params.extract_input<GeometrySet>("Volume");
183
184 const NodeGeometryDistributePointsInVolume &storage = node_storage(params.node());
186 storage.mode);
187
188 float density;
189 int seed;
190 float3 spacing{0, 0, 0};
191 float threshold;
193 density = params.extract_input<float>("Density");
194 seed = params.extract_input<int>("Seed");
195 }
197 spacing = params.extract_input<float3>("Spacing");
198 threshold = params.extract_input<float>("Threshold");
199 }
200
201 geometry_set.modify_geometry_sets([&](GeometrySet &geometry_set) {
202 if (!geometry_set.has_volume()) {
203 geometry_set.keep_only_during_modify({GeometryComponent::Type::PointCloud});
204 return;
205 }
206 const VolumeComponent *component = geometry_set.get_component<VolumeComponent>();
207 const Volume *volume = component->get();
208 BKE_volume_load(volume, params.bmain());
209
210 Vector<float3> positions;
211
212 for (const int i : IndexRange(BKE_volume_num_grids(volume))) {
213 const bke::VolumeGridData *volume_grid = BKE_volume_grid_get(volume, i);
214 if (volume_grid == nullptr) {
215 continue;
216 }
217
218 bke::VolumeTreeAccessToken tree_token;
219 const openvdb::GridBase &base_grid = volume_grid->grid(tree_token);
220
221 if (!base_grid.isType<openvdb::FloatGrid>()) {
222 continue;
223 }
224
225 const openvdb::FloatGrid &grid = static_cast<const openvdb::FloatGrid &>(base_grid);
226
228 point_scatter_density_random(grid, density, seed, positions);
229 }
231 point_scatter_density_grid(grid, spacing, threshold, positions);
232 }
233 }
234
235 PointCloud *pointcloud = BKE_pointcloud_new_nomain(positions.size());
236 bke::MutableAttributeAccessor point_attributes = pointcloud->attributes_for_write();
237 pointcloud->positions_for_write().copy_from(positions);
239 point_attributes.lookup_or_add_for_write_only_span<float>("radius", AttrDomain::Point);
240
241 point_radii.span.fill(0.05f);
242 point_radii.finish();
243
245
246 geometry_set.replace_pointcloud(pointcloud);
247 geometry_set.keep_only_during_modify({GeometryComponent::Type::PointCloud});
248 });
249
250 params.set_output("Points", std::move(geometry_set));
251
252#else
254#endif
255}
256
257static void node_rna(StructRNA *srna)
258{
259 static const EnumPropertyItem mode_items[] = {
261 "DENSITY_RANDOM",
262 0,
263 "Random",
264 "Distribute points randomly inside of the volume"},
266 "DENSITY_GRID",
267 0,
268 "Grid",
269 "Distribute the points in a grid pattern inside of the volume"},
270 {0, nullptr, 0, nullptr, nullptr},
271 };
272
274 "mode",
275 "Distribution Method",
276 "Method to use for scattering points",
277 mode_items,
280}
281
282static void node_register()
283{
284 static blender::bke::bNodeType ntype;
286 &ntype, "GeometryNodeDistributePointsInVolume", GEO_NODE_DISTRIBUTE_POINTS_IN_VOLUME);
287 ntype.ui_name = "Distribute Points in Volume";
288 ntype.ui_description = "Generate points inside a volume";
289 ntype.enum_name_legacy = "DISTRIBUTE_POINTS_IN_VOLUME";
292 "NodeGeometryDistributePointsInVolume",
295 ntype.initfunc = node_init;
296 blender::bke::node_type_size(ntype, 170, 100, 320);
297 ntype.declare = node_declare;
301
302 node_rna(ntype.rna_ext.srna);
303}
305
306} // namespace blender::nodes::node_geo_distribute_points_in_volume_cc
#define NODE_STORAGE_FUNCS(StorageT)
Definition BKE_node.hh:1215
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:447
#define GEO_NODE_DISTRIBUTE_POINTS_IN_VOLUME
General operations for point clouds.
PointCloud * BKE_pointcloud_new_nomain(int totpoint)
Volume data-block.
int BKE_volume_num_grids(const Volume *volume)
bool BKE_volume_load(const Volume *volume, const Main *bmain)
const blender::bke::VolumeGridData * BKE_volume_grid_get(const Volume *volume, int grid_index)
#define BLT_I18NCONTEXT_ID_ID
float[3] Vector
GeometryNodeDistributePointsInVolumeMode
@ GEO_NODE_DISTRIBUTE_POINTS_IN_VOLUME_DENSITY_GRID
@ GEO_NODE_DISTRIBUTE_POINTS_IN_VOLUME_DENSITY_RANDOM
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_storage_enum_accessors(member)
@ PROP_XYZ
Definition RNA_types.hh:257
@ PROP_NONE
Definition RNA_types.hh:221
#define UI_ITEM_NONE
BMesh const char void * data
SIMD_FORCE_INLINE const btScalar & z() const
Return the z value.
Definition btQuadWord.h:117
static unsigned long seed
Definition btSoftBody.h:39
void append(const T &value)
int64_t size() const
void append(const T &value)
GSpanAttributeWriter lookup_or_add_for_write_only_span(StringRef attribute_id, AttrDomain domain, eCustomDataType data_type)
uint pos
VecBase< float, 3 > float3
#define ceil
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
void * MEM_callocN(size_t len, const char *str)
Definition mallocn.cc:118
static void add(blender::Map< std::string, std::string > &messages, Message &msg)
Definition msgfmt.cc:222
void node_type_size(bNodeType &ntype, int width, int minwidth, int maxwidth)
Definition node.cc:5573
void node_register_type(bNodeType &ntype)
Definition node.cc:2748
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
void debug_randomize_point_order(PointCloud *pointcloud)
Definition randomize.cc:178
static void node_layout(uiLayout *layout, bContext *, PointerRNA *ptr)
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 node_geo_exec_with_missing_openvdb(GeoNodeExecParams &params)
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 min(a, b)
Definition sort.cc:36
#define FLT_MAX
Definition stdcycles.h:14
StructRNA * srna
Definition RNA_types.hh:909
void * storage
void replace_pointcloud(PointCloud *pointcloud, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
void keep_only_during_modify(Span< GeometryComponent::Type > component_types)
const GeometryComponent * get_component(GeometryComponent::Type component_type) const
void modify_geometry_sets(ForeachSubGeometryCallback 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
float z
Definition sky_float3.h:27
float y
Definition sky_float3.h:27
float x
Definition sky_float3.h:27
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
max
Definition text_draw.cc:251
PointerRNA * ptr
Definition wm_files.cc:4226