1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16 
17 /** \file
18  * \ingroup modifiers
19  */
20 
21 #include <vector>
22 
23 #include "BKE_lib_query.h"
24 #include "BKE_mesh.h"
25 #include "BKE_modifier.h"
26 #include "BKE_volume.h"
27 
28 #include "MOD_modifiertypes.h"
29 #include "MOD_ui_common.h"
30 
31 #include "DNA_mesh_types.h"
32 #include "DNA_meshdata_types.h"
33 #include "DNA_modifier_types.h"
34 #include "DNA_object_types.h"
35 #include "DNA_screen_types.h"
36 #include "DNA_volume_types.h"
37 
38 #include "UI_interface.h"
39 #include "UI_resources.h"
40 
41 #include "RNA_access.h"
42 
43 #include "BLI_float4x4.hh"
44 #include "BLI_math_vector.h"
45 #include "BLI_span.hh"
46 #include "BLI_timeit.hh"
47 
48 #include "DEG_depsgraph_query.h"
49 
50 #ifdef WITH_OPENVDB
51 #  include <openvdb/tools/GridTransformer.h>
52 #  include <openvdb/tools/VolumeToMesh.h>
53 #endif
54 
55 using blender::float3;
56 using blender::float4x4;
57 using blender::Span;
58 
initData(ModifierData * md)59 static void initData(ModifierData *md)
60 {
61   VolumeToMeshModifierData *vmmd = reinterpret_cast<VolumeToMeshModifierData *>(md);
62   vmmd->object = NULL;
63   vmmd->threshold = 0.1f;
64   strncpy(vmmd->grid_name, "density", MAX_NAME);
65   vmmd->adaptivity = 0.0f;
66   vmmd->resolution_mode = VOLUME_TO_MESH_RESOLUTION_MODE_GRID;
67   vmmd->voxel_amount = 32;
68   vmmd->voxel_size = 0.1f;
69   vmmd->flag = 0;
70 }
71 
updateDepsgraph(ModifierData * md,const ModifierUpdateDepsgraphContext * ctx)72 static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
73 {
74   VolumeToMeshModifierData *vmmd = reinterpret_cast<VolumeToMeshModifierData *>(md);
75   DEG_add_modifier_to_transform_relation(ctx->node, "Volume to Mesh Modifier");
76   if (vmmd->object) {
77     DEG_add_object_relation(
78         ctx->node, vmmd->object, DEG_OB_COMP_GEOMETRY, "Volume to Mesh Modifier");
79     DEG_add_object_relation(
80         ctx->node, vmmd->object, DEG_OB_COMP_TRANSFORM, "Volume to Mesh Modifier");
81   }
82 }
83 
foreachIDLink(ModifierData * md,Object * ob,IDWalkFunc walk,void * userData)84 static void foreachIDLink(ModifierData *md, Object *ob, IDWalkFunc walk, void *userData)
85 {
86   VolumeToMeshModifierData *vmmd = reinterpret_cast<VolumeToMeshModifierData *>(md);
87   walk(userData, ob, (ID **)&vmmd->object, IDWALK_CB_NOP);
88 }
89 
panel_draw(const bContext * UNUSED (C),Panel * panel)90 static void panel_draw(const bContext *UNUSED(C), Panel *panel)
91 {
92   uiLayout *layout = panel->layout;
93 
94   PointerRNA *ptr = modifier_panel_get_property_pointers(panel, NULL);
95   VolumeToMeshModifierData *vmmd = static_cast<VolumeToMeshModifierData *>(ptr->data);
96 
97   uiLayoutSetPropSep(layout, true);
98   uiLayoutSetPropDecorate(layout, false);
99 
100   {
101     uiLayout *col = uiLayoutColumn(layout, false);
102     uiItemR(col, ptr, "object", 0, NULL, ICON_NONE);
103     uiItemR(col, ptr, "grid_name", 0, NULL, ICON_NONE);
104   }
105 
106   {
107     uiLayout *col = uiLayoutColumn(layout, false);
108     uiItemR(col, ptr, "resolution_mode", 0, NULL, ICON_NONE);
109     if (vmmd->resolution_mode == VOLUME_TO_MESH_RESOLUTION_MODE_VOXEL_AMOUNT) {
110       uiItemR(col, ptr, "voxel_amount", 0, NULL, ICON_NONE);
111     }
112     else if (vmmd->resolution_mode == VOLUME_TO_MESH_RESOLUTION_MODE_VOXEL_SIZE) {
113       uiItemR(col, ptr, "voxel_size", 0, NULL, ICON_NONE);
114     }
115   }
116 
117   {
118     uiLayout *col = uiLayoutColumn(layout, false);
119     uiItemR(col, ptr, "threshold", 0, NULL, ICON_NONE);
120     uiItemR(col, ptr, "adaptivity", 0, NULL, ICON_NONE);
121     uiItemR(col, ptr, "use_smooth_shade", 0, NULL, ICON_NONE);
122   }
123 
124   modifier_panel_end(layout, ptr);
125 }
126 
panelRegister(ARegionType * region_type)127 static void panelRegister(ARegionType *region_type)
128 {
129   modifier_panel_register(region_type, eModifierType_VolumeToMesh, panel_draw);
130 }
131 
132 #ifdef WITH_OPENVDB
133 
134 struct VolumeToMeshOp {
135   const openvdb::GridBase &base_grid;
136   VolumeToMeshModifierData &vmmd;
137   const ModifierEvalContext &ctx;
138   std::vector<openvdb::Vec3s> verts;
139   std::vector<openvdb::Vec3I> tris;
140   std::vector<openvdb::Vec4I> quads;
141 
operator ()VolumeToMeshOp142   template<typename GridType> bool operator()()
143   {
144     if constexpr (std::is_scalar_v<typename GridType::ValueType>) {
145       this->generate_mesh_data<GridType>();
146       return true;
147     }
148     else {
149       return false;
150     }
151   }
152 
generate_mesh_dataVolumeToMeshOp153   template<typename GridType> void generate_mesh_data()
154   {
155     /* Make a new transform from the index space into the mesh object space. */
156     openvdb::math::Transform::Ptr transform = this->base_grid.transform().copy();
157     transform->postMult(openvdb::Mat4d((float *)vmmd.object->obmat));
158     openvdb::Mat4d imat = openvdb::Mat4d((float *)ctx.object->imat);
159     /* `imat` had floating point issues and wasn't affine. */
160     imat.setCol(3, openvdb::Vec4d(0, 0, 0, 1));
161     transform->postMult(imat);
162 
163     /* Create a new grid with a different transform. The underlying tree is shared. */
164     typename GridType::ConstPtr grid = openvdb::gridConstPtrCast<GridType>(
165         this->base_grid.copyGridReplacingTransform(transform));
166 
167     if (this->vmmd.resolution_mode == VOLUME_TO_MESH_RESOLUTION_MODE_GRID) {
168       this->grid_to_mesh(*grid);
169       return;
170     }
171 
172     const float resolution_factor = this->compute_resolution_factor(*grid);
173     typename GridType::Ptr temp_grid = this->create_grid_with_changed_resolution(
174         *grid, resolution_factor);
175     this->grid_to_mesh(*temp_grid);
176   }
177 
178   template<typename GridType>
create_grid_with_changed_resolutionVolumeToMeshOp179   typename GridType::Ptr create_grid_with_changed_resolution(const GridType &old_grid,
180                                                              const float resolution_factor)
181   {
182     BLI_assert(resolution_factor > 0.0f);
183 
184     openvdb::Mat4R xform;
185     xform.setToScale(openvdb::Vec3d(resolution_factor));
186     openvdb::tools::GridTransformer transformer{xform};
187 
188     typename GridType::Ptr new_grid = GridType::create();
189     transformer.transformGrid<openvdb::tools::BoxSampler>(old_grid, *new_grid);
190     new_grid->transform() = old_grid.transform();
191     new_grid->transform().preScale(1.0f / resolution_factor);
192     return new_grid;
193   }
194 
compute_resolution_factorVolumeToMeshOp195   float compute_resolution_factor(const openvdb::GridBase &grid) const
196   {
197     const openvdb::Vec3s voxel_size{grid.voxelSize()};
198     const float current_voxel_size = std::max({voxel_size[0], voxel_size[1], voxel_size[2]});
199     const float desired_voxel_size = this->compute_desired_voxel_size(grid);
200     return current_voxel_size / desired_voxel_size;
201   }
202 
compute_desired_voxel_sizeVolumeToMeshOp203   float compute_desired_voxel_size(const openvdb::GridBase &grid) const
204   {
205     if (this->vmmd.resolution_mode == VOLUME_TO_MESH_RESOLUTION_MODE_VOXEL_SIZE) {
206       return this->vmmd.voxel_size;
207     }
208     const openvdb::CoordBBox coord_bbox = base_grid.evalActiveVoxelBoundingBox();
209     const openvdb::BBoxd bbox = grid.transform().indexToWorld(coord_bbox);
210     const float max_extent = bbox.extents()[bbox.maxExtent()];
211     const float voxel_size = max_extent / this->vmmd.voxel_amount;
212     return voxel_size;
213   }
214 
grid_to_meshVolumeToMeshOp215   template<typename GridType> void grid_to_mesh(const GridType &grid)
216   {
217     openvdb::tools::volumeToMesh(
218         grid, this->verts, this->tris, this->quads, this->vmmd.threshold, this->vmmd.adaptivity);
219   }
220 };
221 
new_mesh_from_openvdb_data(Span<openvdb::Vec3s> verts,Span<openvdb::Vec3I> tris,Span<openvdb::Vec4I> quads)222 static Mesh *new_mesh_from_openvdb_data(Span<openvdb::Vec3s> verts,
223                                         Span<openvdb::Vec3I> tris,
224                                         Span<openvdb::Vec4I> quads)
225 {
226   const int tot_loops = 3 * tris.size() + 4 * quads.size();
227   const int tot_polys = tris.size() + quads.size();
228 
229   Mesh *mesh = BKE_mesh_new_nomain(verts.size(), 0, 0, tot_loops, tot_polys);
230 
231   /* Write vertices. */
232   for (const int i : verts.index_range()) {
233     const blender::float3 co = blender::float3(verts[i].asV());
234     copy_v3_v3(mesh->mvert[i].co, co);
235   }
236 
237   /* Write triangles. */
238   for (const int i : tris.index_range()) {
239     mesh->mpoly[i].loopstart = 3 * i;
240     mesh->mpoly[i].totloop = 3;
241     for (int j = 0; j < 3; j++) {
242       /* Reverse vertex order to get correct normals. */
243       mesh->mloop[3 * i + j].v = tris[i][2 - j];
244     }
245   }
246 
247   /* Write quads. */
248   const int poly_offset = tris.size();
249   const int loop_offset = tris.size() * 3;
250   for (const int i : quads.index_range()) {
251     mesh->mpoly[poly_offset + i].loopstart = loop_offset + 4 * i;
252     mesh->mpoly[poly_offset + i].totloop = 4;
253     for (int j = 0; j < 4; j++) {
254       /* Reverse vertex order to get correct normals. */
255       mesh->mloop[loop_offset + 4 * i + j].v = quads[i][3 - j];
256     }
257   }
258 
259   BKE_mesh_calc_edges(mesh, false, false);
260   BKE_mesh_calc_normals(mesh);
261   return mesh;
262 }
263 #endif
264 
create_empty_mesh(const Mesh * input_mesh)265 static Mesh *create_empty_mesh(const Mesh *input_mesh)
266 {
267   Mesh *new_mesh = BKE_mesh_new_nomain(0, 0, 0, 0, 0);
268   BKE_mesh_copy_settings(new_mesh, input_mesh);
269   return new_mesh;
270 }
271 
modifyMesh(ModifierData * md,const ModifierEvalContext * ctx,Mesh * input_mesh)272 static Mesh *modifyMesh(ModifierData *md, const ModifierEvalContext *ctx, Mesh *input_mesh)
273 {
274 #ifdef WITH_OPENVDB
275   VolumeToMeshModifierData *vmmd = reinterpret_cast<VolumeToMeshModifierData *>(md);
276   if (vmmd->object == nullptr) {
277     return create_empty_mesh(input_mesh);
278   }
279   if (vmmd->object->type != OB_VOLUME) {
280     return create_empty_mesh(input_mesh);
281   }
282   if (vmmd->resolution_mode == VOLUME_TO_MESH_RESOLUTION_MODE_VOXEL_SIZE &&
283       vmmd->voxel_size == 0.0f) {
284     return create_empty_mesh(input_mesh);
285   }
286   if (vmmd->resolution_mode == VOLUME_TO_MESH_RESOLUTION_MODE_VOXEL_AMOUNT &&
287       vmmd->voxel_amount == 0) {
288     return create_empty_mesh(input_mesh);
289   }
290 
291   Volume *volume = static_cast<Volume *>(vmmd->object->data);
292 
293   BKE_volume_load(volume, DEG_get_bmain(ctx->depsgraph));
294   VolumeGrid *volume_grid = BKE_volume_grid_find(volume, vmmd->grid_name);
295   if (volume_grid == nullptr) {
296     BKE_modifier_set_error(md, "Cannot find '%s' grid", vmmd->grid_name);
297     return create_empty_mesh(input_mesh);
298   }
299 
300   const openvdb::GridBase::ConstPtr grid = BKE_volume_grid_openvdb_for_read(volume, volume_grid);
301 
302   const VolumeGridType grid_type = BKE_volume_grid_type(volume_grid);
303   VolumeToMeshOp to_mesh_op{*grid, *vmmd, *ctx};
304   if (!BKE_volume_grid_type_operation(grid_type, to_mesh_op)) {
305     BKE_modifier_set_error(md, "Expected a scalar grid");
306     return create_empty_mesh(input_mesh);
307   }
308 
309   Mesh *mesh = new_mesh_from_openvdb_data(to_mesh_op.verts, to_mesh_op.tris, to_mesh_op.quads);
310   BKE_mesh_copy_settings(mesh, input_mesh);
311   if (vmmd->flag & VOLUME_TO_MESH_USE_SMOOTH_SHADE) {
312     BKE_mesh_smooth_flag_set(mesh, true);
313   }
314   return mesh;
315 #else
316   UNUSED_VARS(md, ctx);
317   BKE_modifier_set_error(md, "Compiled without OpenVDB");
318   return create_empty_mesh(input_mesh);
319 #endif
320 }
321 
322 ModifierTypeInfo modifierType_VolumeToMesh = {
323     /* name */ "Volume to Mesh",
324     /* structName */ "VolumeToMeshModifierData",
325     /* structSize */ sizeof(VolumeToMeshModifierData),
326     /* srna */ &RNA_VolumeToMeshModifier,
327     /* type */ eModifierTypeType_Constructive,
328     /* flags */ eModifierTypeFlag_AcceptsMesh,
329     /* icon */ ICON_VOLUME_DATA, /* TODO: Use correct icon. */
330 
331     /* copyData */ BKE_modifier_copydata_generic,
332 
333     /* deformVerts */ NULL,
334     /* deformMatrices */ NULL,
335     /* deformVertsEM */ NULL,
336     /* deformMatricesEM */ NULL,
337     /* modifyMesh */ modifyMesh,
338     /* modifyHair */ NULL,
339     /* modifyPointCloud */ NULL,
340     /* modifyVolume */ NULL,
341 
342     /* initData */ initData,
343     /* requiredDataMask */ NULL,
344     /* freeData */ NULL,
345     /* isDisabled */ NULL,
346     /* updateDepsgraph */ updateDepsgraph,
347     /* dependsOnTime */ NULL,
348     /* dependsOnNormals */ NULL,
349     /* foreachIDLink */ foreachIDLink,
350     /* foreachTexLink */ NULL,
351     /* freeRuntimeData */ NULL,
352     /* panelRegister */ panelRegister,
353     /* blendWrite */ NULL,
354     /* blendRead */ NULL,
355 };
356