3D Print Toolbox: Add hollow out #105194
No reviewers
Labels
No Label
Interest
Animation & Rigging
Interest
Blender Cloud
Interest
Collada
Interest
Core
Interest
Documentation
Interest
Eevee & Viewport
Interest
Geometry Nodes
Interest
Grease Pencil
Interest
Import and Export
Interest
Modeling
Interest
Modifiers
Interest
Nodes & Physics
Interest
Pipeline, Assets & IO
Interest
Platforms, Builds, Tests & Devices
Interest
Python API
Interest
Rendering & Cycles
Interest
Sculpt, Paint & Texture
Interest
Translations
Interest
User Interface
Interest
UV Editing
Interest
VFX & Video
Meta
Good First Issue
Meta
Papercut
Module
Add-ons (BF-Blender)
Module
Add-ons (Community)
Platform
Linux
Platform
macOS
Platform
Windows
Priority
High
Priority
Low
Priority
Normal
Priority
Unbreak Now!
Status
Archived
Status
Confirmed
Status
Duplicate
Status
Needs Info from Developers
Status
Needs Information from User
Status
Needs Triage
Status
Resolved
Type
Bug
Type
Design
Type
Known Issue
Type
Patch
Type
Report
Type
To Do
No Milestone
No project
No Assignees
2 Participants
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: blender/blender-addons#105194
Loading…
Reference in New Issue
Block a user
No description provided.
Delete Branch "usfreitas/blender-addons:hollow"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Hollow out an object with a configurable offset. This is useful in
3D printing workflows, for instance, to save material and/or reduce
printing time. The operator is added to the 3d Print Tools addon, in
the transform section.
Let's handle all the issues in parts: first we deal with technical issues and formatting, then UI, naming and defaults.
This one is execution only, next well do UI.
@ -821,0 +852,4 @@
def execute(self, context):
import numpy as np
import pyopenvdb as vdb
Ther should be "gate" conditions at the beginning of the execute method checking for invalid values.
@ -821,0 +855,4 @@
offset = self.offset
resolution = self.resolution
join = self.join
It's better to not create unnecessary local variables, especially when they are rarely used.
@ -821,0 +861,4 @@
# Target object
obj = context.active_object
m = obj.data # mesh
Code style
Here
m = obj.data # mesh
is unnecessary abbreviation and redundant comment:mesh = obj.data
orme = obj.data
would be more appropriate.Getting Mesh
obj.data
will give you base mesh datablock without modifiers and object deformations. In this case we need modifiers and deformations, so instead of base mesh we should get evaluated mesh and apply object transforms:If we do not apply object transforms to mesh and instead just scale object itself, then offset will also be scaled (which is what currently happens).
@ -821,0 +867,4 @@
nverts = len(m.vertices)
ntris = len(m.loop_triangles)
verts = np.zeros(3*nverts, dtype=np.float32)
tris = np.zeros(3*ntris, dtype=np.int32)
Whitespace missing around multiplication operator, same thing below with division.
@ -821,0 +877,4 @@
half_width = max(3.0, math.ceil(abs(offset)/resolution) + 2.0) # half_width has to envelop offset
trans = vdb.Transform()
trans.scale(resolution)
levelset = vdb.FloatGrid.createLevelSetFromPolygons(verts, triangles=tris,
Trailing whitespace and hard to read. Either do a newline for each attribute or keep it single line, it's not that long anyway.
@ -821,0 +882,4 @@
# Generate offset surface
newverts, newquads = levelset.convertToQuads(offset)
polys = [x for x in newquads]
What is happening here? If you need to convert to list just use
newquads = list(newquads)
.@ -821,0 +885,4 @@
polys = [x for x in newquads]
# Instantiate new object in Blender
mesh = bpy.data.meshes.new(m.name + ' offset')
It would be better to name it
mesh_hollow
to avoid shadowing and make intention clearer.@ -821,0 +888,4 @@
mesh = bpy.data.meshes.new(m.name + ' offset')
mesh.from_pydata(newverts, [], polys)
newobj = bpy.data.objects.new(obj.name + ' offset', mesh)
newobj.matrix_world = obj.matrix_world.copy()
We do not need to copy object transforms, it already happens in evaluated mesh.
@ -821,0 +891,4 @@
newobj.matrix_world = obj.matrix_world.copy()
bpy.context.collection.objects.link(newobj)
if not join:
I really think that join feature is not good in this case, since we use evaluated mesh and original object could have a lot of modifiers, like Subd which will freeze/crash Blender if voxel density is too high.
Let's leave it to the user on what they want to do with the result.
Thank you for your feed back!
I very much agree with all the other points. However, on the case of join I have a counter proposal.
If we operate on the evaluated and scaled mesh, joining the generated offset surface with the target object really does not make any sense. But in this case, the offset surface on its own is not very useful for the user either. In order to generate an actually hollow object, they would have to apply modifiers and scale to (possibly a copy of) the target, flip the normals of the target or the generated surface, depending on the sign of the offset, and finally join the two. That is a somewhat complex series of operations that I think could be difficult for many users.
What if we offer the user the option to perform this operations for them? My idea is roughly this:
obj.to_mesh()
, instantiate the mesh with modifiers inbpy.data.meshes
bpy.data.meshes
, otherwise create a new object with it, adjust normals as required, and join it with the offset surfaceInstead of calling this option as "Join", it could be something like "Create hollow copy" or "Offset surface only" for its inverse.
What do you think?
Yeah, let's do
Create Hollow Copy
instead.I'm not getting what you mean by instantiate in
bpy.data.meshes
, we still have to useobj.to_mesh()
to get evaluated mesh.I'm not aware of native
mesh.join(other_mesh)
method, it seems object join operator is the only one available, so we have to usebmesh
for that.Regular hollow result would not require bmesh, we use it only to join 2 meshes together.
It also would be nice to have hollow copy placed beside original object, so something like this:
I think it is better to explain with code. I implemented my idea in the commit I just pushed. It is functional, but I've left the old
join
parameter. I can change its name later. Here is what I did to get the evaluated mesh:Now
mesh_target
is inbpy.data.meshes
. It is then used to create the offset surface. In case the user wants also the hollow object, it can be included in its own object, otherwise it is removed frombpy.data.meshes
. From what I understood fromobj.to_mesh()
, the mesh it produces can not be used in other objects.In this way, we can use the join operator, and
bmesh
and the conversions to/from mesh aren't needed. What do you think about this approach?Some other points:
mesh_target.transform(obj.matrix_world)
will not only apply the scale, but will also set the mesh origin to the global origin. This is most noticeable if the target was translated somewhere before hollowing out. I don't like this effect. I would rather that the origin of the offset surface and the new hollow object stay on the same position of the target object. I'll try to find a way to do that.Your approach is fine, the intent is not as clear with
new_from_object
, but that is semantics, functionality is exactly the same.You cannot use the result of
to_mesh
directly, but you can create a copy of it inbpy.data.meshes
like some.copy()
That is not required, keeping it in place is fine.
You got it a bit wrong, it does not affect origin, it just transforms mesh with object transforms, all new objects have their location in the center of the scene.
That's easy:
It should be called
Hollow Copy
orHollow Duplicate
, the original object is not changed, we're not joining it with anything.Or alternatively strip world matrix of translation component.
I see. Thanks for the info! Now I understand a problem I had with some of my other scripts.
That worked like a charm! Thanks again!
I've updated the branch with this idea. I've also changed the property name, but now I see I did not use your name suggestion, which I think is better. I'll change it later ( again 😞)
Do you have any more feedback/suggestions/comments about this part?
Tool execution is fine, now we need to tackle UI. I'll do it in a separate thread.
@ -821,0 +911,4 @@
context.view_layer.objects.active = obj
bpy.ops.object.join()
if mode_orig == 'EDIT_MESH':
That's unnecessary, just check if in edit mode in
invoke
method and if true switch to object mode, switching back is not needed here.It's a lot, but after that it all done for the exception of one issue which we'll discuss later after UI part is handled.
@ -124,0 +138,4 @@
name = "Create Hollow Copy",
description = "Create a hollow copy of the target object, with applied modifiers and scale",
default = False
)
Duplicating operator settings in the scene is redundant, it is much better to invoke popup dialog with operator settings:
If you want to let user choose defaults, then add-on preferences should be used instead.
This is cool! I did not know about it. I much prefer the dialog, as the operator UI can then be just a button.
Duplication of the operator settings is a pattern that occur often in the 3D-Print Toolbox. I actually learned it by reading the add-on code. The advantage I see with it is that the last used values get saved along with the Blender file when the user saves it. This gives a set of defaults adapted to the objects. If I understand correctly, add-on preferences are global, so it is not possible to have a per file set of add-on preferences. I also like the fact the user does not need to do anything to save the defaults in the duplicated settings case.
My option would be to use the popup dialog and keep the duplicated settings in the scene. If the duplicated setting are a no go, I would just use hard coded defaults. I don't think add-on preferences are worth it here.
@ -821,0 +828,4 @@
bl_idname = "mesh.print3d_hollow"
bl_label = "Create offset surface"
bl_description = "Create offset surface for hollowing objects"
bl_options = {'REGISTER', 'UNDO'}
Hollow
, it is short and widely accepted terminology.Create offset surface
it describes exactly what the tool does.@ -821,0 +847,4 @@
name = "Create Hollow Copy",
description = "Create a hollow copy of the target object, with applied modifiers and scale",
default = False
)
Code style
=
operator for arguments in function/object call.Offset
5
is too much, let's do1
, it's closer to minimum thickness for 3D printed stuff.step=1
, it just makes slider drag a bit more pleasant.Resolution
Voxel Size
it is already used across Blender and is much more descriptive.0.1
and0.5
. I usually do it with0.3
when I don't need the detail.min
is too big, both sculpt remesh and modifier have it at0.0001
step=1
Hollow Copy
use_
,show_
,make_
, etc., whichever is more applicable in given contextmake_hollow_duplicate
Hollow Copy
orHollow Duplicate
, I think duplicate is better, because there is already tool called duplicate, but copy is also fine.Create hollowed out copy of the object
, I don't think we need to clarify scale and modifiers part, it's kind of obvious given the nature of the tool.default = False
default of boolean property is false, you don't need to specify it.Thanks again for your feedback. As for the last time, I agree with most points. I have, however, observations.
Offset
I was rather too liberal with comments in the code, but I think I still managed not to explain an important point.
There are two distinct use cases for this tool. One is the standard hollowing out, where the offset surface is on the inside of the the target object. The other use case is when the offset surface is on the outside of the target. Its application is to generate a thin walled mesh that, after printing, can be used as a mold for the target object to cast other materials in the target form. If the mold is one-shot, that is, it is discarded or destroyed after casing a single part, this technique is sometimes called eggshell molding.
While this other use case is definitely not so common as the first one, I still would like to keep it in the same operator. The application domain is the same (3d printing), and the two use cases share so much code that I think it makes sense to keep them together.
This second use case, let's call it mold making, is the reason why I used a signed offset as a parameter and mentioned the direction in the description. The "Negative -> inwards" has a counter part that means "positive -> outwards", which produces this other effect.
If we keep this mold making in the operator, there need to be some way to differentiate an inwards from an outwards offset surface. I used the sign convention of negative offset to inwards simply because that is the convention of OpenVDB when generating offset surfaces. Another possibility is to use the opposite sign convention, or to use two parameters like the Solidify modifier. Solidify uses one unsigned parameter, Thickness, for the amount of offset, and a signed parameter, Offset, to indicate inwards or outwards, with the convention of negative meaning inwards.
I'm open to the way to indicate that to the user, but I really would like to keep both functionalities in the operator, if possible.
My other point is about the default values for the voxel size. However, it is late here so I comment about that later. I'm also currently traveling on vacation, so don't be alarmed if I don't update as often as before.
I'm not suggesting removing the bi-directional offset functionality, just flip the sign, so positive would mean inward and negative outward, similar to solidify modifier.
The only software that I know of that does negative inward is MeshLab, the rest of them have a separate direction switch toggle.
Have a nice time traveling!
I'm back.
Regarding offset sign, I would rather go with an unsigned thickness parameter and a direction switch toggle, instead of just flipping the sign. I think it would be easier for users to understand.
Regarding the voxel size (this name is really better), I think we should be ware of setting the default too low. I see two reasons for that.
The first is that, when using Blender for 3D printing, the size of the objects in units tend to be larger compared to the default 0.1 of the remesh modifier. At least in my case, where I have my units in millimeters, and my objects easily reach the hundreds. I usually freeze or crash Blender if I'm not careful when adding a remesh modifier, for instance. In our case, if the voxel size is too small compared with the object, the level set creation in OpenVDB can use an excessive amount of memory. Another potential problem is when the voxel size is small compared with the offset. Since the half width of the level set needs to envelop the offset, this can lead to a very large number of active voxels in the level set, again needing a large amount of memory.
The other reason that I see is that a highly detailed offset surface is neither needed nor generally desired for hollowing out objects for printing, IMO. I personally prefer the offset surface to be low poly compared to the target object.
I ran some tests with the Stanford bunny in millimeters. The model is about 150mm long. I've generated an outside surface with a 2mm offset. Using a voxel size of 0.5mm it took a couple of seconds to execute and generated a mesh with more than ten times the number of triangles of the original model. With a voxel size of 0.3, it took 8 seconds to run and produced about 30x more tris than the model. A voxel size of 0.1 crashed my Blender. With 2mm voxel size, it runs instantly and the result has about 25% less tris than the model. For mold making, I think this latter result is still oversampled and could be made with even less tris.
With this in mind, I would suggest using a default of around 1.0 or larger, as a smaller offset could cause the problems above.
Another way of dealing with this question would be to have dynamic defaults. If we could somehow compute a voxel size adapted to the target object and offset value and set the default to this value, this would be a better solution than a hardcoded default. But I have no idea how to do this, or if dynamic defaults are even possible.
I've committed some code. I've tried to make all the suggested changes, with some exceptions:
I've also changed the sequence of operations a bit, and now it can happen that the offset surface have its normals flipped twice. However, I think it is worth it due to the simpler logic and better code legibility.
I would like to thank you again for the time you are committing to this code review. I've learned a lot, and using the tool feels much better. I think code quality also improved significantly.
@ -821,0 +892,4 @@
obj_offset = bpy.data.objects.new(obj.name + ' offset', mesh_offset)
bpy.context.collection.objects.link(obj_offset)
if not self.create_hollow:
It's better to avoid negation, if possible, it just makes harder to follow the logic.
@ -821,0 +898,4 @@
# Translate surface object to target object's position
obj_offset.matrix_world.translation = obj.matrix_world.translation
# This mesh will not be used anymore
bpy.data.meshes.remove(mesh_target)
These comments are redundant, it's obvious why you flip normals, why you move new object to a location of current object, or why you remove mesh (you could name it
mesh_temp
to emphasize intent).@ -821,0 +903,4 @@
# Create a copy of the target object with applied modifiers and scale
obj_hollow = bpy.data.objects.new(obj.name + " hollow", mesh_target)
bpy.context.collection.objects.link(obj_hollow)
if self.offset < 0.0:
This code block is useless, just do
if self.offset > 0.0
@ -821,0 +910,4 @@
# Offset surface is outside, correct normals, see above
mesh_offset.flip_normals()
# Original surface is inside, flip its normals
mesh_target.flip_normals()
Again, you don't need to comment on every line, there is a check above
if create_hollow
and you are usingbpy.data.objects.new
right after it, the code is self-explanatory.Same with offset check.
@ -821,0 +917,4 @@
obj_offset.select_set(True)
obj_hollow.select_set(True)
context.view_layer.objects.active = obj_hollow
bpy.ops.object.join()
Part of this code should be outside
if
block, currently selection changes only when hollow duplicate is created. It should change regardless of that, new object is added to the scene - it should be selected and active.@ -821,0 +920,4 @@
bpy.ops.object.join()
# Translate hollow object to target object's position
obj_hollow.matrix_world.translation = obj.matrix_world.translation
If you find matrix stuff confusing, then you could write it as:
It actually could be like this, but there is a chance that object could have a parent, so using matrix_world ensures we have visible location.
I'm actually pretty comfortable around matrices. I had a good training in linear algebra, and I've been using NumPy way longer than Blender.
I was looking for something like
obj_hollow.matrix_world[:3, 3] = ...
and had not realized thatmathutils.Matrix.translation
is writable until you suggested it. That code line, as it is now, makes perfect sense for me, and I would not have added the comment above it if I were the only one touching this add-on.However, I have very little experience in programing with other people. As I was afraid that what I found easy to understand might not be that for the next one who needs to work in this code, I went trigger happy with the comments 😅
I'll remove this and the other redundant comments.
@ -821,0 +922,4 @@
# Translate hollow object to target object's position
obj_hollow.matrix_world.translation = obj.matrix_world.translation
Double newline only allowed in-between class and function definitions, everything inside function body should be separated by 1 line max.
@ -121,0 +123,4 @@
col.prop(print_3d, "hollow_create")
col.prop(print_3d, "hollow_offset")
col.prop(print_3d, "hollow_resolution")
col.operator("mesh.print3d_hollow", text="Create Offset Surface")
The name of the panel should be changed from
Transform
toEdit
, Hollow tool should be placed first (no additional label needed).Nice to have you back, meanwhile I got the flu and currently coughing my lungs out, but it's getting better.
The work is mostly done, just a couple of things left, and then it's merge ready.
@ -821,0 +841,4 @@
voxel_size: FloatProperty(
name="Voxel size",
description="Size of the voxel used for volume evaluation. Lower values preserve finer details",
default=5.0,
default=1
@ -821,0 +854,4 @@
name="Inside",
description="Offset surface inside of the object",
default=True,
)
I think that simple checkbox called inside is not user friendly, it is fine with on/off options, but with something more complex it's better to make all available options visible right away (even when there is only two options).
Expanded enum called
Offset Direction
with valuesInside
andOutside
fits better here.Also, it is better to group related options together, so place
Offset Direction
right beforeOffset
option.You did not expand enum property so it currently shows as dropdown list.
Add draw method to the operator, right before
execute
method and manually compose UI:If you want to keep presets, then throw
layout.separator()
in there, to keep it visually separated:I did not understand what you meant by "expand". Now I know, and it looks really better. The separator also helps.
@ -821,0 +929,4 @@
print_3d.hollow_offset = self.offset
print_3d.hollow_voxel_size = self.voxel_size
print_3d.make_hollow_duplicate = self.make_hollow_duplicate
print_3d.make_hollow_inside = self.make_hollow_inside
The scene settings have to go, it's hidden behavior and is really convoluted without clear benefit, and for reusing settings it is better to use presets.
Just add
PRESET
value tobl_options
.I'm sorry about you being sick. I hope when you will be already fully recovered when you read this.
This time I implemented all suggestions. At least I hope. Last time a wrong default flew by... 😅
I'm not very happy about the preset. I think it cluttered a bit an interface that was otherwise very neat. But I think it is better to let that in and give the user the option to customize the operator.
Thanks again! This is fun :D
Adding presets was just a suggestion, the operator settings are quite minimal so presets not necessary, you can remove it if you want.
With the separator it looks definitely better.
I think the preset is useful because of my points about the default voxel size. If a user has a setup where this default isn't appropriate, having the possibility to customize it is a plus. I wish I could do that with the remesh modifier.
@ -821,0 +839,4 @@
name="Offset Direction",
description="Where the offset surface is created relative to the object",
default='inside',
)
Enum values are supposed to be in
UPPERCASE
I noticed inconsistent use of double vs single quotation marks, Blender code guidelines recommends: single quotes when using enum values, double quotes everything else.
Sorry, my bad. It should be fixed now.
OK it's ready for merge. There is just one more thing that I wanted to discuss with you.
I noticed there are two reasons hollow gives empty result (object with no mesh):
Would be nice to have some warning, but the problem is – we cannot definitively know why result is empty.
So, warning would be ambiguous:
Make sure target mesh has closed surface and offset value is not greater than max thickness.
What's your thoughts on that?
Good catch. I've mostly ignored failure conditions.
The first reason is due to too large an offset. The other reason is when the mesh does not define a closed space. I think those conditions can only cause problems for internal offset surfaces. External offsets seam to be always possible.
We may be able to differentiate between these conditions. If the mesh is closed, there will be values below zero in the level set. The level set defines a narrow grid close to the mesh and encodes a signed distance field, with negative values meaning inside.The most negative value of this grid should represent the maximum offset possible for inside surfaces.
If the mesh is not closed, OpenVDB will not be able to determine the inside of it, and all values on the grid will be non negative.
That is how I understand it. However, when I tried to get those minimum and maximum values, I still got negative values for open meshes, and I don' t know why. I used the
evalMinMax()
function to get the extrema. If we can get this values reliably, and they are consistent with I understood of how OpenVDB works, we may give a more clear error message.I'll dive into OpenVDB for a while to see if I can fish out something.
Well, I could not find something very informative in the OpenVDB docs. The only thing I could find is that a closed surface is needed.
So I went for some tests. I added
print(levelset.info(5))
after the level set creation (not sure about 5 being required).For open surfaces, the minimum value is small in magnitude. It is slightly positive or close to zero for simple surfaces, but it can be around
-voxel_size
for complex objects. I tried with Suzanne without the eyes. I don't know how negative this value can go, but I suspect it will never be much grater than the voxel size in magnitude for open surfaces.For closed surfaces, the minimum value behaves as I expect. For instance, for an sphere of radius 15, it is a little greater than -15.
Therefore I think we could use this as a way to provide a better error message. Here is suggestion for error reporting logic:
Got empty mesh from OpenVDB:
OUTSIDE
:INSIDE
:What do you think? And how best to report errors to the user? There should be something better than printing on the console, which is what I usually do 😅
In my testing I found that this:
If min value magnitude less then 2 * voxel size
was not a reliable way to test.I successfully got resulted mesh with -0.5991 min value, which is less than 2 * 0.3.
And for voxel size 0.4, min value was at -0.5371.
Other test Suzanne with no eyes, both offset and voxel size 0.1, resulted in failure (mesh was so small it was practically invisible) min value was -0.1.
So even check for
newquads
array will not give us 100% success rate.Unless there is a definitive enough way to tell apart
offset too big
andclosed mesh
cases, I think we should just stick to ambiguous warning. Otherwise, we risk misinforming the user.For reporting we'll use
report
method, error code makes sure that popup window will appear.We'll skip check for outside direction as I couldn't make it fail, as much as I tried.
Agreed. I'll dig a little more in OpenVDB, mainly because I want a method to identify when a mesh has a hole, but for now, I agree that the ambiguous error is better.
I don't see how it could fail. If we find a failure case later, we can always add a check for that.
It just occurred to me that an outside offset surface could be a nice alternative for the solidify modifier in some cases. I can't wait for the grids to land in Geometry Nodes :D
OK then, it is time for merge.
WIP: 3D Print Toolbox: Add hollow outto 3D Print Toolbox: Add hollow out