Skip to content

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

feat(mesh_gen): batch image-to-3D generation from folder

srandovnidobrodruzstvi6d4bb3149abb
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index 0c20fa9..e744fa9 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -35,6 +35,11 @@ from .texturing.generator import (
ComfyUIGenerate, Reproject, Regenerate, MirrorReproject,
)
from .mesh_gen.trellis2 import Trellis2Generate
+from .mesh_gen.batch import (
+ batch_classes as _batch_classes,
+ TRELLIS2_OT_BatchSelectFolder, TRELLIS2_OT_BatchGenerate,
+ TRELLIS2_OT_BatchCancel, TRELLIS2_OT_BatchClear,
+)
from .dae_import import DAE_IMPORT_CLASSES
# -- Core / UI sub-packages ----------------------------------------------
@@ -92,6 +97,10 @@ classes = [
Regenerate,
MirrorReproject,
Trellis2Generate,
+ TRELLIS2_OT_BatchSelectFolder,
+ TRELLIS2_OT_BatchGenerate,
+ TRELLIS2_OT_BatchCancel,
+ TRELLIS2_OT_BatchClear,
# Operators - render tools
BakeTextures,
AddCameras,
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index 40a09b9..a9b34a1 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -1178,6 +1178,26 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
name="Input Image", description="Path to the reference image for 3D mesh generation",
subtype='FILE_PATH', default=""
)
+ # --- Batch generation ---
+ bpy.types.Scene.trellis2_batch_folder = bpy.props.StringProperty(
+ name="Batch Folder",
+ description="Folder containing images for batch TRELLIS.2 generation",
+ subtype='DIR_PATH', default=""
+ )
+ bpy.types.Scene.trellis2_batch_count = bpy.props.IntProperty(
+ name="Batch Image Count",
+ description="Number of supported images found in the batch folder",
+ default=0, min=0
+ )
+ bpy.types.Scene.trellis2_batch_rename_meshes = bpy.props.BoolProperty(
+ name="Name meshes after input files",
+ description="Rename each imported mesh to the stem of its source image filename",
+ default=True
+ )
+ # WindowManager props for live batch progress display
+ bpy.types.WindowManager.sg_batch_running = bpy.props.BoolProperty(default=False)
+ bpy.types.WindowManager.sg_batch_index = bpy.props.IntProperty(default=0)
+ bpy.types.WindowManager.sg_batch_total = bpy.props.IntProperty(default=0)
bpy.types.Scene.trellis2_resolution = bpy.props.EnumProperty(
name="Resolution", description="Model resolution for generation. Higher values use more VRAM",
items=[
@@ -1586,7 +1606,9 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'trellis2_import_scale', 'trellis2_shade_mode',
'trellis2_clamp_elevation', 'trellis2_max_elevation', 'trellis2_min_elevation',
'trellis2_preview_gallery_enabled', 'trellis2_preview_gallery_count',
- 'trellis2_input_image', 'trellis2_resolution', 'trellis2_vram_mode',
+ 'trellis2_input_image', 'trellis2_batch_folder', 'trellis2_batch_count',
+ 'trellis2_batch_rename_meshes',
+ 'trellis2_resolution', 'trellis2_vram_mode',
'trellis2_attn_backend', 'trellis2_seed', 'trellis2_ss_guidance',
'trellis2_ss_steps', 'trellis2_shape_guidance', 'trellis2_shape_steps',
'trellis2_tex_guidance', 'trellis2_tex_steps', 'trellis2_max_tokens',
@@ -1599,6 +1621,11 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
if hasattr(bpy.types.Scene, prop):
delattr(bpy.types.Scene, prop)
+ # --- Batch generation cleanup ---
+ for attr in ('sg_batch_running', 'sg_batch_index', 'sg_batch_total'):
+ if hasattr(bpy.types.WindowManager, attr):
+ delattr(bpy.types.WindowManager, attr)
+
# --- Scene Queue cleanup ---
if hasattr(bpy.types.WindowManager, 'sg_scene_queue'):
del bpy.types.WindowManager.sg_scene_queue
diff --git a/stablegen/mesh_gen/__init__.py b/stablegen/mesh_gen/__init__.py
index cde2428..e8ae342 100644
--- a/stablegen/mesh_gen/__init__.py
+++ b/stablegen/mesh_gen/__init__.py
@@ -1,3 +1,4 @@
"""mesh_gen – 3D mesh generation (TRELLIS.2)."""
from .trellis2 import Trellis2Generate # noqa: F401
+from .batch import batch_classes, TRELLIS2_OT_BatchSelectFolder, TRELLIS2_OT_BatchGenerate, TRELLIS2_OT_BatchCancel, TRELLIS2_OT_BatchClear # noqa: F401
diff --git a/stablegen/mesh_gen/batch.py b/stablegen/mesh_gen/batch.py
new file mode 100644
index 0000000..ec359d9
--- /dev/null
+++ b/stablegen/mesh_gen/batch.py
@@ -0,0 +1,269 @@
+"""Batch image-to-3D generation for TRELLIS.2."""
+
+import os
+import bpy # pylint: disable=import-error
+
+# Supported input image extensions
+IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tiff', '.tif'}
+
+# ── Module-level batch state ─────────────────────────────────────────────────
+_batch_state = {
+ 'active': False,
+ 'images': [],
+ 'index': -1, # -1 = not yet started; incremented before each gen
+ 'total': 0,
+ 'cancelled': False,
+ 'rename_meshes': True,
+ 'pre_objects': set(), # object names present before current generation
+ 'settling': False, # waiting a few ticks for Trellis2Generate to start
+ 'settle_count': 0,
+}
+
+_SETTLE_TICKS = 4 # ticks to wait after invoking the operator
+_TICK_INTERVAL = 0.5 # seconds between timer callbacks
+
+
+def _scan_images(folder):
+ """Return a sorted list of supported image file paths in *folder*."""
+ if not os.path.isdir(folder):
+ return []
+ result = []
+ for name in sorted(os.listdir(folder)):
+ if os.path.splitext(name)[1].lower() in IMAGE_EXTENSIONS:
+ result.append(os.path.join(folder, name))
+ return result
+
+
+def _redraw():
+ """Request a UI redraw on all 3D viewports."""
+ try:
+ for window in bpy.context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _sync_wm():
+ """Push current batch state into WindowManager display properties."""
+ try:
+ wm = bpy.context.window_manager
+ wm.sg_batch_running = _batch_state['active']
+ wm.sg_batch_index = _batch_state['index'] + 1 # 1-based for display
+ wm.sg_batch_total = _batch_state['total']
+ _redraw()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _rename_new_objects(image_path):
+ """Rename objects imported in the last generation to the input filename stem."""
+ state = _batch_state
+ stem = os.path.splitext(os.path.basename(image_path))[0]
+ try:
+ scene = bpy.context.scene
+ new_objs = [
+ obj for obj in scene.objects
+ if obj.name not in state['pre_objects']
+ ]
+ mesh_objs = [o for o in new_objs if o.type == 'MESH']
+ if not mesh_objs:
+ mesh_objs = new_objs # fallback: rename whatever was imported
+ if len(mesh_objs) == 1:
+ mesh_objs[0].name = stem
+ if mesh_objs[0].data:
+ mesh_objs[0].data.name = stem
+ else:
+ for i, obj in enumerate(mesh_objs):
+ obj.name = f"{stem}_{i + 1:02d}"
+ if obj.data:
+ obj.data.name = f"{stem}_{i + 1:02d}"
+ print(f"[BatchGen] Renamed {len(mesh_objs)} object(s) to '{stem}...'")
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchGen] Warning: could not rename objects: {exc}")
+
+
+def _trigger_next():
+ """Record pre-generation objects, set input image, invoke Trellis2Generate."""
+ state = _batch_state
+ image_path = state['images'][state['index']]
+
+ # Snapshot current objects so we can identify new ones after import
+ try:
+ state['pre_objects'] = {obj.name for obj in bpy.context.scene.objects}
+ except Exception: # noqa: BLE001
+ state['pre_objects'] = set()
+
+ try:
+ bpy.context.scene.trellis2_input_image = image_path
+ print(f"[BatchGen] {state['index'] + 1}/{state['total']}: "
+ f"{os.path.basename(image_path)}")
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchGen] Error setting input image: {exc}")
+ state['cancelled'] = True
+ return
+
+ try:
+ bpy.ops.object.trellis2_generate('INVOKE_DEFAULT')
+ state['settling'] = True
+ state['settle_count'] = 0
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchGen] Error invoking generate: {exc}")
+ state['cancelled'] = True
+
+
+def _batch_tick():
+ """bpy.app.timers callback – drives the batch state machine."""
+ from .trellis2 import Trellis2Generate # late import to avoid circular dep
+
+ state = _batch_state
+
+ # ── Cancelled / stopped ──────────────────────────────────────────────────
+ if state['cancelled'] or not state['active']:
+ state['active'] = False
+ state['cancelled'] = False
+ _sync_wm()
+ print("[BatchGen] Batch stopped")
+ return None # unregister timer
+
+ # ── Settling: waiting for Trellis2Generate to start running ─────────────
+ if state['settling']:
+ state['settle_count'] += 1
+ if state['settle_count'] >= _SETTLE_TICKS:
+ state['settling'] = False
+ return _TICK_INTERVAL
+
+ # ── Still generating ─────────────────────────────────────────────────────
+ if Trellis2Generate._is_running:
+ return _TICK_INTERVAL
+
+ # ── Generation finished (or first tick before first gen) ─────────────────
+ if state['index'] >= 0:
+ # Check for error
+ try:
+ had_error = bpy.context.scene.sg_last_gen_error
+ except Exception: # noqa: BLE001
+ had_error = False
+ if had_error:
+ print(f"[BatchGen] Image {state['index'] + 1} failed, skipping rename")
+ elif state['rename_meshes']:
+ _rename_new_objects(state['images'][state['index']])
+
+ next_index = state['index'] + 1
+
+ if next_index >= state['total']:
+ # ── All done ─────────────────────────────────────────────────────────
+ state['active'] = False
+ _sync_wm()
+ print(f"[BatchGen] Complete! {state['total']} image(s) processed.")
+ return None # stop timer
+
+ state['index'] = next_index
+ _sync_wm()
+ _trigger_next()
+ return _TICK_INTERVAL
+
+
+# ── Operators ────────────────────────────────────────────────────────────────
+
+class TRELLIS2_OT_BatchSelectFolder(bpy.types.Operator):
+ """Select a folder of images for batch TRELLIS.2 generation"""
+ bl_idname = "object.trellis2_batch_select_folder"
+ bl_label = "Select Image Folder for Batch"
+ bl_options = {'REGISTER'}
+
+ directory: bpy.props.StringProperty(subtype='DIR_PATH') # type: ignore
+
+ def invoke(self, context, event):
+ context.window_manager.fileselect_add(self)
+ return {'RUNNING_MODAL'}
+
+ def execute(self, context):
+ folder = self.directory.rstrip('/\\')
+ context.scene.trellis2_batch_folder = folder
+ images = _scan_images(folder)
+ context.scene.trellis2_batch_count = len(images)
+ if images:
+ context.scene.trellis2_input_image = images[0]
+ self.report({'INFO'}, f"Found {len(images)} image(s) in folder")
+ else:
+ self.report({'WARNING'}, "No supported images found in folder")
+ return {'FINISHED'}
+
+
+class TRELLIS2_OT_BatchGenerate(bpy.types.Operator):
+ """Generate 3D models for all images in the selected batch folder"""
+ bl_idname = "object.trellis2_batch_generate"
+ bl_label = "Generate Batch"
+ bl_options = {'REGISTER'}
+
+ @classmethod
+ def poll(cls, context):
+ if _batch_state['active']:
+ return False
+ from .trellis2 import Trellis2Generate
+ if Trellis2Generate._is_running:
+ return False
+ folder = getattr(context.scene, 'trellis2_batch_folder', '')
+ count = getattr(context.scene, 'trellis2_batch_count', 0)
+ return bool(folder) and count > 0
+
+ def execute(self, context):
+ folder = context.scene.trellis2_batch_folder
+ images = _scan_images(folder)
+ if not images:
+ self.report({'ERROR'}, "No images found in batch folder")
+ return {'CANCELLED'}
+
+ _batch_state.update({
+ 'active': True,
+ 'cancelled': False,
+ 'images': images,
+ 'index': -1,
+ 'total': len(images),
+ 'rename_meshes': getattr(context.scene, 'trellis2_batch_rename_meshes', True),
+ 'pre_objects': set(),
+ 'settling': False,
+ 'settle_count': 0,
+ })
+ _sync_wm()
+ print(f"[BatchGen] Starting: {len(images)} image(s) from '{folder}'")
+ bpy.app.timers.register(_batch_tick, first_interval=0.1)
+ return {'FINISHED'}
+
+
+class TRELLIS2_OT_BatchCancel(bpy.types.Operator):
+ """Cancel the running batch generation"""
+ bl_idname = "object.trellis2_batch_cancel"
+ bl_label = "Cancel Batch"
+ bl_options = {'REGISTER'}
+
+ @classmethod
+ def poll(cls, context):
+ return _batch_state['active']
+
+ def execute(self, context):
+ _batch_state['cancelled'] = True
+ self.report({'WARNING'}, "Batch generation cancelling after current model...")
+ return {'FINISHED'}
+
+
+class TRELLIS2_OT_BatchClear(bpy.types.Operator):
+ """Clear the batch folder selection"""
+ bl_idname = "object.trellis2_batch_clear"
+ bl_label = "Clear Batch Folder"
+ bl_options = {'REGISTER'}
+
+ def execute(self, context):
+ context.scene.trellis2_batch_folder = ""
+ context.scene.trellis2_batch_count = 0
+ return {'FINISHED'}
+
+
+batch_classes = [
+ TRELLIS2_OT_BatchSelectFolder,
+ TRELLIS2_OT_BatchGenerate,
+ TRELLIS2_OT_BatchCancel,
+ TRELLIS2_OT_BatchClear,
+]
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 2e071e1..80755b4 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -229,6 +229,15 @@ class StableGenPanel(bpy.types.Panel):
action_row.operator("object.trellis2_generate", text="Cancel TRELLIS.2", icon="CANCEL")
progress_col = layout.column()
+ # Bar 0 — Batch model counter (only during batch)
+ _bi = getattr(context.window_manager, 'sg_batch_index', 0)
+ _bt = getattr(context.window_manager, 'sg_batch_total', 0)
+ if getattr(context.window_manager, 'sg_batch_running', False) and _bt > 0:
+ progress_col.progress(
+ text=f"Batch: Model {_bi}/{_bt}",
+ factor=max(0.0, min((_bi - 1) / _bt, 1.0))
+ )
+
# Bar 1 — Overall
overall_pct = getattr(trellis2_op, '_overall_progress', 0)
overall_label = getattr(trellis2_op, '_overall_stage', 'Initializing')
@@ -369,7 +378,24 @@ class StableGenPanel(bpy.types.Panel):
err_sub.enabled = False
split.operator("stablegen.check_server_status", text="", icon="FILE_REFRESH")
else:
- action_row.operator("object.trellis2_generate", text="Generate 3D Mesh", icon="MESH_ICOSPHERE")
+ _batch_folder = getattr(scene, 'trellis2_batch_folder', '')
+ _batch_count = getattr(scene, 'trellis2_batch_count', 0)
+ _batch_running = getattr(context.window_manager, 'sg_batch_running', False)
+ if _batch_running:
+ _bi = getattr(context.window_manager, 'sg_batch_index', 0)
+ _bt = getattr(context.window_manager, 'sg_batch_total', 0)
+ action_row.operator("object.trellis2_batch_cancel",
+ text=f"Cancel Batch ({_bi}/{_bt})",
+ icon="CANCEL")
+ elif _batch_folder and _batch_count > 0:
+ action_row.operator("object.trellis2_generate",
+ text="Generate Single", icon="MESH_ICOSPHERE")
+ action_row.operator("object.trellis2_batch_generate",
+ text=f"Generate Batch ({_batch_count})",
+ icon="IMGDISPLAY")
+ else:
+ action_row.operator("object.trellis2_generate",
+ text="Generate 3D Mesh", icon="MESH_ICOSPHERE")
else:
# --- Standard Diffusion Generate Button ---
if config_error_message:
@@ -643,7 +669,26 @@ class StableGenPanel(bpy.types.Panel):
if scene.trellis2_generate_from == 'image':
split = params_container.split(factor=0.25)
split.label(text="Input Image:")
- split.prop(scene, "trellis2_input_image", text="")
+ img_row = split.row(align=True)
+ img_row.prop(scene, "trellis2_input_image", text="")
+ img_row.operator("object.trellis2_batch_select_folder",
+ text="", icon="FILE_FOLDER")
+
+ # Batch folder status row
+ batch_folder = getattr(scene, 'trellis2_batch_folder', '')
+ if batch_folder:
+ batch_count = getattr(scene, 'trellis2_batch_count', 0)
+ folder_name = os.path.basename(
+ batch_folder.rstrip('/\\')) or batch_folder
+ b_row = params_container.row(align=True)
+ b_split = b_row.split(factor=0.78, align=True)
+ b_split.label(
+ text=f"Batch: {batch_count} image(s) – {folder_name}",
+ icon="IMAGE_DATA")
+ b_split.operator("object.trellis2_batch_clear",
+ text="", icon="X")
+ rn_row = params_container.row()
+ rn_row.prop(scene, "trellis2_batch_rename_meshes")
# Preview gallery (only when generate_from = prompt)
if scene.trellis2_generate_from == 'prompt':