Skip to content

Official Codebase of 3DCodeVerse

Python
8.4 KB
Raw Blame
"""Blender build wrapper; runs inside Blender, never imported by the harness.

    blender -b --factory-startup --python run_bpy.py -- \
        --script /abs/src/model.py --out /abs/artifacts [--stl] [--rlimit-gb 12] [--seed 0]

Caps memory, clears the factory scene, seeds RNGs, runs the agent's ``model.py`` with ``<ws>/src``
on ``sys.path``, collects the census and contract warnings, refuses non-finite geometry, exports
``object.glb`` (+ optional stl) and writes ``build.json`` + ``census.json``.
Exit 0 = reported (even if the script failed); 2 = wrapper bug."""

from __future__ import annotations

import argparse
import contextlib
import os
import sys
import time
import traceback
from typing import Any

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
from _census import collect_census, is_hidden  # noqa: E402
from _finite import Offenders, scan_objects  # noqa: E402
from _wrapper_common import (  # noqa: E402
    PARTS_PKG,
    exit_after,
    map_exception,
    new_report,
    run_script,
    seed_everything,
    wrapper_argv,
    write_report,
)

GLB_NAME = "object.glb"
STL_NAME = "object.stl"
EXPORT_TYPES = {"MESH", "CURVE", "SURFACE", "FONT", "META", "EMPTY"}
MEMORY_HINT = ("a geometry bomb (tiny remesh voxel_size, huge subdivision/array counts, nested loops "
               "creating millions of faces). Reduce it.")


def parse_args(argv: list[str]) -> argparse.Namespace:
    p = argparse.ArgumentParser(prog="run_bpy.py")
    p.add_argument("--script", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--stl", action="store_true")
    p.add_argument("--rlimit-gb", type=float, default=12.0)
    p.add_argument("--seed", type=int, default=0)
    return p.parse_args(argv)


# ----------------------------------------------------------------------------- scene prep
def clear_scene(bpy: Any) -> None:
    for obj in list(bpy.data.objects):
        bpy.data.objects.remove(obj, do_unlink=True)
    for coll in list(bpy.data.collections):
        bpy.data.collections.remove(coll)
    for attr in ("meshes", "materials", "cameras", "lights", "curves", "images", "node_groups", "textures"):
        block = getattr(bpy.data, attr)
        for item in list(block):
            with contextlib.suppress(RuntimeError):
                block.remove(item)
    scene = bpy.context.scene
    # removing "Collection" leaves the active collection dangling; point it at the master collection
    bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection
    scene.unit_settings.system = "METRIC"
    scene.unit_settings.scale_length = 1.0
    scene.unit_settings.length_unit = "METERS"


def render_fingerprint(bpy: Any) -> dict[str, Any]:
    r = bpy.context.scene.render
    return {
        "engine": r.engine,
        "resolution": [r.resolution_x, r.resolution_y],
        "filepath": r.filepath,
        "frame_range": [bpy.context.scene.frame_start, bpy.context.scene.frame_end],
    }


# ----------------------------------------------------------------------------- errors
def import_hint(exc: BaseException, src_dir: str) -> str:
    msg = str(exc)
    if isinstance(exc, ModuleNotFoundError) and (f"'{PARTS_PKG}." in msg or f"'{PARTS_PKG}'" in msg):
        mod = msg.split("'")[1].split(".")[-1]
        return f" — create {os.path.basename(src_dir)}/{PARTS_PKG}/{mod}.py (snake_case file name) or fix the import"
    if isinstance(exc, ImportError) and "cannot import name" in msg:
        name = msg.split("'")[1]
        where = msg.split("'")[3] if msg.count("'") >= 4 else PARTS_PKG
        return f" — define `def {name}():` in {where.replace('.', '/')}.py (every part file exports build_<snake>)"
    return ""


def script_error(exc: BaseException, script: str) -> dict[str, Any]:
    return map_exception(exc, script, hint=import_hint(exc, os.path.dirname(script)), memory=MEMORY_HINT)


# ----------------------------------------------------------------------------- export
def select_exportables(bpy: Any) -> list[Any]:
    bpy.ops.object.select_all(action="DESELECT")
    chosen = []
    vl_names = set(bpy.context.view_layer.objects.keys())
    for obj in bpy.context.scene.objects:
        if obj.type in EXPORT_TYPES and not is_hidden(obj, vl_names):
            with contextlib.suppress(RuntimeError):
                obj.select_set(True)
                chosen.append(obj)
    if chosen:
        bpy.context.view_layer.objects.active = chosen[0]
    return chosen


def export_glb(bpy: Any, path: str) -> None:
    bpy.ops.export_scene.gltf(
        filepath=path,
        export_format="GLB",
        use_selection=True,
        use_visible=False,
        export_apply=True,
        export_yup=True,
        export_materials="EXPORT",
        export_image_format="AUTO",
        export_cameras=False,
        export_lights=False,
        export_animations=True,
        export_frame_range=True,
        export_extras=False,
        export_normals=True,
        export_texcoords=True,
    )


def export_stl(bpy: Any, path: str) -> None:
    bpy.ops.wm.stl_export(filepath=path, export_selected_objects=True, apply_modifiers=True, ascii_format=False, global_scale=1.0)


def pack_images(bpy: Any) -> list[str]:
    """Pack every image the script generated in memory into the .blend (8-bit PNG, float OpenEXR);
    unpacked, the reopened file regenerates it blank.  Returns their names."""
    packed = []
    for img in bpy.data.images:
        if img.source != "VIEWER" and img.is_dirty:
            img.pack()
            packed.append(img.name)
    return packed


def save_blend(bpy: Any, path: str, *, compress: bool = False) -> list[str]:
    warnings = []
    try:
        pack_images(bpy)
    except RuntimeError as e:
        warnings.append(f"in-memory images could not be packed into {os.path.basename(path)} (they reopen blank): {e}")
    bpy.ops.wm.save_as_mainfile(filepath=path, compress=compress, copy=True)
    return warnings


# ----------------------------------------------------------------------------- main
def main() -> int:
    args = parse_args(wrapper_argv())
    import bpy  # noqa: PLC0415

    out_dir = os.path.abspath(args.out)
    os.makedirs(out_dir, exist_ok=True)
    script = os.path.abspath(args.script)
    t0 = time.monotonic()
    report = new_report(args.rlimit_gb)
    if not os.path.isfile(script):
        report.update(error_type="FileNotFoundError", error_message=f"script not found: {script}")
        write_report(out_dir, report, {}, t0)
        return 0

    clear_scene(bpy)
    seed_everything(args.seed)
    render_before = render_fingerprint(bpy)

    t_exec = time.monotonic()
    exc, _ = run_script(script)
    report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)
    if exc is not None:
        report.update(script_error(exc, script))

    try:
        if bpy.context.object and bpy.context.object.mode != "OBJECT":
            bpy.ops.object.mode_set(mode="OBJECT")
    except RuntimeError:
        pass

    census = collect_census(bpy)
    if render_fingerprint(bpy) != render_before:
        census["warnings"].append("script changed render settings (engine/resolution/filepath/frames): remove that code")
    report["warnings"] = census["warnings"]

    chosen = select_exportables(bpy)
    if chosen and not report["error_type"]:
        bad = scan_objects(chosen, bpy.context.evaluated_depsgraph_get(), Offenders())
        if bad:
            report.update(bad.report())
            chosen = []
    if chosen:
        glb = os.path.join(out_dir, GLB_NAME)
        try:
            export_glb(bpy, glb)
            report["exported"]["glb"] = glb
        except Exception as e:  # noqa: BLE001
            if not report["error_type"]:
                report.update(error_type="ExportError", error_message=f"glTF export failed: {e}")
            report["traceback"] = report["traceback"] or traceback.format_exc()[-4000:]
        if args.stl:
            stl = os.path.join(out_dir, STL_NAME)
            try:
                select_exportables(bpy)
                export_stl(bpy, stl)
                report["exported"]["stl"] = stl
            except Exception as e:  # noqa: BLE001
                report["warnings"].append(f"STL export failed: {e}")
    elif not report["error_type"]:
        report.update(error_type="EmptyScene", error_message="the script created no visible mesh objects")

    report["ok"] = not report["error_type"] and "glb" in report["exported"]
    write_report(out_dir, report, census, t0)
    return 0


if __name__ == "__main__":
    exit_after(main)