Skip to content

Transform your 3D texturing workflow with the power of generative AI, directly within Blender!

add lato.2 low-poly remeshing and flood-fill make solid

sakalond4590c739283e
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index a61ea11..b5d883a 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -132,6 +132,7 @@ classes = [
StableGenApplyBoneDisplay,
StableGenAutoRigSelectedMesh,
StableGenLocalPostProcess,
+ StableGenLato2Remesh,
TRELLIS2_OT_BatchSelectFolder,
TRELLIS2_OT_BatchGenerate,
TRELLIS2_OT_BatchCancel,
diff --git a/stablegen/core/callbacks.py b/stablegen/core/callbacks.py
index 3e810fc..13d286f 100644
--- a/stablegen/core/callbacks.py
+++ b/stablegen/core/callbacks.py
@@ -18,6 +18,8 @@ from .state import (
from .server_api import (
check_pbr_available,
check_server_availability,
+ check_meshtools_available,
+ apply_meshtools_available,
check_skintokens_autorig_available,
check_trellis2_available,
)
@@ -277,10 +279,12 @@ def update_combined(self, context):
result['trellis2'] = check_trellis2_available(server_address, timeout=api_timeout)
result['pbr'] = check_pbr_available(server_address, timeout=api_timeout)
result['skintokens'] = check_skintokens_autorig_available(server_address, timeout=api_timeout)
+ result['meshtools'] = check_meshtools_available(server_address, timeout=api_timeout)
else:
result['trellis2'] = False
result['pbr'] = False
result['skintokens'] = False
+ result['meshtools'] = {}
return result
def _on_done(result):
@@ -293,6 +297,7 @@ def update_combined(self, context):
bpy.context.scene.trellis2_available = result.get('trellis2', False)
bpy.context.scene.pbr_nodes_available = result.get('pbr', False)
bpy.context.scene.skintokens_autorig_available = result.get('skintokens', False)
+ apply_meshtools_available(bpy.context.scene, result.get('meshtools'))
if not result.get('online', False):
print("[StableGen] ComfyUI server is not reachable.")
diff --git a/stablegen/core/load_handlers.py b/stablegen/core/load_handlers.py
index 52471a6..96d046f 100644
--- a/stablegen/core/load_handlers.py
+++ b/stablegen/core/load_handlers.py
@@ -233,6 +233,8 @@ def load_handler(dummy, _second=None, file_loaded=True):
if server_address:
from .server_api import (
check_pbr_available,
+ check_meshtools_available,
+ apply_meshtools_available,
check_skintokens_autorig_available,
check_trellis2_available,
)
@@ -245,6 +247,7 @@ def load_handler(dummy, _second=None, file_loaded=True):
result['trellis2'] = check_trellis2_available(server_address, timeout=_timeout)
result['pbr'] = check_pbr_available(server_address, timeout=_timeout)
result['skintokens'] = check_skintokens_autorig_available(server_address, timeout=_timeout)
+ result['meshtools'] = check_meshtools_available(server_address, timeout=_timeout)
return result
def _apply_node_result(result):
@@ -254,5 +257,6 @@ def load_handler(dummy, _second=None, file_loaded=True):
bpy.context.scene.trellis2_available = result.get('trellis2', False)
bpy.context.scene.pbr_nodes_available = result.get('pbr', False)
bpy.context.scene.skintokens_autorig_available = result.get('skintokens', False)
+ apply_meshtools_available(bpy.context.scene, result.get('meshtools'))
_state._run_async(_check_nodes, _apply_node_result)
diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.py
index 4b38b48..ab7fe71 100644
--- a/stablegen/core/preferences.py
+++ b/stablegen/core/preferences.py
@@ -19,6 +19,8 @@ from .server_api import (
_fetch_api_list,
check_pbr_available,
check_server_availability,
+ check_meshtools_available,
+ apply_meshtools_available,
check_skintokens_autorig_available,
check_trellis2_available,
)
@@ -407,10 +409,12 @@ class CheckServerStatus(bpy.types.Operator):
result['trellis2'] = check_trellis2_available(server_addr, timeout=api_timeout)
result['pbr'] = check_pbr_available(server_addr, timeout=api_timeout)
result['skintokens'] = check_skintokens_autorig_available(server_addr, timeout=api_timeout)
+ result['meshtools'] = check_meshtools_available(server_addr, timeout=api_timeout)
else:
result['trellis2'] = False
result['pbr'] = False
result['skintokens'] = False
+ result['meshtools'] = {}
return result
def _on_done(result):
@@ -425,6 +429,7 @@ class CheckServerStatus(bpy.types.Operator):
bpy.context.scene.trellis2_available = result.get('trellis2', False)
bpy.context.scene.pbr_nodes_available = result.get('pbr', False)
bpy.context.scene.skintokens_autorig_available = result.get('skintokens', False)
+ apply_meshtools_available(bpy.context.scene, result.get('meshtools'))
if result.get('online', False):
print(f"[StableGen] ComfyUI server is online at {server_addr}.")
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index eda8e46..8808223 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -1491,6 +1491,28 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
description="Whether the StableGen SkinTokens auto-rig node is available on the ComfyUI server (auto-detected)",
default=False
)
+ # ── Mesh tools (ComfyUI-LATO2) ──────────────────────────────────────
+ bpy.types.Scene.meshtools_lato2_available = bpy.props.BoolProperty(
+ name="LATO.2 Available",
+ description="Whether ComfyUI-LATO2's LATO2Remesh node is available on the ComfyUI server (auto-detected)",
+ default=False
+ )
+ bpy.types.Scene.show_meshtools = bpy.props.BoolProperty(
+ name="Show Mesh Tools", description="Toggle the mesh tools section", default=False
+ )
+ bpy.types.Scene.meshtools_hide_source = bpy.props.BoolProperty(
+ name="Hide Source",
+ description="Hide the source object after a remeshed or edited copy is imported",
+ default=True
+ )
+ bpy.types.Scene.meshtools_lato2_vertices = bpy.props.IntProperty(
+ name="Vertices",
+ description="Target vertex count of the low-poly mesh (LATO.2 generates 200 to 5000 vertices)",
+ default=2000, min=200, max=5000, step=100
+ )
+ bpy.types.Scene.meshtools_lato2_seed = bpy.props.IntProperty(
+ name="Seed", description="Random seed for LATO.2", default=42, min=0
+ )
bpy.types.Scene.show_trellis2_params = bpy.props.BoolProperty(
name="Show TRELLIS.2 Section", description="Toggle TRELLIS.2 Image-to-3D section", default=False
)
@@ -1720,6 +1742,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
('none', "None (Trimesh)", "Keep triangles (raw or decimated) - no retopology solver"),
('qdc', "QDC (Server)", "Quad Dual Contouring - uniform server-side quad remeshing (handles both decimation and remeshing natively)"),
('quadriflow', "Quadriflow (Local) [Experimental]", "Curvature-adaptive local quad retopology in Blender (Zero-dependency). Note: Experimental, might produce artifacts"),
+ ('lato2', "LATO.2 Low-Poly (Server)", "Rebuild the mesh with generated low-poly topology (200 to 5000 vertices) on the ComfyUI server; needs the LATO.2 package (ComfyUI-LATO2). Shape-only and diffusion texturing, not native TRELLIS.2 textures"),
],
default='qdc',
update=update_parameters
@@ -1734,6 +1757,14 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
description="Apply watertight capping and hollowing to delete internal geometry, saving UV and texture space",
default=False, update=update_parameters
)
+ bpy.types.Scene.trellis2_solidify_seal_bottom = bpy.props.BoolProperty(
+ name="Close Bottom Openings",
+ description=(
+ "Treat the object's underside as closed while finding interior geometry, so a hollow mesh open at "
+ "the bottom (outer and inner shell joined at the rim) becomes solid with a capped bottom"
+ ),
+ default=True, update=update_parameters
+ )
bpy.types.Scene.trellis2_autorig_enabled = bpy.props.BoolProperty(
name="Auto-Rig",
description="Run the generated GLB through the StableGen SkinTokens ComfyUI node before importing it",
@@ -2344,7 +2375,7 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'trellis2_texture_size', 'trellis2_decimation', 'trellis2_remesh',
'trellis2_decimate_method', 'trellis2_remesh_method',
'trellis2_post_processing_enabled',
- 'trellis2_solidify',
+ 'trellis2_solidify', 'trellis2_solidify_seal_bottom',
'trellis2_autorig_enabled', 'trellis2_autorig_use_transfer',
'trellis2_autorig_use_skeleton', 'trellis2_autorig_use_postprocess',
'trellis2_autorig_cleanup_cross_limb_weights',
@@ -2356,6 +2387,8 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'trellis2_autorig_hf_path',
'trellis2_auto_lighting',
'trellis2_skip_texture', 'trellis2_bg_removal', 'trellis2_background_color',
+ 'meshtools_lato2_available', 'show_meshtools', 'meshtools_hide_source', 'meshtools_lato2_vertices',
+ 'meshtools_lato2_seed',
]
for prop in trellis2_props:
if hasattr(bpy.types.Scene, prop):
diff --git a/stablegen/core/server_api.py b/stablegen/core/server_api.py
index 1db4250..4e87df0 100644
--- a/stablegen/core/server_api.py
+++ b/stablegen/core/server_api.py
@@ -140,6 +140,33 @@ def check_skintokens_autorig_available(server_address, timeout=1.0):
return False
+MESHTOOLS_NODES = {
+ 'lato2': 'LATO2Remesh', # ComfyUI-LATO2
+}
+
+
+def check_meshtools_available(server_address, timeout=1.0):
+ """Which mesh tool nodes ComfyUI has: {'lato2': bool}."""
+ found = {tool: False for tool in MESHTOOLS_NODES}
+ if not server_address:
+ return found
+ for tool, node_class in MESHTOOLS_NODES.items():
+ try:
+ response = requests.get(f"http://{server_address}/object_info/{node_class}", timeout=timeout)
+ found[tool] = response.status_code == 200 and node_class in response.json()
+ except Exception as e:
+ print(f"[MeshTools] Auto-detect of {node_class} failed: {e}")
+ break
+ print(f"[MeshTools] Auto-detect: {', '.join(t for t, ok in found.items() if ok) or 'no nodes'} found.")
+ return found
+
+
+def apply_meshtools_available(scene, found):
+ """Store a check_meshtools_available() result on the scene."""
+ found = found or {}
+ scene.meshtools_lato2_available = bool(found.get('lato2', False))
+
+
def fetch_node_info(server_address, node_class, timeout=1.0):
"""Return a node's ``/object_info`` entry, or ``None`` if it is not installed."""
if not server_address:
diff --git a/stablegen/mesh_gen/meshtools.py b/stablegen/mesh_gen/meshtools.py
new file mode 100644
index 0000000..87e8a9f
--- /dev/null
+++ b/stablegen/mesh_gen/meshtools.py
@@ -0,0 +1,287 @@
+"""Mesh tools that run on the ComfyUI server: LATO.2 low-poly remeshing through the ComfyUI-LATO2 node
+(github.com/sakalond/ComfyUI-LATO2, installed by the ComfyUI setup's LATO.2 package).
+
+The operator exports what it needs, runs one node in a background thread (WorkflowManager.generate_meshtools_file)
+and imports the GLB that comes back as new objects, keeping the source.
+"""
+
+import os
+import tempfile
+import threading
+import traceback
+from datetime import datetime
+
+import bpy # pylint: disable=import-error
+
+from ..core import get_addon_prefs
+from ..utils import get_generation_dirs, sg_modal_active
+
+
+def _save_dir(context):
+ gen_dirs = get_generation_dirs(context)
+ prefs = get_addon_prefs(context)
+ folder = bpy.path.abspath(gen_dirs.get("revision", "") or (prefs.output_dir if prefs else "") or "")
+ if not os.path.isabs(folder): # no output folder set: not next to wherever Blender runs from
+ folder = tempfile.gettempdir()
+ folder = os.path.join(folder, "meshtools")
+ os.makedirs(folder, exist_ok=True)
+ return folder
+
+
+def _selected_meshes(context):
+ return [obj for obj in context.selected_objects if obj.type == 'MESH']
+
+
+def lato2_missing():
+ """(why the server has no LATO2Remesh node, an operator that helps, its label, its properties). A ComfyUI loads
+ custom nodes only when it starts: one running since before LATO.2 was installed needs a restart."""
+ from ..setup import packages, runtime
+ p = runtime.prefs()
+ if not runtime.local_mode(p):
+ return ("LATO.2 isn't on the server: install it there with installer.py --packages lato2",
+ "stablegen.comfy_copy_install_command", "Copy the install command", {"tags": "lato2"})
+ folder = runtime.comfy_folder(p)
+ state = packages.row_state(("lato2",), runtime.report(folder))["state"] if folder is not None else "missing"
+ if state != "installed":
+ return ("LATO.2 isn't installed in your ComfyUI", "stablegen.open_setup", "Install it in the ComfyUI setup", {})
+ if runtime.comfy().owned:
+ return ("LATO.2 is installed; ComfyUI started before it, so restart ComfyUI to load it",
+ "stablegen.comfy_restart", "Restart ComfyUI", {})
+ return ("LATO.2 is installed; your ComfyUI started before it, so restart it to load LATO.2 (StableGen didn't "
+ "start it, so it won't restart it)", "stablegen.check_server_status", "Check again", {})
+
+
+def _export_glb(context, objects, path, materials=True, geometry_only=False):
+ """Export the objects (world space, modifiers applied) to one GLB, then restore the selection. geometry_only
+ leaves out normals, UVs and colors, so the exporter splits no vertex at a seam or sharp edge and the mesh stays
+ welded (edge-collapse decimation would open cracks there)."""
+ previous_active = context.view_layer.objects.active
+ previous = list(context.selected_objects)
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in objects:
+ obj.select_set(True)
+ context.view_layer.objects.active = objects[0]
+ options = dict(
+ filepath=path, export_format='GLB', use_selection=True, export_apply=True,
+ export_materials='EXPORT' if materials else 'NONE', export_animations=False,
+ export_skins=False, export_morph=False,
+ )
+ if geometry_only:
+ available = bpy.ops.export_scene.gltf.get_rna_type().properties.keys()
+ options.update((name, value) for name, value in (
+ ('export_normals', False), ('export_texcoords', False), ('export_vertex_color', 'NONE'),
+ ('export_colors', False), ('export_attributes', False)) if name in available)
+ try:
+ bpy.ops.export_scene.gltf(**options)
+ finally:
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in previous:
+ if context.scene.objects.get(obj.name):
+ obj.select_set(True)
+ if previous_active and context.scene.objects.get(previous_active.name):
+ context.view_layer.objects.active = previous_active
+ if not os.path.isfile(path) or os.path.getsize(path) == 0:
+ raise RuntimeError("the GLB export wrote nothing")
+
+
+def _import_glb(context, path, collection_name):
+ """Import a GLB into a new collection; returns the imported objects."""
+ collection = bpy.data.collections.new(collection_name)
+ context.scene.collection.children.link(collection)
+ layer_collection = context.view_layer.layer_collection.children[collection.name]
+ previous = context.view_layer.active_layer_collection
+ context.view_layer.active_layer_collection = layer_collection
+ try:
+ bpy.ops.import_scene.gltf(filepath=path)
+ finally:
+ context.view_layer.active_layer_collection = previous
+ imported = list(collection.all_objects)
+ for obj in imported:
+ obj["sg_generated"] = True
+ return imported
+
+
+class _MeshToolOperator(bpy.types.Operator):
+ """Shared modal flow: prepare inputs, run the node in a thread, import the result."""
+
+ _is_running = False
+ _cancelled = False
+ _active_ws = None
+ _PHASE_WEIGHTS = (10.0, 80.0, 10.0)
+ _total_phases = 3
+ _available_prop = ""
+ _node_label = ""
+ _class_type = ""
+
+ @classmethod
+ def poll(cls, context):
+ if cls._is_running:
+ return True
+ prefs = get_addon_prefs(context)
+ if prefs is None or not prefs.server_address or not prefs.server_online:
+ cls.poll_message_set("ComfyUI server is not connected")
+ return False
+ if not getattr(context.scene, cls._available_prop, False):
+ cls.poll_message_set(lato2_missing()[0])
+ return False
+ if sg_modal_active(context):
+ cls.poll_message_set("Another operation is in progress")
+ return False
+ return cls._poll_inputs(context)
+
+ @classmethod
+ def _poll_inputs(cls, context):
+ return True
+
+ def _set_pipeline_phase(self, phase, label, percent, detail=None):
+ phase = max(1, min(int(phase), self._total_phases))
+ percent = max(0.0, min(float(percent), 100.0))
+ overall = sum(self._PHASE_WEIGHTS[:phase - 1]) + self._PHASE_WEIGHTS[phase - 1] * percent / 100.0
+ self._overall_progress = max(self._overall_progress, overall)
+ self._overall_stage = f"{self._node_label}: {label}"
+ self._phase_progress = percent
+ self._phase_stage = detail or label
+ self._progress = self._overall_progress
+ self._stage = self._phase_stage
+
+ def _prepare(self, context, work_dir):
+ """(inputs, uploads) for the node; raises RuntimeError with a message for the user."""
+ raise NotImplementedError
+
+ def _finish(self, context, glb_path):
+ """Import the result; returns a short report."""
+ raise NotImplementedError
+
+ def execute(self, context):
+ cls = type(self)
+ if cls._is_running:
+ cls._cancelled = True
+ ws = cls._active_ws
+ if ws is not None:
+ try:
+ ws.close()
+ except Exception:
+ pass
+ self.report({'INFO'}, f"Cancelling {self._node_label}...")
+ return {'FINISHED'}
+ try:
+ self._work_dir = _save_dir(context)
+ inputs, uploads = self._prepare(context, self._work_dir)
+ except Exception as exc:
+ traceback.print_exc()
+ self.report({'ERROR'}, f"{self._node_label}: {exc}")
+ return {'CANCELLED'}
+
+ cls._is_running = True
+ cls._cancelled = False
+ self._error = None
+ self._result = None
+ self._overall_progress = 0.0
+ self._overall_stage = f"{self._node_label}: Queued"
+ self._phase_progress = 0.0
+ self._phase_stage = "Preparing"
+ self._progress = 0.0
+ self._stage = "Preparing"
+ from ..workflows import WorkflowManager
+ self.workflow_manager = WorkflowManager(self)
+ self._thread = threading.Thread(target=self._run, args=(context, inputs, uploads), daemon=True)
+ self._thread.start()
+ context.window_manager.modal_handler_add(self)
+ self._timer = context.window_manager.event_timer_add(0.5, window=context.window)
+ self.report({'INFO'}, f"{self._node_label} started")
+ return {'RUNNING_MODAL'}
+
+ def _run(self, context, inputs, uploads):
+ try:
+ result = self.workflow_manager.generate_meshtools_file(
+ context, self._class_type, inputs, uploads=uploads, label=self._node_label)
+ if isinstance(result, dict) and "error" in result:
+ self._error = result["error"]
+ else:
+ self._result = result
+ except Exception as exc:
+ self._error = str(exc)
+ traceback.print_exc()
+
+ def modal(self, context, event):
+ if event.type != 'TIMER':
+ return {'PASS_THROUGH'}
+ for area in context.screen.areas:
+ area.tag_redraw()
+ if self._thread and self._thread.is_alive():
+ return {'RUNNING_MODAL'}
+ context.window_manager.event_timer_remove(self._timer)
+ cls = type(self)
+ was_cancelled = cls._cancelled
+ cls._is_running = False
+ cls._cancelled = False
+ cls._active_ws = None
+ if was_cancelled or self._error == "cancelled":
+ self.report({'INFO'}, f"{self._node_label} cancelled")
+ return {'FINISHED'}
+ if self._error or not self._result:
+ self.report({'ERROR'}, f"{self._node_label} failed: {self._error or 'no GLB was returned'}")
+ return {'CANCELLED'}
+ try:
+ stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ glb_path = os.path.join(self._work_dir, f"{self._class_type}_{stamp}.glb")
+ with open(glb_path, 'wb') as handle:
+ handle.write(self._result)
+ message = self._finish(context, glb_path)
+ self.report({'INFO'}, message)
+ return {'FINISHED'}
+ except Exception as exc:
+ traceback.print_exc()
+ self.report({'ERROR'}, f"{self._node_label}: importing the result failed: {exc}")
+ return {'CANCELLED'}
+
+
+class StableGenLato2Remesh(_MeshToolOperator):
+ """Re-mesh the selected mesh into a low-poly mesh with generated topology (LATO.2 on the ComfyUI server)."""
+
+ bl_idname = "object.stablegen_lato2_remesh"
+ bl_label = "Low-Poly Remesh (LATO.2)"
+ bl_description = (
+ "Export the selected mesh, rebuild it on the ComfyUI server as a low-poly mesh with generated topology "
+ "(LATO.2, 200 to 5000 vertices) and import the result next to the source"
+ )
+ bl_options = {'REGISTER', 'UNDO'}
+ _is_running = False
+ _cancelled = False
+ _active_ws = None
+ _available_prop = "meshtools_lato2_available"
+ _node_label = "LATO.2 Remesh"
+ _class_type = "LATO2Remesh"
+
+ @classmethod
+ def _poll_inputs(cls, context):
+ if not _selected_meshes(context):
+ cls.poll_message_set("Select a mesh object")
+ return False
+ return True
+
+ def _prepare(self, context, work_dir):
+ scene = context.scene
+ self._sources = _selected_meshes(context)
+ path = os.path.join(work_dir, f"lato2_source_{datetime.now():%H%M%S}.glb")
+ _export_glb(context, self._sources, path, materials=False)
+ inputs = {
+ "vertex_count": int(scene.meshtools_lato2_vertices),
+ "seed": int(scene.meshtools_lato2_seed),
+ "filename_prefix": "lato2",
+ }
+ return inputs, {"input_path": path}
+
+ def _finish(self, context, glb_path):
+ name = self._sources[0].name
+ imported = _import_glb(context, glb_path, f"{name}_LATO2")
+ meshes = [obj for obj in imported if obj.type == 'MESH']
+ for obj in meshes:
+ obj.name = f"{name}_LATO2"
+ obj.data.materials.clear()
+ if context.scene.meshtools_hide_source:
+ for obj in self._sources:
+ obj.hide_set(True)
+ faces = sum(len(obj.data.polygons) for obj in meshes)
+ verts = sum(len(obj.data.vertices) for obj in meshes)
+ return f"LATO.2: {verts} vertices, {faces} faces"
diff --git a/stablegen/mesh_gen/trellis2.py b/stablegen/mesh_gen/trellis2.py
index e1e8be2..d4a145f 100644
--- a/stablegen/mesh_gen/trellis2.py
+++ b/stablegen/mesh_gen/trellis2.py
@@ -1773,7 +1773,9 @@ class Trellis2Generate(bpy.types.Operator):
for obj in imported_meshes:
try:
print(f"[TRELLIS2] Solidifying mesh: {obj.name} before decimation/retopology...")
- solid_mesh = _make_solid_mesh_object(obj)
+ solid_mesh = _make_solid_mesh_object(
+ obj, require_printable=False,
+ seal_bottom=getattr(context.scene, "trellis2_solidify_seal_bottom", True))
old_mesh = obj.data
obj.data = solid_mesh
bpy.data.meshes.remove(old_mesh)
diff --git a/stablegen/texturing/exterior_fill.py b/stablegen/texturing/exterior_fill.py
new file mode 100644
index 0000000..eb53731
--- /dev/null
+++ b/stablegen/texturing/exterior_fill.py
@@ -0,0 +1,370 @@
+"""Which faces of a mesh can be seen from outside, by flood-filling empty voxels from the bounding box's border.
+
+TRELLIS.2 meshes are double-walled: under the outer skin runs a parallel copy of the surface a few voxels inside, and
+closed objects keep sealed interiors (a car's seats and inner panels). A face is exterior when the empty space next
+to it connects to the border of the grid. Unlike rays cast from a ring of viewpoints, this reaches every concave
+area wider than about two voxels (armpits, wheel wells, the gap between legs), and it never reaches a cavity
+that only a thin slit opens into.
+
+Generated surfaces are rarely sealed: hairline holes let the flood into most TRELLIS.2 interiors. Closing the
+surface by a few voxels keeps it out, but also fills narrow visible gaps (between roof shingles, petals, slats), so
+an exact visibility pass (a rasterized ID buffer from many directions) keeps every face that can be seen.
+
+Pure numpy (no scipy), so it runs inside Blender.
+"""
+
+import numpy as np
+
+# Largest number of voxels along the longest side. Memory is about 6 bytes per voxel.
+DEFAULT_RESOLUTION = 320
+_MAX_PASSES = 64
+
+
+def _grid(vertices, resolution, pad=2):
+ lo = vertices.min(axis=0)
+ hi = vertices.max(axis=0)
+ pitch = max(float((hi - lo).max()), 1.0e-9) / (resolution - 2 * pad)
+ origin = lo - pad * pitch
+ shape = tuple(int(n) for n in np.ceil((hi - origin) / pitch).astype(np.int64) + pad + 1)
+ return origin, pitch, shape
+
+
+def _surface_occupancy(vertices, triangles, origin, pitch, shape):
+ """Voxels the surface passes through. Each triangle is sampled on a barycentric grid finer than half a voxel, so
+ a closed surface leaves no gap a flood fill could leak through."""
+ occupied = np.zeros(shape, dtype=bool)
+ a = vertices[triangles[:, 0]]
+ b = vertices[triangles[:, 1]]
+ c = vertices[triangles[:, 2]]
+ longest = np.maximum(np.maximum(np.linalg.norm(b - a, axis=1), np.linalg.norm(c - b, axis=1)),
+ np.linalg.norm(a - c, axis=1))
+ steps = np.maximum(1, np.ceil(longest / (0.5 * pitch))).astype(np.int64)
+ limit = np.array(shape) - 1
+ for step in np.unique(steps):
+ chosen = np.nonzero(steps == step)[0]
+ i, j = np.meshgrid(np.arange(step + 1), np.arange(step + 1), indexing='ij')
+ keep = (i + j) <= step
+ u = (i[keep] / step).astype(np.float32)
+ v = (j[keep] / step).astype(np.float32)
+ # Bound the temporary point array to a few million points per batch.
+ batch = max(1, 4_000_000 // len(u))
+ for start in range(0, len(chosen), batch):
+ sel = chosen[start:start + batch]
+ pa, pb, pc = a[sel], b[sel], c[sel]
+ points = (pa[:, None, :] * (1.0 - u - v)[None, :, None] + pb[:, None, :] * u[None, :, None]
+ + pc[:, None, :] * v[None, :, None]).reshape(-1, 3)
+ index = np.floor((points - origin) / pitch).astype(np.int64)
+ np.clip(index, 0, limit, out=index)
+ occupied[index[:, 0], index[:, 1], index[:, 2]] = True
+ return occupied
+
+
+def _flood_exterior(occupied):
+ """Empty voxels connected (6-neighbourhood) to the grid border. Alternating sweeps along each axis spread the
+ exterior through whole runs of empty voxels at once, so a few passes usually converge."""
+ free = ~occupied
+ exterior = np.zeros_like(occupied)
+ exterior[0] = exterior[-1] = True
+ exterior[:, 0] = exterior[:, -1] = True
+ exterior[:, :, 0] = exterior[:, :, -1] = True
+ exterior &= free
+ total = int(exterior.sum())
+ for _ in range(_MAX_PASSES):
+ for axis in range(3):
+ occ_view = np.moveaxis(occupied, axis, -1)
+ ext_view = np.moveaxis(exterior, axis, -1)
+ free_view = np.moveaxis(free, axis, -1)
+ rows, cols, length = occ_view.shape
+ chunk = max(1, 8_000_000 // (cols * length))
+ for start in range(0, rows, chunk):
+ stop = min(rows, start + chunk)
+ occ = occ_view[start:stop]
+ # Runs of empty voxels along each line: a new run starts after every occupied voxel.
+ run = np.cumsum(occ, axis=-1, dtype=np.int32)
+ line = np.arange((stop - start) * cols, dtype=np.int64).reshape(stop - start, cols, 1)
+ ids = line * (length + 1) + run
+ touched = np.zeros((stop - start) * cols * (length + 1), dtype=bool)
+ touched[ids[ext_view[start:stop]]] = True
+ ext_view[start:stop] = free_view[start:stop] & touched[ids]
+ new_total = int(exterior.sum())
+ if new_total == total:
+ break
+ total = new_total
+ return exterior
+
+
+def _dilate(mask):
+ """One voxel of 6-neighbourhood dilation."""
+ out = mask.copy()
+ out[1:] |= mask[:-1]
+ out[:-1] |= mask[1:]
+ out[:, 1:] |= mask[:, :-1]
+ out[:, :-1] |= mask[:, 1:]
+ out[:, :, 1:] |= mask[:, :, :-1]
+ out[:, :, :-1] |= mask[:, :, 1:]
+ return out
+
+
+def _face_adjacency(triangles):
+ """Pairs of triangles that share an edge (manifold edges only)."""
+ edges = np.sort(np.concatenate([triangles[:, [0, 1]], triangles[:, [1, 2]], triangles[:, [2, 0]]]), axis=1)
+ owner = np.tile(np.arange(len(triangles)), 3)
+ order = np.lexsort((edges[:, 1], edges[:, 0]))
+ edges, owner = edges[order], owner[order]
+ same = np.all(edges[1:] == edges[:-1], axis=1)
+ # An edge shared by exactly two triangles: equal to its successor but not to the entry before it or after next.
+ start = np.nonzero(same)[0]
+ if len(start) == 0:
+ return np.zeros((0, 2), dtype=np.int64)
+ before = np.zeros(len(start), dtype=bool)
+ before[start > 0] = same[start[start > 0] - 1]
+ after = np.zeros(len(start), dtype=bool)
+ inside = start + 1 < len(same)
+ after[inside] = same[start[inside] + 1]
+ pairs = start[~before & ~after]
+ return np.stack([owner[pairs], owner[pairs + 1]], axis=1)
+
+
+def _smooth_labels(labels, adjacency, iterations=2):
+ """Majority vote over each triangle and its edge neighbours, which removes speckles of one or two triangles."""
+ if len(adjacency) == 0:
+ return labels
+ labels = labels.copy()
+ neighbours = np.bincount(adjacency.ravel(), minlength=len(labels)).astype(np.int32)
+ for _ in range(iterations):
+ votes = labels.astype(np.int32)
+ np.add.at(votes, adjacency[:, 0], labels[adjacency[:, 1]])
+ np.add.at(votes, adjacency[:, 1], labels[adjacency[:, 0]])
+ total = neighbours + 1
+ flipped = np.where(votes * 2 > total, True, np.where(votes * 2 < total, False, labels))
+ if np.array_equal(flipped, labels):
+ break
+ labels = flipped
+ return labels
+
+
+def _components(count, pairs):
+ """Connected-component root per element for undirected pairs (vectorized union-find: hook every pair's larger
+ root under the smaller, then compress paths, until no pair spans two roots)."""
+ parent = np.arange(count)
+ if len(pairs) == 0:
+ return parent
+ while True:
+ a = parent[pairs[:, 0]]
+ b = parent[pairs[:, 1]]
+ spanning = a != b
+ if not spanning.any():
+ return parent
+ np.minimum.at(parent, np.maximum(a, b)[spanning], np.minimum(a, b)[spanning])
+ while True:
+ jumped = parent[parent]
+ if np.array_equal(jumped, parent):
+ break
+ parent = jumped
+
+
+def _flip_small_regions(labels, adjacency, areas, max_area, flip_value):
+ """Flip regions labelled flip_value whose area is at most max_area and that border the other label."""
+ same = labels[adjacency[:, 0]] == labels[adjacency[:, 1]]
+ root = _components(len(labels), adjacency[same])
+ region_area = np.bincount(root, weights=areas, minlength=len(labels))
+ borders = np.zeros(len(labels), dtype=bool)
+ cross = adjacency[~same]
+ borders[root[cross[:, 0]]] = True
+ borders[root[cross[:, 1]]] = True
+ small = (labels == flip_value) & borders[root] & (region_area[root] <= max_area)
+ return np.where(small, not flip_value, labels)
+
+
+def _clean_regions(labels, adjacency, areas, max_area):
+ """First remove small kept patches inside removed geometry (specks of the inner wall), so the inner wall becomes
+ one region again; then keep small removed patches inside the kept skin (they would become holes to cap). A
+ region that touches only its own label, such as a separate sealed part, keeps its label."""
+ if len(adjacency) == 0:
+ return labels
+ labels = _flip_small_regions(labels, adjacency, areas, max_area, True)
+ return _flip_small_regions(labels, adjacency, areas, max_area, False)
+
+
+def _reach_back(exterior, free, steps):
+ """Grow the exterior through free voxels for a few steps (a geodesic dilation)."""
+ for _ in range(steps):
+ exterior = _dilate(exterior) & free
+ return exterior
+
+
+def _sphere_directions(count):
+ i = np.arange(count) + 0.5
+ phi = np.arccos(1 - 2 * i / count)
+ theta = np.pi * (1 + 5 ** 0.5) * i
+ return np.stack([np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi)], axis=1)
+
+
+RASTER_IMAGE_SIZE = 512
+_RASTER_CHUNK = 4_000_000
+
+
+def _nearest_triangles(px, py, depth, triangles, size):
+ """Orthographic ID buffer: for each pixel centre the nearest triangle covering it (-1 where none does).
+ px, py are vertex positions in pixels, depth grows away from the viewer."""
+ best_depth = np.full(size * size, np.inf)
+ best_id = np.full(size * size, -1, dtype=np.int64)
+ x, y = px[triangles], py[triangles]
+ # Pixel centres sit at i + 0.5: the index range each triangle's bounding box covers.
+ x_lo = np.clip(np.ceil(x.min(axis=1) - 0.5), 0, size).astype(np.int64)
+ x_hi = np.clip(np.floor(x.max(axis=1) - 0.5), -1, size - 1).astype(np.int64)
+ y_lo = np.clip(np.ceil(y.min(axis=1) - 0.5), 0, size).astype(np.int64)
+ y_hi = np.clip(np.floor(y.max(axis=1) - 0.5), -1, size - 1).astype(np.int64)
+ nx = np.maximum(x_hi - x_lo + 1, 0)
+ ny = np.maximum(y_hi - y_lo + 1, 0)
+ area = (x[:, 1] - x[:, 0]) * (y[:, 2] - y[:, 0]) - (x[:, 2] - x[:, 0]) * (y[:, 1] - y[:, 0])
+ count = np.where(np.abs(area) > 1e-12, nx * ny, 0)
+ candidates = np.nonzero(count)[0]
+ # Barycentric weights and depth are affine in the pixel position: w = a + b * cx + c * cy per triangle.
+ tri = candidates
+ inv = 1.0 / area[tri]
+ x0, y0 = x[tri, 0], y[tri, 0]
+ ex1, ey1 = x[tri, 1] - x0, y[tri, 1] - y0
+ ex2, ey2 = x[tri, 2] - x0, y[tri, 2] - y0
+ w1 = np.stack([(-x0 * ey2 + ex2 * y0) * inv, ey2 * inv, -ex2 * inv], axis=1)
+ w2 = np.stack([(x0 * ey1 - ex1 * y0) * inv, -ey1 * inv, ex1 * inv], axis=1)
+ d = depth[triangles[tri]]
+ dz = w1 * (d[:, 1] - d[:, 0])[:, None] + w2 * (d[:, 2] - d[:, 0])[:, None]
+ dz[:, 0] += d[:, 0]
+ per_all = count[tri]
+ ends = np.cumsum(per_all)
+ start = 0
+ while start < len(tri):
+ # Triangles in chunks of about _RASTER_CHUNK candidate pixels.
+ stop = max(start + 1, int(np.searchsorted(ends, (ends[start - 1] if start else 0) + _RASTER_CHUNK)))
+ per = per_all[start:stop]
+ owner = np.repeat(np.arange(start, stop), per)
+ local = np.arange(len(owner)) - np.repeat(np.cumsum(per) - per, per)
+ t = tri[owner]
+ ix = x_lo[t] + local % nx[t]
+ iy = y_lo[t] + local // nx[t]
+ cx, cy = ix + 0.5, iy + 0.5
+ a = w1[owner]
+ b = w2[owner]
+ u = a[:, 0] + a[:, 1] * cx + a[:, 2] * cy
+ v = b[:, 0] + b[:, 1] * cx + b[:, 2] * cy
+ inside = (u >= -1e-9) & (v >= -1e-9) & (u + v <= 1.0 + 1e-9)
+ c = dz[owner[inside]]
+ z = c[:, 0] + c[:, 1] * cx[inside] + c[:, 2] * cy[inside]
+ pixel = iy[inside] * size + ix[inside]
+ np.minimum.at(best_depth, pixel, z)
+ won = z == best_depth[pixel]
+ best_id[pixel[won]] = t[inside][won]
+ start = stop
+ return best_id
+
+
+def visible_triangles(vertices, triangles, directions=64, image_size=RASTER_IMAGE_SIZE, floor_axis=None):
+ """Boolean per triangle: nearest to the viewer at some pixel centre in at least one of `directions`
+ orthographic views spread over the sphere (a rasterized ID buffer, so thin strips and large low-poly
+ triangles count exactly, whatever way their normals point). floor_axis stands the object on an opaque floor
+ that covers its footprint a hair below its lowest point along that axis: nothing is seen through an opening in
+ the underside, while low views past the footprint's edge still see overhangs from below."""
+ vertices = np.asarray(vertices, dtype=np.float64)
+ triangles = np.asarray(triangles, dtype=np.int64)
+ count = len(triangles)
+ lo, hi = vertices.min(axis=0), vertices.max(axis=0)
+ radius = max(float(np.linalg.norm(hi - lo)) / 2, 1e-12)
+ if floor_axis is not None:
+ a, b = [axis for axis in range(3) if axis != floor_axis]
+ quad = np.zeros((4, 3))
+ quad[:, floor_axis] = lo[floor_axis] - 1e-3 * radius
+ quad[:, a] = [lo[a], hi[a], hi[a], lo[a]]
+ quad[:, b] = [lo[b], lo[b], hi[b], hi[b]]
+ triangles = np.concatenate([triangles, len(vertices) + np.array([[0, 1, 2], [0, 2, 3]])])
+ vertices = np.concatenate([vertices, quad])
+ points = (vertices - (lo + hi) / 2) / radius
+ size = int(image_size)
+ visible = np.zeros(len(triangles), dtype=bool)
+ for direction in _sphere_directions(int(directions)):
+ helper = np.array([1.0, 0.0, 0.0]) if abs(direction[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
+ u = np.cross(direction, helper)
+ u /= np.linalg.norm(u)
+ v = np.cross(direction, u)
+ ids = _nearest_triangles((points @ u + 1) * 0.5 * size, (points @ v + 1) * 0.5 * size,
+ -(points @ direction), triangles, size)
+ visible[ids[ids >= 0]] = True
+ return visible[:count]
+
+
+def _grow(labels, adjacency, rings, allowed):
+ """Add the edge neighbours of labelled triangles that are `allowed`, `rings` times."""
+ for _ in range(int(rings)):
+ touched = labels[adjacency[:, 0]] | labels[adjacency[:, 1]]
+ grown = np.zeros_like(labels)
+ grown[adjacency[touched].ravel()] = True
+ labels = labels | (grown & allowed)
+ return labels
+
+
+# Rings of neighbours added to the triangles the view pass sees, among triangles under VISIBLE_GROW_PIXELS pixels
+# of area: one that small can miss every pixel centre although its neighbours are seen.
+VISIBLE_GROW = 2
+VISIBLE_GROW_PIXELS = 4.0
+
+
+def exterior_triangles(vertices, triangles, resolution=DEFAULT_RESOLUTION, smooth=True, clean_area=0.002,
+ seal_bottom=False, up_axis=2, close_holes=0, view_directions=0, visible=None):
+ """Boolean per triangle: whether empty space next to it connects to the outside.
+
+ vertices: (N, 3) float array; triangles: (F, 3) int array. clean_area is the largest region, as a fraction of
+ the total surface area, that _clean_regions may flip (0 disables it). seal_bottom puts a floor under the object
+ (the plane of its lowest point, along up_axis) before the flood, so an opening in the underside does not let
+ outside space into a hollow object: its inside surface is then interior. close_holes (voxels) thickens the
+ surface before the flood, so holes up to about twice that wide do not let it in, then lets outside space back
+ to the real surface through the same number of free voxels. view_directions also keeps every triangle visible
+ from that many directions (visible_triangles, standing on the floor when seal_bottom is set) and its small
+ neighbours, so gap closing cannot cut into surfaces you can see; `visible` passes that mask in precomputed.
+ Returns (mask, info) where info reports the grid."""
+ vertices = np.asarray(vertices, dtype=np.float64)
+ triangles = np.asarray(triangles, dtype=np.int64)
+ if len(triangles) == 0:
+ return np.zeros(0, dtype=bool), {}
+ origin, pitch, shape = _grid(vertices, int(resolution), pad=2 + int(close_holes))
+ occupied = _surface_occupancy(vertices, triangles, origin, pitch, shape)
+ if visible is None and view_directions:
+ visible = visible_triangles(vertices, triangles, directions=view_directions,
+ floor_axis=up_axis if seal_bottom else None)
+ if seal_bottom:
+ floor = int(np.floor((vertices[:, up_axis].min() - origin[up_axis]) / pitch))
+ index = [slice(None)] * 3
+ index[up_axis] = floor
+ occupied[tuple(index)] = True
+ blocked = occupied
+ for _ in range(int(close_holes)):
+ blocked = _dilate(blocked)
+ exterior = _flood_exterior(blocked)
+ if close_holes:
+ exterior = _reach_back(exterior, ~occupied, int(close_holes))
+ near_exterior = _dilate(exterior)
+ corners = vertices[triangles]
+ limit = np.array(shape) - 1
+ mask = np.zeros(len(triangles), dtype=bool)
+ # A triangle is exterior when its centre or a point toward any corner sits next to an exterior voxel.
+ centre = corners.mean(axis=1)
+ for point in (centre, *(0.5 * (centre + corners[:, k]) for k in range(3))):
+ index = np.clip(np.floor((point - origin) / pitch).astype(np.int64), 0, limit)
+ mask |= near_exterior[index[:, 0], index[:, 1], index[:, 2]]
+ # Neighbours by position: a mesh split at UV seams or into separate triangles still has its shared edges.
+ welded = np.unique(vertices, axis=0, return_inverse=True)[1].reshape(-1)[triangles]
+ adjacency = _face_adjacency(welded) if smooth or clean_area or visible is not None else None
+ areas = 0.5 * np.linalg.norm(np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0]), axis=1)
+ max_area = clean_area * float(areas.sum())
+ if smooth:
+ mask = _smooth_labels(mask, adjacency)
+ if clean_area:
+ mask = _clean_regions(mask, adjacency, areas, max_area)
+ if visible is not None:
+ # After the cleanup, so neither the majority vote nor the speck removal takes a seen triangle away.
+ pixel = float(np.linalg.norm(vertices.max(axis=0) - vertices.min(axis=0))) / RASTER_IMAGE_SIZE
+ small = areas < VISIBLE_GROW_PIXELS * pixel * pixel
+ mask |= _grow(np.asarray(visible, dtype=bool), adjacency, VISIBLE_GROW, small)
+ if clean_area:
+ mask = _flip_small_regions(mask, adjacency, areas, max_area, False)
+ info = {'pitch': pitch, 'shape': shape, 'occupied': int(occupied.sum()), 'exterior': int(exterior.sum())}
+ return mask, info
diff --git a/stablegen/texturing/print_export.py b/stablegen/texturing/print_export.py
index 73b58c3..54ea167 100644
--- a/stablegen/texturing/print_export.py
+++ b/stablegen/texturing/print_export.py
@@ -2103,10 +2103,37 @@ def _require_printable_mesh(mesh, *, label="Mesh", require_closed=True):
return topology
+# Make Solid's flood fill: gaps in the surface up to about twice this many voxels do not let outside space into
+# the inside, and faces visible from this many directions are always kept (exterior_fill). Chosen on 19 hard
+# TRELLIS.2 meshes: 3 keeps a median 18% of the hidden area (2: 33%, no closing: 74%) and removes a median 1.8% of
+# the visible area.
+FLOOD_CLOSE_HOLES = 3
+FLOOD_VIEW_DIRECTIONS = 64
+
+
def _make_solid_mesh_object(
obj, fill_gaps=True, visible_faces=None, keep_largest_island=False,
face_visibility=None, *, use_evaluated_mesh=True, raycast_count=None,
- weld_distance=0.0, robust_fill=True, smooth_caps=True):
+ weld_distance=0.0, robust_fill=True, smooth_caps=True,
+ visibility_method='FLOOD', flood_resolution=None,
+ require_printable=True, seal_bottom=False,
+ close_holes=FLOOD_CLOSE_HOLES, view_directions=FLOOD_VIEW_DIRECTIONS):
+ """Remove interior geometry and cap the holes it leaves.
+
+ visibility_method 'FLOOD' keeps the faces that empty space from outside
+ reaches (exterior_fill); 'RAYCAST' keeps the faces hit by rays from a ring
+ of viewpoints around the object (raycast_count of them), the older test.
+ close_holes and view_directions (FLOOD only) keep hairline gaps in the
+ surface from letting the flood reach the inside, without removing faces
+ that can be seen from outside.
+ seal_bottom (FLOOD only) closes the object's underside before the flood,
+ so a hollow object open at the bottom loses its inner shell and gets a
+ capped bottom instead of staying an open shell.
+ require_printable rejects a result with open or non-manifold edges (the
+ slicer export needs that); generated meshes such as TRELLIS.2's carry
+ non-manifold seams of their own, so mesh post-processing passes False and
+ takes the best result instead of keeping every interior shell.
+ """
import bmesh
from mathutils.bvhtree import BVHTree
import numpy as np
@@ -2128,12 +2155,49 @@ def _make_solid_mesh_object(
eval_obj = None
temp.calc_loop_triangles()
try:
+ flood_visible = None
+ if visible_faces is None and visibility_method == 'FLOOD':
+ from .exterior_fill import DEFAULT_RESOLUTION, exterior_triangles
+ t0 = time.perf_counter()
+ temp.calc_loop_triangles()
+ coords = np.empty(len(temp.vertices) * 3, dtype=np.float32)
+ temp.vertices.foreach_get("co", coords)
+ triangles = np.empty(len(temp.loop_triangles) * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("vertices", triangles)
+ polygons = np.empty(len(temp.loop_triangles), dtype=np.int32)
+ temp.loop_triangles.foreach_get("polygon_index", polygons)
+ exterior, info = exterior_triangles(
+ coords.reshape(-1, 3),
+ triangles.reshape(-1, 3),
+ resolution=flood_resolution or DEFAULT_RESOLUTION,
+ seal_bottom=seal_bottom,
+ close_holes=close_holes,
+ view_directions=view_directions,
+ up_axis=2,
+ )
+ flood_visible = np.zeros(len(temp.polygons), dtype=bool)
+ flood_visible[polygons[exterior]] = True
+ print(
+ "[StableGen Make Solid] Exterior flood fill: kept "
+ f"{int(flood_visible.sum())} of {len(flood_visible)} faces "
+ f"(grid {info.get('shape')}) in {time.perf_counter() - t0:.4f}s"
+ )
+
bm = bmesh.new()
bm.from_mesh(temp)
source_vertex_layer, source_face_windings = (
_capture_source_face_windings(bm)
)
-
+
+ exterior_layer = None
+ if flood_visible is not None:
+ # Carried on a face layer so it survives the optional weld below,
+ # which can drop degenerate faces and renumber the rest.
+ exterior_layer = bm.faces.layers.int.new("_SG_Exterior")
+ bm.faces.ensure_lookup_table()
+ for face, visible in zip(bm.faces, flood_visible.tolist()):
+ face[exterior_layer] = 1 if visible else 0
+
# The 3D-print export historically welds coincident evaluated geometry.
# General post-processing must not globally weld detached character
# shells (clothing/body, armor panels, eyes, etc.), because doing so
@@ -2142,7 +2206,21 @@ def _make_solid_mesh_object(
bmesh.ops.remove_doubles(
bm, verts=bm.verts, dist=float(weld_distance)
)
-
+ else:
+ # A mesh stored as separate triangles (flat-shaded or exported
+ # per corner) shares no edges, so every kept face would border a
+ # hole to cap. Join its coincident corners when most of them are
+ # duplicates; the few coincident vertices of a generated mesh
+ # (pinch points) stay apart.
+ positions = np.empty(len(bm.verts) * 3, dtype=np.float64)
+ temp.vertices.foreach_get("co", positions)
+ positions = positions.reshape(-1, 3)
+ if len(positions) and len(positions) >= 1.5 * len(np.unique(positions, axis=0)):
+ extent = float(np.linalg.norm(positions.max(axis=0) - positions.min(axis=0)))
+ before = len(bm.verts)
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-7 * max(extent, 1e-9))
+ print(f"[StableGen Make Solid] Joined split corners: {before} -> {len(bm.verts)} vertices")
+
bm.faces.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.verts.ensure_lookup_table()
@@ -2172,7 +2250,13 @@ def _make_solid_mesh_object(
avg_color = get_avg_color(f.loops, color_lay)
face_info.append((center, avg_color, f.index))
print(f"[StableGen Make Solid] Collected face info in {time.perf_counter() - t0:.4f}s")
-
+
+ if exterior_layer is not None:
+ visible_faces = {
+ f.index for f in bm.faces if f[exterior_layer]
+ }
+ bm.faces.layers.int.remove(exterior_layer)
+
if visible_faces is None:
t0 = time.perf_counter()
bvh = BVHTree.FromBMesh(bm)
@@ -2349,6 +2433,11 @@ def _make_solid_mesh_object(
stack.append(linked)
components.append(component)
+ # A branching boundary (two holes touching at a vertex) or a
+ # loop triangle_fill cannot close stays open. Capping across
+ # it would create overlapping faces, and failing the whole
+ # operation would leave every interior shell in place.
+ skipped = 0
for component in components:
component_vertices = {
vert for edge in component for vert in edge.verts
@@ -2360,11 +2449,8 @@ def _make_solid_mesh_object(
) != 2
]
if branching:
- raise RuntimeError(
- "cannot safely cap a branching boundary "
- f"({len(component)} edges, "
- f"{len(branching)} branching vertices)"
- )
+ skipped += 1
+ continue
fill_result = bmesh.ops.triangle_fill(
bm,
edges=list(component),
@@ -2377,10 +2463,15 @@ def _make_solid_mesh_object(
and geom not in source_faces
]
if not component_faces:
- raise RuntimeError(
- "failed to create a cap for a valid boundary loop"
- )
+ skipped += 1
+ continue
new_faces.extend(component_faces)
+ if skipped:
+ print(
+ f"[StableGen Make Solid] Left {skipped} of "
+ f"{len(components)} boundary loops open (branching "
+ "or not fillable)"
+ )
else:
# Preserve the historical 3D-print fill behavior. The general
# post-processing operator uses the validated triangle-fill
@@ -2612,15 +2703,23 @@ def _make_solid_mesh_object(
print(f"[StableGen Make Solid] Stored _SG_FaceVisibility on {n_faces} faces")
solid_mesh.calc_loop_triangles()
- try:
- _require_printable_mesh(
- solid_mesh,
- label=f"Make Solid result for {obj.name}",
- require_closed=bool(fill_gaps),
+ if require_printable:
+ try:
+ _require_printable_mesh(
+ solid_mesh,
+ label=f"Make Solid result for {obj.name}",
+ require_closed=bool(fill_gaps),
+ )
+ except Exception:
+ bpy.data.meshes.remove(solid_mesh)
+ raise
+ else:
+ topology = _mesh_topology_counts(solid_mesh)
+ print(
+ "[StableGen Make Solid] Result topology: "
+ f"{topology['boundary']} open edges, "
+ f"{topology['non_manifold']} non-manifold edges"
)
- except Exception:
- bpy.data.meshes.remove(solid_mesh)
- raise
print(f"[StableGen Make Solid] Total execution time: {time.perf_counter() - t_start:.4f}s")
return solid_mesh
finally:
diff --git a/stablegen/texturing/solidify.py b/stablegen/texturing/solidify.py
index dc99055..842c5a0 100644
--- a/stablegen/texturing/solidify.py
+++ b/stablegen/texturing/solidify.py
@@ -10,7 +10,6 @@ from ..utils import sg_modal_active
from .print_export import (
_make_solid_mesh_object,
_mesh_topology_counts,
- _require_printable_mesh,
)
@@ -63,7 +62,8 @@ def _restore_vertex_group_names(obj, names):
def _validate_solid_result(
obj, source, target, weighted_before, *, fill_gaps):
- """Reject state loss or a result that remains unsafe for slicing."""
+ """Reject state loss: UVs, projection data, materials, caps, skinning. A few open or non-manifold edges stay
+ allowed: this tool prepares meshes for texturing and rigging; the 3D-print export checks print safety."""
if len(target.vertices) == 0 or len(target.polygons) == 0:
raise RuntimeError("solidification produced an empty mesh")
@@ -89,7 +89,7 @@ def _validate_solid_result(
target_materials = list(target.materials)
if source_materials != target_materials:
raise RuntimeError("solidification changed the material slot layout")
- if any(
+ if target_materials and any( # without material slots every face has index 0, which is fine
polygon.material_index >= len(target_materials)
for polygon in target.polygons
):
@@ -109,12 +109,6 @@ def _validate_solid_result(
if any(polygon.area <= 1.0e-12 for polygon in cap_faces):
raise RuntimeError("solidification produced a degenerate cap face")
- _require_printable_mesh(
- target,
- label=f"Make Solid result for {obj.name}",
- require_closed=bool(fill_gaps),
- )
-
weighted_after = _weighted_membership_count(obj)
if weighted_before and not weighted_after:
raise RuntimeError("solidification removed all skinning weights")
@@ -144,17 +138,47 @@ class StableGenMakeSolid(bpy.types.Operator):
),
default=False,
)
+ visibility_method: bpy.props.EnumProperty(
+ name="Interior Test",
+ description="How hidden interior surfaces are found",
+ items=(
+ ('FLOOD', "Flood Fill",
+ "Keep the faces that empty space from outside the object reaches "
+ "(finds inner walls and sealed cavities, reaches concave areas)"),
+ ('RAYCAST', "Raycast (Legacy)",
+ "Keep the faces hit by rays from a ring of directions around the object"),
+ ),
+ default='FLOOD',
+ )
+ seal_bottom: bpy.props.BoolProperty(
+ name="Close Bottom Openings",
+ description=(
+ "Treat the underside as closed (Flood Fill), so a hollow mesh open at the bottom becomes solid "
+ "with a capped bottom instead of keeping its inside surface"
+ ),
+ default=True,
+ )
raycast_count: bpy.props.IntProperty(
name="Raycast Directions",
description=(
"Number of radial directions used to distinguish exterior from "
- "interior surfaces"
+ "interior surfaces (Raycast only)"
),
default=12,
min=4,
max=64,
)
+ def draw(self, context):
+ layout = self.layout
+ layout.prop(self, "fill_gaps")
+ layout.prop(self, "keep_largest_island")
+ layout.prop(self, "visibility_method")
+ if self.visibility_method == 'RAYCAST':
+ layout.prop(self, "raycast_count")
+ else:
+ layout.prop(self, "seal_bottom")
+
@classmethod
def poll(cls, context):
if sg_modal_active(context):
@@ -200,6 +224,9 @@ class StableGenMakeSolid(bpy.types.Operator):
weld_distance=0.0,
robust_fill=True,
smooth_caps=True,
+ visibility_method=self.visibility_method,
+ seal_bottom=self.seal_bottom,
+ require_printable=False,
)
_restore_mesh_metadata(source, solid)
obj.data = solid
@@ -230,9 +257,13 @@ class StableGenMakeSolid(bpy.types.Operator):
if source.users == 0:
bpy.data.meshes.remove(source)
obj.data.update()
+ topology = _mesh_topology_counts(obj.data)
+ left = ", ".join(f"{count} {name}{'s' if count != 1 else ''}" for name, count in (
+ ("open edge", topology["boundary"]), ("non-manifold edge", topology["non_manifold"])) if count)
self.report(
{'INFO'},
- f"Made {obj.name} solid while preserving rig and materials",
+ f"Made {obj.name} solid while preserving rig and materials"
+ + (f" ({left} left; fine for texturing, not for 3D printing)" if left else ""),
)
return {'FINISHED'}
except Exception as error:
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 12d93e5..18dd96f 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -1011,10 +1011,24 @@ class StableGenPanel(bpy.types.Panel):
if rem_method == 'quadriflow':
row = content_box.row()
row.label(text="Note: Quadriflow is experimental and might produce artifacts.", icon="WARNING")
+ elif rem_method == 'lato2':
+ row = content_box.row(align=True)
+ row.prop(scene, "meshtools_lato2_vertices", text="LATO.2 Vertices")
+ if not getattr(scene, 'meshtools_lato2_available', False):
+ from ..mesh_gen.meshtools import lato2_missing
+ content_box.label(text=lato2_missing()[0], icon="ERROR")
+ elif scene.trellis2_texture_mode == 'native':
+ content_box.label(text="LATO.2 drops native TRELLIS.2 textures; it is skipped in this mode.", icon="INFO")
row = content_box.row()
row.prop(scene, "trellis2_solidify", text="Solidify Mesh")
-
+ if scene.trellis2_solidify:
+ row = content_box.row()
+ row.prop(scene, "trellis2_solidify_seal_bottom")
+ # the same settings on a mesh that already exists (the box keeps its progress with it)
+ _draw_meshtool_button(context, content_box.box(), 'OBJECT_OT_stablegen_local_postprocess',
+ "object.stablegen_local_postprocess", "Post-Process Active Mesh",
+ "MODIFIER", "Cancel Post-Processing")
content_box.separator()
@@ -1179,6 +1193,11 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "trellis2_autorig_hf_path", text="Hugging Face model path")
+ # --- LATO.2 low-poly remesh (ComfyUI-LATO2): any mesh, so every architecture; the Tools tab in the panel ---
+ content_box = draw_collapsible_section(advanced_params_box, "show_meshtools", "Low-Poly Remesh (LATO.2)", icon="MOD_REMESH")
+ if content_box:
+ draw_meshtools_section(context, content_box)
+
# --- TRELLIS.2: Native Texture Settings ---
if is_trellis2 and trellis2_tex_mode == 'native':
content_box = draw_collapsible_section(advanced_params_box, "show_trellis2_texture_settings", "Texture Settings (TRELLIS.2 Native)", icon="TEXTURE")
diff --git a/stablegen/ui/presentation.py b/stablegen/ui/presentation.py
index e4531e1..cf1d91a 100644
--- a/stablegen/ui/presentation.py
+++ b/stablegen/ui/presentation.py
@@ -27,6 +27,7 @@ SECTION_INFO = {
'show_texturing_experiments': ('Experimental Texturing', 'DEBUG', 'EXPERIMENTAL'),
'show_trellis2_mesh_settings': ('Mesh & Post-Processing', 'MESH', 'MESH_DATA'),
'show_trellis2_autorig_settings': ('Rigging & Animation', 'MESH', 'ARMATURE_DATA'),
+ 'show_meshtools': ('Low-poly remesh (LATO.2)', 'TOOLS', 'MOD_REMESH'), # any mesh: with the tools
'show_trellis2_texture_settings': ('Native Textures', 'MESH', 'TEXTURE'),
'show_trellis2_camera_settings': ('Camera Placement', 'CAMERAS', 'CAMERA_DATA'),
}
diff --git a/stablegen/ui/studio.py b/stablegen/ui/studio.py
index dac3e70..a6248e4 100644
--- a/stablegen/ui/studio.py
+++ b/stablegen/ui/studio.py
@@ -1939,9 +1939,12 @@ class StudioSession:
def draw_tools(self, p, x, y, width):
y = self.draw_actions(p, 'Scene setup', [
('object.add_hdri', 'Add HDRI lighting', 'light')], x, y, width)
+ lato2 = next((s for s in self.document.sections if s.key == 'show_meshtools'), None)
for section in self.document.sections:
if section.key in TOOL_SECTIONS:
y = self.draw_section(p, section, x, y, width)
+ if section.key == 'mesh_tools' and lato2 is not None: # LATO.2 remeshes any mesh
+ y = self.draw_section(p, lato2, x, y, width)
y = self.draw_actions(p, 'Import & batch', [
('stablegen.import_dae', 'Import DAE', 'download'),
('stablegen.batch_import_dae', 'Batch import DAE', 'folder'),
diff --git a/stablegen/ui/studio_cards.py b/stablegen/ui/studio_cards.py
index 0b32f58..e3e8505 100644
--- a/stablegen/ui/studio_cards.py
+++ b/stablegen/ui/studio_cards.py
@@ -147,6 +147,15 @@ SCHEMAS = {
'trellis2_autorig_temperature', 'trellis2_autorig_repetition_penalty', 'trellis2_autorig_num_beams')),
Spec('checkpoint', 'Rig model', 'settings', ('trellis2_autorig_model_ckpt', 'trellis2_autorig_hf_path')),
),
+ 'show_meshtools': (
+ Spec('lato2', 'Remesh the selected mesh', 'modifier', ('meshtools_lato2_vertices', 'meshtools_lato2_seed',
+ 'meshtools_hide_source', 'op:object.stablegen_lato2_remesh'),
+ rows=(('meshtools_lato2_vertices', 'meshtools_lato2_seed'),),
+ description='Generated low-poly topology, 200 to 5000 vertices, imported next to the source.'),
+ # while the server has no LATO.2: what would bring it (a restart, the setup, the server's installer)
+ Spec('lato2_missing', 'LATO.2 on the server', 'server', ('op:stablegen.comfy_restart', 'op:stablegen.open_setup',
+ 'op:stablegen.comfy_copy_install_command', 'op:stablegen.check_server_status')),
+ ),
'show_trellis2_texture_settings': (
Spec('texture', 'Native texture generation', 'layers', ('trellis2_tex_guidance',
'trellis2_tex_steps', 'trellis2_texture_size', 'trellis2_auto_lighting')),
diff --git a/stablegen/ui/studio_hierarchy.py b/stablegen/ui/studio_hierarchy.py
index 4f8f54b..431ced7 100644
--- a/stablegen/ui/studio_hierarchy.py
+++ b/stablegen/ui/studio_hierarchy.py
@@ -73,7 +73,9 @@ FAMILIES = {
'pbr_tile_material', 'pbr_tile_normal', 'pbr_tile_height', 'pbr_tile_emission'),
'pbr_use_native_resolution': ('pbr_processing_resolution',),
'trellis2_post_processing_enabled': ('trellis2_decimate_method', 'trellis2_decimation',
- 'trellis2_remesh_method', 'trellis2_solidify'),
+ 'trellis2_remesh_method', 'trellis2_solidify', 'op:object.stablegen_local_postprocess'),
+ 'trellis2_remesh_method': ('meshtools_lato2_vertices',),
+ 'trellis2_solidify': ('trellis2_solidify_seal_bottom',),
'trellis2_exclude_bottom': ('trellis2_exclude_bottom_angle',),
'trellis2_clamp_elevation': ('trellis2_min_elevation', 'trellis2_max_elevation'),
'trellis2_preview_gallery_enabled': ('trellis2_preview_gallery_count',),