Skip to content

Official Codebase of 3DCodeVerse

Python
6.7 KB
Raw Blame
"""Scene census for the Blender build wrappers; runs inside Blender, never imported by the harness.

Imported by run_bpy.py / run_bpy_links.py as a sibling, so it stays standalone.  Reports
the objects (visibility, materials) and the contract warnings."""

from __future__ import annotations

import re
from typing import Any

DEFAULT_NAME_RE = re.compile(
    r"^(Cube|Cylinder|Sphere|Plane|Cone|Torus|Icosphere|Circle|Grid|Monkey|Mesh|Text|Curve)(\.\d+)?$"
)
MEASURABLE_TYPES = ("MESH", "CURVE", "SURFACE", "FONT", "META")


def world_bbox(obj_eval: Any, Vector: Any) -> tuple[list[float], list[float]] | None:
    corners = [obj_eval.matrix_world @ Vector(c) for c in obj_eval.bound_box]
    if not corners:
        return None
    mn = [min(c[i] for c in corners) for i in range(3)]
    mx = [max(c[i] for c in corners) for i in range(3)]
    return [round(v, 5) for v in mn], [round(v, 5) for v in mx]


def is_hidden(obj: Any, vl_names: set[str] | None = None) -> bool:
    """True when the object will not export: hidden, or not in the view layer (``vl_names``)."""
    if vl_names is not None and obj.name not in vl_names:
        return True
    try:
        return bool(obj.hide_render or obj.hide_viewport or obj.hide_get())
    except RuntimeError:
        return True


def _object_record(obj: Any, dg: Any, scene_objects: set[str], vl_names: set[str]) -> dict[str, Any]:
    rec: dict[str, Any] = {
        "name": obj.name,
        "type": obj.type,
        "in_scene": obj.name in scene_objects,
        "in_view_layer": obj.name in vl_names,
        "hidden": is_hidden(obj, vl_names),
        "materials": [s.material.name for s in obj.material_slots if s.material],
        "n_material_slots": len(obj.material_slots),
    }
    if obj.type in MEASURABLE_TYPES and rec["n_material_slots"]:
        try:
            ob_eval = obj.evaluated_get(dg)
            me = ob_eval.to_mesh()
            if len(me.polygons):
                # modifiers can add slot indices the mesh never had; export clamps out-of-range ones
                per_poly = [0] * len(me.polygons)
                me.polygons.foreach_get("material_index", per_poly)
                rec["material_indices_used"] = sorted(set(per_poly))
            ob_eval.to_mesh_clear()
        except RuntimeError:
            pass   # an object that cannot be evaluated has no slot census
    return rec


def _named(items: list[str], limit: int = 6) -> str:
    head = ", ".join(items[:limit])
    return head if len(items) <= limit else f"{head} (+{len(items) - limit} more)"


def material_slot_warnings(meshes: list[dict[str, Any]]) -> list[str]:
    """Material slots no polygon uses: an assignment that silently no-opped leaves them unused
    while the material list still looks complete."""
    unused: list[str] = []
    clamped: list[str] = []
    for o in meshes:
        used = o.get("material_indices_used")
        n_slots = o.get("n_material_slots", 0)
        if not used:
            continue
        if used[-1] >= n_slots:
            clamped.append(f"'{o['name']}' (index {used[-1]}, {n_slots} slot(s))")
        elif len(used) < n_slots:
            unused.append(f"'{o['name']}' ({n_slots} slots, {len(used)} used)")
    warnings: list[str] = []
    if unused:
        warnings.append(
            f"mesh(es) {_named(unused)} carry material slots no polygon uses — those colours never reach "
            "the export; assign per face (for f in bm.faces: f.material_index = k, BEFORE bm.to_mesh, or "
            "poly.material_index on the built mesh) or drop the unused slots"
        )
    if clamped:
        warnings.append(
            f"mesh(es) {_named(clamped)} have polygons on a material_index past the last slot: Blender "
            "clamps them to the last material instead of raising; append the missing materials in slot order"
        )
    return warnings


def _warnings(bpy: Any, objects: list[dict[str, Any]], boolean_operands: dict[str, list[str]],
              scene_objects: set[str], vl_names: set[str]) -> list[str]:
    warnings: list[str] = []
    excluded = [o["name"] for o in objects if o["in_scene"] and not o["in_view_layer"]]
    if excluded:
        warnings.append(f"object(s) {excluded} are in a collection excluded from the view layer → NOT exported "
                        "and not counted; re-enable the collection (layer_collection.exclude = False) or remove them")
    cams = [o.name for o in bpy.data.objects if o.type == "CAMERA"]
    lights = [o.name for o in bpy.data.objects if o.type == "LIGHT"]
    if cams:
        warnings.append(f"script created camera(s) {cams}: not exported; remove camera code (the harness owns cameras)")
    if lights:
        warnings.append(f"script created light(s) {lights}: not exported; remove light code (the harness owns lighting)")
    for cutter, users in boolean_operands.items():
        o = bpy.data.objects.get(cutter)
        if o is not None and not is_hidden(o, vl_names) and o.name in scene_objects:
            warnings.append(
                f"object '{cutter}' is a boolean operand of {users} but is still visible and WILL be exported as "
                f"geometry; hide it: obj.hide_set(True); obj.hide_render = True  (or bpy.data.objects.remove(obj))"
            )
    visible = [o for o in objects if o["in_scene"] and not o["hidden"] and o["type"] == "MESH"]
    if not visible:
        warnings.append("no visible mesh objects in the scene — nothing to export")
    for o in visible:
        if not o["materials"]:
            warnings.append(f"mesh '{o['name']}' has no material (will export grey)")
        if DEFAULT_NAME_RE.match(o["name"]):
            warnings.append(f"mesh '{o['name']}' keeps a default primitive name; set obj.name = '<PartName>'")
    warnings.extend(material_slot_warnings(visible))
    unlinked = [o["name"] for o in objects if o["type"] == "MESH" and not o["in_scene"]]
    if unlinked:
        warnings.append(f"mesh object(s) {unlinked} were created but never linked to the scene → not exported; "
                        "call bpy.context.collection.objects.link(obj)")
    return warnings


def collect_census(bpy: Any) -> dict[str, Any]:
    bpy.context.view_layer.update()
    dg = bpy.context.evaluated_depsgraph_get()
    scene_objects = set(bpy.context.scene.objects.keys())
    vl_names = set(bpy.context.view_layer.objects.keys())
    boolean_operands: dict[str, list[str]] = {}
    objects: list[dict[str, Any]] = []
    for obj in bpy.data.objects:
        for m in obj.modifiers:
            if m.type == "BOOLEAN" and getattr(m, "object", None) is not None:
                boolean_operands.setdefault(m.object.name, []).append(obj.name)
        objects.append(_object_record(obj, dg, scene_objects, vl_names))
    return {"objects": objects, "warnings": _warnings(bpy, objects, boolean_operands, scene_objects, vl_names)}