Blender V4.3
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#endif
10
11#include "DNA_node_types.h"
13
14#include "BKE_pointcloud.hh"
15#include "BKE_volume.hh"
16#include "BKE_volume_grid.hh"
17
18#include "NOD_rna_define.hh"
19
20#include "UI_interface.hh"
21#include "UI_resources.hh"
22
23#include "GEO_randomize.hh"
24
25#include "node_geometry_util.hh"
26
28
29enum class DistributeMode {
30 Random = 0,
31 Grid = 1,
32};
33
35{
36 b.add_input<decl::Float>("Grid").hide_value();
37 auto &density = b.add_input<decl::Float>("Density")
38 .default_value(1.0f)
39 .min(0.0f)
40 .max(100000.0f)
42 .description(
43 "When combined with each voxel's value, determines the number of points "
44 "to sample per unit volume");
45 auto &seed = b.add_input<decl::Int>("Seed").min(-10000).max(10000).description(
46 "Seed used by the random number generator to generate random points");
47 auto &spacing = b.add_input<decl::Vector>("Spacing")
48 .default_value({0.3, 0.3, 0.3})
49 .min(0.0001f)
51 .description("Spacing between grid points");
52 auto &threshold = b.add_input<decl::Float>("Threshold")
53 .default_value(0.1f)
54 .min(0.0f)
55 .max(FLT_MAX)
56 .description("Minimum density of a voxel to contain a grid point");
57 b.add_output<decl::Geometry>("Points").propagate_all();
58
59 const bNode *node = b.node_or_null();
60 if (node != nullptr) {
61 const auto mode = DistributeMode(node->custom1);
62
63 density.available(mode == DistributeMode::Random);
64 seed.available(mode == DistributeMode::Random);
65 spacing.available(mode == DistributeMode::Grid);
66 threshold.available(mode == DistributeMode::Grid);
67 }
68}
69
70static void node_layout(uiLayout *layout, bContext * /*C*/, PointerRNA *ptr)
71{
72 uiItemR(layout, ptr, "mode", UI_ITEM_NONE, "", ICON_NONE);
73}
74
75static void node_init(bNodeTree * /*tree*/, bNode *node)
76{
77 node->custom1 = int16_t(DistributeMode::Random);
78}
79
80#ifdef WITH_OPENVDB
81/* Implements the interface required by #openvdb::tools::NonUniformPointScatter. */
82class PositionsVDBWrapper {
83 private:
84 float3 offset_fix_;
85 Vector<float3> &vector_;
86
87 public:
88 PositionsVDBWrapper(Vector<float3> &vector, const float3 &offset_fix)
89 : offset_fix_(offset_fix), vector_(vector)
90 {
91 }
92 PositionsVDBWrapper(const PositionsVDBWrapper &wrapper) = default;
93
94 void add(const openvdb::Vec3R &pos)
95 {
96 vector_.append(float3(float(pos[0]), float(pos[1]), float(pos[2])) + offset_fix_);
97 }
98};
99
100/* Use #std::mt19937 as a random number generator. It has a very long period and thus there should
101 * be no visible patterns in the generated points. */
102using RNGType = std::mt19937;
103/* Non-uniform scatter allows the amount of points to be scaled with the volume's density. */
104using NonUniformPointScatterVDB =
105 openvdb::tools::NonUniformPointScatter<PositionsVDBWrapper, RNGType>;
106
107static void point_scatter_density_random(const openvdb::FloatGrid &grid,
108 const float density,
109 const int seed,
110 Vector<float3> &r_positions)
111{
112 /* Offset points by half a voxel so that grid points are aligned with world grid points. */
113 const float3 offset_fix = {0.5f * float(grid.voxelSize().x()),
114 0.5f * float(grid.voxelSize().y()),
115 0.5f * float(grid.voxelSize().z())};
116 /* Setup and call into OpenVDB's point scatter API. */
117 PositionsVDBWrapper vdb_position_wrapper(r_positions, offset_fix);
118 RNGType random_generator(seed);
119 NonUniformPointScatterVDB point_scatter(vdb_position_wrapper, density, random_generator);
120 point_scatter(grid);
121}
122
123static void point_scatter_density_grid(const openvdb::FloatGrid &grid,
124 const float3 spacing,
125 const float threshold,
126 Vector<float3> &r_positions)
127{
128 const openvdb::Vec3d half_voxel(0.5, 0.5, 0.5);
129 const openvdb::Vec3d voxel_spacing(double(spacing.x) / grid.voxelSize().x(),
130 double(spacing.y) / grid.voxelSize().y(),
131 double(spacing.z) / grid.voxelSize().z());
132
133 /* Abort if spacing is zero. */
134 const double min_spacing = std::min(voxel_spacing.x(),
135 std::min(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;
256 geo_node_type_base(&ntype,
257 GEO_NODE_DISTRIBUTE_POINTS_IN_GRID,
258 "Distribute Points in Grid",
260 ntype.initfunc = node_init;
261 blender::bke::node_type_size(&ntype, 170, 100, 320);
262 ntype.declare = node_declare;
267
268 node_rna(ntype.rna_ext.srna);
269}
271
272} // namespace blender::nodes::node_geo_distribute_points_in_grid_cc
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:418
General operations for point clouds.
PointCloud * BKE_pointcloud_new_nomain(int totpoint)
Volume data-block.
#define NOD_REGISTER_NODE(REGISTER_FUNC)
#define NOD_inline_enum_accessors(member)
@ PROP_XYZ
Definition RNA_types.hh:172
@ PROP_NONE
Definition RNA_types.hh:136
#define UI_ITEM_NONE
void uiItemR(uiLayout *layout, PointerRNA *ptr, const char *propname, eUI_Item_Flag flag, const char *name, int icon)
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)
local_group_size(16, 16) .push_constant(Type b
draw_view in_light_buf[] float
draw_view push_constant(Type::INT, "radiance_src") .push_constant(Type capture_info_buf storage_buf(1, Qualifier::READ, "ObjectBounds", "bounds_buf[]") .push_constant(Type draw_view int
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
ccl_device_inline float3 ceil(const float3 a)
static void add(blender::Map< std::string, std::string > &messages, Message &msg)
Definition msgfmt.cc:227
void node_type_size(bNodeType *ntype, int width, int minwidth, int maxwidth)
Definition node.cc:4602
void node_register_type(bNodeType *ntype)
Definition node.cc:1708
void debug_randomize_point_order(PointCloud *pointcloud)
Definition randomize.cc:181
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)
void geo_node_type_base(blender::bke::bNodeType *ntype, int type, const char *name, short nclass)
#define min(a, b)
Definition sort.c:32
#define FLT_MAX
Definition stdcycles.h:14
signed short int16_t
Definition stdint.h:76
StructRNA * srna
Definition RNA_types.hh:780
static GeometrySet from_pointcloud(PointCloud *pointcloud, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
Defines a node type.
Definition BKE_node.hh:218
void(* initfunc)(bNodeTree *ntree, bNode *node)
Definition BKE_node.hh:267
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:339
void(* draw_buttons)(uiLayout *, bContext *C, PointerRNA *ptr)
Definition BKE_node.hh:238
NodeGatherSocketLinkOperationsFunction gather_link_search_ops
Definition BKE_node.hh:363
NodeDeclareFunction declare
Definition BKE_node.hh:347
float z
Definition sky_float3.h:27
float y
Definition sky_float3.h:27
float x
Definition sky_float3.h:27
PointerRNA * ptr
Definition wm_files.cc:4126