diff --git a/scripts/check_camera_view.py b/scripts/check_camera_view.py index 5804bb0..da5a91d 100644 --- a/scripts/check_camera_view.py +++ b/scripts/check_camera_view.py @@ -3,7 +3,8 @@ PLAN_03 の要件「カメラの視野」の確認用.カメラ位置の候補点(既定: 中心と ±dx・±dy の 9 点)から 開口部の矩形上の格子点へ線分を引き,筐体・評価板・スマホ以外のメッシュ(LED 基板カバー・ 遮光板など)の軸平行バウンディングボックスと交わるかを調べる.AABB で判定するので保守側 -(実際より「ふさぐ」と出やすい)である. +(実際より「ふさぐ」と出やすい)である.斜めに置いた部品は AABB が大きく過大に出るので, +--exact で三角形と線分の交差を調べる(計算は重いので研究室サーバで回す). SH-02M のメッシュは直方体でカメラの穴が無いため,カメラ位置は引数で与える(既定は箱形の スマホ側の窓の中心 (0, 4) mm・Z = -144 mm). @@ -50,7 +51,32 @@ return (enter <= leave) & (leave >= 0.0) & (enter <= 1.0) -def check_scene(scene: Path, camera: np.ndarray, spread: float, grid: int) -> list[str]: +def segment_hits_triangles( + start: np.ndarray, ends: np.ndarray, triangles: np.ndarray, chunk: int = 64 +) -> np.ndarray: + """線分 start→ends[i] がいずれかの三角形と交わるかを返す(Moller-Trumbore 法).""" + d = ends - start # (N, 3).交点は t ∈ (0, 1) + hit = np.zeros(len(ends), dtype=bool) + for k in range(0, len(triangles), chunk): + tri = triangles[k:k + chunk] + a = tri[:, 0] + e1, e2 = tri[:, 1] - a, tri[:, 2] - a # (M, 3) + p = np.cross(d[:, None, :], e2[None, :, :]) # (N, M, 3) + det = np.einsum("nmk,mk->nm", p, e1) + ok = np.abs(det) > 1e-12 + inv = np.where(ok, 1.0 / np.where(ok, det, 1.0), 0.0) + s = start - a # (M, 3) + u = np.einsum("nmk,mk->nm", p, s) * inv + q = np.cross(s, e1) # (M, 3) + v = np.einsum("nk,mk->nm", d, q) * inv + t = np.einsum("mk,mk->m", q, e2)[None, :] * inv + hit |= np.any(ok & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > 0) & (t < 1), axis=1) + return hit + + +def check_scene( + scene: Path, camera: np.ndarray, spread: float, grid: int, exact: bool = False +) -> list[str]: """シーン 1 つを調べ,視野をふさぐメッシュ id とふさぐ割合を文字列で返す.""" config = yaml.safe_load(scene.read_text(encoding="utf-8")) xs = np.linspace(-OPENING_HALF[0], OPENING_HALF[0], grid) @@ -62,8 +88,12 @@ for mesh in config["geometry"]["meshes"]: if any(key in mesh["id"] for key in IGNORED_IDS): continue - bounds = trimesh.load(scene.parent / mesh["path"], force="mesh").bounds - worst = max(segment_hits_aabb(c, targets, bounds[0], bounds[1]).mean() for c in cams) + part = trimesh.load(scene.parent / mesh["path"], force="mesh") + if exact: + worst = max(segment_hits_triangles(c, targets, part.triangles).mean() for c in cams) + else: + worst = max(segment_hits_aabb(c, targets, part.bounds[0], part.bounds[1]).mean() + for c in cams) if worst > 0: found.append(f"{mesh['id']}: 開口部の {worst * 100:.1f}% をふさぐ(最悪のカメラ位置)") return found @@ -77,10 +107,12 @@ parser.add_argument("--spread", type=float, default=10.0, help="カメラ位置の不確かさ(±mm.9 点で調べる)") parser.add_argument("--grid", type=int, default=41, help="開口部の格子の 1 辺の点数") + parser.add_argument("--exact", action="store_true", + help="AABB ではなく三角形との交差で調べる(斜めの部品向け.重い)") args = parser.parse_args(argv) camera = np.array(args.camera) for scene in args.scenes: - found = check_scene(scene, camera, args.spread, args.grid) + found = check_scene(scene, camera, args.spread, args.grid, args.exact) status = "OK(ふさぐ部品なし)" if not found else "要確認" print(f"{scene.name}: {status}") for line in found: diff --git a/scripts/check_wall_clearance.py b/scripts/check_wall_clearance.py new file mode 100644 index 0000000..56f7e4b --- /dev/null +++ b/scripts/check_wall_clearance.py @@ -0,0 +1,50 @@ +"""候補のシーンで LED 基板カバーが筐体の壁に食い込んでいないかを調べる. + +筐体(id が box_housing のメッシュ)と各 LED 基板カバー(id が led_cover_ で始まる)の積の体積を +manifold3d で求める.0 なら干渉なし.manifold3d は CPU の全コアを使うので,研究室サーバで +実行する(sm-remote run). + +実行方法: + uv run python scripts/check_wall_clearance.py configs/_tmp_candidates/scene_F1_58.yaml +""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import trimesh +import yaml + + +def overlap_volumes(scene: Path) -> dict[str, float]: + """LED 基板カバーごとに筐体との積の体積 [mm^3] を返す.""" + config = yaml.safe_load(scene.read_text(encoding="utf-8")) + meshes = config["geometry"]["meshes"] + housing_entry = next(m for m in meshes if m["id"] == "box_housing") + housing = trimesh.load(scene.parent / housing_entry["path"], force="mesh") + volumes = {} + for entry in meshes: + if not entry["id"].startswith("led_cover_"): + continue + cover = trimesh.load(scene.parent / entry["path"], force="mesh") + both = trimesh.boolean.intersection([housing, cover], engine="manifold") + volumes[entry["id"]] = float(both.volume) if len(both.faces) else 0.0 + return volumes + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("scenes", nargs="+", type=Path) + args = parser.parse_args(argv) + for scene in args.scenes: + bad = {k: v for k, v in overlap_volumes(scene).items() if v > 0.0} + status = "OK(干渉なし)" if not bad else "干渉あり" + print(f"{scene.name}: {status}") + for key, vol in bad.items(): + print(f" {key}: {vol:.2f} mm^3") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/sweep_candidate_layouts.py b/scripts/sweep_candidate_layouts.py index a5dca02..495fc2c 100644 --- a/scripts/sweep_candidate_layouts.py +++ b/scripts/sweep_candidate_layouts.py @@ -99,6 +99,7 @@ angle_deg: float led_xy: tuple[float, float] dz: float = 0.0 # この基板だけ Z 方向に追加で動かす量 [mm](候補の led_dz に足す) + tilt_deg: float = 0.0 # LED 列の中心を軸に X 軸まわりに傾ける角度(正で LED が +Y を向く) @dataclass(frozen=True) @@ -117,6 +118,10 @@ fillet: float = 0.0 # 箱形の内側の稜と角を丸める半径 [mm](0 で丸めない) y_min: float = -80.0 # housing="sloped": 内面の -Y 側の壁 [mm] nose: bool = False # 箱形: 上の壁に鼻の穴(現行機と同じ U 字の切り欠き)を開ける + nose_pocket: bool = False # 鼻の穴を箱の中から壁で囲って袋にする + ceiling_strip: bool = False # 鼻の穴の左右の天井近くに細い LED 列(新しい細い基板)を置く + strip_gain: float = 1.0 # 細い LED 列の放射量の倍率(抵抗で電流を絞る想定) + half_x: float = 80.0 # housing="sloped": 内面の X の半幅 [mm] def _current_top() -> Board: @@ -245,8 +250,10 @@ SLOPED_TOP_LED_Z = -70.0 -def _sloped_boards(y_min: float, with_top: bool) -> tuple[Board, ...]: - wall_x = SLOPED_HALF_X - LED_WALL_OFFSET +def _sloped_boards( + y_min: float, with_top: bool, half_x: float = SLOPED_HALF_X +) -> tuple[Board, ...]: + wall_x = half_x - LED_WALL_OFFSET boards = [ Board("bottom", 0.0, (0.0, y_min + LED_WALL_OFFSET)), Board("right", 90.0, (wall_x, 0.0)), @@ -301,6 +308,8 @@ NOSE_HALF_WIDTH = 7.5 NOSE_DEPTH = 22.5 NOSE_Y_START = BOARD_HALF[1] + 1.0 # 評価板の縁(受けの部分)は切らない +NOSE_POCKET_WALL = 1.5 # 鼻の穴を袋にするときの壁の厚さ +NOSE_POCKET_GAP = 0.2 # 袋の評価板側の壁と評価板の縁の隙間 for _base in [c for c in CANDIDATES if c.name in ("B2_z25_L160", "F3_y80", "F3_y80_s10_b1", "F3_y80_s20_b1")]: @@ -339,6 +348,111 @@ f"LED 高さ Z={_z:g}"), ) +# 2 回目の改善(R20・LED Z=-35 の最良案 F3_y80_s20_b1_N_R20_z35 から).残る暗部は上の縁の中央 +# (鼻の穴の前)と下の角,わずかな上下の傾き. +# a. 下の基板だけ奥へ(下側が明るすぎる分を減らす) +# b. 左右の基板を傾けて LED を +Y(上の縁)へ向ける +# c. 下の基板も傾けて LED を +Y(中央)へ向ける +# d. 箱を X に広げる(左右の基板を評価板の縁から離す)・-Y 側を広げる +_best2 = next(c for c in CANDIDATES if c.name == "F3_y80_s20_b1_N_R20_z35") + + +def _shifted(boards: tuple[Board, ...], **per_label: dict) -> tuple[Board, ...]: + """基板ラベルごとに Board のフィールドを置き換えた組を返す.""" + return tuple(replace(b, **per_label.get(b.label, {})) for b in boards) + + +_side = {"right", "left"} +_variants = ( + ("bdz10", "下の基板だけ 10 mm 奥へ", _shifted(_best2.boards, bottom={"dz": -10.0}), {}), + ("bdz20", "下の基板だけ 20 mm 奥へ", _shifted(_best2.boards, bottom={"dz": -20.0}), {}), + ("st15", "左右の基板を +Y へ 15° 傾ける", + _shifted(_best2.boards, right={"tilt_deg": 15.0}, left={"tilt_deg": 15.0}), {}), + ("st30", "左右の基板を +Y へ 30° 傾ける", + _shifted(_best2.boards, right={"tilt_deg": 30.0}, left={"tilt_deg": 30.0}), {}), + ("bt30", "下の基板を +Y へ 30° 傾ける", _shifted(_best2.boards, bottom={"tilt_deg": 30.0}), {}), + ("x90", "箱を X に ±90 へ広げる", + tuple(Board(b.label, b.angle_deg, + (b.led_xy[0] + (10.0 if b.led_xy[0] > 0 else -10.0) if b.label in _side + else b.led_xy[0], b.led_xy[1]), b.dz, b.tilt_deg) + for b in _best2.boards), {"half_x": 90.0}), + ("y90", "-Y 側を -90 へ広げる", + _shifted(_best2.boards, bottom={"led_xy": (0.0, -90.0 + LED_WALL_OFFSET)}), {"y_min": -90.0}), +) +for _key, _desc, _boards, _extra in _variants: + CANDIDATES += ( + replace(_best2, name=f"H_{_key}", boards=_boards, note=f"R20・Z=-35 の最良案 + {_desc}", + **_extra), + ) + +# e. 鼻の穴を箱の中から壁で囲って袋にする(光が穴から逃げない.鼻が入る空間は同じ) +_by_name = {c.name: c for c in CANDIDATES} +for _src in ("F3_y80_s20_b1_N_R20_z35", "H_y90", "H_bt30"): + CANDIDATES += ( + replace(_by_name[_src], name=f"{_src}_P", nose_pocket=True, + note=f"{_by_name[_src].note}・鼻の穴を袋にする"), + ) + +# E. 鼻の穴の左右の天井近くに細い LED 列(新しい細い基板).評価板の上の縁(Y = 51)と上の壁の +# 間に収まる幅 4.5 mm の基板を,丸めた上の縁の稜(R8)より下に置き,LED は今の基板と同じく +# 箱の奥(-Z)へ向ける.片側 3 個 × 左右で 6 個(今の基板 1 枚分) +STRIP_LED_X = (25.0, 32.0, 39.0) +STRIP_Y = (51.5, 56.0) +STRIP_Z = (-10.0, -8.4) # 基板(カバー)の下面・上面 + + +def _ceiling_strips(base: dict, name: str, yaml_dir: Path) -> tuple[list[dict], list[dict]]: + """鼻の穴の左右に置く細い LED 列のメッシュエントリと光源エントリを作る.""" + template = _bottom_leds(base)[0] + y_mid = sum(STRIP_Y) / 2 + meshes, lights = [], [] + for sign, label in ((1.0, "strip_r"), (-1.0, "strip_l")): + x0, x1 = min(STRIP_LED_X) - 4.0, max(STRIP_LED_X) + 4.0 + plate = trimesh.creation.box( + extents=[x1 - x0, STRIP_Y[1] - STRIP_Y[0], STRIP_Z[1] - STRIP_Z[0]]) + plate.apply_translation([sign * (x0 + x1) / 2, y_mid, sum(STRIP_Z) / 2]) + path = MESH_DIR / f"{name}_led_cover_{label}.stl" + plate.export(path) + meshes.append({"id": f"led_cover_{label}", "path": relative_mesh_path(path, yaml_dir), + "unit": "mm", "material": "printer_white"}) + for k, x in enumerate(STRIP_LED_X): + light = copy.deepcopy(template) + light["id"] = f"led_{label}_{k}" + light["center"] = [sign * x, y_mid, STRIP_Z[0] - 0.05] + lights.append(light) + return meshes, lights + + +# F. 左右の基板を上の角へ移して 45° に置く(上の縁の方を照らす).基板が長い(52 mm)ので角の +# 奥までは入らない.カメラから開口部への視線と丸めた壁を避けられる位置を,角へ寄せながら探す +CORNER_LED_XYS = ((57.0, 30.0), (58.0, 31.0), (59.0, 31.5), (60.0, 32.0)) +_y90 = next(c for c in CANDIDATES if c.name == "H_y90") +_y90_bt30 = _shifted(_y90.boards, bottom={"tilt_deg": 30.0}) +CANDIDATES += ( + replace(_best2, name="E1", ceiling_strip=True, + note="R20・Z=-35 の最良案 + 鼻の穴の左右の天井近くに細い LED 列(6 個)"), + replace(_y90, name="G1", boards=_y90_bt30, + note="-Y を -90 へ広げた案 + 下の基板を +Y へ 30° 傾ける"), + replace(_y90, name="G2", ceiling_strip=True, + note="-Y を -90 へ広げた案 + 天井近くの細い LED 列"), + replace(_y90, name="G3", boards=_y90_bt30, ceiling_strip=True, + note="-Y を -90 へ広げた案 + 下の基板を 30° 傾ける + 天井近くの細い LED 列"), +) +# E の LED 列は全灯(今の LED と同じ明るさ)だと上の縁が明るすぎる(b1 が大きく負)ので絞る +for _g in (0.15, 0.25, 0.4): + CANDIDATES += ( + replace(_y90, name=f"G2_g{_g:g}".replace(".", ""), ceiling_strip=True, strip_gain=_g, + note=f"-Y を -90 へ広げた案 + 天井近くの細い LED 列(明るさ ×{_g:g})"), + ) +for _cx, _cy in CORNER_LED_XYS: + CANDIDATES += ( + replace(_best2, name=f"F1_{_cx:g}", boards=( + next(b for b in _best2.boards if b.label == "bottom"), + Board("corner_r", 135.0, (_cx, _cy)), + Board("corner_l", -135.0, (-_cx, _cy)), + ), note=f"R20・Z=-35 の最良案で左右の基板を上の角へ 45° に置く(±{_cx:g}, {_cy:g})"), + ) + # 遮光板: LED 発光面から BAFFLE_GAP 上に置く厚さ BAFFLE_THICKNESS の板.LED のどの点からも # 評価板の裏面(Z = -4.5,±49.5 × ±51)が直接見えない大きさにし,BAFFLE_MARGIN だけ広げる BAFFLE_GAP = 10.0 @@ -385,6 +499,10 @@ probe.apply_transform(transform) dz = (RIM_Z - box_size + 0.2) - float(probe.bounds[0][2]) transform = trimesh.transformations.translation_matrix([0.0, 0.0, dz + board.dz]) @ transform + if board.tilt_deg: + pivot = transform @ np.array([0.0, BOTTOM_LED_Y, BOTTOM_LED_Z, 1.0]) + transform = trimesh.transformations.rotation_matrix( + np.radians(board.tilt_deg), [1, 0, 0], point=pivot[:3]) @ transform mesh = cover.copy() mesh.apply_transform(transform) path = MESH_DIR / f"{name}_led_cover_{board.label}.stl" @@ -438,18 +556,40 @@ return plate -def cut_nose(housing: trimesh.Trimesh) -> trimesh.Trimesh: - """箱形の筐体の上の壁に鼻の穴(U 字の切り欠き.NOSE_* 参照)を開ける.""" - face_z = float(housing.bounds[1][2]) +def _nose_prism( + face_z: float, y0: float, y1: float, grow: float = 0.0 +) -> trimesh.Trimesh: + """鼻の穴の断面(NOSE_* .grow だけ外へ太らせる)を Y = y0〜y1 に押し出した凸多面体.""" + half, top_half = NOSE_HALF_WIDTH + grow, NOSE_TOP_HALF_WIDTH + grow center_z = face_z - NOSE_DEPTH + NOSE_HALF_WIDTH - y_end = float(housing.bounds[1][1]) + 10.0 angles = np.linspace(np.pi, 2 * np.pi, 33) - section = [(NOSE_HALF_WIDTH * np.cos(a), center_z + NOSE_HALF_WIDTH * np.sin(a)) - for a in angles] - section += [(NOSE_TOP_HALF_WIDTH, face_z + 10.0), (-NOSE_TOP_HALF_WIDTH, face_z + 10.0)] - points = [(x, y, z) for x, z in section for y in (NOSE_Y_START, y_end)] - cutter = trimesh.convex.convex_hull(np.array(points)) - result = trimesh.boolean.difference([housing, cutter], engine="manifold") + section = [(half * np.cos(a), center_z + half * np.sin(a)) for a in angles] + section += [(top_half, face_z + 10.0), (-top_half, face_z + 10.0)] + points = [(x, y, z) for x, z in section for y in (y0, y1)] + return trimesh.convex.convex_hull(np.array(points)) + + +def cut_nose(housing: trimesh.Trimesh, pocket: bool = False) -> trimesh.Trimesh: + """箱形の筐体の上の壁に鼻の穴(NOSE_* 参照)を開ける. + + pocket のときは,鼻が入る空間を箱の中から厚さ NOSE_POCKET_WALL の壁で囲って袋にする + (顔側と上は開いたまま,箱の中とはつながらない).評価板側の壁は評価板の縁から + NOSE_POCKET_GAP だけ離す. + """ + face_z = float(housing.bounds[1][2]) + y_end = float(housing.bounds[1][1]) + 10.0 + if not pocket: + parts = [housing] + cutter = _nose_prism(face_z, NOSE_Y_START, y_end) + else: + y_wall = BOARD_HALF[1] + NOSE_POCKET_GAP + y_cut = y_wall + NOSE_POCKET_WALL + shell = trimesh.boolean.intersection( + [_nose_prism(face_z, y_wall, y_end, grow=NOSE_POCKET_WALL), housing.convex_hull], + engine="manifold") + parts = [trimesh.boolean.union([housing, shell], engine="manifold")] + cutter = _nose_prism(face_z, y_cut, y_end) + result = trimesh.boolean.difference([*parts, cutter], engine="manifold") if not result.is_watertight: raise RuntimeError("鼻の穴を開けた筐体が閉じた立体になっていない") return result @@ -457,24 +597,26 @@ def _box_meshes( yaml_dir: Path, box_size: float = BOX_SIZE, fillet: float = 0.0, y_min: float | None = None, - nose: bool = False, + nose: bool = False, half_x: float = SLOPED_HALF_X, nose_pocket: bool = False, ) -> list[dict]: suffix = f"_R{fillet:g}" if fillet > 0 else "" if y_min is not None: suffix = f"_傾斜_y{-y_min:g}" + (f"_R{fillet:g}" if fillet > 0 else "") + if half_x != SLOPED_HALF_X: + suffix += f"_x{half_x:g}" if nose: plain = MESH_DIR / f"箱形_L{box_size:g}{suffix}.stl" - _box_meshes(yaml_dir, box_size, fillet, y_min) # 穴の無い筐体を先に用意する - housing = MESH_DIR / f"箱形_L{box_size:g}{suffix}_鼻.stl" + _box_meshes(yaml_dir, box_size, fillet, y_min, half_x=half_x) # 穴の無い筐体を先に用意 + housing = MESH_DIR / f"箱形_L{box_size:g}{suffix}_鼻{'袋' if nose_pocket else ''}.stl" if not housing.exists(): - cut_nose(trimesh.load(plain, force="mesh")).export(housing) + cut_nose(trimesh.load(plain, force="mesh"), nose_pocket).export(housing) else: housing = MESH_DIR / f"箱形_L{box_size:g}{suffix}.stl" window = MESH_DIR / f"箱形_L{box_size:g}_スマホ側の窓.stl" MESH_DIR.mkdir(parents=True, exist_ok=True) if not housing.exists() and y_min is not None and fillet > 0: build_rounded_sloped_box_housing( - half_x=SLOPED_HALF_X, y_min=y_min, y_top=SLOPED_Y_TOP, slope=SLOPED_SLOPE, + half_x=half_x, y_min=y_min, y_top=SLOPED_Y_TOP, slope=SLOPED_SLOPE, depth=box_size, thickness=BOX_THICKNESS, board_half_x=BOARD_HALF[0], board_half_y=BOARD_HALF[1], rim_inset=RIM_INSET, rim_z=RIM_Z, @@ -482,7 +624,7 @@ ).export(housing) elif not housing.exists() and y_min is not None: build_sloped_box_housing( - half_x=SLOPED_HALF_X, y_min=y_min, y_top=SLOPED_Y_TOP, slope=SLOPED_SLOPE, + half_x=half_x, y_min=y_min, y_top=SLOPED_Y_TOP, slope=SLOPED_SLOPE, depth=box_size, thickness=BOX_THICKNESS, board_half_x=BOARD_HALF[0], board_half_y=BOARD_HALF[1], rim_inset=RIM_INSET, rim_z=RIM_Z, @@ -535,7 +677,8 @@ ] else: meshes = _box_meshes(yaml_dir, cand.box_size, cand.fillet, - cand.y_min if cand.housing == "sloped" else None, cand.nose) + cand.y_min if cand.housing == "sloped" else None, cand.nose, + cand.half_x, cand.nose_pocket) meshes.append({ "id": "evaluation_board", "path": relative_mesh_path(BASE_YAML.parent / "meshes" / "照明ムラ補正ボード.stl", @@ -559,6 +702,12 @@ "unit": "mm", "material": "printer_white"}) lights.extend(board_lights) + if cand.ceiling_strip: + strip_meshes, strip_lights = _ceiling_strips(base, cand.name, yaml_dir) + for light in strip_lights: + light["radiance"] = [float(r) * cand.strip_gain for r in light["radiance"]] + meshes.extend(strip_meshes) + lights.extend(strip_lights) if cand.gain_bottom != 1.0: for light in lights: if light["id"].startswith("led_bottom_"):