from pathlib import Path from uuid import uuid4 import numpy as np import trimesh from scipy.sparse import coo_matrix from scipy.sparse.csgraph import breadth_first_order, connected_components DOWNLOAD_STEM = "skyebrowse-3d-model" def _edge_runs_forward(faces, start, end): start_position = np.argmax(faces == start[:, None], axis=1) end_position = np.argmax(faces == end[:, None], axis=1) return (end_position - start_position) % 3 == 1 def _adjacency_flips(mesh): pairs = mesh.face_adjacency shared = mesh.face_adjacency_edges faces = mesh.faces same_direction = _edge_runs_forward(faces[pairs[:, 0]], shared[:, 0], shared[:, 1]) == _edge_runs_forward( faces[pairs[:, 1]], shared[:, 0], shared[:, 1]) return pairs, same_direction def unify_winding(mesh): count = len(mesh.faces) pairs, same_direction = _adjacency_flips(mesh) graph = coo_matrix((np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), shape=(count, count)) _, labels = connected_components(graph, directed=False) _, representatives = np.unique(labels, return_index=True) root = count rows = np.concatenate([pairs[:, 0], np.full(len(representatives), root)]) cols = np.concatenate([pairs[:, 1], representatives]) rooted = coo_matrix((np.ones(len(rows)), (rows, cols)), shape=(count + 1, count + 1)).tocsr() _, parent = breadth_first_order(rooted, root, directed=False, return_predecessors=True) parent[root] = root parent[parent < 0] = np.flatnonzero(parent < 0) keys = np.sort(pairs, axis=1) @ np.array([count + 1, 1]) order = np.argsort(keys) nodes = np.arange(count) tree_keys = np.minimum(nodes, parent[:count]) * (count + 1) + np.maximum(nodes, parent[:count]) found = np.clip(np.searchsorted(keys[order], tree_keys), 0, len(order) - 1) flip = np.zeros(count + 1, dtype=bool) flip[:count] = same_direction[order][found] & (keys[order][found] == tree_keys) while not np.array_equal(parent, parent[parent]): flip ^= flip[parent] parent = parent[parent] flipped = flip[:count] if flipped.any(): faces = mesh.faces.copy() faces[flipped] = faces[flipped][:, ::-1] mesh.faces = faces def prepare_stl_mesh(vertices, faces, target_size_mm=152.4): vertices = np.asarray(vertices, dtype=np.float64) faces = np.asarray(faces) if vertices.ndim != 2 or vertices.shape[1] != 3 or not len(vertices): raise ValueError("The model has no valid vertices.") if faces.ndim != 2 or faces.shape[1] != 3 or not len(faces): raise ValueError("The model has no valid triangles.") if not np.isfinite(vertices).all() or faces.dtype.kind not in "iu": raise ValueError("The model contains invalid geometry.") if faces.min() < 0 or faces.max() >= len(vertices): raise ValueError("The model contains invalid triangle indices.") mesh = trimesh.Trimesh(vertices=vertices.copy(), faces=faces.copy(), process=True, validate=False) mesh.update_faces(mesh.unique_faces() & mesh.nondegenerate_faces()) mesh.remove_unreferenced_vertices() if mesh.is_empty or not len(mesh.faces): raise ValueError("The model has no usable triangles.") trimesh.repair.fill_holes(mesh) unify_winding(mesh) trimesh.repair.fix_inversion(mesh, multibody=True) longest_side = float(mesh.extents.max()) if not np.isfinite(longest_side) or longest_side <= 0: raise ValueError("The model has invalid dimensions.") mesh.apply_scale(target_size_mm / longest_side) return mesh def export_stl_from_state(state, export_directory): if not state or "mesh" not in state: raise ValueError("Generate a model before downloading STL.") geometry = state["mesh"] mesh = prepare_stl_mesh(geometry["vertices"], geometry["faces"]) directory = Path(export_directory) / uuid4().hex directory.mkdir(parents=True, exist_ok=True) path = directory / f"{DOWNLOAD_STEM}.stl" mesh.export(str(path), file_type="stl") return str(path.resolve()), bool(mesh.is_watertight)