File size: 6,299 Bytes
3e0d585
 
d4c2386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb416ab
 
 
 
 
d4c2386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e0d585
 
 
 
 
 
 
 
 
 
 
d4c2386
 
 
 
3e0d585
d4c2386
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import os
import shutil
import subprocess
import sys
from pathlib import Path

from agent_core.config import WORKDIR

IMAGE_SIZE = 1024
GAP = 4

# (label, view direction from model center toward camera, camera up)
VIEWS = [
    ("ISO front-right-top", (1, -1, 1), (0, 0, 1)),
    ("ISO back-left-bottom", (-1, 1, -1), (0, 0, 1)),
    ("FRONT (from -Y), right=+X, up=+Z", (0, -1, 0), (0, 0, 1)),
    ("TOP (from +Z), right=+X, up=+Y", (0, 0, 1), (0, 1, 0)),
]


def _normalize(v):
    length = sum(c * c for c in v) ** 0.5
    return tuple(c / length for c in v)


def _cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def _dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def _fit_camera(camera, bounds, direction, up):
    xmin, xmax, ymin, ymax, zmin, zmax = bounds
    center = ((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2)
    diagonal = ((xmax - xmin) ** 2 + (ymax - ymin) ** 2 + (zmax - zmin) ** 2) ** 0.5 or 1.0
    direction = _normalize(direction)
    right = _normalize(_cross(up, direction))
    true_up = _cross(direction, right)

    corners = [(x, y, z) for x in (xmin, xmax) for y in (ymin, ymax) for z in (zmin, zmax)]
    offsets = [tuple(c - m for c, m in zip(corner, center)) for corner in corners]
    half_width = max(abs(_dot(o, right)) for o in offsets)
    half_height = max(abs(_dot(o, true_up)) for o in offsets)

    camera.ParallelProjectionOn()
    camera.SetFocalPoint(*center)
    camera.SetPosition(*(m + d * diagonal * 2 for m, d in zip(center, direction)))
    camera.SetViewUp(*true_up)
    camera.SetParallelScale(max(half_width, half_height, diagonal * 0.01) * 1.25)
    camera.SetClippingRange(diagonal * 0.1, diagonal * 4)


def render_views(stl_path: Path, png_path: Path) -> dict:
    import vtk

    reader = vtk.vtkSTLReader()
    reader.SetFileName(str(stl_path))
    reader.Update()
    mesh = reader.GetOutput()
    if mesh.GetNumberOfCells() == 0:
        raise ValueError("STL preview contains no triangles.")
    bounds = mesh.GetBounds()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputData(mesh)
    normals.SetFeatureAngle(30)
    normals.SplittingOn()

    surface_mapper = vtk.vtkPolyDataMapper()
    surface_mapper.SetInputConnection(normals.GetOutputPort())

    edges = vtk.vtkFeatureEdges()
    edges.SetInputData(mesh)
    edges.SetFeatureAngle(30)
    edges.BoundaryEdgesOn()
    edges.FeatureEdgesOn()
    edges.NonManifoldEdgesOn()
    edges.ManifoldEdgesOff()
    edges.ColoringOff()

    edge_mapper = vtk.vtkPolyDataMapper()
    edge_mapper.SetInputConnection(edges.GetOutputPort())
    edge_mapper.SetResolveCoincidentTopologyToPolygonOffset()

    window = vtk.vtkRenderWindow()
    window.SetOffScreenRendering(1)
    window.SetSize(IMAGE_SIZE, IMAGE_SIZE)

    backdrop = vtk.vtkRenderer()
    backdrop.SetBackground(0.55, 0.55, 0.55)
    window.AddRenderer(backdrop)

    gap = GAP / IMAGE_SIZE / 2
    size = (bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4])
    for index, (label, direction, up) in enumerate(VIEWS):
        col, row = index % 2, 1 - index // 2
        renderer = vtk.vtkRenderer()
        renderer.SetViewport(col / 2 + gap, row / 2 + gap, (col + 1) / 2 - gap, (row + 1) / 2 - gap)
        renderer.SetBackground(1, 1, 1)

        surface = vtk.vtkActor()
        surface.SetMapper(surface_mapper)
        surface.GetProperty().SetColor(0.72, 0.78, 0.86)
        surface.GetProperty().SetAmbient(0.25)
        surface.GetProperty().SetDiffuse(0.75)
        renderer.AddActor(surface)

        edge_actor = vtk.vtkActor()
        edge_actor.SetMapper(edge_mapper)
        edge_actor.GetProperty().SetColor(0.05, 0.05, 0.05)
        edge_actor.GetProperty().SetLineWidth(1.5)
        renderer.AddActor(edge_actor)

        text = vtk.vtkTextActor()
        caption = label
        if index == 0:
            caption += f"\nBBox X={size[0]:.1f} Y={size[1]:.1f} Z={size[2]:.1f} mm"
        text.SetInput(caption)
        text.GetTextProperty().SetFontSize(16)
        text.GetTextProperty().SetColor(0.8, 0.1, 0.1)
        text.GetTextProperty().SetVerticalJustificationToTop()
        text.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
        text.GetPositionCoordinate().SetValue(0.015, 0.975)
        # VTK 9.5+ Python wheels drop AddActor2D; AddViewProp is the supported synonym.
        if hasattr(renderer, "AddViewProp"):
            renderer.AddViewProp(text)
        else:
            renderer.AddActor2D(text)

        _fit_camera(renderer.GetActiveCamera(), bounds, direction, up)
        renderer.LightFollowCameraOn()
        window.AddRenderer(renderer)

    window.Render()
    capture = vtk.vtkWindowToImageFilter()
    capture.SetInput(window)
    capture.ReadFrontBufferOff()
    capture.Update()

    png_path.parent.mkdir(parents=True, exist_ok=True)
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(str(png_path))
    writer.SetInputConnection(capture.GetOutputPort())
    writer.Write()
    window.Finalize()

    return {"bbox_mm": {"x": size[0], "y": size[1], "z": size[2]}}


def _render_command(stl_path: Path, png_path: Path) -> list[str]:
    cmd = [sys.executable, "-m", "agent_core.verify.render", str(stl_path), str(png_path)]
    # Prefer an existing display (local desktop). On headless Spaces, wrap with xvfb-run.
    if os.environ.get("DISPLAY"):
        return cmd
    xvfb_run = shutil.which("xvfb-run")
    if xvfb_run:
        return [xvfb_run, "-a", *cmd]
    return cmd


def render_in_subprocess(stl_path: Path, png_path: Path, timeout: int = 60) -> str | None:
    """Render in a child process so VTK/OpenGL crashes cannot take down the agent. Returns an error or None."""
    try:
        process = subprocess.run(
            _render_command(stl_path, png_path),
            cwd=WORKDIR,
            capture_output=True,
            text=True,
            timeout=timeout,
        )
    except subprocess.TimeoutExpired:
        return f"Rendering timed out after {timeout} seconds."
    if process.returncode != 0 or not png_path.exists():
        return f"Rendering failed (exit {process.returncode}): {process.stderr[-2000:]}"
    return None


if __name__ == "__main__":
    render_views(Path(sys.argv[1]), Path(sys.argv[2]))