Print3D: Cleanup code

Remove redundant code and workarounds, better variable names, cleanup style.
This commit is contained in:
Mikhail Rachinskiy
2019-09-20 18:50:10 +04:00
parent 4fc5558f68
commit a658a1053d
4 changed files with 46 additions and 57 deletions

View File

@ -81,40 +81,47 @@ class Print3D_Scene_Props(PropertyGroup):
export_path: StringProperty( export_path: StringProperty(
name="Export Directory", name="Export Directory",
description="Path to directory where the files are created", description="Path to directory where the files are created",
default="//", maxlen=1024, subtype="DIR_PATH", default="//",
maxlen=1024,
subtype="DIR_PATH",
) )
thickness_min: FloatProperty( thickness_min: FloatProperty(
name="Thickness", name="Thickness",
description="Minimum thickness", description="Minimum thickness",
subtype='DISTANCE', subtype='DISTANCE',
default=0.001, # 1mm default=0.001, # 1mm
min=0.0, max=10.0, min=0.0,
max=10.0,
) )
threshold_zero: FloatProperty( threshold_zero: FloatProperty(
name="Threshold", name="Threshold",
description="Limit for checking zero area/length", description="Limit for checking zero area/length",
default=0.0001, default=0.0001,
precision=5, precision=5,
min=0.0, max=0.2, min=0.0,
max=0.2,
) )
angle_distort: FloatProperty( angle_distort: FloatProperty(
name="Angle", name="Angle",
description="Limit for checking distorted faces", description="Limit for checking distorted faces",
subtype='ANGLE', subtype='ANGLE',
default=math.radians(45.0), default=math.radians(45.0),
min=0.0, max=math.radians(180.0), min=0.0,
max=math.radians(180.0),
) )
angle_sharp: FloatProperty( angle_sharp: FloatProperty(
name="Angle", name="Angle",
subtype='ANGLE', subtype='ANGLE',
default=math.radians(160.0), default=math.radians(160.0),
min=0.0, max=math.radians(180.0), min=0.0,
max=math.radians(180.0),
) )
angle_overhang: FloatProperty( angle_overhang: FloatProperty(
name="Angle", name="Angle",
subtype='ANGLE', subtype='ANGLE',
default=math.radians(45.0), default=math.radians(45.0),
min=0.0, max=math.radians(90.0), min=0.0,
max=math.radians(90.0),
) )

View File

@ -44,6 +44,7 @@ def image_copy_guess(filepath, objects):
imagepath_dst = filepath_noext + ext imagepath_dst = filepath_noext + ext
print(f"copying texture: {imagepath!r} -> {imagepath_dst!r}") print(f"copying texture: {imagepath!r} -> {imagepath_dst!r}")
try: try:
shutil.copy(imagepath, imagepath_dst) shutil.copy(imagepath, imagepath_dst)
except: except:
@ -181,7 +182,6 @@ def write_mesh(context, info, report_cb):
collection.objects.unlink(obj) collection.objects.unlink(obj)
bpy.data.objects.remove(obj) bpy.data.objects.remove(obj)
bpy.data.meshes.remove(mesh) bpy.data.meshes.remove(mesh)
del obj_tmp, obj, mesh
# restore context # restore context
for ob in context_backup["selected_objects"]: for ob in context_backup["selected_objects"]:
@ -195,6 +195,6 @@ def write_mesh(context, info, report_cb):
if report_cb is not None: if report_cb is not None:
report_cb({'INFO'}, f"Exported: {filepath!r}") report_cb({'INFO'}, f"Exported: {filepath!r}")
return True return True
else:
info.append((f"{os.path.basename(filepath)!r} fail", None)) info.append((f"{os.path.basename(filepath)!r} fail", None))
return False return False

View File

@ -36,7 +36,6 @@ def bmesh_copy_from_object(obj, transform=True, triangulate=True, apply_modifier
bm = bmesh.new() bm = bmesh.new()
bm.from_mesh(me) bm.from_mesh(me)
obj_eval.to_mesh_clear() obj_eval.to_mesh_clear()
del bpy
else: else:
me = obj.data me = obj.data
if obj.mode == 'EDIT': if obj.mode == 'EDIT':
@ -79,10 +78,7 @@ def bmesh_to_object(obj, bm):
bmesh.update_edit_mesh(me, True) bmesh.update_edit_mesh(me, True)
else: else:
bm.to_mesh(me) bm.to_mesh(me)
me.update()
# grr... cause an update
if me.vertices:
me.vertices[0].co[0] = me.vertices[0].co[0]
def bmesh_calc_area(bm): def bmesh_calc_area(bm):
@ -109,11 +105,11 @@ def bmesh_check_self_intersect_object(obj):
def bmesh_face_points_random(f, num_points=1, margin=0.05): def bmesh_face_points_random(f, num_points=1, margin=0.05):
import random import random
from random import uniform from random import uniform
uniform_args = 0.0 + margin, 1.0 - margin
# for pradictable results # for pradictable results
random.seed(f.index) random.seed(f.index)
uniform_args = 0.0 + margin, 1.0 - margin
vecs = [v.co for v in f.verts] vecs = [v.co for v in f.verts]
for i in range(num_points): for i in range(num_points):
@ -150,12 +146,10 @@ def bmesh_check_thick_object(obj, thickness):
# Create a real mesh (lame!) # Create a real mesh (lame!)
context = bpy.context context = bpy.context
layer = context.view_layer layer = context.view_layer
layer_collection = context.layer_collection or layer.active_layer_collection scene_collection = context.layer_collection.collection
scene_collection = layer_collection.collection
me_tmp = bpy.data.meshes.new(name="~temp~") me_tmp = bpy.data.meshes.new(name="~temp~")
bm.to_mesh(me_tmp) bm.to_mesh(me_tmp)
# bm.free() # delay free
obj_tmp = bpy.data.objects.new(name=me_tmp.name, object_data=me_tmp) obj_tmp = bpy.data.objects.new(name=me_tmp.name, object_data=me_tmp)
scene_collection.objects.link(obj_tmp) scene_collection.objects.link(obj_tmp)
@ -187,7 +181,7 @@ def bmesh_check_thick_object(obj, thickness):
f_org_index = face_index_map_org[f_org] f_org_index = face_index_map_org[f_org]
faces_error.add(f_org_index) faces_error.add(f_org_index)
bm.free() # finished with bm bm.free()
scene_collection.objects.unlink(obj_tmp) scene_collection.objects.unlink(obj_tmp)
bpy.data.objects.remove(obj_tmp) bpy.data.objects.remove(obj_tmp)
@ -213,19 +207,17 @@ def object_merge(context, objects):
scene = context.scene scene = context.scene
layer = context.view_layer layer = context.view_layer
layer_collection = context.layer_collection or layer.active_layer_collection scene_collection = context.layer_collection.collection
scene_collection = layer_collection.collection
# deselect all # deselect all
for obj in scene.objects: for obj in scene.objects:
obj.select_set(False) obj.select_set(False)
# add empty object # add empty object
mesh_base = bpy.data.meshes.new(name="~tmp~") mesh_tmp = bpy.data.meshes.new(name="~tmp~")
obj_base = bpy.data.objects.new(name="~tmp~", object_data=mesh_base) obj_tmp = bpy.data.objects.new(name="~tmp~", object_data=mesh_tmp)
scene_collection.objects.link(obj_base) scene_collection.objects.link(obj_tmp)
layer.objects.active = obj_base obj_tmp.select_set(True)
obj_base.select_set(True)
depsgraph = context.evaluated_depsgraph_get() depsgraph = context.evaluated_depsgraph_get()
@ -244,22 +236,20 @@ def object_merge(context, objects):
# join into base mesh # join into base mesh
obj_new = bpy.data.objects.new(name="~tmp-new~", object_data=mesh_new) obj_new = bpy.data.objects.new(name="~tmp-new~", object_data=mesh_new)
base_new = scene_collection.objects.link(obj_new) scene_collection.objects.link(obj_new)
obj_new.matrix_world = obj.matrix_world obj_new.matrix_world = obj.matrix_world
fake_context = context.copy() override = context.copy()
fake_context["active_object"] = obj_base override["active_object"] = obj_tmp
fake_context["selected_editable_objects"] = [obj_base, obj_new] override["selected_editable_objects"] = [obj_tmp, obj_new]
bpy.ops.object.join(fake_context) bpy.ops.object.join(override)
del base_new, obj_new
obj_eval.to_mesh_clear() obj_eval.to_mesh_clear()
layer.update() layer.update()
# return new object return obj_tmp
return obj_base
def face_is_distorted(ele, angle_distort): def face_is_distorted(ele, angle_distort):

View File

@ -44,10 +44,10 @@ def clean_float(text):
text = head + tail text = head + tail
return text return text
# --------- # ---------
# Mesh Info # Mesh Info
class MESH_OT_Print3D_Info_Volume(Operator): class MESH_OT_Print3D_Info_Volume(Operator):
"""Report the volume of the active mesh""" """Report the volume of the active mesh"""
bl_idname = "mesh.print3d_info_volume" bl_idname = "mesh.print3d_info_volume"
@ -64,11 +64,11 @@ class MESH_OT_Print3D_Info_Volume(Operator):
bm.free() bm.free()
if unit.system == 'METRIC': if unit.system == 'METRIC':
volume = volume * (scale ** 3.0) / (0.01 ** 3.0) volume_cm = volume * (scale ** 3.0) / (0.01 ** 3.0)
volume_fmt = clean_float(f"{volume:.4f}") + " cm" volume_fmt = "{} cm".format(clean_float(f"{volume_cm:.4f}"))
elif unit.system == 'IMPERIAL': elif unit.system == 'IMPERIAL':
volume = volume * (scale ** 3.0) / (0.0254 ** 3.0) volume_inch = volume * (scale ** 3.0) / (0.0254 ** 3.0)
volume_fmt = clean_float(f"{volume:.4f}") + ' "' volume_fmt = '{} "'.format(clean_float(f"{volume_inch:.4f}"))
else: else:
volume_fmt = clean_float(f"{volume:.8f}") volume_fmt = clean_float(f"{volume:.8f}")
@ -93,11 +93,11 @@ class MESH_OT_Print3D_Info_Area(Operator):
bm.free() bm.free()
if unit.system == 'METRIC': if unit.system == 'METRIC':
area = area * (scale ** 2.0) / (0.01 ** 2.0) area_cm = area * (scale ** 2.0) / (0.01 ** 2.0)
area_fmt = clean_float(f"{area:.4f}") + " cm" area_fmt = "{} cm".format(clean_float(f"{area_cm:.4f}"))
elif unit.system == 'IMPERIAL': elif unit.system == 'IMPERIAL':
area = area * (scale ** 2.0) / (0.0254 ** 2.0) area_inch = area * (scale ** 2.0) / (0.0254 ** 2.0)
area_fmt = clean_float(f"{area:.4f}") + ' "' area_fmt = '{} "'.format(clean_float(f"{area_inch:.4f}"))
else: else:
area_fmt = clean_float(f"{area:.8f}") area_fmt = clean_float(f"{area:.8f}")
@ -392,8 +392,8 @@ class MESH_OT_Print3D_Clean_Isolated(Operator):
if change: if change:
mesh_helpers.bmesh_to_object(obj, bm) mesh_helpers.bmesh_to_object(obj, bm)
return {'FINISHED'} return {'FINISHED'}
else:
return {'CANCELLED'} return {'CANCELLED'}
class MESH_OT_Print3D_Clean_Distorted(Operator): class MESH_OT_Print3D_Clean_Distorted(Operator):
@ -616,9 +616,6 @@ class MESH_OT_Print3D_Select_Report(Operator):
# possible arrays are out of sync # possible arrays are out of sync
self.report({'WARNING'}, "Report is out of date, re-run check") self.report({'WARNING'}, "Report is out of date, re-run check")
# cool, but in fact annoying
# bpy.ops.view3d.view_selected(use_all_regions=False)
return {'FINISHED'} return {'FINISHED'}
@ -627,13 +624,7 @@ class MESH_OT_Print3D_Select_Report(Operator):
def _scale(scale, report=None, report_suffix=""): def _scale(scale, report=None, report_suffix=""):
if scale != 1.0: if scale != 1.0:
bpy.ops.transform.resize( bpy.ops.transform.resize(value=(scale,) * 3)
value=(scale,) * 3,
mirror=False,
use_proportional_edit=False,
snap=False,
texture_space=False,
)
if report is not None: if report is not None:
scale_fmt = clean_float(f"{scale:.6f}") scale_fmt = clean_float(f"{scale:.6f}")
report({'INFO'}, f"Scaled by {scale_fmt}{report_suffix}") report({'INFO'}, f"Scaled by {scale_fmt}{report_suffix}")
@ -651,7 +642,8 @@ class MESH_OT_Print3D_Scale_To_Volume(Operator):
volume: FloatProperty( volume: FloatProperty(
name="Volume", name="Volume",
unit='VOLUME', unit='VOLUME',
min=0.0, max=100000.0, min=0.0,
max=100000.0,
) )
def execute(self, context): def execute(self, context):