feat(hero): v0.1.2 — scale calibration, façade detail, export preset refactor (#28)

Merged PR #28: v0.1.2 — scale calibration, façade detail, export preset

Co-authored-by: Zwitschi <zwitschi82@gmail.com>
This commit was merged in pull request #28.
This commit is contained in:
zwitschi authored and zwitschi committed 2026-11-08 18:48:33 +01:00
1 parent 640bff9631
commit ba68dcfdbc
60 files changed
+1114 -291

No files matched your search

+9 -1
View File
@@ -16,6 +16,7 @@ Geographic tools live in [`Geo/tools/`](../Geo/README.md) and the Blender-side b
| Tool | Purpose |
| --- | --- |
| `check-lfs.sh` | Fails if the `lfs` filter is missing or an LFS-tracked file was committed as a plain blob |
| `fbx_export_preset.py` | The **single** FBX export preset (`ue_metric_v1` / `ue_character_v1`): metres→centimetres via `FBX_SCALE_NONE`, axis mapping east +X / north −Y / up +Z, `mesh_smooth_type="FACE"` (smoothing groups survive the import). Every Blender exporter imports it instead of copying the argument block; `preset_kwargs()` is bpy-free and unit-tested. |
| `sibling_asset_audit.py` | Reads the sibling project's prop library from GLB headers into `Art/props/reuse-manifest.json`; copies nothing |
| `scale_test_export.py` / `ue_scale_test_import.py` | The 1 m = 100 uu scale test; the named presets `ue_metric_v1` live in these two files |
@@ -57,9 +58,16 @@ Geographic tools live in [`Geo/tools/`](../Geo/README.md) and the Blender-side b
| Command | Purpose |
| --- | --- |
| `UnrealEditor <uproject> /Game/Hollywood/DemoMap -game -qaselftest` | Headless behaviour check: drives forward input for 2 s, then resets and pauses. Logs `GigLine QA: ... PASS/FAIL` lines and a final `RESULT`. Runs only with `-qaselftest`, so normal play is unaffected. |
| `-qaselftest` phases | Walk, reset, pause/unpause, a 16-row seam transect (0 holes) and a ground-referenced wall probe (0/35), plus a frame-time capture writing `Saved/Profiling/perf-walk-frametimes.csv` and logging `GigLine PERF:`. |
| `-qaselftest` phases | Walk, reset, pause/unpause, a 16-row seam transect (0 holes), a ground-referenced wall probe (0/35) and a **facade occlusion probe** that fires sideways from the road centre and requires a blocking wall wherever a building is staged (0/9), plus a frame-time capture writing `Saved/Profiling/perf-walk-frametimes.csv` and logging `GigLine PERF:`. |
| `gigline.SetupLogs` cvar | Spawn/input setup logging, **off by default** (`DefaultEngine.ini [ConsoleVariables]`); enable at runtime with `gigline.SetupLogs 1`. |
## Reference and concept generation
| Tool | Purpose |
| --- | --- |
| `facade_detail_concepts.py` | Generates **frontal building plates** (whole elevation, entrance in its facade, or building with neighbours) from a local reference photograph with an image model (OpenRouter); close-up detail crops are deliberately not requested because they cannot be measured for proportion. `--list` is free and shows which studies have their reference present; `--all`/`--only <name>` generates. Never overwrites (writes `-v2`, `-v3`), writes a `.refgen.json` sidecar per image (model, prompt, source photo, SHA-256), and puts everything under `Art/reference/facade-details/` — gitignored, local-only, never shipped. Costs money per image, so it is never automatic. |
| `judge_screenshot.py` | (see Visual review) |
## Input injection
| Tool | Purpose |
+4 -14
View File
@@ -19,6 +19,9 @@ import os
import sys
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import fbx_export_preset as fbx_preset # noqa: E402
# blockout object name -> (asset name, note). Addresses from the verification doc.
BUILDINGS = {
@@ -69,20 +72,7 @@ def main():
bpy.context.view_layer.objects.active = new_obj
path = os.path.join(args.out, asset_name + ".fbx")
bpy.ops.export_scene.fbx(
filepath=path,
use_selection=True,
object_types={"MESH"},
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_NONE",
axis_forward="-Y",
axis_up="Z",
use_space_transform=True,
use_mesh_modifiers=True,
mesh_smooth_type="OFF",
path_mode="AUTO",
bake_space_transform=False,
)
fbx_preset.export_static(path, selection=True)
world = new_obj.matrix_world
zs = [(world @ v.co).z for v in new_mesh.vertices]
ys = [(world @ v.co).y for v in new_mesh.vertices]
+4 -14
View File
@@ -13,6 +13,9 @@ import os
import sys
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import fbx_export_preset as fbx_preset # noqa: E402
BUILDINGS = ("TCL Chinese Theatre", "Madame Tussaud's")
@@ -50,20 +53,7 @@ def main():
bpy.context.view_layer.objects.active = new_obj
path = os.path.join(args.out, name.replace(" ", "_").replace("'", "") + ".fbx")
bpy.ops.export_scene.fbx(
filepath=path,
use_selection=True,
object_types={"MESH"},
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_NONE",
axis_forward="-Y",
axis_up="Z",
use_space_transform=True,
use_mesh_modifiers=True,
mesh_smooth_type="OFF",
path_mode="AUTO",
bake_space_transform=False,
)
fbx_preset.export_static(path, selection=True)
world = new_obj.matrix_world
zs = [(world @ v.co).z for v in new_mesh.vertices]
print(f"[north] {name:22} verts {len(new_mesh.vertices):5} z {min(zs):+.2f}..{max(zs):+.2f} m "
+328
View File
@@ -0,0 +1,328 @@
#!/usr/bin/env python3
"""Generate frontal building plates from the local reference photography.
Each study takes one photograph we already hold (`Art/reference/`, gitignored) as
the geometric anchor and asks an image model to re-stage it as a clean **frontal
view of the building** — the whole elevation, the entrance in its facade, or the
building with its neighbours — evenly lit, no crowd, no staging, so the modelling
pass has something measurable instead of a tourist photo.
Deliberately **not** close-up detail crops: a doorway or cornice crop cannot be
measured for proportion, which is what the modelling pass actually needs.
python3 Tools/facade_detail_concepts.py --list
python3 Tools/facade_detail_concepts.py --only door-recess,parapet-motto
python3 Tools/facade_detail_concepts.py --all
python3 Tools/facade_detail_concepts.py --all --model google/gemini-2.5-flash-image
Output: `Art/reference/facade-details/<study>.png` plus a `<study>.refgen.json`
sidecar recording the model, the source photograph, the prompt and the SHA-256 of
the result. `Art/reference/` is gitignored, so **neither the images nor the
sidecars are committed** — they are local working material. The study list and
the tool are the committed part.
Design notes
------------
* Standard library only: the OpenRouter chat-completions call is `urllib`, and
the returned `data:` URL is decoded with `base64` and written straight to disk.
* An existing output is never overwritten; `-v2`, `-v3` … are used instead, so
re-running after a prompt edit keeps both studies comparable.
* Generation costs money, so it is never automatic: `--list` is free, and every
generating run prints the model and the study count first.
* The token is read from `OPENROUTER_API_KEY` or the ignored `.env` and is never
written to a sidecar or a log line.
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
REFERENCE_DIR = os.path.join(ROOT, "Art", "reference")
OUT_DIR = os.path.join(REFERENCE_DIR, "facade-details")
API_URL = "https://openrouter.ai/api/v1/chat/completions"
DEFAULT_MODEL = "google/gemini-2.5-flash-image"
# The instruction appended to every study. Kept identical to the sibling
# project's convention so the two sets stay comparable: the photograph fixes the
# geometry, the prompt only restages light, weather, people and surface.
ANCHOR_SUFFIX = (
"Use the attached reference photograph as the source of the architecture: keep "
"the building's proportions, storey count, column rhythm, band heights and "
"signage placement exactly as photographed. You may REFRAME — step back across "
"the street, zoom out or widen the field of view — so that the whole building "
"fits in the frame from the pavement to the parapet; the reference is often "
"cropped and the plate must not be. Keep the view exterior and frontal (or "
"three-quarter where asked). Restage only lighting, weather, people and surface "
"condition. Do not invent extra storeys, wings or ornaments, and do not change "
"the architecture to fit the frame."
)
# name -> (reference photo relative to Art/reference/, what the plate must show)
#
# Verified framing (vision pre-check, 2026-11-09): the model follows the reference
# crop closely, so a plate is only as wide as its source photo. `building-entrance`
# and `building-street-front` come back as full-elevation frontal views; the studies
# anchored on the tightly cropped 2009 facade photo stay cropped, because the model
# will not invent the parapet and sky that the photograph does not contain. A full
# building plate for 6840 needs a full-elevation photograph, which the local set
# does not have (see Docs/reference-notes-hollywood.md).
#
# Every study asks for a *frontal view of a building*, not a crop of one detail:
# the whole elevation, the entrance in its facade, or the building together with
# its neighbours. Close-up framing is deliberately absent — a detail crop cannot
# be measured for proportion, which is what the modelling pass needs.
STUDIES: dict[str, tuple[str, str]] = {
"building-front": (
"hollywood/el-capitan-facade-day-wikimedia-2009-10-27.jpg",
"A frontal view of the complete building shown in the reference "
"photograph: the whole elevation from the pavement to the parapet fits in "
"the frame with clear sky above the roofline and pavement below the ground "
"floor, shot straight on and centred. Nothing may be cut off at the top or "
"bottom. Even daylight, no crowd, no vehicles.",
),
"building-entrance": (
"el-capitan-entrance/01-hollywood-el-capitan-entrance.jpg",
"A frontal view of the building in the reference photograph, framed so its "
"street entrance is clearly visible as part of the facade — the doors and "
"the wall around them in proportion, not a close-up of the doorway. "
"Include the pavement in front. Even daylight, no crowd.",
),
"building-with-neighbours": (
"hollywood/el-capitan-theatre-blade-sign-day-wikimedia-2008-10.jpg",
"A straight-on view of the street wall in the reference photograph: the "
"building and its neighbouring buildings either side, each at full height "
"from pavement to parapet with sky above, the joins between them visible, "
"nothing cut off. Shot from across the road, parallel to the frontage. "
"Even daylight, no crowd.",
),
"building-street-front": (
"hollywood/walk-of-fame-terrazzo-ovation-day-cc0-2019-06-20.jpg",
"A frontal view along the pavement of the building in the reference "
"photograph: the building's frontage seen from street level with its "
"neighbours continuing either side and the pavement in the foreground. "
"Straight on, even daylight, no crowd.",
),
"building-front-oblique": (
"hollywood/el-capitan-facade-day-wikimedia-2009-10-27.jpg",
"A three-quarter view of the complete building in the reference "
"photograph: the frontal elevation and one side visible together so the "
"building's depth and mass read, with its neighbouring building at one "
"edge. The whole building stays in frame. Even daylight, no crowd.",
),
"theatre-front-with-neighbours": (
"el-capitan-theater-detail/01-el-capitan-marquee.jpg",
"A frontal view of the theatre in the reference photograph together with "
"the buildings either side of it, the whole frontage and its full height "
"in frame, shot from across the road. Even daylight, no crowd, marquee "
"lettering blocked out as unreadable texture.",
),
}
def load_token() -> str:
token = os.environ.get("OPENROUTER_API_KEY")
if token:
return token.strip()
env_path = os.path.join(ROOT, ".env")
if os.path.exists(env_path):
with open(env_path, encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if line.startswith("OPENROUTER_API_KEY="):
return line.split("=", 1)[1].strip().strip('"').strip("'")
raise SystemExit("no OpenRouter key: set OPENROUTER_API_KEY or add it to .env")
def build_prompt(study: str) -> str:
"""The full prompt for a study: its request plus the fixed anchor suffix."""
if study not in STUDIES:
raise KeyError(f"unknown study {study!r}; known: {sorted(STUDIES)}")
return f"{STUDIES[study][1]}\n\n{ANCHOR_SUFFIX}"
def reference_path(study: str) -> str:
return os.path.join(REFERENCE_DIR, STUDIES[study][0])
def missing_references() -> list[str]:
"""Studies whose source photograph is not present locally."""
return [name for name in STUDIES if not os.path.isfile(reference_path(name))]
def next_free_path(study: str, directory: str = OUT_DIR) -> str:
"""`<study>.png`, or `<study>-v2.png`, `-v3` … if the name is taken."""
base = os.path.join(directory, f"{study}.png")
if not os.path.exists(base):
return base
index = 2
while True:
candidate = os.path.join(directory, f"{study}-v{index}.png")
if not os.path.exists(candidate):
return candidate
index += 1
def data_url(path: str) -> str:
suffix = os.path.splitext(path)[1].lower()
mime = {".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png"}.get(suffix)
if not mime:
raise SystemExit(f"unsupported reference type: {path}")
with open(path, "rb") as handle:
return f"data:{mime};base64,{base64.b64encode(handle.read()).decode('ascii')}"
def decode_image(payload: dict) -> bytes:
"""Extract the returned image bytes from a chat-completions payload."""
message = (payload.get("choices") or [{}])[0].get("message", {})
urls = [item.get("image_url", {}).get("url", "")
for item in (message.get("images") or []) if isinstance(item, dict)]
if not urls:
match = re.search(r"data:image/[a-z]+;base64,[A-Za-z0-9+/=]+",
str(message.get("content") or ""))
if match:
urls.append(match.group(0))
if not urls or not urls[0]:
raise SystemExit(f"model returned no image data: {json.dumps(payload)[:400]}")
url = urls[0]
if url.startswith("data:"):
return base64.b64decode(url.split(",", 1)[1])
with urllib.request.urlopen(urllib.request.Request(url), timeout=120) as response:
return response.read()
def generate(study: str, token: str, model: str, force: bool = False) -> str:
"""Generate one study; returns the written path. Never overwrites by default."""
path = next_free_path(study)
if force and os.path.exists(os.path.join(OUT_DIR, f"{study}.png")):
path = os.path.join(OUT_DIR, f"{study}.png")
# Write to a temp name then replace, so a failed call cannot destroy the
# previous result.
target = path + ".new"
else:
target = path
body = {
"model": model,
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": build_prompt(study)},
{"type": "image_url", "image_url": {"url": data_url(reference_path(study))}},
],
}],
}
request = urllib.request.Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"HTTP-Referer": "https://git.allucanget.biz/zwitschi/gig-line",
"X-Title": "gig-line facade details",
},
method="POST",
)
payload = None
for attempt in range(3):
try:
with urllib.request.urlopen(request, timeout=180) as response:
payload = json.load(response)
break
except urllib.error.HTTPError as exc:
if exc.code == 429 or exc.code >= 500:
wait = 5 * (attempt + 1)
sys.stderr.write(f" HTTP {exc.code}; retrying in {wait}s\n")
time.sleep(wait)
continue
detail = exc.read().decode("utf-8", "replace")[:300]
raise SystemExit(f"{study}: HTTP {exc.code} — {detail}")
except urllib.error.URLError as exc:
sys.stderr.write(f" network error ({exc.reason}); retrying\n")
time.sleep(5 * (attempt + 1))
if payload is None:
raise SystemExit(f"{study}: no response after retries")
image = decode_image(payload)
os.makedirs(OUT_DIR, exist_ok=True)
with open(target, "wb") as handle:
handle.write(image)
if target != path:
os.replace(target, path)
import hashlib
sidecar = {
"study": study,
"generated": os.path.basename(path),
"generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"model": model,
"prompt": build_prompt(study),
"reference": {
"file": STUDIES[study][0],
"note": "local reference photography; Art/reference is gitignored and never shipped",
},
"sha256": hashlib.sha256(image).hexdigest(),
"bytes": len(image),
"redistribution": "local development reference only; not committed, not shipped",
}
sidecar_path = os.path.splitext(path)[0] + ".refgen.json"
with open(sidecar_path, "w", encoding="utf-8") as handle:
json.dump(sidecar, handle, indent=2)
if token in json.dumps(sidecar):
raise SystemExit("refusing to write a sidecar containing the token")
return path
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--list", action="store_true", help="list studies and exit (free)")
ap.add_argument("--all", action="store_true", help="generate every study")
ap.add_argument("--only", help="comma-separated study names")
ap.add_argument("--model", default=DEFAULT_MODEL)
ap.add_argument("--force", action="store_true",
help="replace the existing <study>.png instead of writing a -vN")
args = ap.parse_args(argv)
if args.list or not (args.all or args.only):
missing = set(missing_references())
print(f"{len(STUDIES)} studies; model {args.model}")
for name, (ref, _prompt) in STUDIES.items():
state = "MISSING reference" if name in missing else "ready"
print(f" {name:22} {state:18} <- {ref}")
if missing:
print(f"\n{len(missing)} study(ies) cannot run without their reference photograph.")
return 0
names = list(STUDIES) if args.all else [s.strip() for s in args.only.split(",") if s.strip()]
unknown = [n for n in names if n not in STUDIES]
if unknown:
raise SystemExit(f"unknown study(ies): {unknown}; known: {sorted(STUDIES)}")
blocked = [n for n in names if n in set(missing_references())]
if blocked:
raise SystemExit(f"missing reference photograph for: {blocked}")
token = load_token()
print(f"generating {len(names)} study(ies) with {args.model} -> {OUT_DIR}")
for index, name in enumerate(names, 1):
print(f"[{index}/{len(names)}] {name}")
try:
path = generate(name, token, args.model, force=args.force)
except SystemExit as exc:
sys.stderr.write(f" FAILED: {exc}\n")
continue
print(f" wrote {os.path.relpath(path, ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""The one FBX export preset for this project ("ue_metric_v1"/"ue_character_v1").
Before this module the same `bpy.ops.export_scene.fbx(...)` argument block was
copied into six scripts (hero, frontage, north buildings, site, scale test, MPFB
character). They had already drifted only by accident, and every one of them
carried `mesh_smooth_type="OFF"` — which is why Unreal logged "No smoothing group
information was found for this mesh" on every import and round parts rendered
faceted. One preset, one place to fix that.
Use from inside Blender:
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "Tools"))
import fbx_export_preset as preset
preset.export_static(path) # whole scene, MESH only
preset.export_static(path, selection=True) # selected objects only
preset.export_character(path) # armature + mesh, character flags
`preset_kwargs()` is pure (no `bpy`), so the argument set can be unit-tested
without Blender — see Tools/tests/test_fbx_export_preset.py.
Why these values:
* `FBX_SCALE_NONE` + `apply_unit_scale` keeps Blender metres → Unreal centimetres
at exactly ×100, verified by the three-cube scale test (1 m → 100.00 uu).
* `axis_forward="-Y"`, `axis_up="Z"` is the project's recorded mapping: east → +X,
north → −Y, up → +Z.
* `mesh_smooth_type="FACE"` exports smoothing groups. `"OFF"` (the old value)
drops them, so Unreal rebuilds flat normals and every cylinder is faceted.
* `use_mesh_modifiers=True` bakes the bevel/modifier stack at export; the source
`.blend` stays non-destructive.
"""
from __future__ import annotations
# Shared by every mesh export. Values are the recorded ue_metric_v1 preset.
_METRIC = {
"object_types": {"MESH"},
"apply_unit_scale": True,
"apply_scale_options": "FBX_SCALE_NONE",
"axis_forward": "-Y",
"axis_up": "Z",
"use_space_transform": True,
"use_mesh_modifiers": True,
"mesh_smooth_type": "FACE",
"path_mode": "AUTO",
"bake_space_transform": False,
}
# Character exports differ only in the object set and the armature/path flags.
_CHARACTER = dict(
_METRIC,
object_types={"ARMATURE", "MESH"},
add_leaf_bones=False,
path_mode="COPY",
embed_textures=False,
)
PRESETS = {"ue_metric_v1": _METRIC, "ue_character_v1": _CHARACTER}
def preset_kwargs(preset: str = "ue_metric_v1", selection: bool = False, **overrides) -> dict:
"""Return the `bpy.ops.export_scene.fbx` argument dict (no `bpy` needed).
`preset` selects the base set, `selection` decides whether only selected
objects are exported, and `overrides` wins last for the rare special case.
"""
if preset not in PRESETS:
raise KeyError(f"unknown preset {preset!r}; known: {sorted(PRESETS)}")
kwargs = dict(PRESETS[preset])
kwargs["use_selection"] = bool(selection)
kwargs.update(overrides)
if "filepath" in kwargs:
raise ValueError("pass the path to export_static/export_character, not as an override")
return kwargs
def _export(path: str, preset: str, selection: bool, overrides: dict) -> str:
import bpy # imported here so `preset_kwargs` stays usable without Blender
kwargs = preset_kwargs(preset, selection=selection, **overrides)
bpy.ops.export_scene.fbx(filepath=path, **kwargs)
return path
def export_static(path: str, selection: bool = False, **overrides) -> str:
"""Export meshes with the ue_metric_v1 preset. Returns the path."""
return _export(path, "ue_metric_v1", selection, overrides)
def export_character(path: str, selection: bool = False, **overrides) -> str:
"""Export armature + mesh with the ue_character_v1 preset. Returns the path."""
return _export(path, "ue_character_v1", selection, overrides)
+91 -29
View File
@@ -33,6 +33,9 @@ import os
import sys
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import fbx_export_preset as fbx_preset # noqa: E402
# --- measured / derived ------------------------------------------------------
FRONTAGE_W = 25.75
@@ -50,8 +53,12 @@ FRONTAGE_Y = 0.0 # front plane sits at the building line of the block fra
PEDESTAL_H = 1.45 # column pedestal top; entrance platform sits on it
COLUMN_D = 0.95 # Ionic shaft diameter at the base
CAPITAL_H = 0.95
ENTABLATURE_H = 3.40 # band between the capitals and the motto panel
PARAPET_H = 2.20 # motto panel and cornice above the entablature
ENTABLATURE_H = 3.00 # band between the capitals and the motto panel
# 3.40 -> 3.00 on 2026-11-09: the photographs put the
# colonnade at 50-60 % of the 14.5 m elevation, and our
# 3.40/2.20 entablature+parapet left it at 47.6 %. Thinning
# both lifts the colonnade to 7.70 m = 53.1 %, inside the band.
PARAPET_H = 1.80 # motto panel and cornice above the entablature (see above)
PORTAL_W = 3.10 # each of the three door openings
PORTAL_H = 3.40
STEP_TREAD = 0.34
@@ -70,7 +77,7 @@ def cube(name, x, y, z, dx, dy, dz, material=None):
return obj
def cylinder(name, x, y, z0, z1, radius, material, vertices=24):
def cylinder(name, x, y, z0, z1, radius, material, vertices=24, smooth=True):
bpy.ops.mesh.primitive_cylinder_add(
vertices=vertices,
radius=radius,
@@ -81,6 +88,30 @@ def cylinder(name, x, y, z0, z1, radius, material, vertices=24):
obj.name = name
if material:
obj.data.materials.append(material)
if smooth:
# Round parts must shade smoothly *around* the axis while keeping the
# caps creased. Without this the columns read as faceted prisms, and the
# FBX carries no smoothing groups at all (Unreal warns about it).
bpy.ops.object.shade_smooth_by_angle(angle=math.radians(35.0))
return obj
def disc_on_wall(name, x, y, z, radius, thickness, material=None, vertices=24):
"""A round disc mounted vertically on a wall face.
`cylinder()` builds along Z, so a "medallion" made with it is a pancake lying
flat on top of the parapet rather than a disc on its face — which is what the
first build did (1.1 m across in Y, 0.02 m thick in Z, sitting at the coping).
This rotates the cylinder 90 degrees about X so the axis points along Y and
the disc faces the street.
"""
obj = cylinder(name, x, y, z - thickness / 2.0, z + thickness / 2.0,
radius, material, vertices=vertices)
obj.rotation_euler = (math.radians(90.0), 0.0, 0.0)
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
return obj
@@ -132,14 +163,32 @@ def build():
col_xs.append(x)
cube(f"Hero_Pedestal_{i + 1}", x, -0.62, PEDESTAL_H + 0.27,
1.24, 1.24, 0.54, stone)
cylinder(f"Hero_Column_{i + 1}", x, -0.55, PEDESTAL_H + 0.55,
PEDESTAL_H + 0.55 + (HEIGHT - ENTABLATURE_H - PARAPET_H - PEDESTAL_H - 0.55 - CAPITAL_H),
# Base moulding: a taller, wider cylinder where the shaft meets the
# pedestal. Without it the shaft starts straight off a square plinth,
# which is not how an Ionic base reads in silhouette.
base_z0 = PEDESTAL_H + 0.55
base_h = 0.22
cylinder(f"Hero_ColumnBase_{i + 1}", x, -0.55, base_z0, base_z0 + base_h,
0.68, stone, vertices=20)
shaft_z0 = base_z0 + base_h
cap_z0 = HEIGHT - ENTABLATURE_H - PARAPET_H - CAPITAL_H
cylinder(f"Hero_Column_{i + 1}", x, -0.55, shaft_z0, cap_z0,
COLUMN_D / 2.0, stone)
cylinder(f"Hero_Capital_{i + 1}", x, -0.55,
HEIGHT - ENTABLATURE_H - PARAPET_H - CAPITAL_H,
HEIGHT - ENTABLATURE_H - PARAPET_H, 0.62, stone, vertices=16)
# Capital block, then the square abacus that carries the architrave.
# The abacus takes the top 0.14 m of the capital zone so the colonnade
# still ends at HEIGHT - ENTABLATURE_H - PARAPET_H (proportion unchanged).
abacus_h = 0.14
cylinder(f"Hero_Capital_{i + 1}", x, -0.55, cap_z0,
HEIGHT - ENTABLATURE_H - PARAPET_H - abacus_h, 0.62, stone, vertices=16)
cube(f"Hero_Abacus_{i + 1}", x, -0.55,
HEIGHT - ENTABLATURE_H - PARAPET_H - abacus_h / 2.0,
1.30, 1.30, abacus_h, stone)
note("Hero_Column_x6", (COLUMN_D, COLUMN_D, HEIGHT - ENTABLATURE_H - PARAPET_H - PEDESTAL_H),
f"6 columns at {COLUMN_BAY} m centres (sibling notes x measured frontage)")
note("Hero_ColumnBase_x6", (1.36, 1.36, 0.22),
"assumption: Ionic base moulding; photographs show a wider base at the shaft foot")
note("Hero_Abacus_x6", (1.30, 1.30, 0.14),
"assumption: square abacus under the architrave, as Ionic capitals carry")
# --- entablature and parapet ------------------------------------------
ent_z0 = HEIGHT - ENTABLATURE_H - PARAPET_H
@@ -147,9 +196,25 @@ def build():
# elevation reads as layered stone rather than one flat plane.
cube("Hero_Architrave", 0.0, -1.55, ent_z0 + 0.42, FRONTAGE_W, 1.65, 0.84, stone)
note("Hero_Architrave", (FRONTAGE_W, 1.65, 0.84), "assumption: stacked entablature bands")
# Cornice under the parapet.
cube("Hero_Cornice", 0.0, -1.6, HEIGHT - PARAPET_H - 0.18, FRONTAGE_W, 1.75, 0.36, stone)
# Cornice under the parapet: a projecting corona carried on a dentil course,
# so the top of the order reads as layered stone with a shadow line rather
# than one flat box. Dentils hang under the corona and stand 0.25 m clear of
# it, which is what gives the elevation its cornice shadow at street level.
cornice_z = HEIGHT - PARAPET_H - 0.18
cube("Hero_Cornice", 0.0, -1.6, cornice_z, FRONTAGE_W, 1.75, 0.36, stone)
note("Hero_Cornice", (FRONTAGE_W, 1.75, 0.36), "assumption: projecting cornice line")
DENTIL_W, DENTIL_D, DENTIL_H, DENTIL_GAP = 0.18, 0.30, 0.22, 0.27
dentil_y = -2.30
dentil_z = cornice_z - 0.18 - DENTIL_H / 2.0
dentil_span = FRONTAGE_W - 2.0
dentil_count = int(dentil_span / (DENTIL_W + DENTIL_GAP))
for i in range(dentil_count):
dx = -dentil_span / 2.0 + (DENTIL_W + DENTIL_GAP) * i + DENTIL_W / 2.0
cube(f"Hero_Dentil_{i + 1}", dx, dentil_y, dentil_z,
DENTIL_W, DENTIL_D, DENTIL_H, stone)
note("Hero_Dentil_xN", (DENTIL_W, DENTIL_D, DENTIL_H),
f"{dentil_count} dentils at {DENTIL_W + DENTIL_GAP:.2f} m centres under the corona; "
"assumption: photographed cornice reads as a dentilled course")
cube("Hero_Entablature", 0.0, -0.75, ent_z0 + ENTABLATURE_H / 2.0,
FRONTAGE_W, 1.5, ENTABLATURE_H, stone)
note("Hero_Entablature", (FRONTAGE_W, 1.5, ENTABLATURE_H), "assumption: entablature depth")
@@ -163,11 +228,13 @@ def build():
FRONTAGE_W - 3.0, 0.08, 0.85, stone_dark)
note("Hero_MottoBand", (FRONTAGE_W - 3.0, 0.08, 0.85), "photographs: motto panel above the colonnade")
# Medallions either side of the inscription.
# Medallions either side of the inscription: discs on the parapet face, not
# pancakes on the coping (see disc_on_wall).
for i, x in enumerate((-6.2, 6.2), start=1):
cylinder(f"Hero_Medallion_{i}", x, -1.36, HEIGHT - PARAPET_H / 2.0 + 0.42,
HEIGHT - PARAPET_H / 2.0 + 0.44, 0.55, stone_dark, vertices=20)
note("Hero_Medallion_x2", (1.1, 1.1, 0.02), "photographs: two stone discs beside the motto")
disc_on_wall(f"Hero_Medallion_{i}", x, -1.30, HEIGHT - PARAPET_H / 2.0,
0.55, 0.04, stone_dark, vertices=20)
note("Hero_Medallion_x2", (1.1, 0.04, 1.1),
"photographs: two stone discs beside the motto, mounted on the parapet face")
# --- entrances ---------------------------------------------------------
# Three portals between column pairs, each with its own short flight. The
@@ -241,32 +308,27 @@ def build():
# --- windows -----------------------------------------------------------
# Two ranks of windows between the columns and behind the colonnade.
# Y must sit on the wall plane: the mass front face is at Y -0.50 and the
# columns stand proud to -1.02. These were at -1.98, i.e. 1.44 m in FRONT of
# the wall and ahead of the column line, so the glazing floated in the
# colonnade instead of reading as openings behind it (visible in the
# review-hero-facade-* shots). WINDOW_Y puts the pane 6 cm proud of the wall,
# safely behind the columns.
WINDOW_Y = -0.56
for rank, z in enumerate((4.4, 8.2), start=1):
for i, x in enumerate(col_xs[:-1], start=1):
wx = x + COLUMN_BAY / 2.0
cube(f"Hero_Window_{rank}_{i}", wx, -1.98, z, 2.0, 0.08, 1.9, glass)
cube(f"Hero_Window_{rank}_{i}", wx, WINDOW_Y, z, 2.0, 0.08, 1.9, glass)
note("Hero_Window_x10", (2.0, 0.08, 1.9), "photographs: window bands behind the colonnade")
return parts, lines
def export_fbx(path):
# Preset lives in Tools/fbx_export_preset.py (ue_metric_v1).
os.makedirs(os.path.dirname(path), exist_ok=True)
# Named export preset "ue_metric_v1" - same settings as Tools/scale_test_export.py.
bpy.ops.export_scene.fbx(
filepath=path,
use_selection=False,
object_types={"MESH"},
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_NONE",
axis_forward="-Y",
axis_up="Z",
use_space_transform=True,
use_mesh_modifiers=True,
mesh_smooth_type="OFF",
path_mode="AUTO",
bake_space_transform=False,
)
fbx_preset.export_static(path)
print(f"[hero] exported FBX preset ue_metric_v1 -> {path}")
+4 -16
View File
@@ -19,6 +19,9 @@ import sys
import zlib
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import fbx_export_preset as fbx_preset # noqa: E402
import numpy
from mathutils import Euler
@@ -149,22 +152,7 @@ def make_diffuse(human, size=1024):
def export_fbx(human, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
# Named export preset "ue_character_v1" — change only via a new preset name.
bpy.ops.export_scene.fbx(
filepath=path,
use_selection=False,
object_types={"ARMATURE", "MESH"},
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_NONE",
axis_forward="-Y",
axis_up="Z",
use_space_transform=True,
use_mesh_modifiers=True,
add_leaf_bones=False,
path_mode="COPY",
embed_textures=False,
mesh_smooth_type="OFF",
bake_space_transform=False,
)
fbx_preset.export_character(path)
log(f"export: FBX preset ue_character_v1 -> {path}")
+4 -14
View File
@@ -16,6 +16,9 @@ import os
import sys
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import fbx_export_preset as fbx_preset # noqa: E402
def build_scene():
@@ -44,20 +47,7 @@ def build_scene():
def export_fbx(path):
os.makedirs(os.path.dirname(path), exist_ok=True)
# Named export preset "ue_metric_v1" - change only via a new preset name.
bpy.ops.export_scene.fbx(
filepath=path,
use_selection=False,
object_types={"MESH"},
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_NONE",
axis_forward="-Y",
axis_up="Z",
use_space_transform=True,
use_mesh_modifiers=True,
mesh_smooth_type="OFF",
path_mode="AUTO",
bake_space_transform=False,
)
fbx_preset.export_static(path)
print(f"[scale_test] exported FBX preset ue_metric_v1 -> {path}")
+108
View File
@@ -0,0 +1,108 @@
"""Tests for Tools/facade_detail_concepts.py — the pure parts.
No network calls: the OpenRouter request and the image bytes are represented as
the small structures the API uses. Generation itself is manual and paid.
"""
import base64
import json
import os
import sys
import unittest
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "Tools"))
import facade_detail_concepts as fc # noqa: E402
class StudyTableTest(unittest.TestCase):
def test_every_study_has_a_reference_and_a_prompt(self):
self.assertTrue(fc.STUDIES)
for name, (ref, prompt) in fc.STUDIES.items():
self.assertTrue(ref, f"{name} has no reference")
self.assertTrue(prompt.strip(), f"{name} has no prompt")
# References are relative to Art/reference and never escape it.
self.assertFalse(os.path.isabs(ref), f"{name} reference is absolute")
self.assertNotIn("..", ref, f"{name} reference escapes the directory")
def test_prompt_always_carries_the_anchor_suffix(self):
for name in fc.STUDIES:
prompt = fc.build_prompt(name)
self.assertIn(fc.ANCHOR_SUFFIX, prompt)
self.assertIn(fc.STUDIES[name][1], prompt)
def test_unknown_study_raises(self):
with self.assertRaises(KeyError):
fc.build_prompt("no-such-study")
class NextFreePathTest(unittest.TestCase):
def test_uses_the_plain_name_when_free(self):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
self.assertEqual(os.path.basename(fc.next_free_path("x", tmp)), "x.png")
def test_never_overwrites(self):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
open(os.path.join(tmp, "x.png"), "w").close()
self.assertEqual(os.path.basename(fc.next_free_path("x", tmp)), "x-v2.png")
open(os.path.join(tmp, "x-v2.png"), "w").close()
self.assertEqual(os.path.basename(fc.next_free_path("x", tmp)), "x-v3.png")
class DecodeImageTest(unittest.TestCase):
PAYLOAD_BYTES = b"\x89PNG\r\n\x1a\nfake"
def _data_url(self):
return "data:image/png;base64," + base64.b64encode(self.PAYLOAD_BYTES).decode()
def test_reads_message_images(self):
payload = {"choices": [{"message": {
"images": [{"image_url": {"url": self._data_url()}}]}}]}
self.assertEqual(fc.decode_image(payload), self.PAYLOAD_BYTES)
def test_reads_a_data_url_embedded_in_content(self):
payload = {"choices": [{"message": {"content": f"here: {self._data_url()}"}}]}
self.assertEqual(fc.decode_image(payload), self.PAYLOAD_BYTES)
def test_refusal_raises_with_the_text(self):
payload = {"choices": [{"message": {"content": "I cannot do that."}}]}
with self.assertRaises(SystemExit):
fc.decode_image(payload)
class DataUrlTest(unittest.TestCase):
def test_encodes_a_jpeg(self):
import tempfile
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as handle:
handle.write(b"jpegbytes")
path = handle.name
try:
url = fc.data_url(path)
self.assertTrue(url.startswith("data:image/jpeg;base64,"))
finally:
os.unlink(path)
def test_rejects_an_unsupported_type(self):
import tempfile
with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as handle:
path = handle.name
try:
with self.assertRaises(SystemExit):
fc.data_url(path)
finally:
os.unlink(path)
class SidecarShapeTest(unittest.TestCase):
def test_studies_and_outputs_are_local_only(self):
# The output directory lives under the gitignored Art/reference tree, so
# neither the images nor the sidecars can be committed.
self.assertIn(os.path.join("Art", "reference"), fc.OUT_DIR)
self.assertIn("gitignored", fc.__doc__)
if __name__ == "__main__":
unittest.main()
+70
View File
@@ -0,0 +1,70 @@
"""Tests for Tools/fbx_export_preset.py.
The preset module keeps its argument set in plain dicts and builds it in
`preset_kwargs()`, so the export contract can be checked without starting
Blender. Only `export_static`/`export_character` import `bpy`.
"""
import os
import sys
import unittest
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "Tools"))
import fbx_export_preset as preset # noqa: E402
class MetricPresetTest(unittest.TestCase):
def test_scale_and_axis_contract(self):
# These three are the project's recorded conversion contract: metres ->
# centimetres by a factor of exactly 100, east +X, north -Y, up +Z.
kwargs = preset.preset_kwargs()
self.assertTrue(kwargs["apply_unit_scale"])
self.assertEqual(kwargs["apply_scale_options"], "FBX_SCALE_NONE")
self.assertEqual(kwargs["axis_forward"], "-Y")
self.assertEqual(kwargs["axis_up"], "Z")
def test_smoothing_groups_are_exported(self):
# "OFF" (the pre-refactor value) drops smoothing groups and every Unreal
# import warns about it, with round parts faceted.
self.assertEqual(preset.preset_kwargs()["mesh_smooth_type"], "FACE")
def test_selection_flag(self):
self.assertFalse(preset.preset_kwargs()["use_selection"])
self.assertTrue(preset.preset_kwargs(selection=True)["use_selection"])
def test_object_types_are_meshes_only(self):
self.assertEqual(preset.preset_kwargs()["object_types"], {"MESH"})
class CharacterPresetTest(unittest.TestCase):
def test_character_exports_armature_and_mesh(self):
kwargs = preset.preset_kwargs("ue_character_v1")
self.assertEqual(kwargs["object_types"], {"ARMATURE", "MESH"})
self.assertFalse(kwargs["add_leaf_bones"])
self.assertEqual(kwargs["path_mode"], "COPY")
self.assertFalse(kwargs["embed_textures"])
def test_character_keeps_the_scale_contract(self):
kwargs = preset.preset_kwargs("ue_character_v1")
self.assertEqual(kwargs["apply_scale_options"], "FBX_SCALE_NONE")
self.assertEqual(kwargs["mesh_smooth_type"], "FACE")
class OverrideTest(unittest.TestCase):
def test_overrides_win(self):
kwargs = preset.preset_kwargs(mesh_smooth_type="OFF")
self.assertEqual(kwargs["mesh_smooth_type"], "OFF")
def test_unknown_preset_raises(self):
with self.assertRaises(KeyError):
preset.preset_kwargs("ue_imperial_v9")
def test_filepath_must_not_be_an_override(self):
with self.assertRaises(ValueError):
preset.preset_kwargs(filepath="/tmp/x.fbx")
if __name__ == "__main__":
unittest.main()
+9 -3
View File
@@ -236,7 +236,11 @@ try:
# the plinth, which is what "portal detail" means here.
("hero-portals", unreal.Vector(hero_x + 100, -2250, 170), unreal.Vector(hero_x + 100, hero_y, 230)),
# straight on from the north sidewalk; the building body spans Y -1443..+250
("hero-facade-front", unreal.Vector(hero_x + 200, -3200, 420), unreal.Vector(hero_x, hero_y + 400, 760)),
# Level horizon: camera height == target height, so the elevation's
# verticals stay parallel. The old shot looked up ~4 deg from 4.2 m at a
# 7.6 m target, which converged the columns — the one thing an
# architectural elevation must not do (archviz: "straight verticals").
("hero-facade-front", unreal.Vector(hero_x + 200, -3200, 760), unreal.Vector(hero_x, hero_y + 400, 760)),
# oblique from the north-west, reading the colonnade in depth
("hero-facade-oblique", unreal.Vector(hero_x - 2200, -3400, 620), unreal.Vector(hero_x + 300, hero_y, 700)),
]
@@ -276,12 +280,14 @@ try:
demo_shots = [
# 14 m back so the 14.5 m elevation fits: at 2 m the camera sees only
# the colonnade's underside.
("demo-spawn-view", unreal.Vector(-13336, -3100, 420), unreal.Vector(-13336, 1300, 620)),
# Level horizon for the same reason: a block elevation is read by its
# verticals, and a pitched camera makes them lean.
("demo-spawn-view", unreal.Vector(-13336, -3100, 620), unreal.Vector(-13336, 1300, 620)),
# Street level, from the north sidewalk: the old camera sat at Y -400,
# inside the facade body (which spans Y -1457..-200), so it looked at
# the unlit back face. Y -2600 is on the sidewalk in front of the lit
# elevation.
("demo-street-level", unreal.Vector(-13420, -1650, 170), unreal.Vector(-13336, 1300, 400)),
("demo-street-level", unreal.Vector(-13420, -1650, 170), unreal.Vector(-13336, 1300, 170)),
# The designated mid-block crossing. Street arc length runs from the
# west end (s=0 at X -27966 cm), so s=130.1 m is UE X -14956, not the
# -24291 the old camera used (that is the s=36.6 crossing). Camera sits
+10
View File
@@ -61,6 +61,16 @@ def measure_and_place():
if asset is None:
log(f"MISSING {DEST}/SM_HeroFacade")
return
# Collision: complex-as-simple, not auto-generated convex hulls.
# The facade is 95 separate parts across 26 m; Unreal's auto hull generation
# wraps them in a few coarse hulls that bulged into the street (the QA wall
# probe went 0/35 -> 2/35 after trying it). Complex-as-simple makes the real
# triangles the simple collision, so line traces and capsule sweeps block on
# the actual wall — the same approach used for the terrain, for the same
# reason. The flag lives on the asset, so save it explicitly.
unreal.GigLineAssetTools.set_complex_collision_as_simple(asset, True)
saved = unreal.EditorAssetLibrary.save_loaded_asset(asset)
log(f"collision: {unreal.GigLineAssetTools.get_collision_complexity(asset)} (saved={saved})")
box = asset.get_bounding_box()
mn, mx = box.min, box.max
log(f"SM_HeroFacade bounds cm: size=({mx.x - mn.x:.1f}, {mx.y - mn.y:.1f}, {mx.z - mn.z:.1f}) "