Skip to content

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

add auto aspect operator, dae importer, and trellis.2 skip fix

sakalond9fa4577d154d
diff --git a/.gitignore b/.gitignore
index 8fdddc2..804749a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -174,3 +174,4 @@ cython_debug/
.pypirc
stablegen/feather.oso
stablegen.zip
+ref/
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index b64ee3f..0c20fa9 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -24,7 +24,7 @@ from .texturing.rendering import (
from .texturing.orbit_export import ExportOrbitGIF
from .texturing.game_export import ExportForGameEngine
from .cameras import (
- AddCameras, CloneCamera, MirrorCamera, ToggleCameraLabels,
+ AddCameras, ApplyAutoAspect, CloneCamera, MirrorCamera, ToggleCameraLabels,
CollectCameraPrompts,
CameraPromptItem, CameraOrderItem, SG_UL_CameraOrderList, SyncCameraOrder,
MoveCameraOrder, ApplyCameraOrderPreset,
@@ -35,6 +35,7 @@ from .texturing.generator import (
ComfyUIGenerate, Reproject, Regenerate, MirrorReproject,
)
from .mesh_gen.trellis2 import Trellis2Generate
+from .dae_import import DAE_IMPORT_CLASSES
# -- Core / UI sub-packages ----------------------------------------------
from .core.preferences import (
@@ -94,6 +95,7 @@ classes = [
# Operators - render tools
BakeTextures,
AddCameras,
+ ApplyAutoAspect,
CloneCamera,
MirrorCamera,
ToggleCameraLabels,
@@ -109,6 +111,8 @@ classes = [
AddHDRI,
ApplyModifiers,
CurvesToMesh,
+ # Operators - DAE import
+ *DAE_IMPORT_CLASSES,
# Operators - presets / panel
ApplyPreset,
SavePreset,
diff --git a/stablegen/cameras/__init__.py b/stablegen/cameras/__init__.py
index 05bc781..c91f103 100644
--- a/stablegen/cameras/__init__.py
+++ b/stablegen/cameras/__init__.py
@@ -25,6 +25,7 @@ from .placement import AddCameras # noqa: F401
# -- operators.py -------------------------------------------------------------
from .operators import ( # noqa: F401
switch_viewport_to_camera,
+ ApplyAutoAspect,
CloneCamera,
MirrorCamera,
ToggleCameraLabels,
diff --git a/stablegen/cameras/operators.py b/stablegen/cameras/operators.py
index 5d58aca..49c4ccf 100644
--- a/stablegen/cameras/operators.py
+++ b/stablegen/cameras/operators.py
@@ -9,7 +9,113 @@ from .overlays import (
_sg_ensure_crop_overlay, _sg_remove_crop_overlay,
_setup_square_camera_display,
)
-from .geometry import _store_per_camera_resolution
+from .geometry import (
+ _store_per_camera_resolution,
+ _gather_target_meshes, _get_mesh_verts_world,
+ _compute_per_camera_aspect, _resolution_from_aspect,
+ _get_fov, _compute_silhouette_distance, _perspective_aspect,
+ _camera_basis, _rotation_from_basis, _get_resolution_align
+)
+import numpy as np
+
+class ApplyAutoAspect(bpy.types.Operator):
+ """Apply automatic aspect ratio and framing to selected cameras based on object silhouette.
+
+ If no camera is selected, applies to all cameras in the 'sg_cameras' collection."""
+ bl_idname = "object.apply_auto_aspect"
+ bl_label = "Apply Auto Aspect"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ @classmethod
+ def poll(cls, context):
+ return any(o.type == 'CAMERA' for o in context.scene.objects) and not sg_modal_active(context)
+
+ def execute(self, context):
+ cameras = [o for o in context.selected_objects if o.type == 'CAMERA']
+ if not cameras:
+ col = bpy.data.collections.get("sg_cameras")
+ if col:
+ cameras = [o for o in col.objects if o.type == 'CAMERA']
+ else:
+ cameras = [o for o in context.scene.objects if o.type == 'CAMERA']
+
+ if not cameras:
+ self.report({'WARNING'}, "No cameras found")
+ return {'CANCELLED'}
+
+ target_meshes = _gather_target_meshes(context)
+ if not target_meshes:
+ self.report({'WARNING'}, "No target meshes found for silhouette calculation")
+ return {'CANCELLED'}
+
+ verts_world = _get_mesh_verts_world(target_meshes)
+ center_for_aspect = verts_world.mean(axis=0)
+ center_np = center_for_aspect
+ center_vec = mathutils.Vector(center_np.tolist())
+
+ render = context.scene.render
+ total_px = render.resolution_x * render.resolution_y
+ align = _get_resolution_align(context)
+
+ updated_count = 0
+ for cam_obj in cameras:
+ cam_settings = cam_obj.data
+ mat = cam_obj.matrix_world
+ # Extract direction: 'd' in the placement geometry logic points FROM the object TO the camera.
+ # Since the camera looks down its local -Z, the local +Z points back towards the camera.
+ d_vec = mathutils.Vector(mat.col[2][:3])
+ d_np = np.array([d_vec.x, d_vec.y, d_vec.z], dtype=float)
+ norm = np.linalg.norm(d_np)
+ if norm < 1e-6:
+ continue
+ d_unit = d_np / norm
+
+ # --- Pass 1: orthographic aspect as initial estimate ---
+ aspect = _compute_per_camera_aspect(d_unit, verts_world, center_for_aspect)
+ res_x, res_y = _resolution_from_aspect(aspect, total_px, align=align)
+ fov_x, fov_y = _get_fov(cam_settings, context, res_x, res_y)
+ dist, aim_off = _compute_silhouette_distance(
+ verts_world, center_np, d_np, fov_x, fov_y)
+
+ # --- Pass 2: refine aspect from actual perspective camera pos ---
+ aim_point_np = center_np + aim_off
+ cam_pos_np = aim_point_np + d_unit * dist
+ aspect = _perspective_aspect(verts_world, cam_pos_np, d_np)
+ res_x, res_y = _resolution_from_aspect(aspect, total_px, align=align)
+ fov_x, fov_y = _get_fov(cam_settings, context, res_x, res_y)
+ dist, aim_off = _compute_silhouette_distance(
+ verts_world, center_np, d_np, fov_x, fov_y)
+
+ dir_vec = mathutils.Vector(d_np.tolist()).normalized()
+ aim_point = center_vec + mathutils.Vector(aim_off.tolist())
+ pos = aim_point + dir_vec * dist
+
+ # Apply new transform (world-space — works even with parented cameras)
+ right, up_v, d_unit_cam = _camera_basis(d_np)
+ cam_obj.matrix_world = mathutils.Matrix.LocRotScale(
+ pos,
+ _rotation_from_basis(right, up_v, d_unit_cam).to_quaternion(),
+ None,
+ )
+
+ # Store per-camera resolution
+ _store_per_camera_resolution(cam_obj, res_x, res_y)
+ _setup_square_camera_display(cam_obj, res_x, res_y)
+ updated_count += 1
+
+ # Set scene to max square resolution for viewport display
+ all_sg_cams = [o for o in context.scene.objects if o.type == 'CAMERA' and 'sg_res_x' in o]
+ if all_sg_cams:
+ max_side = max(
+ max(int(c.get('sg_res_x', 0)), int(c.get('sg_res_y', 0)))
+ for c in all_sg_cams
+ )
+ if max_side > 0:
+ context.scene.render.resolution_x = max_side
+ context.scene.render.resolution_y = max_side
+
+ self.report({'INFO'}, f"Applied Auto Aspect to {updated_count} camera(s)")
+ return {'FINISHED'}
def switch_viewport_to_camera(context, camera):
"""Switches the first found 3D viewport to the specified camera's view."""
diff --git a/stablegen/dae_import/__init__.py b/stablegen/dae_import/__init__.py
new file mode 100644
index 0000000..4206b2d
--- /dev/null
+++ b/stablegen/dae_import/__init__.py
@@ -0,0 +1,10 @@
+"""DAE (COLLADA) import and preprocessing for StableGen.
+
+Provides a custom XML-based COLLADA importer that works across all Blender
+versions (including 5.x where the built-in Collada importer was removed),
+plus geometry cleanup utilities tailored for SketchUp exports.
+"""
+
+from .operators import DAE_IMPORT_CLASSES
+
+__all__ = ["DAE_IMPORT_CLASSES"]
diff --git a/stablegen/dae_import/cleanup.py b/stablegen/dae_import/cleanup.py
new file mode 100644
index 0000000..9214d39
--- /dev/null
+++ b/stablegen/dae_import/cleanup.py
@@ -0,0 +1,353 @@
+"""Geometry cleanup utilities for imported DAE meshes.
+
+Addresses SketchUp-specific issues:
+- Duplicate/overlapping faces from component boundaries
+- Coincident vertices at joins
+- Non-manifold geometry
+- Inconsistent normals
+- Excessive/conflicting materials
+"""
+
+import bpy # pylint: disable=import-error
+import bmesh # pylint: disable=import-error
+import mathutils # pylint: disable=import-error
+
+
+def remove_exact_duplicate_faces(obj, precision=5):
+ """Remove faces that share the exact same vertex positions.
+
+ Uses high-precision coordinate rounding to detect true duplicates
+ without affecting intentional nearby geometry. Also removes faces
+ that share the same vertex objects (detected after merge-by-distance).
+ """
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.mode_set(mode='EDIT')
+
+ bm = bmesh.from_edit_mesh(obj.data)
+ bm.faces.ensure_lookup_table()
+
+ seen = {}
+ duplicates = []
+
+ for face in bm.faces:
+ # Key 1: sorted vertex indices (catches faces sharing same verts after merge)
+ vert_key = tuple(sorted(v.index for v in face.verts))
+ # Key 2: sorted rounded positions (catches faces with coincident but separate verts)
+ pos_key = tuple(sorted(
+ (round(v.co.x, precision),
+ round(v.co.y, precision),
+ round(v.co.z, precision))
+ for v in face.verts
+ ))
+
+ if vert_key in seen or pos_key in seen:
+ duplicates.append(face)
+ else:
+ seen[vert_key] = face
+ seen[pos_key] = face
+
+ removed = len(duplicates)
+ for f in duplicates:
+ bm.faces.remove(f)
+
+ bmesh.update_edit_mesh(obj.data)
+ bpy.ops.object.mode_set(mode='OBJECT')
+ return removed
+
+
+def remove_coplanar_overlapping_faces(obj, distance_threshold=0.001, normal_threshold=0.95):
+ """Remove overlapping coplanar faces from different SketchUp components.
+
+ Detects overlapping faces by checking if any face's centroid lies
+ very close to (and is coplanar with) another face. When two faces
+ occupy the same space, the smaller one (or back-facing one) is removed.
+
+ This catches overlapping geometry even when faces have different
+ tessellation patterns.
+ """
+ bpy.context.view_layer.objects.active = obj
+
+ bm = bmesh.new()
+ bm.from_mesh(obj.data)
+ bm.faces.ensure_lookup_table()
+
+ from mathutils.bvhtree import BVHTree
+
+ bvh = BVHTree.FromBMesh(bm)
+
+ to_remove = set()
+
+ for face in bm.faces:
+ if face.index in to_remove:
+ continue
+
+ center = face.calc_center_median()
+ normal = face.normal
+
+ # Cast a short ray forward and backward from the face center
+ # to find very close parallel/anti-parallel faces
+ for direction in (normal, -normal):
+ origin = center + direction * 0.0001
+ hit_loc, hit_normal, hit_idx, hit_dist = bvh.ray_cast(origin, direction, distance_threshold)
+
+ if hit_loc is None or hit_idx is None:
+ continue
+ if hit_idx == face.index or hit_idx in to_remove:
+ continue
+
+ # Check if hit face is nearly coplanar (parallel or anti-parallel normal)
+ hit_face = bm.faces[hit_idx]
+ dot = normal.dot(hit_face.normal)
+
+ if abs(dot) > normal_threshold:
+ # Skip faces that share vertices — they are connected
+ # geometry (e.g. window mullions), not true overlaps
+ face_verts = set(v.index for v in face.verts)
+ hit_verts = set(v.index for v in hit_face.verts)
+ if face_verts & hit_verts:
+ continue
+
+ # Faces are coplanar and very close — one is a duplicate
+ # Remove the one with anti-parallel normal (back-face)
+ # or the smaller one if normals are parallel
+ if dot < 0:
+ # Anti-parallel normals — back face
+ to_remove.add(hit_idx)
+ else:
+ # Parallel normals — keep the larger face
+ if face.calc_area() < hit_face.calc_area():
+ to_remove.add(face.index)
+ else:
+ to_remove.add(hit_idx)
+
+ # Remove marked faces
+ faces_to_remove = [bm.faces[i] for i in to_remove if i < len(bm.faces)]
+ removed = len(faces_to_remove)
+
+ for f in faces_to_remove:
+ bm.faces.remove(f)
+
+ bm.to_mesh(obj.data)
+ bm.free()
+ obj.data.update()
+ return removed
+
+
+def merge_coincident_vertices(obj, threshold=0.0001):
+ """Merge vertices that are essentially at the same position.
+
+ Uses a very conservative threshold (0.1mm default) to avoid
+ destroying any intentional detail. Also removes degenerate faces
+ left behind after the merge.
+ """
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.mode_set(mode='EDIT')
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.remove_doubles(threshold=threshold)
+ # Clean up degenerate geometry left after merge
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.dissolve_degenerate(threshold=threshold)
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+
+def remove_loose_geometry(obj):
+ """Remove loose vertices and edges (no faces attached)."""
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.mode_set(mode='EDIT')
+
+ # Remove wire edges (edges with no connected faces) via bmesh
+ # — select_loose won't catch these if their vertices are shared
+ # with faced edges
+ bm = bmesh.from_edit_mesh(obj.data)
+ wire_edges = [e for e in bm.edges if not e.link_faces]
+ if wire_edges:
+ bmesh.ops.delete(bm, geom=wire_edges, context='EDGES')
+ bmesh.update_edit_mesh(obj.data)
+
+ # Remove truly loose verts (no edges at all)
+ bpy.ops.mesh.select_all(action='DESELECT')
+ bpy.ops.mesh.select_loose()
+ bpy.ops.mesh.delete(type='VERT')
+
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+
+def fix_normals(obj):
+ """Recalculate normals to face consistently outward."""
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.mode_set(mode='EDIT')
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.normals_make_consistent(inside=False)
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+
+def remove_interior_faces(obj, ray_samples=14):
+ """Remove faces that are fully enclosed inside the mesh.
+
+ Casts rays outward from face centers in multiple directions;
+ if all rays hit another face of the same mesh, the face is
+ considered interior (internal wall/partition).
+ """
+ bpy.context.view_layer.objects.active = obj
+
+ bm = bmesh.new()
+ bm.from_mesh(obj.data)
+ bm.faces.ensure_lookup_table()
+
+ from mathutils.bvhtree import BVHTree
+
+ bvh = BVHTree.FromBMesh(bm)
+
+ # Generate ray directions: 6 axis-aligned + 8 diagonal corners
+ directions = [
+ mathutils.Vector((1, 0, 0)),
+ mathutils.Vector((-1, 0, 0)),
+ mathutils.Vector((0, 1, 0)),
+ mathutils.Vector((0, -1, 0)),
+ mathutils.Vector((0, 0, 1)),
+ mathutils.Vector((0, 0, -1)),
+ mathutils.Vector((1, 1, 1)).normalized(),
+ mathutils.Vector((-1, 1, 1)).normalized(),
+ mathutils.Vector((1, -1, 1)).normalized(),
+ mathutils.Vector((-1, -1, 1)).normalized(),
+ mathutils.Vector((1, 1, -1)).normalized(),
+ mathutils.Vector((-1, 1, -1)).normalized(),
+ mathutils.Vector((1, -1, -1)).normalized(),
+ mathutils.Vector((-1, -1, -1)).normalized(),
+ ]
+
+ # Find candidate faces where all rays are blocked (no distance limit)
+ candidate_indices = set()
+ for face in bm.faces:
+ center = face.calc_center_median()
+ normal = face.normal
+ all_blocked = True
+
+ for d in directions:
+ # Offset origin slightly along face normal to avoid self-hit
+ origin = center + normal * 0.001
+ hit_loc, hit_normal, hit_idx, hit_dist = bvh.ray_cast(origin, d)
+ if hit_loc is None:
+ all_blocked = False
+ break
+
+ if all_blocked:
+ candidate_indices.add(face.index)
+
+ if not candidate_indices:
+ bm.free()
+ return 0
+
+ # Group candidates into edge-connected clusters.
+ # Interior partitions form large contiguous surfaces while window
+ # glass panes are small isolated patches. Only remove large clusters.
+ visited = set()
+ clusters = []
+ for start_idx in candidate_indices:
+ if start_idx in visited:
+ continue
+ cluster = []
+ queue = [start_idx]
+ while queue:
+ idx = queue.pop()
+ if idx in visited or idx not in candidate_indices:
+ continue
+ visited.add(idx)
+ cluster.append(idx)
+ for edge in bm.faces[idx].edges:
+ for linked_face in edge.link_faces:
+ if linked_face.index not in visited and linked_face.index in candidate_indices:
+ queue.append(linked_face.index)
+ clusters.append(cluster)
+
+ # Only remove clusters whose total area exceeds 2% of the full mesh area
+ total_area = sum(f.calc_area() for f in bm.faces)
+ min_cluster_area = total_area * 0.02
+
+ interior = []
+ for cluster in clusters:
+ cluster_area = sum(bm.faces[idx].calc_area() for idx in cluster)
+ if cluster_area >= min_cluster_area:
+ interior.extend(bm.faces[idx] for idx in cluster)
+
+ removed = len(interior)
+ for f in interior:
+ bm.faces.remove(f)
+
+ bm.to_mesh(obj.data)
+ bm.free()
+ obj.data.update()
+ return removed
+
+
+def strip_materials_and_apply_clean(obj):
+ """Remove all materials and assign a single clean Principled BSDF.
+
+ This ensures compatibility with StableGen's projection/baking system.
+ """
+ # Clear all material slots
+ obj.data.materials.clear()
+
+ # Create a clean material
+ mat = bpy.data.materials.new(name="SG_DAE_Material")
+ mat.use_nodes = True
+ tree = mat.node_tree
+ nodes = tree.nodes
+ nodes.clear()
+
+ # Create Principled BSDF + Output
+ bsdf = nodes.new("ShaderNodeBsdfPrincipled")
+ bsdf.location = (0, 0)
+ bsdf.inputs["Base Color"].default_value = (0.8, 0.8, 0.8, 1.0)
+
+ output = nodes.new("ShaderNodeOutputMaterial")
+ output.location = (300, 0)
+ tree.links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
+
+ obj.data.materials.append(mat)
+
+
+def join_all_meshes(context):
+ """Join all mesh objects in the scene into a single object.
+
+ Returns the resulting joined object, or None if no meshes found.
+ """
+ meshes = [obj for obj in context.scene.objects if obj.type == 'MESH']
+ if not meshes:
+ return None
+
+ # Deselect all, then select only mesh objects
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in meshes:
+ obj.select_set(True)
+ context.view_layer.objects.active = meshes[0]
+
+ if len(meshes) > 1:
+ bpy.ops.object.join()
+
+ return context.view_layer.objects.active
+
+
+def remove_edge_only_objects(context):
+ """Delete objects that have no faces (edge/vertex only geometry)."""
+ removed = 0
+ for obj in list(context.scene.objects):
+ if obj.type == 'MESH' and len(obj.data.polygons) == 0:
+ bpy.data.objects.remove(obj, do_unlink=True)
+ removed += 1
+ return removed
+
+
+def auto_smooth_shading(obj, angle=30.0):
+ """Apply smooth shading with auto-smooth angle."""
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.shade_smooth()
+
+ # Blender 4.x+: use auto smooth via modifier or mesh attribute
+ import math
+ try:
+ # Blender 4.1+
+ obj.data.use_auto_smooth = True
+ obj.data.auto_smooth_angle = math.radians(angle)
+ except AttributeError:
+ pass
diff --git a/stablegen/dae_import/operators.py b/stablegen/dae_import/operators.py
new file mode 100644
index 0000000..4951700
--- /dev/null
+++ b/stablegen/dae_import/operators.py
@@ -0,0 +1,522 @@
+"""Blender operators for DAE import and preprocessing."""
+
+import os
+import bpy # pylint: disable=import-error
+
+from ..utils import sg_modal_active
+
+
+class ImportDAE(bpy.types.Operator):
+ """Import and preprocess a COLLADA (.dae) file for StableGen texturing."""
+
+ bl_idname = "stablegen.import_dae"
+ bl_label = "Import DAE for Texturing"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ filepath: bpy.props.StringProperty(
+ name="File Path",
+ description="Path to the .dae file to import",
+ subtype='FILE_PATH',
+ ) # type: ignore
+
+ directory: bpy.props.StringProperty(
+ subtype='DIR_PATH',
+ ) # type: ignore
+
+ filter_glob: bpy.props.StringProperty(
+ default="*.dae",
+ options={'HIDDEN'},
+ ) # type: ignore
+
+ # ── Cleanup options ──
+
+ merge_threshold: bpy.props.FloatProperty(
+ name="Merge Distance",
+ description=(
+ "Distance below which vertices are considered coincident and merged. "
+ "Default 1mm is safe for architectural models"
+ ),
+ default=0.001,
+ min=0.0,
+ max=0.1,
+ precision=4,
+ unit='LENGTH',
+ ) # type: ignore
+
+ remove_interior: bpy.props.BoolProperty(
+ name="Remove Interior Faces",
+ description="Detect and remove faces fully enclosed inside the mesh (internal walls/partitions)",
+ default=True,
+ ) # type: ignore
+
+ strip_materials: bpy.props.BoolProperty(
+ name="Replace Materials",
+ description="Strip all imported materials and apply a clean Principled BSDF",
+ default=True,
+ ) # type: ignore
+
+ # ── Topology options ──
+
+ topology_method: bpy.props.EnumProperty(
+ name="Topology",
+ description="Method to improve mesh topology after cleanup",
+ items=[
+ ('NONE', "None", "Keep original topology. No changes"),
+ ('FIX_FANS', "Fix Triangle Fans",
+ "Only fixes fan patterns (many triangles radiating from one vertex) "
+ "on flat surfaces. Keeps the rest of the topology intact. "
+ "Also subdivides any remaining large faces"),
+ ('SUBDIVIDE_ONLY', "Subdivide Large Faces",
+ "Subdivide only faces above a threshold area. Keeps existing topology"),
+ ('PLANAR_SUBDIVIDE', "Dissolve + Subdivide",
+ "Merge coplanar triangles then retriangulate. "
+ "WARNING: can create poor triangulation on large flat walls"),
+ ('VOXEL', "Voxel Remesh",
+ "Full remesh with uniform voxel size. Gives clean topology "
+ "but loses sharp edges"),
+ ],
+ default='FIX_FANS',
+ ) # type: ignore
+
+ edge_ratio: bpy.props.FloatProperty(
+ name="Edge Ratio",
+ description=(
+ "Edges longer than median length × this ratio get split. "
+ "Lower = more uniform triangles but higher poly count"
+ ),
+ default=2.5,
+ min=1.5,
+ max=10.0,
+ precision=1,
+ ) # type: ignore
+
+ equalize_iterations: bpy.props.IntProperty(
+ name="Equalize Passes",
+ description=(
+ "Number of edge-splitting passes to equalize triangle density. "
+ "More passes = more uniform but higher poly count"
+ ),
+ default=4,
+ min=0,
+ max=10,
+ ) # type: ignore
+
+ voxel_size: bpy.props.FloatProperty(
+ name="Voxel Size",
+ description="Voxel size for remesh (0 = auto-calculate from bounding box)",
+ default=0.0,
+ min=0.0,
+ max=1.0,
+ precision=4,
+ unit='LENGTH',
+ ) # type: ignore
+
+ # ── Scale / orientation ──
+
+ auto_scale: bpy.props.FloatProperty(
+ name="Target Size (BU)",
+ description=(
+ "Scale the imported model so its largest dimension equals this value "
+ "in Blender Units. Set to 0 to keep the original scale"
+ ),
+ default=0.0,
+ min=0.0,
+ max=100.0,
+ ) # type: ignore
+
+ shading_mode: bpy.props.EnumProperty(
+ name="Shading",
+ description="Shading mode for the imported model",
+ items=[
+ ('FLAT', "Flat", "Flat shading (sharp edges, best for architecture)"),
+ ('SMOOTH', "Smooth", "Smooth shading"),
+ ('AUTO', "Auto Smooth", "Smooth shading with auto-smooth angle"),
+ ],
+ default='FLAT',
+ ) # type: ignore
+
+ center_origin: bpy.props.BoolProperty(
+ name="Center at Origin",
+ description="Move the imported model so its center is at the world origin",
+ default=True,
+ ) # type: ignore
+
+ join_meshes: bpy.props.BoolProperty(
+ name="Join Meshes",
+ description="Join all imported mesh parts into a single object",
+ default=True,
+ ) # type: ignore
+
+ triangulate: bpy.props.BoolProperty(
+ name="Triangulate",
+ description="Convert all faces to triangles (required for VR and best for UV projection)",
+ default=True,
+ ) # type: ignore
+
+ @classmethod
+ def poll(cls, context):
+ return not sg_modal_active(context)
+
+ def invoke(self, context, event):
+ context.window_manager.fileselect_add(self)
+ return {'RUNNING_MODAL'}
+
+ def draw(self, context):
+ layout = self.layout
+
+ layout.label(text="Cleanup", icon='BRUSH_DATA')
+ box = layout.box()
+ box.prop(self, "merge_threshold")
+ box.prop(self, "remove_interior")
+ box.prop(self, "strip_materials")
+ box.prop(self, "join_meshes")
+ box.prop(self, "triangulate")
+
+ layout.separator()
+ layout.label(text="Topology", icon='MOD_REMESH')
+ box = layout.box()
+ box.prop(self, "topology_method")
+ if self.topology_method == 'FIX_FANS':
+ box.prop(self, "edge_ratio")
+ box.prop(self, "equalize_iterations")
+ elif self.topology_method == 'VOXEL':
+ box.prop(self, "voxel_size")
+
+ layout.separator()
+ layout.label(text="Transform", icon='OBJECT_ORIGIN')
+ box = layout.box()
+ box.prop(self, "auto_scale")
+ box.prop(self, "shading_mode")
+ box.prop(self, "center_origin")
+
+ def execute(self, context):
+ if not self.filepath or not os.path.isfile(self.filepath):
+ self.report({'ERROR'}, "No valid .dae file selected")
+ return {'CANCELLED'}
+
+ import time
+ t0 = time.monotonic()
+
+ # ── Stage 1: Parse & Import ──
+ from .parser import ColladaParser
+
+ name_prefix = os.path.splitext(os.path.basename(self.filepath))[0]
+ parser = ColladaParser(self.filepath)
+ parser.parse()
+
+ if not parser.instances:
+ self.report({'WARNING'}, "No geometry found in the COLLADA file")
+ return {'CANCELLED'}
+
+ created = parser.create_blender_objects(context, name_prefix=name_prefix)
+ if not created:
+ self.report({'WARNING'}, "No mesh faces could be created from the file")
+ return {'CANCELLED'}
+
+ self.report({'INFO'}, f"Imported {len(created)} mesh objects")
+
+ # ── Stage 2: Remove edge-only objects ──
+ from . import cleanup
+
+ edge_removed = cleanup.remove_edge_only_objects(context)
+ if edge_removed:
+ self.report({'INFO'}, f"Removed {edge_removed} edge-only objects")
+
+ # Refresh the created list (some may have been removed)
+ created = [obj for obj in context.scene.objects
+ if obj.type == 'MESH' and obj.name.startswith(name_prefix)]
+
+ if not created:
+ self.report({'WARNING'}, "All imported geometry was edge-only (no faces)")
+ return {'CANCELLED'}
+
+ # ── Stage 3: Join meshes ──
+ if self.join_meshes and len(created) > 1:
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in created:
+ obj.select_set(True)
+ context.view_layer.objects.active = created[0]
+ bpy.ops.object.join()
+ created = [context.view_layer.objects.active]
+
+ # ── Stage 3b: Center at origin (sit on floor) ──
+ if self.center_origin:
+ import mathutils as _mu # pylint: disable=import-error
+ for obj in created:
+ bpy.ops.object.select_all(action='DESELECT')
+ obj.select_set(True)
+ context.view_layer.objects.active = obj
+ # Compute world-space bounding box
+ corners = [obj.matrix_world @ _mu.Vector(c) for c in obj.bound_box]
+ xs = [c.x for c in corners]
+ ys = [c.y for c in corners]
+ zs = [c.z for c in corners]
+ # Center XY, put bottom at Z=0
+ center_x = (min(xs) + max(xs)) / 2
+ center_y = (min(ys) + max(ys)) / 2
+ bottom_z = min(zs)
+ obj.location.x -= center_x
+ obj.location.y -= center_y
+ obj.location.z -= bottom_z
+
+ # ── Stage 4: Geometry cleanup ──
+ for obj in created:
+ # Merge coincident vertices
+ if self.merge_threshold > 0:
+ cleanup.merge_coincident_vertices(obj, self.merge_threshold)
+
+ # Remove exact duplicate faces (same verts or same positions)
+ dup_removed = cleanup.remove_exact_duplicate_faces(obj)
+ if dup_removed:
+ self.report({'INFO'}, f"Removed {dup_removed} duplicate faces from {obj.name}")
+
+ # Remove coplanar overlapping faces (different tessellation, same surface)
+ overlap_removed = cleanup.remove_coplanar_overlapping_faces(obj)
+ if overlap_removed:
+ self.report({'INFO'}, f"Removed {overlap_removed} coplanar overlaps from {obj.name}")
+
+ # Remove loose geometry
+ cleanup.remove_loose_geometry(obj)
+
+ # Fix normals
+ cleanup.fix_normals(obj)
+
+ # Remove interior faces (internal walls/partitions)
+ if self.remove_interior:
+ int_removed = cleanup.remove_interior_faces(obj)
+ if int_removed:
+ self.report({'INFO'}, f"Removed {int_removed} interior faces from {obj.name}")
+ # Clean up loose edges/verts left behind by face removal
+ cleanup.remove_loose_geometry(obj)
+
+ # ── Stage 5: Topology improvement ──
+ if self.topology_method != 'NONE':
+ from . import topology
+
+ for obj in created:
+ if self.topology_method == 'FIX_FANS':
+ topology.fix_triangle_fans(
+ obj,
+ max_edge_ratio=self.edge_ratio,
+ equalize_iterations=self.equalize_iterations,
+ )
+ elif self.topology_method == 'PLANAR_SUBDIVIDE':
+ topology.auto_improve_topology(obj, method='planar_subdivide')
+ elif self.topology_method == 'SUBDIVIDE_ONLY':
+ topology.auto_improve_topology(obj, method='subdivide_only')
+ elif self.topology_method == 'VOXEL':
+ topology.voxel_remesh(obj, voxel_size=self.voxel_size)
+
+ # ── Stage 5b: Triangulate ──
+ if self.triangulate and self.topology_method != 'FIX_FANS':
+ # FIX_FANS already triangulates; skip to avoid double-triangulation
+ for obj in created:
+ bpy.context.view_layer.objects.active = obj
+ obj.select_set(True)
+ bpy.ops.object.mode_set(mode='EDIT')
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+ # ── Stage 6: Materials ──
+ if self.strip_materials:
+ for obj in created:
+ cleanup.strip_materials_and_apply_clean(obj)
+
+ # ── Stage 7: Scale ──
+ if self.auto_scale > 0:
+ self._apply_auto_scale(context, created, self.auto_scale)
+
+ # ── Stage 8: Shading ──
+ if self.shading_mode == 'SMOOTH':
+ for obj in created:
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.shade_smooth()
+ elif self.shading_mode == 'AUTO':
+ for obj in created:
+ cleanup.auto_smooth_shading(obj)
+ else: # FLAT
+ for obj in created:
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.shade_flat()
+
+ # ── Stage 9: Apply transforms ──
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in created:
+ obj.select_set(True)
+ if created:
+ context.view_layer.objects.active = created[0]
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+
+ elapsed = time.monotonic() - t0
+ verts = sum(len(o.data.vertices) for o in created)
+ faces = sum(len(o.data.polygons) for o in created)
+ self.report({'INFO'},
+ f"DAE import complete: {verts} verts, {faces} faces "
+ f"({elapsed:.1f}s)")
+
+ return {'FINISHED'}
+
+ @staticmethod
+ def _apply_auto_scale(context, objects, target_bu):
+ """Scale objects so the largest dimension equals target_bu."""
+ import mathutils # pylint: disable=import-error
+
+ all_corners = []
+ for obj in objects:
+ for corner in obj.bound_box:
+ all_corners.append(obj.matrix_world @ mathutils.Vector(corner))
+ if not all_corners:
+ return
+
+ xs = [c.x for c in all_corners]
+ ys = [c.y for c in all_corners]
+ zs = [c.z for c in all_corners]
+ extent = max(
+ max(xs) - min(xs),
+ max(ys) - min(ys),
+ max(zs) - min(zs),
+ )
+ if extent < 1e-6:
+ return
+
+ scale_factor = target_bu / extent
+ for obj in objects:
+ obj.scale *= scale_factor
+
+ # Apply scale
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in objects:
+ obj.select_set(True)
+ context.view_layer.objects.active = objects[0]
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+
+
+class BatchImportDAE(bpy.types.Operator):
+ """Batch import and preprocess all .dae files from a directory."""
+
+ bl_idname = "stablegen.batch_import_dae"
+ bl_label = "Batch Import DAE Files"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ directory: bpy.props.StringProperty(
+ name="Directory",
+ description="Directory containing .dae files",
+ subtype='DIR_PATH',
+ ) # type: ignore
+
+ filter_glob: bpy.props.StringProperty(
+ default="*.dae",
+ options={'HIDDEN'},
+ ) # type: ignore
+
+ export_format: bpy.props.EnumProperty(
+ name="Export Format",
+ description="Format to export each processed model",
+ items=[
+ ('GLB', ".glb", "glTF Binary"),
+ ('FBX', ".fbx", "FBX"),
+ ('NONE', "Don't Export", "Keep in scene only"),
+ ],
+ default='GLB',
+ ) # type: ignore
+
+ output_dir: bpy.props.StringProperty(
+ name="Output Directory",
+ description="Directory to save processed models (defaults to 'processed' subfolder)",
+ subtype='DIR_PATH',
+ default="",
+ ) # type: ignore
+
+ # Inherit cleanup/topology settings from ImportDAE
+ merge_threshold: bpy.props.FloatProperty(
+ name="Merge Distance", default=0.0001, min=0.0, max=0.1,
+ precision=5, unit='LENGTH',
+ ) # type: ignore
+
+ strip_materials: bpy.props.BoolProperty(
+ name="Replace Materials", default=True,
+ ) # type: ignore
+
+ topology_method: bpy.props.EnumProperty(
+ name="Topology",
+ items=[
+ ('NONE', "None", "Keep original topology"),
+ ('PLANAR_SUBDIVIDE', "Planar Dissolve + Subdivide", "Best for buildings"),
+ ('SUBDIVIDE_ONLY', "Subdivide Large Faces", "Conservative"),
+ ('VOXEL', "Voxel Remesh", "Full remesh"),
+ ],
+ default='PLANAR_SUBDIVIDE',
+ ) # type: ignore
+
+ auto_scale: bpy.props.FloatProperty(
+ name="Target Size (BU)", default=0.0, min=0.0, max=100.0,
+ ) # type: ignore
+
+ @classmethod
+ def poll(cls, context):
+ return not sg_modal_active(context)
+
+ def invoke(self, context, event):
+ context.window_manager.fileselect_add(self)
+ return {'RUNNING_MODAL'}
+
+ def execute(self, context):
+ if not self.directory or not os.path.isdir(self.directory):
+ self.report({'ERROR'}, "No valid directory selected")
+ return {'CANCELLED'}
+
+ dae_files = sorted(
+ f for f in os.listdir(self.directory)
+ if f.lower().endswith('.dae')
+ )
+ if not dae_files:
+ self.report({'WARNING'}, "No .dae files found in the directory")
+ return {'CANCELLED'}
+
+ out_dir = self.output_dir or os.path.join(self.directory, "processed")
+ if self.export_format != 'NONE':
+ os.makedirs(out_dir, exist_ok=True)
+
+ processed = 0
+ for filename in dae_files:
+ filepath = os.path.join(self.directory, filename)
+ name = os.path.splitext(filename)[0]
+
+ # Clear scene for each file
+ bpy.ops.object.select_all(action='SELECT')
+ bpy.ops.object.delete(use_global=False)
+
+ # Use the single-file operator logic
+ bpy.ops.stablegen.import_dae(
+ filepath=filepath,
+ merge_threshold=self.merge_threshold,
+ remove_interior=False,
+ strip_materials=self.strip_materials,
+ topology_method=self.topology_method,
+ auto_scale=self.auto_scale,
+ shading_mode='FLAT',
+ join_meshes=True,
+ )
+
+ # Export if requested
+ if self.export_format == 'GLB':
+ out_path = os.path.join(out_dir, f"{name}.glb")
+ bpy.ops.export_scene.gltf(filepath=out_path)
+ self.report({'INFO'}, f"Exported: {out_path}")
+ elif self.export_format == 'FBX':
+ out_path = os.path.join(out_dir, f"{name}.fbx")
+ bpy.ops.export_scene.fbx(filepath=out_path)
+ self.report({'INFO'}, f"Exported: {out_path}")
+
+ processed += 1
+
+ self.report({'INFO'}, f"Batch processed {processed} DAE files")
+ return {'FINISHED'}
+
+
+# Classes to register with Blender
+DAE_IMPORT_CLASSES = [
+ ImportDAE,
+ BatchImportDAE,
+]
diff --git a/stablegen/dae_import/parser.py b/stablegen/dae_import/parser.py
new file mode 100644
index 0000000..b5be74f
--- /dev/null
+++ b/stablegen/dae_import/parser.py
@@ -0,0 +1,425 @@
+"""XML-based COLLADA (.dae) parser.
+
+Parses the subset of COLLADA 1.4/1.5 used by SketchUp exports:
+- <library_geometries>: mesh positions, normals, texcoords, triangles
+- <library_visual_scenes>: scene graph with transforms
+- <library_nodes>: reusable component definitions (SketchUp components)
+- <library_materials> / <library_effects>: basic diffuse colors
+- Unit conversion (SketchUp uses inches)
+
+Creates Blender mesh objects via the bmesh API with no dependency on
+any deprecated Blender import operators.
+"""
+
+import xml.etree.ElementTree as ET
+import math
+from collections import defaultdict
+
+try:
+ import bpy # pylint: disable=import-error
+ import bmesh # pylint: disable=import-error
+ import mathutils # pylint: disable=import-error
+except ImportError:
+ pass # Allow importing outside Blender for testing
+
+NS = {"c": "http://www.collada.org/2005/11/COLLADASchema"}
+
+
+def _tag(name):
+ """Return namespace-qualified tag."""
+ return f"{{{NS['c']}}}{name}"
+
+
+def _find(elem, path):
+ return elem.find(path, NS)
+
+
+def _findall(elem, path):
+ return elem.findall(path, NS)
+
+
+def _parse_float_array(text):
+ """Parse a space-separated float string into a list of floats."""
+ return [float(x) for x in text.split()]
+
+
+def _parse_int_array(text):
+ """Parse a space-separated int string into a list of ints."""
+ return [int(x) for x in text.split()]
+
+
+def _parse_matrix(text):
+ """Parse a 16-float COLLADA matrix (row-major) into a mathutils.Matrix."""
+ vals = _parse_float_array(text)
+ if len(vals) != 16:
+ return mathutils.Matrix.Identity(4)
+ return mathutils.Matrix((
+ vals[0:4],
+ vals[4:8],
+ vals[8:12],
+ vals[12:16],
+ ))
+
+
+class _GeometryData:
+ """Parsed geometry: vertex positions, normals, UVs, and face groups."""
+ __slots__ = ("positions", "normals", "uvs", "face_groups")
+
+ def __init__(self):
+ self.positions = [] # list of (x, y, z)
+ self.normals = [] # list of (nx, ny, nz)
+ self.uvs = [] # list of (u, v)
+ self.face_groups = [] # list of {material, faces: [(v_indices, uv_indices, n_indices)]}
+
+
+class _MeshInstance:
+ """A geometry placed in the scene with a world transform."""
+ __slots__ = ("geo_id", "world_matrix", "material_map")
+
+ def __init__(self, geo_id, world_matrix, material_map=None):
+ self.geo_id = geo_id
+ self.world_matrix = world_matrix
+ self.material_map = material_map or {}
+
+
+class ColladaParser:
+ """Parse a COLLADA file and create Blender mesh objects."""
+
+ def __init__(self, filepath):
+ self.filepath = filepath
+ self.tree = ET.parse(filepath)
+ self.root = self.tree.getroot()
+
+ # Unit scale: COLLADA stores a <unit meter="X"> attribute
+ self.unit_scale = 1.0
+ self._parse_asset()
+
+ # Lookup tables populated during parsing
+ self.geometries = {} # id -> _GeometryData
+ self.library_nodes = {} # id -> ET Element
+ self.instances = [] # list of _MeshInstance
+
+ def _parse_asset(self):
+ """Extract unit scale and up-axis from <asset>."""
+ asset = _find(self.root, "c:asset")
+ if asset is not None:
+ unit = _find(asset, "c:unit")
+ if unit is not None:
+ meter = unit.get("meter")
+ if meter:
+ self.unit_scale = float(meter)
+
+ # ------------------------------------------------------------------
+ # Geometry parsing
+ # ------------------------------------------------------------------
+
+ def _parse_source(self, source_elem):
+ """Parse a <source> element, return (data_list, stride)."""
+ fa = _find(source_elem, "c:float_array")
+ if fa is None or fa.text is None:
+ return [], 3
+ data = _parse_float_array(fa.text)
+ accessor = _find(source_elem, "c:technique_common/c:accessor")
+ stride = int(accessor.get("stride", "3")) if accessor is not None else 3
+ return data, stride
+
+ def _parse_geometry(self, geo_elem):
+ """Parse a single <geometry> element into _GeometryData."""
+ geo = _GeometryData()
+ mesh_elem = _find(geo_elem, "c:mesh")
+ if mesh_elem is None:
+ return geo
+
+ # Build source lookup: id -> (data, stride)
+ sources = {}
+ for src in _findall(mesh_elem, "c:source"):
+ sid = src.get("id")
+ data, stride = self._parse_source(src)
+ sources[sid] = (data, stride)
+
+ # Parse <vertices> to find position/normal source bindings
+ vertices_elem = _find(mesh_elem, "c:vertices")
+ vert_id = vertices_elem.get("id") if vertices_elem is not None else None
+ pos_source_id = None
+ norm_source_id = None
+
+ if vertices_elem is not None:
+ for inp in _findall(vertices_elem, "c:input"):
+ semantic = inp.get("semantic")
+ src_ref = inp.get("source", "").lstrip("#")
+ if semantic == "POSITION":
+ pos_source_id = src_ref
+ elif semantic == "NORMAL":
+ norm_source_id = src_ref
+
+ # Extract positions
+ if pos_source_id and pos_source_id in sources:
+ data, stride = sources[pos_source_id]
+ for i in range(0, len(data), stride):
+ geo.positions.append(tuple(data[i:i + stride]))
+
+ # Extract normals from vertices binding
+ if norm_source_id and norm_source_id in sources:
+ data, stride = sources[norm_source_id]
+ for i in range(0, len(data), stride):
+ geo.normals.append(tuple(data[i:i + stride]))
+
+ # Parse <triangles> and <polylist> elements
+ for prim_tag in ("c:triangles", "c:polylist"):
+ for prim in _findall(mesh_elem, prim_tag):
+ group = self._parse_primitive(prim, sources, vert_id,
+ geo.positions, geo.normals, geo.uvs)
+ if group and group["faces"]:
+ geo.face_groups.append(group)
+
+ return geo
+
+ def _parse_primitive(self, prim_elem, sources, vert_id, positions, normals, uvs):
+ """Parse a <triangles> or <polylist> element into a face group."""
+ count = int(prim_elem.get("count", "0"))
+ material = prim_elem.get("material", "")
+ if count == 0:
+ return None
+
+ # Determine input layout (which offsets map to which semantics)
+ inputs = _findall(prim_elem, "c:input")
+ max_offset = 0
+ vertex_offset = None
+ normal_offset = None
+ texcoord_offset = None
+ normal_source_id = None
+ texcoord_source_id = None
+
+ for inp in inputs:
+ semantic = inp.get("semantic")
+ offset = int(inp.get("offset", "0"))
+ src_ref = inp.get("source", "").lstrip("#")
+ max_offset = max(max_offset, offset)
+
+ if semantic == "VERTEX":
+ vertex_offset = offset
+ elif semantic == "NORMAL":
+ normal_offset = offset
+ normal_source_id = src_ref
+ elif semantic == "TEXCOORD":
+ texcoord_offset = offset
+ texcoord_source_id = src_ref
+
+ stride = max_offset + 1 # number of indices per vertex in <p>
+
+ # Parse normals from per-primitive source (if not in <vertices>)
+ prim_normals = []
+ if normal_source_id and normal_source_id in sources:
+ data, ns = sources[normal_source_id]
+ for i in range(0, len(data), ns):
+ prim_normals.append(tuple(data[i:i + ns]))
+
+ # Parse UVs
+ prim_uvs = []
+ if texcoord_source_id and texcoord_source_id in sources:
+ data, us = sources[texcoord_source_id]
+ for i in range(0, len(data), us):
+ prim_uvs.append(tuple(data[i:i + min(us, 2)]))
+
+ # Parse index array <p>
+ p_elem = _find(prim_elem, "c:p")
+ if p_elem is None or p_elem.text is None:
+ return None
+ p_data = _parse_int_array(p_elem.text)
+
+ # Determine face sizes
+ tag_local = prim_elem.tag.split("}")[-1] if "}" in prim_elem.tag else prim_elem.tag
+ if tag_local == "triangles":
+ vcount = [3] * count
+ else:
+ # <polylist> has a <vcount> element
+ vc_elem = _find(prim_elem, "c:vcount")
+ if vc_elem is None or vc_elem.text is None:
+ return None
+ vcount = _parse_int_array(vc_elem.text)
+
+ faces = []
+ idx = 0
+ for nv in vcount:
+ face_vert_indices = []
+ face_norm_indices = []
+ face_uv_indices = []
+ for _ in range(nv):
+ if idx + stride > len(p_data):
+ break
+ if vertex_offset is not None:
+ face_vert_indices.append(p_data[idx + vertex_offset])
+ if normal_offset is not None:
+ face_norm_indices.append(p_data[idx + normal_offset])
+ if texcoord_offset is not None:
+ face_uv_indices.append(p_data[idx + texcoord_offset])
+ idx += stride
+ if len(face_vert_indices) >= 3:
+ faces.append((face_vert_indices, face_norm_indices, face_uv_indices))
+
+ return {"material": material, "faces": faces,
+ "prim_normals": prim_normals, "prim_uvs": prim_uvs}
+
+ # ------------------------------------------------------------------
+ # Scene graph traversal
+ # ------------------------------------------------------------------
+
+ def _collect_library_nodes(self):
+ """Build lookup for <library_nodes> definitions."""
+ for node in _findall(self.root, ".//c:library_nodes/c:node"):
+ nid = node.get("id")
+ if nid:
+ self.library_nodes[nid] = node
+
+ def _traverse_node(self, node_elem, parent_matrix):
+ """Recursively walk a <node>, collecting mesh instances."""
+ # Compute this node's local transform
+ local_matrix = mathutils.Matrix.Identity(4)
+ mat_elem = _find(node_elem, "c:matrix")
+ if mat_elem is not None and mat_elem.text:
+ local_matrix = _parse_matrix(mat_elem.text)
+ else:
+ # Try decomposed transforms: translate, rotate, scale
+ for translate in _findall(node_elem, "c:translate"):
+ if translate.text:
+ vals = _parse_float_array(translate.text)
+ if len(vals) == 3:
+ t = mathutils.Matrix.Translation(vals)
+ local_matrix = local_matrix @ t
+ for rotate in _findall(node_elem, "c:rotate"):
+ if rotate.text:
+ vals = _parse_float_array(rotate.text)
+ if len(vals) == 4:
+ axis = mathutils.Vector(vals[:3])
+ angle = math.radians(vals[3])
+ r = mathutils.Matrix.Rotation(angle, 4, axis)
+ local_matrix = local_matrix @ r
+ for scale_elem in _findall(node_elem, "c:scale"):
+ if scale_elem.text:
+ vals = _parse_float_array(scale_elem.text)
+ if len(vals) == 3:
+ s = mathutils.Matrix.Diagonal((*vals, 1.0))
+ local_matrix = local_matrix @ s
+
+ world_matrix = parent_matrix @ local_matrix
+
+ # Collect instance_geometry references
+ for ig in _findall(node_elem, "c:instance_geometry"):
+ geo_url = ig.get("url", "").lstrip("#")
+ if geo_url:
+ # Parse material bindings
+ mat_map = {}
+ for im in _findall(ig, ".//c:instance_material"):
+ symbol = im.get("symbol", "")
+ target = im.get("target", "").lstrip("#")
+ if symbol and target:
+ mat_map[symbol] = target
+ self.instances.append(_MeshInstance(geo_url, world_matrix, mat_map))
+
+ # Resolve instance_node references (SketchUp components)
+ for in_node in _findall(node_elem, "c:instance_node"):
+ ref_url = in_node.get("url", "").lstrip("#")
+ if ref_url and ref_url in self.library_nodes:
+ self._traverse_node(self.library_nodes[ref_url], world_matrix)
+
+ # Recurse into child <node> elements
+ for child in _findall(node_elem, "c:node"):
+ self._traverse_node(child, world_matrix)
+
+ # ------------------------------------------------------------------
+ # Blender object creation
+ # ------------------------------------------------------------------
+
+ def parse(self):
+ """Parse the COLLADA file and populate internal data structures."""
+ # Parse all geometries
+ for geo_elem in _findall(self.root, ".//c:library_geometries/c:geometry"):
+ gid = geo_elem.get("id")
+ if gid:
+ self.geometries[gid] = self._parse_geometry(geo_elem)
+
+ # Build library_nodes lookup
+ self._collect_library_nodes()
+
+ # Walk visual scene
+ for vs in _findall(self.root, ".//c:library_visual_scenes/c:visual_scene"):
+ for node in _findall(vs, "c:node"):
+ self._traverse_node(node, mathutils.Matrix.Identity(4))
+
+ def create_blender_objects(self, context, name_prefix="DAE"):
+ """Create Blender mesh objects from parsed COLLADA data.
+
+ Returns list of created objects.
+ """
+ created = []
+ collection = context.collection or context.scene.collection
+
+ for i, inst in enumerate(self.instances):
+ geo = self.geometries.get(inst.geo_id)
+ if geo is None or not geo.positions or not geo.face_groups:
+ continue
+
+ mesh_name = f"{name_prefix}_{i:03d}"
+ mesh = bpy.data.meshes.new(mesh_name)
+ bm = bmesh.new()
+
+ # Add vertices with unit scaling and world transform
+ # Important: apply the world transform FIRST (in original units),
+ # THEN scale to meters. The COLLADA matrix translations are in
+ # the same unit system as the geometry positions.
+ scale = self.unit_scale
+ verts = []
+ for pos in geo.positions:
+ co = mathutils.Vector((pos[0], pos[1], pos[2]))
+ co = inst.world_matrix @ co
+ co = mathutils.Vector((co.x * scale, co.y * scale, co.z * scale))
+ verts.append(bm.verts.new(co))
+ bm.verts.ensure_lookup_table()
+ bm.verts.index_update()
+
+ # Collect all UVs from face groups
+ has_any_uvs = any(
+ grp.get("prim_uvs") and any(f[2] for f in grp["faces"])
+ for grp in geo.face_groups
+ )
+ uv_layer = None
+ if has_any_uvs:
+ uv_layer = bm.loops.layers.uv.new("UVMap")
+
+ # Add faces from each group
+ for grp in geo.face_groups:
+ prim_uvs = grp.get("prim_uvs", [])
+ for face_data in grp["faces"]:
+ v_indices, _n_indices, uv_indices = face_data
+ # Validate indices
+ if any(vi >= len(verts) or vi < 0 for vi in v_indices):
+ continue
+ face_verts = [verts[vi] for vi in v_indices]
+ # Skip degenerate faces
+ if len(set(id(v) for v in face_verts)) < 3:
+ continue
+ try:
+ face = bm.faces.new(face_verts)
+ except ValueError:
+ # Face already exists (duplicate)
+ continue
+ # Assign UVs
+ if uv_layer and uv_indices and prim_uvs:
+ for loop, uv_idx in zip(face.loops, uv_indices):
+ if uv_idx < len(prim_uvs):
+ uv = prim_uvs[uv_idx]
+ loop[uv_layer].uv = (uv[0], uv[1]) if len(uv) >= 2 else (0, 0)
+
+ if len(bm.faces) == 0:
+ bm.free()
+ continue
+
+ bm.to_mesh(mesh)
+ bm.free()
+ mesh.update()
+
+ obj = bpy.data.objects.new(mesh_name, mesh)
+ collection.objects.link(obj)
+ created.append(obj)
+
+ return created
diff --git a/stablegen/dae_import/topology.py b/stablegen/dae_import/topology.py
new file mode 100644
index 0000000..b907d9f
--- /dev/null
+++ b/stablegen/dae_import/topology.py
@@ -0,0 +1,213 @@
+"""Topology improvement utilities for imported DAE meshes.
+
+Addresses low-poly issues and bad topology from SketchUp:
+- Voxel remesh for clean topology
+- Planar decimation to simplify flat surfaces then subdivide
+- Adaptive subdivision for large faces
+- QuadriFlow remesh for high-quality quad topology
+"""
+
+import bpy # pylint: disable=import-error
+import bmesh # pylint: disable=import-error
+import math
+
+
+def voxel_remesh(obj, voxel_size=0.02):
+ """Apply voxel remesh to get clean, uniform topology.
+
+ Args:
+ obj: Blender mesh object.
+ voxel_size: Size of voxels in Blender units. Smaller = more detail.
+ """
+ bpy.context.view_layer.objects.active = obj
+ obj.select_set(True)
+
+ # Auto-calculate voxel size if not specified: ~1/100th of bounding box diagonal
+ if voxel_size <= 0:
+ bbox = obj.bound_box
+ dims = obj.dimensions
+ diagonal = math.sqrt(dims.x ** 2 + dims.y ** 2 + dims.z ** 2)
+ voxel_size = diagonal / 100.0
+
+ obj.data.remesh_voxel_size = voxel_size
+ bpy.ops.object.voxel_remesh()
+
+
+def subdivide_large_faces(obj, area_threshold=None, max_cuts=2):
+ """Subdivide faces that are larger than a threshold.
+
+ This addresses the low-poly problem where large flat faces cause
+ texture distortion. Only large faces are subdivided, preserving
+ detail in already-dense areas.
+
+ Args:
+ obj: Blender mesh object.
+ area_threshold: Minimum face area to subdivide. If None, auto-calculated
+ as 4x the median face area.
+ max_cuts: Number of subdivision cuts per large face.
+ """
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.mode_set(mode='EDIT')
+
+ bm = bmesh.from_edit_mesh(obj.data)
+ bm.faces.ensure_lookup_table()
+
+ if not bm.faces:
+ bpy.ops.object.mode_set(mode='OBJECT')
+ return
+
+ # Auto-calculate threshold from median face area
+ if area_threshold is None:
+ areas = sorted(f.calc_area() for f in bm.faces)
+ median_area = areas[len(areas) // 2]
+ area_threshold = median_area * 4.0
+
+ # Select only large faces
+ bpy.ops.mesh.select_all(action='DESELECT')
+ bm.faces.ensure_lookup_table()
+ selected_count = 0
+ for face in bm.faces:
+ if face.calc_area() > area_threshold:
+ face.select = True
+ selected_count += 1
+
+ bmesh.update_edit_mesh(obj.data)
+
+ if selected_count > 0:
+ bpy.ops.mesh.subdivide(number_cuts=max_cuts)
+
+ bpy.ops.object.mode_set(mode='OBJECT')
+ return selected_count
+
+
+def fix_triangle_fans(obj, max_edge_ratio=2.5, equalize_iterations=4):
+ """Fix triangle fan patterns by dissolving flat regions and retriangulating.
+
+ SketchUp creates fans where edges radiate from corner vertices across
+ entire walls. This function:
+ 1. Dissolves all edges between coplanar faces → wall polygons
+ 2. Retriangulates with BEAUTY (Delaunay-like, avoids star/fan shapes)
+ 3. Iteratively splits long edges to equalize triangle density
+ 4. Runs beautify_fill to flip remaining sub-optimal triangle edges
+
+ Args:
+ obj: Blender mesh object.
+ max_edge_ratio: Edges longer than median * this ratio get split.
+ equalize_iterations: Max rounds of edge-length equalization.
+ """
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.mode_set(mode='EDIT')
+
+ # Step 1: Dissolve all edges between coplanar faces.
+ # This completely removes the original fan topology, merging flat
+ # triangles back into their underlying wall/roof polygons.
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.dissolve_limited(angle_limit=math.radians(1.0))
+
+ # Step 2: Retriangulate with BEAUTY.
+ # BEAUTY uses a Delaunay-like algorithm that maximises minimum angles,
+ # producing roughly-equilateral triangles instead of fans.
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
+
+ # Step 3: Iteratively split edges that are much longer than the
+ # median, then retriangulate. Each pass halves the longest edges
+ # and redistributes triangles via BEAUTY.
+ for _ in range(equalize_iterations):
+ bm = bmesh.from_edit_mesh(obj.data)
+ bm.edges.ensure_lookup_table()
+
+ lengths = sorted(e.calc_length() for e in bm.edges)
+ if not lengths:
+ break
+ median_len = lengths[len(lengths) // 2]
+ threshold = median_len * max_edge_ratio
+
+ bpy.ops.mesh.select_all(action='DESELECT')
+ bm.edges.ensure_lookup_table()
+ long_count = 0
+ for edge in bm.edges:
+ if edge.calc_length() > threshold:
+ edge.select = True
+ long_count += 1
+ bmesh.update_edit_mesh(obj.data)
+
+ if long_count == 0:
+ break
+
+ # Subdivide only the long edges (adds midpoint vertices)
+ bpy.ops.mesh.subdivide(number_cuts=1)
+
+ # Retriangulate so BEAUTY can incorporate the new vertices
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
+
+ # Step 4: Final beautify pass — flips existing triangle edges to
+ # maximize minimum angles. This catches remaining fan-like
+ # connections that quads_convert_to_tris doesn't touch.
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.beautify_fill(angle_limit=math.radians(5))
+
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+
+def planar_decimate(obj, angle_limit=2.0):
+ """Dissolve edges between coplanar faces to simplify flat regions.
+
+ This is useful for SketchUp models where flat walls are unnecessarily
+ triangulated. Merges coplanar triangles into larger N-gons.
+
+ Uses a conservative angle limit (2°) to avoid dissolving edges at
+ window frames, door frames, and other intentional angle breaks.
+
+ Args:
+ obj: Blender mesh object.
+ angle_limit: Maximum angle (degrees) between face normals to consider
+ them coplanar.
+ """
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.mode_set(mode='EDIT')
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.dissolve_limited(angle_limit=math.radians(angle_limit))
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+
+def apply_subdivision_modifier(obj, levels=1):
+ """Add and apply a Subdivision Surface modifier.
+
+ Args:
+ obj: Blender mesh object.
+ levels: Subdivision levels to apply.
+ """
+ bpy.context.view_layer.objects.active = obj
+ mod = obj.modifiers.new(name="DAE_Subdiv", type='SUBSURF')
+ mod.levels = levels
+ mod.render_levels = levels
+ bpy.ops.object.modifier_apply(modifier=mod.name)
+
+
+def auto_improve_topology(obj, method='planar_subdivide'):
+ """High-level topology improvement combining multiple strategies.
+
+ Methods:
+ 'fix_fans': Only fix triangle fan patterns, keep rest of topology.
+ Best balance of quality and preservation.
+ 'planar_subdivide': Dissolve coplanar faces, then subdivide large ones.
+ Can create poor triangulation on large walls.
+ 'voxel': Voxel remesh at auto-calculated resolution. Gives clean uniform
+ topology but loses sharp edges. Good for organic shapes.
+ 'subdivide_only': Just subdivide large faces without topology changes.
+
+ Args:
+ obj: Blender mesh object.
+ method: One of 'fix_fans', 'planar_subdivide', 'voxel', 'subdivide_only'.
+ """
+ if method == 'fix_fans':
+ fix_triangle_fans(obj)
+ elif method == 'planar_subdivide':
+ planar_decimate(obj, angle_limit=2.0)
+ subdivide_large_faces(obj, max_cuts=2)
+ elif method == 'voxel':
+ voxel_remesh(obj, voxel_size=0) # auto-size
+ elif method == 'subdivide_only':
+ subdivide_large_faces(obj, max_cuts=2)
diff --git a/stablegen/mesh_gen/workflows.py b/stablegen/mesh_gen/workflows.py
index 799fd8f..7a45b76 100644
--- a/stablegen/mesh_gen/workflows.py
+++ b/stablegen/mesh_gen/workflows.py
@@ -74,6 +74,48 @@ class _Trellis2WorkflowMixin:
except OSError:
pass
+ @staticmethod
+ def _rasterize_alpha(image_path, background_color='black'):
+ """Flatten a PNG's alpha channel onto a solid background colour.
+
+ When BG removal is set to *Skip*, the user's image may still
+ contain arbitrary RGB data behind transparent pixels. Vision
+ encoders read raw RGB — not premultiplied data — so those
+ hidden pixels leak into the conditioning and corrupt the
+ generated shape.
+
+ This method composites the foreground onto *background_color*,
+ writes a new temp PNG (preserving the alpha channel for ComfyUI's
+ LoadImage mask output), and returns the path to that temp file.
+
+ If the image has no alpha channel, the original path is returned
+ unchanged.
+ """
+ import tempfile
+
+ img = Image.open(image_path)
+ if img.mode != 'RGBA':
+ return image_path # nothing to rasterize
+
+ bg_map = {'black': (0, 0, 0), 'gray': (128, 128, 128), 'white': (255, 255, 255)}
+ bg_rgb = bg_map.get(background_color, (0, 0, 0))
+
+ # Composite: result_rgb = fg_rgb * alpha + bg_rgb * (1 - alpha)
+ r, g, b, a = img.split()
+ bg = Image.new('RGB', img.size, bg_rgb)
+ bg.paste(img, mask=a)
+
+ # Re-attach the original alpha so ComfyUI's LoadImage still
+ # provides the correct mask output via its second slot.
+ result = bg.convert('RGBA')
+ result.putalpha(a)
+
+ fd, tmp_path = tempfile.mkstemp(suffix='.png', prefix='sg_rasterized_')
+ os.close(fd)
+ result.save(tmp_path, 'PNG')
+ print(f"[TRELLIS2] Rasterized alpha onto {background_color} background: {tmp_path}")
+ return tmp_path
+
@staticmethod
def _is_local_server(server_address):
"""Return True if server_address points to localhost."""
@@ -127,7 +169,31 @@ class _Trellis2WorkflowMixin:
# Upload the input image to ComfyUI
from .._generator_utils import upload_image_to_comfyui
+
+ # When BG removal is skipped, rasterize the image client-side:
+ # flatten the alpha channel onto the configured background colour so
+ # that invisible pixels behind the alpha don't leak into the
+ # conditioning encoder (which reads raw RGB, not premultiplied data).
+ skip_bg = getattr(context.scene, 'trellis2_bg_removal', 'auto') == 'skip'
+ rasterized_tmp = None
+ if skip_bg:
+ maybe_tmp = self._rasterize_alpha(
+ input_image_path,
+ getattr(context.scene, 'trellis2_background_color', 'black'),
+ )
+ if maybe_tmp != input_image_path:
+ rasterized_tmp = maybe_tmp
+ input_image_path = rasterized_tmp
+
image_info = upload_image_to_comfyui(server_address, input_image_path)
+
+ # Clean up the temp rasterized file after upload
+ if rasterized_tmp:
+ try:
+ os.remove(rasterized_tmp)
+ except OSError:
+ pass
+
if image_info is None:
self.operator._error = f"Failed to upload input image: {input_image_path}"
return {"error": self.operator._error}
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index b6513d7..2e071e1 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -154,6 +154,7 @@ class StableGenPanel(bpy.types.Panel):
cam_extra_row = layout.row(align=True)
cam_extra_row.operator("object.clone_camera", text="Clone Camera", icon="DUPLICATE")
cam_extra_row.operator("object.mirror_camera", text="Mirror", icon="MOD_MIRROR")
+ cam_extra_row.operator("object.apply_auto_aspect", text="Auto Aspect", icon="FULLSCREEN_ENTER")
cam_extra_row.operator("object.toggle_camera_labels", text="Labels", icon="FONT_DATA")
@@ -1859,6 +1860,12 @@ class StableGenPanel(bpy.types.Panel):
if width_mode == 'narrow':
row = tools_box.row()
row.operator("object.curves_to_mesh", text="Convert Curves to Mesh", icon="CURVE_DATA")
+
+ row = tools_box.row()
+ row.operator("stablegen.import_dae", text="Import DAE", icon="IMPORT")
+ if width_mode == 'narrow':
+ row = tools_box.row()
+ row.operator("stablegen.batch_import_dae", text="Batch Import DAE", icon="FILE_FOLDER")
row = tools_box.row()
if config_error_message: