Blender V4.5
node_geo_distribute_points_in_grid.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_grid.hh"
18
19#include "NOD_rna_define.hh"
20
21#include "UI_interface.hh"
22#include "UI_resources.hh"
23
24#include "GEO_randomize.hh"
25
26#include "node_geometry_util.hh"
27
29
30enum class DistributeMode {
31 Random = 0,
32 Grid = 1,
33};
34
36{
37 b.add_input<decl::Float>("Grid").hide_value().structure_type(StructureType::Grid);
38 auto &density = b.add_input<decl::Float>("Density")
39 .default_value(1.0f)
40 .min(0.0f)
41 .max(100000.0f)
43 .description(
44 "When combined with each voxel's value, determines the number of points "
45 "to sample per unit volume");
46 auto &seed = b.add_input<decl::Int>("Seed").min(-10000).max(10000).description(
47 "Seed used by the random number generator to generate random points");
48 auto &spacing = b.add_input<decl::Vector>("Spacing")
49 .default_value({0.3, 0.3, 0.3})
50 .min(0.0001f)
52 .description("Spacing between grid points");
53 auto &threshold = b.add_input<decl::Float>("Threshold")
54 .default_value(0.1f)
55 .min(0.0f)
56 .max(FLT_MAX)
57 .description("Minimum density of a voxel to contain a grid point");
58 b.add_output<decl::Geometry>("Points").propagate_all();
59
60 const bNode *node = b.node_or_null();
61 if (node != nullptr) {
62 const auto mode = DistributeMode(node->custom1);
63
64 density.available(mode == DistributeMode::Random);
65 seed.available(mode == DistributeMode::Random);
66 spacing.available(mode == DistributeMode::Grid);
67 threshold.available(mode == DistributeMode::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
76static void node_init(bNodeTree * /*tree*/, bNode *node)
77{
78 node->custom1 = int16_t(DistributeMode::Random);
79}
80
81#ifdef WITH_OPENVDB
82/* Implements the interface required by #openvdb::tools::NonUniformPointScatter. */
83class PositionsVDBWrapper {
84 private:
85 float3 offset_fix_;
86 Vector<float3> &vector_;
87
88 public:
89 PositionsVDBWrapper(Vector<float3> &vector, const float3 &offset_fix)
90 : offset_fix_(offset_fix), vector_(vector)
91 {
92 }
93 PositionsVDBWrapper(const PositionsVDBWrapper &wrapper) = default;
94
95 void add(const openvdb::Vec3R &pos)
96 {
97 vector_.append(float3(float(pos[0]), float(pos[1]), float(pos[2])) + offset_fix_);
98 }
99};
100
101/* Use #std::mt19937 as a random number generator. It has a very long period and thus there should
102 * be no visible patterns in the generated points. */
103using RNGType = std::mt19937;
104/* Non-uniform scatter allows the amount of points to be scaled with the volume's density. */
105using NonUniformPointScatterVDB =
106 openvdb::tools::NonUniformPointScatter<PositionsVDBWrapper, RNGType>;
107
108static void point_scatter_density_random(const openvdb::FloatGrid &grid,
109 const float density,
110 const int seed,
111 Vector<float3> &r_positions)
112{
113 /* Offset points by half a voxel so that grid points are aligned with world grid points. */
114 const float3 offset_fix = {0.5f * float(grid.voxelSize().x()),
115 0.5f * float(grid.voxelSize().y()),
116 0.5f * float(grid.voxelSize().z())};
117 /* Setup and call into OpenVDB's point scatter API. */
118 PositionsVDBWrapper vdb_position_wrapper(r_positions, offset_fix);
119 RNGType random_generator(seed);
120 NonUniformPointScatterVDB point_scatter(vdb_position_wrapper, density, random_generator);
121 point_scatter(grid);
122}
123
124static void point_scatter_density_grid(const openvdb::FloatGrid &grid,
125 const float3 spacing,
126 const float threshold,
127 Vector<float3> &r_positions)
128{
129 const openvdb::Vec3d half_voxel(0.5, 0.5, 0.5);
130 const openvdb::Vec3d voxel_spacing(double(spacing.x) / grid.voxelSize().x(),
131 double(spacing.y) / grid.voxelSize().y(),
132 double(spacing.z) / grid.voxelSize().z());
133
134 /* Abort if spacing is zero. */
135 const double min_spacing = std::min({voxel_spacing.x(), voxel_spacing.y(), voxel_spacing.z()});
136 if (std::abs(min_spacing) < 0.0001) {
137 return;
138 }
139
140 /* Iterate through tiles and voxels on the grid. */
141 for (openvdb::FloatGrid::ValueOnCIter cell = grid.cbeginValueOn(); cell; ++cell) {
142 /* Check if the cell's value meets the minimum threshold. */
143 if (cell.getValue() < threshold) {
144 continue;
145 }
146 /* Compute the bounding box of each tile/voxel. */
147 const openvdb::CoordBBox bbox = cell.getBoundingBox();
148 const openvdb::Vec3d box_min = bbox.min().asVec3d() - half_voxel;
149 const openvdb::Vec3d box_max = bbox.max().asVec3d() + half_voxel;
150
151 /* Pick a starting point rounded up to the nearest possible point. */
152 double abs_spacing_x = std::abs(voxel_spacing.x());
153 double abs_spacing_y = std::abs(voxel_spacing.y());
154 double abs_spacing_z = std::abs(voxel_spacing.z());
155 const openvdb::Vec3d start(ceil(box_min.x() / abs_spacing_x) * abs_spacing_x,
156 ceil(box_min.y() / abs_spacing_y) * abs_spacing_y,
157 ceil(box_min.z() / abs_spacing_z) * abs_spacing_z);
158
159 /* Iterate through all possible points in box. */
160 for (double x = start.x(); x < box_max.x(); x += abs_spacing_x) {
161 for (double y = start.y(); y < box_max.y(); y += abs_spacing_y) {
162 for (double z = start.z(); z < box_max.z(); z += abs_spacing_z) {
163 /* Transform with grid matrix and add point. */
164 const openvdb::Vec3d idx_pos(x, y, z);
165 const openvdb::Vec3d local_pos = grid.indexToWorld(idx_pos + half_voxel);
166 r_positions.append({float(local_pos.x()), float(local_pos.y()), float(local_pos.z())});
167 }
168 }
169 }
170 }
171}
172
173#endif /* WITH_OPENVDB */
174
176{
177#ifdef WITH_OPENVDB
178 const bke::VolumeGrid<float> volume_grid = params.extract_input<bke::VolumeGrid<float>>("Grid");
179 if (!volume_grid) {
180 params.set_default_remaining_outputs();
181 return;
182 }
183
184 bke::VolumeTreeAccessToken tree_token;
185 const openvdb::GridBase &base_grid = volume_grid.grid(tree_token);
186 if (!base_grid.isType<openvdb::FloatGrid>()) {
187 params.set_default_remaining_outputs();
188 return;
189 }
190 const openvdb::FloatGrid &grid = static_cast<const openvdb::FloatGrid &>(base_grid);
191
192 const DistributeMode mode = DistributeMode(params.node().custom1);
193
194 float density;
195 int seed;
196 float3 spacing{0, 0, 0};
197 float threshold;
198 if (mode == DistributeMode::Random) {
199 density = params.extract_input<float>("Density");
200 seed = params.extract_input<int>("Seed");
201 }
202 else if (mode == DistributeMode::Grid) {
203 spacing = params.extract_input<float3>("Spacing");
204 threshold = params.extract_input<float>("Threshold");
205 }
206
207 Vector<float3> positions;
208 switch (mode) {
210 point_scatter_density_random(grid, density, seed, positions);
211 break;
213 point_scatter_density_grid(grid, spacing, threshold, positions);
214 break;
215 }
216
217 PointCloud *pointcloud = BKE_pointcloud_new_nomain(positions.size());
218 pointcloud->positions_for_write().copy_from(positions);
219
221
222 params.set_output("Points", GeometrySet::from_pointcloud(pointcloud));
223#else
225#endif
226}
227
228static void node_rna(StructRNA *srna)
229{
230 static const EnumPropertyItem mode_items[] = {
232 "DENSITY_RANDOM",
233 0,
234 "Random",
235 "Distribute points randomly inside of the volume"},
237 "DENSITY_GRID",
238 0,
239 "Grid",
240 "Distribute the points in a grid pattern inside of the volume"},
241 {0, nullptr, 0, nullptr, nullptr},
242 };
243
245 "mode",
246 "Distribution Method",
247 "Method to use for scattering points",
248 mode_items,
251}
252
253static void node_register()
254{
255 static blender::bke::bNodeType ntype;
257 &ntype, "GeometryNodeDistributePointsInGrid", GEO_NODE_DISTRIBUTE_POINTS_IN_GRID);
258 ntype.ui_name = "Distribute Points in Grid";
259 ntype.ui_description = "Generate points inside a volume grid";
260 ntype.enum_name_legacy = "DISTRIBUTE_POINTS_IN_GRID";
262 ntype.initfunc = node_init;
263 blender::bke::node_type_size(ntype, 170, 100, 320);
264 ntype.declare = node_declare;
269
270 node_rna(ntype.rna_ext.srna);
271}
273
274} // namespace blender::nodes::node_geo_distribute_points_in_grid_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:447
#define GEO_NODE_DISTRIBUTE_POINTS_IN_GRID
General operations for point clouds.
PointCloud * BKE_pointcloud_new_nomain(int totpoint)
float[3] Vector
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
@ PROP_XYZ
Definition RNA_types.hh:257
@ PROP_NONE
Definition RNA_types.hh:221
#define UI_ITEM_NONE
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)
uint pos
VecBase< float, 3 > float3
#define ceil
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
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 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 search_link_ops_for_volume_grid_node(GatherLinkSearchOpParams &params)
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)
#define min(a, b)
Definition sort.cc:36
#define FLT_MAX
Definition stdcycles.h:14
StructRNA * srna
Definition RNA_types.hh:909
int16_t custom1
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
NodeGatherSocketLinkOperationsFunction gather_link_search_ops
Definition BKE_node.hh:371
NodeDeclareFunction declare
Definition BKE_node.hh:355
static GeometrySet from_pointcloud(PointCloud *pointcloud, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
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)
PointerRNA * ptr
Definition wm_files.cc:4227