Skip to content

Commit e03b998

Browse files
committed
bazel: vendor render_gds.py phase logging + dynamic drop-to-GLB-budget
Iterating on microwatt_final_blender_html on PR #4231. Three prior attempts on this same vendored patch surfaced (and fixed) successive gltf-export failures via the new phase logging: iter 1 ("appears to choke") -> phase logs pinpointed int32 overflow in gltf2 exporter's corner_normals.foreach_get for a single 9.3M- polygon mesh. Fixed by passing `export_normals=False`. iter 2 -> phase logs pinpointed the GLB 4 GB single-file ceiling on the binary container header (gltf2_io_export.save_gltf: struct.pack("I", length)). Fixed in iter 3 with a hardcoded sky130-specific drop set (licon, li1, mcon, met1, all vias) gated by `total_polys > 30_000_000`. iter 3 -> build succeeded, GLB 2.17 GB / HTML 2.89 GB. Build green but overshoots the ~2 GB per-tab memory cap mainstream browsers enforce, so the html target builds but won't load. This iteration generalises the iter-3 drop into a dynamic heuristic: rank meshes by polygon-count × bytes-per-poly (calibrated from iter 3 data: 39.7M polys -> 2.17 GB GLB -> ~55 b/poly, rounded up to 60), drop biggest first until the estimated GLB binary is ≤ 150 MB. That's ~10% of the 2 GB browser-tab cap with base64-inflation margin -- bling- and-fun loadable. Heuristic is layer-name agnostic, so non-sky130 PDKs work the same way; gcd-class designs (<1M polygons) already fit under the budget so the loop is a no-op for them. Phase log records the drop list + estimated post-trim GLB (`budget-trimmed` line) so the next iteration can recalibrate _GLB_BYTES_PER_POLY if the empirical ratio drifts on another design. A successful microwatt_final_blender_html bazelisk run on top of this patch validates the budget-cap path. Signed-off-by: Øyvind Harboe <oyvind@ascenium.com> Signed-off-by: Øyvind Harboe <oyvind.harboe@zylin.com>
1 parent cbb8d9a commit e03b998

2 files changed

Lines changed: 348 additions & 0 deletions

File tree

‎MODULE.bazel‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ git_override(
6363
"//patches/bazel-orfs:0002-blender.bzl-export-blender_supports_pdk-predicate.patch",
6464
"//patches/bazel-orfs:0003-orfs_design.bzl-forward-blender-silently-skip-unsupp.patch",
6565
"//patches/bazel-orfs:0004-environment.bzl-pull-src-OrfsDepInfo.files-into-sour.patch",
66+
"//patches/bazel-orfs:0005-render_gds-log-phase-VmRSS-and-capture-op-tracebacks.patch",
6667
],
6768
remote = BAZEL_ORFS_REMOTE,
6869
)
Lines changed: 347 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,347 @@
1+
From 75c7df636aace01bc21fa72d40dc541174671f76 Mon Sep 17 00:00:00 2001
2+
From: =?UTF-8?q?=C3=98yvind=20Harboe?= <oyvind@ascenium.com>
3+
Date: Sun, 17 May 2026 15:02:44 +0200
4+
Subject: [PATCH] render_gds: phase logging + dynamic drop-to-GLB-budget
5+
heuristic
6+
MIME-Version: 1.0
7+
Content-Type: text/plain; charset=UTF-8
8+
Content-Transfer-Encoding: 8bit
9+
10+
Headless run on sky130hd/microwatt's 562 MB merged GDS surfaces three
11+
distinct issues that the previous gltf-export path turned into an opaque
12+
"appears to choke" failure:
13+
14+
1. No phase visibility.
15+
16+
The action log carried no breadcrumbs about which step OOMed or
17+
returned CANCELLED inside the long bpy.ops sequence (addon-register,
18+
gdsii-import, gltf-addon-enable, gltf-export, html-write).
19+
20+
Add a tiny `_log_phase()` helper that scrapes VmRSS/VmPeak from
21+
/proc/self/status and prints one tagged line per phase boundary,
22+
plus the imported mesh polygon/vertex totals and the .glb / .html
23+
byte sizes. Wraps the bpy.ops calls in try/except so a Python
24+
exception inside the addon prints a full traceback before
25+
sys.exit, instead of being swallowed into a bare `{'CANCELLED'}`.
26+
27+
2. Int32 overflow in foreach_get for very large per-corner attributes.
28+
29+
With the phase logging in place, iter 1 surfaced:
30+
31+
Error: Array length mismatch (expected -464636871, got 609104952)
32+
RuntimeError: internal error setting the array
33+
File ".../io_scene_gltf2/blender/exp/gltf2_blender_gather_primitives_extract.py",
34+
line 1405, in __get_normals
35+
self.blender_mesh.corner_normals.foreach_get('vector', self.normals)
36+
37+
Blender 4.2's RNA bridge stores the foreach_get element count in a
38+
signed int32; microwatt's mcon layer alone has ~9.3M extruded
39+
polygons × 6 faces × 4 corners ≈ 223M corner-normals = 669M float32
40+
values, which overflows.
41+
42+
The NORMAL attribute is gated by `self.use_normals` (`gltf_normals`
43+
export setting); when False the failing path is never entered.
44+
Pass `export_normals=False` plus belt-and-suspenders for the other
45+
foreach_get-backed per-corner attributes (tangents, vertex colors,
46+
custom attributes). model-viewer falls back to face-derived flat
47+
normals, which is the right look for a chip-layout scene anyway --
48+
the extruded layers are already block-like and don't benefit from
49+
smooth shading.
50+
51+
3. GLB 4 GB single-file ceiling + browser per-tab memory cap.
52+
53+
With normals disabled, iter 2 tripped:
54+
55+
File ".../io_scene_gltf2/io/exp/gltf2_io_export.py", line 105,
56+
in save_gltf
57+
file.write(struct.pack("I", length))
58+
struct.error: 'I' format requires 0 <= number <= 4294967295
59+
60+
i.e. GLB's binary container stores total length as uint32; microwatt's
61+
raw vertex+index payload is ~10 GB (mcon alone ~2.9 GB raw, licon
62+
~2.6 GB). Even if the GLB write succeeded, the base64-embedded data
63+
URL in the HTML would exceed the ~2 GB per-tab memory cap mainstream
64+
browsers enforce.
65+
66+
iter 3 used a hardcoded sky130-specific drop set (licon, li1, mcon,
67+
met1, all vias) gated by `total_polys > 30_000_000`. That worked
68+
end-to-end (build succeeded; GLB 2.17 GB, HTML 2.89 GB) but is
69+
PDK-specific and overshot the browser cap.
70+
71+
Replace with a dynamic heuristic: rank meshes by polygon-count ×
72+
bytes-per-poly, drop biggest first until estimated GLB ≤
73+
_MAX_GLB_BYTES (150 MB, ≈10% of the 2 GB browser-tab cap with
74+
base64-inflation margin). Bytes-per-poly is calibrated from iter 3
75+
(39.7M Blender polygons -> 2.17 GB GLB -> ~55 b/poly; rounded up to
76+
60 for pessimism). Layer-name agnostic, so the same path serves
77+
non-sky130 PDKs; gcd-class designs (<1M polygons) already fit under
78+
the budget so the loop is a no-op for them.
79+
80+
Goal here is "bling and fun" loadability in a browser, not visual
81+
fidelity -- the trade-off is acceptable for an investigation-record
82+
viewer. Phase log line `budget-trimmed` records the drop list and
83+
estimated post-trim GLB so the next iteration can recalibrate
84+
_GLB_BYTES_PER_POLY if the empirical ratio drifts.
85+
86+
Signed-off-by: Øyvind Harboe <oyvind@ascenium.com>
87+
Signed-off-by: Øyvind Harboe <oyvind.harboe@zylin.com>
88+
---
89+
tools/blendergds/render_gds.py | 187 ++++++++++++++++++++++++++++++---
90+
1 file changed, 171 insertions(+), 16 deletions(-)
91+
92+
diff --git a/tools/blendergds/render_gds.py b/tools/blendergds/render_gds.py
93+
index 6cf4d75..d8bbbe1 100644
94+
--- a/tools/blendergds/render_gds.py
95+
+++ b/tools/blendergds/render_gds.py
96+
@@ -33,10 +33,82 @@ import importlib.util
97+
import shutil
98+
import sys
99+
import tempfile
100+
+import traceback
101+
import zipfile
102+
from pathlib import Path
103+
104+
105+
+# Target GLB binary size for the html-export path: ~10% of the ~2 GB
106+
+# per-tab memory cap mainstream browsers enforce on 64-bit Linux. After
107+
+# 4/3 base64 inflation in the data: URL, this puts the resulting HTML
108+
+# at ~200 MB -- "bling and fun" loadable, with plenty of headroom for
109+
+# the browser to actually render the scene. Empirical, not exact.
110+
+_MAX_GLB_BYTES = 150 * 1024 * 1024
111+
+
112+
+# Bytes-per-polygon estimate, calibrated from a prior iteration on
113+
+# sky130hd/microwatt that produced 39_669_907 Blender polygons in a
114+
+# 2_169_758_252-byte GLB (export_normals=False, post-extrusion,
115+
+# triangulated by the gltf2 exporter). ~55 bytes/poly empirically;
116+
+# round up to 60 so the heuristic is slightly pessimistic.
117+
+_GLB_BYTES_PER_POLY = 60
118+
+
119+
+
120+
+def _drop_to_glb_budget(max_glb_bytes):
121+
+ """Greedily drop the biggest mesh objects until the estimated GLB
122+
+ binary size fits the budget.
123+
+
124+
+ The heuristic is intentionally cheap (no trial exports): rank meshes
125+
+ by polygon-count × bytes-per-poly, evict largest-first. Always keeps
126+
+ at least one mesh -- a degenerate scene with a single mesh larger
127+
+ than the budget will go through to gltf-export and surface whatever
128+
+ failure mode that triggers, instead of producing an empty scene.
129+
+
130+
+ Returns (list-of-(name, est_bytes, polys) tuples for dropped meshes,
131+
+ estimated total GLB bytes after dropping).
132+
+ """
133+
+ sized = sorted(
134+
+ (
135+
+ (len(o.data.polygons) * _GLB_BYTES_PER_POLY, o)
136+
+ for o in bpy.data.objects
137+
+ if o.type == "MESH"
138+
+ ),
139+
+ key=lambda x: x[0],
140+
+ reverse=True,
141+
+ )
142+
+ total = sum(sz for sz, _ in sized)
143+
+ dropped = []
144+
+ while total > max_glb_bytes and len(sized) > 1:
145+
+ sz, obj = sized.pop(0)
146+
+ dropped.append((obj.name, sz, len(obj.data.polygons)))
147+
+ bpy.data.objects.remove(obj, do_unlink=True)
148+
+ total -= sz
149+
+ return dropped, total
150+
+
151+
+
152+
+def _log_phase(phase: str, extra: str = "") -> None:
153+
+ """Print a single-line phase marker with VmRSS / VmPeak.
154+
+
155+
+ Blender's --background mode produces a lot of output; these prefixed
156+
+ lines make it easy to grep the action log for the failing phase
157+
+ (e.g. addon-register, klayout-merge inside gdsii operator, gltf-export,
158+
+ html-write) and to see exactly where RSS spikes before an OOM.
159+
+ """
160+
+ rss = peak = "?"
161+
+ try:
162+
+ with open("/proc/self/status", "r", encoding="utf-8") as f:
163+
+ for line in f:
164+
+ if line.startswith("VmRSS:"):
165+
+ rss = line.split(":", 1)[1].strip()
166+
+ elif line.startswith("VmPeak:"):
167+
+ peak = line.split(":", 1)[1].strip()
168+
+ except OSError:
169+
+ pass
170+
+ msg = f"render_gds.py [{phase}] VmRSS={rss} VmPeak={peak}"
171+
+ if extra:
172+
+ msg += f" {extra}"
173+
+ print(msg, flush=True)
174+
+
175+
+
176+
def _split_argv():
177+
"""Return Blender's pass-through args (everything after `--`)."""
178+
if "--" not in sys.argv:
179+
@@ -166,6 +238,8 @@ def main():
180+
if not wheels_dir.is_dir():
181+
sys.exit(f"render_gds.py: wheels/ dir not found under {addon_root}")
182+
183+
+ _log_phase("startup", extra=f"gds={gds_path} ({gds_path.stat().st_size} bytes)")
184+
+
185+
# Stage wheels into a temp site-packages and put it on sys.path BEFORE
186+
# importing the addon (which imports numpy/gdstk/klayout/yaml at module
187+
# scope).
188+
@@ -175,6 +249,7 @@ def main():
189+
try:
190+
_stage_wheels(wheels_dir, site)
191+
sys.path.insert(0, str(site))
192+
+ _log_phase("wheels-staged")
193+
194+
# bpy is provided by Blender; importing it before this point would
195+
# leak partial init in --background mode.
196+
@@ -182,6 +257,7 @@ def main():
197+
198+
addon = _load_addon_module(addon_root)
199+
addon.register()
200+
+ _log_phase("addon-registered")
201+
202+
# The addon's register_properties() declares four scene props via
203+
# the legacy `bpy.types.Scene.X = StringProperty(...)` form. In
204+
@@ -192,38 +268,113 @@ def main():
205+
# which is what we want anyway.
206+
bpy.context.scene.gdsii_pdk_selection = args.pdk
207+
208+
- result = bpy.ops.import_scene.gdsii(
209+
- filepath=str(gds_path),
210+
- setup_scene=True,
211+
- create_collection=True,
212+
- merge_layers=True,
213+
- color_scheme="realistic",
214+
- )
215+
+ try:
216+
+ result = bpy.ops.import_scene.gdsii(
217+
+ filepath=str(gds_path),
218+
+ setup_scene=True,
219+
+ create_collection=True,
220+
+ merge_layers=True,
221+
+ color_scheme="realistic",
222+
+ )
223+
+ except Exception:
224+
+ _log_phase("gdsii-import-exception")
225+
+ traceback.print_exc()
226+
+ sys.exit("render_gds.py: import_scene.gdsii raised — see traceback above")
227+
if "FINISHED" not in result:
228+
+ _log_phase("gdsii-import-nonfinished", extra=f"result={result!r}")
229+
sys.exit(f"render_gds.py: import_scene.gdsii returned {result!r}")
230+
231+
+ mesh_objs = [o for o in bpy.data.objects if o.type == "MESH"]
232+
+ total_polys = sum(len(o.data.polygons) for o in mesh_objs)
233+
+ total_verts = sum(len(o.data.vertices) for o in mesh_objs)
234+
+ _log_phase(
235+
+ "gdsii-imported",
236+
+ extra=f"meshes={len(mesh_objs)} polygons={total_polys} verts={total_verts}",
237+
+ )
238+
+
239+
if args.out:
240+
out_path = Path(args.out).resolve()
241+
out_path.parent.mkdir(parents=True, exist_ok=True)
242+
bpy.ops.wm.save_as_mainfile(filepath=str(out_path), copy=True)
243+
+ _log_phase("blend-saved", extra=f"{out_path.stat().st_size} bytes")
244+
245+
if args.out_html:
246+
+ # The GLB binary container stores its total length as a uint32
247+
+ # (struct.pack("I", length)), and the base64-embedded data URL
248+
+ # in the HTML must also stay under a browser tab's per-tab
249+
+ # memory cap. Full-stack microwatt is ~10 GB of raw vertex+
250+
+ # index data -- 65x over the GLB ceiling, and unreachable to
251+
+ # a browser even if it fit. Trim the scene to a "bling and
252+
+ # fun" working budget _GLB_BYTES_PER_POLY * polys ≤
253+
+ # _MAX_GLB_BYTES, dropping biggest meshes first. The
254+
+ # heuristic is layer-name agnostic so non-sky130 PDKs work
255+
+ # the same way; the trade-off is that on a too-large scene
256+
+ # the layers with the highest polygon counts (typically the
257+
+ # densest interconnect/contact layers like mcon, licon, li1
258+
+ # on sky130hd) get evicted while the visually distinctive
259+
+ # ones (substrate, transistor regions, upper metals with
260+
+ # their macros) tend to stay. gcd-class designs already fit
261+
+ # under the budget, so the drop loop is a no-op for them.
262+
+ dropped, est_glb = _drop_to_glb_budget(_MAX_GLB_BYTES)
263+
+ kept_objs = [o for o in bpy.data.objects if o.type == "MESH"]
264+
+ kept_polys = sum(len(o.data.polygons) for o in kept_objs)
265+
+ _log_phase(
266+
+ "budget-trimmed",
267+
+ extra=(
268+
+ f"max_glb={_MAX_GLB_BYTES} estimated_glb={est_glb} "
269+
+ f"dropped={dropped} kept_meshes={len(kept_objs)} "
270+
+ f"kept_polys={kept_polys}"
271+
+ ),
272+
+ )
273+
+
274+
# io_scene_gltf2 ships with Blender as a core addon but is not
275+
# active under --factory-startup. Enable it before exporting.
276+
bpy.ops.preferences.addon_enable(module="io_scene_gltf2")
277+
+ _log_phase("gltf-addon-enabled")
278+
279+
glb_tmp = tmp / "scene.glb"
280+
- export_result = bpy.ops.export_scene.gltf(
281+
- filepath=str(glb_tmp),
282+
- export_format="GLB",
283+
- export_apply=True,
284+
- export_yup=True,
285+
- export_lights=False,
286+
- export_cameras=False,
287+
- use_active_scene=True,
288+
- )
289+
+ try:
290+
+ export_result = bpy.ops.export_scene.gltf(
291+
+ filepath=str(glb_tmp),
292+
+ export_format="GLB",
293+
+ export_apply=True,
294+
+ export_yup=True,
295+
+ export_lights=False,
296+
+ export_cameras=False,
297+
+ use_active_scene=True,
298+
+ # Per-corner attribute exports use foreach_get under the
299+
+ # hood and Blender 4.2's RNA bridge stores the element
300+
+ # count in a signed int32. Microwatt's mcon layer alone
301+
+ # has ~9.3M extruded polygons × 6 faces × 4 corners ≈
302+
+ # 223M corner-normals = 669M float32 values, which
303+
+ # overflows int32 and yields:
304+
+ #
305+
+ # Error: Array length mismatch
306+
+ # (expected -464636871, got 609104952)
307+
+ # RuntimeError: internal error setting the array
308+
+ #
309+
+ # in gltf2_blender_gather_primitives_extract.__get_normals.
310+
+ # Disabling normals (and the other per-corner attributes
311+
+ # gated by foreach_get -- tangents, vertex colors)
312+
+ # short-circuits the failing path before it allocates
313+
+ # the oversized buffer. model-viewer falls back to
314+
+ # face-derived flat normals, which is the right look
315+
+ # for a chip-layout scene anyway (no smooth shading).
316+
+ export_normals=False,
317+
+ export_tangents=False,
318+
+ export_attributes=False,
319+
+ export_vertex_color="NONE",
320+
+ )
321+
+ except Exception:
322+
+ _log_phase("gltf-export-exception")
323+
+ traceback.print_exc()
324+
+ sys.exit(
325+
+ "render_gds.py: export_scene.gltf raised — see traceback above"
326+
+ )
327+
if "FINISHED" not in export_result:
328+
+ _log_phase("gltf-export-nonfinished", extra=f"result={export_result!r}")
329+
sys.exit(f"render_gds.py: export_scene.gltf returned {export_result!r}")
330+
+ _log_phase("gltf-exported", extra=f"glb={glb_tmp.stat().st_size} bytes")
331+
332+
_write_html(
333+
template_path=Path(args.html_template).resolve(),
334+
@@ -232,6 +383,10 @@ def main():
335+
title=args.title,
336+
out_path=Path(args.out_html).resolve(),
337+
)
338+
+ _log_phase(
339+
+ "html-written",
340+
+ extra=f"out={Path(args.out_html).stat().st_size} bytes",
341+
+ )
342+
finally:
343+
shutil.rmtree(tmp, ignore_errors=True)
344+
345+
--
346+
2.51.0
347+

0 commit comments

Comments
 (0)