Campus pipeline hardening: backend parity, wall union, mullion grids, Draco tooling

Sandbox round (Linux):
- detect_sheet_frames.py: multi-frame sheet splitter (column AND row layouts),
  grid-vote per-floor offsets, section-elevation harvesting for storey heights
- dwg_dump_json.mjs + dwgjson_to_dxf.py: WASM libredwg DWG->DXF fallback
  (blocks/INSERT preserved, ATTRIB->TEXT so axis labels survive)
- assemble_campus.py: manifest-driven campus assembly with mandatory
  neighbour-gap gate (overlap = exit 3, 0.1-0.3m flagged as expansion joints)
- site_context_from_dump.py: site-context floors (ground/roads/parking/
  fence/trees/context massings) from site-plan dumps
- write_offline_viewer.py + assets/offline-viewer-libs/: fully-offline
  single-file viewer (vendored three r147 + pako, gzip-embedded GLB)
- audit: clip-scoped coverage figures; report: multi_frame_sheet warning;
  audit gate floors_aligned catches the diagonal-staircase failure mode

Mac round:
- build_blender_showcase.py now honors slab_bounds_fallback and prefers
  footprint polygons for generated roofs (bounds rects made roof plates jut
  past the facade and buried campuses under full-extent slabs); contract now
  matches spec_to_glb.py exactly
- merge_wall_solids (default off) in BOTH backends: shapely union in
  spec_to_glb.py, native delaunay_2d_cdt union in Blender; endpoint-shared
  wall ends pre-extended w/2 so L-corners close seamlessly (flat caps leave
  a notch a union alone cannot fill) while openings stay flat
- glazing_mullions (default off): curtain-wall panel grid (verticals every
  glazing_panel_w + floor-line transoms) as pseudo wall segments in the
  <floor>__walls node; glass pane kept
- build_showcase_variants.py keeps source_file=="site" floors intact in all
  variants (roads/trees live on filtered categories)
- web template: instanced low-poly trees from metadata site_trees,
  grade-level shadow catcher (was at basement depth), data-URI favicon
- tools/compress.mjs deps pinned (package.json); 15MB campus GLB -> 0.57MB
- tests: 24 -> 52 checks (wall union, mullions, byte-identical defaults)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-02 17:44:41 +08:00
parent 74cc7168f7
commit 6ace84ffba
27 changed files with 8515 additions and 85 deletions

View File

@@ -269,6 +269,54 @@ def probe_keep_entity(entity, config: dict[str, Any]) -> bool:
return category is not None and category in allowed
_BLOCK_LEAF_LAYERS: dict[tuple[int, str], frozenset[str]] = {}
def block_leaf_layers(doc, name: str, max_depth: int, depth: int = 0) -> frozenset[str]:
"""Layers used by a block definition (recursing into nested INSERTs).
Cheap definition walk (no explode/transform) memoized per document+name so
probe expansion can skip the expensive virtual explode for the vast
majority of blocks (axis bubbles, tags, hatched symbols) whose contents can
never classify into block_content_categories.
"""
key = (id(doc), name)
cached = _BLOCK_LEAF_LAYERS.get(key)
if cached is not None:
return cached
layers: set[str] = set()
try:
block = doc.blocks.get(name)
except Exception:
block = None
if block is not None:
for inner in block:
if inner.dxftype() == "INSERT" and depth < max_depth:
inner_name = str(inner.dxf.name) if inner.dxf.hasattr("name") else ""
if inner_name:
layers |= block_leaf_layers(doc, inner_name, max_depth, depth + 1)
else:
layers.add(entity_layer(inner))
result = frozenset(layers)
_BLOCK_LEAF_LAYERS[key] = result
return result
def probe_block_may_match(entity, config: dict[str, Any]) -> bool:
"""True if any leaf layer of the INSERT's block could classify for probing."""
doc = getattr(entity, "doc", None)
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
if doc is None or not block_name:
return True # cannot prove it is irrelevant; expand as before
patterns, excludes, allowed = _probe_rules(config)
max_depth = int(config.get("expand_blocks_max_depth", 2))
for layer in block_leaf_layers(doc, block_name, max_depth):
category = match_category(layer, patterns, excludes)
if category is not None and category in allowed:
return True
return False
def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
"""Yield (entity, fallback_layer, block_name) tuples to inspect/extract.
@@ -291,6 +339,11 @@ def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
if (not explicit and not probe) or depth >= max_depth:
yield entity, "", ""
return
if not explicit and probe and not probe_block_may_match(entity, config):
# No leaf layer of this block can classify -> exploding it cannot
# contribute geometry; skip the expensive virtual expansion.
yield entity, "", ""
return
insert_layer = entity_layer(entity)
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
@@ -426,68 +479,76 @@ def collect_raw_segments(
entities = list(doc.modelspace())
floors = drawing.get("floors") or [{"key": Path(drawing["file"]).stem, "name": Path(drawing["file"]).stem}]
# Single pass over (expanded) entities, bucketed per floor. Expanding
# INSERTs per floor is O(floors x inserts) and times out on Chinese
# multi-frame sheets where one DWG holds every floor of a building.
floor_specs = []
buckets: dict[str, dict[str, list[dict[str, Any]]]] = {}
counts: dict[str, int] = {}
for floor in floors:
key = str(floor["key"])
offset_values = floor.get("offset", drawing.get("offset", [0, 0]))
offset = (float(offset_values[0]), float(offset_values[1]))
segments_by_category: dict[str, list[dict[str, Any]]] = defaultdict(list)
ignored_by_type: dict[str, int] = defaultdict(int)
included = 0
floor_specs.append((floor, key, (float(offset_values[0]), float(offset_values[1]))))
buckets[key] = defaultdict(list)
counts[key] = 0
ignored_by_type: dict[str, int] = defaultdict(int)
for entity in entities:
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
layer = entity_layer(extracted_entity)
category = category_for_entity(
extracted_entity,
patterns,
config,
fallback_layer=fallback_layer,
block_name=block_name,
)
if not category:
ignored_by_type[extracted_entity.dxftype()] += 1
continue
for start, end in entity_segments(extracted_entity, max_chord):
for entity in entities:
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
layer = entity_layer(extracted_entity)
category = category_for_entity(
extracted_entity,
patterns,
config,
fallback_layer=fallback_layer,
block_name=block_name,
)
if not category:
ignored_by_type[extracted_entity.dxftype()] += 1
continue
segments = entity_segments(extracted_entity, max_chord)
if not segments:
continue
source_type = extracted_entity.dxftype()
width = default_widths.get(category, 0.1)
min_source = min_source_by_category.get(category, min_source_length)
min_meters = min_meters_by_category.get(category, min_meters_length)
for start, end in segments:
for floor, key, offset in floor_specs:
if not segment_matches_floor(start, end, floor, drawing):
continue
seg = cleaned_segment(
start,
end,
offset,
min_source_by_category.get(category, min_source_length),
min_meters_by_category.get(category, min_meters_length),
scale,
)
seg = cleaned_segment(start, end, offset, min_source, min_meters, scale)
if not seg:
continue
clean_start, clean_end = seg
segments_by_category[category].append(
buckets[key][category].append(
{
"start_source": clean_start,
"end_source": clean_end,
"width": default_widths.get(category, 0.1),
"width": width,
"layer": layer,
"source_type": extracted_entity.dxftype(),
"source_type": source_type,
"block_name": block_name,
"fallback_layer": fallback_layer,
}
)
included += 1
counts[key] += 1
for floor, key, _offset in floor_specs:
floor_data[key] = {
"key": key,
"name": str(floor.get("name", key)),
"z": floor.get("z"),
"height": float(floor.get("height", config.get("floor_height", 4.2))),
"source_file": path.name,
"segments_source": dict(segments_by_category),
"segments_source": dict(buckets[key]),
}
extraction_report.append(
{
"file": path.name,
"floor": key,
"status": "ok",
"segments": included,
"segments": counts[key],
"ignored_entity_types": dict(sorted(ignored_by_type.items())),
}
)
@@ -624,7 +685,16 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
return out
def _cap_floor_group(fk: str) -> str:
def _cap_floor_group(fk: str, config: dict[str, Any] | None = None) -> str:
"""Cap grouping: which floors stack in the same tower for cap logic.
Configurable via config["cap_groups"] = [["AUX_*", "AUX"], ["B*", "BASE"], ...]
(fnmatch patterns, first match wins). Defaults reproduce the A208 case:
AUX_* prefix = annex tower, B1/B1M = basement, everything else = main.
"""
for pattern, group in (config or {}).get("cap_groups", []):
if fnmatch.fnmatch(fk.upper(), str(pattern).upper()):
return str(group)
if fk.startswith("AUX_"):
return "AUX"
if fk in {"B1", "B1M"}:
@@ -678,10 +748,10 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
if not own_polys:
continue
ftop = float(fl["z"]) + float(fl.get("height", 4.2))
grp = _cap_floor_group(fk)
grp = _cap_floor_group(fk, config)
upper = []
for ok, ot in floors.items():
if ok == fk or _cap_floor_group(ok) != grp:
if ok == fk or _cap_floor_group(ok, config) != grp:
continue
if abs(float(ot.get("z", 0.0)) - ftop) > 0.8:
continue
@@ -765,6 +835,33 @@ def finalize_spec(
)
compute_caps(floors, config)
# Topless-roof guard: the top above-ground floor of each group must end in
# a cap or a config roof_specs entry, otherwise the model renders open-top
# ("没有屋顶"). Warn loudly so the Agent adds roof_specs before building.
roof_tops: dict[str, float] = {}
for r in config.get("roof_specs", []):
fk = str(r.get("floor_key"))
if fk not in floors:
continue
grp = _cap_floor_group(fk, config)
z = float(r.get("z", float(floors[fk]["z"]) + float(floors[fk].get("height", 4.2))))
roof_tops[grp] = max(roof_tops.get(grp, -1e9), z)
groups: dict[str, str] = {}
for key in floors:
grp = _cap_floor_group(key, config)
if grp not in groups or float(floors[key]["z"]) > float(floors[groups[grp]]["z"]):
groups[grp] = key
for grp, top_key in groups.items():
top = floors[top_key]
covered = roof_tops.get(grp, -1e9) >= float(top["z"]) - 0.8
if grp != "BASE" and not top.get("caps") and not covered:
print(
f"WARNING topless_group {grp}: top floor '{top_key}' has no caps and no "
f"roof_specs entry; add config roof_specs=[{{'floor_key': '{top_key}', ...}}] "
"or the model will have no roof plate.",
file=sys.stderr,
)
categories = {
key: {"label": value["label"], "color": value["color"]}
for key, value in DEFAULT_CATEGORIES.items()