"""Fusion エクスポート(ボディ群)からシーン YAML の dict を組み立てる.
入力は「ボディ名・所属トップレベルオカレンス・STL パス・頂点」の並びと対応表,
ベースのシーン dict(材質・センサ・render 設定の流用元)で,ファイル I/O は行わない
(STL の読込とマニフェストの解釈は呼び出し側=`scripts/fusion_to_scene.py` の責務).
処理の流れ:
1. detect_led_bodies: OBB 寸法がパッケージ寸法に一致するボディを LED とみなす
2. assign_board_labels: LED を含むトップレベルオカレンス(LED ユニット)ごとに
bottom / right / left / top を決める(geometry.led_boards の規則)
3. build_leds: 発光方向・中心・サイズを決め,基板内の並び順で `led_<board>_<k>` を振る
4. build_light_entries / build_mesh_entries: シーン YAML の lights / geometry.meshes
5. build_scene_dict: ベース dict の meshes と lights を差し替える
"""
from __future__ import annotations
import copy
import logging
import re
from collections import defaultdict
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
from sm_tias_lightsim.fusion_import.leds import (
LedGeometry,
OrientedBox,
compute_led_geometry,
compute_oriented_box,
could_be_led,
matches_package,
resolve_led_direction,
)
from sm_tias_lightsim.fusion_import.mapping import FusionMapping, LedDetectionConfig
from sm_tias_lightsim.geometry.led_boards import (
board_order_index,
classify_board_position,
order_leds_on_board,
)
from sm_tias_lightsim.scene.paths import relative_mesh_path
_logger = logging.getLogger(__name__)
# 出力 YAML の丸め桁(既存 extract_led_positions_from_stl.py の 4 桁に合わせる.方向は 6 桁)
_POS_DECIMALS = 4
_DIR_DECIMALS = 6
# LED の長辺が矩形の局所軸からこれ以上ずれていたら警告する [deg]
_MISALIGN_WARN_DEG = 1.0
@dataclass(frozen=True)
class BodyInput:
"""1 ボディの入力(マニフェストの記述 + 読み込んだ頂点).
Attributes:
index: マニフェスト内の通し番号.
name: Fusion のボディ名.
top_occurrence: トップレベルオカレンス名(ルートのボディは空文字).
stl_path: シーン YAML から参照するワールド座標の STL のパス(呼び出し側が
manifest の transform を適用して書き出す先).
vertices: 頂点座標 (N, 3),ワールド座標 [mm](transform 適用済み).
"""
index: int
name: str
top_occurrence: str
stl_path: Path
vertices: np.ndarray
@dataclass(frozen=True)
class NamedLed:
"""ID を振った LED.
Attributes:
id: 光源 ID(例: led_bottom_0).
board: 基板ラベル.
body_index: 元ボディの通し番号.
top_occurrence: 所属トップレベルオカレンス名.
geometry: 面光源ジオメトリ.
"""
id: str
board: str
body_index: int
top_occurrence: str
geometry: LedGeometry
def detect_led_bodies(bodies: Sequence[BodyInput],
led_cfg: LedDetectionConfig) -> dict[int, OrientedBox]:
"""パッケージ寸法に一致するボディを LED として検出する.
Args:
bodies: 全ボディ.
led_cfg: LED 識別設定.
Returns:
LED と判定したボディの index → OBB.
"""
found: dict[int, OrientedBox] = {}
for body in bodies:
aabb_ext = body.vertices.max(axis=0) - body.vertices.min(axis=0)
if not could_be_led(aabb_ext, led_cfg.package_dims_mm, led_cfg.tolerance_mm):
continue
box = compute_oriented_box(body.vertices)
if matches_package(box.extents, led_cfg.package_dims_mm, led_cfg.tolerance_mm):
found[body.index] = box
return found
def _union_aabb_center(bodies: Sequence[BodyInput]) -> np.ndarray:
"""複数ボディの和集合 AABB の中心 [mm]."""
lo = np.min([b.vertices.min(axis=0) for b in bodies], axis=0)
hi = np.max([b.vertices.max(axis=0) for b in bodies], axis=0)
return (lo + hi) / 2.0
def _unit_reference_centers(bodies: Sequence[BodyInput],
led_boxes: dict[int, OrientedBox]) -> dict[str, np.ndarray]:
"""トップレベルオカレンスごとの「LED 以外のボディ」の中心(和集合 AABB 中心)."""
others: dict[str, list[BodyInput]] = defaultdict(list)
for body in bodies:
if body.index not in led_boxes:
others[body.top_occurrence].append(body)
return {occ: _union_aabb_center(group) for occ, group in others.items()}
def assign_board_labels(bodies: Sequence[BodyInput], led_boxes: dict[int, OrientedBox],
overrides: dict[str, str] | None = None) -> dict[str, str]:
"""LED を含むトップレベルオカレンスごとに基板ラベルを決める.
基板の位置はユニット内の LED 以外のボディ(基板カバー等)の中心で判定する
(既存 extract_led_positions_from_stl.py がカバー中心で判定していたのと同じ).
LED 以外のボディが無いユニットは LED 中心の平均で判定する.
Args:
bodies: 全ボディ.
led_boxes: detect_led_bodies の結果.
overrides: トップレベルオカレンス名 → 基板ラベルの手動指定.
Returns:
トップレベルオカレンス名 → 基板ラベル.
Raises:
ValueError: 2 つのユニットが同じ基板ラベルになった場合.
"""
overrides = overrides or {}
by_index = {b.index: b for b in bodies}
led_units: dict[str, list[int]] = defaultdict(list)
for idx in led_boxes:
led_units[by_index[idx].top_occurrence].append(idx)
refs = _unit_reference_centers(bodies, led_boxes)
labels: dict[str, str] = {}
for occ, idxs in led_units.items():
if occ in overrides:
labels[occ] = overrides[occ]
continue
# ルート直下(occ="")の「LED 以外」は筐体等なので基板位置の判定には使わない
if occ and occ in refs:
center = refs[occ]
else:
center = np.mean([led_boxes[i].center for i in idxs], axis=0)
labels[occ] = classify_board_position(center)
seen: dict[str, str] = {}
for occ, label in labels.items():
if label in seen:
msg = (
f"LED ユニット {seen[label]!r} と {occ!r} が同じ基板ラベル {label!r} になりました."
"対応表の boards で各ユニットのラベルを指定してください"
)
raise ValueError(msg)
seen[label] = occ
return labels
def build_leds(bodies: Sequence[BodyInput], led_boxes: dict[int, OrientedBox],
board_labels: dict[str, str], led_cfg: LedDetectionConfig) -> list[NamedLed]:
"""各 LED の発光方向・ジオメトリを決め,基板ラベルと並び順で ID を振る.
Args:
bodies: 全ボディ.
led_boxes: detect_led_bodies の結果.
board_labels: assign_board_labels の結果.
led_cfg: LED 設定(方向の上書きを含む).
Returns:
BOARD_ORDER 順・基板内の並び順に並べた NamedLed のリスト.
"""
by_index = {b.index: b for b in bodies}
refs = _unit_reference_centers(bodies, led_boxes)
per_board: dict[str, list[tuple[int, str, LedGeometry]]] = defaultdict(list)
for idx, box in led_boxes.items():
occ = by_index[idx].top_occurrence
override = led_cfg.direction_overrides.get(occ, led_cfg.direction)
# ルート直下の LED はユニットの概念が無いので,自動判定の参照点を持たない
ref = refs.get(occ) if occ else None
direction = resolve_led_direction(box, ref, override)
geom = compute_led_geometry(box, direction)
if geom.inplane_misalignment_deg > _MISALIGN_WARN_DEG:
_logger.warning(
"LED(ボディ %d, %s)の長辺が矩形の局所軸から %.1f° 回転しています."
"面光源は局所軸に沿った矩形でしか表せないため向きは再現されません",
idx, by_index[idx].name, geom.inplane_misalignment_deg,
)
if geom.normal_misalignment_deg > _MISALIGN_WARN_DEG:
_logger.warning(
"LED(ボディ %d)の上書き方向が厚み方向から %.1f° ずれています",
idx, geom.normal_misalignment_deg,
)
per_board[board_labels[occ]].append((idx, occ, geom))
leds: list[NamedLed] = []
for board in sorted(per_board, key=board_order_index):
group = per_board[board]
order = order_leds_on_board(board, [g.center for _, _, g in group])
for k, pos in enumerate(order):
idx, occ, geom = group[pos]
leds.append(NamedLed(id=f"led_{board}_{k}", board=board, body_index=idx,
top_occurrence=occ, geometry=geom))
return leds
def _rounded(values: Sequence[float], decimals: int) -> list[float]:
"""丸めて -0.0 を 0.0 にした Python float のリスト."""
return [round(float(v), decimals) + 0.0 for v in values]
def build_light_entries(leds: Sequence[NamedLed], template: dict[str, Any]) -> list[dict[str, Any]]:
"""ベース YAML の先頭ライトをテンプレートに,LED ごとの lights エントリを作る.
type・radiance・spot 設定等はテンプレートのまま,位置・サイズ・方向・id だけ差し替える.
- area(rectangle): center / size / direction
- area(disk): center / direction(radius はテンプレートのまま)
- spot: position / direction
- point: position
Args:
leds: build_leds の結果.
template: ベース YAML の lights[0](dict).
Returns:
lights エントリのリスト.
Raises:
ValueError: テンプレートが位置を持たない光源(directional 等)の場合.
"""
light_type = template.get("type")
if light_type not in ("area", "spot", "point"):
msg = (
f"ベース YAML の先頭ライトの type={light_type!r} は"
"テンプレートに使えません(area / spot / point)"
)
raise ValueError(msg)
entries = []
for led in leds:
g = led.geometry
body = {k: copy.deepcopy(v) for k, v in template.items() if k != "id"}
center = _rounded(g.center, _POS_DECIMALS)
direction = _rounded(g.direction, _DIR_DECIMALS)
if light_type == "area":
body["center"] = center
if body.get("shape", "rectangle") == "rectangle":
body["size"] = _rounded(g.size, _POS_DECIMALS)
body["direction"] = direction
elif light_type == "spot":
body["position"] = center
body["direction"] = direction
else:
body["position"] = center
entries.append({"id": led.id, **body})
return entries
def _fallback_mesh_id(body: BodyInput) -> str:
"""対応表に無いボディのメッシュ id(ASCII 安全な名前)."""
ascii_part = re.sub(r"[^A-Za-z0-9_]+", "_", body.name).strip("_")
return f"body_{body.index:03d}" + (f"_{ascii_part}" if ascii_part else "")
def build_mesh_entries(bodies: Sequence[BodyInput], led_indices: set[int] | Sequence[int],
board_labels: dict[str, str], mapping: FusionMapping,
yaml_dir: Path) -> list[dict[str, Any]]:
"""LED 以外のボディから geometry.meshes エントリを作る.
並び順は対応表の bodies の記載順 → 基板順(bottom/right/left/top)→ マニフェスト順.
対応表に無いボディは default_material で含め,警告を出す.
Args:
bodies: 全ボディ.
led_indices: LED と判定したボディの index(メッシュに含めない).
board_labels: assign_board_labels の結果(`{board}` 展開に使う).
mapping: 対応表.
yaml_dir: 生成 YAML の置き場所(メッシュパスをここからの相対にする).
Returns:
meshes エントリのリスト.
Raises:
ValueError: `{board}` を含む id のボディが LED ユニットに属さない場合,
または id が重複した場合.
"""
led_set = set(led_indices)
rule_order = {name: i for i, name in enumerate(mapping.bodies)}
rows: list[tuple[tuple[int, int, int], dict[str, Any]]] = []
for body in bodies:
if body.index in led_set:
continue
rule = mapping.bodies.get(body.name)
board = board_labels.get(body.top_occurrence)
if rule is None:
mesh_id = _fallback_mesh_id(body)
material = mapping.default_material
_logger.warning(
"ボディ %r(%s)は対応表に無いため id=%s,材質 %s で含めます",
body.name, body.top_occurrence or "ルート", mesh_id, material,
)
order = len(rule_order)
else:
if rule.exclude:
continue
mesh_id = str(rule.id)
if "{board}" in mesh_id:
if board is None:
msg = (
f"ボディ {body.name!r}({body.top_occurrence or 'ルート'})の id "
f"{mesh_id!r} は {{board}} を含みますが,LED ユニットに属していません"
)
raise ValueError(msg)
mesh_id = mesh_id.replace("{board}", board)
material = rule.material or mapping.default_material
order = rule_order[body.name]
key = (order, board_order_index(board) if board else -1, body.index)
rows.append((key, {
"id": mesh_id,
"path": relative_mesh_path(body.stl_path, yaml_dir),
"unit": "mm",
"material": material,
}))
rows.sort(key=lambda r: r[0])
entries = [entry for _, entry in rows]
seen: set[str] = set()
for entry in entries:
if entry["id"] in seen:
msg = (
f"メッシュ id {entry['id']!r} が重複しました.同名ボディが複数ある場合は "
"対応表の id に {board} を含めるか,ボディ名を分けてください"
)
raise ValueError(msg)
seen.add(entry["id"])
return entries
def build_scene_dict(base: dict[str, Any], meshes: list[dict[str, Any]],
lights: list[dict[str, Any]], *, name: str | None = None,
description: str | None = None) -> dict[str, Any]:
"""ベースのシーン dict の geometry.meshes と lights を差し替えた dict を返す.
materials・sensor・render・evaluation などそれ以外のキーはそのまま流用する
(キーの並び順もベースに従う).
Args:
base: ベース YAML を読んだ dict.
meshes: geometry.meshes に入れるエントリ.
lights: lights に入れるエントリ.
name: シーン名(None ならベースのまま).
description: 説明(None ならベースのまま).
Returns:
新しいシーン dict(base は変更しない).
"""
scene = copy.deepcopy(base)
geometry = dict(scene.get("geometry") or {})
geometry["meshes"] = meshes
scene["geometry"] = geometry
scene["lights"] = lights
if name is not None:
scene["name"] = name
if description is not None:
scene["description"] = description
return scene
def generate_scene(bodies: Sequence[BodyInput], mapping: FusionMapping, base: dict[str, Any],
yaml_dir: Path, *, name: str | None = None,
description: str | None = None) -> tuple[dict[str, Any], list[NamedLed]]:
"""ボディ群・対応表・ベース dict からシーン dict を生成する(1 〜 5 の一括実行).
Args:
bodies: 全ボディ.
mapping: 対応表.
base: ベース YAML の dict(lights[0] を光源テンプレートに使う).
yaml_dir: 生成 YAML の置き場所.
name: シーン名(None ならベースのまま).
description: 説明(None ならベースのまま).
Returns:
(シーン dict, ID を振った LED のリスト).
Raises:
ValueError: LED が 1 個も見つからない場合,ベースに lights が無い場合など.
"""
led_boxes = detect_led_bodies(bodies, mapping.led)
if not led_boxes:
dims = mapping.led.package_dims_mm
msg = (
f"LED ボディが見つかりません(パッケージ寸法 {dims} ± {mapping.led.tolerance_mm} mm)."
"対応表の led.package_dims_mm / tolerance_mm を確認してください"
)
raise ValueError(msg)
base_lights = base.get("lights") or []
if not base_lights:
msg = "ベース YAML に lights が無く,光源テンプレートを決められません"
raise ValueError(msg)
board_labels = assign_board_labels(bodies, led_boxes, mapping.boards)
leds = build_leds(bodies, led_boxes, board_labels, mapping.led)
lights = build_light_entries(leds, base_lights[0])
meshes = build_mesh_entries(bodies, set(led_boxes), board_labels, mapping, yaml_dir)
scene = build_scene_dict(base, meshes, lights, name=name, description=description)
return scene, leds
def compare_lights(generated: Sequence[dict[str, Any]],
reference: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
"""生成した lights と参照 YAML の lights を id で突き合わせる(検証用).
位置は area なら center,spot / point なら position を比べる.
Args:
generated: 生成した lights エントリ.
reference: 参照 YAML の lights エントリ.
Returns:
id ごとの比較結果 dict のリスト(generated の順.参照のみにある id は末尾).
キー: id, status("both" / "generated_only" / "reference_only"),
position_diff_mm(中心間距離),size_diff_mm(各辺の差の最大),
direction_angle_deg(方向の角度差).比較できない項目は None.
"""
def _pos(e: dict[str, Any]) -> np.ndarray | None:
p = e.get("center", e.get("position"))
return None if p is None else np.asarray(p, dtype=float)
def _unmatched(light_id: str, status: str) -> dict[str, Any]:
return {"id": light_id, "status": status, "position_diff_mm": None,
"size_diff_mm": None, "direction_angle_deg": None}
ref_by_id = {e["id"]: e for e in reference}
results: list[dict[str, Any]] = []
for gen in generated:
ref = ref_by_id.get(gen["id"])
if ref is None:
results.append(_unmatched(gen["id"], "generated_only"))
continue
pg, pr = _pos(gen), _pos(ref)
pos_diff = None if pg is None or pr is None else float(np.linalg.norm(pg - pr))
size_diff = None
if gen.get("size") is not None and ref.get("size") is not None:
size_diff = float(np.max(np.abs(np.asarray(gen["size"]) - np.asarray(ref["size"]))))
angle = None
if gen.get("direction") is not None and ref.get("direction") is not None:
dg = np.asarray(gen["direction"], dtype=float)
dr = np.asarray(ref["direction"], dtype=float)
cos = float(np.dot(dg, dr) / (np.linalg.norm(dg) * np.linalg.norm(dr)))
angle = float(np.degrees(np.arccos(np.clip(cos, -1.0, 1.0))))
results.append({"id": gen["id"], "status": "both", "position_diff_mm": pos_diff,
"size_diff_mm": size_diff, "direction_angle_deg": angle})
gen_ids = {e["id"] for e in generated}
for ref in reference:
if ref["id"] not in gen_ids:
results.append(_unmatched(ref["id"], "reference_only"))
return results