---
title: "サービスロボット導入シミュレーション Log#56 | ストレッチャーと曲がり角で、搬送ロボットの譲り方を比べる"
slug: hospital-robot-yields-stretcher-and-blind-corner-3d
date: 2026-11-23
day: 564
meta_description: "病院の廊下で搬送ロボットがストレッチャーに譲るとき、前のくぼみに入れれば待たせる時間は0秒、後ろに下がると33.5秒。見えない角では0.8m/秒のままだと車いすの2.4cm手前で止まり、0.4m/秒なら1.34m空いた。"
tags: [サービスロボット導入シミュレーション, 搬送ロボット, 病院, ストレッチャー, 車いす, 曲がり角, 看護師, 3Dモデル, Blender, Unity, AI音声, 依頼箱]
series: "導入シミュレーション"
---

病院の廊下で搬送ロボットがストレッチャーに道を譲るとき、少し先にある病室の扉のくぼみに入れればストレッチャーを待たせる時間は0秒で済み、くぼみを通り過ぎていて後ろに下がると33.5秒待たせた。**実物ではなく Unity の3DCGで作った病院の場面で、見通しの悪い曲がり角では、搬送ロボット「ハコブくん」が0.8m/秒のまま角に入ると車いすの2.4cm手前でやっと止まり、角の2m手前で0.4m/秒に落とすと1.34m空けて止まれた。看護師を止めずに済んだので、角を曲がり終えるのは速さを落としたほうが4.5秒早かった。**

この回でできるようになったことです。

- [サービスロボット導入シミュレーションのページ](https://pixelstomotors.com/series8#scenes) の「3Dで見る現場の場面」に、ストレッチャーに道を空ける2本（くぼみに入る・後ろに下がる）と、曲がり角で車いすと出会う2本（速さを落とさない・手前で落とす）を足した。どれも真上から見た動画つきで、場面は14本になった
- 「道を譲る」と一言で言っても、譲れる所が前にあるか後ろにあるかで、人を待たせる時間が0秒と33.5秒に分かれることを、同じ廊下・同じ速さの2本で見せられるようになった
- 角の手前で速さを落とすかどうかを、病院の1日のシミュレーションと同じ止まり方の決まりのまま比べた。すき間（0.024m と 1.34m）、看護師が止まった時間（9.0秒と0秒）、角を曲がり終えるまでの差（4.5秒）が並ぶので、ロボットの走らせ方を決める材料になる
- 空のストレッチャーの3Dモデルを作った。車いすと同じ作り方（Blender の Python）で、車輪の向きと回転を Unity で動かせる。作り方のコードとモデルは GitHub に置いた
- 時間：Unity への依頼は3本（270・271・279）で、16時02分〜23時15分（そのうち清掃ロボットの依頼2本の待ちが約2時間半）。ストレッチャーのモデルは見た目の確かめまで約15分。前のやり方と比べられる時間は測っていない

困っていたのは、病院の1日のシミュレーション（人とロボットが丸と四角で動く版）で「ストレッチャーにはロボットが譲る」「止まるまでの距離は速さで決まる」と決まりを置いても、それが現場でどう見えて、だれをどれだけ待たせるのかが伝わらないことでした。ストレッチャーは幅が約0.7mあり、横に看護師が付くと、幅1.68mの廊下ではロボットが横を通れる幅は残りません。曲がり角は壁で向こうが見えないので、ロボットのセンサーが車いすを見つけられるのは角の手前1〜2mになってからです。

| やったこと | 何を・なぜ | 結果 |
|---|---|---|
| ストレッチャーの3D | ⑩で看護師2人が運ぶ。空の状態、柵は上げた形 | 幅0.74m・長さ2.07m・三角形6,384 |
| 依頼270 | ⑩ストレッチャーに道を空ける を2本（前のくぼみに入る／後ろに下がる） | 待たせた時間 0秒／33.7秒（声の差し替え後 33.5秒）。当たったコマ0 |
| 依頼271 | ⑪曲がり角で車いすと出会う を2本（0.8m/秒のまま／2m手前で0.4m/秒） | 止まったときのすき間 0.024m／1.339m。当たったコマ0 |
| 依頼279 | ⑩のハコブくんの声を、⑤〜⑨と同じ声に差し替えた（依頼文の書き間違い） | 声だけ差し替え。動きは同じ |
| サイト | /series8 の3Dの場面に4本を足した（サイトの番号では⑪〜⑭） | 場面は14本になった |

【図解】LOG564_yield_compare.html

配膳ロボットを自分の店に入れたらどうなるかは、このシリーズの試算をもとにした別のページで試せます。

【バナー】serving-robot-one-less-staff


## 作業ログ ― 次の場面を、病院の1日で数えている問題から選んだ

前の回（LOG526）で、立ち話の車いすで「立ち往生」になる場面まで作りました。そのとき、⑧車いすに道を譲る の続きとして、病院の1日のシミュレーションで数えている問題（立ち往生・待ち時間・車いすの前を横切った）と同じ場面になる候補を7つ出していました。今回はその残りから、エイイチが「ストレッチャーが来る」と「曲がり角で出会う」を選びました。どちらも、病院の1日の条件の表（`tools/hospital_sim/hospital-unity-params.json`）にすでに決まりがある場面です。

| 場面 | 病院の1日の決まり | 3Dで見せたいこと |
|---|---|---|
| ストレッチャーが来る | `stretcher_yield`：ロボットが譲る（待つのは20秒まで） | 譲れる所が前にあるか後ろにあるかで、人を待たせる時間が変わる |
| 曲がり角で出会う | `braking`：反応0.2秒のあと0.5m/秒²で減速（0.8m/秒で約0.80m、0.4m/秒で約0.24m進んで止まる） | 見えない角での速さが、すき間と人の止まり方を分ける |

どちらも、作り方を決めるところでエイイチに聞いて決めました。

| 聞いたこと | エイイチの答え |
|---|---|
| ⑩で、横を通れないときの道の空け方 | 2本で比べる（前のくぼみに入る版と、間に合わない版） |
| ⑪で、角での速さ | 2本で比べる（0.8m/秒のまま／角の手前で0.4m/秒） |
| ストレッチャーに寝ている患者 | 空のストレッチャー |

「間に合わない版」は、そのままではストレッチャーもハコブくんも通れなくなります。ハコブくんが後ろ向きにゆっくり下がってくぼみに入る形にして、エイイチに確かめてから依頼にしました。


## 作業ログ ― 空のストレッチャーの3Dモデルを作った

車いす（LOG523 の `wheelchair_build.py`）と同じく、Blender を Python から動かす作り方で作りました。Blender の Python（bpy）は、Blender の操作をコードで書ける仕組みです。形はすべてコードの中の寸法で決まるので、大きさを変えたいときは数字を直して作り直せます。

- 大きさは、国内の搬送用ストレッチャーのよくある大きさに合わせました。マットレスの長さ1.90m・幅0.60m、上の高さ0.74m。柵の外の幅は0.70m、角のバンパーまで入れると0.74mです
- 足の側を前（Unity の +Z）にして進み、押す手は頭の側にあります
- 4つの車輪は、向き（`Caster_FL` など）と回転（`CasterWheel_FL` など）を別の部品にしました。Unity で、進む向きに合わせて車輪の向きを変え、進んだ距離に合わせて回せます。車いすと同じ扱いです
- 横の柵（`Rail_L`・`Rail_R`）は上げた形で作り、下の軸を中心にしてあります

【画像】LOG564_01_stretcher_model.jpg ストレッチャー（空）の3Dモデル。上段は斜め・横・頭の側から、下段は反対の斜めと真上から。青いマットレスに白いシーツとまくら、横の柵は上げた形

見た目をエイイチに確かめてもらい、そのまま p2m-site の `tools/sim_people/stretcher/` に入れました。人の3Dモデルの置き場所ですが、車いすも患者の茂さんのフォルダに入れているので、同じ扱いにしています。


## 作業ログ ― 依頼270：⑩ストレッチャーに道を空ける を2本作った

### 廊下に病室の扉の前のくぼみを足し、ストレッチャーと看護師2人を置いた

廊下は⑧と同じ（手すりの間1.68m）で、ハコブくんの側の壁に、病室の扉の前のくぼみを1つ足しました。ストレッチャーは足の側を前にして向こうから来ます。大城さんが頭の側の押す手を押し、寺島さんは足の側の横を、廊下の真ん中寄りで歩いて柵に手を添えます。

ストレッチャーと寺島さんが並ぶと、両側に残る幅はハコブくんの側が約0.37m、反対側が0.09mでした。ハコブくんが決まりのすき間を取って横を通るには0.863m要るので、どちらの側も通れません。

| 本 | くぼみの位置 | 流れ |
|---|---|---|
| ⑩-1 くぼみに入る | ハコブくんの前。見つけた所から間に合う | 見つけたら「ストレッチャーが通ります。こちらでお待ちします」と言ってくぼみへ入る。ストレッチャーは止まらずに通る |
| ⑩-2 後ろに下がる | ハコブくんの後ろ。見つける少し前に通り過ぎた | 止まって「すみません、下がります」。看護師が「はーい、待ってるね」とストレッチャーを止め、ハコブくんが0.2m/秒で後ろ向きにくぼみまで下がる |

【画像】LOG564_02_alcove_main.jpg ⑩-1 くぼみに入る。左奥のくぼみにハコブくんが入って止まり、その横を寺島さん（手前・丸めがね）と、ストレッチャーを押す大城さんが通っていく

【画像】LOG564_03_alcove_top.jpg ⑩-1 の真上の動画の15.7秒。紫の枠がくぼみ（奥行0.72m・長さ7.90m）、緑の線がハコブくんの通った跡で、くぼみの中で止まっている。左下をストレッチャーが通っていく

【画像】LOG564_04_sagarimasu.jpg ⑩-2 で、ストレッチャーを見つけて止まったハコブくんの画面。黄色の帯に「下がります」

【画像】LOG564_05_backing_top.jpg ⑩-2 の真上の動画の28.2秒。ハコブくんが後ろ向きに下がりながら、くぼみ（紫の枠）へ寄っていく。右下でストレッチャーは止まって待っている

【画像】LOG564_06_wait_label.jpg ⑩-2 でストレッチャーが動き出した所。左下に「ストレッチャーを待たせた 33.5秒」の字を3秒出す

### ⑩の結果：待たせた時間は0秒と33.5秒に分かれた

当たったコマは2本とも0で、くぼみに入ったハコブくんは、廊下の側へはみ出していませんでした（⑩-1 は手すりの線より0.056m内側、⑩-2 は0.067m内側）。病院の1日と同じ数え方で数えた値です。数字は、声を差し替えた依頼279 のあとのものです。

| 項目 | ⑩-1 くぼみに入る | ⑩-2 後ろに下がる |
|---|---|---|
| ストレッチャーを待たせた時間 | 0秒 | 33.5秒 |
| ハコブくんが止まっていた時間 | 2.4秒（くぼみの中） | 25.0秒（下がる前4.2秒・くぼみの中20.8秒）。ほかに後ろへ下がっていた30.7秒 |
| いちばん近づいた人とのすき間 | 0.218m（寺島さん） | 0.459m（寺島さん） |
| ひやり（0.3m未満） | 1件 | 0件 |
| ストレッチャーの進む先1.5m以内を横切った | 1件 | 0件 |
| 動画の長さ | 32.8秒 | 79.8秒 |

⑩-1 は、ストレッチャーを待たせない代わりに、くぼみに入りきる前に寺島さんが横を通り、すき間が0.218mになってひやりの1件に数えられました。見つける距離（6m）が⑧と同じままだと、くぼみへ寄る途中ですれ違うためです。⑩-2 は、人とは0.459m離れていますが、ストレッチャーを33.5秒止めています。

- ねらい：「ロボットが譲る」という同じ決まりでも、譲れる所の位置で、人の待ち時間がどう変わるかを見せる
- 変わったこと：くぼみが前にあればストレッチャーを待たせる時間は0秒、後ろにあると33.5秒。ハコブくんは約6m・30.7秒後ろに下がった
- 見込める効果：搬送ロボットの通り道を決めるときに、廊下のどこに待てる所（くぼみ・扉の前）があるかを、待ち時間の数字で話せる。病院の1日のシミュレーションに「くぼみがあれば入る、なければ下がる」を入れるかどうかの材料になる（いまの1日のシミュレーションには、ロボットが自分で選ぶ決まりは入っていない）

### Claude Code が決めた値と、エイイチが決めたこと

Claude Code の報告には「決めてほしいこと」が14ありました。おもなものは、くぼみの長さが7.90mと扉の前のくぼみとしては長いこと（ハコブくんがゆるい角度でしか曲がれない、⑧の寄り方の決まりから出た値）、⑩-1 で入りきる前に寺島さんが通ること、ハコブくんの声が⑧⑨と違うこと、公開中の⑨で寺島さんが歩かずに滑って動いていたこと、などです。

Claude からは、くぼみを扉1枚分に縮めてその場で向きを変えて入る形にする、ストレッチャーの出発を遅らせる、声をそろえる、⑨を撮り直す、の4つを直す案を出しました。エイイチの答えは、声だけを直して、ほかはこのままにする、でした。

> 声だけ変えて。なんでイケボ？


## 作業ログ ― ハコブくんの声が⑧⑨と違ったのは、依頼文の書き間違いだった

⑩のハコブくんの声は、⑤〜⑨で使っている声（Voice ID `gWJpc8whMBqnF7Y0kc9f`）とは別の、「ハコブ_イケボ」という名前で声の一覧に残っていた声（`N2Gsbfc4IcGM8KYgkrUz`）で作られていました。原因は、依頼270 の文に Claude が「声は 声の一覧.json の ハコブ_イケボ」と書いたことです。

同じ間違いは、⑨の最初の依頼231 でもしていて、依頼233 で `gWJpc8…` に直していました。声の一覧の名前で指したので、また同じ声に戻ってしまいました。依頼271 の文では声を名前で指していなかったので、Claude Code は⑧⑨の声に合わせていました。

これからは、依頼文に声の ID を直接書きます。

### 依頼279：声だけ差し替えて撮り直した

依頼279 では、⑩のハコブくんのセリフ2つを `gWJpc8…` で作り直し、本番と真上の4本を撮り直しました。声のほかは何も変えない決まりにしています。

| セリフ | 声の長さ（前→後） |
|---|---|
| ストレッチャーが通ります。こちらでお待ちします | 3.220 → 2.780秒 |
| すみません、下がります | 1.940 → 1.750秒 |

声が短くなった分、⑩-1 は口が動く所と、画面の寄りから本番のカメラへ戻る時刻だけが変わりました。⑩-2 は、大城さんの返事からあとが0.2秒前へずれ、待たせた時間は33.7秒から33.5秒になりました。動きそのものは、前の動きを6コマ前へずらしたものと全部のコマで同じです。⑪の2本は、はじめから `gWJpc8…` だったので作り直していません。


## 作業ログ ― 依頼271：⑪曲がり角で車いすと出会う を2本作った

### L の字の廊下を作り、2本で違うのはハコブくんの角での速さだけにした

⑧と同じ幅（手すりの間1.68m）の廊下を2本、直角につなぎました。内側の角は高さ2.6mの壁で、向こうは見えません（鏡・ガラスは置いていません）。ハコブくんは一方の廊下を角へ向かって進み、大城さんが押す茂さんの車いすが、もう一方の廊下を角へ向かって来ます。車いすは内側の角に近い側、見えにくい側を来ます。

ハコブくんのセンサーは壁を通して見えないので、車いすを見つけられるのは、車いすが角の壁の線より手前に出てからです。2本で車いすの動き（出発の時刻・速さ・線）は同じにして、ハコブくんの出発の時刻も同じにしました。出発の時刻は、⑪-1 でぶつからずに止まれる範囲で、いちばん近くで出会う時刻（台本の0.900秒）を Claude Code が1/30秒ずつ回して決めています。

【画像】LOG564_07_corner_unseen.jpg ⑪-1 の本番のカメラ。角の外側の上から、2本の廊下が両方見える。左上から車いす、右からハコブくんが角へ向かっていて、お互いは壁で見えていない

### ⑪の結果：0.8m/秒のままだとすき間は2.4cm、0.4m/秒に落とすと1.34m

止まり方は2本とも、病院の1日と同じ決まり（反応0.2秒のあと0.5m/秒²で減速）のままです。決まりより強く止めて合わせることはしていません。

| 項目 | ⑪-1 0.8m/秒のまま | ⑪-2 角の2m手前で0.4m/秒 |
|---|---|---|
| 車いすを見つけた距離 | 1.649m | 2.391m |
| 見つけてから止まるまで | 1.800秒・0.800m | 1.033秒・0.240m |
| 止まったときのすき間 | 0.024m（茂さんのスリッパ） | 1.339m |
| 看護師が止まった時間 | 8.966秒 | 0秒 |
| ひやり（0.3m未満） | 3件 | 1件（止まったまま横を通られたとき 0.151m） |
| 人がよけさせられた | 1件 | 0件 |
| 車いすの進む先を横切った | 2件 | 0件 |
| 急に止まった（減速の始まりから1.0秒以内） | 0件 | 1件（0.4m/秒からは0.833秒で止まる） |
| 角を曲がり終えるまで（出発から） | 28.9秒 | 24.4秒 |
| 動画の長さ | 31.3秒 | 26.8秒 |

【画像】LOG564_08_corner_fast_top.jpg ⑪-1 の真上の動画の9.4秒。ハコブくん（左上）が角で止まり、車いす（オレンジの線）とのすき間は0.02m。「見つけた 7.6秒」「止まった 9.4秒」の印

【画像】LOG564_09_corner_slow_top.jpg ⑪-2 の真上の動画の8.7秒。ハコブくんは角の手前で止まっていて、車いすとのすき間は1.34m

【画像】LOG564_10_wa_face.jpg ⑪-1 で、角から出てきたハコブくんに驚く大城さん（口は驚いた形）。このあと8.966秒止まる

角を曲がり終えるのは⑪-1 のほうが4.5秒遅くなりました。0.8m/秒のまま入ったのに遅いのは、ぎりぎりで止まったあと、手すり側へ下がって寄り、大城さんが押し始めるのを待ったためです。⑪-2 は0.4m/秒に落とした分ゆっくりですが、だれも止めずに済みました。

一方で、⑪-2 は「急に止まった」の1件に数えられています。0.4m/秒からは0.833秒で止まれるので、「走っている状態から1.0秒以内に止まった」に当たるためです。急ブレーキで止まったわけではなく、遅い速さから決まりどおりに止まっただけでも、この数え方では1件になります。病院の1日の数え方をそのまま当てはめたときに出る、数え方の側の問題です。

- ねらい：見えない角での速さを変えたとき、すき間・人の止まり方・遅れがどう変わるかを、同じ車いすの動きで比べる
- 変わったこと：角の2m手前で0.4m/秒に落とすと、止まったときのすき間は0.024mから1.339mに、看護師が止まった時間は8.966秒から0秒になった。遅れは出ず、角を曲がり終えるのはむしろ4.5秒早かった
- 見込める効果：病院の1日のシミュレーションに「見えない角の手前では0.4m/秒」という決まりを入れたときに、ひやりと人の止まりが減るかを確かめる材料になる（まだ1日のシミュレーションでは確かめていない）

### Claude Code が決めた値

Claude Code の報告の「決めてほしいこと」は11でした。見つける決まりを「角の壁の線より手前に出て、前の端から6.0m以内」にしたこと（病院の1日の前のセンサーの形だと、内側を曲がる車いすが入らず、⑪-2 で止まらずにすれ違ってしまう）、⑪-1 だけ大城さんが止まるのを台本で分けたこと、本番のカメラを高さ7.5mにしたので人が小さく写ること、などです。エイイチはこのままでよいとしました。


## 作業ログ ― サイトの3Dの場面に4本を足した

サービスロボット導入シミュレーションのページ（/series8）とサイトのトップの「3Dで見る現場の場面」は、同じデータ（p2m-site の `src/data/sim_scenes.json`）から作っています。そこに4本を足しました。サイトの番号は場面を足した順に振っているので、⑩-1・⑩-2・⑪-1・⑪-2 はサイトでは⑪〜⑭になります。

| サイトの番号 | 名前 | 動画 |
|---|---|---|
| ⑪ | ストレッチャーに道を空ける（くぼみに入る） | 本番・真上（32.8秒） |
| ⑫ | ストレッチャーに道を空ける（後ろに下がる） | 本番・真上（79.8秒） |
| ⑬ | 曲がり角で車いすと出会う（速さを落とさない） | 本番・真上（31.3秒） |
| ⑭ | 曲がり角で車いすと出会う（手前で速さを落とす） | 本番・真上（26.8秒） |

動画と、一覧に出す絵（poster）は、R2（p2m-media）に `scene3d_11_stretcher_alcove_v1.mp4` のような名前で入れました。場面ごとに、場所・登場する人・状況の説明・見どころ3つ・流れ（押すとその場面の時刻へ飛ぶ）を書いています。公開したあと、ページに4本の動画の住所が出ていること、動画と絵が開けることを確かめました。

### sim_scenes.json の差分

```diff
commit 670fad1f19981a24f533e40bc0b36d38538a48cd
Author: Claude <noreply@anthropic.com>
Date:   Mon Nov 23 23:41:40 2026 +0900

    series8 の3Dの場面に ⑪⑫ ストレッチャーに道を空ける・⑬⑭ 曲がり角で車いすと出会う を足す（依頼270・271・279）
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
    Claude-Session: https://claude.ai/code/session_01LevEXU3L9i9r9acENYEHNs

diff --git a/src/data/sim_scenes.json b/src/data/sim_scenes.json
index 3f8872d..2fe5030 100644
--- a/src/data/sim_scenes.json
+++ b/src/data/sim_scenes.json
@@ -1,8 +1,8 @@
 {
-  "about": "サービスロボット導入シミュレーション（/series8）の「3Dの場面」に並べる動画と、場面ごとの説明（2026-11-13・LOG503）。動画は R2（p2m-media）の /media/。時刻は本番のカメラの動画の秒。看護師とハコブくんは実物ではなく Unity の3DCG。⑤⑥は 2026-11-15 に追加（依頼205・214）、2026-11-16 に画面の「2個」を「1個」に直した v2（依頼221）へ差し替え。⑦は依頼222。⑧は依頼229（2026-11-16・患者と車いすのモデルは tools/sim_people/morita_shigeru/）。⑧の真上の動画は依頼236。⑨⑩は依頼238・237（2026-11-17・LOG526。看護師の寺島さんのモデルは tools/sim_people/nurse_terashima/）",
+  "about": "サービスロボット導入シミュレーション（/series8）の「3Dの場面」に並べる動画と、場面ごとの説明（2026-11-13・LOG503）。動画は R2（p2m-media）の /media/。時刻は本番のカメラの動画の秒。看護師とハコブくんは実物ではなく Unity の3DCG。⑤⑥は 2026-11-15 に追加（依頼205・214）、2026-11-16 に画面の「2個」を「1個」に直した v2（依頼221）へ差し替え。⑦は依頼222。⑧は依頼229（2026-11-16・患者と車いすのモデルは tools/sim_people/morita_shigeru/）。⑧の真上の動画は依頼236。⑨⑩は依頼238・237（2026-11-17・LOG526。看護師の寺島さんのモデルは tools/sim_people/nurse_terashima/）。⑪⑫は依頼270（2026-11-23・ストレッチャーのモデルは tools/sim_people/stretcher/）、ハコブくんの声は依頼279 で⑤〜⑩と同じ声に差し替えた版。⑬⑭は依頼271（L の字の廊下）。LOG564",
   "groups": ["薬剤部", "病棟", "廊下"],
   "title": "3Dで見る、看護師と搬送ロボットのやり取り",
-  "note": "試算や病院の1日のシミュレーションでは、人とロボットは丸や四角で動きます。ここでは、その中の要所を、看護師と搬送ロボット「ハコブくん」の3DCGで短く切り取りました。薬を積む・受け取る・廊下ですれ違うに加え、受け取る人が来ない・認証に失敗する・廊下で話しかけられる・車いすに道を譲る・立ち話の車いすで通れない、といった場面も入れています。動きの速さは現場に合わせています（Unity・実物ではありません）。",
+  "note": "試算や病院の1日のシミュレーションでは、人とロボットは丸や四角で動きます。ここでは、その中の要所を、看護師と搬送ロボット「ハコブくん」の3DCGで短く切り取りました。薬を積む・受け取る・廊下ですれ違うに加え、受け取る人が来ない・認証に失敗する・廊下で話しかけられる・車いすに道を譲る・立ち話の車いすで通れない・ストレッチャーに道を空ける・曲がり角で車いすと出会う、といった場面も入れています。動きの速さは現場に合わせています（Unity・実物ではありません）。",
   "log": { "label": "作り方とコードの記録（LOG503）", "href": "/record/hospital-robot-nurse-3d-scenes-at-real-speed" },
   "scenes": [
     {
@@ -267,6 +267,110 @@
         { "t": 57.3, "text": "ハコブくんが走り出す（動けない時間 49.7秒）" },
         { "t": 63.6, "text": "「ありがとうございます」と目まで笑う顔。患者が小さくうなずく" }
       ]
+    },
+    {
+      "id": "stretcher_alcove",
+      "group": "廊下",
+      "num": "11",
+      "name": "ストレッチャーに道を空ける（くぼみに入る）",
+      "short": "前の扉のくぼみに入り、ストレッチャーは止まらずに通る",
+      "poster": "/media/scene3d_11_stretcher_alcove_poster_v1.jpg",
+      "place": "幅1.8mの病棟の廊下（両側に手すり・病室の扉の前にくぼみ）",
+      "who": "看護師2人（ストレッチャーを押す人と、横に付き添う人）・空のストレッチャー・ハコブくん（薬を載せて走っている）",
+      "situation": "看護師2人が空のストレッチャーを運んで来ます。ストレッチャー（幅約0.7m）と横を歩く看護師が並ぶと、ハコブくん（幅0.65m）が横を通れる幅は残りません。病院の1日のシミュレーションと同じく、ハコブくんはストレッチャーに道を譲ります。見つけたとき、少し先に病室の扉の前のくぼみがあったので、そこへ入って待ちます。ストレッチャーは一度も速さを落とさずに通り、看護師が「ありがとう」と声をかけます。",
+      "points": ["ストレッチャーを待たせた時間は0秒", "入りきる前に看護師が横を通り、いちばん近づいたのは0.22m（ひやり1件）", "くぼみに入ったハコブくんは、廊下の側へはみ出していない"],
+      "angles": [
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_11_stretcher_alcove_v1.mp4", "sec": 32.8, "timed": true, "note": "声あり（音を出して見てください）" },
+        { "id": "top", "label": "真上から", "src": "/media/scene3d_11_stretcher_alcove_top_v1.mp4", "sec": 32.8, "timed": true, "note": "床の点線はハコブくんのふだんの通り道。紫の枠は扉の前のくぼみ。緑はハコブくん、オレンジはストレッチャーの通った跡" }
+      ],
+      "steps": [
+        { "t": 0.0, "text": "ハコブくんが廊下を走る。向こうから看護師2人がストレッチャーを運んで来る" },
+        { "t": 6.9, "text": "ストレッチャーを見つけ、前の扉のくぼみへ寄り始める" },
+        { "t": 7.2, "text": "「ストレッチャーが通ります。こちらでお待ちします」" },
+        { "t": 12.0, "text": "看護師「ありがとう」。ハコブくんは目まで笑う顔" },
+        { "t": 15.4, "text": "くぼみの中で止まる。ストレッチャーは止まらずに通る" },
+        { "t": 17.8, "text": "ストレッチャーが通り過ぎたので、くぼみから出る" },
+        { "t": 30.7, "text": "ふだんの通り道に戻る" }
+      ]
+    },
+    {
+      "id": "stretcher_back",
+      "group": "廊下",
+      "num": "12",
+      "name": "ストレッチャーに道を空ける（後ろに下がる）",
+      "short": "くぼみを通り過ぎていたので、後ろ向きに下がって道を空ける",
+      "poster": "/media/scene3d_12_stretcher_back_poster_v1.jpg",
+      "place": "幅1.8mの病棟の廊下（両側に手すり・病室の扉の前にくぼみ）",
+      "who": "看護師2人（ストレッチャーを押す人と、横に付き添う人）・空のストレッチャー・ハコブくん（薬を載せて走っている）",
+      "situation": "⑪と同じくストレッチャーが来ますが、扉の前のくぼみは、ハコブくんがストレッチャーを見つける少し前に通り過ぎていました。前には譲れる所がありません。ハコブくんは止まって「すみません、下がります」と伝え、看護師にストレッチャーを止めてもらってから、後ろ向きにゆっくり（0.2m/秒）くぼみまで下がって入ります。ストレッチャーを待たせた時間を、左下に字で出しています。",
+      "points": ["ストレッチャーを待たせた時間は33.5秒（⑪は0秒）", "ハコブくんは約6m・31秒かけて後ろに下がった", "くぼみが前にあるか後ろにあるかで、人を待たせる時間が変わる"],
+      "angles": [
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_12_stretcher_back_v1.mp4", "sec": 79.8, "timed": true, "note": "声あり（音を出して見てください）" },
+        { "id": "top", "label": "真上から", "src": "/media/scene3d_12_stretcher_back_top_v1.mp4", "sec": 79.8, "timed": true, "note": "床の点線はハコブくんのふだんの通り道。紫の枠は扉の前のくぼみ。緑はハコブくん、オレンジはストレッチャーの通った跡" }
+      ],
+      "steps": [
+        { "t": 0.0, "text": "ハコブくんが廊下を走る。くぼみの横を通り過ぎる" },
+        { "t": 6.9, "text": "ストレッチャーを見つけて止まる" },
+        { "t": 8.9, "text": "「すみません、下がります」。画面が黄色の「下がります」" },
+        { "t": 11.2, "text": "看護師「はーい、待ってるね」。ストレッチャーを止める" },
+        { "t": 12.8, "text": "後ろ向きに0.2m/秒で下がり始める" },
+        { "t": 43.5, "text": "くぼみの中で止まる" },
+        { "t": 44.5, "text": "ストレッチャーが動き出す。左下に「ストレッチャーを待たせた 33.5秒」" },
+        { "t": 57.1, "text": "看護師「ありがとう」。ハコブくんは目まで笑う顔" },
+        { "t": 64.3, "text": "くぼみから出て、ふだんの通り道に戻る" }
+      ]
+    },
+    {
+      "id": "corner_fast",
+      "group": "廊下",
+      "num": "13",
+      "name": "曲がり角で車いすと出会う（速さを落とさない）",
+      "short": "0.8m/秒のまま角に入り、2.4cmの所で止まる",
+      "poster": "/media/scene3d_13_corner_fast_poster_v1.jpg",
+      "place": "幅1.8mの廊下が直角に曲がる角（内側は壁で、向こうが見えない）",
+      "who": "看護師（車いすを押す人）・入院中の患者（車いすに乗る人）・ハコブくん（薬を載せて走っている）",
+      "situation": "見通しの悪い曲がり角から、看護師が押す車いすが出てきます。ハコブくんは角でもふだんの速さ（0.8m/秒）のまま進みました。車いすが見えたのは1.65m手前。止まるまでに0.8m進むので、止まったときのすき間は2.4cmでした。看護師は「わっ」と驚いて9秒止まり、ハコブくんは下がって手すり側へ寄ってから車いすを通します。",
+      "points": ["止まったときのすき間は0.024m。ひやり3件・人がよけさせられた1件", "看護師が止まっていた時間は9.0秒", "止まるまでの距離は病院の1日と同じ決まり（0.8m/秒で約0.8m）"],
+      "angles": [
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_13_corner_fast_v1.mp4", "sec": 31.3, "timed": true, "note": "声あり（音を出して見てください）" },
+        { "id": "top", "label": "真上から", "src": "/media/scene3d_13_corner_fast_top_v1.mp4", "sec": 31.3, "timed": true, "note": "オレンジは車いす、緑はハコブくんの通った跡。「見つけた」「止まった」の所に印" }
+      ],
+      "steps": [
+        { "t": 0.0, "text": "ハコブくんが0.8m/秒で角へ向かう。角の向こうから車いすが来る（お互いに見えない）" },
+        { "t": 7.6, "text": "角で車いすを見つける（1.65m手前）。画面が黄色の「止まります」" },
+        { "t": 8.0, "text": "看護師「わっ」" },
+        { "t": 9.4, "text": "止まる。いちばん近い所は2.4cm" },
+        { "t": 9.7, "text": "「失礼しました。お先にどうぞ」" },
+        { "t": 12.1, "text": "手すり側へ下がって寄る。患者「おお、びっくりした」" },
+        { "t": 18.2, "text": "看護師が車いすを押して横を通る" },
+        { "t": 23.9, "text": "車いすが離れたので、角を曲がる" }
+      ]
+    },
+    {
+      "id": "corner_slow",
+      "group": "廊下",
+      "num": "14",
+      "name": "曲がり角で車いすと出会う（手前で速さを落とす）",
+      "short": "角の2m手前で0.4m/秒に落とし、1.34m空けて止まる",
+      "poster": "/media/scene3d_14_corner_slow_poster_v1.jpg",
+      "place": "幅1.8mの廊下が直角に曲がる角（内側は壁で、向こうが見えない）",
+      "who": "看護師（車いすを押す人）・入院中の患者（車いすに乗る人）・ハコブくん（薬を載せて走っている）",
+      "situation": "⑬と同じ角で、車いすも同じ動きで来ます。違うのは、ハコブくんが角の2m手前で0.4m/秒に速さを落としたことだけです。車いすが見えたのは2.39m手前で、0.24mで止まれたので、すき間は1.34m残りました。看護師は止まらずに角を曲がって横を通り、「ありがとう」と声をかけます。",
+      "points": ["止まったときのすき間は1.34m。看護師は止まらずに通れた", "角を曲がり終えるのは⑬より4.5秒遅い", "ひやりは横を通られたときの1件だけ（⑬は3件）"],
+      "angles": [
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_14_corner_slow_v1.mp4", "sec": 26.8, "timed": true, "note": "声あり（音を出して見てください）" },
+        { "id": "top", "label": "真上から", "src": "/media/scene3d_14_corner_slow_top_v1.mp4", "sec": 26.8, "timed": true, "note": "オレンジは車いす、緑はハコブくんの通った跡。「見つけた」「止まった」の所に印" }
+      ],
+      "steps": [
+        { "t": 0.0, "text": "ハコブくんが角へ向かう" },
+        { "t": 4.8, "text": "角の2m手前で0.4m/秒に落とす" },
+        { "t": 7.6, "text": "角で車いすを見つける（2.39m手前）" },
+        { "t": 8.7, "text": "止まる。すき間は1.34m" },
+        { "t": 9.0, "text": "「お先にどうぞ」" },
+        { "t": 10.3, "text": "看護師は止まらずに曲がって横を通る。「ありがとう」" },
+        { "t": 15.0, "text": "車いすが離れたので、0.4m/秒で角を曲がる" },
+        { "t": 24.3, "text": "曲がり終えて0.8m/秒に戻す" }
+      ]
     }
   ]
 }
```



## 作業ログ ― ストレッチャーを作るコード（p2m-site の tools/sim_people/stretcher/）


### README.md

```markdown
# ストレッチャー（空）の3Dモデル（サービスロボット導入シミュレーション・病院の場面の物）

要所の場面 ⑩ストレッチャーに道を空ける のための物。車いす（p2m-site の tools/sim_people/morita_shigeru/wheelchair_build.py）と同じ作り方で、Blender の Python で作った。患者は乗せない。

- 大きさ：幅 0.74 m（角のバンパーまで。柵の外は 0.70 m）・長さ 2.07 m（押す手まで）・高さ 0.99 m。マットレスの上 0.74 m、柵の上 0.98 m、押す手 0.98 m（頭の側）
- 向き：根（Stretcher）は床の中心。足の側が Unity の +Z（進む向き）、押す手は頭の側（−Z）
- 動かせる部品：Caster_FL/FR/BL/BR（車輪の向き・Y 軸まわり）、その子の CasterWheel_**（車輪の回転・X 軸まわり）、Rail_L/R（横の柵。作った形は上げた状態）
- 三角形 6,384

## 作り方

1. `pip install bpy==5.3.0`
2. `python3 stretcher_build.py <出力フォルダ>`：stretcher.fbx・stretcher.blend・stretcher_report.json
3. 確認用の絵は GitHub に入れない（iCloud の サービスロボット導入シミュレーション/hospital/people_3d/stretcher_3d_preview.jpg）
```


### stretcher_build.py

```python
"""病院のストレッチャー（患者を寝かせて運ぶ台車。空の状態）を作る。
python3 stretcher_build.py <out_dir>
前（足の側・進む向き）が -y、上が z、単位は m。根（Stretcher）は床の中心。頭の側（+y）に押す手がある。
出力：stretcher.blend・stretcher.fbx・stretcher_report.json
FBX は Unity 向け（前が Unity の +Z、上が +Y）。車いす（../morita_shigeru/wheelchair_build.py）と同じ作り方。
回る部品は根を回る中心に置いてある：
- Caster_FL / FR / BL / BR：4つの車輪の向き（支柱が中心。Unity の Y 軸まわりに回す）。F＝足の側、B＝頭の側、L＝+x
- CasterWheel_**：車輪の回転（車軸が中心。Caster の子。Unity の X 軸まわりに回す）
- Rail_L / Rail_R：横の柵（下の軸が中心。Unity の Z 軸まわりに倒せる。作った形は上げた状態）
"""
import json
import math
import os
import sys

import bpy  # noqa: I001
from mathutils import Vector

OUT = sys.argv[1]
os.makedirs(OUT, exist_ok=True)

# ---------- 寸法（m）。国内の搬送用ストレッチャーのよくある大きさ ----------
LEN = 1.90              # 寝台（マットレス）の長さ
MAT_W = 0.60            # マットレスの幅
MAT_T = 0.08            # マットレスの厚み
DECK_Z = 0.66           # 寝台の板の上（この上にマットレス）
MAT_TOP = DECK_Z + MAT_T
DECK_X = 0.315          # 寝台の枠の横の位置
RAIL_X = 0.338          # 横の柵の外の面（全体の幅は 2×(RAIL_X+半径) ≒ 0.70）
RAIL_TOP = MAT_TOP + 0.24
RAIL_Y = 0.62           # 柵の半分の長さ
HANDLE_Y = LEN / 2 + 0.10   # 頭の側の押す手
HANDLE_Z = 0.98
BASE_Z0, BASE_Z1 = 0.17, 0.30   # 下の台（カバー）
BASE_W, BASE_L = 0.54, 1.50
CASTER_R = 0.100        # 車輪（直径 200 mm）
CASTER_X, CASTER_Y = 0.235, 0.66
CASTER_STEM_Z = 0.235   # 車輪の向きを変える支柱の上
CASTER_TRAIL = 0.040

SILVER = (196, 200, 206)
COVER = (226, 228, 232)
MATTRESS = (64, 112, 160)
SHEET = (244, 244, 240)
BLACK = (34, 34, 36)
TIRE = (52, 52, 54)


bpy.ops.wm.read_factory_settings(use_empty=True)


def mat(name, col, metal=0.0, rough=0.5):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    b = m.node_tree.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*[(c / 255) ** 2.2 for c in col], 1)
    b.inputs["Metallic"].default_value = metal
    b.inputs["Roughness"].default_value = rough
    return m


M_SILVER = mat("ST_Frame_Mat", SILVER, 0.8, 0.35)
M_COVER = mat("ST_Cover_Mat", COVER, 0.0, 0.55)
M_MAT = mat("ST_Mattress_Mat", MATTRESS, 0.0, 0.8)
M_SHEET = mat("ST_Sheet_Mat", SHEET, 0.0, 0.9)
M_BLACK = mat("ST_Black_Mat", BLACK, 0.0, 0.6)
M_TIRE = mat("ST_Tire_Mat", TIRE, 0.0, 0.8)


def finish(ob, m, smooth=True):
    bpy.context.view_layer.objects.active = ob
    ob.select_set(True)
    if ob.type == "CURVE":
        bpy.ops.object.convert(target="MESH")
        ob = bpy.context.view_layer.objects.active
    ob.data.materials.clear()
    ob.data.materials.append(m)
    for p in ob.data.polygons:
        p.use_smooth = smooth
    ob.select_set(False)
    return ob


def tube(name, pts, r=0.011, m=M_SILVER, res=10):
    cu = bpy.data.curves.new(name, "CURVE")
    cu.dimensions = "3D"
    cu.bevel_depth = r
    cu.bevel_resolution = 2
    cu.use_fill_caps = True
    sp = cu.splines.new("POLY")
    sp.points.add(len(pts) - 1)
    for i, p in enumerate(pts):
        sp.points[i].co = (*p, 1)
    ob = bpy.data.objects.new(name, cu)
    bpy.context.scene.collection.objects.link(ob)
    return finish(ob, m)


def rounded_corner_path(pts, rad=0.04, n=5):
    """折れ線の角を丸める（パイプを曲げた形）"""
    P = [Vector(p) for p in pts]
    out = [P[0]]
    for i in range(1, len(P) - 1):
        a, b, c = P[i - 1], P[i], P[i + 1]
        u, v = (a - b).normalized(), (c - b).normalized()
        r = min(rad, (a - b).length * 0.45, (c - b).length * 0.45)
        p0, p1 = b + u * r, b + v * r
        for k in range(n + 1):
            t = k / n
            out.append((1 - t) ** 2 * p0 + 2 * (1 - t) * t * b + t * t * p1)
    out.append(P[-1])
    return [tuple(p) for p in out]


def box(name, c, size, m, bevel=0.006):
    bpy.ops.mesh.primitive_cube_add(size=1, location=c)
    ob = bpy.context.active_object
    ob.name = name
    ob.scale = size
    bpy.ops.object.transform_apply(scale=True)
    if bevel:
        md = ob.modifiers.new("b", "BEVEL")
        md.width = bevel
        md.segments = 3
        bpy.ops.object.modifier_apply(modifier="b")
    ob.select_set(False)
    return finish(ob, m)


def torus_x(name, center, R, r, m, seg=72, mseg=10):
    """x 軸に垂直な面の輪"""
    bpy.ops.mesh.primitive_torus_add(major_radius=R, minor_radius=r, major_segments=seg, minor_segments=mseg,
                                     location=center, rotation=(0, math.radians(90), 0))
    ob = bpy.context.active_object
    ob.name = name
    bpy.ops.object.transform_apply(rotation=True)
    ob.select_set(False)
    return finish(ob, m)


def cyl_x(name, center, r, depth, m, seg=32):
    bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=depth, vertices=seg, location=center,
                                        rotation=(0, math.radians(90), 0))
    ob = bpy.context.active_object
    ob.name = name
    bpy.ops.object.transform_apply(rotation=True)
    ob.select_set(False)
    return finish(ob, m)


def join(name, obs, origin):
    bpy.ops.object.select_all(action="DESELECT")
    for o in obs:
        o.select_set(True)
    bpy.context.view_layer.objects.active = obs[0]
    if len(obs) > 1:
        bpy.ops.object.join()
    ob = bpy.context.view_layer.objects.active
    ob.name = name
    ob.data.name = name
    # 根を回る中心へ
    bpy.context.scene.cursor.location = origin
    bpy.ops.object.origin_set(type="ORIGIN_CURSOR")
    ob.select_set(False)
    return ob


# ---------- 下の台（カバー）と寝台を支える柱 ----------
base = [box("base", (0, 0, (BASE_Z0 + BASE_Z1) / 2), (BASE_W, BASE_L, BASE_Z1 - BASE_Z0), M_COVER, 0.04)]
for y in (-0.42, 0.42):   # 上下に動く柱（カバーつき）
    base.append(box(f"col{y}", (0, y, (BASE_Z1 + DECK_Z - 0.06) / 2), (0.20, 0.16, DECK_Z - 0.06 - BASE_Z1), M_COVER, 0.03))
for s in (-1, 1):         # 足で踏むペダル（ブレーキ・高さ）
    base.append(box(f"pedal{s}", (s * 0.18, -BASE_L / 2 - 0.035, 0.20), (0.11, 0.07, 0.025), M_BLACK, 0.006))
base_ob = join("ST_Base", base, (0, 0, 0))

# ---------- 寝台の枠 ----------
fr = []
for s in (-1, 1):
    x = s * DECK_X
    fr.append(tube(f"long{s}", [(x, -LEN / 2, DECK_Z - 0.03), (x, LEN / 2, DECK_Z - 0.03)], 0.016))
for y in (-LEN / 2, LEN / 2):
    fr.append(tube(f"end{y}", [(-DECK_X, y, DECK_Z - 0.03), (DECK_X, y, DECK_Z - 0.03)], 0.016))
# 頭の側の押す手（U の字）
fr.append(tube("handle", rounded_corner_path([
    (-0.25, LEN / 2, DECK_Z - 0.03), (-0.25, HANDLE_Y, HANDLE_Z), (0.25, HANDLE_Y, HANDLE_Z), (0.25, LEN / 2, DECK_Z - 0.03)], 0.06), 0.015))
# 点滴の柱をさす筒（頭の側の角）
for s in (-1, 1):
    fr.append(tube(f"ivsock{s}", [(s * (DECK_X + 0.02), LEN / 2 - 0.03, DECK_Z - 0.10), (s * (DECK_X + 0.02), LEN / 2 - 0.03, DECK_Z + 0.02)], 0.013))
frame_ob = join("ST_Frame", fr, (0, 0, 0))
deck = box("deck", (0, 0, DECK_Z - 0.012), (2 * DECK_X - 0.01, LEN, 0.024), M_COVER, 0.006)
deck_ob = join("ST_Deck", [deck], (0, 0, 0))

# ---------- 角のバンパー（黒い丸） ----------
bmp = []
for s in (-1, 1):
    for t in (-1, 1):
        bpy.ops.mesh.primitive_cylinder_add(radius=0.045, depth=0.05, vertices=32,
                                            location=(s * (DECK_X + 0.01), t * (LEN / 2 + 0.01), DECK_Z - 0.03))
        ob = bpy.context.active_object
        ob.select_set(False)
        bmp.append(finish(ob, M_BLACK))
bmp_ob = join("ST_Bumpers", bmp, (0, 0, 0))

# ---------- マットレスとシーツ・まくら ----------
mat_ob = join("ST_Mattress", [box("mattress", (0, 0, DECK_Z + MAT_T / 2), (MAT_W, LEN - 0.02, MAT_T), M_MAT, 0.03)], (0, 0, 0))
sheet = box("sheet", (0, -0.05, MAT_TOP + 0.002), (MAT_W - 0.03, LEN - 0.20, 0.006), M_SHEET, 0.002)
pillow = box("pillow", (0, LEN / 2 - 0.22, MAT_TOP + 0.045), (0.44, 0.30, 0.09), M_SHEET, 0.04)
sheet_ob = join("ST_Sheet", [sheet, pillow], (0, 0, 0))

# ---------- 横の柵（上げた状態）。根は下の軸 ----------
rails = {}
for s, tag in ((1, "L"), (-1, "R")):
    x = s * RAIL_X
    parts = [tube("rail", rounded_corner_path([
        (x, -RAIL_Y, DECK_Z - 0.02), (x, -RAIL_Y, RAIL_TOP), (x, RAIL_Y, RAIL_TOP), (x, RAIL_Y, DECK_Z - 0.02)], 0.05), 0.012)]
    parts.append(tube("railmid", [(x, -RAIL_Y, (DECK_Z + RAIL_TOP) / 2 + 0.02), (x, RAIL_Y, (DECK_Z + RAIL_TOP) / 2 + 0.02)], 0.009))
    for k in range(1, 6):
        y = -RAIL_Y + 2 * RAIL_Y * k / 6
        parts.append(tube("railbar", [(x, y, DECK_Z - 0.01), (x, y, RAIL_TOP)], 0.008))
    parts.append(tube("hinge", [(x, -RAIL_Y - 0.02, DECK_Z - 0.03), (x, RAIL_Y + 0.02, DECK_Z - 0.03)], 0.011))
    rails[tag] = join("Rail_" + tag, parts, (x, 0, DECK_Z - 0.03))

# ---------- 4つの車輪。向きの根は支柱、回る根は車軸 ----------
casters = {}
for fy, ft in ((-1, "F"), (1, "B")):
    for s, st in ((1, "L"), (-1, "R")):
        tag = ft + st
        x, y = s * CASTER_X, fy * CASTER_Y
        stem_top = (x, y, CASTER_STEM_Z)
        axle = (x, y + CASTER_TRAIL, CASTER_R)
        fork = [tube("forkstem", [(x, y, CASTER_STEM_Z + 0.03), (x, y, CASTER_R + 0.11)], 0.012)]
        for d in (-1, 1):
            fork.append(tube("fork", rounded_corner_path([
                (x, y, CASTER_R + 0.11), (x + d * 0.030, y, CASTER_R + 0.11), (x + d * 0.030, axle[1], axle[2])], 0.015), 0.007))
        fork.append(box("forktop", (x, y + 0.01, CASTER_R + 0.115), (0.075, 0.045, 0.014), M_SILVER, 0.003))
        casters[tag] = join("Caster_" + tag, fork, stem_top)
        w = [cyl_x("cw", axle, CASTER_R, 0.040, M_TIRE, 48), cyl_x("cwhub", axle, 0.035, 0.046, M_COVER, 24)]
        casters["W" + tag] = join("CasterWheel_" + tag, w, axle)

# ---------- 親子と根 ----------
root = bpy.data.objects.new("Stretcher", None)
bpy.context.scene.collection.objects.link(root)
for ob in (base_ob, frame_ob, deck_ob, bmp_ob, mat_ob, sheet_ob, rails["L"], rails["R"],
           *[casters[t] for t in ("FL", "FR", "BL", "BR")]):
    ob.parent = root
for t in ("FL", "FR", "BL", "BR"):
    cw = casters["W" + t]
    mw = cw.matrix_world.copy()
    cw.parent = casters[t]
    cw.matrix_world = mw

bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "stretcher.blend"))
bpy.ops.export_scene.fbx(
    filepath=os.path.join(OUT, "stretcher.fbx"), use_selection=False, object_types={"EMPTY", "MESH"},
    apply_unit_scale=True, apply_scale_options="FBX_SCALE_ALL", axis_forward="-Z", axis_up="Y",
    bake_space_transform=False, mesh_smooth_type="FACE", use_mesh_modifiers=False, use_triangles=True,
    add_leaf_bones=False, bake_anim=False, path_mode="STRIP", embed_textures=False,
)
tris = {o.name: sum(len(p.vertices) - 2 for p in o.data.polygons) for o in bpy.data.objects if o.type == "MESH"}
tris["_total_triangles"] = sum(tris.values())
mins = Vector((9, 9, 9))
maxs = Vector((-9, -9, -9))
for o in bpy.data.objects:
    if o.type == "MESH":
        for v in o.data.vertices:
            w = o.matrix_world @ v.co
            mins = Vector(map(min, mins, w))
            maxs = Vector(map(max, maxs, w))
rep = {"triangles": tris, "size_m": {"width_x": round(maxs.x - mins.x, 3), "length_y": round(maxs.y - mins.y, 3),
       "height_z": round(maxs.z - mins.z, 3)}, "bbox_min": [round(v, 3) for v in mins], "bbox_max": [round(v, 3) for v in maxs],
       "mattress_top_z": round(MAT_TOP, 3), "rail_top_z": round(RAIL_TOP, 3), "push_handle_z": HANDLE_Z,
       "push_handle_y": round(HANDLE_Y, 3), "caster_radius": CASTER_R}
json.dump(rep, open(os.path.join(OUT, "stretcher_report.json"), "w"), ensure_ascii=False, indent=1)
print(json.dumps(rep, ensure_ascii=False))
```


### 確認用の絵を描いたスクリプト（st_render.py。GitHub には入れていない）

```python
import bpy, sys, math
from mathutils import Vector
bpy.ops.wm.open_mainfile(filepath=sys.argv[1]); out=sys.argv[2]
sc=bpy.context.scene
try: sc.render.engine='BLENDER_EEVEE_NEXT'
except: sc.render.engine='BLENDER_EEVEE'
sc.render.resolution_x=900; sc.render.resolution_y=700
w=bpy.data.worlds.new('w'); sc.world=w; w.use_nodes=True; w.node_tree.nodes['Background'].inputs[0].default_value=(1,1,1,1); w.node_tree.nodes['Background'].inputs[1].default_value=0.9
for e,r in [((50,0,30),3.0),((-40,0,-120),1.5)]:
    l=bpy.data.lights.new('s','SUN'); l.energy=r; o=bpy.data.objects.new('s',l); sc.collection.objects.link(o); o.rotation_euler=[math.radians(a) for a in e]
cam=bpy.data.cameras.new('c'); co=bpy.data.objects.new('c',cam); sc.collection.objects.link(co); sc.camera=co
T=Vector((0,0,0.5))
views={'persp':(2.6,-2.4,1.8),'side':(3.2,0,0.55),'front':(0,-3.4,0.6),'top':(0,0,4.5),'back':(-2.2,2.8,1.6)}
for n,p in views.items():
    if n in ('side','front','top'):
        cam.type='ORTHO'; cam.ortho_scale=2.5 if n!='front' else 1.4
    else: cam.type='PERSP'; cam.lens=40
    co.location=p; d=T-Vector(p)
    if n=='top': co.rotation_euler=(0,0,0)
    else: co.rotation_euler=d.to_track_quat('-Z','Y').to_euler()
    sc.render.filepath=f'{out}/{n}.png'; bpy.ops.render.render(write_still=True)
```



## 作業ログ ― 依頼箱に置いた依頼文


### 依頼270 の依頼文（20261123_270_ストレッチャーに道を空ける場面を2本作って撮る.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 300
---
# 依頼270：要所の場面⑩「ストレッチャーに道を空ける」を2本作って撮る

依頼228・229（⑧車いすに道を譲る）と 235・237（⑨車いすが廊下の真ん中で止まる）の依頼文と報告を読んでから始める。廊下・ハコブくん・大城さん・寺島さん・声の作り方・真上の動画の作り（230・232・234・236）は、それを土台にする。⑩は新しい台本 closeup270_script.json と Editor/Closeup270.cs で作る。**①〜⑨の台本・コード・出力には触らない。**

## エイイチと決めたこと（2026-11-23）
- 空のストレッチャーを看護師2人が運んで来る。ハコブくんは、すき間があっても道を譲る（病院の1日の決まり：tools/hospital_sim/hospital-unity-params.json の stretcher_yield「ロボットが譲る」）
- 2本で比べる。⑩-1 前の扉のくぼみに間に合って入り、ストレッチャーは止まらずに通る／⑩-2 くぼみに間に合わず、ストレッチャーを止めて待たせてしまう

## 0. 新しい物：ストレッチャー
- Claude が作ったモデルを使う：iCloud の サービスロボット導入シミュレーション/hospital/people_3d/stretcher/stretcher.fbx（README.md に大きさと部品）。Assets/ServiceSim/Closeups/Models_stretcher/ に写して使う（Models/ には入れない）
- 車輪の向き（Caster_**）は進む向きに合わせ、車輪（CasterWheel_**）は進んだ距離に合わせて回す。車いすと同じ扱い。柵は上げたまま

## 1. 置き方
- 廊下は 229 と同じ（手すりの間 1.68 m）。ハコブくん側（−x）の壁に、病室の扉の前のくぼみを1つ足す（幅と奥行きは、ハコブくんがまっすぐの向きのまま中に入れて、柵の外の面より廊下へ出ない大きさにする。決めた値を報告に書く）。くぼみの所は手すりを切る
- ストレッチャーは、足の側を前にして向こうから来る。大城さんが頭の側の押す手を押し、寺島さんは足の側の横（+x 側から見て廊下の真ん中寄り）を歩いて手を添える。速さは 229 の車いすと同じ
- ストレッチャーと寺島さんが並ぶと、ハコブくんが決まりのすき間で横を通れない幅になること（両側に残る幅を数字で書く）
- ハコブくんは 229 と同じ向き・速さ（0.8 m/秒）・決まりで進む。ストレッチャーを見つける距離は 229 の車いすと同じ

## 2. 流れとセリフ（声は 237 と同じ道具・−20 LUFS。大城さん・寺島さん・ハコブ_イケボ は 声の一覧.json）

### ⑩-1 くぼみに入って待つ（くぼみはハコブくんの前、見つけた所から間に合う距離）
| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1 | ハコブくんが進む。向こうからストレッチャーが来る | ― | 「基本」 |
| 2 | 見つけたら、前のくぼみまで進んで入り、止まる | ハコブ「ストレッチャーが通ります。こちらでお待ちします」 | 帯（ミント）「お待ちしています」 |
| 3 | ストレッチャーは止まらずに通る。寺島さんがハコブくんの横で言う | 寺島「ありがとう」 | 目まで笑う顔 1.5 秒 → 帯 |
| 4 | ストレッチャーの後ろの端がくぼみを 1 m 過ぎたら、くぼみから出て、元の向きで進む | ― | 「基本」 |

### ⑩-2 くぼみに間に合わない（くぼみはハコブくんの後ろ。見つけた時にはもう通り過ぎている）
| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1 | ⑩-1 と同じ。ただしくぼみは、ハコブくんがストレッチャーを見つける少し前に通り過ぎた所にある | ― | 「基本」 |
| 2 | 見つけたら止まる。前には譲れる所が無い | ハコブ「すみません、下がります」 | 帯（黄）「下がります」 |
| 3 | 大城さんがストレッチャーを止める（ハコブくんの前で、決まりのすき間より手前） | 大城「はーい、待ってるね」 | 帯のまま |
| 4 | ハコブくんが後ろ向きにゆっくり（0.2 m/秒）くぼみまで下がって入る。下がるのはこの場面だけの動き | ― | 帯のまま |
| 5 | 大城さんがストレッチャーを動かし始め、通る | 寺島「ありがとう」 | 目まで笑う顔 1.5 秒 → 帯「お待ちしています」 |
| 6 | ⑩-1 の 4 と同じ | ― | 「基本」 |

- ⑩-2 では、ストレッチャーが止まっていた秒（止まってから動き出すまで）を画面の左下に「ストレッチャーを待たせた ○秒」と、動き出した時に 3 秒出す。⑩-1 には出さない
- 待っている間の口：大城さんと寺島さんは話さない。ハコブくんの声に合わせた口の動きだけ

## 3. カメラ（2本とも）
- 本番：229 の本番のカメラ（ハコブくんの後ろの上から、向こうから来るストレッチャーが見える向き）
- 寄り：ハコブくんの画面（帯が出た所）、寺島さんの「ありがとう」の顔
- 真上：1本ずつ。236 の真上の作り（床の目印・通った跡・左上の字）。目印は、くぼみの輪郭と、ハコブくんのふだんの線。左上の字は「動画の秒・ハコブくんとストレッチャー（人を含む）のすき間」

## 4. 確かめ
**必ず守る（外れたら撮らずに止める）**：229・237 と同じ（当たったコマ 0・手が押す手から離れない・車輪が横にすべらない・1 コマで骨が動く量 6 cm 以内・肘が肩より上にならない）。加えて、ハコブくんがくぼみに入った時、廊下の側へ出ている分が無いこと（出ていればその量を書いて止める）
**できるだけ守る（外れても撮って、外れた量を書く）**：ストレッチャーとハコブくんのすき間が 0.15 m 以上・セリフの間 0.4〜0.7 秒・⑩-1 でストレッチャーが一度も速さを落とさないこと
**数えて書く**：⑩-1 と⑩-2 の、ストレッチャーを待たせた秒・ハコブくんが動けなかった秒・病院の1日の数え方（count_rules）での1〜5 の件数

## 5. 撮る
- 動画：closeup270_stretcher_alcove.mp4（⑩-1）・closeup270_stretcher_back.mp4（⑩-2）・それぞれの真上の動画。声あり
- 静止画：ストレッチャーを見つけた所・くぼみに入った所（本番と真上）・寺島さんの「ありがとう」（寄り）・⑩-2 の「下がります」（寄り）・下がっている所（真上）・「ストレッチャーを待たせた」の字の所
- 出力は KIOXIA の service_sim/unity/closeup/20261123_closeup270/、iCloud の hospital/closeup270/ に動画と静止画を写す（md5 を確かめる）。声の mp3 は KIOXIA の出力の audio/ に置く。撮ったコマの画像は mp4 を確かめてから消す
- 作業の区切りで check-in（Mixamo のフォルダは除く）

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・清掃の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**指示していない動作は足さない。** おじぎ・吹き出し・手を振るなどは入れない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・ストレッチャーの FBX が iCloud にある

## 6. 報告
claude_code_reports/20261123_closeup_270.txt（KIOXIA にも写し）。くぼみの大きさと位置、ストレッチャーと人の置き方と両側に残る幅、2本それぞれのセリフごとの時刻の表（動画の秒・声の長さ）、4 の確かめの表と数えた値、カメラの切りかえの表、動画の長さ、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後の1行は「判定：合格／一部外れて撮った／止めた」のどれか。
```


### 依頼271 の依頼文（20261123_271_曲がり角で車いすと出会う場面を2本作って撮る.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 300
---
# 依頼271：要所の場面⑪「曲がり角で車いすと出会う」を2本作って撮る

依頼228・229（⑧車いすに道を譲る）と 237（⑨）の依頼文と報告を読んでから始める。ハコブくん・大城さん・茂さんと車いす・声の作り方・真上の動画の作り（236）は、それを土台にする。⑪は新しい台本 closeup271_script.json と Editor/Closeup271.cs で作る。**①〜⑩（依頼270 を含む）の台本・コード・出力には触らない。** 依頼270 が終わってから始める。

## エイイチと決めたこと（2026-11-23）
- 見通しの悪い曲がり角から、大城さんの押す茂さんの車いすが出てくる。ハコブくんの角での速さを変えて2本で比べる
- ⑪-1 角でも 0.8 m/秒のまま／⑪-2 角の手前で 0.4 m/秒に落とす
- 止まるまでの距離は病院の1日と同じ決まり（hospital-unity-params.json の braking：反応 0.2 秒・減速 0.5 m/秒²。0.8 m/秒で約 0.80 m、0.4 m/秒で約 0.24 m）

## 1. 置き方
- 229 と同じ幅（手すりの間 1.68 m）の廊下を2本、直角につなぐ（L の字）。内側の角は壁で、角の向こうは見えない（鏡・ガラスは置かない）
- ハコブくんは一方の廊下を角へ向かって進み、角を曲がる。ふだんの線は 229 と同じ（壁から同じ距離）。曲がる線は Claude Code が決め、報告に書く
- 大城さんが茂さんの車いすを押して、もう一方の廊下を角へ向かって来る（229 の車いすの速さ）。車いすは内側の角に近い側を来る（見えにくい側）
- ハコブくんのセンサーは、壁を通して見えない（見えるのは、角の壁の線より手前に出てから）。見つけた時の距離を報告に書く
- **2本とも、車いすの動き（出発の時刻・速さ・線）は同じにする。** 違うのはハコブくんの角での速さだけ。ハコブくんの出発の時刻は、⑪-1 で車いすとぶつからずに止まれる範囲で、いちばん近くで出会う時刻にする（決め方と値を書く）。⑪-2 は⑪-1 と同じ出発の時刻・同じ場所から出る

## 2. 流れとセリフ（声は 237 と同じ道具・−20 LUFS。茂さんは 237 の声）

### ⑪-1 0.8 m/秒のまま
| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1 | ハコブくんが 0.8 m/秒で角へ向かう | ― | 「基本」 |
| 2 | 角で車いすを見つけ、決まりどおりに止まる。大城さんも驚いて止まる（口は surprised） | 大城「わっ」 | 帯（黄）「止まります」 |
| 3 | 止まったあと | ハコブ「失礼しました。お先にどうぞ」 | 帯（ミント）「お先にどうぞ」 |
| 4 | 大城さんが車いすを押して、ハコブくんの横を通る（ハコブくんは 229 と同じく、通れるように手すり側へ寄ってから止まっていてよい。寄るかは決まりのすき間で決める） | 茂「おお、びっくりした」 | 帯のまま |
| 5 | 車いすが 1 m 以上離れたら、ハコブくんが角を曲がって進む | ― | 「基本」 |

### ⑪-2 角の手前で 0.4 m/秒
| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1 | 角の手前（角の壁の線から 2.0 m）で 0.4 m/秒に落とす | ― | 「基本」 |
| 2 | 角で車いすを見つけ、止まる | ハコブ「お先にどうぞ」 | 帯（ミント）「お先にどうぞ」 |
| 3 | 大城さんは止まらずに（または少し速さを落として）通る | 大城「ありがとう」 | 目まで笑う顔 1.5 秒 → 「基本」 |
| 4 | ⑪-1 の 5 と同じ。曲がり終えたら 0.8 m/秒に戻す | ― | 「基本」 |

## 3. カメラ（2本とも）
- 本番：角の外側の上から、2本の廊下が両方見える向き（ハコブくんと車いすが、お互いに見えていないことが分かる画角）
- 寄り：ハコブくんの画面（帯が出た所）、大城さんの「わっ」と「ありがとう」の顔
- 真上：1本ずつ。236 の真上の作り。目印は、角の壁の線・ハコブくんの線・「見つけた所」と「止まった所」の印（字つき）。左上の字は「動画の秒・ハコブくんの速さ・ハコブくんと車いす（人を含む）のすき間」

## 4. 確かめ
**必ず守る（外れたら撮らずに止める）**：229・237 と同じ（当たったコマ 0・手が握りから離れない・車輪が横にすべらない・1 コマで骨が動く量 6 cm 以内・肘が肩より上にならない）。ハコブくんの止まり方は braking の決まりのまま（決まりより強く止めて合わせない）
**できるだけ守る（外れても撮って、外れた量を書く）**：セリフの間 0.4〜0.7 秒・2本で車いすの動きの差 0
**数えて書く（2本並べて）**：見つけた時の距離・見つけてから止まるまでの秒と距離・止まった時のいちばん近いすき間・大城さんが止まった秒・病院の1日の数え方（count_rules）での1〜5 の件数（特に 2 ひやり＝0.3 m 未満、3 人がよけさせられた）・角を曲がり終えるまでの秒（2本の差）

## 5. 撮る
- 動画：closeup271_corner_fast.mp4（⑪-1）・closeup271_corner_slow.mp4（⑪-2）・それぞれの真上の動画。声あり
- 静止画：お互いに見えていない所（本番）・見つけた所（本番と真上）・止まった所（本番と真上）・大城さんの「わっ」（寄り）・「ありがとう」（寄り）
- 出力は KIOXIA の service_sim/unity/closeup/20261123_closeup271/、iCloud の hospital/closeup271/ に動画と静止画を写す（md5 を確かめる）。声の mp3 は KIOXIA の出力の audio/ に置く。撮ったコマの画像は mp4 を確かめてから消す
- 作業の区切りで check-in（Mixamo のフォルダは除く）

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・清掃の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**指示していない動作は足さない。** おじぎ・吹き出し・手を振るなどは入れない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み

## 6. 報告
claude_code_reports/20261123_closeup_271.txt（KIOXIA にも写し）。L の字の廊下の寸法、ハコブくんの曲がる線、出発の時刻の決め方、2本それぞれのセリフごとの時刻の表、4 の確かめの表と数えた値（2本並べて）、カメラの切りかえの表、動画の長さ、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後の1行は「判定：合格／一部外れて撮った／止めた」のどれか。
```


### 依頼279 の依頼文（20261123_279_⑩⑪のハコブくんの声を⑤〜⑨と同じ声に差し替える.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 90
---
# 依頼279：⑩（依頼270）と⑪（依頼271）のハコブくんの声だけを、⑤〜⑨と同じ声に差し替える

依頼270 で、ハコブくんの声を 声の一覧.json の「ハコブ_イケボ」（N2Gsbfc4IcGM8KYgkrUz）で作ってしまった。これは依頼文（Claude）の書き間違い。ハコブくんの声は⑤〜⑨と同じ **`gWJpc8whMBqnF7Y0kc9f`**（依頼233・237 と同じ）。

## やること
1. 依頼270 の⑩-1・⑩-2 の、ハコブくんのセリフをすべて `gWJpc8whMBqnF7Y0kc9f` で作り直す（作り方・−20 LUFS は 237 と同じ）
2. 依頼271 の⑪-1・⑪-2 のハコブくんの声も確かめ、`gWJpc8whMBqnF7Y0kc9f` でなければ同じく作り直す（そうなら何もしない。どちらだったかを報告に書く）
3. 声の長さが変わった分だけ、そのセリフの口の動きと、その声に続く出来事の時刻を合わせる。動き・カメラ・画面の字・ほかの人の声は変えない。時刻がずれた所は表で書く
4. 本番の動画と真上の動画を撮り直し、同じ名前のファイルを置き換える（KIOXIA の 20261123_closeup270/・20261123_closeup271/、iCloud の hospital/closeup270/・closeup271/。置き換える前の mp4 は同じフォルダの _old_voice/ に移す）。md5 を確かめる。撮ったコマの画像は mp4 を確かめてから消す

## 変えないこと
**声のほかは何も変えない。** くぼみの大きさ・出発の時刻・速さ・カメラ・置き方・セリフの文はそのまま。依頼270・271 の報告の「決めてほしいこと」は、ここでは直さない。

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・清掃の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・依頼271 が終わっている

## 報告
claude_code_reports/20261123_closeup_279.txt（KIOXIA にも写し）。作り直した声の一覧（セリフ・Voice ID・長さの前と後）、271 がどちらだったか、ずれた時刻の表、確かめ（当たったコマ 0 など 270・271 の「必ず守る」がそのままか）、出力の場所、check-in の番号。最後の1行は「判定：合格／止めた」のどちらか。
```



## 作業ログ ― Claude Code の報告


### 依頼270 の結果（20261123_270_ストレッチャーに道を空ける場面を2本作って撮る_20261123_1602.md）

```markdown
# 結果：20261123_270_ストレッチャーに道を空ける場面を2本作って撮る

- 状態：完了
- 始めた時刻：2026-11-23 16:02
- 終わった時刻：2026-11-23 18:24（142分）
- 作業フォルダ：/Users/shimazueiichi/Robotics_UX/ServiceSim
- この続きを Claude Code で話すとき：作業フォルダで `claude --resume c28fc591-4d0b-432f-aaf8-bf2195e024a2`
- 止められた操作：1件（いちばん下に一覧）

## Claude Code の報告

やったこと
- ⑩「ストレッチャーに道を空ける」を2本作り、撮影しました。⑩-1 はくぼみに入って待つ版、⑩-2 はくぼみに間に合わず下がる版です。
- ストレッチャーは Closeups/Models_stretcher/ に写して読み込みました。車輪の向きと回り方は車いすと同じ扱いで、柵は上げたままです。
- 廊下の −x 側にくぼみを足し、その所の手すりを切りました。
- 声4文は 237 と同じ道具で作り、−20 LUFS にそろえました（ハコブ2・大城さん1・寺島さん1）。
- 真上の動画は 236 と同じ作りです（くぼみの輪郭・ハコブくんのふだんの線・通った跡・左上の字）。

結果
- くぼみの大きさは、奥行 0.72 m・長さ 7.90 m にしました（z 4.0〜11.9）。
- 両側に残る幅は −x 側が約 0.37 m、+x 側が 0.09 m です。ハコブくんが通るには 0.863 m 要るので、どちらも通れません。
- 必ず守ることは、2本ともすべて守れました。
  - 当たったコマ 0
  - 手は押す手・柵から離れない
  - 車輪の横すべり 0
  - 1コマで骨が動く量は 5.10 cm
  - 肘が肩より上になることはない
  - くぼみの中で廊下の側へ出ている分は無し（⑩-1 は 0.056 m、⑩-2 は 0.067 m 内側）
- できるだけ守ることのうち、すき間は守れました（⑩-1 は 0.218 m、⑩-2 は 0.459 m）。⑩-1 のストレッチャーは 0.8 m/秒のまま、一度も速さを落としていません。
- 外れたのはセリフの間です。⑩-1 のハコブ→寺島が 1.568 秒、⑩-2 の大城→寺島が 44.582 秒でした。どちらも寺島さんが横に来る時刻で決まる間です。

数えた値

| 項目 | ⑩-1 | ⑩-2 |
|---|---|---|
| ストレッチャーを待たせた秒 | 0 | 33.7 |
| ハコブくんが動けなかった秒 | 2.4 | 25.2（ほかに下がっていた 30.7 秒） |
| count_rules 1 急に止まった | 0 | 0 |
| 2 ひやり | 1（寺島さん 0.218 m） | 0 |
| 3 人がよけさせられた | 0 | 0 |
| 4 立ち往生 | 0 | 0 |
| 5 ストレッチャーの進む先を横切った | 1 | 0 |

- 動画の長さは ⑩-1 が 32.767 秒、⑩-2 が 79.967 秒です（声あり）。それぞれに真上の動画があります。
- 静止画は14枚撮りました。KIOXIA と iCloud に写し、md5 は 18 ファイルとも同じでした。
- 撮ったコマの画像は、mp4 を確かめてから消しました。
- check-in は cs:176 と cs:177 です。保留は無しです。

変えたファイル
- Assets/ServiceSim/Closeups/ の中の新しいファイルだけです。
  - closeup270_script.json
  - closeup270_top.json
  - Editor/Closeup270.cs
  - Editor/Closeup270Stretcher.cs
  - Models_stretcher/（stretcher.fbx と材質6個）
  - Textures/c270_back_band.png
  - それぞれの .meta
- 報告：claude_code_reports/20261123_closeup_270.txt（KIOXIA の 20261123_closeup270/report270.txt にも写し）

決めてほしいこと
1. くぼみの長さ 7.90 m は、229 の向きの決まり（入る時 15°・出る時 10°）から出た値で、扉の前のくぼみとしては長いです。この大きさでよいか。
2. ⑩-1 は 229 の決まりと見つける距離 6 m のままでは入り切れませんでした。寺島さんが横を通った時はまだ寄っている途中で、止まったのはその 3.1 秒後です。この形でよいか。
3. ⑩-2 の下がり方：まっすぐ 0.73 m 下がってから寄り、合わせて 5.98 m・30.7 秒下がりました。これより手前で止まると、くぼみから前へ出られません。この下がり方でよいか。
4. 「決まりのすき間より手前」は、大城さんが「すみません」を聞いて止め始める形と読みました。前の端どうし 2.677 m で止まっています。この読み方でよいか。
5. セリフの間の外れ（1.568 秒と 44.582 秒）は、このままでよいか。
6. 依頼文はハコブくんの速さ 0.8 m/秒でしたが、依頼233 の答えに合わせて 0.6 m/秒にしました。これでよいか。
7. ハコブくんの声は 声の一覧.json の「ハコブ_イケボ」N2Gs… を使いました（⑧⑨は gWJpc8…）。この声でよいか。
8. 本番のカメラは、229 と同じ置き方のままハコブくんの z に付いて動く形にしました。ストレッチャーが通る時、2人がカメラのすぐ近くを通ります。このままでよいか。
9. 寺島さんのプレハブには動かし方（controller）が入っていません。そのため 235〜238 の動画では、寺島さんは腕を下ろした形のまま足を動かさずに位置だけ動いていました。270 では場面の中だけで入れて歩かせました（プレハブは変えていません）。235〜238 を直すか。
10. ⑩-2 でくぼみから出る時、ハコブくんの角がくぼみの端の壁の角と 0.016 m まで近づきます（当たってはいません）。このままでよいか。
11. 数え方 5「横切った」の数え方を私が決めました（⑩-1 で 1 件）。この数え方でよいか。
12. 前にくぼみがあれば入る・無ければ下がる、の選び方は場面ごとに台本で決めました。ハコブくんが自分で見積もって選ぶ決まりにはしていません。病院の1日に入れるなら、決め方が要ります。
13. ⑩-2 の真上のカメラは、止まったストレッチャーが写るように ⑩-1 より広くしました。2本で大きさが違ってよいか。
14. 229 の車いすは横を通る時 0.65 m/秒に落としていましたが、⑩-1 は「一度も速さを落とさない」を優先して 0.8 m/秒のままにしました。これでよいか。

判定：一部外れて撮った

## 止められた操作

- {"tool_name": "Bash", "tool_use_id": "toolu_01AxjaoLZ9w9wArKTdzjV3ug", "tool_input": {"command": "rm -rf /tmp/c270/out/stretcher_alcove_r/frames /tmp/c270/out/stretcher_back_r/frames /tmp/c270/out/stretcher_back_t/frames", "description": "Delete rendered frame images after mp4 check"}}
```


### 依頼271 の結果（20261123_271_曲がり角で車いすと出会う場面を2本作って撮る_20261123_1824.md）

```markdown
# 結果：20261123_271_曲がり角で車いすと出会う場面を2本作って撮る

- 状態：完了
- 始めた時刻：2026-11-23 18:24
- 終わった時刻：2026-11-23 19:50（86分）
- 作業フォルダ：/Users/shimazueiichi/Robotics_UX/ServiceSim
- この続きを Claude Code で話すとき：作業フォルダで `claude --resume 4cc8df4e-9068-49d7-97af-d8cf09d68929`
- 止められた操作：1件（いちばん下に一覧）

## Claude Code の報告

**やったこと**
- 228・229・237（と 236・270）の依頼文と報告を読み、⑪ を新しく作りました。台本 `closeup271_script.json`（`make_script271.py` が作る）と `Editor/Closeup271.cs` で、場面は2本です。⑪-1 は「角でも 0.8 m/秒のまま」、⑪-2 は「角の手前で 0.4 m/秒」です。
- 廊下は手すりの間 1.68 m の2本を、L の字につなぎました。内側の角は壁の塊にしてあります。
- ハコブくんは、229 と同じ x −0.33 を進み、半径 1.53 m で右へ曲がります。1.53 m は、0.8 m/秒で向きの変わる速さがちょうど 30°/秒になる半径です。
- 車いすは内側を通ります。手すりの線の角を中心に、半径 0.42 m で左へ曲がります。
- 見つける決まり：車いす・人の点が角の壁の線（x 0.90）より手前に出て、前の端から 6.0 m 以内に入った時です。止まり方は braking の決まり（0.2 秒そのまま → 0.5 m/秒²）のままです。
- 出発の時刻は、⑪-1 を 1/30 秒ごとに回して決めました。外形の箱のすき間が 0 にならない範囲で一番小さくなる時刻で、0.900 秒です。⑪-2 も同じ時刻・同じ場所から出ます。
- 新しい声を3つ作りました（ハコブ「失礼しました。お先にどうぞ」・大城「わっ」・茂「おお、びっくりした」。どれも −20 LUFS）。⑪-2 の「お先にどうぞ」「ありがとう」は 228 の声をそのまま使いました。
- 本番・寄り・真上の動画を撮りました。真上は 236 の作りで、角の壁の線・ハコブくんの線・「見つけた」「止まった」の印を描き、左上に秒・速さ・すき間を出しています。

**結果**
- 必ず守る：2本ともすべて守れました。
  - 当たったコマは 0 です。
  - 手は握りから離れません。
  - 車輪の横すべりは最大 0.14 mm/コマ（丸めの差）です。
  - 1 コマの骨の動きは最大 5.64 cm です。
  - 肘は肩より上になりません。
  - 見つけてから止まるまで、⑪-1 は 0.800 m・1.800 秒、⑪-2 は 0.240 m・1.033 秒で、決まりのままです。
- 見つけた時の距離（前の端から見つけた点まで）：⑪-1 は 1.649 m、⑪-2 は 2.391 m です。
- 止まった時のすき間：⑪-1 は 0.024 m（茂さんのスリッパ）、⑪-2 は 1.339 m です。⑪-2 は、その後止まったまま横を通られて 0.094 m（人だけなら 0.151 m）まで近づきます。
- 大城さんが止まった秒：⑪-1 は 8.966 秒、⑪-2 は 0 秒です。
- 角を曲がり終えるまで、⑪-1 は ⑪-2 より 4.500 秒遅いです。
- できるだけ守る、で外れたのは2つです。
  - ⑪-1 のセリフの間「わっ」→「失礼しました」が 1.397 秒です。
  - 2本で車いすの動きの差：線の差は 0.0019 m だけですが、⑪-1 は大城さんが止まるので途中から時刻がずれます。
- 病院の1日の数え方（count_rules）での件数：

| 項目 | ⑪-1 | ⑪-2 |
|---|---|---|
| 1 急に止まった | 0 | 1 |
| 2 ひやり（0.3 m 未満） | 3 | 1 |
| 3 人がよけさせられた | 1 | 0 |
| 4 立ち往生 | 0 | 0 |
| 5 横切った | 2 | 0 |

- 動画の長さ：⑪-1 は 31.333 秒、⑪-2 は 26.833 秒です。真上の動画にも同じ声を入れました。
- KIOXIA と iCloud に写して md5 を確かめ、違いは 0 でした。撮ったコマの画像は mp4 を確かめてから消しました。
- check-in は cs:178 です。保留は無しです。
- 判定：一部外れて撮った

**変えたファイル**
- `Assets/ServiceSim/Closeups/closeup271_script.json`
- `Assets/ServiceSim/Closeups/closeup271_top.json`
- `Assets/ServiceSim/Closeups/Editor/Closeup271.cs`
- `Assets/ServiceSim/Closeups/Textures/c271_stop_band.png`
- 上の4つそれぞれの `.meta`
- 出力：KIOXIA の `service_sim/unity/closeup/20261123_closeup271/`、iCloud の `hospital/closeup271/`
- 報告：`claude_code_reports/20261123_closeup_271.txt`（KIOXIA にも写し）

**決めてほしいこと**
1. 見つける決まり：「角の壁の線より手前に出て、6.0 m 以内」にしました。病院の1日の前のセンサー（幅 0.65 m の箱）にすると、内側を曲がる車いすが箱に入らず、⑪-2 では止まらずにすれ違ってしまうので使っていません。この決め方でよいか。
2. 出発の時刻の決め方と、その結果の近さ（止まった時 0.024 m）でよいか。
3. 大城さんは、ハコブくんが見えた 0.6 秒後から止めました（270 の値）。⑪-1 だけ止まるのは決まりで分けたのではなく、台本で分けています。この形でよいか。
4. 車いすは半径 0.42 m・0.65 m/秒で曲がります（向きの変わる速さ 約 89°/秒）。大城さんの足が転倒防止のバーに当たっていたので、曲がる間は1歩を短くし、足を少し後ろに着くようにしました。この曲がり方でよいか。
5. ⑪-1 のハコブくんは、止まった時すでに 15.0° 曲がり始めていました。そこから 1.02 m 下がりながら手すり側へ寄りました。向きは最大 15.2° で、229 の 15° をわずかに超えます。この寄り方でよいか。
6. ⑪-2 は車いすが止まらないので寄る時間が無く、0.094 m で横を通られました。寄らずに止まっていてよいか。
7. 数え方：「急に止まった」は ⑪-2 だけが 1件になります。「横切った」には ⑪-1 で下がって寄る動きも1件に数えました。この数え方でよいか。
8. ⑪-1 のセリフの間（1.397 秒）と、茂さんの「おお、びっくりした」の時刻でよいか。茂さんのセリフは、横を通る時ではなく、ハコブくんが下がって寄っている間に置きました。
9. ハコブくんの声は ⑧⑨ と同じ gWJpc8…（270 は ハコブ_イケボ）にしました。読みは耳で聞いていません。この声でよいか。
10. 本番のカメラは 2本の廊下と角の壁の塊が入るよう、高さ 7.5 m から撮りました。そのため人とハコブくんが小さく写ります。このままでよいか。
11. 大城さんの口は、「わっ」から「失礼しました…」が終わるまで surprised のままです。このままでよいか。

## 止められた操作

- {"tool_name": "Bash", "tool_use_id": "toolu_016GRtamhi6bnJAPHkA9pRJX", "tool_input": {"command": "cp /tmp/c271/out/closeup271_script.json /tmp/c271/out/closeup271_top.json ~/Robotics_UX/ServiceSim/Assets/ServiceSim/Closeups/ && cd /tmp/c271 && rm -rf /tmp/c271/rend_old; mv /tmp/c271/rend /tmp/c271/rend_old 2>/dev/null; for sh in corner_fast corner_slow; do S=$(date +%s); tools/run271.sh /tmp/c271/run5/$sh $sh off on; echo \"check $sh $(( $(date +%s)-S )) s\"; done; for sh in corner_fast corner_s
```


### 依頼279 の結果（20261123_279_⑩⑪のハコブくんの声を⑤〜⑨と同じ声に差し替える_20261123_2229.md）

```markdown
# 結果：20261123_279_⑩⑪のハコブくんの声を⑤〜⑨と同じ声に差し替える

- 状態：完了
- 始めた時刻：2026-11-23 22:29
- 終わった時刻：2026-11-23 23:15（47分）
- 作業フォルダ：/Users/shimazueiichi/Robotics_UX/ServiceSim
- この続きを Claude Code で話すとき：作業フォルダで `claude --resume 8762c71d-3f38-4b2b-84f3-802a0af7a79b`

## Claude Code の報告

**やったこと**
- 始める前に 4 点を確かめ、どれも依頼の条件どおりでした。
  - 保留は無し（cs:180）
  - Unity と回し係は動いていない
  - KIOXIA はマウント済み
  - 依頼271 は終わっている
- ⑩（依頼270）のハコブくんのセリフ 2 つを `gWJpc8whMBqnF7Y0kc9f` で作り直しました。作り方は 237 と同じです（eleven_v4・種 7・1 文ずつ −20 LUFS・48 kHz）。
- 台本は 270 の道具をそのまま使い、声のファイルだけ差し替えて作り直しました。
  - 作る前に、古い声を入れると check-in 済みの台本と md5 まで同じものができることを確かめました。
- 本番と真上の 4 本を撮り直し、同じ名前で置き換えました。前の動画は同じフォルダの `_old_voice/` に移しました。

**結果**
- 声の長さ（声のある所）：
  - 「ストレッチャーが通ります。こちらでお待ちします」：3.220 → 2.780 秒
  - 「すみません、下がります」：1.940 → 1.750 秒
- ⑪（依頼271）は 2 本ともはじめから `gWJpc8whMBqnF7Y0kc9f` でした。作り直していません。
- ⑩-1 で変わったのは次の 2 つだけで、動きの値は全部同じです。
  - 口が動く所
  - 画面の寄りから本番に戻る時刻：10.567 → 10.133 秒
- ⑩-2 は、大城さんの返事から後が 0.2 秒（6 コマ）前へずれました。動きそのものは、前の動きを 6 コマ前へずらしたものと全部のコマで同じです。
  - 長さ：79.967 → 79.767 秒
  - ストレッチャーを待たせた秒：33.7 → 33.5 秒
  - ずれた時刻は報告の表に全部書きました。
- 「必ず守る」はすべて 270 と同じ値のままです。当たったコマは 0 で、すき間・数え方 1〜5 も同じです。⑩-1 の確かめの記録は 1 字も違いません。
- 動画 4 本と静止画 14 枚の md5 は、作業の元・KIOXIA・iCloud の 3 か所で違い 0 でした。撮ったコマの画像は、動画を確かめてから消しました。
- check-in は cs:181 です。

**変えたファイル**
- `Assets/ServiceSim/Closeups/closeup270_script.json` だけです。コードは変えていません。
- 出力は次の 2 か所です。
  - KIOXIA の `20261123_closeup270/`：動画、stills、stills_check、audio、`_old_voice/`、`v279/`
  - iCloud の `hospital/closeup270/`：動画、stills、`_old_voice/`
- 報告は `claude_code_reports/20261123_closeup_279.txt` に書き、KIOXIA の `v279/` にも写しました。
- ⑪ のフォルダには触っていません。

**決めてほしいこと**
なし。ただし、声が短くなったため、⑩-1 のハコブ→寺島のセリフの間が 1.568 → 2.008 秒に広がりました。270 の「決めてほしいこと 5」の外れが大きくなっています。依頼どおり、ここでは直していません。

判定：合格
```


### 依頼270 の報告の全文（report270.txt）

```text
依頼270：要所の場面⑩「ストレッチャーに道を空ける」を 2 本作って撮った（⑩-1 くぼみに入って待つ・⑩-2 くぼみに間に合わず下がる）（2026-11-23）

依頼228・229・235・237 の依頼文と報告を読んでから始めた。廊下・ハコブくん・大城さん・寺島さん・声の作り方・真上の動画の作り（230・232・234・236）を土台にした。
⑩ は新しい台本 closeup270_script.json（道具 make_script270.py が作る。場面 stretcher_alcove＝⑩-1・stretcher_back＝⑩-2。寺島さんは <場面>__tera）と、
新しいコード Editor/Closeup270.cs（Closeup237.cs の作りを写して変えた）・Editor/Closeup270Stretcher.cs（ストレッチャーの読み込み・寸法）で作った。
触ったのは Assets/ServiceSim/Closeups/ の中の新しいファイルだけ。①〜⑨ の台本・コード・出力、Models/、病院の1日の場面、配膳・清掃の場面、共通の部品（CloseupDirector.cs・CloseupNurse.cs を含む）、
Packages、実行ファイルには触っていない。寺島さんのプレハブ（Models_terashima/）も変えていない。場面のファイルは保存していない。Mixamo の FBX は使っていない・写していない・check-in していない。
指示していない動作（おじぎ・吹き出し・手を振る）は入れていない。

結論：2 本とも「必ず守る」はすべて守れた（当たったコマ 0・手は押す手／柵から離れない・車輪は横にすべらない・1 コマの骨の動き 5.10 cm・肘は肩より上にならない・くぼみの中で廊下の側へ出ている分 無し）。
「できるだけ守る」は、すき間（⑩-1 寺島さんと 0.218 m・⑩-2 0.459 m）と ⑩-1 のストレッチャーの速さ（0.800 m/秒のまま）は守れた。外れたのはセリフの間（⑩-1 ハコブ→寺島 1.568 秒・⑩-2 大城→寺島 44.582 秒。動きで決まる所）。
ただし ⑩-1 は、229 の決まり（横へ 0.15 m/秒・向き 15°まで）と見つける距離 6.0 m のままでは、ストレッチャーが来るまでにくぼみに入り切れない。寺島さんが横を通った時ハコブくんはまだ寄っている途中で、くぼみの中で止まったのはその 3.1 秒後（決めてほしいことの 2）。
ストレッチャーを待たせた秒：⑩-1 0 秒・⑩-2 33.667 秒（字は「33.7秒」）。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:175 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- ストレッチャーの FBX：iCloud の サービスロボット導入シミュレーション/hospital/people_3d/stretcher/stretcher.fbx がある（md5 f11314265a873ea36110151ac91eb550）

■ 0. ストレッチャー
- Closeups/Models_stretcher/stretcher.fbx に写した（写した後の md5 同じ）。Models/ には入れていない。Rig なし・頂点を読める・材質 6 個は Models_stretcher/Materials/（228 の車いすと同じく FBX の色を sRGB に直した Standard）
- Unity で測った値（根から）：幅 0.74 m（角のバンパー ±0.370）・長さ 2.069 m（足の側の前の端 +1.005・押す手の後ろの端 −1.064）・高さ 0.994 m。
  押す手＝頭の側の横の棒（根の後ろ 1.050・高さ 0.980・半径 0.0144・まっすぐな所 x ±0.19）。柵 Rail_L/R（x ∓0.338・上の棒の高さ 0.98）。車輪 4 つ（半径 0.10、支柱から 0.04 後ろ）
- 根の向き 180°（足の側が −z＝進む向き）。FBX の根の回転（x 270°）は 228 と同じく入れ物の子にして残した
- 車輪：4 つとも 228 の前の車輪と同じ「支柱に引っぱられて後ろへ付いていく」形で向きを決め、進んだ長さ ÷ 0.10 m だけ回した。まっすぐ進むだけなので向きは 4 つとも 0° のまま。柵は上げたまま（動かしていない）

■ 1. 置き方
くぼみ（−x の壁。決めた値）
| 項目 | 値 |
| 奥行 | 0.72 m（壁の面 x −0.90 → くぼみの奥の壁の面 x −1.62） |
| 長さ（z） | 7.898 m（z 4.000〜11.898。廊下の原点から） |
| ハコブくんがくぼみの中で止まる所（根） | x −1.237（奥の壁と 0.053 m＝229 の寄る所と同じすき間）・z 7.21 前後 |
| 手すり | くぼみの所は切った（−x の手すりは z 2.0〜11.9 に無い：扉 1 の前 2.0〜3.8 は前のまま、手すり 2（3.8〜10.1）はくぼみにかかるので外し、手すり 3 は 11.9 から） |
| 扉 | もとの扉 2（z 10.29〜11.71）はくぼみにかかるので外し、くぼみの奥の壁の真ん中に病室の扉（z 7.30〜8.59。飾り）を付けた |
| 廊下 | 断面は 229 と同じ（手すりの間 1.68 m）。ストレッチャーが向こうから来て通り過ぎる所が要るので、長さを奥へ 10 m・手前へ 12 m のばした（z −16〜31） |
- 決め方：ハコブくんがまっすぐ（向き 0°）で中に入り、手すりの内の面（x −0.84。柵の外の面＝廊下の側の面と読んだ）より廊下へ出ない奥行 0.72 m。
  長さは、229 の決まり（寄る時は向き 15°まで・横 0.15 m/秒まで、走り出しは向き 10°まで・角の線）で、⑩-1 の入る道と出る道・⑩-2 の下がる道と出る道で、ハコブくんの角が手すりの線より外に出る z の範囲＋0.05 m（tools/make_script270.py・geo/feas270.txt・geo/chk270.txt）。
  入る道だけで 3.84 m 前へ進み、向き 10° で出る道に 7.03 m かかるため、この長さになった（決めてほしいことの 1）
- くぼみの中で止まった時の右（+x）の端：⑩-1 x −0.8959・⑩-2 x −0.9068（手すりの線 −0.84 から廊下の側へ出ている分 無し。0.056・0.067 m 内側）

ストレッチャーと人
| | 置き方 |
| ストレッチャー | 中心 x +0.38（+x の端 0.75 と手すりの内の面 0.84 のすき間 0.09 m・−x の端 +0.01）。足の側を前にして向こう（+z）から −z へ。速さ 0.8 m/秒（229 の車いすと同じ） |
| 大城さん | 頭の側。根 x +0.38、ストレッチャーの根の後ろ 1.32 m（押す手の棒は根の前 0.27 m）。両手を棒の上（x ±0.14）に、手のひらの中心は棒の面の 4.6 cm 上・棒の中心の 4.5 cm 手前、指はのばして棒の上から前へ（指の曲げ 5°・親指は上げる） |
| 寺島さん | 足の側の横・−x の側（廊下の真ん中寄り）。根 x −0.22、ストレッチャーの根の前 0.21 m（足の側の半分の横）。左手を柵（Rail_R）の上の棒（根の前 0.31 m の所。柱の間）に添える。右手は歩きの振り |
両側に残る幅（ハコブくんが通るのに要る幅：外形の幅 0.66＋すき間 0.15＋手すりと 0.053 ＝ 0.863 m）
| 側 | 残る幅 | 通れるか |
| −x（ハコブくんの側） | 手すりの線 −0.84 から寺島さんの −x の端（約 −0.47。根 −0.22 から体の半分 0.25 m とした見積もり）まで 約 0.37 m／寺島さんがいなくてもストレッチャーの −x の端 +0.01 まで 0.85 m | 通れない（0.863 m 要る） |
| +x | ストレッチャーの +x の端 0.75 と手すりの線 0.84 のあいだ 0.09 m | 通れない |

ハコブくん
- 229 と同じ向き・決まり（台本 robot_rule の値は 229 のまま）。速さは 229 の決まりの 0.6 m/秒にした（依頼文の「0.8 m/秒」は、依頼233 の答え「229 と同じ決まり（0.6 m/秒）。0.8 m/秒は誤り」に合わせた。決めてほしいことの 6）
- 見つける距離は 229 と同じ（前の端どうし 6.0 m・0.1 秒前に見た値）。見つけたら、すき間があっても譲る（stretcher_yield「ロボットが譲る」）
- ⑩-1：前のくぼみへ、229 の「寄る」動き（寄る速さ 0.5 m/秒・向き 15°まで・角の線・残り 0.03 m で止まり始める）で入って止まる
- ⑩-2：止まる（0.4 m/秒²）→ 声 → 大城さんの返事の後、後ろ向きに 0.2 m/秒で下がる。くぼみの端（根が 11.898＋0.5）まではまっすぐ下がり、そこから 229 の寄り方を後ろ向きに使ってくぼみへ寄り、⑩-1 と同じ止まる所まで下がって止まる
  （まっすぐ下がる所を入れないと角が手すりに当たる。止まる所を ⑩-1 と同じにしないと、走り出しの向き 10° でくぼみの奥の端までに出られない。決めてほしいことの 3）
- 出る（2 本とも）：ストレッチャーの後ろの端（押す手）がくぼみの手前の端 z 4.0 を 1 m 過ぎたら、229 の走り出し（0.6 m/秒・向き 10°まで・角の線）でふだんの位置 x −0.33 へ戻り、元の向きで進む
- ハコブくんの動きは、台本を作る時に Python で 229 の決まり（Closeup229.cs の StepSpeed・StepLat を写した robot270.py）を回して毎コマの位置・向きを台本に書き、Unity はそれを置いて確かめた
  （Unity の頂点で測った「見つけた」：2 本とも 6.933 秒・前の端どうし 5.993 m。台本は 0.1 秒前に見た値で 7.000 秒）

■ 2. 流れとセリフ（動画の秒＝台本の秒 − 0.100。はじめの 3 コマは寺島さんの形が落ち着くコマなので使っていない）
⑩-1（closeup270_stretcher_alcove.mp4・32.767 秒）
| 順 | できごと・セリフ | 動画の秒 | 声の長さ | 画面 |
| 1 | ハコブくん 0.6 m/秒・ストレッチャーが向こうから 0.8 m/秒 | 0.000〜 | | 基本 |
| 2 | 見つけた（前の端どうし 6.0 m）→ くぼみへ寄り始める | 6.900 | | |
| 2 | ハコブ「ストレッチャーが通ります。こちらでお待ちします」 | 7.200〜10.420 | 3.220 秒 | 帯（ミント）「お待ちしています」7.200〜 |
| 3 | 寺島さんがハコブくんの横（根の z が並んだ所 12.333）で 寺島「ありがとう」（顔をハコブくんのほうへ） | 11.988〜12.678 | 0.690 秒 | 目まで笑う顔 12.667〜14.167（1.5 秒）→ 帯 |
| 2 | 寄り終わり（残り 3 cm）・くぼみの中で止まる | 13.900・15.433 | | |
| 4 | ストレッチャーの後ろの端がくぼみを 1 m 過ぎた → くぼみから出る → ふだんの位置に戻り終わる | 17.833・30.733 | | 基本 17.833〜 |
| | 終わり（戻り終わりの 2 秒後） | 32.767 | | |
- セリフの間：ハコブ→寺島 1.568 秒（寺島さんが横に来る時刻で決まる）
⑩-2（closeup270_stretcher_back.mp4・79.967 秒）
| 順 | できごと・セリフ | 動画の秒 | 声の長さ | 画面 |
| 1 | ハコブくん 0.6 m/秒（くぼみの横を通り、後ろの端が奥の端を 0.30 m 過ぎた所で見つける） | 0.000〜 | | 基本 |
| 2 | 見つけた・止まる（z 13.127） | 6.900・8.667 | | |
| 2 | ハコブ「すみません、下がります」 | 8.867〜10.807 | 1.940 秒 | 帯（黄）「下がります」8.867〜 |
| 3 | 大城さんが止め始める（声の始まり＋0.6 秒）・止まる（前の端どうし 2.677 m） | 9.467・11.067 | | 帯のまま |
| 3 | 大城「はーい、待ってるね」（顔をハコブくんのほうへ） | 11.357〜12.707 | 1.350 秒 | 帯のまま |
| 4 | 後ろ向きに 0.2 m/秒で下がり始める・寄り始める（z 12.396）・くぼみの中で止まる（z 7.147） | 13.033・17.133・43.733 | | 帯のまま |
| 5 | 大城さんが動かし始める（止まって 1.0 秒後） | 44.733 | | |
| 5 | 左下に「ストレッチャーを待たせた 33.7秒」 | 44.733〜47.733（3 秒） | | |
| 5 | 寺島「ありがとう」（横に並んだ所 57.633） | 57.288〜57.978 | 0.690 秒 | 目まで笑う顔 57.967〜59.467 → 帯（ミント）「お待ちしています」 |
| 6 | ストレッチャーの後ろの端がくぼみを 1 m 過ぎた → 出る → 戻り終わる | 64.533・77.900 | | 基本 64.533〜 |
| | 終わり | 79.967 | | |
- セリフの間：ハコブ→大城 0.550 秒・大城→寺島 44.582 秒（下がって通り過ぎるまでの動きで決まる）
- 待っている間の口：大城さん・寺島さんは話さない（口は自分の声の間だけ talk）。ハコブくんは自分の声に合わせて顔の板の口（4 段階）
- 声（tools は 237 と同じ：動画/_制作ベース/tts_eleven.py --try・eleven_v4・種 7・道具の既定の設定。ffmpeg ebur128 で 1 文ずつ −20 LUFS・48 kHz モノラル）。Voice ID は 声の一覧.json
| 名前 | 誰 | セリフ | Voice ID | 長さ | 元 → 直し |
| H1_hakobu_stretcher | ハコブ_イケボ | ストレッチャーが通ります。こちらでお待ちします | N2Gsbfc4IcGM8KYgkrUz | 3.44 秒 | −17.5 → −2.5 dB |
| H2_hakobu_sagarimasu | ハコブ_イケボ | すみません、下がります | N2Gsbfc4IcGM8KYgkrUz | 2.08 秒 | −20.8 → +0.8 dB |
| T1_terashima_arigatou | 寺島 | ありがとう | yWM6Fym2UxDGZqWRoGLB | 1.04 秒 | −16.5 → −3.5 dB |
| O1_oshiro_matteru | 大城 | はーい、待ってるね | PrFsT9a2iZebpuiWVeug | 1.52 秒 | −17.2 → −2.8 dB |
  動画の音全体：⑩-1 −20.4 LUFS・⑩-2 −20.5 LUFS（48 kHz・AAC・2 チャンネル）。読みは耳で聞いていない

■ 3. カメラの切りかえ（動画の秒）
| 本 | 切りかえ |
| ⑩-1 | 本番 0.000／画面の寄り 7.033／本番 10.567／寺島さんの顔 11.633／画面の寄り 12.767（目まで笑う顔）／本番 14.333〜終わり |
| ⑩-2 | 本番 0.000／画面の寄り 8.700（「下がります」）／本番 10.967／寺島さんの顔 56.933／画面の寄り 58.067（目まで笑う顔）／本番 59.633〜終わり |
- 本番：229 の本番と同じ置き方（ハコブくんの後ろ 5.3 m・x −0.62・高さ 1.72 m から、ハコブくんの前 2.3 m の高さ 0.8 m を見る・38°）。229 は止まる所に動かないカメラだったが、⑩ はハコブくんの止まる所が 2 本で違い、⑩-2 は 6 m 下がるので、ハコブくんの z に付いて動く形にした（決めてほしいことの 8）
- 画面の寄り：ハコブくんの位置と向きに付いて動く（217〜237 と同じ置き方）。寺島さんの顔：「ありがとう」の真ん中の時刻のハコブくんの後ろ 2.3 m・高さ 1.42 m から寺島さんの顔（22°）
- 真上：236 の作り（ものごとに穴を埋めた外形の中に床の目印を描かない・目印は通った跡の下）。目印はくぼみの輪郭（紫・字「くぼみ（奥行 0.72 m・長さ 7.90 m）」）とハコブくんのふだんの線 x −0.33（緑の点線）。
  通った跡：ハコブくんの根（深緑）・ストレッチャーの根（橙）。印：見つけた・止まった・下がり始め・くぼみで止まった・出た／ストレッチャーが止まった・動き出した。左上の字は「動画の秒」と「ハコブくんとストレッチャー（人を含む）のすき間」（1.5 m より遠い時はそう書く）。
  もの：ハコブくん／ストレッチャーと大城さんと寺島さん（2 人とも手をのせたままなので 1 つのものとして埋めた。236 の考えと同じ）。外形の中に残った目印の画素：2 本とも 0
  真上のカメラ：⑩-1 は 230 と同じ大きさ（z 3.42〜13.67）。⑩-2 は止まったストレッチャーとくぼみの中のハコブくんが一緒に写るように広くした（z 3.9〜18.1・1 m＝135 画素）

■ 4. 確かめ（区切らずに最後まで回した回の値。out/<場面>/check270.txt・an270_<場面>.txt）
必ず守る
| 項目 | ⑩-1 | ⑩-2 | 合否 |
| 当たったコマ：ハコブくんと物（ストレッチャー・大城さん・寺島さん）／ハコブくんと壁・手すり・扉 | 0／0 | 0／0 | 合う |
| 当たったコマ：ストレッチャー・大城さん・寺島さんと壁 | 0・0・0 | 0・0・0 | 合う |
| 当たったコマ：大城さん・寺島さんとストレッチャー（手の押す手／柵のほか）・2 人どうし・手が棒／柵の中 | 0・0・0・0・0 | 0・0・0・0・0 | 合う |
| 手が押す手から離れない（大城さん） | 手のひらの中心と棒の面 0.0461 m（全部のコマ同じ）・的とのずれ 0.0000・手の頂点と棒の面 +2.1 mm | 同じ | 合う |
| 寺島さんの手が柵から離れない | 手のひらの中心と柵の面 0.0300 m（同じ）・ずれ 0.0000・手の頂点と柵 +1.0 mm | 同じ | 合う |
| 車輪が横にすべらない | 横すべり 0.00000 m/コマ・車輪の向き 0°・車輪の下 0〜0.21 mm・回った角度と進んだ長さのずれ 0.18 mm | 0.00000・0°・0〜0.21 mm・0.45 mm | 合う |
| 1 コマで骨が動く量（根の動きを除く） | 大城さん 5.10 cm・寺島さん 5.10 cm（つま先・歩き） | 同じ | 合う（6 cm 以内） |
| 肘が肩より上にならない（肘と肩の高さの差の最大） | 大城さん −0.238 m・寺島さん −0.166 m | 同じ | 合う |
| 足のすべり・沈み・浮き（2 人） | 0.00・0.00・0.00 cm | 同じ | 合う |
| くぼみに入った時、廊下の側（手すりの線 −0.84）へ出ている分 | 無し（一番 +x の所 −0.8959） | 無し（−0.9068） | 合う |
できるだけ守る
| 項目 | ⑩-1 | ⑩-2 | 合否 |
| ストレッチャー（人を含む）とハコブくんのすき間 0.15 m 以上 | 0.218 m（寺島さん・12.467 動画）・ストレッチャー 0.616・大城さん 0.993 | 0.459 m（寺島さん）・0.925・1.073 | 合う |
| セリフの間 0.4〜0.7 秒 | ハコブ→寺島 1.568 秒 | ハコブ→大城 0.550 秒・大城→寺島 44.582 秒 | 外れ（動きで決まる間） |
| ⑩-1 でストレッチャーが一度も速さを落とさない | 0.800〜0.800 m/秒 | — | 合う |
参考
- ハコブくんと壁の一番近い所：⑩-1 0.028 m（くぼみに寄っている途中 15.233 台本）・⑩-2 0.016 m（くぼみから出る時、左前の角とくぼみの奥の端の壁の角 73.233 台本）。当たってはいない（229 の寄る所の 0.053 m より近い。決めてほしいことの 10）
- ⑩-1 でくぼみの中で止まったのは、寺島さんが横を通った 3.1 秒後（寺島さんが横 12.433・止まった 15.533 台本）

数えて書く
| 項目 | ⑩-1 | ⑩-2 |
| ストレッチャーを待たせた秒 | 0 秒 | 33.667 秒（止まり終わり 11.167 → 動き出し 44.833 台本） |
| ハコブくんが動けなかった（止まっていた）秒 | 2.434 秒（くぼみの中） | 25.234 秒（下がる前 4.400・くぼみの中 20.834）。ほかに後ろへ下がっていた 30.700 秒 |
| 1 急に止まった（走っている所から 1.0 秒以内に止まった） | 0（減速の始まりから 8.466 秒） | 0（1.700 秒） |
| 2 ひやり（人とハコブくんの外形が 0.3 m 未満） | 1（寺島さん 0.218 m） | 0（寺島さん 0.459 m） |
| 3 人がよけさせられた（2.0 m 以内で人が止まる・向きを変える） | 0（2 人とも止まらず、向きも変えない） | 0（止まった時、寺島さんの体の前の端とハコブくんの前の端 3.32 m・大城さん 4.85 m。向きは変えない） |
| 4 立ち往生（30 秒以上動けず人が動かした） | 0 | 0（30 秒以上止まっていた区切りは無い・人は動かしていない） |
| 5 ストレッチャーの進む先 1.5 m 以内をハコブくんが横切った | 1（台本 10.367 秒：前の端どうし 1.50 m の時、ハコブくんの +x の端 −0.372 が寺島さんとストレッチャーの通る帯〔−0.47〜+0.75〕に入ったまま横へ動いていた） | 0 |
  数え方：hospital-unity-params.json の count_rules の値（1.0 秒・0.3 m・2.0 m・30 秒・1.5 m）。2 は Unity の外形どうしの距離。3 は 1.5 m より遠いと Unity の値が無いので前後の z で数えた。5 の「横切った」は上の決め方（私が決めた。決めてほしいことの 11）

■ 5. 撮ったもの（1920×1080・30 コマ/秒・1 倍）
| 動画 | 長さ | md5 |
| closeup270_stretcher_alcove.mp4（⑩-1・声あり） | 32.767 秒・983 コマ | 44ccd792b76a302b18d56d2928285cc4 |
| closeup270_stretcher_alcove_top.mp4（⑩-1 真上） | 32.767 秒 | 848fb8e9ca1596895bed9e4e62dd2ad4 |
| closeup270_stretcher_back.mp4（⑩-2・声あり） | 79.967 秒・2399 コマ | 0d5346a259522713149381bcbc65d51a |
| closeup270_stretcher_back_top.mp4（⑩-2 真上） | 79.967 秒 | 54ca76a16a17841529fcee21202e54a9 |
静止画（stills/、場面名を頭に付けた）
- ストレッチャーを見つけた所：s01_found_main・s01_found_top（2 本とも）
- くぼみに入った所：s02_in_alcove_main・s02_in_alcove_top（2 本とも。くぼみの中で止まって 0.3 秒）
- 寺島さんの「ありがとう」（寄り）：s03_arigatou_close（2 本とも）
- ⑩-2 の「下がります」（寄り）：stretcher_back_s04_sagarimasu_close
- 下がっている所（真上）：stretcher_back_s05_backing_top（本番 s05_backing_main も）
- 「ストレッチャーを待たせた」の字の所：stretcher_back_s06_wait_label（動画から取り出したコマ・字が出て 1 秒）
- 真上の静止画は動画と同じ目印・字を重ねたもの。確かめの静止画（stills_check/）：押す手の手・寺島さんの手（1 秒と「ありがとう」の 1 秒前）
撮り方：確かめは区切らずに最後まで回した回、コマは台本の秒で区切って撮った（決まった動きなので区切りをつないでも同じ。区切りの前のコマは確かめを飛ばして動きだけ進めた）。
⑩-2 の真上は、カメラを広くした後に真上だけ撮り直した（本番のコマは同じ）。撮ったコマの画像は mp4 を確かめてから消した

■ 出力の場所（写した後に md5 を確かめた。動画 4 本と静止画 14 枚を KIOXIA・iCloud の両方で確かめて、違い 0）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261123_closeup270/
  動画 4 本・stills/・stills_check/・audio/（声の mp3 と 48 kHz の wav 4 つ・lufs.txt・mix270_<場面>.wav〔台本の秒の音〕・voice_src/〔ElevenLabs の元の mp3〕）・
  out/<場面>/（check270.txt・events270.txt・an270_<場面>.txt・frames270.csv・top270.csv・bones270.csv・feet270.csv・wc270.csv・top270_cam.json・per270・vmap270・unity の記録）・out/make_script270_out.json・
  geo/（stretcher270.txt〔ストレッチャーの寸法〕・stretcher_side/head.png・feas270.txt・chk270.txt）・tools/（make_script270.py・robot270.py・feas270.py・chk270.py・make270.py・an270.py・screen270.py・run270.sh・pipe270*.sh・Closeup270.cs と Closeup270Stretcher.cs の写し）・report270.txt
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup270/（動画 4 本・stills/）

■ check-in
- cs:176（28 件。フォルダ 2 つを含む：closeup270_script.json・closeup270_top.json・Editor/Closeup270.cs・Editor/Closeup270Stretcher.cs・Models_stretcher/（stretcher.fbx・Materials/ 6 個）・Textures/c270_back_band.png と、それぞれの .meta）
- cs:177（closeup270_top.json：⑩-2 の真上のカメラを広くした）
- 保留は無し（cm status は cs:177 で変更なし。Mixamo のフォルダは保留に出ていない）

■ 決めてほしいこと
1. くぼみの大きさ：奥行 0.72 m・長さ 7.90 m。長さは 229 の決まり（寄る時 向き 15°・走り出し 向き 10°）でハコブくんが向きを変えずに入って出られる長さで、病室の扉の前のくぼみとしては長い。この大きさでよいか（短くするなら、くぼみに出入りする時の向きの決まりを変えることになる）
2. ⑩-1：229 の決まり（横へ 0.15 m/秒・向き 15°）と見つける距離 6.0 m では、ストレッチャーが来るまでにくぼみに入り切れない。寺島さんが横を通った時（すき間 0.218 m）ハコブくんはまだ寄っている途中で、止まったのはその 3.1 秒後。「間に合って入る」の形としてこれでよいか
3. ⑩-2 の下がり方：くぼみの端まではまっすぐ 0.73 m 下がり、そこから 229 の寄り方を後ろ向きに使って寄り、⑩-1 と同じ止まる所まで下がった（合わせて 5.98 m・30.7 秒）。ここまで下がらないと、走り出し（向き 10°）でくぼみの奥の端までに出られない。そのためストレッチャーを 33.7 秒待たせた。この下がり方でよいか
4. ⑩-2 で大城さんがストレッチャーを止める所：「決まりのすき間より手前」を「ハコブくんの『すみません』を聞いて止め始める（声の始まりの 0.6 秒後から 1.6 秒で止まる）」とし、前の端どうし 2.677 m で止まった（229 の止まる所 2.0〜3.0 m の中）。この読み方でよいか
5. セリフの間：⑩-1 ハコブ→寺島 1.568 秒、⑩-2 大城→寺島 44.582 秒（寺島さんが横に来る時刻で決まる）。このままでよいか
6. ハコブくんの速さは 229 の決まりの 0.6 m/秒にした（依頼文は 0.8 m/秒。依頼233 の答えに合わせた）。これでよいか
7. ハコブくんの声は 声の一覧.json の「ハコブ_イケボ」N2Gsbfc4IcGM8KYgkrUz を使った（228〜237 の⑧⑨は gWJpc8whMBqnF7Y0kc9f）。この声でよいか
8. 本番のカメラ：229 の本番と同じ置き方を、ハコブくんの z に付いて動く形にした（229 は止まる所に動かないカメラ）。ストレッチャーが通り過ぎる時、2 人がカメラの近くを通る（s02_in_alcove_main）。このままでよいか
9. 寺島さんのプレハブ（Models_terashima/NurseTerashima.prefab）の Animator には動かし方（controller）が入っていない。235〜238 の動画では、寺島さんは腕を下ろした形のまま足を動かさずに位置だけ動いていた（例：237 の stop_voice_s01_terashima_calls.png）。
   270 ではこの場面の中だけで大城さんと同じ Closeup_Nurse.controller を入れて歩かせた（プレハブ・235〜238 は変えていない）。235〜238 を直すか
10. ⑩-2 でくぼみから出る時、ハコブくんの左前の角がくぼみの奥の端の壁の角と 0.016 m まで近づく（当たってはいない。229 の寄る所のすき間 0.053 m より近い）。このままでよいか
11. 数え方 5「横切った」は、ハコブくんが横へ動いている間に、外形の +x の端が寺島さんとストレッチャーの通る帯に入っていて、前の端どうしが 1.5 m 以内、とした（⑩-1 で 1 件）。この数え方でよいか
12. 前にくぼみがあれば入る／無ければ止まって後ろのくぼみへ下がる、の選び方は、場面ごとに台本で決めた（⑩-1 は前・⑩-2 は後ろ）。「入り切れるか」をハコブくんが見積もって選ぶ決まりにはしていない。病院の1日に入れるなら決め方が要る
13. ⑩-2 の真上のカメラは、止まったストレッチャーが写るように ⑩-1（230 と同じ大きさ）より広くした（1 m＝135 画素）。2 本で大きさが違ってよいか
14. ⑩-1 はストレッチャーの速さを 0.8 m/秒のままにした（229 の車いすは横を通る時 0.65 m/秒に落としていたが、「一度も速さを落とさない」を優先した）。これでよいか

判定：一部外れて撮った
```


### 依頼270 ⑩-1 の確かめの記録（check270.txt）

```text
■ stretcher_alcove（986 コマ）
見つけた（Unity の頂点で測った前の端どうし）	6.933 秒・5.993 m（台本の見つけた時刻 7.000）
当たったコマ	ハコブくんと物 0・ハコブくんと壁/手すり/扉 0（）・ストレッチャーと壁 0（）・大城さんと壁 0（）・寺島さんと壁 0（）
当たったコマ（看護師）	大城さんとストレッチャー 0（）・寺島さんとストレッチャー 0（）・寺島さんと大城さん 0（）・手が押す手の棒の中 0（）・手が柵の中 0（）
ハコブくんとストレッチャーの一番近い距離	0.616 m（11.867 秒・ST_Bumpers）
ハコブくんと大城さんの一番近い距離	0.993 m（13.433 秒・Nurse_Skin）
ハコブくんと寺島さんの一番近い距離	0.218 m（12.567 秒・Nurse_Skin）
壁・手すりとのすき間	ハコブくん 0.028 m・ストレッチャー 0.120 m・大城さん 0.258 m・寺島さん 340282300000000000000000000000000000000.000 m
くぼみの中で止まっている間（72 コマ）	ハコブくんの一番 +x の所 x -0.8959（手すりの内の面 −0.84 から廊下の側へ出ている分 -0.0559 m・負は出ていない・15.533 秒）
大城さんの手と押す手の棒	手のひらの中心と棒の面 0.0461〜0.0461 m・的とのずれの最大 0.0000 m・手の頂点と棒の面の一番近い 0.0021 m
寺島さんの手と柵	手のひらの中心と柵の面 0.0300〜0.0300 m・的とのずれの最大 0.0000 m・手の頂点と柵の面の一番近い 0.0010 m
ストレッチャー	車輪の横すべりの最大 0.00000 m/コマ・車輪の向きの最大 0.00°・車輪の下 0.00000〜0.00021 m・回った角度と進んだ長さのずれ 0.00018 m・速さ 0.800〜0.800 m/秒
大城さん	1 コマの骨の動き（根の動きを除く）5.10 cm（LeftToes・0.900 秒）・世界（参考）7.76 cm（LeftToes・0.900）・肘と肩の高さの差の最大 -0.238 m（RightLowerArm・0.567 秒。正は肘が上）
大城さんの足	歩く所 986 コマ・すべり最大 0.00 cm（1.200 秒）・沈み 0.00 cm・両足とも浮いた 0.00 cm
寺島さん	1 コマの骨の動き（根の動きを除く）5.10 cm（RightFoot・0.900 秒）・世界（参考）7.76 cm（RightFoot・0.900）・肘と肩の高さの差の最大 -0.166 m（LeftLowerArm・0.467 秒。正は肘が上）
寺島さんの足	歩く所 986 コマ・すべり最大 0.00 cm（0.133 秒）・沈み 0.00 cm・両足とも浮いた 0.00 cm
画面の変わり目	0.000	- → 基本／7.300	基本 → 帯wait基本／12.767	帯wait基本 → 目まで笑う顔／14.267	目まで笑う顔 → 帯wait基本／17.933	帯wait基本 → 基本
大城さんのまばたき	1.878・5.675・9.174・13.451・17.494・21.851・25.166・30.071・33.229
```


### 依頼271 の報告の全文（report271.txt）

```text
依頼271：要所の場面⑪「曲がり角で車いすと出会う」を 2 本作って撮った（⑪-1 角でも 0.8 m/秒のまま・⑪-2 角の手前で 0.4 m/秒）（2026-11-23）

依頼228・229・237（と 236・270）の依頼文と報告を読んでから始めた（依頼270 は cs:176/177 で終わっていた）。
⑪ は新しい台本 closeup271_script.json（道具 make_script271.py が作る。場面 corner_fast＝⑪-1・corner_slow＝⑪-2）と、新しいコード Editor/Closeup271.cs（Closeup236.cs の車いす・茂さん・大城さん・真上の型を写し、ハコブくんは 270 と同じく台本の値をそのまま置く形）で作った。
触ったのは Assets/ServiceSim/Closeups/ の中の新しいファイルだけ（closeup271_script.json・closeup271_top.json・Editor/Closeup271.cs・Textures/c271_stop_band.png と .meta）。
①〜⑩ の台本・コード・出力、Models/、病院の1日・配膳・清掃の場面、共通の部品（CloseupDirector.cs・CloseupNurse.cs を含む）、Packages、実行ファイルには触っていない。場面のファイルは保存していない。Mixamo の FBX は使っていない・写していない・check-in していない。
病院の1日の params（hospital-unity-params.json の braking・count_rules）は読んだだけ。指示していない動作（おじぎ・吹き出し・手を振る）は入れていない。

結論：2 本とも「必ず守る」はすべて守れた（当たったコマ 0・手は握りから離れない・車輪は横にすべらない・1 コマの骨の動き 最大 5.64 cm・肘は肩より上にならない・止まり方は braking の決まりのまま＝見つけてから止まるまで ⑪-1 0.800 m・⑪-2 0.240 m）。
「できるだけ守る」は 2 つ外れた：⑪-1 のセリフの間 大城「わっ」→ハコブ「失礼しました…」1.397 秒（ハコブくんが止まってから話すため）／2 本の車いすの動き（線の差は 0.0019 m＝コマの間の丸めだけだが、⑪-1 は大城さんが止まるので 9.000 秒から時刻がずれる）。
数えた値：⑪-1 は止まった時のすき間 0.024 m（茂さんのスリッパ）でひやり・人がよけさせられた・横切ったが出た。⑪-2 は止まった時 1.339 m だが、止まったまま車いすが横を通る時に 0.094 m（人だけ 0.151 m）。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:177 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み

■ 1. L の字の廊下の寸法（廊下の原点 (50, 0, 0) から。m）
| 所 | 値 |
| 廊下 A（ハコブくんの廊下） | z の向き。壁の面 x −0.90〜+0.90（1.80）・手すりの間 x −0.84〜+0.84（1.68＝229 と同じ）・長さ z −14.0〜角 |
| 廊下 B（車いすの廊下） | x の向き。壁の面 z −0.90〜+0.90・手すりの間 z −0.84〜+0.84（1.68）・長さ 角〜x 14.0 |
| 角（二つの廊下が重なる所） | x −0.90〜+0.90・z −0.90〜+0.90 |
| 内側の角 | 壁の角 (0.90, −0.90)。x>0.90 かつ z<−0.90 は高さ 2.6 m の壁の塊（向こうは見えない。鏡・ガラスは無し） |
| 角の壁の線 | 内側の角の壁の面の線：A の側 x 0.90・B の側 z −0.90 |
| 手すり | 高さ 0.765〜0.80・太さ 0.035。外側はつながったまま、内側は角で切った（A の内側 z −0.92 まで・B の内側 x 0.92 から） |
| 飾り | 外側の壁に病室の扉 1 つずつ（A：z −5.6〜−4.3・B：x 4.3〜5.6。手すりの後ろ） |

■ 2. ハコブくんの線と曲がる線（決めた値）
- ふだんの線：A は x −0.33（229 と同じ。外側の手すりから 0.51 m）、B は z +0.33（外側の手すりから 0.51 m）。左側通行なので、右へ曲がるハコブくんは外側、車いすは内側を通る
- 曲がる線：z −1.20 から、中心 (1.20, −1.20)・半径 1.53 m の円弧で右へ 90°曲がり、(1.20, +0.33) から B の z +0.33 を +x へ。半径 1.53 m は 0.8 m/秒で向きの変わる速さがちょうど 30°/秒（229 の決まりの向きの変わる速さ）になる値
- ⑪-1 で手すり側へ寄った後（x −0.47）は、z −1.34 から中心 (1.20, −1.34)・半径 1.67 m の円弧で同じ B の z +0.33 に入る（0.8 m/秒で 27.4°/秒）
- 車いすの線（後ろの車軸の真ん中）：B の内側 z −0.42（229 の車いすの中心と同じく手すりから 0.42 m）を −x へ → 手すりの線の角 (0.84, −0.84) を中心に半径 0.42 m で左へ 90° → A の x +0.42 を −z へ（229 と同じ x +0.42）
- 車いすの速さ：229 と同じ 0.8 m/秒。円弧の手前 0.85 m から 0.65 m/秒（229 の横を通る速さ。加速度 0.3 m/秒²）に落として曲がり、大城さんの体がハコブくんの後ろの端を過ぎたら 0.8 m/秒へ戻す
- ⑪-2 の減速：角の壁の線（z −0.90）から前の端が 2.0 m の所で 0.4 m/秒になるように、0.4 m/秒²（229 の減速）で落とした（落とし始め 前の端 z −3.485＝線の 2.585 m 手前・0.4 になった所 2.005 m 手前）。曲がり終えたら 0.8 m/秒へ戻す

■ 3. 見つける・止まる・出発の時刻の決め方
- 見つける：車いす・茂さん・大城さんの点が角の壁の線（x 0.90）より手前に出て、ハコブくんの前の端から 6.0 m 以内（228 の見る範囲）に入ったら。壁の向こうは見えない
- 止まる：見つけたら braking の決まりのまま（0.2 秒そのままの速さ → 0.5 m/秒² で止まる）。0.8 m/秒で 0.800 m・0.4 m/秒で 0.240 m（台本の値で確かめた。強く止めて合わせていない）
- 大城さん：ハコブくんが目から見えた（壁の角を通らない線が引けた）0.6 秒後から止める（⑪-1 だけ。270 と同じ 0.6 秒。0.8 m/秒なら 1.6 秒で止まる形）。⑪-2 は依頼のとおり止まらない
- 出発の時刻の決め方：ハコブくんは z −7.0（x −0.33）に止まっていて、出発の時刻に 0.4 m/秒² で 0.8 m/秒まで加速する。車いすの出発は 0.2 秒（229 と同じ）。
  ⑪-1 を出発の時刻 0.500〜2.500 秒について 1/30 秒ごとに回し、ハコブくんの外形（0.66×0.762 m の箱）と車いす・大城さんの箱（車いす 0.652×1.07 m・大城さん 0.56×0.50 m の大きめの箱）のすき間が 0 にならない範囲で一番小さくなる時刻を選んだ
  → 0.900 秒（箱のすき間 0.0012 m。0.867 秒より前は箱が重なる）。⑪-2 も同じ 0.900 秒・同じ場所から出る
  Unity の本当の形で数えると、⑪-1 のすき間の最小は 0.024 m（止まった時・ハコブくんと茂さんのスリッパ）

■ 4. 流れとセリフ（動画の秒＝台本の秒 − 1.000）
⑪-1（closeup271_corner_fast.mp4・31.333 秒）
| 順 | できごと・セリフ | 動画の秒 | 声の長さ | 画面 |
| 1 | ハコブくん 0.8 m/秒で角へ（車いすも 0.8 m/秒で角へ） | 0.000〜 | | 基本 |
| 2 | 大城さんにハコブくんが見えた | 7.367 | | |
| 2 | ハコブくんが車いすを見つけた（前の端から見つけた点まで 1.649 m） | 7.633 | | |
| 2 | 止め始め（0.2 秒後） | 7.833 | | 帯（黄）「止まります」7.833〜 |
| 2 | 大城「わっ」（口 surprised。止め始め） | 7.967〜8.337 | 0.37 秒 | |
| 2 | 大城さんが止まった・ハコブくんが止まった（z −0.80・向き 15.0°＝曲がり始めていた） | 9.300・9.433 | | |
| 3 | ハコブ「失礼しました。お先にどうぞ」 | 9.733〜11.753 | 2.02 秒 | 帯（ミント）「お先にどうぞ」9.733〜 |
| 4 | 茂「おお、びっくりした」 | 12.303〜13.793 | 1.49 秒 | 帯のまま |
| 4 | ハコブくんが手すり側へ寄る（下がりながら x −0.47 へ・1.02 m・0.2 m/秒） | 12.067〜17.733 | | |
| 4 | 大城さんが押し始める（寄り終わりの 0.5 秒後）→ 横を通る → 大城さんの体がハコブくんの後ろの端を過ぎた | 18.200・21.400 | | |
| 5 | 車いすが 1.005 m 離れた → 角を曲がって進む（0.8 m/秒）→ 曲がり終えた | 23.900・28.800 | | 基本 23.900〜 |
| | 終わり（曲がり終えて 2.5 秒） | 31.333 | | |
- セリフの間：わっ→失礼しました 1.397 秒（外れ）・失礼しました→おお 0.550 秒
⑪-2（closeup271_corner_slow.mp4・26.833 秒）
| 順 | できごと・セリフ | 動画の秒 | 声の長さ | 画面 |
| 1 | 0.8 m/秒 → 0.4 m/秒に落とす（角の壁の線の 2.0 m 手前で 0.4） | 4.800〜5.767 | | 基本 |
| 2 | 車いすを見つけた（前の端から見つけた点まで 2.391 m）・止め始め・止まった（z −2.30・向き 0°） | 7.633・7.833・8.667 | | |
| 2 | ハコブ「お先にどうぞ」（228 の声） | 8.967〜9.797 | 0.83 秒 | 帯（ミント）「お先にどうぞ」8.967〜 |
| 3 | 大城さんにハコブくんが見えた（8.233）。止まらずに 0.65 m/秒で曲がって横を通る。大城「ありがとう」（228 の声） | 10.347〜11.147 | 0.80 秒 | 目まで笑う顔 11.147〜12.647（帯のまま）→ 基本 |
| 4 | 大城さんの体が後ろの端を過ぎた → 1.018 m 離れた → 0.4 m/秒で曲がる → 曲がり終えて 0.8 m/秒へ | 13.700・15.000・24.300 | | 基本 |
| | 終わり | 26.833 | | |
- セリフの間：お先にどうぞ→ありがとう 0.550 秒
- 声（237 と同じ道具：tts_eleven.py --try・eleven_v4・種 7・道具の既定の設定。1 文ずつ −20 LUFS・48 kHz）
| 名前 | 誰 | セリフ | Voice ID | 長さ | 元 → 直し |
| H1_hakobu_shitsurei | ハコブ | 失礼しました。お先にどうぞ | gWJpc8whMBqnF7Y0kc9f（⑧⑨と同じ） | 2.24 秒 | −18.2 → −1.8 dB |
| O1_oshiro_wa | 大城 | わっ | PrFsT9a2iZebpuiWVeug | 0.72 秒 | −18.8 → −1.2 dB |
| M1_morita_bikkuri | 茂 | おお、びっくりした | ydyMD3g4SbEeNpF0wahP（237 の茂さんの声） | 1.60 秒 | −21.2 → +1.2 dB |
| （228 の声） | ハコブ「お先にどうぞ」・大城「ありがとう」 | 228 の L4_hakobu.wav・L5_oshiro.wav をそのまま | | | |
  動画の音全体：⑪-1 −19.9 LUFS・⑪-2 −20.5 LUFS（48 kHz・AAC・2 チャンネル）。読みは耳で聞いていない（読みの確かめもしていない）
- 口：大城さんは「わっ」から「失礼しました…」の終わりまで surprised、「ありがとう」は話す口。茂さんは自分の声の間 talk。ハコブくんは顔の板の口（4 段階）
- 大城さんの顔：自分の声の間だけハコブくんの画面のほうへ（体から 35°まで）。茂さんは顔を動かしていない

■ 5. カメラの切りかえ（動画の秒）
| 本 | 切りかえ |
| ⑪-1 | 本番 0.000／大城さんの顔（わっ）7.567／画面の寄り 8.800（止まります → お先にどうぞ）／本番 12.067〜終わり |
| ⑪-2 | 本番 0.000／画面の寄り 8.867（お先にどうぞ）／大城さんの顔（ありがとう）10.033／画面の寄り 11.400（目まで笑う顔）／本番 12.733〜終わり |
- 本番：角の外側の上（外側の角の上 (−0.85, 7.5, 0.85) から (1.0, 0, −1.5) を見る・画角 50°）。2 本の廊下が両方写り、内側の角の壁の塊がハコブくんと車いすの間にある（s1_unseen_main）
- 画面の寄り：ハコブくんの位置と向きに付いて動く（217〜237 と同じ置き方）。大城さんの顔：声の真ん中の時刻の大城さんの前 1.45 m・高さ 1.48 m（動かないカメラ）
- 真上：1 本ずつ（正射影・画面の上が +z・右が +x・z −4.4〜1.1／x −1.6〜8.2・1 m＝196 画素）。236 の作り（もの〔ハコブくん／車いす・茂さん・大城さん〕ごとに穴を埋めた外形の中に床の目印を描かない・目印は通った跡の下）。
  目印：角の壁の線（紫の実線・字）・ハコブくんの線（緑の点線＝ふだんの線と曲がる線）・「見つけた」「止まった」の印（字に動画の秒）。通った跡：ハコブくんの根（深緑）・車いすの後ろの車軸（橙）。
  左上の字：動画の秒・ハコブくんの速さ・ハコブくんと車いす（人を含む）のすき間（1.5 m より遠い時はそう書く）。外形の中に残った目印の画素：2 本とも 0

■ 6. 確かめ（区切らずに最後まで回した回の値。out/<場面>/check271.txt・an271.txt）
必ず守る
| 項目 | ⑪-1 | ⑪-2 | 合否 |
| 当たったコマ：ハコブくんと車いす・茂さん・大城さん | 0（最小 0.024 m） | 0（最小 0.094 m） | 合う |
| 当たったコマ：車いす・茂さん／大城さん／ハコブくんと壁・手すり・扉 | 0・0・0（0.146・0.159・0.039 m） | 0・0・0（0.146・0.159・0.173 m） | 合う |
| 当たったコマ：大城さんと車いす・手が握りの中 | 0・0 | 0・0 | 合う |
| 手が握りから離れない | 手のひらの中心と握りの面 0.0214 m（全部のコマ同じ）・的とのずれ 0.0000・手の頂点と握り +3.4 mm | 同じ | 合う |
| 車輪が横にすべらない | 後ろ 0.00007 m/コマ（0.07 mm）・前 0.00000・車輪の下 0〜0.23 mm・根の高さ 0 | 後ろ 0.00014 m/コマ（0.14 mm。まっすぐから円弧へ変わるコマ）・前 0.00000 | 合う（229 と同じ数え方の丸め。前の車輪は最大 61°向きを変えて付いていく） |
| 1 コマで骨が動く量（根の動きを除く） | 5.64 cm（右足・曲がる所） | 5.41 cm | 合う（6 cm 以内） |
| 肘が肩より上にならない（肘と肩の高さの差の最大） | −0.221 m | −0.223 m | 合う |
| 大城さんの足のすべり・沈み・浮き | 0.00・0.00・0.00 cm | 同じ | 合う |
| 茂さんの足・体（車いすから） | スリッパ 0.0740・ズボン 0.4899（228 と同じ）・骨の動き 0.00 cm | 同じ | 合う |
| 止まり方が braking の決まりのまま | 見つけてから 0.800 m（決まり 0.80）・1.800 秒 | 0.240 m（決まり 0.24）・1.033 秒 | 合う |
| 止まっている間に動かない | 0.0000 m（266 コマ） | 0.0000 m（191 コマ） | 合う |
できるだけ守る
| 項目 | ⑪-1 | ⑪-2 | 合否 |
| セリフの間 0.4〜0.7 秒 | わっ→失礼しました 1.397 秒／失礼しました→おお 0.550 秒 | 0.550 秒 | ⑪-1 の 1 つ外れ（0.697 秒長い。ハコブくんが止まって 0.3 秒後に話す） |
| 2 本で車いすの動きの差 0 | 線の差（⑪-1 の各点から ⑪-2 の線まで）最大 0.0019 m（コマの間の丸め）。同じ時刻の位置は 9.000 秒（台本）まで同じで、そこから ⑪-1 は大城さんが止まるのでずれる（最大 7.66 m） | | 外れ（止まる分だけ。線は同じ） |
参考：曲がる所で大城さんの足が車いすの転倒防止のバーに入らないように、曲がる間の 1 歩を短く（1 歩で向きの変わる量 20°まで・0.3 秒まで）し、足を根の 0.12 m 後ろ・0.04 m 内側に着くようにした（直す前は ⑪-1・⑪-2 とも 8〜11 コマ当たっていた）

数えて書く（2 本並べて）
| 項目 | ⑪-1 | ⑪-2 |
| 見つけた時の距離 | 前の端から見つけた点（茂さんの足のせのあたり）1.649 m・外形のすき間 1.071 m（Unity の頂点で数え直すと 2 コマ前の動画 7.567 秒・1.414 m） | 2.391 m・外形のすき間 1.5 m より遠い（Unity：2 コマ前・2.038 m） |
| 見つけてから止まるまで | 1.800 秒・0.800 m | 1.033 秒・0.240 m |
| 止まった時のいちばん近いすき間 | 0.024 m（茂さんのスリッパ。人だけでも 0.024 m） | 1.339 m（人だけ 1.366 m） |
| 全体でいちばん近いすき間 | 0.024 m（止まった時） | 0.094 m（車いすの右の後ろの車輪・止まったまま車いすが横を通る時）・人だけ 0.151 m（大城さん） |
| 大城さんが止まった秒 | 8.966 秒（動画 9.300〜18.267） | 0 秒（止まらない） |
| 1 急に止まった（減速の始まりから 1.0 秒以内に止まった） | 0（1.600 秒） | 1（0.833 秒。0.4 m/秒からの止まり方が 1.0 秒より短い） |
| 2 ひやり（人とハコブくんの外形 0.3 m 未満） | 3：動いている間 1（動画 8.500〜13.933・最小 0.024 m。止まる前から下がって寄る間まで続く）・止まっている間 2（横を通る時 0.210 m・0.288 m） | 1：止まっている間（横を通る時 0.151 m） |
| 3 人がよけさせられた（2.0 m 以内で人が止まる・向きを変える） | 1（大城さんが止まった。その時のすき間 0.025 m） | 0（止まらない。向きは予定の線のとおり） |
| 4 立ち往生（30 秒以上動けず人が動かした） | 0（止まっていた間 2.666 秒・6.200 秒） | 0（6.367 秒） |
| 5 車いすの進む先 1.5 m 以内を横切った | 2（動画 8.233〜9.300：止まりながら曲がる線に入った・12.200〜14.400：下がって寄る時に車いすの前を横へ動いた） | 0 |
| 角を曲がり終えるまで（台本の 0 秒から・ハコブくんの出発から） | 29.800 秒・28.900 秒 | 25.300 秒・24.400 秒 |
| 角を曲がり終えるまでの差 | ⑪-1 が 4.500 秒遅い | |
  数え方：hospital-unity-params.json の count_rules（1.0 秒・0.3 m・2.0 m・30 秒・1.5 m）。2 は Unity の外形どうしの距離で、茂さん・大城さんを人として数えた（車いすを含めた参考も an271.txt にある）。
  params の near_miss_split_by_robot_moving・waiting_near_miss に合わせて、ハコブくんが動いている間と止まっている間を分けた。5 の「横切った」は 270 と同じ決め方（決めてほしいことの 7）

■ 7. 撮ったもの（1920×1080・30 コマ/秒・1 倍・声あり）
| 動画 | 長さ | md5 |
| closeup271_corner_fast.mp4（⑪-1） | 31.333 秒・940 コマ | 7813502a004a975501278d31693f8e19 |
| closeup271_corner_fast_top.mp4（⑪-1 真上） | 31.333 秒・940 コマ | cbae81e7254dc102c8a28a37b594d9e1 |
| closeup271_corner_slow.mp4（⑪-2） | 26.833 秒・805 コマ | 6ad53362163863c691f06335ecf6a975 |
| closeup271_corner_slow_top.mp4（⑪-2 真上） | 26.833 秒・805 コマ | fa36bf302a260cc7dab138fdfd8f9908 |
- 真上の動画にも本番と同じ音を入れた（依頼の「声あり」に合わせた。270 の真上は音なし）
- 静止画（stills/、場面名を頭に付けた。2 本とも）：s1_unseen_main（お互いに見えていない所・見つける 1 秒前）・s2_found_main／s2_found_top（見つけた所）・s3_stopped_main／s3_stopped_top（止まった所）・
  corner_fast_s4_wa_face（大城さんの「わっ」寄り）・corner_slow_s4_arigatou_face（「ありがとう」寄り）・s5_pass_main（車いすが横を通り過ぎた所）。真上の静止画は動画と同じ目印・字を重ねたもの
- 確かめの静止画（stills_check/）：握り（2 秒・止める時・曲がる時）・横から（曲がる時）・⑪-1 の寄り終わりの真上
- 撮ったコマの画像は mp4 を確かめて（コマ数・長さ・音）から消した

■ 出力の場所（写した後に md5 を確かめた。動画 4 本と静止画 14 枚を KIOXIA・iCloud の両方で確かめて、違い 0）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261123_closeup271/
  動画 4 本・stills/・stills_check/・audio/（新しい声 3 つの mp3 と 48 kHz の wav・lufs.txt・mix271_<場面>.wav〔台本の秒の音〕・voice_src/〔ElevenLabs の元の mp3〕）・
  out/（closeup271_script.json・closeup271_top.json・make_script271_out.json〔出発の時刻の探し方の表を含む〕・an271.txt・<場面>/〔check271.txt・events271.txt・frames271.csv・top271.csv・bones271.csv・feet271.csv・wc271.csv・top271_cam.json・per271・vmap271・unity の記録〕）・
  tools/（make_script271.py・plan271.py・make271.py・an271.py・screen271.py・run271.sh・lufs.sh・Closeup271.cs の写し）・report271.txt
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup271/（動画 4 本・stills/）

■ check-in
- cs:178（8 件：closeup271_script.json・closeup271_top.json・Editor/Closeup271.cs・Textures/c271_stop_band.png と .meta）。保留は無し（cm status は cs:178 で変更なし）
- 帯の絵 c271_stop_band.png は 270 の帯と同じ描き方（screen271.py。同じ描き方で「お届け完了」「お待ちしています」「通れません」「下がります」「お先にどうぞ」を描くと今の絵と画素まで同じ）

■ 決めてほしいこと
1. 見つける決まり：「角の壁の線（x 0.90）より手前に出た点が、前の端から 6.0 m（228 の見る範囲）以内」にした。病院の1日の前のセンサー（幅 0.65 m・長さ＝止まるまでの距離＋0.3 m の箱）にすると、左側通行で内側を曲がる車いすは箱に入らず、⑪-2 では止まらずにすれ違う形になるため使っていない。止まり方だけ braking の決まり。この決め方でよいか
2. 出発の時刻：「箱で数えたすき間が 0 にならない範囲で一番小さい時刻」（0.900 秒・箱 0.0012 m）にした。Unity の本当の形では止まった時 0.024 m（ひやり）。この近さでよいか
3. 大城さんが止まる所：ハコブくんが見えた 0.6 秒後から止める（270 の値）。⑪-1 だけ止まり、⑪-2 は依頼のとおり止まらない（決まりで分けたのではなく、台本で分けた）。この形でよいか
4. 車いすの曲がり方：車軸の真ん中を手すりの線の角から半径 0.42 m で回し、曲がる間は 0.65 m/秒（向きの変わる速さ 約 89°/秒）。大城さんの足が転倒防止のバーに入らないよう、曲がる間は 1 歩を短く・足を根の後ろに着くようにした。この曲がり方・速さでよいか
5. ⑪-1 のハコブくんは、止まった時すでに曲がり始めていて（向き 15.0°）、そこから 1.02 m 下がりながら手すり側（x −0.47）へ寄った（向きは最大 15.2°＝止まった向きから始まるので 229 の 15°を 0.2°超える。5.7 秒かかる）。寄った後は半径 1.67 m で曲がる。この寄り方でよいか
6. ⑪-2 は車いすが止まらないので寄る時間が無く、止まったまま横を通られた（車いす 0.094 m・人だけ 0.151 m。229 の「すれ違うすき間 0.15 m」より車いすで狭い）。寄らずに止まっていてよいか
7. 数え方：1「急に止まった」は ⑪-2（0.4 m/秒・0.833 秒で止まる）が 1 件になり、⑪-1（1.6 秒）は 0 件になる。5「横切った」は 270 と同じ決め方で、⑪-1 は下がって寄る動きも 1 件に数えた。この数え方でよいか
8. ⑪-1 のセリフの間：「わっ」→「失礼しました」が 1.397 秒（ハコブくんが止まって 0.3 秒後に話すため）。茂さんの「おお、びっくりした」は、横を通る時ではなく「失礼しました」の 0.55 秒後（ハコブくんが下がって寄っている間）にした。このままでよいか
9. 声：ハコブくんは ⑧⑨ と同じ gWJpc8whMBqnF7Y0kc9f（270 はハコブ_イケボ N2Gsbfc4IcGM8KYgkrUz）。⑪-2 の「お先にどうぞ」と「ありがとう」は 228 の声をそのまま使った。読みは耳で聞いていない。この声でよいか
10. 本番のカメラは 2 本の廊下と角の壁の塊が入るように高い所（7.5 m）から撮ったので、人とハコブくんは小さい。寄り（顔・画面）で補った。このままでよいか
11. 大城さんの口：「わっ」の後、ハコブくんの「失礼しました…」が終わるまで surprised のまま。このままでよいか

判定：一部外れて撮った
```


### 依頼279 の報告の全文（report279.txt）

```text
依頼279：⑩（依頼270）と⑪（依頼271）のハコブくんの声を、⑤〜⑨と同じ声 gWJpc8whMBqnF7Y0kc9f にそろえた（2026-11-23）

結論：⑩ はハコブくんのセリフ 2 つを gWJpc8whMBqnF7Y0kc9f で作り直し、4 本（本番と真上 × 2）を撮り直して同じ名前で置き換えた。
⑪ はもともと 2 本とも gWJpc8whMBqnF7Y0kc9f だったので、何もしていない。
270 の「必ず守る」はすべて前と同じ値のまま（当たったコマ 0 など）。動きは ⑩-1 は 1 コマも変わらず、⑩-2 は大城さんの返事から後が、前の動きをそのまま 0.2 秒（6 コマ）前へずらしただけ。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:180 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- 依頼271：終わっている（報告 20261123_closeup_271.txt・cs:178。その後に 272・273 も終わっている）

■ 1. 作り直した声（270 と同じ作り方：動画/_制作ベース/tts_eleven.py --try・eleven_v4・種 7・道具の既定の設定。ffmpeg ebur128 で 1 文ずつ −20 LUFS・48 kHz モノラル）
| 名前 | セリフ | Voice ID（前 → 後） | 声の長さ（声のある所）前 → 後 | ファイルの長さ 前 → 後 | 元 → 直し |
| H1_hakobu_stretcher | ストレッチャーが通ります。こちらでお待ちします | N2Gsbfc4IcGM8KYgkrUz → gWJpc8whMBqnF7Y0kc9f | 3.220 → 2.780 秒（−0.440） | 3.44 → 2.96 秒 | −17.9 LUFS → −2.1 dB → −20.0 |
| H2_hakobu_sagarimasu | すみません、下がります | N2Gsbfc4IcGM8KYgkrUz → gWJpc8whMBqnF7Y0kc9f | 1.940 → 1.750 秒（−0.190） | 2.08 → 1.92 秒 | −18.5 LUFS → −1.5 dB → −20.0 |
- 寺島さん「ありがとう」・大城さん「はーい、待ってるね」は 270 の wav をそのまま使った（md5 同じ）
- 読みは耳で聞いていない（270 と同じ）
- 動画の音全体：⑩-1 −20.4 LUFS・⑩-2 −20.4 LUFS（48 kHz・AAC・2 チャンネル）

■ 2. ⑪（依頼271）はどちらだったか
- ⑪-1 の「失礼しました。お先にどうぞ」（H1_hakobu_shitsurei）：gWJpc8whMBqnF7Y0kc9f（271 の報告と声の記録）
- ⑪-2 の「お先にどうぞ」：228 の L4_hakobu.wav をそのまま使ったもので、228 の報告に gWJpc8whMBqnF7Y0kc9f と書いてある
- 2 本とも正しい声だったので、⑪ は作り直していない・撮り直していない（KIOXIA・iCloud の closeup271 は触っていない）

■ 3. 作り方
- 台本は 270 の道具 make_script270.py をそのまま使い、声の wav のフォルダだけ新しい声のものにして作り直した（コードは 1 行も変えていない）
- 写しの確かめ：同じ道具に 270 の古い声を入れると、check-in されていた closeup270_script.json と md5 まで同じもの（f54eb14a…）と、同じ音（mix270）ができることを確かめてから作った
- 真上のカメラの closeup270_top.json は作り直しても md5 同じ（変えていない）
- 声に続く時刻の決め方は 270 のまま：⑩-1 は「画面の寄りから本番へ戻る＝声の終わり＋0.15 秒」だけが声の長さに付いている。
  ⑩-2 は「大城さんの返事＝ハコブくんの声の終わり＋0.55 秒」「下がり始め＝返事の終わり＋0.3 秒」で、そこから後（下がる・くぼみで止まる・ストレッチャーが動き出す・寺島さんが横に来る・ありがとう・画面・カメラ・出る）はすべて動きで続く
- 動きの確かめ：⑩-2 のハコブくんの毎コマの位置・向きは、新しい台本の 12.933 秒（台本）から後が、古い台本の 6 コマ後と全部のコマで同じ。ストレッチャーも動き出し（44.667 秒）から後が 6 コマ後と同じ。⑩-1 の動きの値は全部同じ
- 変わったのは台本の closeup270_script.json の 1 ファイルだけ。コード（Closeup270.cs など）は変えていない

■ 4. ずれた時刻（動画の秒。動画の秒＝台本の秒 − 0.100）
⑩-1（closeup270_stretcher_alcove.mp4）
| できごと | 前 | 後 | ずれ |
| ハコブ「ストレッチャーが通ります。こちらでお待ちします」 | 7.200〜10.420 | 7.200〜9.980 | 終わり −0.440 |
| ハコブくんの口（話す口が動く所） | 7.233〜10.467 | 7.233〜10.067 | 終わり −0.400（声に合わせた） |
| カメラ：画面の寄り → 本番 | 10.567 | 10.133 | −0.433 |
| セリフの間：ハコブ→寺島 | 1.568 秒 | 2.008 秒 | +0.440（寺島さんの「ありがとう」は横に来る時刻で決まるので動かない） |
- ほかは変わらない（見つけた 6.900・帯「お待ちしています」7.200・寺島「ありがとう」11.988〜12.678・寄り終わり・くぼみで止まる 15.433・出る 17.833・終わり 32.767・983 コマ）
⑩-2（closeup270_stretcher_back.mp4）
| できごと | 前 | 後 | ずれ |
| ハコブ「すみません、下がります」 | 8.867〜10.807 | 8.867〜10.617 | 終わり −0.190 |
| カメラ：画面の寄り → 本番 | 10.967 | 10.767 | −0.200 |
| 大城「はーい、待ってるね」 | 11.357〜12.707 | 11.167〜12.517 | −0.190 |
| 後ろ向きに下がり始める | 13.033 | 12.833 | −0.200 |
| 寄り始める | 17.133 | 16.933 | −0.200 |
| 寄り終わり | 34.433 | 34.233 | −0.200 |
| くぼみの中で止まる | 43.733 | 43.533 | −0.200 |
| 大城さんが動かし始める | 44.733 | 44.533 | −0.200 |
| 左下の字「ストレッチャーを待たせた ○秒」 | 44.733〜47.733「33.7秒」 | 44.533〜47.533「33.5秒」 | −0.200（字の数も 0.2 秒へった） |
| カメラ：寺島さんの顔 | 56.933 | 56.733 | −0.200 |
| 寺島「ありがとう」（横に並んだ所） | 57.288〜57.978（57.633） | 57.088〜57.778（57.433） | −0.200 |
| 画面：目まで笑う顔 → 帯（ミント） | 57.967 → 59.467 | 57.767 → 59.267 | −0.200 |
| カメラ：画面の寄り → 本番 | 58.067 → 59.633 | 57.867 → 59.433 | −0.200 |
| くぼみから出る・画面が基本へ | 64.533 | 64.333 | −0.200 |
| ふだんの位置に戻り終わる | 77.900 | 77.700 | −0.200 |
| 終わり | 79.967（2399 コマ） | 79.767（2393 コマ） | −0.200 |
- 変わらない所：見つけた 6.900・止まる 8.667・帯「下がります」8.867・大城さんが止め始める 9.467（声の始まり＋0.6 秒。声の始まりは同じ）・止まる 11.067
- 大城さんの返事が早くなったので、ストレッチャーが止まり終わる（11.067）から返事の始まり（11.167）まで 0.100 秒になった（前は 0.290 秒）
- セリフの間：ハコブ→大城 0.550 秒（前と同じ）・大城→寺島 44.572 秒（前 44.582）
- 数えて書く値で変わったもの：ストレッチャーを待たせた秒 33.667 → 33.467 秒・ハコブくんが止まっていた秒 25.234 → 25.034 秒（下がる前 4.400 → 4.200 秒。くぼみの中 20.834 秒は同じ）

■ 5. 確かめ（区切らずに最後まで回した回の check270.txt・an270_<場面>.txt を 270 のものと並べた）
| 項目 | ⑩-1 | ⑩-2 | 270 と |
| 当たったコマ（ハコブくんと物・壁/手すり/扉、ストレッチャー・大城さん・寺島さんと壁、看護師とストレッチャー・2 人どうし・手が棒/柵の中） | すべて 0 | すべて 0 | 同じ |
| 手が押す手・柵から離れない／車輪の横すべり 0／1 コマの骨の動き 5.10 cm／肘が肩より上にならない／足のすべり・沈み・浮き 0 | 同じ値 | 同じ値 | 同じ（⑩-1 の check270.txt は 1 字も違わない） |
| くぼみの中で廊下の側へ出ている分 | 無し（−0.8959） | 無し（−0.9068） | 同じ |
| すき間（寺島さん／ストレッチャー／大城さん） | 0.218／0.616／0.993 m | 0.459／0.925／1.073 m | 同じ（⑩-2 は起きた時刻が 0.2 秒早いだけ） |
| ⑩-1 のストレッチャーの速さ | 0.800 m/秒のまま | — | 同じ |
| count_rules の 1〜5 | 0・1・0・0・1 | 0・0・0・0・0 | 同じ |
| 真上：外形の中に残った目印の画素 | 0 | 0 | 同じ |
- 口：ハコブくんの話す口は新しい声の間だけ動く（⑩-1 7.233〜10.067 動画）。⑩-2 の大城さん・寺島さんの口は自分の声に付いて 0.19〜0.2 秒前へずれた
- 撮った動画：⑩-1 983 コマ 32.767 秒、⑩-2 2393 コマ 79.767 秒（台本の長さと合う）。静止画の「待たせた」の字（s06）は「33.5秒」

■ 6. 撮ったもの（1920×1080・30 コマ/秒・1 倍。270 と同じ区切りで撮り、区切らずに回した回の記録で重ねた）
| 動画 | 長さ | md5 |
| closeup270_stretcher_alcove.mp4（⑩-1・声あり） | 32.767 秒・983 コマ | a3fc47634bd5f2f3c31d19236747fb94 |
| closeup270_stretcher_alcove_top.mp4（⑩-1 真上） | 32.767 秒・983 コマ | 12a3aa9d538ade13a1d09cf62329c5ac |
| closeup270_stretcher_back.mp4（⑩-2・声あり） | 79.767 秒・2393 コマ | bff99ea4b896d70d86df644dc1fb7c58 |
| closeup270_stretcher_back_top.mp4（⑩-2 真上） | 79.767 秒・2393 コマ | 2a00104f3d2cbd5a6ecb5084881d875c |
- 静止画 14 枚（stills/）・確かめの静止画 8 枚（stills_check/）も同じ名前で作り直した（⑩-2 は時刻が 0.2 秒ずれるため）
- 撮ったコマの画像は、mp4 のコマ数・長さ・音を確かめてから消した（残り 0）

■ 出力の場所（写した後に md5 を確かめた。動画 4 本・静止画 14 枚を KIOXIA・iCloud・作業の元の 3 か所で、確かめの静止画 8 枚と声の wav/mp3・mix を KIOXIA で確かめて違い 0）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261123_closeup270/
  動画 4 本（置き換え）・stills/・stills_check/（置き換え）・
  audio/（H1・H2 の mp3 と wav を新しい声に置き換え・mix270_<場面>.wav〔台本の秒の音〕・lufs.txt・voice_src/hakobu/〔ElevenLabs の元の mp3〕）・
  _old_voice/（置き換える前の動画 4 本・stills/・stills_check/・audio/〔古い H1・H2・mix・lufs.txt・voice_src_hakobu/〕）・
  v279/（out/<場面>/〔check270.txt・an270・events270・frames270.csv・top270.csv ほか・unity の記録〕・out/make_script270_out.json〔新〕と _old_voice.json〔古い声で作り直した写しの確かめ〕・tools/〔cmp279.py・pipe279.sh・lufs.sh〕）・report279.txt
  270 の out/・tools/・geo/・report270.txt はそのまま残した
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup270/（動画 4 本・stills/ を置き換え。前のものは _old_voice/）
- ⑪：KIOXIA の 20261123_closeup271/・iCloud の hospital/closeup271/ は触っていない（作り直しが要らなかったため）

■ check-in
- cs:181（Assets/ServiceSim/Closeups/closeup270_script.json の 1 件）
- 保留は無し（cm status は cs:181 で変更なし。Mixamo のフォルダは保留に出ていない）
- 触ったのは Closeups/ の中の closeup270_script.json だけ。Models/・病院の1日・配膳・清掃の場面・共通の部品・Packages・実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない・check-in していない。
  hospital-unity-params.json は 270 と同じ数え方の値を読んだだけ（変えていない）

■ 決めてほしいこと
なし（ただし、声が短くなった結果、⑩-1 のセリフの間 ハコブ→寺島 が 1.568 → 2.008 秒になり、270 の「決めてほしいこと 5」の外れが広がった。⑩-2 の待たせた秒は 33.7 → 33.5 秒。依頼どおりここでは直していない）

判定：合格
```



## 作業ログ ― 依頼270 のコード（ServiceSim の Assets/ServiceSim/Closeups/ と、KIOXIA の 20261123_closeup270/tools/）


### Closeup270.cs

```csharp
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace ServiceSim.Closeups.EditorTools
{
    /// <summary>
    /// 依頼270：要所の場面 ⑩「ストレッチャーに道を空ける」。場面 stretcher_alcove（⑩-1 くぼみに入って待つ）・stretcher_back（⑩-2 くぼみに間に合わず下がる）。
    /// 台本は closeup270_script.json（make_script270.py）。Closeup237.cs の作り（廊下・看護師の焼いた形・口・寺島さんの 2 つめの CloseupDirector・画面の帯・真上の型・撮り方）を土台にした。
    /// 237 から変えたこと：
    ///   ・車いす・茂さんの代わりに、空のストレッチャー（Models_stretcher/stretcher.fbx。Closeup270Stretcher が読む）。根の位置は台本の c270.stretcher（毎コマ・向き 180°）。
    ///     4 つの車輪は 237 の前の車輪と同じ「支柱に引っぱられて後ろへ付いていく」形で向きを決め、進んだ長さ ÷ 0.1 m だけ回す。柵は上げたまま（動かさない）
    ///   ・大城さんは頭の側の押す手（横の棒）を両手で押す。寺島さんは足の側の横（−x の側）を一緒に歩き、左手を柵（Rail_R）の上の棒に添える
    ///   ・ハコブくんの位置・向きは台本の c270.robot（make_script270.py が 229 の決まりで出した値）をそのまま置く。Unity では確かめる（見つけた時の前の端どうしのあいだも頂点で測る）
    ///   ・確かめ：当たり（ハコブくんと物・物と壁・看護師とストレッチャー・手が棒/柵の中）・手が棒/柵から離れない・車輪の横すべり・1 コマの骨の動き・肘が肩より上にならない・
    ///     足のすべり（2 人）・くぼみの中で止まっている間に廊下の側（x −0.84 より +x）へ出ている分
    ///   ・真上の型 frames/<場面>_top_obj は赤＝ハコブくん・緑＝ストレッチャーと大城さんと寺島さん（2 人とも手をのせたままなので 1 つのもの）
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup270.Run \
    ///                 -c270Out <出力フォルダ> -c270Shot <場面> [-c270Script closeup270_script.json] [-c270Frames on|off] [-c270Stills on|off] [-c270Views main,top] [-c270From 秒] [-c270To 秒] [-c270Until 秒]
    /// 出すもの：frames/<場面>/f_*.png・frames/<場面>_top(_mask/_obj)/f_*.png・stills/・stills_check/・frames270.csv・top270.csv・bones270.csv・feet270.csv・wc270.csv・check270.txt・events270.txt
    /// </summary>
    public static class Closeup270
    {
        const string Root = CloseupShoot.Root;
        const string TexDir = CloseupShoot.TexDir;
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string F(float v, string f = "0.0000") { return v.ToString(f, IC); }
        const int LayerSt = 30, LayerNurse = 31, LayerTera = 28;
        const int LayerMask232 = 29;

        class RobotShape
        {
            public float band = 0.02f, top, minX, maxX, minZ, maxZ;
            public List<Vector2[]> hulls = new List<Vector2[]>();
            public Vector2[] all;
            public Vector3[] verts;
        }

        static Vector2[] Hull(List<Vector2> p)
        {
            if (p.Count < 3) return null;
            p.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.y.CompareTo(b.y));
            var h = new Vector2[p.Count * 2]; int k = 0;
            Func<Vector2, Vector2, Vector2, float> cr = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
            for (int i = 0; i < p.Count; i++) { while (k >= 2 && cr(h[k - 2], h[k - 1], p[i]) <= 0) k--; h[k++] = p[i]; }
            for (int i = p.Count - 2, t = k + 1; i >= 0; i--) { while (k >= t && cr(h[k - 2], h[k - 1], p[i]) <= 0) k--; h[k++] = p[i]; }
            var r = new Vector2[k - 1]; Array.Copy(h, r, k - 1); return r;
        }

        static float PolyDist(Vector2[] poly, Vector2 q)
        {
            bool inside = true; float best = float.MaxValue;
            for (int i = 0; i < poly.Length; i++)
            {
                Vector2 a = poly[i], b = poly[(i + 1) % poly.Length];
                Vector2 e = b - a;
                if (e.x * (q.y - a.y) - e.y * (q.x - a.x) < 0) inside = false;
                float u = Mathf.Clamp01(Vector2.Dot(q - a, e) / Mathf.Max(1e-12f, e.sqrMagnitude));
                best = Mathf.Min(best, (a + e * u - q).sqrMagnitude);
            }
            return inside ? 0f : Mathf.Sqrt(best);
        }

        static RobotShape MeasureRobot(CloseupDirector dir)
        {
            var rs = new RobotShape();
            var pts = new List<Vector3>();
            foreach (var mf in dir.robot.GetComponentsInChildren<MeshFilter>(true))
            {
                if (dir.screenOverlay != null && mf.gameObject == dir.screenOverlay.gameObject) continue;
                if (!mf.gameObject.activeInHierarchy || mf.sharedMesh == null) continue;
                foreach (var v in mf.sharedMesh.vertices) pts.Add(dir.robot.InverseTransformPoint(mf.transform.TransformPoint(v)));
            }
            rs.verts = pts.ToArray();
            rs.top = float.MinValue; rs.minX = rs.minZ = float.MaxValue; rs.maxX = rs.maxZ = float.MinValue;
            foreach (var p in pts) { rs.top = Mathf.Max(rs.top, p.y); rs.minX = Mathf.Min(rs.minX, p.x); rs.maxX = Mathf.Max(rs.maxX, p.x); rs.minZ = Mathf.Min(rs.minZ, p.z); rs.maxZ = Mathf.Max(rs.maxZ, p.z); }
            int nb = Mathf.CeilToInt(rs.top / rs.band) + 1;
            var bl = new List<Vector2>[nb]; for (int i = 0; i < nb; i++) bl[i] = new List<Vector2>();
            var al = new List<Vector2>();
            foreach (var p in pts)
            {
                int b = Mathf.Clamp(Mathf.FloorToInt(p.y / rs.band), 0, nb - 1);
                bl[b].Add(new Vector2(p.x, p.z)); al.Add(new Vector2(p.x, p.z));
                int b2 = Mathf.Clamp(Mathf.FloorToInt((p.y + 0.005f) / rs.band), 0, nb - 1); if (b2 != b) bl[b2].Add(new Vector2(p.x, p.z));
                b2 = Mathf.Clamp(Mathf.FloorToInt((p.y - 0.005f) / rs.band), 0, nb - 1); if (b2 != b) bl[b2].Add(new Vector2(p.x, p.z));
            }
            for (int i = 0; i < nb; i++) rs.hulls.Add(Hull(bl[i]));
            for (int i = 0; i < nb; i++)
                if (rs.hulls[i] == null)
                {
                    var m = new List<Vector2>();
                    for (int j = i - 1; j >= 0; j--) if (rs.hulls[j] != null) { m.AddRange(rs.hulls[j]); break; }
                    for (int j = i + 1; j < nb; j++) if (bl[j].Count >= 3) { m.AddRange(Hull(new List<Vector2>(bl[j]))); break; }
                    rs.hulls[i] = Hull(m);
                }
            rs.all = Hull(al);
            return rs;
        }

        static float RobotDist(RobotShape rs, Vector3 p, float cut)
        {
            Vector2 q = new Vector2(p.x, p.z);
            float dAll = PolyDist(rs.all, q);
            float dyTop = Mathf.Max(0f, p.y - rs.top), dyBot = Mathf.Max(0f, -p.y);
            if (Mathf.Sqrt(dAll * dAll + Mathf.Max(dyTop, dyBot) * Mathf.Max(dyTop, dyBot)) > cut) return float.MaxValue;
            float best = float.MaxValue;
            int b0 = Mathf.FloorToInt((p.y - cut) / rs.band), b1 = Mathf.FloorToInt((p.y + cut) / rs.band);
            for (int b = Mathf.Max(0, b0); b <= Mathf.Min(rs.hulls.Count - 1, b1); b++)
            {
                if (rs.hulls[b] == null) continue;
                float y0 = b * rs.band, y1 = y0 + rs.band;
                float dy = p.y < y0 ? y0 - p.y : p.y > y1 ? p.y - y1 : 0f;
                if (dy >= best) continue;
                float dh = PolyDist(rs.hulls[b], q);
                best = Mathf.Min(best, Mathf.Sqrt(dh * dh + dy * dy));
            }
            return best;
        }

        class SolidBox { public string name; public Vector3 min, max; public bool rail; }
        static float PointBoxDist(Vector3 p, Vector3 mn, Vector3 mx)
        {
            Vector3 q = new Vector3(Mathf.Clamp(p.x, mn.x, mx.x), Mathf.Clamp(p.y, mn.y, mx.y), Mathf.Clamp(p.z, mn.z, mx.z));
            return Vector3.Distance(p, q);
        }
        static bool InBox(Vector3 p, Vector3 mn, Vector3 mx) { return p.x > mn.x && p.x < mx.x && p.y > mn.y && p.y < mx.y && p.z > mn.z && p.z < mx.z; }

        /// <summary>看護師ひとり分（焼いた形・手の頂点の分け方・骨・靴）</summary>
        class NurseRig
        {
            public string name; public CloseupNurse n; public Animator an;
            public List<SkinnedMeshRenderer> parts = new List<SkinnedMeshRenderer>();
            public List<string[]> partCat = new List<string[]>();
            public List<HumanBodyBones> bones = new List<HumanBodyBones>();
            public Vector3[] prevBones; public Vector3 prevRoot; public bool havePrev;
            public float jumpR, jumpRT, jumpW, jumpWT; public string jumpRB = "", jumpWB = "";
            public float elbowOver = -9f, elbowOverT = -1f; public string elbowOverSide = "";
            public SkinnedMeshRenderer shoe; public Mesh shoeMesh = new Mesh();
            public Vector3[] shoePrev; public bool[] shoeOn; public bool prevInWalk;
            public float slideMax, slideMaxT, sinkMax, sinkMaxT, floatMax, floatMaxT; public int walkFrames;
        }
        static NurseRig MakeRig(string name, CloseupNurse n)
        {
            var g = new NurseRig { name = name, n = n, an = n.Anim };
            foreach (var smr in n.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                foreach (var nm in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                    if (smr.name == nm) g.parts.Add(smr);
            var boneMap = new Dictionary<Transform, HumanBodyBones>();
            for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = g.an.GetBoneTransform((HumanBodyBones)i); if (tb != null) { boneMap[tb] = (HumanBodyBones)i; g.bones.Add((HumanBodyBones)i); } }
            foreach (var smr in g.parts)
            {
                var bw = smr.sharedMesh.boneWeights;
                var cat = new string[smr.sharedMesh.vertexCount];
                for (int i = 0; i < cat.Length; i++) cat[i] = bw.Length > i ? HandCat(smr.bones[bw[i].boneIndex0], boneMap) : "";
                g.partCat.Add(cat);
                if (smr.name == "Nurse_Shoes") g.shoe = smr;
            }
            g.prevBones = new Vector3[g.bones.Count];
            return g;
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c270Out", "");
            if (outDir == "") throw new Exception("-c270Out がない");
            string scriptName = CloseupArgs.Get("-c270Script", "closeup270_script.json");
            string shotName = CloseupArgs.Get("-c270Shot", "stretcher_alcove");
            bool frames = CloseupArgs.Get("-c270Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c270Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c270Views", "main,top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c270From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c270To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                Closeup270Stretcher.CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                string scriptText = File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName);
                dir.LoadScript(scriptText);
                var js = dir.script;
                string topErr; var topAll = JsonValue.Parse(File.ReadAllText(Root + "/closeup270_top.json"), out topErr); if (topAll == null) throw new Exception("closeup270_top.json: " + topErr);
                var topJs = topAll[shotName];
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（237 と同じ。台本の rooms の「廊下…」。くぼみの箱も入っている）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor270").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C270_" + k };
                    Color c; ColorUtility.TryParseHtmlString(js["colors"][k].S(), out c); m.color = c; m.SetFloat("_Glossiness", 0.15f);
                    mats[k] = m;
                }
                var rooms = js["rooms"];
                int nCorr = 0;
                for (int i = 0; i < rooms.Count; i++)
                {
                    var r = rooms[i];
                    if (!r["name"].S("").StartsWith("廊下")) continue;
                    Vector3 a = CloseupDirector.V3(r["min"]), b = CloseupDirector.V3(r["max"]);
                    var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    UnityEngine.Object.DestroyImmediate(go.GetComponent<Collider>());
                    go.name = r["name"].S(); go.transform.SetParent(corr, false);
                    go.transform.position = (a + b) * 0.5f; go.transform.localScale = b - a;
                    var rr = go.GetComponent<Renderer>(); rr.sharedMaterial = mats[r["mat"].S()];
                    if (!r["shadow"].B(false)) rr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
                    if (r["solid"].B(false)) solids.Add(new SolidBox { name = r["name"].S(), min = a, max = b, rail = r["rail"].B(false) });
                    nCorr++;
                }
                log.AppendLine("廊下の箱 " + nCorr + " 個（当たりを数える箱 " + solids.Count + " 個）");

                // ---- 焼いた形（描くのは焼いた形。237 と同じ）
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked270").transform;
                var proxyRootT = new GameObject("Baked270Tera").transform;
                Action<SkinnedMeshRenderer, Transform> addProxy = (smr, pr) =>
                {
                    var g = new GameObject(smr.name + "_Baked"); g.transform.SetParent(pr, false);
                    var mf = g.AddComponent<MeshFilter>(); mf.sharedMesh = new Mesh();
                    var mr = g.AddComponent<MeshRenderer>(); mr.sharedMaterials = smr.sharedMaterials;
                    smr.enabled = false;
                    proxies.Add(new KeyValuePair<SkinnedMeshRenderer, MeshFilter>(smr, mf));
                };
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true)) addProxy(smr, proxyRoot);
                Action syncProxies = () =>
                {
                    foreach (var kv in proxies)
                    {
                        bool on = kv.Key.gameObject.activeInHierarchy;
                        kv.Value.gameObject.SetActive(on);
                        if (!on) continue;
                        kv.Key.BakeMesh(kv.Value.sharedMesh, true);
                        kv.Value.sharedMesh.RecalculateBounds();
                        kv.Value.transform.SetPositionAndRotation(kv.Key.transform.position, kv.Key.transform.rotation);
                    }
                };
                var O_ = MakeRig("大城さん", dir.nurse);
                var an = O_.an;

                // ---- 寺島さん（235 と同じ：2 つめの CloseupDirector。部品の名前 Terashima_ → Nurse_）
                var teraGo = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(Closeup231Terashima.Prefab));
                teraGo.name = "Terashima270";
                foreach (var tr in teraGo.GetComponentsInChildren<Transform>(true)) if (tr.name.StartsWith("Terashima_")) tr.name = "Nurse_" + tr.name.Substring("Terashima_".Length);
                var teraN = teraGo.GetComponent<CloseupNurse>(); if (teraN == null) teraN = teraGo.AddComponent<CloseupNurse>();
                // 寺島さんのプレハブの Animator には動かし方（controller）が入っていない（235〜238 は入れずに動かしていた）。大城さんと同じ Closeup_Nurse.controller をこの場面の中だけで入れる（プレハブは変えない）
                var anTg = teraGo.GetComponent<Animator>();
                if (anTg.runtimeAnimatorController == null) { anTg.runtimeAnimatorController = AssetDatabase.LoadAssetAtPath<RuntimeAnimatorController>(Root + "/Closeup_Nurse.controller"); log.AppendLine("寺島さん：Animator に Closeup_Nurse.controller を入れた（場面の中だけ）"); }
                anTg.cullingMode = AnimatorCullingMode.AlwaysAnimate;
                teraN.Init();
                var dir2 = new GameObject("Director270Tera").AddComponent<CloseupDirector>();
                dir2.nurse = teraN; dir2.robot = dir.robot; dir2.drawer = dir.drawer; dir2.body = dir.body; dir2.face = dir.face; dir2.ring = dir.ring;
                dir2.trays = dir.trays; dir2.box = dir.box; dir2.bag = dir.bag; dir2.card = dir.card; dir2.pocket = dir.pocket; dir2.cam = dir.cam;
                dir2.screenOverlay = dir.screenOverlay; dir2.screenTex = dir.screenTex; dir2.screenTexNames = dir.screenTexNames;
                dir2.LoadScript(scriptText);
                int nProxyO = proxies.Count;
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true)) addProxy(smr, proxyRootT);
                var T_ = MakeRig("寺島さん", teraN);
                var anT = T_.an;
                log.AppendLine("寺島さん：部品 " + T_.parts.Count + "（体）・写し " + (proxies.Count - nProxyO));

                // 口（217・218 と同じ：talk を上の端を止めて縦に倍）
                Func<int, CloseupNurse, Func<float>, Action> mouthScaler = (from, nn, sc) =>
                {
                    MeshFilter tp = null;
                    for (int i = from; i < proxies.Count; i++) if (proxies[i].Key.name == "Nurse_Mouth_talk" && proxies[i].Key.transform.IsChildOf(nn.transform)) tp = proxies[i].Value;
                    if (tp == null) throw new Exception("口の部品 Nurse_Mouth_talk が無い: " + nn.name);
                    return () =>
                    {
                        float s = sc();
                        if (!tp.gameObject.activeSelf || Mathf.Abs(s - 1f) < 1e-4f) return;
                        var mesh = tp.sharedMesh; var vs = mesh.vertices;
                        Vector3 fw = nn.HeadForward().normalized;
                        Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                        Vector3 u = Quaternion.Inverse(tp.transform.rotation) * upW;
                        float top = float.MinValue; foreach (var v in vs) top = Mathf.Max(top, Vector3.Dot(v, u));
                        for (int i = 0; i < vs.Length; i++) { float h = Vector3.Dot(vs[i], u) - top; vs[i] -= u * (h * (1f - s)); }
                        mesh.vertices = vs; mesh.RecalculateBounds();
                    };
                };
                float curMouthScale = 1f, curMouthScaleT = 1f;
                var scaleMouth = mouthScaler(0, dir.nurse, () => curMouthScale);
                var scaleMouthT = mouthScaler(nProxyO, teraN, () => curMouthScaleT);

                // ---- ストレッチャー
                var st = Closeup270Stretcher.Spawn("Stretcher270").transform;
                Func<string, Transform> SF = n => { var t0 = CloseupNurse.Find(st, n); if (t0 == null) throw new Exception("ストレッチャーの部品が無い: " + n); return t0; };
                string[] casN = { "FL", "FR", "BL", "BR" };
                var cas = new Transform[4]; var cw = new Transform[4];
                for (int i = 0; i < 4; i++) { cas[i] = SF("Caster_" + casN[i]); cw[i] = SF("CasterWheel_" + casN[i]); }
                st.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                var casRest = new Quaternion[4]; var cwRest = new Quaternion[4]; var axC = new Vector3[4]; var axW = new Vector3[4]; var stem0 = new Vector3[4]; var hub0 = new Vector3[4];
                for (int i = 0; i < 4; i++)
                {
                    casRest[i] = cas[i].localRotation; cwRest[i] = cw[i].localRotation;
                    axC[i] = cas[i].parent.InverseTransformDirection(Vector3.up); axW[i] = cw[i].parent.InverseTransformDirection(Vector3.right);
                    stem0[i] = cas[i].position; hub0[i] = cw[i].position;
                }
                var stMF = new List<MeshFilter>(st.GetComponentsInChildren<MeshFilter>(true));
                var stCol = new Dictionary<Collider, string>();
                foreach (var mf in stMF) { var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerSt; stCol[mc] = mf.name; }
                var stVerts = new List<Vector3>(); var stPart = new List<string>();
                foreach (var mf in stMF) foreach (var v in mf.sharedMesh.vertices) { stVerts.Add(mf.transform.TransformPoint(v)); stPart.Add(mf.name); }
                var stMin = Vector3.one * 9f; var stMax = -Vector3.one * 9f;
                foreach (var p in stVerts) { stMin = Vector3.Min(stMin, p); stMax = Vector3.Max(stMax, p); }
                log.AppendLine(string.Format(IC, "ストレッチャー：頂点 {0}・範囲 {1}〜{2}", stVerts.Count, stMin.ToString("0.000"), stMax.ToString("0.000")));

                // 看護師の体の当たり（焼いた形の MeshCollider）：大城さん LayerNurse・寺島さん LayerTera
                Func<NurseRig, int, List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>> mkCols = (g, layer) =>
                {
                    var root = new GameObject("Col_" + g.name); root.layer = layer;
                    var l = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                    foreach (var smr in g.parts)
                    {
                        var go = new GameObject(smr.name + "_Col"); go.layer = layer; go.transform.SetParent(root.transform, false);
                        var mc = go.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                        l.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                    }
                    return l;
                };
                var colsO = mkCols(O_, LayerNurse); var colsT = mkCols(T_, LayerTera);

                // ---- 画面の絵
                var faceR = dir.face.GetComponent<Renderer>();
                var faceAlb = new Dictionary<string, Texture2D>(); var faceEmi = new Dictionary<string, Texture2D>();
                foreach (var fk in new[] { "closed", "small", "large", "happy" })
                {
                    faceAlb[fk] = PrepTex(TexDir + "/face218_" + fk + "_albedo.png"); faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png");
                }
                faceAlb["happy_closed"] = faceAlb["happy"]; faceEmi["happy_closed"] = faceEmi["happy"];
                foreach (var mk in new[] { "small", "mid", "large" }) { faceAlb["happy_" + mk] = PrepTex(TexDir + "/face224_happy_" + mk + "_albedo.png"); faceEmi["happy_" + mk] = PrepTex(TexDir + "/face224_happy_" + mk + "_emission.png"); }
                var scrTex = new Dictionary<string, Texture2D> { { "wait", ScreenTex(TexDir + "/c235_wait_band.png") }, { "back", ScreenTex(TexDir + "/c270_back_band.png") } };

                int fps = js["fps"].I(30), W = js["width"].I(1920), H = js["height"].I(1080), SS = js["supersample"].I(2);
                int iters = js["nurse"]["ik_iters"].I(3);
                float dt = 1f / fps;

                dir2.BeginShot(shotName + "__tera");
                anT.Rebind();
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c270"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var robotKeys = C["robot"]; var stKeys = C["stretcher"]; var stV = C["stretcher_v"];
                var scrKeys = C["screen"];
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var teraMouth = C["tera_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var bar = C["bar"]; float barY = bar["y"].F(), barZ = -bar["z_behind_root"].F(), barR = bar["r"].F(), barHalf = bar["x_half"].F();
                var railJ = C["rail"]; float railX = railJ["x"].F(), railY = railJ["y"].F(), railR = railJ["r"].F();
                var alc = C["alcove"]; float alcZ0 = alc["z0"].F(), alcZ1 = alc["z1"].F();
                var evJ = C["events"];
                float detT = evJ["detect"].F(), inStopT = evJ["in_stop"].F(), exitT = evJ["exit"].F();
                int vFrom0 = Mathf.RoundToInt(C["video_from"].F(0f) * 30f);

                dir.Apply(0f, dt);
                var rs = MeasureRobot(dir);
                log.AppendLine(string.Format(IC, "ハコブくんの外形（根から）: 幅 x {0:0.000}〜{1:0.000}・奥行 z {2:0.000}〜{3:0.000}・高さ {4:0.000} m", rs.minX, rs.maxX, rs.minZ, rs.maxZ, rs.top));

                // 確かめ
                var cats = new[] { "ストレッチャー", "大城さん", "寺島さん" };
                var gapMin = new Dictionary<string, float>(); var gapMinT = new Dictionary<string, float>(); var gapMinWhere = new Dictionary<string, string>();
                foreach (var c in cats) { gapMin[c] = float.MaxValue; gapMinT[c] = -1f; gapMinWhere[c] = ""; }
                int hitRG = 0, hitRS = 0, hitSS = 0, hitOS = 0, hitTS = 0, hitOSt = 0, hitTSt = 0, hitOT = 0, hitBar = 0, hitRail = 0;
                string hitRSW = "", hitSSW = "", hitOSW = "", hitTSW = "", hitOStW = "", hitTStW = "", hitOTW = "", hitBarW = "", hitRailW = "";
                float robotRailMin = float.MaxValue, stSolidMin = float.MaxValue, oSolidMin = float.MaxValue, tSolidMin = float.MaxValue;
                float palmBarMin = float.MaxValue, palmBarMax = float.MinValue, palmRailMin = float.MaxValue, palmRailMax = float.MinValue, palmErrO = 0f, palmErrT = 0f;
                float handBarMin = float.MaxValue, handRailMin = float.MaxValue;
                float wheelSlip = 0f, casYawMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, rollErr = 0f;
                var cwAng = new float[4]; var casYaw = new float[4]; var cAx = new Vector3[4]; bool haveSt = false;
                float protrudeMax = -9f, protrudeT = -1f; int alcoveFrames = 0; float robotXMaxInAlc = -9f;
                float detGapUnity = float.NaN, detGapUnityT = -1f; bool seenU = false;
                float stVmin = float.MaxValue, stVmax = 0f;
                string prevScr = ""; var scrChanges = new List<string>();
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,mode,screen,st_z,st_v,gap_m,gap_st,gap_o,gap_t,front_gap_m,rail_gap_m,robot_maxx,palm_bar_l,palm_bar_r,palm_rail_t,o_head_yaw,t_head_yaw,nurse_mouth,tera_mouth,o_z,t_z\n");
                var topCsv = new StringBuilder("frame,t,st_x,st_z,st_px,st_py,robot_x,robot_z,robot_px,robot_py,st_in,robot_in\n");
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in O_.bones) bonesCsv.Append(",o_" + hb + "_x,o_" + hb + "_y,o_" + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,who,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,st_z,dist,caster_yaw_fl,caster_yaw_fr,caster_yaw_bl,caster_yaw_br,wheel_deg_fl,wheel_deg_fr,wheel_deg_bl,wheel_deg_br,tire_min_y,slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c270Until", "1e9"), IC)) * fps);
                nFrames = Mathf.Min(nFrames, robotKeys.Count);
                string fdirM = Path.Combine(outDir, "frames", shotName), fdirT = Path.Combine(outDir, "frames", shotName + "_top");
                bool vMain = frames && views.Contains("main"), vTop = frames && views.Contains("top");
                if (vMain) Directory.CreateDirectory(fdirM);
                if (vTop) { Directory.CreateDirectory(fdirT); Directory.CreateDirectory(fdirT + "_mask"); Directory.CreateDirectory(fdirT + "_obj"); }

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    if (f > 0 && f % 150 == 0) GC.Collect();
                    // ---------- ハコブくん（台本の値）
                    var rk = robotKeys[f];
                    float rx = rk[0].F(), rz = rk[1].F(), ryaw = rk[2].F(), rv = rk[3].F(); string mode = rk[4].S();
                    // ---------- 看護師（寺島さんを先に。大城さんの Apply がハコブくん・画面を決め直す）
                    dir2.Apply(t, dt);
                    int tml = f < teraMouth.Count ? teraMouth[f].I() : 0;
                    if (tml > 0) teraN.mouth = "talk";
                    curMouthScaleT = tml > 0 ? nmScale[tml].F() : 1f;
                    teraN.Step(f == 0 ? 0f : dt, iters);
                    dir.Apply(t, dt);
                    dir.robot.position = O + new Vector3(rx, 0f, rz);
                    dir.robot.rotation = Quaternion.Euler(0f, ryaw, 0f);
                    int nml = f < nurseMouth.Count ? nurseMouth[f].I() : 0;
                    if (nml > 0) dir.nurse.mouth = "talk";
                    curMouthScale = nml > 0 ? nmScale[nml].F() : 1f;
                    dir.nurse.Step(f == 0 ? 0f : dt, iters);
                    Transform nr = dir.nurse.transform;

                    // ---------- ストレッチャー：台本の根（向き 180°）・車輪
                    var sk = stKeys[Mathf.Min(f, stKeys.Count - 1)];
                    st.SetPositionAndRotation(O + new Vector3(sk[0].F(), 0f, sk[1].F()), Quaternion.Euler(0f, 180f, 0f));
                    float svNow = stV[Mathf.Min(f, stV.Count - 1)].F(); if (f > 0) { stVmin = Mathf.Min(stVmin, svNow); stVmax = Mathf.Max(stVmax, svNow); }
                    {
                        float slipNow = 0f, tmn = float.MaxValue;
                        for (int i = 0; i < 4; i++)
                        {
                            Vector3 s0 = st.TransformPoint(stem0[i]); s0.y = 0f;
                            float trail = new Vector2(hub0[i].x - stem0[i].x, hub0[i].z - stem0[i].z).magnitude;
                            if (!haveSt) { cAx[i] = st.TransformPoint(new Vector3(hub0[i].x, 0f, hub0[i].z)); cAx[i].y = 0f; }
                            Vector3 d = cAx[i] - s0; d.y = 0f;
                            Vector3 axN = s0 + (d.sqrMagnitude > 1e-12f ? d.normalized : -st.forward) * trail;
                            Vector3 move = axN - cAx[i]; move.y = 0f;
                            Vector3 fwdW = -(axN - s0).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            slipNow = Mathf.Max(slipNow, Mathf.Abs(slip));
                            casYaw[i] = Mathf.DeltaAngle(st.eulerAngles.y, Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg);
                            casYawMax = Mathf.Max(casYawMax, Mathf.Abs(casYaw[i]));
                            cAx[i] = axN;
                            cwAng[i] += roll / 0.1f * Mathf.Rad2Deg;
                            cas[i].localRotation = Quaternion.AngleAxis(casYaw[i], axC[i]) * casRest[i];
                            cw[i].localRotation = Quaternion.AngleAxis(cwAng[i], axW[i]) * cwRest[i];
                        }
                        for (int i = 0; i < 4; i++) foreach (var v in cw[i].GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, cw[i].TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); wheelSlip = Mathf.Max(wheelSlip, slipNow);
                        float dist = (stKeys[0][1].F() - sk[1].F());
                        rollErr = Mathf.Max(rollErr, Mathf.Abs(cwAng[0] * Mathf.Deg2Rad * 0.1f - dist));
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(sk[1].F()) + "," + F(dist) + "," + F(casYaw[0], "0.00") + "," + F(casYaw[1], "0.00") + "," + F(casYaw[2], "0.00") + "," + F(casYaw[3], "0.00") + "," +
                                         F(cwAng[0], "0.00") + "," + F(cwAng[1], "0.00") + "," + F(cwAng[2], "0.00") + "," + F(cwAng[3], "0.00") + "," + F(tmn, "0.00000") + "," + F(slipNow, "0.00000"));
                        haveSt = true;
                    }

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    string skey = "face"; for (int k = 0; k < scrKeys.Count; k++) if (scrKeys[k][0].F() <= t + 1e-4f) skey = scrKeys[k][1].S();
                    bool bandNow = scrTex.ContainsKey(skey), happyNow = skey == "happy";
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", scrTex[skey]); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy_" + rmo : rmo != "mid" ? rmo : "";
                    { var mpf = new MaterialPropertyBlock(); if (fk != "") { mpf.SetTexture("_MainTex", faceAlb[fk]); mpf.SetTexture("_EmissionMap", faceEmi[fk]); } faceR.SetPropertyBlock(mpf); }
                    string scrNow = (bandNow ? "帯" + skey : "") + (happyNow ? "目まで笑う顔" : "基本");
                    if (scrNow != prevScr) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr) + " → " + scrNow);
                    prevScr = scrNow;

                    // 区切って撮る時（-c270From）：範囲より前のコマは動き（看護師・ストレッチャー・車輪）だけ進め、確かめは飛ばす（確かめの値は区切らずに回した回のものを使う）
                    if (frames && t < fromT - 1e-4f) continue;
                    // ---------- 当たりの形を焼く
                    foreach (var l in new[] { colsO, colsT })
                        foreach (var kv in l)
                        {
                            var cm = kv.Value.sharedMesh; kv.Key.BakeMesh(cm, true);
                            kv.Value.sharedMesh = null; kv.Value.sharedMesh = cm;
                            kv.Value.transform.SetPositionAndRotation(kv.Key.transform.position, kv.Key.transform.rotation);
                        }
                    Physics.SyncTransforms();
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix, toS = st.worldToLocalMatrix;
                    var gapNow = new Dictionary<string, float>(); foreach (var c in cats) gapNow[c] = float.MaxValue;
                    string gapWhereNow = ""; float nearZ = float.MaxValue;
                    Action<Vector3, string, string> seeVert = (w, cat, what) =>
                    {
                        nearZ = Mathf.Min(nearZ, w.z - O.z);
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        if (lr.x < rs.minX - 1.6f || lr.x > rs.maxX + 1.6f || lr.z < rs.minZ - 1.6f || lr.z > rs.maxZ + 1.6f) return;
                        float d = RobotDist(rs, lr, Mathf.Min(gapNow[cat], 1.5f));
                        if (d < gapNow[cat]) { gapNow[cat] = d; if (d < gapMin[cat]) { gapMin[cat] = d; gapMinT[cat] = t; gapMinWhere[cat] = what; } }
                    };
                    // ストレッチャーの頂点：見る・壁
                    bool ssHit = false;
                    {
                        Matrix4x4 sw = st.localToWorldMatrix;
                        for (int k = 0; k < stVerts.Count; k++)
                        {
                            Vector3 w = sw.MultiplyPoint3x4(stVerts[k]);
                            seeVert(w, "ストレッチャー", stPart[k]);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                if (InBox(w, s.min, s.max)) { ssHit = true; if (hitSSW == "") hitSSW = F(t, "0.000") + " 秒 " + stPart[k] + "→" + s.name; }
                                stSolidMin = Mathf.Min(stSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    // 看護師の頂点：見る・壁・ストレッチャー（手は押す手の棒／柵のほかに当たらない）・大城さんと寺島さん
                    bool osHit = false, tsHit = false, ostHit = false, tstHit = false, otHit = false, barHit = false, railHit = false;
                    foreach (var g in new[] { O_, T_ })
                    {
                        bool isO = g == O_;
                        for (int pi = 0; pi < g.parts.Count; pi++)
                        {
                            var smr = g.parts[pi];
                            smr.BakeMesh(baked, true);
                            Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                            var vs = baked.vertices; var cat = g.partCat[pi];
                            for (int i = 0; i < vs.Length; i += isO ? 1 : 1)
                            {
                                Vector3 w = m.MultiplyPoint3x4(vs[i]);
                                seeVert(w, g.name, smr.name);
                                foreach (var s in solids)
                                {
                                    if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                    float dd = PointBoxDist(w, s.min, s.max);
                                    if (isO) oSolidMin = Mathf.Min(oSolidMin, dd); else tSolidMin = Mathf.Min(tSolidMin, dd);
                                    if (InBox(w, s.min, s.max)) { if (isO) { osHit = true; if (hitOSW == "") hitOSW = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; } else { tsHit = true; if (hitTSW == "") hitTSW = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; } }
                                }
                                if (!isO && Physics.CheckSphere(w, 0.003f, 1 << LayerNurse)) { otHit = true; if (hitOTW == "") hitOTW = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→大城さん"; }
                                Vector3 lc = toS.MultiplyPoint3x4(w);
                                if (lc.x < stMin.x - 0.05f || lc.x > stMax.x + 0.05f || lc.z < stMin.z - 0.05f || lc.z > stMax.z + 0.05f || lc.y > stMax.y + 0.05f) continue;
                                bool hand = cat[i] != "";
                                if (hand && isO)
                                {
                                    // 押す手の棒（根から x ±barHalf・y barY・z barZ）：筒の中に入らない
                                    if (Mathf.Abs(lc.x) <= barHalf + 0.02f) { float dg = new Vector2(lc.y - barY, lc.z - barZ).magnitude - barR; handBarMin = Mathf.Min(handBarMin, dg); if (dg < -0.001f) { barHit = true; if (hitBarW == "") hitBarW = F(t, "0.000") + " 秒 " + cat[i] + " 棒の中 " + F(dg); } }
                                    foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerSt))
                                        if (!(stCol[col] == "ST_Frame" && lc.y > 0.9f && lc.z < -0.95f)) { ostHit = true; if (hitOStW == "") hitOStW = F(t, "0.000") + " 秒 " + cat[i] + "→" + stCol[col]; }
                                }
                                else if (hand && !isO)
                                {
                                    // 柵（Rail_R：根から x +railX・y railY・z −0.63〜0.63 の上の棒）
                                    if (Mathf.Abs(lc.z) <= 0.63f) { float dg = new Vector2(lc.x - railX, lc.y - railY).magnitude - railR; handRailMin = Mathf.Min(handRailMin, dg); if (dg < -0.001f) { railHit = true; if (hitRailW == "") hitRailW = F(t, "0.000") + " 秒 " + cat[i] + " 柵の中 " + F(dg); } }
                                    foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerSt))
                                        if (stCol[col] != "Rail_R") { tstHit = true; if (hitTStW == "") hitTStW = F(t, "0.000") + " 秒 " + cat[i] + "→" + stCol[col]; }
                                }
                                else
                                {
                                    var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerSt);
                                    if (cols.Length > 0) { if (isO) { ostHit = true; if (hitOStW == "") hitOStW = F(t, "0.000") + " 秒 " + smr.name + "→" + stCol[cols[0]] + " " + lc.ToString("0.000"); } else { tstHit = true; if (hitTStW == "") hitTStW = F(t, "0.000") + " 秒 " + smr.name + "→" + stCol[cols[0]] + " " + lc.ToString("0.000"); } }
                                }
                            }
                        }
                    }
                    // ストレッチャーの頂点が看護師の体の中（押す手の棒・柵の上の棒は手でさわる所なので除く）
                    {
                        Matrix4x4 sw = st.localToWorldMatrix;
                        for (int k = 0; k < stVerts.Count; k++)
                        {
                            Vector3 lp = stVerts[k];
                            Vector3 w = sw.MultiplyPoint3x4(lp);
                            bool barV = stPart[k] == "ST_Frame" && lp.y > 0.9f && lp.z < -0.95f;
                            bool railV = stPart[k] == "Rail_R" && lp.y > 0.95f;
                            if (!barV && Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ostHit = true; if (hitOStW == "") hitOStW = F(t, "0.000") + " 秒 ストレッチャー " + stPart[k] + " が大城さんの体に"; }
                            if (!railV && Physics.CheckSphere(w, 0.002f, 1 << LayerTera)) { tstHit = true; if (hitTStW == "") hitTStW = F(t, "0.000") + " 秒 ストレッチャー " + stPart[k] + " が寺島さんの体に"; }
                        }
                    }
                    float gapAll = Mathf.Min(gapNow["ストレッチャー"], Mathf.Min(gapNow["大城さん"], gapNow["寺島さん"]));
                    if (gapAll <= 0f) hitRG++;
                    if (ssHit) hitSS++; if (osHit) hitOS++; if (tsHit) hitTS++; if (ostHit) hitOSt++; if (tstHit) hitTSt++; if (otHit) hitOT++; if (barHit) hitBar++; if (railHit) hitRail++;
                    float frontGap = nearZ - (rz + rs.maxZ);
                    if (!seenU && f > 0 && frontGap < 6.0f) { seenU = true; detGapUnity = frontGap; detGapUnityT = t; }

                    // ハコブくんと箱（壁・手すり・扉）・くぼみの中で廊下の側へ出ている分
                    bool rsHit = false; float railGapNow = float.MaxValue, rMaxX = float.MinValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        rMaxX = Mathf.Max(rMaxX, w.x - O.x);
                        foreach (var s in solids)
                        {
                            if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                            if (InBox(w, s.min, s.max)) { rsHit = true; if (hitRSW == "") hitRSW = F(t, "0.000") + " 秒 →" + s.name; }
                            railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (mode == "wait") { alcoveFrames++; float pr = rMaxX - (-0.84f); if (pr > protrudeMax) { protrudeMax = pr; protrudeT = t; } robotXMaxInAlc = Mathf.Max(robotXMaxInAlc, rMaxX); }

                    // 手と棒・柵
                    float pbL = float.NaN, pbR = float.NaN, prT = float.NaN;
                    for (int s = 0; s < 2; s++)
                    {
                        Vector3 pc = toS.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float d = new Vector2(pc.y - barY, pc.z - barZ).magnitude - barR;
                        if (s == 0) pbL = d; else pbR = d;
                        palmBarMin = Mathf.Min(palmBarMin, d); palmBarMax = Mathf.Max(palmBarMax, d);
                        palmErrO = Mathf.Max(palmErrO, Vector3.Distance(dir.nurse.PalmCenter(s), dir.nurse.hands[s].palmTarget));
                    }
                    {
                        Vector3 pc = toS.MultiplyPoint3x4(teraN.PalmCenter(0));
                        prT = new Vector2(pc.x - railX, pc.y - railY).magnitude - railR;
                        palmRailMin = Mathf.Min(palmRailMin, prT); palmRailMax = Mathf.Max(palmRailMax, prT);
                        palmErrT = Mathf.Max(palmErrT, Vector3.Distance(teraN.PalmCenter(0), teraN.hands[0].palmTarget));
                    }

                    // 骨：1 コマの動き（根の動きを除く）・肘が肩より上にならない・足
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    foreach (var g in new[] { O_, T_ })
                    {
                        Vector3 rootNow = g.n.transform.position;
                        for (int b = 0; b < g.bones.Count; b++)
                        {
                            Vector3 p = g.an.GetBoneTransform(g.bones[b]).position;
                            if (g == O_) bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                            if (g.havePrev && f > vFrom0)     // 動画の始め（video_from）より前の、はじめの形が落ち着くコマは数えない
                            {
                                float dw = Vector3.Distance(p, g.prevBones[b]);
                                float drl = ((p - g.prevBones[b]) - (rootNow - g.prevRoot)).magnitude;
                                if (dw > g.jumpW) { g.jumpW = dw; g.jumpWT = t; g.jumpWB = g.bones[b].ToString(); }
                                if (drl > g.jumpR) { g.jumpR = drl; g.jumpRT = t; g.jumpRB = g.bones[b].ToString(); }
                            }
                            g.prevBones[b] = p;
                        }
                        g.prevRoot = rootNow; g.havePrev = true;
                        foreach (var sd in new[] { new[] { HumanBodyBones.LeftUpperArm, HumanBodyBones.LeftLowerArm }, new[] { HumanBodyBones.RightUpperArm, HumanBodyBones.RightLowerArm } })
                        {
                            float over = g.an.GetBoneTransform(sd[1]).position.y - g.an.GetBoneTransform(sd[0]).position.y;
                            if (over > g.elbowOver) { g.elbowOver = over; g.elbowOverT = t; g.elbowOverSide = sd[1].ToString(); }
                        }
                        // 足（237 と同じ数え方）
                        var dd2 = g == O_ ? dir : dir2;
                        bool inWalk = dd2.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        g.shoe.BakeMesh(g.shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(g.shoe.transform.position, g.shoe.transform.rotation, Vector3.one);
                        Vector3 lfp = g.an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = g.an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = g.shoeMesh.vertices;
                        if (g.shoePrev == null || g.shoePrev.Length != sv.Length) { g.shoePrev = new Vector3[sv.Length]; g.shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != g.prevInWalk; g.prevInWalk = inWalk;
                        float slideNow = 0f;
                        for (int i = 0; i < sv.Length; i++)
                        {
                            Vector3 w = sm.MultiplyPoint3x4(sv[i]);
                            if ((w - lfp).sqrMagnitude < (w - rfp).sqrMagnitude) lMin = Mathf.Min(lMin, w.y); else rMin = Mathf.Min(rMin, w.y);
                            bool on = w.y <= 0.01f;
                            if (on && (!g.shoeOn[i] || winChange)) g.shoePrev[i] = w;
                            float acc = on ? new Vector2(w.x - g.shoePrev[i].x, w.z - g.shoePrev[i].z).magnitude : 0f;
                            g.shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, acc);
                        }
                        if (inWalk)
                        {
                            g.walkFrames++;
                            if (slideNow > g.slideMax) { g.slideMax = slideNow; g.slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > g.sinkMax) { g.sinkMax = -low; g.sinkMaxT = t; }
                            if (low > g.floatMax) { g.floatMax = low; g.floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (g == O_ ? "o" : "t") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }
                    bonesCsv.AppendLine();

                    string camName = CutAt(shot, t);
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + mode + "," + scrNow + "," +
                                   F(sk[1].F()) + "," + F(svNow) + "," + F(gapAll) + "," + F(gapNow["ストレッチャー"]) + "," + F(gapNow["大城さん"]) + "," + F(gapNow["寺島さん"]) + "," + F(frontGap) + "," + F(railGapNow) + "," + F(rMaxX) + "," +
                                   F(pbL) + "," + F(pbR) + "," + F(prT) + "," + F(dir.nurse.headYawDeg, "0.00") + "," + F(teraN.headYawDeg, "0.00") + "," + nml + "," + tml + "," + F(nr.position.z - O.z) + "," + F(teraN.transform.position.z - O.z));

                    // ---------- 真上の画面の位置（ストレッチャーの根・ハコブくんの根）
                    {
                        SetTop(dir.cam, topJs, O);
                        Func<Vector3, Vector2> px = w => { Vector3 vp = dir.cam.WorldToViewportPoint(w); return new Vector2(vp.x * W, (1f - vp.y) * H); };
                        Func<Vector3, bool> inV = w => { Vector3 vp = dir.cam.WorldToViewportPoint(w); return vp.x >= 0f && vp.x <= 1f && vp.y >= 0f && vp.y <= 1f; };
                        Vector3 sp = st.position; sp.y = 0f; Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(sp), pr = px(rRoot);
                        int sIn = 0; foreach (var c4 in new[] { new Vector3(-0.37f, 0f, -1.06f), new Vector3(0.37f, 0f, -1.06f), new Vector3(-0.37f, 0f, 1.0f), new Vector3(0.37f, 0f, 1.0f) }) if (inV(st.TransformPoint(c4))) sIn++;
                        int rIn = 0; foreach (var c4 in new[] { new Vector3(rs.minX, 0f, rs.minZ), new Vector3(rs.maxX, 0f, rs.minZ), new Vector3(rs.minX, 0f, rs.maxZ), new Vector3(rs.maxX, 0f, rs.maxZ) }) if (inV(dir.robot.TransformPoint(c4))) rIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(sp.x - O.x, "0.00000") + "," + F(sp.z - O.z, "0.00000") + "," + F(pa.x, "0.000") + "," + F(pa.y, "0.000") + "," +
                                          F(rRoot.x - O.x, "0.00000") + "," + F(rRoot.z - O.z, "0.00000") + "," + F(pr.x, "0.000") + "," + F(pr.y, "0.000") + "," + (sIn == 4 ? 2 : sIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            var cj = new StringBuilder("{\n");
                            cj.AppendLine(string.Format(IC, "  \"center_x\": {0}, \"center_z\": {1}, \"height\": {2}, \"ortho_size\": {3}, \"aspect\": {4:0.000000}, \"orthographic\": {5},",
                                topJs["center_x"].F(), topJs["center_z"].F(), topJs["height"].F(), topJs["ortho_size"].F(), dir.cam.aspect, dir.cam.orthographic ? "true" : "false"));
                            var p00 = px(O); var p10 = px(O + Vector3.right); var p01 = px(O + Vector3.forward);
                            cj.AppendLine(string.Format(IC, "  \"px_origin\": [{0:0.0000}, {1:0.0000}], \"px_per_x\": [{2:0.0000}, {3:0.0000}], \"px_per_z\": [{4:0.0000}, {5:0.0000}]",
                                p00.x, p00.y, p10.x - p00.x, p10.y - p00.y, p01.x - p00.x, p01.y - p00.y));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top270_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && inRange)
                    {
                        syncProxies(); scaleMouth(); scaleMouthT();
                        if (vMain) { SetCam(dir.cam, shot["cameras"][camName], O, dir); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirM, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            SetTop(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f)));
                            var body = BodyRenderers(new[] { dir.robot, st, proxyRoot, dir.nurse.transform, proxyRootT, teraN.transform });
                            if (!log.ToString().Contains("体の型に入れた部品")) LogRenderers(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // もの別の型：赤＝ハコブくん・緑＝ストレッチャーと大城さんと寺島さん（2 人とも手をストレッチャーにのせたままなので 1 つのものとして埋める。make270.py）
                            var grp = new List<Renderer>[2]; for (int g = 0; g < 2; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[rd.transform.IsChildOf(dir.robot) ? 0 : 1].Add(rd);
                            var obj = new Texture2D(W, H, TextureFormat.RGBA32, false);
                            var pxs = new Color32[W * H];
                            for (int i = 0; i < pxs.Length; i++) pxs[i].a = 255;
                            for (int g = 0; g < 2; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < pxs.Length; i++) { if (g == 0) pxs[i].r = mp[i].r; else pxs[i].g = mp[i].r; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(pxs); obj.Apply();
                            SavePng(obj, Path.Combine(fdirT + "_obj", string.Format("f_{0:00000}.png", f)));
                        }
                    }
                    for (int s = 0; stillsOn && s < (stills != null ? stills.Count : 0); s++)
                    {
                        if (Mathf.RoundToInt(stills[s][0].F() * fps) != f) continue;
                        syncProxies(); scaleMouth(); scaleMouthT();
                        if (stills[s][1].S() == "top") SetTop(dir.cam, topJs, O); else SetCam(dir.cam, shot["cameras"][stills[s][1].S()], O, dir);
                        string sn = stills[s][2].S();
                        string sd = Path.Combine(outDir, sn.StartsWith("chk_") ? "stills_check" : "stills"); Directory.CreateDirectory(sd);
                        SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(sd, shotName + "_" + sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames270.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top270.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones270.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet270.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc270.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName + "（" + nFrames + " コマ）");
                tab.AppendLine(string.Format(IC, "見つけた（Unity の頂点で測った前の端どうし）\t{0:0.000} 秒・{1:0.000} m（台本の見つけた時刻 {2:0.000}）", detGapUnityT, detGapUnity, detT));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと物 {0}・ハコブくんと壁/手すり/扉 {1}（{2}）・ストレッチャーと壁 {3}（{4}）・大城さんと壁 {5}（{6}）・寺島さんと壁 {7}（{8}）",
                                              hitRG, hitRS, hitRSW, hitSS, hitSSW, hitOS, hitOSW, hitTS, hitTSW));
                tab.AppendLine(string.Format(IC, "当たったコマ（看護師）\t大城さんとストレッチャー {0}（{1}）・寺島さんとストレッチャー {2}（{3}）・寺島さんと大城さん {4}（{5}）・手が押す手の棒の中 {6}（{7}）・手が柵の中 {8}（{9}）",
                                              hitOSt, hitOStW, hitTSt, hitTStW, hitOT, hitOTW, hitBar, hitBarW, hitRail, hitRailW));
                foreach (var c in cats) tab.AppendLine(string.Format(IC, "ハコブくんと{0}の一番近い距離\t{1:0.000} m（{2:0.000} 秒・{3}）", c, gapMin[c], gapMinT[c], gapMinWhere[c]));
                tab.AppendLine(string.Format(IC, "壁・手すりとのすき間\tハコブくん {0:0.000} m・ストレッチャー {1:0.000} m・大城さん {2:0.000} m・寺島さん {3:0.000} m", robotRailMin, stSolidMin, oSolidMin, tSolidMin));
                tab.AppendLine(string.Format(IC, "くぼみの中で止まっている間（{0} コマ）\tハコブくんの一番 +x の所 x {1:0.0000}（手すりの内の面 −0.84 から廊下の側へ出ている分 {2:0.0000} m・負は出ていない・{3:0.000} 秒）", alcoveFrames, robotXMaxInAlc, protrudeMax, protrudeT));
                tab.AppendLine(string.Format(IC, "大城さんの手と押す手の棒\t手のひらの中心と棒の面 {0:0.0000}〜{1:0.0000} m・的とのずれの最大 {2:0.0000} m・手の頂点と棒の面の一番近い {3:0.0000} m", palmBarMin, palmBarMax, palmErrO, handBarMin));
                tab.AppendLine(string.Format(IC, "寺島さんの手と柵\t手のひらの中心と柵の面 {0:0.0000}〜{1:0.0000} m・的とのずれの最大 {2:0.0000} m・手の頂点と柵の面の一番近い {3:0.0000} m", palmRailMin, palmRailMax, palmErrT, handRailMin));
                tab.AppendLine(string.Format(IC, "ストレッチャー\t車輪の横すべりの最大 {0:0.00000} m/コマ・車輪の向きの最大 {1:0.00}°・車輪の下 {2:0.00000}〜{3:0.00000} m・回った角度と進んだ長さのずれ {4:0.00000} m・速さ {5:0.000}〜{6:0.000} m/秒",
                                              wheelSlip, casYawMax, tireYMin, tireYMax, rollErr, stVmin, stVmax));
                foreach (var g in new[] { O_, T_ })
                {
                    tab.AppendLine(string.Format(IC, "{0}\t1 コマの骨の動き（根の動きを除く）{1:0.00} cm（{2}・{3:0.000} 秒）・世界（参考）{4:0.00} cm（{5}・{6:0.000}）・肘と肩の高さの差の最大 {7:0.000} m（{8}・{9:0.000} 秒。正は肘が上）",
                                                  g.name, g.jumpR * 100f, g.jumpRB, g.jumpRT, g.jumpW * 100f, g.jumpWB, g.jumpWT, g.elbowOver, g.elbowOverSide, g.elbowOverT));
                    tab.AppendLine(string.Format(IC, "{0}の足\t歩く所 {1} コマ・すべり最大 {2:0.00} cm（{3:0.000} 秒）・沈み {4:0.00} cm・両足とも浮いた {5:0.00} cm", g.name, g.walkFrames, g.slideMax * 100f, g.slideMaxT, g.sinkMax * 100f, g.floatMax * 100f));
                }
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check270.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events270.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C270] done\n" + log + "\n" + tab);
        }

        static string HandCat(Transform b, Dictionary<Transform, HumanBodyBones> map)
        {
            for (var t = b; t != null; t = t.parent)
            {
                HumanBodyBones hb;
                if (!map.TryGetValue(t, out hb)) continue;
                string s = hb.ToString();
                if (hb == HumanBodyBones.LeftHand || (s.StartsWith("Left") && (s.Contains("Thumb") || s.Contains("Index") || s.Contains("Middle") || s.Contains("Ring") || s.Contains("Little")))) return "左手";
                if (hb == HumanBodyBones.RightHand || (s.StartsWith("Right") && (s.Contains("Thumb") || s.Contains("Index") || s.Contains("Middle") || s.Contains("Ring") || s.Contains("Little")))) return "右手";
                return "";
            }
            return "";
        }

        static Texture2D ScreenTex(string path)
        {
            var ti = (TextureImporter)AssetImporter.GetAtPath(path);
            if (ti == null) throw new Exception("絵が無い: " + path);
            if (ti.textureCompression != TextureImporterCompression.Uncompressed || ti.maxTextureSize < 2048 || ti.npotScale != TextureImporterNPOTScale.None || !ti.alphaIsTransparency || !ti.mipmapEnabled || ti.wrapMode != TextureWrapMode.Clamp || !ti.sRGBTexture)
            {
                ti.textureCompression = TextureImporterCompression.Uncompressed; ti.maxTextureSize = 2048; ti.npotScale = TextureImporterNPOTScale.None;
                ti.alphaIsTransparency = true; ti.mipmapEnabled = true; ti.wrapMode = TextureWrapMode.Clamp; ti.sRGBTexture = true; ti.filterMode = FilterMode.Trilinear; ti.anisoLevel = 4;
                ti.SaveAndReimport();
            }
            var tx = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (tx == null) throw new Exception("絵が読めない: " + path);
            return tx;
        }

        static Texture2D PrepTex(string path)
        {
            var tx = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (tx == null) throw new Exception("絵が無い: " + path);
            return tx;
        }

        static string CutAt(JsonValue shot, float t)
        {
            var c = shot["cuts"];
            string name = c[0][1].S();
            for (int i = 0; i < c.Count; i++) if (c[i][0].F() <= t + 1e-4f) name = c[i][1].S();
            return name;
        }

        /// <summary>カメラ：pos・look は廊下の原点から。follow "robot"・"nurse" は z を足す（237 と同じ）。"robot_pose" はハコブくんの根の位置と向きから</summary>
        static void SetCam(Camera cam, JsonValue C, Vector3 O, CloseupDirector dir)
        {
            if (C == null || C.IsNull) throw new Exception("台本にカメラが無い");
            cam.orthographic = false; cam.ResetAspect();
            string fo = C["follow"].S("");
            if (fo == "robot_pose")
            {
                Transform r = dir.robot;
                cam.transform.position = r.TransformPoint(CloseupDirector.V3(C["pos"]));
                cam.transform.rotation = Quaternion.LookRotation(r.TransformPoint(CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            Vector3 add = Vector3.zero;
            if (fo == "robot") add = new Vector3(0f, 0f, dir.robot.position.z - O.z);
            else if (fo == "nurse") add = new Vector3(0f, 0f, dir.nurse.transform.position.z - O.z);
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>動かない真上のカメラ（230 と同じ正射影）。画面の上が −x・右が +z</summary>
        static void SetTop(Camera cam, JsonValue T, Vector3 O)
        {
            cam.orthographic = true;
            cam.orthographicSize = T["ortho_size"].F();
            cam.transform.position = O + new Vector3(T["center_x"].F(), T["height"].F(), T["center_z"].F());
            cam.transform.rotation = Quaternion.LookRotation(Vector3.down, Vector3.left);
            cam.nearClipPlane = 0.3f; cam.farClipPlane = T["height"].F() + 5f;
            cam.aspect = T["width_px"].F(1920f) / T["height_px"].F(1080f);
        }

        static Camera maskCam; static Material whiteMat;

        static List<Renderer> BodyRenderers(Transform[] roots)
        {
            var list = new List<Renderer>();
            foreach (var r in roots)
                foreach (var rd in r.GetComponentsInChildren<Renderer>(false))
                    if (rd.enabled && rd.gameObject.activeInHierarchy && !list.Contains(rd)) list.Add(rd);
            return list;
        }

        static void LogRenderers(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}）", r.name, r.gameObject.layer));
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
                if (r.enabled && r.gameObject.activeInHierarchy && !body.Contains(r) && r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
        }

        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam == null)
            {
                var g = new GameObject("MaskCam270"); maskCam = g.AddComponent<Camera>(); maskCam.enabled = false;
                whiteMat = new Material(Shader.Find("Unlit/Color")) { name = "Mask270" }; whiteMat.color = Color.white;
            }
            maskCam.CopyFrom(cam);
            maskCam.cullingMask = 1 << LayerMask232;
            maskCam.clearFlags = CameraClearFlags.SolidColor; maskCam.backgroundColor = Color.black;
            maskCam.allowHDR = false; maskCam.allowMSAA = false;
            var layers = new int[body.Count]; var mats = new Material[body.Count][]; var mpbs = new MaterialPropertyBlock[body.Count]; var hadMpb = new bool[body.Count];
            for (int i = 0; i < body.Count; i++)
            {
                layers[i] = body[i].gameObject.layer; mats[i] = body[i].sharedMaterials;
                hadMpb[i] = body[i].HasPropertyBlock(); if (hadMpb[i]) { mpbs[i] = new MaterialPropertyBlock(); body[i].GetPropertyBlock(mpbs[i]); body[i].SetPropertyBlock(null); }
                body[i].gameObject.layer = LayerMask232;
                var w = new Material[Mathf.Max(1, mats[i].Length)]; for (int k = 0; k < w.Length; k++) w[k] = whiteMat;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam, W, H, SS); }
            finally
            {
                for (int i = 0; i < body.Count; i++) { body[i].gameObject.layer = layers[i]; body[i].sharedMaterials = mats[i]; if (hadMpb[i]) body[i].SetPropertyBlock(mpbs[i]); }
            }
        }

        static Texture2D Shoot(Camera cam, int W, int H, int SS)
        {
            var big = RenderTexture.GetTemporary(W * SS, H * SS, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
            var small = RenderTexture.GetTemporary(W, H, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
            big.filterMode = FilterMode.Bilinear;
            cam.targetTexture = big;
            cam.Render();
            cam.targetTexture = null;
            Graphics.Blit(big, small);
            var prev = RenderTexture.active;
            RenderTexture.active = small;
            var tex = new Texture2D(W, H, TextureFormat.RGB24, false);
            tex.ReadPixels(new Rect(0, 0, W, H), 0, 0);
            tex.Apply();
            RenderTexture.active = prev;
            RenderTexture.ReleaseTemporary(big);
            RenderTexture.ReleaseTemporary(small);
            return tex;
        }

        static void SavePng(Texture2D tex, string path)
        {
            File.WriteAllBytes(path, tex.EncodeToPNG());
            UnityEngine.Object.DestroyImmediate(tex);
        }
    }
}
```


### Closeup270Stretcher.cs

```csharp
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace ServiceSim.Closeups.EditorTools
{
    /// <summary>
    /// 依頼270：空のストレッチャー（Closeups/Models_stretcher/stretcher.fbx。iCloud の hospital/people_3d/stretcher/ の写し）を読む・置く。
    ///   ・Rig なし・頂点を読める・材質は Models_stretcher/Materials/ に作り、FBX の色（Blender の linear の値）を sRGB に直す（228 の車いすと同じ）
    ///   ・根（Stretcher）は床の中心。足の側が +Z（進む向き）、押す手は頭の側（−Z）
    ///   ・動かす部品：Caster_FL/FR/BL/BR（車輪の向き・Y 軸まわり）、その子の CasterWheel_**（車輪の回転・X 軸まわり）。柵 Rail_L/R は上げたまま
    /// コマンド（読み込みと寸法・静止画）
    ///   Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup270Stretcher.Run -c270Out <出力フォルダ>
    /// </summary>
    public static class Closeup270Stretcher
    {
        public const string Dir = "Assets/ServiceSim/Closeups/Models_stretcher";
        public const string Fbx = Dir + "/stretcher.fbx";
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string V(Vector3 v) { return string.Format(IC, "({0:0.0000},{1:0.0000},{2:0.0000})", v.x, v.y, v.z); }
        static string Hex(Color c) { return "#" + ColorUtility.ToHtmlStringRGB(c); }

        /// <summary>読み込みの設定（設定が違う時だけ読み直す）。材質は Models_stretcher/Materials/</summary>
        public static void Import(StringBuilder sb)
        {
            if (!AssetDatabase.IsValidFolder(Dir + "/Materials")) AssetDatabase.CreateFolder(Dir, "Materials");
            var mi = (ModelImporter)AssetImporter.GetAtPath(Fbx);
            if (mi == null) throw new Exception("FBX が無い: " + Fbx);
            bool changed = mi.animationType != ModelImporterAnimationType.None || !mi.isReadable || mi.importAnimation || mi.materialImportMode != ModelImporterMaterialImportMode.ImportStandard;
            if (changed)
            {
                mi.animationType = ModelImporterAnimationType.None;
                mi.isReadable = true;
                mi.importAnimation = false;
                mi.materialImportMode = ModelImporterMaterialImportMode.ImportStandard;
                mi.SaveAndReimport();
            }
            sb.AppendLine("stretcher.fbx：Rig " + mi.animationType + "・読み直し " + (changed ? "した" : "しない"));
            var shader = Shader.Find("Standard");
            bool remapped = false;
            foreach (var o in AssetDatabase.LoadAllAssetsAtPath(Fbx))
            {
                var fm = o as Material;
                if (fm == null) continue;
                string mp = Dir + "/Materials/" + fm.name + ".mat";
                var nm = AssetDatabase.LoadAssetAtPath<Material>(mp);
                if (nm == null) { nm = new Material(shader); AssetDatabase.CreateAsset(nm, mp); }
                nm.shader = shader;
                Color lin = fm.color;
                nm.color = lin.gamma;
                float metal = fm.HasProperty("_Metallic") ? fm.GetFloat("_Metallic") : 0f;
                nm.SetFloat("_Metallic", metal);
                nm.SetFloat("_Glossiness", metal > 0.3f ? 0.6f : 0.2f);
                EditorUtility.SetDirty(nm);
                mi.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(Material), fm.name), nm); remapped = true;
                sb.AppendLine("  材質 " + fm.name + " " + Hex(lin) + " → " + Hex(nm.color) + "・金属 " + metal.ToString("0.00", IC));
            }
            if (remapped) mi.SaveAndReimport();
            AssetDatabase.SaveAssets();
        }

        /// <summary>設定が Import のままかを確かめるだけ（違えば止める）</summary>
        public static void CheckImport(StringBuilder sb)
        {
            var mi = (ModelImporter)AssetImporter.GetAtPath(Fbx);
            if (mi == null) throw new Exception("FBX が無い: " + Fbx);
            bool ok = mi.animationType == ModelImporterAnimationType.None && mi.isReadable && !mi.importAnimation && mi.GetExternalObjectMap().Count > 0;
            sb.AppendLine("stretcher.fbx：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・読み込みの設定のまま " + (ok ? "はい" : "いいえ"));
            if (!ok) throw new Exception("ストレッチャーの読み込みの設定が違う");
        }

        public static GameObject Spawn(string name) { return Closeup228Morita.Spawn(Fbx, name); }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c270Out", "");
            if (outDir == "") throw new Exception("-c270Out がない");
            Directory.CreateDirectory(outDir);
            var sb = new StringBuilder();
            try
            {
                Import(sb);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                Vector3 O = new Vector3(80f, 0f, 0f);
                var st = Spawn("Stretcher270");
                st.transform.SetPositionAndRotation(O, Quaternion.identity);
                sb.AppendLine("== 部品（根から）");
                foreach (Transform c in st.GetComponentsInChildren<Transform>(true))
                {
                    var r = c.GetComponent<Renderer>();
                    string info = r != null ? " 範囲 " + V(r.bounds.min - O) + "〜" + V(r.bounds.max - O) + " 材質 " + r.sharedMaterial.name : "";
                    sb.AppendLine("  " + c.name + " 位置 " + V(c.position - O) + " 回転 " + V(c.localEulerAngles) + " 右 " + V(c.right) + " 上 " + V(c.up) + " 前 " + V(c.forward) + info);
                }
                // 押す手：頭の側（z ＜ −0.9）の 0.9 m より上の頂点
                var all = new List<Vector3>(); var allPart = new List<string>();
                foreach (var mf in st.GetComponentsInChildren<MeshFilter>(true))
                    foreach (var v in mf.sharedMesh.vertices) { all.Add(mf.transform.TransformPoint(v) - O); allPart.Add(mf.name); }
                Vector3 mn = Vector3.one * 9, mx = -Vector3.one * 9;
                foreach (var p in all) { mn = Vector3.Min(mn, p); mx = Vector3.Max(mx, p); }
                sb.AppendLine("全体 " + V(mn) + "〜" + V(mx) + " 頂点 " + all.Count);
                foreach (var zr in new[] { new[] { -1.2f, -0.9f }, new[] { 0.9f, 1.2f } })
                {
                    var byPart = new Dictionary<string, Vector3[]>();
                    for (int i = 0; i < all.Count; i++)
                    {
                        var p = all[i]; if (p.z < zr[0] || p.z > zr[1] || p.y < 0.85f) continue;
                        if (!byPart.ContainsKey(allPart[i])) byPart[allPart[i]] = new[] { Vector3.one * 9, -Vector3.one * 9 };
                        byPart[allPart[i]][0] = Vector3.Min(byPart[allPart[i]][0], p); byPart[allPart[i]][1] = Vector3.Max(byPart[allPart[i]][1], p);
                    }
                    foreach (var kv in byPart) sb.AppendLine(string.Format("z {0}〜{1}・高さ 0.85 より上：{2} {3}〜{4}", zr[0], zr[1], kv.Key, V(kv.Value[0]), V(kv.Value[1])));
                }
                // 押す手の断面：x ごとの y・z の範囲（x を 0.05 m ごと）
                for (float x0 = -0.40f; x0 < 0.40f; x0 += 0.05f)
                {
                    Vector3 a = Vector3.one * 9, b = -Vector3.one * 9; int n = 0;
                    for (int i = 0; i < all.Count; i++) { var p = all[i]; if (p.z > -0.95f || p.y < 0.85f || p.x < x0 || p.x >= x0 + 0.05f) continue; a = Vector3.Min(a, p); b = Vector3.Max(b, p); n++; }
                    if (n > 0) sb.AppendLine(string.Format(IC, "  押す手 x {0:0.00}〜{1:0.00}：{2} 頂点 {3}〜{4}", x0, x0 + 0.05f, n, V(a), V(b)));
                }
                // 柵の上の端（x ごと）
                foreach (var rn in new[] { "Rail_L", "Rail_R" })
                {
                    var t = CloseupNurse.Find(st.transform, rn); if (t == null) continue;
                    var m = t.GetComponent<MeshFilter>().sharedMesh; Vector3 a = Vector3.one * 9, b = -Vector3.one * 9;
                    foreach (var v in m.vertices) { var p = t.TransformPoint(v) - O; if (p.y < 0.95f) continue; a = Vector3.Min(a, p); b = Vector3.Max(b, p); }
                    sb.AppendLine(rn + " 0.95 より上 " + V(a) + "〜" + V(b));
                    for (float z0 = -1.0f; z0 < 1.0f; z0 += 0.1f)
                    {
                        Vector3 c = Vector3.one * 9, d = -Vector3.one * 9; int n = 0;
                        foreach (var v in m.vertices) { var p = t.TransformPoint(v) - O; if (p.z < z0 || p.z >= z0 + 0.1f) continue; c = Vector3.Min(c, p); d = Vector3.Max(d, p); n++; }
                        if (n > 0) sb.AppendLine(string.Format(IC, "  {0} z {1:0.0}〜：{2} 頂点 {3}〜{4}", rn, z0, n, V(c), V(d)));
                    }
                }
                // 車輪
                foreach (var cn in new[] { "CasterWheel_FL", "CasterWheel_FR", "CasterWheel_BL", "CasterWheel_BR" })
                {
                    var t = CloseupNurse.Find(st.transform, cn); if (t == null) { sb.AppendLine(cn + " なし"); continue; }
                    float lo = 9f; foreach (var v in t.GetComponent<MeshFilter>().sharedMesh.vertices) lo = Mathf.Min(lo, t.TransformPoint(v).y);
                    sb.AppendLine(cn + " 中心 " + V(t.position - O) + " 下 " + lo.ToString("0.0000", IC));
                }
                // 静止画 2 枚
                var cam = UnityEngine.Object.FindObjectOfType<CloseupDirector>().cam;
                foreach (var v in new[] { new[] { "side", "2.6", "1.4", "0.4" }, new[] { "head", "-1.6", "1.6", "-2.6" } })
                {
                    cam.orthographic = false; cam.ResetAspect(); cam.fieldOfView = 40f;
                    cam.transform.position = O + new Vector3(float.Parse(v[1], IC), float.Parse(v[2], IC), float.Parse(v[3], IC));
                    cam.transform.LookAt(O + new Vector3(0f, 0.6f, 0f));
                    var rt = RenderTexture.GetTemporary(1600, 900, 24); cam.targetTexture = rt; cam.Render(); cam.targetTexture = null;
                    var prev = RenderTexture.active; RenderTexture.active = rt;
                    var tex = new Texture2D(1600, 900, TextureFormat.RGB24, false); tex.ReadPixels(new Rect(0, 0, 1600, 900), 0, 0); tex.Apply();
                    RenderTexture.active = prev; RenderTexture.ReleaseTemporary(rt);
                    File.WriteAllBytes(Path.Combine(outDir, "stretcher_" + v[0] + ".png"), tex.EncodeToPNG());
                }
            }
            catch (Exception e) { Debug.LogError(e); sb.AppendLine("エラー: " + e); }
            File.WriteAllText(Path.Combine(outDir, "stretcher270.txt"), sb.ToString(), new UTF8Encoding(false));
            Debug.Log("[C270S] done\n" + sb);
        }
    }
}
```


### an270.py

```python
"""依頼270：報告の表（セリフの時刻・カメラの切りかえ・待たせた秒・動けなかった秒・病院の1日の数え方 count_rules の 1〜5）
使い方: python3 an270.py <台本> <Unity の出力フォルダ（区切らずに回した回）> <場面> <hospital-unity-params.json>"""
import csv, json, sys
SC, D, SHOT, PJ = sys.argv[1:5]
S = json.load(open(SC)); sh = [s for s in S["shots"] if s["name"] == SHOT][0]; C = sh["c270"]; EV = C["events"]
P = json.load(open(PJ))["count_rules"]
V0 = C["video_from"]; vs = lambda t: t - V0
rows = list(csv.DictReader(open(D + "/frames270.csv")))
FPS = 30; DT = 1 / FPS
out = []
pr = lambda *a: out.append("".join(str(x) for x in a))
pr("■ ", SHOT, "（動画の秒＝台本の秒 − ", V0, "）")
pr("セリフ\t誰\t台本の秒\t動画の秒\t声の長さ")
L = sorted(C["lines"].items(), key=lambda kv: kv[1]["voice_on_s"])
who = {"robot": "ハコブ", "nurse": "大城", "tera": "寺島"}
prev = None
for k, l in L:
    pr(f"{l['text']}\t{who[l['who']]}\t{l['voice_on_s']:.3f}〜{l['voice_off_s']:.3f}\t{vs(l['voice_on_s']):.3f}〜{vs(l['voice_off_s']):.3f}\t{l['voice_len_s']:.3f}")
gaps = [(L[i][1]["text"], L[i + 1][1]["text"], L[i + 1][1]["voice_on_s"] - L[i][1]["voice_off_s"]) for i in range(len(L) - 1)]
for a, b, g in gaps: pr(f"セリフの間：{a} → {b}\t{g:.3f} 秒")
pr("カメラの切りかえ（台本の秒 → 動画の秒）：" + "／".join(f"{c[1]} {c[0]:.3f}→{max(0.0, vs(c[0])):.3f}" for c in sh["cuts"]))
pr("画面：" + "／".join(f"{s[1]} {s[0]:.3f}（動画 {max(0.0, vs(s[0])):.3f}）" for s in C["screen"]))
pr("できごと（台本の秒・動画の秒）：" + "・".join(f"{k} {v:.3f}（{vs(v):.3f}）" if isinstance(v, float) and k not in ("detect_gap", "detect_rz", "stop_rz", "back_turn_rz") else f"{k} {v}" for k, v in EV.items()))
# ストレッチャーを待たせた秒・速さ
sv = C["stretcher_v"]
stop_frames = sum(1 for v in sv[1:] if v < 0.004)
pr(f"ストレッチャーの速さ：最小 {min(sv[1:]):.3f}・最大 {max(sv[1:]):.3f} m/秒・止まっていたコマ {stop_frames}（{stop_frames * DT:.3f} 秒）")
if C["stretcher_stop"]: pr(f"ストレッチャーを待たせた秒（止まり終わり {C['stretcher_stop'][0]:.3f} → 動き出し {C['stretcher_stop'][1]:.3f}）\t{C['stretcher_stop'][1] - C['stretcher_stop'][0]:.3f} 秒（字は {C['wait_label'][2]:.1f} 秒）")
else: pr("ストレッチャーを待たせた秒\t0（一度も速さを落としていない）")
# ハコブくんが動けなかった秒（見つけた後、速さ 0 のコマ）
segs = []; a = None
for r in rows:
    t = float(r["t"]); v = abs(float(r["robot_v"]))
    if t < EV["detect"]: continue
    if v < 1e-4 and a is None: a = t
    if v >= 1e-4 and a is not None: segs.append((a, t)); a = None
if a is not None: segs.append((a, float(rows[-1]["t"]) + DT))
pr("ハコブくんが動けなかった（止まっていた）秒\t合計 " + f"{sum(b - a for a, b in segs):.3f} 秒（" + "・".join(f"{a:.3f}〜{b:.3f} {b - a:.3f} 秒" for a, b in segs) + "）")
# count_rules
# 1 急に止まった：走っている状態（0.6 m/秒）から sudden_stop 秒以内に止まった
st1 = []; run_t = None
for r in rows:
    t = float(r["t"]); v = abs(float(r["robot_v"]))
    if v >= 0.59: run_t = t
    if v < 1e-4 and run_t is not None: st1.append(t - run_t); run_t = None
n1 = sum(1 for d in st1 if d <= P["sudden_stop"]["value"])
pr(f"数え方 1 急に止まった（{P['sudden_stop']['value']} 秒以内）\t{n1} 件（走っている状態から止まるまで " + "・".join(f"{d:.3f}" for d in st1) + " 秒）")
# 2 ひやり：人（大城さん・寺島さん）とハコブくんの外形どうしが near_miss_m 未満
def episodes(col, th):
    n = 0; on = False; mn = 9.0
    for r in rows:
        g = float(r[col]); mn = min(mn, g)
        if g < th and not on: n += 1; on = True
        if g >= th: on = False
    return n, mn
nm = P["near_miss_m"]["value"]
n2o, m2o = episodes("gap_o", nm); n2t, m2t = episodes("gap_t", nm); n2s, m2s = episodes("gap_st", nm)
pr(f"数え方 2 ひやり（人と {nm} m 未満）\t{n2o + n2t} 件（大城さん {n2o}・最小 {m2o:.3f} m／寺島さん {n2t}・最小 {m2t:.3f} m）。参考：ストレッチャー（物）{n2s} 回・最小 {m2s:.3f} m")
# 3 人がよけさせられた：ハコブくんから yield_m 以内で人が止まるか向きを変えた（向きは 2 人とも 180°のまま。止まったのは ⑩-2 のストレッチャーを止めた所）
ym = P["yield_m"]["value"]
if C["stretcher_stop"]:
    f = int(round(C["stretcher_stop"][0] * FPS)); r = rows[f]
    go = float(r["gap_o"]); gt = float(r["gap_t"])
    # 1.5 m より遠いと Unity の値は無い：前後の z で数える（人の体の前の端 ≒ 根の前 0.15 m・ハコブくんの前の端）
    rz = float(r["robot_z"]); tz = float(r["t_z"]); oz = float(r["o_z"])
    dt_ = (tz - 0.15) - (rz + 0.382); do_ = (oz - 0.15) - (rz + 0.382)
    n3 = int(min(go, gt) < ym or min(dt_, do_) < ym)
    pr(f"数え方 3 人がよけさせられた（{ym} m 以内で止まる・向きを変える）\t{n3} 件（止まった時のハコブくんとの前後のあいだ：寺島さん {dt_:.2f} m・大城さん {do_:.2f} m。2 人とも向きは変えていない）")
else:
    pr(f"数え方 3 人がよけさせられた（{ym} m 以内）\t0 件（2 人とも止まらず・向きも変えていない）")
# 4 立ち往生
long = [b - a for a, b in segs if b - a >= P["stuck_s"]["value"]]
pr(f"数え方 4 立ち往生（{P['stuck_s']['value']} 秒以上動けず、人が動かしに行った）\t0 件（{P['stuck_s']['value']} 秒以上止まっていた区切り {len(long)}・人は動かしに行っていない）")
# 5 ストレッチャーの進む先 cross_front_m 以内をハコブくんが横切った：ハコブくんが横へ動いている（横の速さ 0.01 m/秒より大）間に、
#   ハコブくんの外形の +x の端がストレッチャーと寺島さんの通る帯（寺島さんの −x の端 〜 ストレッチャーの +x の端）に入っていて、前の端どうしが cross_front_m 以内
cf = P["cross_front_m"]["value"]; band_lo = C["tera"]["x"] - 0.25
n5 = 0; on = False; first = None; prev_x = None
for r in rows:
    x = float(r["robot_x"]); fg = float(r["front_gap_m"]); mx = float(r["robot_maxx"])
    vx = (x - prev_x) / DT if prev_x is not None else 0.0; prev_x = x
    hit = abs(vx) > 0.01 and mx > band_lo and 0.0 < fg <= cf
    if hit and not on: n5 += 1; on = True; first = first or (float(r["t"]), fg, mx)
    if not hit: on = False
pr(f"数え方 5 ストレッチャーの進む先 {cf} m 以内を横切った\t{n5} 件" + (f"（はじめ 台本 {first[0]:.3f} 秒・前の端どうし {first[1]:.2f} m・ハコブくんの +x の端 {first[2]:.3f}・帯の −x の端 {band_lo:.2f}）" if first else ""))
print("\n".join(out))
open(D + f"/an270_{SHOT}.txt", "w").write("\n".join(out) + "\n")
```


### chk270.py

```python
"""依頼270：台本のハコブくんの道の確かめ（2 次元・長方形）：廊下の外に出た角がくぼみの中か・くぼみの中で止まった時の右の端・ストレッチャーの止まった所"""
import json, sys
sys.path.insert(0, "/tmp/c270/tools")
from robot270 import corners
S = json.load(open(sys.argv[1]))
for sh in S["shots"]:
    if "__" in sh["name"]: continue
    C = sh["c270"]; A = C["alcove"]; rob = C["robot"]; st = C["stretcher"]; ev = C["events"]
    bad = 0; xmin = 9; worst = None
    for f, r in enumerate(rob):
        for cx, cz in corners(r[0], r[1], r[2]):
            xmin = min(xmin, cx)
            if cx < -0.84 and not (A["z0"] + 0.0 <= cz <= A["z1"]): bad += 1; worst = worst or (f, cx, cz)
            if cx < A["x_back"] + 0.0: bad += 1
    fi = int(round(ev["in_stop"] * 30)); r = rob[fi]
    re = max(c[0] for c in corners(r[0], r[1], r[2]))
    print(sh["name"], "廊下の外でくぼみの外の角", bad, worst, "x の最小", round(xmin, 4), "・くぼみの中で止まった時の右の端", round(re, 4), "向き", r[2], "根", r[0], r[1])
    if C["stretcher_stop"]:
        f0 = int(round(C["stretcher_stop"][0] * 30)); sz = st[f0][1]; rr = rob[f0]
        print("  ストレッチャーの止まった前の端 z", round(sz - 1.005, 3), "ハコブくんの前の端", round(rr[1] + 0.382, 3), "→ あいだ", round(sz - 1.005 - rr[1] - 0.382, 3), "・待たせた", C["wait_label"])
    # 寺島さんの外形（根 ±0.2・x TX−0.22〜）とハコブくんのすき間（おおよそ）
    T = C["tera"]; best = 9; bt = None
    for f, rr in enumerate(rob):
        tz = st[f][1] - T["ahead_m"]; cs = corners(rr[0], rr[1], rr[2])
        zmin, zmax = min(c[1] for c in cs), max(c[1] for c in cs)
        if tz - 0.15 <= zmax and tz + 0.15 >= zmin:
            g = (T["x"] - 0.22) - max(c[0] for c in cs)
            if g < best: best, bt = g, f / 30
    print("  寺島さん（おおよそ）とのすき間の最小", round(best, 3), "秒", bt)
```


### feas270.py

```python
"""依頼270：くぼみの大きさを決める試算（真上の 2 次元・ハコブくんは外形の長方形）。
⑩-1：見つけて（前の端どうし 6.0 m・0.1 秒後）くぼみへ入る→止まる→（ストレッチャーが過ぎたら）出る
⑩-2：見つけて止まる→後ろへ 0.2 m/秒でくぼみへ下がる→出る
くぼみの奥の壁 x、ハコブくんのくぼみの中の x、手すりの内の面 −0.84・壁の面 −0.90"""
import json, math, sys
sys.path.insert(0, "/tmp/c270/tools")
from robot270 import *

RAIL = -0.84; WALLF = -0.90
XB = float(sys.argv[1]) if len(sys.argv) > 1 else -1.59      # くぼみの奥の壁の面
XA = XB + R["wall_clear"] + RX1                                # くぼみの中のハコブくんの根の x（奥の壁と 0.053）
EXIT_ANG = float(sys.argv[2]) if len(sys.argv) > 2 else R["resume_angle"]
ENTER_V = float(sys.argv[3]) if len(sys.argv) > 3 else R["slow"]


def run_enter(rz=0.0):
    """見つけた所（根 z=rz・x lane・速さ 0.6）からくぼみへ入って止まる。戻り値：コマごとの (t, x, z, th, v)"""
    rx, th, rv, ra = R["lane"], 0.0, R["cruise"], 0.0
    out = []; done = False; t = 0.0
    for f in range(3000):
        vT = 0.0 if done else ENTER_V
        rv, ra = step_speed(rv, ra, vT)
        rx, th = step_lat(rx, th, XA, rv, R["lat_angle"], XA)
        if not done and abs(XA - rx) < R["lat_done"]: done = True
        rz += rv * DT; t += DT
        out.append((t, rx, rz, th, rv))
        if done and rv <= 0: break
    return out


def run_exit(rx, rz, th, ang):
    """くぼみの中（止まっている）から 0.6 m/秒へ、ふだんの位置へ戻る（229 の走り出し：角の線＋向き ang まで）"""
    rv, ra = 0.0, 0.0; out = []; t = 0.0
    for f in range(3000):
        rv, ra = step_speed(rv, ra, R["cruise"])
        rx, th = step_lat(rx, th, R["lane"], rv, ang, XA)
        rz += rv * DT; t += DT
        out.append((t, rx, rz, th, rv))
        if abs(rx - R["lane"]) < 0.002 and abs(th) < 0.01: break
    return out


def run_back(rx, rz, th, vb=0.2):
    """止まった所から後ろへ vb でくぼみへ（横は 229 の StepLat を後ろ向きに）"""
    rv, ra = 0.0, 0.0; out = []; t = 0.0; done = False
    for f in range(6000):
        rv, ra = step_speed(rv, ra, 0.0 if done else vb)
        rx, th = step_lat(rx, th, XA, rv, R["lat_angle"], XA, sgn=-1.0)
        if not done and abs(XA - rx) < R["lat_done"]: done = True
        rz -= rv * DT; t += DT
        out.append((t, rx, rz, th, rv))
        if done and rv <= 0: break
    return out


def swept(path, xlim=RAIL):
    """廊下の外（x < xlim）に出た角の z の範囲・x の最小"""
    zs = []; xmin = 9
    for (_, x, z, th, _) in path:
        for cx, cz in corners(x, z, th):
            xmin = min(xmin, cx)
            if cx < xlim: zs.append(cz)
        # 辺の途中も（左の辺の真ん中）
    return (min(zs), max(zs)) if zs else (None, None), xmin


def right_edge(x, z, th):
    return max(c[0] for c in corners(x, z, th))


en = run_enter(0.0)
t1, x1, z1, th1, _ = en[-1]
(za, zb), xmin = swept(en)
print(f"入る：{t1:.2f} 秒・前へ {z1:.3f} m・止まった x {x1:.4f} 向き {th1:.2f}° 右の端 {right_edge(x1, z1, th1):.4f}・廊下の外へ出た角の z {za:.3f}〜{zb:.3f}（見つけた時の根から）・x の最小 {xmin:.4f}（奥の壁 {XB}）")
# 右の端が -0.6 を切るまで
for (t, x, z, th, v) in en:
    if right_edge(x, z, th) < -0.60: print(f"  右の端が −0.60 を切る：{t:.2f} 秒・前へ {z:.2f} m"); break
for (t, x, z, th, v) in en:
    if right_edge(x, z, th) < -0.84: print(f"  右の端が −0.84 を切る：{t:.2f} 秒・前へ {z:.2f} m"); break
ex = run_exit(x1, z1, th1, EXIT_ANG)
(ea, eb), _ = swept(ex)
t2, x2, z2, th2, _ = ex[-1]
print(f"出る（向き {EXIT_ANG}°まで）：{t2:.2f} 秒・前へ {z2 - z1:.3f} m・廊下の外の角の z {ea:.3f}〜{eb:.3f}")
print(f"⑩-1 のくぼみ（見つけた時の根から）：{min(za, ea):.3f}〜{max(zb, eb):.3f}・長さ {max(zb, eb) - min(za, ea):.3f} m")
# ⑩-2：止まった所から下がる
bk = run_back(R["lane"], 0.0, 0.0)
(ba, bb), bxmin = swept(bk)
t3, x3, z3, th3, _ = bk[-1]
print(f"下がる：{t3:.2f} 秒・後ろへ {-z3:.3f} m・止まった x {x3:.4f} 向き {th3:.2f}° 右の端 {right_edge(x3, z3, th3):.4f}・廊下の外の角の z {ba:.3f}〜{bb:.3f}（止まった根から）x の最小 {bxmin:.4f}")
ex2 = run_exit(x3, z3, th3, EXIT_ANG)
(ca, cb), _ = swept(ex2)
print(f"⑩-2 出る：廊下の外の角の z {ca:.3f}〜{cb:.3f}・⑩-2 のくぼみ（止まった根から）{min(ba, ca):.3f}〜{max(bb, cb):.3f}・長さ {max(bb, cb) - min(ba, ca):.3f}")
```


### make270.py

```python
"""依頼270：make237.py を写して変えた。
(1) closeup270_<名前>.mp4：frames/<場面>/f_*.png（台本の video_from から終わりまで）に台本の秒の音（mix270_<場面>.wav）を重ねる。早回しは無し。
    ⑩-2 はストレッチャーが動き出した時から 3 秒、左下に「ストレッチャーを待たせた ○秒」（止まってから動き出すまで。台本 c270.wait_label）
(2) closeup270_<名前>_top.mp4：frames/<場面>_top に 236 の描き方で床の目印・通った跡・印・左上の字を重ねる。
    目印：くぼみの輪郭（実線）・ハコブくんのふだんの線 x −0.33（点線）。床の目印は、ものごとに穴を埋めた外形（閉じる処理 半径 6 画素 → 中の穴埋め）の中には描かない。
    もの：ハコブくん（赤）と、ストレッチャー・大城さん・寺島さん（緑）。大城さんと寺島さんは手をストレッチャーにのせたままなので、3 つを 1 つのものとして埋める（236 の「手を握りにのせている間は 1 つ」と同じ考え）
    重ねる順：コマ → 床の目印（外形の所は消す）→ 通った跡 → 印 → 左上の字（動画の秒・ハコブくんとストレッチャー（人を含む）のすき間）
使い方: python3 make270.py <Unity の出力フォルダ> <台本> <場面> <音の wav> <動画を置くフォルダ> <動画の名前>"""
import csv, json, math, os, subprocess, sys, tempfile, wave
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, SHOT, WAV, VD, NAME = sys.argv[1:7]
os.makedirs(os.path.join(VD, "stills"), exist_ok=True)
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c270"]
FPS, W, H, S = 30, 1920, 1080, 2
f0 = int(round(C["video_from"] * FPS)); f1 = int(round(C["video_to"] * FPS))
seq = list(range(f0, f1 + 1))
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
def font(px, s=1): return ImageFont.truetype(FONT_PATH, px * s)
lab = C.get("wait_label")
vmap = {f: (f - f0) / FPS for f in seq}

# ---------------------------------------------------------------- (1) 本番の動画（TOP_ONLY=1 なら作らない＝真上だけ作り直す時）
TOP_ONLY = os.environ.get("TOP_ONLY") == "1"
tmp = tempfile.mkdtemp(prefix="m270_", dir="/tmp")
FB = font(40)
info = {"frames": len(seq), "label": None}
for k, f in enumerate([] if TOP_ONLY else seq):
    src = os.path.join(D, "frames", SHOT, f"f_{f:05d}.png"); assert os.path.exists(src), src
    t = f / FPS
    on = lab is not None and lab[0] - 1e-4 <= t < lab[1] - 1e-4
    if not on:
        os.symlink(os.path.abspath(src), os.path.join(tmp, f"v_{k:05d}.png")); continue
    im = Image.open(src).convert("RGB"); d = ImageDraw.Draw(im)
    if info["label"] is None: info["label"] = vmap[f]
    s = f"ストレッチャーを待たせた {lab[2]:.1f}秒"
    bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0]
    d.rounded_rectangle([24, H - 24 - 80, 24 + w + 50, H - 24], radius=12, fill=(242, 194, 48))
    d.text((49, H - 24 - 40), s, font=FB, fill=(25, 25, 25), anchor="lm")
    im.save(os.path.join(tmp, f"v_{k:05d}.png"))
    if abs(t - (lab[0] + 1.0)) < 0.5 / FPS: im.save(os.path.join(VD, "stills", f"{SHOT}_s06_wait_label.png"))     # 「ストレッチャーを待たせた」の字の所（動画のコマ）
if not TOP_ONLY:
  wr = wave.open(WAV); SR = wr.getframerate(); x = np.frombuffer(wr.readframes(wr.getnframes()), np.int16)
  a0 = int(round(f0 / FPS * SR)); a1 = int(round((f1 + 1) / FPS * SR))
  aud = x[a0:a1]; aud = np.pad(aud, (0, max(0, a1 - a0 - len(aud))))
  aw = os.path.join(tmp, "a.wav"); w2 = wave.open(aw, "w"); w2.setnchannels(1); w2.setsampwidth(2); w2.setframerate(SR); w2.writeframes(aud.astype(np.int16).tobytes()); w2.close()
  vid = os.path.join(VD, f"{NAME}.mp4")
  subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-i", aw,
                  "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30",
                  "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", "-shortest", vid], check=True)
  json.dump({"seq_first": seq[0], "seq_last": seq[-1], "n": len(seq), "video_s": len(seq) / FPS, "video_from": C["video_from"], "label_video_s": info["label"], "label": lab},
            open(os.path.join(D, f"vmap270_{SHOT}.json"), "w"), ensure_ascii=False)
  print("動画", vid, len(seq), "コマ", len(seq) / FPS, "秒・待たせた字", info["label"])

# ---------------------------------------------------------------- (2) 真上の動画
CAM = json.load(open(os.path.join(D, "top270_cam.json")))
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 60, 34, 36
COL = {"alcove": (142, 36, 170), "lane": (46, 173, 107), "st": (239, 108, 0), "robot": (0, 105, 92)}
LW = {"alcove": 5, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)
rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames270.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top270.csv")))}
EV = C["events"]; A = C["alcove"]
back = SHOT == "stretcher_back"
MARKS = [("robot", EV["detect"], "見つけた")]
if back: MARKS += [("robot", EV["stop"], "止まった"), ("robot", EV["back0"], "下がり始め"), ("robot", EV["in_stop"], "くぼみで止まった"),
                   ("st", C["stretcher_stop"][0], "止まった"), ("st", C["stretcher_stop"][1], "動き出した")]
else: MARKS += [("robot", EV["in_stop"], "くぼみで止まった")]
MARKS += [("robot", EV["exit"], "出た")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]
FL, FM, FH = font(LINE_LABEL_PX, S), font(MARK_LABEL_PX, S), font(HUD_PX, S)
def sc(p): return (p[0] * S, p[1] * S)
def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy; bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)
def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1); L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0.0
    while s < L:
        e = min(L, s + DASH * S); d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S); s += (DASH + GAP) * S
def down(layer): return layer.resize((W, H), Image.LANCZOS)
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
poly = [to_px(-0.90, A["z0"]), to_px(A["x_back"], A["z0"]), to_px(A["x_back"], A["z1"]), to_px(-0.90, A["z1"])]
d.line([sc(p) for p in poly], fill=COL["alcove"] + (255,), width=LW["alcove"] * S, joint="curve")
dashed(d, to_px(-0.90, A["z0"]), to_px(-0.90, A["z1"]), COL["alcove"] + (255,), 3)
dashed(d, to_px(-0.33, z_lo), to_px(-0.33, z_hi), COL["lane"] + (255,), LW["dash"])
cx_al = to_px(A["x_back"], (A["z0"] + A["z1"]) / 2)
text_box(d, sc((cx_al[0], cx_al[1] - 14)), f"くぼみ（奥行 {A['depth_m']:.2f} m・長さ {A['length_m']:.2f} m）", FL, COL["alcove"], "mb", edge=COL["alcove"])
lp = to_px(-0.33, z_hi)
text_box(d, sc((W - 14, lp[1] + 10)), "ハコブくんのふだん −0.33", FL, COL["lane"], "rt", edge=COL["lane"])
static = down(st); static_A = static.getchannel("A")
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(A["x_back"] - 0.15, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    nr = 0; ns = 0
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["st_px"]), float(r["st_py"])) if who == "st" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "st": ly = rail_lo_py + 40 + 70 * (ns % 2); anchor = "mt"; ns += 1
        else: ly = rail_hi_py - 30 - 62 * (nr % 3); anchor = "mb"; nr += 1
        ly = max(ly, 215)                         # 左上の字（〜190 画素）の下に
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        tv = vmap.get(mark_f[i], 0.0)
        lab_s = f"{head} {tv:.1f}秒"; bw = d.textbbox((0, 0), lab_s, font=FM)[2] / S
        lx = min(max(px, bw / 2 + 20), W - bw / 2 - 20)          # 字が画面の外へ出ないように（引き出し線は印の所のまま）
        text_box(d, sc((lx, ly)), lab_s, FM, COL[who], anchor, edge=COL[who])
    return down(L)
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    g = num_ok(rows[f]["gap_m"])
    return [f"{vmap[f]:.1f} 秒", "ハコブくんとストレッチャー（人を含む）のすき間 " + (f"{g:.2f} m" if g is not None and g < 1.5 else "1.5 m より遠い")]
RC = 6
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24
def fill_obj(soft):
    ys, xs = np.nonzero(soft); added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added
    y0, y1 = max(0, ys.min() - PAD), min(H, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(W, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    added[y0:y1, x0:x1] = filled & ~b.astype(bool)
    return added
tmpT = tempfile.mkdtemp(prefix="m270t_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"st": None, "robot": None}; shown = [False] * len(MARKS); mcache = mark_layer(shown)
per = []; top_stills = {}
want = {int(round(s[0] * FPS)): s[2] for s in shot["stills"] if s[1] == "top"}
k = 0
seqset = set(seq)
for f in range(0, f1 + 1):
    r = top[f]
    for who, kx, ky in (("st", "st_px", "st_py"), ("robot", "robot_px", "robot_py")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)
        if prev[who] is not None: td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2; td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))
        prev[who] = p
    if f not in seqset: continue
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", SHOT + "_top", f"f_{f:05d}.png")).convert("RGBA")
    mkn = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_mask", f"f_{f:05d}.png")).convert("L"))
    ob = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_obj", f"f_{f:05d}.png")).convert("RGBA"))
    groups = [ob[:, :, 0], ob[:, :, 1]]       # 赤＝ハコブくん・緑＝ストレッチャーと 2 人（Closeup270.cs が 1 つの型に写す）
    add_any = np.zeros((H, W), bool)
    for g in groups: add_any |= fill_obj(g)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(Image.fromarray(Fn, "L"))))
    lines = hud_lines(f)
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl); x0, y0, lh = 30, 22, 78
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 2 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(down(trail)); im.alpha_composite(mcache); im.alpha_composite(down(hl))
    o = im.convert("RGB"); o.save(os.path.join(tmpT, f"v_{k:05d}.png")); k += 1
    stA = np.array(st_m.getchannel("A"))
    per.append((f, int(((stA > 0) & (Fn == 255)).sum()), int(add_any.sum())))
    if f in want: top_stills[want[f]] = o
vidT = os.path.join(VD, f"{NAME}_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmpT, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vidT], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for nm, im in top_stills.items(): im.save(os.path.join(sd, f"{SHOT}_{nm}.png"))
open(os.path.join(D, f"per270_{SHOT}.csv"), "w").write("frame,line_left_inside,added\n" + "".join(",".join(map(str, p)) + "\n" for p in per))
print("真上", vidT, k, "コマ・外形の中に残る目印の画素 合計", sum(p[1] for p in per))
```


### make_script270.py

```python
"""依頼270：要所の場面 ⑩「ストレッチャーに道を空ける」の台本 closeup270_script.json を作る。場面は 2 つ：stretcher_alcove（⑩-1）・stretcher_back（⑩-2）。
寺島さんは別の場面 <名前>__tera（同じ台本の中。Closeup270.cs が 2 つめの CloseupDirector で動かす）。
make_script237.py（229・235 の土台）を手本にした（廊下・色・光・看護師の値・声の口の作り方・ハコブくんの決まりの値）。
・廊下：229 の台本の rooms を写し、z の奥を 10 m 長くした（⑩-2 でストレッチャーが向こうから来る所が要るため）。−x の壁にくぼみを 1 つ足し、くぼみの所の手すり・壁・巾木・扉 2 を切った。
  くぼみの奥に病室の扉を付けた（飾り）
・ストレッチャー（Closeups/Models_stretcher/stretcher.fbx）：向き 180°（足の側が −z＝進む向き）。大城さんの根の前 ST_AHEAD に固く付ける。
  後ろの押す手（頭の側・横の棒）を大城さんが両手で押す。寺島さんは足の側の横（−x の側＝廊下の真ん中寄り）を一緒に歩き、左手を柵（Rail_R）の上に添える
・ハコブくんの動き：229 の決まり（robot270.py に写した StepSpeed・StepLat）で、台本を作る時に Python で回す（毎コマの x・z・向きを台本 c270.robot に書く）。
  見つけるのは 229 と同じ「前の端どうしのあいだ 6.0 m」（0.1 秒前に見た値）。ストレッチャーを見つけたら、すき間があっても譲る（病院の1日の決まり stretcher_yield「ロボットが譲る」）
  ⑩-1：前にくぼみがあれば、寄る速さ 0.5 m/秒でくぼみの中の所へ寄り（向き 15°まで・残り 0.03 m で止まり始める）、止まる
  ⑩-2：前にくぼみが無いので止まる（0.4 m/秒²）→「すみません、下がります」→ 大城さんの返事の後、後ろ向きに 0.2 m/秒で下がる：
        くぼみの端に着くまではまっすぐ、着いたら 229 の寄り方を後ろ向きに使ってくぼみの中へ寄り、⑩-1 と同じくぼみの中の所まで下がって止まる
  出る（2 本とも）：ストレッチャーの後ろの端がくぼみを 1 m 過ぎたら、229 の走り出し（0.6 m/秒・向き 10°まで・角の線）でふだんの位置 x −0.33 へ戻る
使い方：python3 make_script270.py <229 の台本> <出力の台本> <声の wav のフォルダ> <出力の top の json>"""
import json, math, os, sys, wave
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from robot270 import R, step_speed, step_lat, corners, RX0, RX1, RZ0, RZ1

def E(k, d):
    v = os.environ.get(k)
    return type(d)(v) if v is not None else d

src, dst, wavdir, topdst = sys.argv[1:5]
S = json.load(open(src))
FPS = 30; DT = 1.0 / FPS
O = list(S["corridor"]["origin"])
q = lambda t: round(round(t * FPS) / FPS, 4)
def smooth(u): u = min(1, max(0, u)); return u * u * (3 - 2 * u)

# ---------------------------------------------------------------- 寸法
SX = E("SX", 0.38)                          # ストレッチャーの中心の x（手すりの内の面 +0.84 と角のバンパー +0.75 のすき間 0.09）
ST_FRONT, ST_REAR, ST_HW = 1.005, 1.0644, 0.37      # 足の側の前の端（バンパー）・頭の側の後ろの端（押す手）・横の半分（Unity で測った値）
BAR_Z, BAR_Y, BAR_R, BAR_HALF = 1.050, 0.980, 0.0144, 0.19   # 押す手（横の棒）：根の後ろ・高さ・太さの半径・まっすぐな所の半分の長さ
D_PUSH = E("D_PUSH", 0.27)                  # 大城さんの根から押す手の棒の中心まで（前へ）
ST_AHEAD = BAR_Z + D_PUSH                   # ストレッチャーの根：大城さんの根の前
GRIP_X = 0.14
RAIL_X, RAIL_Y, RAIL_R = 0.338, 0.980, 0.012       # 柵（Rail_R）の上の棒（根から。向き 180° なので世界では −x の側）
T_HAND_LZ = 0.31                            # 寺島さんの手：柵の上の棒の、根の前 0.31（足の側。柱 0.21 と 0.41 の間）
TX = E("TX", -0.22)                         # 寺島さんの根の x
T_AHEAD = T_HAND_LZ - 0.10                  # 寺島さんの根：ストレッチャーの根の前 0.21（手は根の 0.10 前）
V_S = 0.8                                   # 押す速さ（229 の車いすと同じ）
STEP_T = 0.5
SPINE, CHEST = 4.0, 3.0
# くぼみ（−x の壁）
XB = E("XB", -1.62)                         # くぼみの奥の壁の面（廊下の中心から）
XA = XB + R["wall_clear"] + RX1             # くぼみの中のハコブくんの根の x（奥の壁と 0.053）
RAIL_IN = -0.84; WALL_F = -0.90
ZA0 = E("ZA0", 4.0)                         # くぼみの始まり（z）
EXIT_ANG = R["resume_angle"]
Z_END = 31.0                                # 廊下の奥（229 は 21.0）

# ---------------------------------------------------------------- ハコブくん（229 の決まり）
def st_front(sz): return sz - ST_FRONT
def st_rear(sz): return sz + ST_REAR

def sim_enter(rx, rz, th, rv, ra):
    out = []; done = False
    while True:
        rv, ra = step_speed(rv, ra, 0.0 if done else R["slow"])
        rx, th = step_lat(rx, th, XA, rv, R["lat_angle"], XA)
        if not done and abs(XA - rx) < R["lat_done"]: done = True
        rz += rv * DT; out.append((rx, rz, th, rv))
        if done and rv <= 0: return out

def sim_exit(rx, rz, th):
    rv, ra = 0.0, 0.0; out = []
    while True:
        rv, ra = step_speed(rv, ra, R["cruise"])
        rx, th = step_lat(rx, th, R["lane"], rv, EXIT_ANG, XA)
        rz += rv * DT; out.append((rx, rz, th, rv))
        if abs(rx - R["lane"]) < 0.002 and abs(th) < 0.01 and len(out) > 30: return out

def outside_z(path):
    zs = []
    for p in path:
        for cx, cz in corners(p[0], p[1], p[2]):
            if cx < RAIL_IN: zs.append(cz)
    return min(zs), max(zs)

# くぼみの長さ：⑩-1 の入る道（見つけた所 z 0 から）と出る道の、廊下の外（x < −0.84）へ出る角の z の範囲＋0.05
en = sim_enter(R["lane"], 0.0, 0.0, R["cruise"], 0.0)
ex = sim_exit(en[-1][0], en[-1][1], en[-1][2])
za, zb = outside_z(en + ex)
MARG = 0.05
D_TRIG = ZA0 + MARG - za                    # ⑩-1：決まりに当たった時（寄り始め）の根の z
SLOT_Z = D_TRIG + en[-1][1]                 # くぼみの中の止まる所（根の z）
_ex2 = sim_exit(XA, SLOT_Z - 0.1, 0.0)        # ⑩-2：下がって向き 0°・くぼみの中の x で止まった所から出る（止まる所の 0.1 m 手前まで見込む）
ZA1 = max(D_TRIG + zb, outside_z(_ex2)[1]) + MARG
SLOT_Z = D_TRIG + en[-1][1]                 # くぼみの中の止まる所（根の z）
ALC = {"x_back": XB, "x_robot": round(XA, 4), "z0": round(ZA0, 4), "z1": round(ZA1, 4), "slot_z": round(SLOT_Z, 4), "depth_m": round(WALL_F - XB, 4), "length_m": round(ZA1 - ZA0, 4)}
print("くぼみ", ALC)


def robot_run(variant, st_z, t_events):
    """ハコブくんを 1 コマずつ。st_z(t)：ストレッチャーの根の z。t_events：⑩-2 の下がり始めの時刻など（無ければ見つけた所まで）"""
    back = variant == "stretcher_back"
    rz = RZ_START[variant]; rx, th, rv, ra = R["lane"], 0.0, R["cruise"], 0.0
    mode = "cruise"; rows = []; ev = {}; latdone = False
    n_react = int(round(R["react"] * FPS))
    f = 0
    while True:
        t = f * DT
        tob = max(0.0, t - n_react * DT)
        gap = st_front(st_z(tob)) - (rz + RZ1)
        if mode == "cruise" and gap < R["detect"] and "detect" not in ev:
            ev["detect"] = t; ev["detect_gap"] = gap; ev["detect_rz"] = rz
            mode = "back_stop" if back else "alcove"
        if mode == "alcove":
            rv, ra = step_speed(rv, ra, 0.0 if latdone else R["slow"])
            rx, th = step_lat(rx, th, XA, rv, R["lat_angle"], XA)
            if not latdone and abs(XA - rx) < R["lat_done"]: latdone = True; ev["lat_done"] = t
            if latdone and rv <= 0: mode = "wait"; ev["in_stop"] = t
        elif mode == "back_stop":
            rv, ra = step_speed(rv, ra, 0.0)
            if rv <= 0 and "stop" not in ev: ev["stop"] = t; ev["stop_rz"] = rz
            if "back_t" in t_events and t >= t_events["back_t"] - 1e-6: mode = "back1"; ev["back0"] = t
        elif mode in ("back1", "back2"):
            if mode == "back1" and rz <= ZA1 + E("B_TURN", 0.50): mode = "back2"; ev["back_turn"] = t; ev["back_turn_rz"] = rz
            stopnow = rz <= SLOT_Z + 0.02
            rv, ra = step_speed(rv, ra, 0.0 if stopnow else 0.2)
            if mode == "back1": rx, th = step_lat(rx, th, R["lane"], rv, R["lat_angle"], None, sgn=-1.0)
            else:
                rx, th = step_lat(rx, th, XA, rv, R["lat_angle"], XA, sgn=-1.0)
                if not latdone and abs(XA - rx) < R["lat_done"]: latdone = True; ev["lat_done"] = t
            if stopnow and rv <= 0: mode = "wait"; ev["in_stop"] = t
            rz -= rv * DT; rows.append((t, rx, rz, th, -rv, mode)); f += 1
            continue
        elif mode == "wait":
            rv, ra = 0.0, 0.0
            if st_rear(st_z(tob)) < ZA0 - 1.0: mode = "exit"; ev["exit"] = t
        elif mode in ("exit", "cruise2"):
            rv, ra = step_speed(rv, ra, R["cruise"])
            rx, th = step_lat(rx, th, R["lane"], rv, EXIT_ANG, XA)
            if mode == "exit" and abs(rx - R["lane"]) < 0.002 and abs(th) < 0.01: mode = "cruise2"; ev["lane_back"] = t
        rz += rv * DT
        rows.append((t, rx, rz, th, rv, mode))
        f += 1
        if "lane_back" in ev and t > ev["lane_back"] + E("TAIL", 2.0): break
        if t > 200: raise Exception("終わらない " + variant)
        if back and "stop" in ev and "back_t" not in t_events: break     # 1 回目：止まるまで
        if back and "in_stop" in ev and t_events.get("until_in"): break  # 2 回目：くぼみの中で止まるまで
    return rows, ev

# ---------------------------------------------------------------- 声
LINES = {"H1": ("robot", "H1_hakobu_stretcher.wav", "ストレッチャーが通ります。こちらでお待ちします"),
         "H2": ("robot", "H2_hakobu_sagarimasu.wav", "すみません、下がります"),
         "T1": ("tera", "T1_terashima_arigatou.wav", "ありがとう"),
         "O1": ("nurse", "O1_oshiro_matteru.wav", "はーい、待ってるね")}
SR = 48000
def load_wav(p):
    w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float64) / 32768.0
    assert w.getframerate() == SR and w.getnchannels() == 1, p
    return x
def voiced(x, th_db=-45.0):
    hop = 480
    e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
    on = np.where(20 * np.log10(e + 1e-9) > th_db)[0]
    return on[0] * hop / SR, (on[-1] + 1) * hop / SR
clips = {}
for k, (who, fn, text) in LINES.items():
    x = load_wav(os.path.join(wavdir, fn)); v0, v1 = voiced(x)
    clips[k] = {"who": who, "file": fn, "text": text, "x": x, "v0": v0, "v1": v1, "dur": v1 - v0, "len": len(x) / SR}
GAP = E("GAP", 0.55)
HAPPY_S = 1.5

# ---------------------------------------------------------------- 場面ごと
T_DET = E("T_DET", 7.0)                     # 見つける時刻の目安（動画の始めから）
RZ_START = {}
def build(variant):
    back = variant == "stretcher_back"
    # ハコブくんの始め：⑩-1 は寄り始め（＝見つけた 0.1 秒後…見つけたコマ）に根が D_TRIG、⑩-2 は見つけた時に後ろの端がくぼみの端を DZ_PASS 過ぎている
    if back: rz_det = ZA1 + E("DZ_PASS", 0.30) - RZ0          # RZ0 は負（後ろの端）
    else: rz_det = D_TRIG
    RZ_START[variant] = rz_det - R["cruise"] * T_DET
    # ストレッチャー：見つける時（T_DET−0.1 に見た値）に前の端どうし 6.0 m になる所から 0.8 m/秒
    sz_obs = rz_det + RZ1 + R["detect"] - 0.0005 + ST_FRONT       # T_DET−react の時のストレッチャーの根（前の端どうし 6.0 m より 0.5 mm 近く）
    SZ0 = sz_obs + V_S * (T_DET - R["react"])
    # ---- ⑩-2：止まる・待つ・動き出す（2 回まわす：1 回目でハコブくんが止まる時刻、2 回目で下がる）
    plan = {}
    def st_z_factory(plan):
        def st_z(t):
            if not back or "brake0" not in plan: return SZ0 - V_S * t
            b0, b1 = plan["brake0"], plan["brake0"] + plan["T_BR"]
            zb0 = SZ0 - V_S * b0
            if t <= b0: return SZ0 - V_S * t
            if t <= b1:
                u = (t - b0) / plan["T_BR"]; return zb0 - V_S * plan["T_BR"] * (u - (u ** 3 - 0.5 * u ** 4))
            zst = zb0 - V_S * plan["T_BR"] * 0.5
            r0 = plan.get("resume", 1e9)
            if t <= r0: return zst
            if t <= r0 + plan["T_ACC"]:
                u = (t - r0) / plan["T_ACC"]; return zst - V_S * plan["T_ACC"] * (u ** 3 - 0.5 * u ** 4)
            return zst - V_S * plan["T_ACC"] * 0.5 - V_S * (t - r0 - plan["T_ACC"])
        return st_z
    on = {}
    if back:
        rows, ev = robot_run(variant, st_z_factory(plan), {})
        on["H2"] = ev["stop"] + 0.2
        endH2 = on["H2"] + clips["H2"]["dur"]
        on["O1"] = endH2 + GAP
        plan["T_BR"] = E("T_BR", 1.6); plan["T_ACC"] = 1.2
        plan["brake0"] = on["H2"] + E("BRAKE_AFTER", 0.6)          # 「すみません」を聞いて止め始める
        back_t = on["O1"] + clips["O1"]["dur"] + 0.3
        rows, ev = robot_run(variant, st_z_factory(plan), {"back_t": back_t, "until_in": True})
        plan["resume"] = ev["in_stop"] + E("RESUME_AFTER", 1.0)      # ハコブくんがくぼみの中で止まって 1.0 秒
        rows, ev = robot_run(variant, st_z_factory(plan), {"back_t": back_t})
    else:
        rows, ev = robot_run(variant, st_z_factory(plan), {})
        on["H1"] = ev["detect"] + E("H1_AFTER", 0.3)
    st_z = st_z_factory(plan)
    NF = len(rows)
    DUR = q(NF * DT)
    # 寺島さんの「ありがとう」：寺島さんの根がハコブくんの根と並ぶ所（横）で声の真ん中
    t_side = None
    for (t, rx, rz, th, rv, mode) in rows:
        if t_side is None and t > ev["detect"] and st_z(t) - T_AHEAD <= rz: t_side = t
    if t_side is None: raise Exception("寺島さんが横に来ない")
    on["T1"] = t_side - clips["T1"]["dur"] / 2 + E("T1_SHIFT", 0.0)
    endT1 = on["T1"] + clips["T1"]["dur"]
    happy_from, happy_to = endT1, endT1 + HAPPY_S
    ev["t_side"] = t_side
    # ---- ストレッチャー・大城さん・寺島さんの根（毎コマ）
    srows = [(f * DT, st_z(f * DT)) for f in range(NF + 1)]
    sv = [0.0] + [-(srows[i][1] - srows[i - 1][1]) / DT for i in range(1, len(srows))]
    keys = lambda vals: [[round(srows[i][0], 4), round(vals[i], 5), "lin"] if i else [0.0, round(vals[0], 5)] for i in range(len(srows))]
    n_x = [SX] * len(srows); n_z = [r[1] + ST_AHEAD for r in srows]; n_y = [180.0] * len(srows)
    t_x = [TX] * len(srows); t_z = [r[1] - T_AHEAD for r in srows]
    moving = [v > 0.004 for v in sv]
    # 歩き：動いている間（止まる前後は 237 と同じく止まり終わり＋0.25 まで）0.5 秒ごと
    def segs_of(mv):
        out = []; a = None
        for i, m in enumerate(mv):
            if m and a is None: a = i
            if not m and a is not None: out.append((a * DT, i * DT)); a = None
        if a is not None: out.append((a * DT, len(mv) * DT))
        return out
    mseg = segs_of(moving)
    def walk_steps(segs, first, t_first):
        st = []; foot = first
        for (a, b) in segs:
            t = max(a, t_first) if a < 1e-6 else a - 0.05
            while t + STEP_T <= b + 0.25 + 1e-6:
                st.append([round(t, 4), round(t + STEP_T, 4), foot]); t += STEP_T; foot = "L" if foot == "R" else "R"
            if b < (NF - 1) * DT - 0.5:     # 止まる：そろえる 1 歩
                st.append([round(t, 4), round(t + STEP_T * 0.9, 4), foot]); foot = "L" if foot == "R" else "R"
        return st
    steps_o = walk_steps(mseg, "R", 0.0)
    steps_t = walk_steps(mseg, "L", 0.0)
    walk = [[0, 1]]
    for (a, b) in mseg:
        if a > 1e-6: walk += [[round(a, 4), 0], [round(a + 0.6, 4), 1]]
        if b < (NF - 1) * DT - 0.5: walk += [[round(b - 0.6, 4), 1], [round(b, 4), 0]]
    # ---- 顔：大城さんは「はーい、待ってるね」の間だけハコブくんのほうへ（体から 20°まで）、寺島さんは「ありがとう」の間ハコブくんのほうへ（40°まで）
    def look_yaw(nx_, nz_, byaw, tx, tz):
        want = math.degrees(math.atan2(tx - nx_, tz - nz_)); return ((want - byaw + 180) % 360) - 180
    def rob_at(t):
        i = min(len(rows) - 1, max(0, int(round(t * FPS)))); return rows[i]
    hy_o = [[0, 0.0]]; hn_o = [[0, 6.0]]
    if back:
        t0 = on["O1"] - 0.35; r = rob_at(on["O1"])
        a = max(-20.0, min(20.0, look_yaw(SX, st_z(on["O1"]) + ST_AHEAD, 180.0, r[1], r[2] + RZ1)))
        hy_o += [[round(t0, 4), 0.0], [round(on["O1"], 4), round(a, 3)], [round(on["O1"] + clips["O1"]["dur"] + 0.4, 4), round(a, 3)], [round(on["O1"] + clips["O1"]["dur"] + 0.9, 4), 0.0]]
    r = rob_at(on["T1"])
    a_t = max(-40.0, min(40.0, look_yaw(TX, st_z(on["T1"]) - T_AHEAD, 180.0, r[1], r[2] + 0.2)))
    hy_t = [[0, 0.0], [round(on["T1"] - 0.45, 4), 0.0], [round(on["T1"], 4), round(a_t, 3)], [round(endT1 + 0.3, 4), round(a_t, 3)], [round(endT1 + 0.8, 4), 0.0]]
    hn_t = [[0, 6.0]]
    # ---- 画面
    if back:
        scr = [[0, "face"], [q(on["H2"]), "back"], [q(happy_from), "happy"], [q(happy_to), "wait"], [q(ev["exit"]), "face"]]
    else:
        scr = [[0, "face"], [q(on["H1"]), "wait"], [q(happy_from), "happy"], [q(happy_to), "wait"], [q(ev["exit"]), "face"]]
    # ---- 声の並び・口
    tracks = {w: np.zeros(int(DUR * SR) + SR) for w in ("nurse", "robot", "tera")}
    place = {}
    for k, t0 in on.items():
        c = clips[k]; s0 = t0 - c["v0"]; i0 = int(round(s0 * SR))
        tracks[c["who"]][i0:i0 + len(c["x"])] += c["x"]
        place[k] = {"who": c["who"], "file": c["file"], "text": c["text"], "clip_start_s": round(s0, 4), "voice_on_s": round(t0, 4), "voice_off_s": round(t0 + c["dur"], 4),
                    "voice_len_s": round(c["dur"], 4), "clip_len_s": round(c["len"], 4)}
    HOP = SR // FPS
    def frame_rms(x): return np.array([np.sqrt(np.mean(x[i * HOP:(i + 1) * HOP] ** 2)) if i * HOP < len(x) else 0 for i in range(NF)])
    def ladder(who, rest, speak):
        rms = frame_rms(tracks[who])
        ref = np.percentile(rms[rms > 0.01], 90) if (rms > 0.01).any() else 1.0
        lvl = np.convolve(rms / ref, np.ones(3) / 3, mode="same")
        target = np.where(speak, np.digitize(lvl, [0.15, 0.35, 0.65]), 0)
        for i in range(NF):
            if not speak[i]: target[i] = rest[i]
        for i in range(1, NF - 1):
            if target[i] != target[i - 1] and target[i] != target[i + 1]: target[i] = target[i - 1]
        step = np.zeros(NF, int)
        for i in range(NF):
            prev = step[i - 1] if i else rest[0]
            step[i] = prev + int(np.clip(target[i] - prev, -1, 1)) if i % 2 == 0 else prev
        return step
    def speak_mask(names):
        m = np.zeros(NF, bool)
        for k in names:
            if k in on: m[int(math.floor(on[k] * FPS)):int(math.ceil(place[k]["voice_off_s"] * FPS))] = True
        return m
    LADDER = ["closed", "small", "mid", "large"]
    robot_mouth = [LADDER[s] for s in ladder("robot", np.full(NF, 2), speak_mask(["H1", "H2"]))]
    nurse_mouth = [int(s) for s in ladder("nurse", np.zeros(NF, int), speak_mask(["O1"]))]
    tera_mouth = [int(s) for s in ladder("tera", np.zeros(NF, int), speak_mask(["T1"]))]
    mix = sum(tracks.values())[: int(round(DUR * SR))]
    pk = float(np.max(np.abs(mix))); assert pk < 1.0, pk
    wav_out = os.path.join(os.path.dirname(dst), f"mix270_{variant}.wav")
    w = wave.open(wav_out, "w"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
    w.writeframes((np.clip(mix, -1, 1) * 32767).astype(np.int16).tobytes()); w.close()
    # ---- カメラ（main は 229 の本番：ハコブくんの後ろの上・高さ 1.72・向こうを見下ろす。ハコブくんの z に付いて動く）
    tt = on["T1"] + clips["T1"]["dur"] * 0.5; rr = rob_at(tt)
    tz_h = st_z(tt) - T_AHEAD
    CAM = {
        "main": {"follow": "robot", "pos": [-0.62, 1.72, -5.3], "look": [0.12, 0.8, 2.3], "fov": 38},
        "screen_close": {"follow": "robot_pose", "pos": [0.0, 1.23, 1.15], "look": [0.0, 0.962, 0.29], "fov": 24},
        "tera_face": {"pos": [round(rr[1] + 0.30, 4), 1.42, round(rr[2] - 2.3, 4)], "look": [round(TX, 4), 1.48, round(tz_h, 4)], "fov": 22},
        "chk_grip": {"follow": "nurse", "pos": [round(SX - 0.75, 4), 1.35, -0.05], "look": [round(SX, 4), 0.98, -0.27], "fov": 30},
        "chk_tera": {"follow": "nurse", "pos": [round(TX - 0.9, 4), 1.45, round(-ST_AHEAD - T_AHEAD - 0.3, 4)], "look": [round(TX + 0.2, 4), 1.0, round(-ST_AHEAD - T_AHEAD, 4)], "fov": 40},
    }
    first = "H2" if back else "H1"
    cuts = [[0, "main"], [q(on[first] - 0.15), "screen_close"], [q(on[first] + clips[first]["dur"] + 0.15), "main"],
            [q(on["T1"] - 0.35), "tera_face"], [q(endT1 + 0.1), "screen_close"], [q(happy_to + 0.15), "main"]]
    cuts.sort(key=lambda c: c[0])
    stills = [[q(ev["detect"]), "main", "s01_found_main"]]
    stills += [[q(ev["in_stop"] + 0.3), "main", "s02_in_alcove_main"], [q(ev["in_stop"] + 0.3), "top", "s02_in_alcove_top"],
               [q(on["T1"] + clips["T1"]["dur"] * 0.5), "tera_face", "s03_arigatou_close"], [q(ev["detect"]), "top", "s01_found_top"]]
    if back:
        stills += [[q(on["H2"] + 0.8), "screen_close", "s04_sagarimasu_close"], [q((ev["back0"] + ev["in_stop"]) / 2), "top", "s05_backing_top"],
                   [q((ev["back0"] + ev["in_stop"]) / 2), "main", "s05_backing_main"]]
    stills += [[q(on["T1"] - 1.0), "chk_grip", "chk_grip"], [q(on["T1"] - 1.0), "chk_tera", "chk_tera_hand"], [1.0, "chk_grip", "chk_grip_1s"], [1.0, "chk_tera", "chk_tera_1s"]]
    # ---- 台本
    robot_rows = [[round(r[1], 5), round(r[2], 5), round(r[3], 4), round(r[4], 4), r[5]] for r in rows]
    wait_s = (plan["resume"] - (plan["brake0"] + plan["T_BR"])) if back else 0.0
    shot = {"name": variant, "about": "⑩ ストレッチャーに道を空ける（依頼270：" + ("⑩-2 くぼみに間に合わない" if back else "⑩-1 くぼみに入って待つ") + "）", "origin": O, "duration": DUR, "video": True,
            "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]},
            "box_events": [], "card_events": [], "presses": [], "card": False, "check_open": [], "check_close": [], "check_above": [], "transitions": [],
            "robot_start_z": round(RZ_START[variant], 4), "swing_ramp": 0.15, "lift_pow": 0.5,
            "nurse": {"x": keys(n_x), "z": keys(n_z), "yaw": keys(n_y), "walk": walk, "spine": [[0, SPINE]], "chest": [[0, CHEST]],
                      "head_yaw": hy_o, "head_nod": hn_o, "mouth": [[0, "flat"]], "talk": [[0, 0]],
                      "L_w": [[0, 1.0]], "R_w": [[0, 1.0]], "L_target": [[0, "bar_l"]], "R_target": [[0, "bar_r"]],
                      "L_curl": [[0, E("CURL", 5.0)]], "R_curl": [[0, E("CURL", 5.0)]], "L_thumb": [[0, E("THUMB", -10.0)]], "R_thumb": [[0, E("THUMB", -10.0)]],
                      "L_hint": [[0, "push_l"]], "R_hint": [[0, "push_r"]], "L_hint_w": [[0, 0.5]], "R_hint_w": [[0, 0.5]]},
            "steps": steps_o, "look_windows": [], "cameras": CAM, "cuts": cuts, "stills": stills,
            "c270": {"st_ahead_m": round(ST_AHEAD, 4), "video_from": 0.1, "video_to": round((NF - 1) * DT, 4),
                     "stretcher": [[round(SX, 4), round(r[1], 5)] for r in srows], "stretcher_v": [round(v, 4) for v in sv],
                     "robot": robot_rows, "screen": scr, "happy": [round(happy_from, 4), round(happy_to, 4)],
                     "robot_mouth": robot_mouth, "nurse_mouth": nurse_mouth, "tera_mouth": tera_mouth, "nurse_mouth_scale": [1.0, 1.2, 1.8, 2.4],
                     "lines": place, "bar": {"x_half": BAR_HALF, "y": BAR_Y, "z_behind_root": BAR_Z, "r": BAR_R, "grip_x": GRIP_X},
                     "rail": {"x": RAIL_X, "y": RAIL_Y, "r": RAIL_R, "z_lo": -0.63, "z_hi": 0.63}, "tera": {"x": TX, "ahead_m": T_AHEAD},
                     "alcove": ALC, "events": {k: (round(v, 4) if isinstance(v, float) else v) for k, v in ev.items()},
                     "wait_label": [round(plan["resume"], 4), round(plan["resume"] + 3.0, 4), round(wait_s, 3)] if back else None,
                     "stretcher_stop": [round(plan["brake0"] + plan["T_BR"], 4), round(plan["resume"], 4)] if back else None}}
    tshot = {"name": variant + "__tera", "about": "寺島さん（" + variant + "）", "origin": O, "duration": DUR, "video": True,
             "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]}, "box_events": [], "card_events": [], "presses": [], "card": False,
             "check_open": [], "check_close": [], "check_above": [], "transitions": [], "swing_ramp": 0.15, "lift_pow": 0.5,
             "nurse": {"x": keys(t_x), "z": keys(t_z), "yaw": keys(n_y), "walk": walk, "spine": [[0, 2.0]], "chest": [[0, 1.0]],
                       "head_yaw": hy_t, "head_nod": hn_t, "mouth": [[0, "flat"]], "talk": [[0, 0]],
                       "L_w": [[0, 1.0]], "R_w": [[0, 0.0]], "L_target": [[0, "rail_t"]], "L_curl": [[0, E("TCURL", 8.0)]], "L_thumb": [[0, E("TTHUMB", 40.0)]],
                       "L_hint": [[0, "tera_l"]], "L_hint_w": [[0, 0.5]]},
             "steps": steps_t}
    info = {"variant": variant, "duration": DUR, "frames": NF, "events": shot["c270"]["events"], "on": {k: round(v, 3) for k, v in on.items()},
            "happy": [round(happy_from, 3), round(happy_to, 3)], "robot_start_z": round(RZ_START[variant], 3), "stretcher_start_z": round(SZ0, 3),
            "stretcher_stop": shot["c270"]["stretcher_stop"], "wait_s": round(wait_s, 3)}
    return shot, tshot, info

# ---------------------------------------------------------------- 廊下（229 の rooms を写す・奥を長く・くぼみ）
def box(name, mn, mx, mat, solid=True, rail=None, shadow=None):
    r = {"name": name, "min": [round(v, 4) for v in mn], "max": [round(v, 4) for v in mx], "mat": mat}
    if solid: r["solid"] = True
    if rail: r["rail"] = True
    if shadow: r["shadow"] = True
    return r
rooms = []
EXT = Z_END - 21.0
EXT0 = Z_BEG0 = 12.0                         # 手前（−z）へのばす長さ（229 の廊下は z −4.0 から）
ox = O[0]
lx = lambda v: v - ox
cut0, cut1 = ZA0, ZA1           # −x の壁を切る z
for r in S["rooms"]:
    if not r["name"].startswith("廊下"): rooms.append(r); continue
    r = json.loads(json.dumps(r)); mn, mx = r["min"], r["max"]
    if r["name"] == "廊下_奥の壁": mn[2] += EXT; mx[2] += EXT; rooms.append(r); continue
    if r["name"] == "廊下_手前の壁": mn[2] -= EXT0; mx[2] -= EXT0; rooms.append(r); continue
    if mx[2] >= 20.69: mx[2] += EXT
    if mn[2] <= -3.69: mn[2] -= EXT0                                    # 手前も EXT0 のばす（ストレッチャーが通り過ぎてから先へ行く所）
    if r["name"].startswith("廊下_扉2"): continue                        # 扉 2 はくぼみの中（くぼみの奥に扉を付け直す）
    left = lx(mx[0]) <= -0.83 and r["name"] != "廊下_床"
    if left and mn[2] < cut1 and mx[2] > cut0:
        is_rail = "手すり" in r["name"]
        m0, m1 = (cut0 - 0.15, cut1 + 0.15) if is_rail and "金具" not in r["name"] else (cut0, cut1)
        if "金具" in r["name"] and (mn[2] < m1 + 0.12 and mx[2] > m0 - 0.12): continue
        pieces = []
        if mn[2] < m0: pieces.append((mn[2], min(mx[2], m0)))
        if mx[2] > m1: pieces.append((max(mn[2], m1), mx[2]))
        for i, (a, b) in enumerate(pieces):
            if b - a < (0.3 if is_rail else 0.01): continue
            rr = json.loads(json.dumps(r)); rr["min"][2] = round(a, 4); rr["max"][2] = round(b, 4); rr["name"] = r["name"] + ("_a" if a < cut0 else "_b"); rooms.append(rr)
        continue
    rooms.append(r)
# 奥へのばした所の手すりの金具（右 1.21 m ごと・左の手すり 4 は 1.33 m ごと）
for i in range(1, 9):
    z = 20.588 + 1.21 * i
    if z > Z_END - 0.4: break
    rooms.append(box(f"廊下_右の手すりの金具1_{21 + i}", [ox + 0.8575, 0.735, z], [ox + 0.9, 0.7825, z + 0.024], "dark", shadow=True))
for i in range(1, 11):
    z = -3.612 - 1.21 * i
    rooms.append(box(f"廊下_右の手すりの金具1_m{i}", [ox + 0.8575, 0.735, z], [ox + 0.9, 0.7825, z + 0.024], "dark", shadow=True))
    rooms.append(box(f"廊下_左の手すりの金具1_m{i}", [ox - 0.9, 0.735, z], [ox - 0.8575, 0.7825, z + 0.024], "dark", shadow=True))
for i in range(1, 9):
    z = 20.588 + 1.3333 * i
    if z > Z_END - 0.4: break
    rooms.append(box(f"廊下_左の手すりの金具4_{4 + i}", [ox - 0.9, 0.735, z], [ox - 0.8575, 0.7825, z + 0.024], "dark", shadow=True))
# くぼみ：床・奥の壁・両端の壁・巾木・奥の扉（飾り）
W_T = 0.15
rooms += [box("廊下_くぼみ_床", [ox + XB - W_T, -0.2, ZA0 - W_T], [ox - 1.05, 0.0, ZA1 + W_T], "floor", solid=False),
          box("廊下_くぼみ_奥の壁", [ox + XB - W_T, 0.0, ZA0 - W_T], [ox + XB, 2.6, ZA1 + W_T], "wall"),
          box("廊下_くぼみ_手前の端の壁", [ox + XB - W_T, 0.0, ZA0 - W_T], [ox + WALL_F, 2.6, ZA0], "wall"),
          box("廊下_くぼみ_奥の端の壁", [ox + XB - W_T, 0.0, ZA1], [ox + WALL_F, 2.6, ZA1 + W_T], "wall"),
          box("廊下_くぼみ_巾木", [ox + XB, 0.0, ZA0], [ox + XB + 0.008, 0.08, ZA1], "dark")]
zc = (ZA0 + ZA1) / 2; dz0, dz1 = zc - 0.71, zc + 0.71
rooms += [box("廊下_くぼみ_扉_枠の上", [ox + XB, 2.05, dz0], [ox + XB + 0.012, 2.13, dz1], "dark"),
          box("廊下_くぼみ_扉_枠の左", [ox + XB, 0.0, dz0], [ox + XB + 0.012, 2.05, dz0 + 0.06], "dark", solid=False),
          box("廊下_くぼみ_扉_枠の右", [ox + XB, 0.0, dz1 - 0.06], [ox + XB + 0.012, 2.05, dz1], "dark", solid=False),
          box("廊下_くぼみ_扉", [ox + XB + 0.002, 0.012, dz0 + 0.065], [ox + XB + 0.025, 2.045, dz1 - 0.065], "cloth"),
          box("廊下_くぼみ_扉_窓", [ox + XB + 0.025, 1.35, dz1 - 0.36], [ox + XB + 0.027, 1.8, dz1 - 0.26], "paper", solid=False),
          box("廊下_くぼみ_扉_取っ手", [ox + XB + 0.025, 0.85, dz1 - 0.18], [ox + XB + 0.045, 1.25, dz1 - 0.16], "top"),
          box("廊下_くぼみ_扉_番号の札", [ox + XB, 2.18, zc - 0.15], [ox + XB + 0.012, 2.3, zc + 0.15], "paper", solid=False)]

out = {k: S[k] for k in ("fps", "width", "height", "supersample", "colors", "light", "box", "bag", "nurse", "targets", "card", "pocket", "screen_ui", "drawer_parts", "hints", "check_stand_parts", "corridor")}
out["rooms"] = rooms
out["corridor"] = dict(out["corridor"]); out["corridor"]["z"] = [-4.0 - EXT0, Z_END]; out["corridor"]["alcove"] = ALC
out["about"] = "依頼270：⑩ ストレッチャーに道を空ける（場面 stretcher_alcove・stretcher_back、寺島さんは __tera）。make_script270.py が作った。廊下・色・光・看護師・画面の値は 229 の台本から写した（廊下は奥を 10 m・手前を 12 m のばし、−x の壁にくぼみを足した）"
out["nurse"] = dict(out["nurse"]); out["nurse"]["walk"] = dict(out["nurse"]["walk"])
out["nurse"]["walk"].update({"amp_deg": 11.0, "knee_deg": 24, "bob_m": 0.008, "lift_m": 0.05})
out["targets"] = dict(out["targets"])
py = BAR_Y + BAR_R + E("PY_UP", 0.026)
GZ = E("GZ", D_PUSH - 0.045)                # 手のひらの的：棒の中心の 4.5 cm 手前・棒の面の 2.6 cm 上（指はほぼのばして棒の上から前へ。親指は上げる＝棒の下へ回さない）
out["targets"]["bar_l"] = {"ref": "nurse", "pos": [-GRIP_X, round(py, 4), round(GZ, 4)], "finger_frame": "nurse", "finger": [-0.25, -0.45, 1], "palm_frame": "nurse", "palm": [0.15, -1, 0.0]}
out["targets"]["bar_r"] = {"ref": "nurse", "pos": [GRIP_X, round(py, 4), round(GZ, 4)], "finger_frame": "nurse", "finger": [0.25, -0.45, 1], "palm_frame": "nurse", "palm": [-0.15, -1, 0.0]}
# 寺島さんの左手：柵（世界の x = SX − 0.338）の上の棒の上。寺島さんの向き 180°なので、看護師の向きの x は世界の −x
rail_wx = SX - RAIL_X
out["targets"]["rail_t"] = {"ref": "nurse", "pos": [round(-(rail_wx - TX) + E("TPX", 0.0), 4), round(RAIL_Y + RAIL_R + E("TPY_UP", 0.03), 4), 0.10], "finger_frame": "nurse", "finger": [-1.0, -0.35, 0.4], "palm_frame": "nurse", "palm": [0.3, -1, 0.0]}
out["hints"] = dict(out["hints"]); out["hints"]["tera_l"] = [-0.45, 1.0, -0.15]
out["robot_rule"] = {"about": "ハコブくんの決まり（229 のまま）。依頼270 で足したこと：ストレッチャーを見つけたら（前の端どうし detect_range_m）すき間があっても譲る（病院の1日の stretcher_yield「ロボットが譲る」）。"
                              "前にくぼみがあれば寄って入り、無ければ止まって後ろのくぼみへ back_mps で下がる。ストレッチャーの後ろの端がくぼみを exit_after_m 過ぎたら出る（229 の走り出し）",
                     "cruise_mps": R["cruise"], "slow_mps": R["slow"], "accel_max_mps2": R["accel"], "decel_max_mps2": R["decel"], "jerk_max_mps3": R["jerk"],
                     "detect_range_m": R["detect"], "react_s": R["react"], "margin_m": R["margin"], "gap_slow_m": R["gap_slow"], "gap_stop_m": R["gap_stop"],
                     "lane_x": R["lane"], "wall_clear_m": R["wall_clear"], "lateral_max_mps": R["lat_max"], "lateral_angle_deg": R["lat_angle"], "lateral_accel_mps2": R["lat_accel"],
                     "lateral_gain": R["kx"], "lateral_done_m": R["lat_done"], "resume_lateral_angle_deg": R["resume_angle"], "turn_rate_dps": R["turn_rate"],
                     "corner_half_len_m": R["half_len"], "corner_slack_m": R["slack"], "back_mps": 0.2, "exit_after_m": 1.0, "back_turn_after_m": E("B_TURN", 0.50)}
shots, infos = [], []
for v in ("stretcher_alcove", "stretcher_back"):
    a, b, i = build(v); shots += [a, b]; infos.append(i)
out["shots"] = shots
out["c270_common"] = {"sx": SX, "st_ahead": round(ST_AHEAD, 4), "tx": TX, "t_ahead": T_AHEAD, "alcove": ALC, "d_trig": round(D_TRIG, 4)}
json.dump(out, open(dst, "w"), ensure_ascii=False, indent=0)
# 真上のカメラ（230 と同じ大きさ・場面ごとの真ん中）
TOP = {"about": "依頼270：⑩ の真上のカメラ（230 と同じ正射影・同じ大きさ。場面ごとに真ん中の z を変えた）。画面の上が −x・右が +z",
       "stretcher_alcove": {"center_x": -0.6, "center_z": round((ZA0 + ZA1) / 2 + 0.6, 3), "height": 10.0, "ortho_size": 2.8828125, "width_px": 1920, "height_px": 1080},
       "stretcher_back": {"center_x": -0.4, "center_z": 11.0, "height": 10.0, "ortho_size": 4.0, "width_px": 1920, "height_px": 1080,
                          "about": "⑩-2 は止まったストレッチャー（前の端 z 16.2）とくぼみの中のハコブくんが一緒に写るように広くした（z 3.9〜18.1）"}}
json.dump(TOP, open(topdst, "w"), ensure_ascii=False, indent=1)
print(json.dumps({"common": out["c270_common"], "shots": infos}, ensure_ascii=False, indent=1))
```


### pipe270.sh

```bash
#!/bin/bash
# 依頼270：確かめ（区切らずに最後まで・静止画も）→ 区切って撮る
R=/tmp/c270/tools; O=/tmp/c270/out
for sh in stretcher_alcove stretcher_back; do S=$(date +%s); $R/run270.sh $O/$sh $sh off on main,top; echo "check $sh $(( $(date +%s)-S )) s"; done
for c in stretcher_alcove:0:11 stretcher_alcove:11:22 stretcher_alcove:22:1e9 stretcher_back:0:14 stretcher_back:14:28 stretcher_back:28:42 stretcher_back:42:56 stretcher_back:56:70 stretcher_back:70:1e9; do
  IFS=: read sh a b <<< "$c"; S=$(date +%s)
  $R/run270.sh $O/${sh}_r $sh on off main,top $a $b
  echo "render $sh $a-$b $(( $(date +%s)-S )) s $(ls $O/${sh}_r/frames/$sh | wc -l)"
done
echo ALLDONE
```


### pipe270b.sh

```bash
#!/bin/bash
# 依頼270：pipe270.sh の続き（⑩-1 の確かめは済み）。⑩-1 を区切って撮る → ⑩-2 の確かめ → ⑩-2 を区切って撮る
R=/tmp/c270/tools; O=/tmp/c270/out
run_r() { IFS=: read sh a b <<< "$1"; S=$(date +%s); $R/run270.sh $O/${sh}_r $sh on off main,top $a $b; echo "render $sh $a-$b $(( $(date +%s)-S )) s $(ls $O/${sh}_r/frames/$sh | wc -l)"; }
for c in stretcher_alcove:0:11 stretcher_alcove:11:22 stretcher_alcove:22:1e9; do run_r $c; done
S=$(date +%s); $R/run270.sh $O/stretcher_back stretcher_back off on main,top; echo "check stretcher_back $(( $(date +%s)-S )) s"
for c in stretcher_back:0:14 stretcher_back:14:28 stretcher_back:28:42 stretcher_back:42:56 stretcher_back:56:70 stretcher_back:70:1e9; do run_r $c; done
echo ALLDONE
```


### pipe270t.sh

```bash
#!/bin/bash
# 依頼270：⑩-2 の真上だけ撮り直す（真上のカメラを広くした closeup270_top.json）
R=/tmp/c270/tools; O=/tmp/c270/out
for c in 0:14 14:28 28:42 42:56 56:70 70:1e9; do IFS=: read a b <<< "$c"; S=$(date +%s); $R/run270.sh $O/stretcher_back_t stretcher_back on off top $a $b; echo "top $a-$b $(( $(date +%s)-S )) s $(ls $O/stretcher_back_t/frames/stretcher_back_top | wc -l)"; done
echo ALLDONE
```


### robot270.py

```python
"""依頼270：ハコブくんの動き（229 の決まり Closeup229.cs の StepSpeed・StepLat を Python に写した）と、くぼみに入る・下がる・出る。
make_script270.py と feas270.py が使う。"""
import math

FPS = 30; DT = 1.0 / FPS
R = dict(cruise=0.6, slow=0.5, accel=0.4, decel=0.4, jerk=1.0, detect=6.0, react=0.1, margin=2.4, gap_slow=0.4, gap_stop=0.15,
         lane=-0.33, wall_clear=0.053, lat_max=0.15, lat_angle=15.0, lat_accel=0.25, kx=2.0, lat_done=0.03, resume_angle=10.0,
         turn_rate=30.0, half_len=0.38, slack=0.006)
RX0, RX1, RZ0, RZ1 = -0.33, 0.33, -0.380, 0.382      # ハコブくんの外形（根から。Unity で測った値）


def f32(x):
    return x


def step_speed(rv, ra, vT, dt=DT):
    dvT = vT - rv
    aD = 0.0 if abs(dvT) < 1e-6 else math.copysign(min(R["accel"] if dvT > 0 else R["decel"], math.sqrt(2 * R["jerk"] * abs(dvT))), dvT)
    d = R["jerk"] * dt
    ra = aD if abs(aD - ra) <= d else ra + math.copysign(d, aD - ra)
    rvn = rv + ra * dt
    if abs(dvT) > 1e-6 and (math.copysign(1, vT - rvn) != math.copysign(1, dvT) or abs(vT - rvn) < 0.001):
        rvn = vT; ra = 0.0
    return max(0.0, rvn), ra


def step_lat(rx, th, xT, rv, ang, xWall, sgn=1.0, dt=DT):
    """229 の StepLat。sgn=-1 は後ろへ進む（依頼270 の下がる動き）。向き th の時、横の速さは sgn·rv·tan(th)"""
    if rv <= 1e-4: return rx, th
    dx = xT - rx
    vdes = math.copysign(min(min(abs(dx) * R["kx"], math.sqrt(2 * R["lat_accel"] * abs(dx))), R["lat_max"]), dx) if dx != 0 else 0.0
    thd = math.degrees(math.atan2(vdes * sgn, rv))
    clear = math.degrees(math.asin(min(1.0, max(0.0, (rx - xWall + R["slack"]) / R["half_len"])))) if xWall is not None else 90.0
    lim = min(ang, clear)
    thd = max(-lim, min(lim, thd))
    d = R["turn_rate"] * dt
    th = thd if abs(thd - th) <= d else th + math.copysign(d, thd - th)
    th = max(-max(lim, 0), min(max(lim, 0), th))
    rx += sgn * rv * math.tan(math.radians(th)) * dt
    return rx, th


def corners(rx, rz, th):
    c, s = math.cos(math.radians(th)), math.sin(math.radians(th))
    out = []
    for lx, lz in ((RX0, RZ0), (RX1, RZ0), (RX0, RZ1), (RX1, RZ1)):
        out.append((rx + lx * c + lz * s, rz - lx * s + lz * c))
    return out
```


### run270.sh

```bash
#!/bin/bash
# 依頼270 使い方: run270.sh <出力フォルダ> <場面 stretcher_alcove|stretcher_back> <コマ on|off> [静止画 on|off] [views] [from] [to]
OUT="$1"; SH="$2"; FR="${3:-off}"; ST="${4:-off}"; VW="${5:-main,top}"; FROM="${6:--1}"; TO="${7:-1e9}"
UNTIL=$(python3 -c "print($TO + 0.05 if $TO < 1e8 else 1e9)")
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup270.Run \
   -c270Out "$OUT" -c270Shot "$SH" -c270Frames "$FR" -c270Stills "$ST" -c270Views "$VW" -c270From "$FROM" -c270To "$TO" -c270Until "$UNTIL" -logFile "$OUT/unity_${FROM}_${TO}.log"
echo "exit $?"
```


### screen270.py

```python
#!/usr/bin/env python3
"""依頼270：帯（黄 #F2C230）「下がります」だけの絵 c270_back_band.png（screen237.py の band() と同じ描き方。帯の下は透明）。
確かめ：同じ描き方で「お届け完了」→ c223_done_band.png・「お待ちしています」→ c235_wait_band.png・「通れません」（黄）→ c237_stuck_band.png と画素まで同じ
使い方：python3 screen270.py <台本の JSON（screen_ui）> <Textures フォルダ> <screen218.py のフォルダ> <出力フォルダ>"""
import importlib.util, json, sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
js = json.load(open(sys.argv[1])); tex = Path(sys.argv[2]); s218dir, out = sys.argv[3], Path(sys.argv[4])
spec = importlib.util.spec_from_file_location("s218", str(Path(s218dir) / "screen218.py")); m = importlib.util.module_from_spec(spec)
argv0 = sys.argv; sys.argv = sys.argv[:1]; spec.loader.exec_module(m); sys.argv = argv0
S = js["screen_ui"]
def band(text, k=0.46, color=None):
    W = int(S["tex_w"]); H = int(round(W / float(S["aspect"]))); R = int(S["corner_r"] * H)
    mask = Image.new("L", (W, H), 0); ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, H - 1], radius=R, fill=255)
    bh = int(0.2 * H)
    img = Image.new("RGBA", (W, H), m.hexc(S["bg"])); d = ImageDraw.Draw(img)
    d.rectangle([0, 0, W, bh], fill=m.hexc(color or S["band"], int(S.get("band_alpha", 235))))
    d.text((W // 2, bh // 2), text, font=m.font(bh * k), fill=m.hexc(S["fg"]) if color is None else (30, 30, 30, 255), anchor="mm")
    a = img.split()[3]; img.putalpha(Image.composite(a, Image.new("L", (W, H), 0), mask))
    b = np.array(img); b[bh + 1:, :, :] = 0
    return b
for txt, fn, col in (("お届け完了", "c223_done_band.png", None), ("お待ちしています", "c235_wait_band.png", None), ("通れません", "c237_stuck_band.png", "#F2C230")):
    ref = np.array(Image.open(tex / fn).convert("RGBA")); chk = band(txt, color=col)
    print("確かめ：", txt, "を描くと", fn, "と同じ", chk.shape == ref.shape and bool((chk == ref).all()))
Image.fromarray(band("下がります", color="#F2C230")).save(out / "c270_back_band.png"); print("作った絵: c270_back_band.png 下がります（黄・帯だけ）")
```



## 作業ログ ― 依頼271 のコード（KIOXIA の 20261123_closeup271/tools/）


### Closeup271.cs

```csharp
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace ServiceSim.Closeups.EditorTools
{
    /// <summary>
    /// 依頼271：要所の場面 ⑪「曲がり角で車いすと出会う」。場面 corner_fast（⑪-1 角でも 0.8 m/秒のまま）・corner_slow（⑪-2 角の手前で 0.4 m/秒）。
    /// 台本は closeup271_script.json（make_script271.py）。Closeup236.cs（229 の車いす・茂さん・大城さん・真上の型）を土台に、ハコブくんは 270 と同じく台本の値をそのまま置く形にした。
    ///   ・廊下：台本の rooms（L の字）。当たりは "solid" の箱
    ///   ・ハコブくん：台本の c271.robot（毎コマ x・z・向き・速さ・決まりの状態。make_script271.py が braking の決まりで出した値）
    ///   ・大城さんの根・向き・歩き：台本の nurse（毎コマ）。車いすは 228・229 と同じく大城さんの根の前に固く付けて動かす（向きも一緒）。前の車輪は引っぱりの形
    ///   ・画面：c271.screen（face・stop＝帯（黄）「止まります」・yield＝帯（ミント）「お先にどうぞ」・yield_happy＝帯のまま目まで笑う顔）
    ///   ・確かめ：当たり（ハコブくんと車いす・茂さん・大城さん／車いす・茂さん・大城さん・ハコブくんと壁/手すり／大城さんと車いす／手が握りの中）・手が握りから離れない・車輪の横すべり・
    ///     1 コマの骨の動き・肘が肩より上にならない・足のすべり・止まっている間に動かない・見つけた時（角の壁の線 x 0.90 より手前に出た頂点）の距離
    ///   ・真上の型 frames/<場面>_top_obj は赤＝ハコブくん・緑＝車いすと茂さんと大城さん（手を握りにのせたままなので 1 つのもの）
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup271.Run \
    ///                 -c271Out <出力フォルダ> -c271Shot <場面> [-c271Script closeup271_script.json] [-c271Frames on|off] [-c271Stills on|off] [-c271Views main,top] [-c271From 秒] [-c271To 秒] [-c271Until 秒]
    /// 場面（Closeup_Handover.unity）は保存しない。
    /// </summary>
    public static class Closeup271
    {
        const string Root = CloseupShoot.Root;
        const string TexDir = CloseupShoot.TexDir;
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string F(float v, string f = "0.0000") { return v.ToString(f, IC); }
        const int LayerChair = 30, LayerNurse = 31;
        const int LayerMask232 = 29;

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        class RobotShape
        {
            public float band = 0.02f, top, minX, maxX, minZ, maxZ;
            public List<Vector2[]> hulls = new List<Vector2[]>();
            public Vector2[] all;
            public Vector3[] verts;
        }

        static Vector2[] Hull(List<Vector2> p)
        {
            if (p.Count < 3) return null;
            p.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.y.CompareTo(b.y));
            var h = new Vector2[p.Count * 2]; int k = 0;
            Func<Vector2, Vector2, Vector2, float> cr = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
            for (int i = 0; i < p.Count; i++) { while (k >= 2 && cr(h[k - 2], h[k - 1], p[i]) <= 0) k--; h[k++] = p[i]; }
            for (int i = p.Count - 2, t = k + 1; i >= 0; i--) { while (k >= t && cr(h[k - 2], h[k - 1], p[i]) <= 0) k--; h[k++] = p[i]; }
            var r = new Vector2[k - 1]; Array.Copy(h, r, k - 1); return r;
        }

        static float PolyDist(Vector2[] poly, Vector2 q)
        {
            bool inside = true; float best = float.MaxValue;
            for (int i = 0; i < poly.Length; i++)
            {
                Vector2 a = poly[i], b = poly[(i + 1) % poly.Length];
                Vector2 e = b - a;
                if (e.x * (q.y - a.y) - e.y * (q.x - a.x) < 0) inside = false;
                float u = Mathf.Clamp01(Vector2.Dot(q - a, e) / Mathf.Max(1e-12f, e.sqrMagnitude));
                best = Mathf.Min(best, (a + e * u - q).sqrMagnitude);
            }
            return inside ? 0f : Mathf.Sqrt(best);
        }

        static RobotShape MeasureRobot(CloseupDirector dir)
        {
            var rs = new RobotShape();
            var pts = new List<Vector3>();
            foreach (var mf in dir.robot.GetComponentsInChildren<MeshFilter>(true))
            {
                if (dir.screenOverlay != null && mf.gameObject == dir.screenOverlay.gameObject) continue;
                if (!mf.gameObject.activeInHierarchy || mf.sharedMesh == null) continue;
                foreach (var v in mf.sharedMesh.vertices) pts.Add(dir.robot.InverseTransformPoint(mf.transform.TransformPoint(v)));
            }
            rs.verts = pts.ToArray();
            rs.top = float.MinValue; rs.minX = rs.minZ = float.MaxValue; rs.maxX = rs.maxZ = float.MinValue;
            foreach (var p in pts) { rs.top = Mathf.Max(rs.top, p.y); rs.minX = Mathf.Min(rs.minX, p.x); rs.maxX = Mathf.Max(rs.maxX, p.x); rs.minZ = Mathf.Min(rs.minZ, p.z); rs.maxZ = Mathf.Max(rs.maxZ, p.z); }
            int nb = Mathf.CeilToInt(rs.top / rs.band) + 1;
            var bl = new List<Vector2>[nb]; for (int i = 0; i < nb; i++) bl[i] = new List<Vector2>();
            var al = new List<Vector2>();
            foreach (var p in pts)
            {
                int b = Mathf.Clamp(Mathf.FloorToInt(p.y / rs.band), 0, nb - 1);
                bl[b].Add(new Vector2(p.x, p.z)); al.Add(new Vector2(p.x, p.z));
                int b2 = Mathf.Clamp(Mathf.FloorToInt((p.y + 0.005f) / rs.band), 0, nb - 1); if (b2 != b) bl[b2].Add(new Vector2(p.x, p.z));
                b2 = Mathf.Clamp(Mathf.FloorToInt((p.y - 0.005f) / rs.band), 0, nb - 1); if (b2 != b) bl[b2].Add(new Vector2(p.x, p.z));
            }
            for (int i = 0; i < nb; i++) rs.hulls.Add(Hull(bl[i]));
            for (int i = 0; i < nb; i++)
                if (rs.hulls[i] == null)
                {
                    var m = new List<Vector2>();
                    for (int j = i - 1; j >= 0; j--) if (rs.hulls[j] != null) { m.AddRange(rs.hulls[j]); break; }
                    for (int j = i + 1; j < nb; j++) if (bl[j].Count >= 3) { m.AddRange(Hull(new List<Vector2>(bl[j]))); break; }
                    rs.hulls[i] = Hull(m);
                }
            rs.all = Hull(al);
            return rs;
        }

        static float RobotDist(RobotShape rs, Vector3 p, float cut)
        {
            Vector2 q = new Vector2(p.x, p.z);
            float dAll = PolyDist(rs.all, q);
            float dyTop = Mathf.Max(0f, p.y - rs.top), dyBot = Mathf.Max(0f, -p.y);
            if (Mathf.Sqrt(dAll * dAll + Mathf.Max(dyTop, dyBot) * Mathf.Max(dyTop, dyBot)) > cut) return float.MaxValue;
            float best = float.MaxValue;
            int b0 = Mathf.FloorToInt((p.y - cut) / rs.band), b1 = Mathf.FloorToInt((p.y + cut) / rs.band);
            for (int b = Mathf.Max(0, b0); b <= Mathf.Min(rs.hulls.Count - 1, b1); b++)
            {
                if (rs.hulls[b] == null) continue;
                float y0 = b * rs.band, y1 = y0 + rs.band;
                float dy = p.y < y0 ? y0 - p.y : p.y > y1 ? p.y - y1 : 0f;
                if (dy >= best) continue;
                float dh = PolyDist(rs.hulls[b], q);
                best = Mathf.Min(best, Mathf.Sqrt(dh * dh + dy * dy));
            }
            return best;
        }

        class SolidBox { public string name; public Vector3 min, max; public bool rail; }
        static float PointBoxDist(Vector3 p, Vector3 mn, Vector3 mx)
        {
            Vector3 q = new Vector3(Mathf.Clamp(p.x, mn.x, mx.x), Mathf.Clamp(p.y, mn.y, mx.y), Mathf.Clamp(p.z, mn.z, mx.z));
            return Vector3.Distance(p, q);
        }
        static bool InBox(Vector3 p, Vector3 mn, Vector3 mx) { return p.x > mn.x && p.x < mx.x && p.y > mn.y && p.y < mx.y && p.z > mn.z && p.z < mx.z; }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c271Out", "");
            if (outDir == "") throw new Exception("-c271Out がない");
            string scriptName = CloseupArgs.Get("-c271Script", "closeup271_script.json");
            string shotName = CloseupArgs.Get("-c271Shot", "corner_fast");
            bool frames = CloseupArgs.Get("-c271Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c271Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c271Views", "main,top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c271From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c271To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topAll = JsonValue.Parse(File.ReadAllText(Root + "/closeup271_top.json"), out topErr); if (topAll == null) throw new Exception("closeup271_top.json: " + topErr);
                var topJs = topAll[shotName];
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（L の字。台本の rooms の「廊下…」）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor271").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C271_" + k };
                    Color c; ColorUtility.TryParseHtmlString(js["colors"][k].S(), out c); m.color = c; m.SetFloat("_Glossiness", 0.15f);
                    mats[k] = m;
                }
                var rooms = js["rooms"];
                int nCorr = 0;
                for (int i = 0; i < rooms.Count; i++)
                {
                    var r = rooms[i];
                    if (!r["name"].S("").StartsWith("廊下")) continue;
                    Vector3 a = CloseupDirector.V3(r["min"]), b = CloseupDirector.V3(r["max"]);
                    var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    UnityEngine.Object.DestroyImmediate(go.GetComponent<Collider>());
                    go.name = r["name"].S(); go.transform.SetParent(corr, false);
                    go.transform.position = (a + b) * 0.5f; go.transform.localScale = b - a;
                    var rr = go.GetComponent<Renderer>(); rr.sharedMaterial = mats[r["mat"].S()];
                    if (!r["shadow"].B(false)) rr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
                    if (r["solid"].B(false)) solids.Add(new SolidBox { name = r["name"].S(), min = a, max = b, rail = r["rail"].B(false) });
                    nCorr++;
                }
                log.AppendLine("廊下の箱 " + nCorr + " 個（当たりを数える箱 " + solids.Count + " 個）");

                // ---- 看護師：描くのは焼いた形（229 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked271").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, false);
                    var mf = g.AddComponent<MeshFilter>(); mf.sharedMesh = new Mesh();
                    var mr = g.AddComponent<MeshRenderer>(); mr.sharedMaterials = smr.sharedMaterials;
                    smr.enabled = false;
                    proxies.Add(new KeyValuePair<SkinnedMeshRenderer, MeshFilter>(smr, mf));
                };
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true)) addProxy(smr);
                Action syncProxies = () =>
                {
                    foreach (var kv in proxies)
                    {
                        bool on = kv.Key.gameObject.activeInHierarchy;
                        kv.Value.gameObject.SetActive(on);
                        if (!on) continue;
                        kv.Key.BakeMesh(kv.Value.sharedMesh, true);
                        kv.Value.sharedMesh.RecalculateBounds();
                        kv.Value.transform.SetPositionAndRotation(kv.Key.transform.position, kv.Key.transform.rotation);
                    }
                };
                var partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in parts)
                {
                    var bw = smr.sharedMesh.boneWeights;
                    var cat = new string[smr.sharedMesh.vertexCount];
                    for (int i = 0; i < cat.Length; i++) cat[i] = bw.Length > i ? HandCat(smr.bones[bw[i].boneIndex0], boneMap) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk") talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.transform.rotation) * upW;
                    float top = float.MinValue; foreach (var v in vs) top = Mathf.Max(top, Vector3.Dot(v, u));
                    for (int i = 0; i < vs.Length; i++) { float h = Vector3.Dot(vs[i], u) - top; vs[i] -= u * (h * (1f - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 車いすと茂さん（228 の置き方。茂さんは車いすの子）
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair271").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita271").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF) { var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name; }
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000")));
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                var nurseColGo = new GameObject("NurseCol271"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                var faceR = dir.face.GetComponent<Renderer>();
                var faceAlb = new Dictionary<string, Texture2D>(); var faceEmi = new Dictionary<string, Texture2D>();
                foreach (var fk in new[] { "closed", "small", "large", "happy" })
                {
                    faceAlb[fk] = PrepTex(TexDir + "/face218_" + fk + "_albedo.png", ""); faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", "");
                }
                var scrTex = new Dictionary<string, Texture2D> { { "stop", ScreenTex(TexDir + "/c271_stop_band.png") }, { "yield", ScreenTex(TexDir + "/c228_yield_band.png") } };

                int fps = js["fps"].I(30), W = js["width"].I(1920), H = js["height"].I(1080), SS = js["supersample"].I(2);
                int iters = js["nurse"]["ik_iters"].I(3);
                float dt = 1f / fps;

                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c271"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                float wcAhead = C["wc_ahead_m"].F();
                var robotKeys = C["robot"]; var scrKeys = C["screen"];
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();
                var EV = C["events"]; float detT = EV["det"].F(), stopRT = EV["stopR"].F();
                float cornerWall = C["corner"]["wall"].F(0.9f), detRange = C["corner"]["detect_range_m"].F(6f);

                dir.Apply(0f, dt);
                var rs = MeasureRobot(dir);
                log.AppendLine(string.Format(IC, "ハコブくんの外形（根から）: 幅 x {0:0.000}〜{1:0.000}・奥行 z {2:0.000}〜{3:0.000}・高さ {4:0.000} m", rs.minX, rs.maxX, rs.minZ, rs.maxZ, rs.top));

                // ---- 確かめ
                string[] cats = { "車いす", "茂さん", "大城さん" };
                var gapMin = new Dictionary<string, float>(); var gapMinT = new Dictionary<string, float>(); var gapMinWhere = new Dictionary<string, string>();
                foreach (var c in cats) { gapMin[c] = float.MaxValue; gapMinT[c] = -1f; gapMinWhere[c] = ""; }
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotSolidMin = float.MaxValue, nurseSolidMin = float.MaxValue;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                float elbowOver = -9f, elbowOverT = -1f; string elbowOverSide = "";
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float wheelSlipMax = 0f, wheelSlipT = -1f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f, casYawMaxT = -1f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;
                float handGripMin = float.MaxValue; string handGripWhere = "";
                float detUnityT = -1f, detUnityDist = float.NaN, detUnityGap = float.NaN; string detUnityWhat = "";
                float gapAtDet = float.NaN, distAtDet = float.NaN, gapAtStop = float.NaN, peopleGapAtStop = float.NaN;
                float stopMove = 0f; int stopFrames = 0; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; string prevMode = "";
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c271Until", "1e9"), IC)) * fps);
                nFrames = Mathf.Min(nFrames, robotKeys.Count);
                string fdirM = Path.Combine(outDir, "frames", shotName), fdirT = Path.Combine(outDir, "frames", shotName + "_top");
                bool vMain = frames && views.Contains("main"), vTop = frames && views.Contains("top");
                if (vMain) Directory.CreateDirectory(fdirM);
                if (vTop) { Directory.CreateDirectory(fdirT); Directory.CreateDirectory(fdirT + "_mask"); Directory.CreateDirectory(fdirT + "_obj"); }
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,mode,screen,gap_m,gap_chair,gap_morita,gap_oshiro,gap_people,rail_gap_m,chair_solid_m,palm_grip_l,palm_grip_r,head_yaw,nurse_mouth,m_mouth,chair_x,chair_z,chair_yaw,nurse_x,nurse_z,nurse_yaw,visible_near_m\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,robot_fx,robot_fz,robot_fpx,robot_fpy\n");
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    if (f > 0 && f % 150 == 0) GC.Collect();
                    var rk = robotKeys[f];
                    float rx = rk[0].F(), rz = rk[1].F(), ryaw = rk[2].F(), rv = rk[3].F(); string mode = rk[4].S();

                    // ---------- 看護師（台本の根・向き・歩き）・ハコブくん（台本の値）
                    dir.Apply(t, dt);
                    dir.robot.position = O + new Vector3(rx, 0f, rz);
                    dir.robot.rotation = Quaternion.Euler(0f, ryaw, 0f);
                    int nml = f < nurseMouth.Count ? nurseMouth[f].I() : 0;
                    if (nml > 0) dir.nurse.mouth = "talk";
                    curMouthScale = nml > 0 ? nmScale[nml].F() : 1f;
                    dir.nurse.Step(f == 0 ? 0f : dt, iters);
                    Transform nr = dir.nurse.transform;

                    // ---------- 車いす：看護師の根の前に固く付ける（228・229 と同じ）
                    chair.SetPositionAndRotation(nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead), nr.rotation);
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        float sideNow = 0f;
                        if (haveChairPrev)
                        {
                            // 後ろの車輪の横すべり：コマの前後の向きの間（真ん中）の横で数える（229 と同じ）
                            Vector3 rgt = (chair.right + prevChairRight).normalized;
                            sideNow = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt)));
                            if (sideNow > wheelSlipMax) { wheelSlipMax = sideNow; wheelSlipT = t; }
                        }
                        prevHubL = hubL; prevHubR = hubR;
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(sideNow, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 茂さん：顔の向き・うなずき（この場面では 0）・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面（帯：stop＝黄「止まります」・yield＝ミント「お先にどうぞ」・yield_happy＝帯のまま目まで笑う顔）
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    string skey = "face"; for (int k = 0; k < scrKeys.Count; k++) if (scrKeys[k][0].F() <= t + 1e-4f) skey = scrKeys[k][1].S();
                    bool happyNow = skey == "yield_happy";
                    string bandKey = happyNow ? "yield" : skey;
                    bool bandNow = scrTex.ContainsKey(bandKey);
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", scrTex[bandKey]); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy" : rmo != "mid" ? rmo : "";
                    { var mpf = new MaterialPropertyBlock(); if (fk != "") { mpf.SetTexture("_MainTex", faceAlb[fk]); mpf.SetTexture("_EmissionMap", faceEmi[fk]); } faceR.SetPropertyBlock(mpf); }
                    string scrNow = (bandNow ? "帯" + bandKey : "") + (happyNow ? "目まで笑う顔" : "基本");
                    if (scrNow != prevScr) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr) + " → " + scrNow);
                    prevScr = scrNow;

                    if (frames && t < fromT - 1e-4f) continue;
                    Physics.SyncTransforms();

                    // ---------- 当たり・すき間
                    var gapNow = new Dictionary<string, float>(); foreach (var c in cats) gapNow[c] = float.MaxValue;
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix, toC = chair.worldToLocalMatrix;
                    Vector3 rFront = dir.robot.TransformPoint(new Vector3(0f, 0f, rs.maxZ)); rFront.y = 0f;
                    float visNear = float.MaxValue; string visWhat = "";
                    Action<Vector3, string, string> seeVert = (w, cat, what) =>
                    {
                        Vector3 lc = w - O;
                        if (lc.x < cornerWall) { float dd = new Vector2(w.x - rFront.x, w.z - rFront.z).magnitude; if (dd < visNear) { visNear = dd; visWhat = cat + " " + what; } }
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        if (lr.x < rs.minX - 1.6f || lr.x > rs.maxX + 1.6f || lr.z < rs.minZ - 1.6f || lr.z > rs.maxZ + 1.6f) return;
                        float d = RobotDist(rs, lr, Mathf.Min(gapNow[cat], 1.5f));
                        if (d < gapNow[cat]) { gapNow[cat] = d; if (d < gapMin[cat]) { gapMin[cat] = d; gapMinT[cat] = t; gapMinWhere[cat] = what; } }
                    };
                    bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key; var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    int pi = -1;
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "大城さん", smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            if (cat[i] != "")
                            {
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i]; } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                            }
                        }
                    }
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    bool csHit = false; float chairSolidNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす", chairVertsPart[k]);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidNow = Mathf.Min(chairSolidNow, dd);
                                if (s.rail) chairRailMin = Mathf.Min(chairRailMin, dd);
                            }
                        }
                    }
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん", smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidNow = Mathf.Min(chairSolidNow, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    chairSolidMin = Mathf.Min(chairSolidMin, chairSolidNow);
                    float gapAll = Mathf.Min(gapNow["車いす"], Mathf.Min(gapNow["茂さん"], gapNow["大城さん"]));
                    float gapPeople = Mathf.Min(gapNow["茂さん"], gapNow["大城さん"]);
                    if (gapAll <= 0f) hitRG++;
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    // 見つける（Unity の頂点で：角の壁の線 x 0.90 より手前に出た点が、ハコブくんの前の端から 6.0 m 以内。走っている間だけ）
                    if (detUnityT < 0f && mode == "cruise" && visNear <= detRange) { detUnityT = t; detUnityDist = visNear; detUnityGap = gapAll; detUnityWhat = visWhat; }
                    if (Mathf.Abs(t - detT) < 0.5f * dt) { gapAtDet = gapAll; distAtDet = visNear; }
                    if (Mathf.Abs(t - stopRT) < 0.5f * dt) { gapAtStop = gapAll; peopleGapAtStop = gapPeople; }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        foreach (var s in solids)
                        {
                            if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                            if (InBox(w, s.min, s.max)) { rsHit = true; if (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotSolidMin = Mathf.Min(robotSolidMin, railGapNow);
                    // 止まっている間に動かない（台本の mode が stopped・stopped2）
                    if (mode == "stopped" || mode == "stopped2")
                    {
                        if (mode != prevMode) { stopPos = dir.robot.position; stopYaw = ryaw; }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f); stopFrames++;
                    }
                    prevMode = mode;

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    for (int s = 0; s < 2; s++)
                    {
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), dir.nurse.hands[s].palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                    }

                    // 骨：1 コマの動き（根の動きを除く）・肘が肩より上にならない
                    Vector3 rootNow = nr.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev && f > vFrom)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    foreach (var sd in new[] { new[] { HumanBodyBones.LeftUpperArm, HumanBodyBones.LeftLowerArm }, new[] { HumanBodyBones.RightUpperArm, HumanBodyBones.RightLowerArm } })
                    {
                        float over = an.GetBoneTransform(sd[1]).position.y - an.GetBoneTransform(sd[0]).position.y;
                        if (over > elbowOver) { elbowOver = over; elbowOverT = t; elbowOverSide = sd[1].ToString(); }
                    }
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（229 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; prevInWalk = inWalk;
                        float slideNow = 0f;
                        for (int i = 0; i < sv.Length; i++)
                        {
                            Vector3 w = sm.MultiplyPoint3x4(sv[i]);
                            if ((w - lfp).sqrMagnitude < (w - rfp).sqrMagnitude) lMin = Mathf.Min(lMin, w.y); else rMin = Mathf.Min(rMin, w.y);
                            bool on = w.y <= 0.01f;
                            if (on && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            float acc = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, acc);
                        }
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    string camName = CutAt(shot, t);
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + mode + "," + scrNow + "," +
                                   F(gapAll) + "," + F(gapNow["車いす"]) + "," + F(gapNow["茂さん"]) + "," + F(gapNow["大城さん"]) + "," + F(gapPeople) + "," + F(railGapNow) + "," + F(chairSolidNow) + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + nml + "," + mMouth + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," +
                                   F(nr.position.x - O.x) + "," + F(nr.position.z - O.z) + "," + F(nr.eulerAngles.y, "0.000") + "," + (visNear < float.MaxValue ? F(visNear) : ""));

                    // ---------- 真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根と前の端）
                    {
                        SetTop271(dir.cam, topJs, O);
                        Func<Vector3, Vector2> px = w => { Vector3 vp = dir.cam.WorldToViewportPoint(w); return new Vector2(vp.x * W, (1f - vp.y) * H); };
                        Vector3 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot), pf = px(rFront);
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.z - O.z, "0.00000") + "," + F(pa.x, "0.000") + "," + F(pa.y, "0.000") + "," +
                                          F(rRoot.x - O.x, "0.00000") + "," + F(rRoot.z - O.z, "0.00000") + "," + F(pr.x, "0.000") + "," + F(pr.y, "0.000") + "," +
                                          F(rFront.x - O.x, "0.00000") + "," + F(rFront.z - O.z, "0.00000") + "," + F(pf.x, "0.000") + "," + F(pf.y, "0.000"));
                        if (f == 0)
                        {
                            var cj = new StringBuilder("{\n");
                            cj.AppendLine(string.Format(IC, "  \"center_x\": {0}, \"center_z\": {1}, \"height\": {2}, \"ortho_size\": {3}, \"aspect\": {4:0.000000}, \"orthographic\": {5},",
                                topJs["center_x"].F(), topJs["center_z"].F(), topJs["height"].F(), topJs["ortho_size"].F(), dir.cam.aspect, dir.cam.orthographic ? "true" : "false"));
                            var p00 = px(O); var p10 = px(O + Vector3.right); var p01 = px(O + Vector3.forward);
                            cj.AppendLine(string.Format(IC, "  \"px_origin\": [{0:0.0000}, {1:0.0000}], \"px_per_x\": [{2:0.0000}, {3:0.0000}], \"px_per_z\": [{4:0.0000}, {5:0.0000}]",
                                p00.x, p00.y, p10.x - p00.x, p10.y - p00.y, p01.x - p00.x, p01.y - p00.y));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top271_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && inRange)
                    {
                        syncProxies(); scaleMouth();
                        if (vMain) { SetCam(dir.cam, shot["cameras"][camName], O, dir); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirM, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            SetTop271(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f)));
                            var body = BodyRenderers(new[] { dir.robot, chair, mor, proxyRoot, dir.nurse.transform });
                            if (!log.ToString().Contains("依頼232 体の型")) LogRenderers232(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // もの別の型：赤＝ハコブくん・緑＝車いすと茂さんと大城さん（手を握りにのせたままなので 1 つのもの。236 と同じ考え）
                            var grp = new List<Renderer>[2]; for (int g = 0; g < 2; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[rd.transform.IsChildOf(dir.robot) ? 0 : 1].Add(rd);
                            var obj = new Texture2D(W, H, TextureFormat.RGB24, false);
                            var pxs = new Color32[W * H];
                            for (int g = 0; g < 2; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < pxs.Length; i++) { if (g == 0) pxs[i].r = mp[i].r; else pxs[i].g = mp[i].r; pxs[i].a = 255; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(pxs); obj.Apply();
                            SavePng(obj, Path.Combine(fdirT + "_obj", string.Format("f_{0:00000}.png", f)));
                        }
                    }
                    for (int s = 0; stillsOn && s < (stills != null ? stills.Count : 0); s++)
                    {
                        if (Mathf.RoundToInt(stills[s][0].F() * fps) != f) continue;
                        syncProxies(); scaleMouth();
                        if (stills[s][1].S() == "top") SetTop271(dir.cam, topJs, O); else SetCam(dir.cam, shot["cameras"][stills[s][1].S()], O, dir);
                        string sn = stills[s][2].S();
                        string sd = Path.Combine(outDir, sn.StartsWith("chk_") ? "stills_check" : "stills"); Directory.CreateDirectory(sd);
                        SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(sd, shotName + "_" + sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames271.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top271.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones271.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet271.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc271.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName + "（" + nFrames + " コマ）");
                tab.AppendLine(string.Format(IC, "見つけた（台本）\t{0:0.000} 秒・その時の外形のすき間（Unity）{1:0.000} m・前の端から一番近い見える点 {2:0.000} m", detT, gapAtDet, distAtDet));
                tab.AppendLine(string.Format(IC, "見つけた（Unity の頂点で数え直し）\t{0:0.000} 秒・前の端からの距離 {1:0.000} m（{2}）・外形のすき間 {3:0.000} m", detUnityT, detUnityDist, detUnityWhat, detUnityGap));
                tab.AppendLine(string.Format(IC, "止まった（台本）\t{0:0.000} 秒・その時の外形のすき間 {1:0.000} m（人だけ {2:0.000} m）", stopRT, gapAtStop, peopleGapAtStop));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・大城さん）{0}・車いす/茂さんと壁/手すり {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・大城さんと車いす {5}・手が握りの中 {6}（{7}）・大城さんと壁/手すり {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                foreach (var c in cats) tab.AppendLine(string.Format(IC, "ハコブくんと{0}の一番近い距離\t{1:0.000} m（{2:0.000} 秒・{3}）", c, gapMin[c], gapMinT[c], gapMinWhere[c]));
                tab.AppendLine(string.Format(IC, "壁・手すりとのすき間\tハコブくん {0:0.000} m・車いす/茂さん {1:0.000} m（手すり {2:0.000} m）・大城さん {3:0.000} m", robotSolidMin, chairSolidMin, chairRailMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）・手の頂点と握りの面 一番近い {5:0.0000} m（{6}）",
                                              palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT, handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ（{6:0.000} 秒）・前の車輪の横すべり {7:0.00000} m/コマ・前の車輪の向きの最大 {8:0.00}°（{9:0.000} 秒）",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, wheelSlipT, casterSlipMax, casYawMax, casYawMaxT));
                tab.AppendLine(string.Format(IC, "足（大城さん）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t大城さん 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "肘と肩\t肘と肩の高さの差の最大 {0:0.000} m（{1}・{2:0.000} 秒。正は肘が上）", elbowOver, elbowOverSide, elbowOverT));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check271.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events271.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C271] done\n" + log + "\n" + tab);
        }

        /// <summary>カメラ：pos・look は廊下の原点から。follow "robot_pose"・"nurse_pose" は根の位置と向きから（その物の前が +z）</summary>
        static void SetCam(Camera cam, JsonValue C, Vector3 O, CloseupDirector dir)
        {
            if (C == null || C.IsNull) throw new Exception("台本にカメラが無い");
            cam.orthographic = false; cam.ResetAspect();
            string fo = C["follow"].S("");
            if (fo == "robot_pose" || fo == "nurse_pose")
            {
                Transform r = fo == "robot_pose" ? dir.robot : dir.nurse.transform;
                Vector3 rp = r.position; Quaternion rq = Quaternion.Euler(0f, r.eulerAngles.y, 0f);
                cam.transform.position = rp + rq * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((rp + rq * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + CloseupDirector.V3(C["pos"]);
            cam.transform.rotation = Quaternion.LookRotation((O + CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>動かない真上のカメラ（正射影）。画面の上の向きは closeup271_top.json の up（既定 +z）</summary>
        static void SetTop271(Camera cam, JsonValue T, Vector3 O)
        {
            cam.orthographic = true;
            cam.orthographicSize = T["ortho_size"].F();
            cam.transform.position = O + new Vector3(T["center_x"].F(), T["height"].F(), T["center_z"].F());
            Vector3 up = T.Has("up") ? CloseupDirector.V3(T["up"]) : Vector3.forward;
            cam.transform.rotation = Quaternion.LookRotation(Vector3.down, up);
            cam.nearClipPlane = 0.3f; cam.farClipPlane = T["height"].F() + 5f;
            cam.aspect = T["width_px"].F(1920f) / T["height_px"].F(1080f);
        }
        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        static string HandCat(Transform b, Dictionary<Transform, HumanBodyBones> map)
        {
            for (var t = b; t != null; t = t.parent)
            {
                HumanBodyBones hb;
                if (!map.TryGetValue(t, out hb)) continue;
                string s = hb.ToString();
                if (hb == HumanBodyBones.LeftHand || (s.StartsWith("Left") && (s.Contains("Thumb") || s.Contains("Index") || s.Contains("Middle") || s.Contains("Ring") || s.Contains("Little")))) return "左手";
                if (hb == HumanBodyBones.RightHand || (s.StartsWith("Right") && (s.Contains("Thumb") || s.Contains("Index") || s.Contains("Middle") || s.Contains("Ring") || s.Contains("Little")))) return "右手";
                return "";
            }
            return "";
        }

        static Texture2D ScreenTex(string path)
        {
            var ti = (TextureImporter)AssetImporter.GetAtPath(path);
            if (ti == null) throw new Exception("絵が無い: " + path);
            if (ti.textureCompression != TextureImporterCompression.Uncompressed || ti.maxTextureSize < 2048 || ti.npotScale != TextureImporterNPOTScale.None || !ti.alphaIsTransparency || !ti.mipmapEnabled || ti.wrapMode != TextureWrapMode.Clamp || !ti.sRGBTexture)
            {
                ti.textureCompression = TextureImporterCompression.Uncompressed; ti.maxTextureSize = 2048; ti.npotScale = TextureImporterNPOTScale.None;
                ti.alphaIsTransparency = true; ti.mipmapEnabled = true; ti.wrapMode = TextureWrapMode.Clamp; ti.sRGBTexture = true; ti.filterMode = FilterMode.Trilinear; ti.anisoLevel = 4;
                ti.SaveAndReimport();
            }
            var tx = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (tx == null) throw new Exception("絵が読めない: " + path);
            return tx;
        }

        static Texture2D PrepTex(string path, string like)
        {
            var tx = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (tx == null) throw new Exception("絵が無い: " + path);
            return tx;
        }

        static string CutAt(JsonValue shot, float t)
        {
            var c = shot["cuts"];
            string name = c[0][1].S();
            for (int i = 0; i < c.Count; i++) if (c[i][0].F() <= t + 1e-4f) name = c[i][1].S();
            return name;
        }

        static Camera maskCam232; static Material white232;

        /// <summary>依頼232：写る体の部品（ハコブくん・車いす・茂さん・大城さんと、写しの部品）。その時に写る物だけ</summary>
        static List<Renderer> BodyRenderers(Transform[] roots)
        {
            var list = new List<Renderer>();
            foreach (var r in roots)
                foreach (var rd in r.GetComponentsInChildren<Renderer>(false))
                    if (rd.enabled && rd.gameObject.activeInHierarchy && !list.Contains(rd)) list.Add(rd);
            return list;
        }
        /// <summary>依頼232：体に数えた部品と、数えなかった部品（廊下など）を書く</summary>
        static void LogRenderers232(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("依頼232 体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
            int n = 0;
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (!r.enabled || !r.gameObject.activeInHierarchy || body.Contains(r)) continue;
                n++; if (n <= 60) log.AppendLine(string.Format(IC, "  入れない {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
                if (r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
            }
            log.AppendLine("  入れない部品 " + n);
        }

        /// <summary>依頼232：体だけを白く写した型（黒＝床など・白＝体）。真上のカメラ（cam）を写した別のカメラで撮る。cam と部品は元のまま残す</summary>
        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam232 == null)
            {
                var g = new GameObject("MaskCam232"); maskCam232 = g.AddComponent<Camera>(); maskCam232.enabled = false;
                white232 = new Material(Shader.Find("Unlit/Color")) { name = "Mask232" }; white232.color = Color.white;
            }
            maskCam232.CopyFrom(cam);
            maskCam232.cullingMask = 1 << LayerMask232;
            maskCam232.clearFlags = CameraClearFlags.SolidColor; maskCam232.backgroundColor = Color.black;
            maskCam232.allowHDR = false; maskCam232.allowMSAA = false;
            var layers = new int[body.Count]; var mats = new Material[body.Count][]; var mpbs = new MaterialPropertyBlock[body.Count]; var hadMpb = new bool[body.Count];
            for (int i = 0; i < body.Count; i++)
            {
                layers[i] = body[i].gameObject.layer; mats[i] = body[i].sharedMaterials;
                hadMpb[i] = body[i].HasPropertyBlock(); if (hadMpb[i]) { mpbs[i] = new MaterialPropertyBlock(); body[i].GetPropertyBlock(mpbs[i]); body[i].SetPropertyBlock(null); }
                body[i].gameObject.layer = LayerMask232;
                var w = new Material[Mathf.Max(1, mats[i].Length)]; for (int k = 0; k < w.Length; k++) w[k] = white232;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam232, W, H, SS); }
            finally
            {
                for (int i = 0; i < body.Count; i++) { body[i].gameObject.layer = layers[i]; body[i].sharedMaterials = mats[i]; if (hadMpb[i]) body[i].SetPropertyBlock(mpbs[i]); }
            }
        }

        static Texture2D Shoot(Camera cam, int W, int H, int SS)
        {
            var big = RenderTexture.GetTemporary(W * SS, H * SS, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
            var small = RenderTexture.GetTemporary(W, H, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
            big.filterMode = FilterMode.Bilinear;
            cam.targetTexture = big;
            cam.Render();
            cam.targetTexture = null;
            Graphics.Blit(big, small);
            var prev = RenderTexture.active;
            RenderTexture.active = small;
            var tex = new Texture2D(W, H, TextureFormat.RGB24, false);
            tex.ReadPixels(new Rect(0, 0, W, H), 0, 0);
            tex.Apply();
            RenderTexture.active = prev;
            RenderTexture.ReleaseTemporary(big);
            RenderTexture.ReleaseTemporary(small);
            return tex;
        }

        static void SavePng(Texture2D tex, string path)
        {
            File.WriteAllBytes(path, tex.EncodeToPNG());
            UnityEngine.Object.DestroyImmediate(tex);
        }
    }
}
```


### an271.py

```python
"""依頼271：報告の表（2 本並べて）を作る。Unity の確かめの出力（frames271.csv・check271.txt）と台本（closeup271_script.json）から。
数え方：hospital-unity-params.json の count_rules（1 急に止まった 1.0 秒・2 ひやり 0.3 m・3 人がよけさせられた 2.0 m・4 立ち往生 30 秒・5 横切った 1.5 m）。
使い方：python3 an271.py <台本> <corner_fast の出力> <corner_slow の出力> <hospital-unity-params.json>"""
import csv, json, math, sys
import numpy as np
SC, DF, DS, PJ = sys.argv[1:5]
SJ = json.load(open(SC)); PR = json.load(open(PJ)); CR = PR["count_rules"]
FPS = 30; DT = 1 / FPS
def rd(d): return [r for r in csv.DictReader(open(d + "/frames271.csv"))]
def fl(x):
    try:
        v = float(x); return v if abs(v) < 1e6 else float("inf")
    except ValueError: return float("inf")
def episodes(mask):
    out = []; a = None
    for i, m in enumerate(mask):
        if m and a is None: a = i
        if not m and a is not None: out.append((a, i - 1)); a = None
    if a is not None: out.append((a, len(mask) - 1))
    return out
res = {}
for name, D in (("corner_fast", DF), ("corner_slow", DS)):
    sh = [s for s in SJ["shots"] if s["name"] == name][0]; C = sh["c271"]; ev = C["events"]; tm = C["times"]
    R = rd(D); n = len(R)
    t = np.array([fl(r["t"]) for r in R]); x = np.array([fl(r["robot_x"]) for r in R]); z = np.array([fl(r["robot_z"]) for r in R])
    yaw = np.array([fl(r["robot_yaw"]) for r in R]); v = np.array([fl(r["robot_v"]) for r in R]); mode = [r["mode"] for r in R]
    g = np.array([fl(r["gap_m"]) for r in R]); gp = np.array([fl(r["gap_people"]) for r in R])
    cx = np.array([fl(r["chair_x"]) for r in R]); cz = np.array([fl(r["chair_z"]) for r in R]); cyaw = np.array([fl(r["chair_yaw"]) for r in R])
    nx = np.array([fl(r["nurse_x"]) for r in R]); nz = np.array([fl(r["nurse_z"]) for r in R])
    i_det = int(round(ev["det"] * FPS)); i_stop = int(round(ev["stopR"] * FPS)); i_br = int(round(ev["brake"] * FPS))
    path = np.concatenate([[0], np.cumsum(np.hypot(np.diff(x), np.diff(z)))])
    o = {}
    o["見つけた時刻"] = ev["det"]; o["見つけた時の速さ"] = ev["det_v"]
    o["見つけた時：前の端から見つけた点まで（台本）"] = ev["det_dist_pt"]
    o["見つけた時：外形のすき間（Unity）"] = g[i_det]
    o["見つけてから止まるまで（秒）"] = round(ev["stopR"] - ev["det"], 3)
    o["見つけてから止まるまで（m）"] = round(path[i_stop] - path[i_det], 3)
    o["止まるまでの距離の決まり（m）"] = round(ev["det_v"] * 0.2 + ev["det_v"] ** 2 / (2 * 0.5), 3)
    o["止まった時のすき間（車いすを含む）"] = g[i_stop]; o["止まった時のすき間（人だけ）"] = gp[i_stop]
    o["一番近いすき間（車いすを含む）"] = (float(g.min()), float(t[g.argmin()])); o["一番近いすき間（人だけ）"] = (float(gp.min()), float(t[gp.argmin()]))
    # 大城さんが止まった秒（車いすの根が動かない間）
    cv = np.concatenate([[0], np.hypot(np.diff(cx), np.diff(cz)) / DT])
    st = episodes(list((cv < 0.004) & (t > 1.0)))
    o["大城さんが止まった間"] = [(round(t[a], 3), round(t[b] + DT, 3), round(t[b] + DT - t[a], 3)) for a, b in st]
    # 1 急に止まった：減速の始まりから止まるまで 1.0 秒以内
    o["1 急に止まった"] = (1 if ev["stopR"] - ev["brake"] <= CR["sudden_stop"]["value"] else 0, round(ev["stopR"] - ev["brake"], 3))
    # 2 ひやり：人（茂さん・大城さん）とハコブくんの外形が 0.3 m 未満（ハコブくんが動いている／止まっている で分ける）
    nm = CR["near_miss_m"]["value"]
    eps = episodes(list(gp < nm))
    o["2 ひやり（人だけ）"] = [(round(t[a], 3), round(t[b], 3), round(float(gp[a:b + 1].min()), 3), "動いている" if any(v[a:b + 1] > 1e-6) else "止まっている") for a, b in eps]
    eps2 = episodes(list(g < nm))
    o["2 参考（車いすを含む）"] = [(round(t[a], 3), round(t[b], 3), round(float(g[a:b + 1].min()), 3), "動いている" if any(v[a:b + 1] > 1e-6) else "止まっている") for a, b in eps2]
    # 3 人がよけさせられた：ハコブくんから 2.0 m 以内で人が止まった・向きを変えた（予定の線の曲がりは数えない＝台本の線のとおりの向き）
    ym = CR["yield_m"]["value"]
    c3 = []
    for a, b in st:
        if g[a] <= ym: c3.append(("止まった", round(t[a], 3), round(g[a], 3)))
    o["3 人がよけさせられた"] = c3
    # 4 立ち往生：30 秒以上動けず人が動かした
    rs = episodes([m in ("stopped", "stopped2") for m in mode])
    o["4 止まっていた間"] = [(round(t[a], 3), round(t[b] + DT, 3), round(t[b] + DT - t[a], 3)) for a, b in rs]
    o["4 立ち往生"] = sum(1 for a, b in rs if t[b] + DT - t[a] >= CR["stuck_s"]["value"])
    # 5 横切った：ハコブくんが動いている間に、外形が車いすの進む先（足のせの前の端から 1.5 m・車いすの幅）に入り、車いすの向きに対して横へ動いていた
    cf = CR["cross_front_m"]["value"]; c5 = []
    for i in range(1, n):
        if v[i] <= 1e-6: continue
        cy = math.radians(cyaw[i]); fx, fz = math.sin(cy), math.cos(cy); rx_, rz_ = math.cos(cy), -math.sin(cy)
        front = np.array([cx[i], cz[i]]) + np.array([fx, fz]) * 0.64
        ry = math.radians(yaw[i]); f2 = np.array([math.sin(ry), math.cos(ry)]); r2 = np.array([math.cos(ry), -math.sin(ry)])
        corners = [np.array([x[i], z[i]]) + r2 * a + f2 * b for a in (-0.33, 0.33) for b in (-0.38, 0.382)]
        inside = any(0 <= (p - front) @ np.array([fx, fz]) <= cf and abs((p - front) @ np.array([rx_, rz_])) <= 0.33 for p in corners)
        lat = abs((np.array([x[i] - x[i - 1], z[i] - z[i - 1]]) / DT) @ np.array([rx_, rz_]))
        if inside and lat > 0.05: c5.append(round(t[i], 3))
    eps5 = []
    for tt in c5:
        if eps5 and tt - eps5[-1][1] <= 2 * DT: eps5[-1][1] = tt
        else: eps5.append([tt, tt])
    o["5 横切った"] = eps5
    o["角を曲がり終えた"] = ev["turn_end"]; o["走り出し"] = ev["resume"]
    o["セリフ"] = {k: (v2["voice_on_s"], v2["voice_off_s"], v2["voice_len_s"], v2["text"]) for k, v2 in C["lines"].items()}
    o["画面"] = C["screen"]; o["切りかえ"] = sh["cuts"]; o["動画の長さ"] = round(C["video_to"] - C["video_from"] + DT, 3)
    o["_chair"] = (t, cx, cz, cyaw, nx, nz)
    res[name] = o
# 2 本で車いすの動きの差
tf, cxf, czf, cyf, nxf, nzf = res["corner_fast"].pop("_chair"); ts, cxs, czs, cys, nxs, nzs = res["corner_slow"].pop("_chair")
m = min(len(tf), len(ts)); d = np.hypot(cxf[:m] - cxs[:m], czf[:m] - czs[:m])
i_first = int(np.argmax(d > 1e-4)) if (d > 1e-4).any() else -1
# 線の差：⑪-1 の車いすの根の各点から ⑪-2 の線（点の並び）までの一番近い距離
P2 = np.stack([cxs, czs], 1); A_, B_ = P2[:-1], P2[1:]; E_ = B_ - A_; L2 = np.maximum((E_ ** 2).sum(1), 1e-12)
def seg_d(q):
    u = np.clip(((q - A_) * E_).sum(1) / L2, 0, 1); return float(np.min(np.hypot(*(A_ + E_ * u[:, None] - q).T)))
dl = [seg_d(np.array([a, b])) for a, b in zip(cxf, czf)]
diff = {"同じ時刻の位置の差が出始めた時刻": round(float(tf[i_first]), 3) if i_first >= 0 else None, "同じ時刻の位置の差の最大": round(float(d.max()), 4),
        "線の差（⑪-1 の各点から ⑪-2 の線まで）の最大": round(max(dl), 4)}
for k in ("corner_fast", "corner_slow"):
    print("■", k)
    for kk, vv in res[k].items(): print(f"  {kk}\t{vv}")
print("■ 2 本で車いすの動きの差"); [print(f"  {k}\t{v}") for k, v in diff.items()]
print("■ 角を曲がり終えた差", round(res["corner_fast"]["角を曲がり終えた"] - res["corner_slow"]["角を曲がり終えた"], 3), "秒（⑪-1 − ⑪-2）")
```


### lufs.sh

```bash
#!/bin/bash
# 1 文ずつ 48 kHz モノラルにして −20 LUFS にそろえる（270 と同じ：ffmpeg ebur128 で測って音量を掛ける）
src="$1"; name="$2"
ffmpeg -v error -y -i "$src" -ac 1 -ar 48000 out/${name}_raw.wav
L=$(ffmpeg -nostats -i out/${name}_raw.wav -af ebur128 -f null - 2>&1 | grep -A2 "Integrated loudness" | grep " I:" | awk '{print $2}')
G=$(python3 -c "print(round(-20.0-($L),2))")
ffmpeg -v error -y -i out/${name}_raw.wav -af "volume=${G}dB" -ar 48000 -ac 1 -c:a pcm_s16le out/${name}.wav
L2=$(ffmpeg -nostats -i out/${name}.wav -af ebur128 -f null - 2>&1 | grep -A2 "Integrated loudness" | grep " I:" | awk '{print $2}')
ffmpeg -v error -y -i out/${name}.wav -c:a libmp3lame -b:a 128k out/${name}.mp3
D=$(ffprobe -v error -show_entries format=duration -of csv=p=0 out/${name}.wav)
echo "$name 元 $L → ${G} dB → $L2 長さ $D"
rm out/${name}_raw.wav
```


### make271.py

```python
"""依頼271：make270.py を写して変えた。
(1) closeup271_<名前>.mp4：frames/<場面>/f_*.png（台本の video_from から終わりまで）に台本の秒の音（mix271_<場面>.wav）を重ねる。
(2) closeup271_<名前>_top.mp4：frames/<場面>_top に 236 の描き方で床の目印・通った跡・印・左上の字を重ねる。
    目印：角の壁の線（内側の角の壁の面 x 0.90・z −0.90。実線）・ハコブくんの線（ふだんの線と曲がる線。点線）。床の目印は、ものごとに穴を埋めた外形の中には描かない。
    もの：ハコブくん（赤）と、車いす・茂さん・大城さん（緑。手を握りにのせたままなので 1 つのもの。236 と同じ考え）
    印：「見つけた」「止まった」（ハコブくんの根。字に動画の秒）。左上の字：動画の秒・ハコブくんの速さ・ハコブくんと車いす（人を含む）のすき間
    重ねる順：コマ → 床の目印（外形の所は消す）→ 通った跡 → 印 → 左上の字
使い方: python3 make271.py <Unity の出力フォルダ> <台本> <場面> <音の wav> <動画を置くフォルダ> <動画の名前>"""
import csv, json, math, os, subprocess, sys, tempfile, wave
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, SHOT, WAV, VD, NAME = sys.argv[1:7]
os.makedirs(os.path.join(VD, "stills"), exist_ok=True)
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c271"]
FPS, W, H, S = 30, 1920, 1080, 2
f0 = int(round(C["video_from"] * FPS)); f1 = int(round(C["video_to"] * FPS))
seq = list(range(f0, f1 + 1))
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
def font(px, s=1): return ImageFont.truetype(FONT_PATH, px * s)
vmap = {f: (f - f0) / FPS for f in seq}

# ---------------------------------------------------------------- (1) 本番の動画（TOP_ONLY=1 なら作らない）
TOP_ONLY = os.environ.get("TOP_ONLY") == "1"
tmp = tempfile.mkdtemp(prefix="m271_", dir="/tmp")
if not TOP_ONLY:
    for k, f in enumerate(seq):
        src = os.path.join(D, "frames", SHOT, f"f_{f:05d}.png"); assert os.path.exists(src), src
        os.symlink(os.path.abspath(src), os.path.join(tmp, f"v_{k:05d}.png"))
    wr = wave.open(WAV); SR = wr.getframerate(); x = np.frombuffer(wr.readframes(wr.getnframes()), np.int16)
    a0 = int(round(f0 / FPS * SR)); a1 = int(round((f1 + 1) / FPS * SR))
    aud = x[a0:a1]; aud = np.pad(aud, (0, max(0, a1 - a0 - len(aud))))
    aw = os.path.join(tmp, "a.wav"); w2 = wave.open(aw, "w"); w2.setnchannels(1); w2.setsampwidth(2); w2.setframerate(SR); w2.writeframes(aud.astype(np.int16).tobytes()); w2.close()
    vid = os.path.join(VD, f"{NAME}.mp4")
    subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-i", aw,
                    "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30",
                    "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", "-shortest", vid], check=True)
    json.dump({"seq_first": seq[0], "seq_last": seq[-1], "n": len(seq), "video_s": len(seq) / FPS, "video_from": C["video_from"]},
              open(os.path.join(D, f"vmap271_{SHOT}.json"), "w"), ensure_ascii=False)
    print("動画", vid, len(seq), "コマ", len(seq) / FPS, "秒")

# ---------------------------------------------------------------- (2) 真上の動画
CAM = json.load(open(os.path.join(D, "top271_cam.json")))
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 48, 32, 34
COL = {"wall": (142, 36, 170), "lane": (46, 173, 107), "chair": (239, 108, 0), "robot": (0, 105, 92)}
LW = {"wall": 6, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)
rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames271.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top271.csv")))}
EV = C["events"]; K = C["corner"]
MARKS = [("robot", EV["det"], "見つけた"), ("robot", EV["stopR"], "止まった")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]
FL, FM, FH = font(LINE_LABEL_PX, S), font(MARK_LABEL_PX, S), font(HUD_PX, S)
def sc(p): return (p[0] * S, p[1] * S)
def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy; bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)
def dashed_poly(d, pts, col, w):
    s_acc = 0.0; on = True; lim = DASH * S
    for (p0, p1) in zip(pts[:-1], pts[1:]):
        (x0, y0), (x1, y1) = sc(p0), sc(p1); L = math.hypot(x1 - x0, y1 - y0)
        if L < 1e-9: continue
        ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0.0
        while s < L:
            step = min(L - s, lim - s_acc)
            if on: d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * (s + step), y0 + uy * (s + step))], fill=col, width=w * S)
            s += step; s_acc += step
            if s_acc >= lim - 1e-9: on = not on; s_acc = 0.0; lim = (DASH if on else GAP) * S
def down(layer): return layer.resize((W, H), Image.LANCZOS)
x_lo, z_lo = from_px(0, H); x_hi, z_hi = from_px(W, 0)
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
wl = K["wall"]
# 角の壁の線（内側の角の壁の面）：A の側 x 0.90（z −0.90 から手前へ）と B の側 z −0.90（x 0.90 から奥へ）
d.line([sc(to_px(wl, z_lo - 1)), sc(to_px(wl, -wl)), sc(to_px(x_hi + 1, -wl))], fill=COL["wall"] + (255,), width=LW["wall"] * S, joint="curve")
pc = to_px(wl, -wl)
text_box(d, sc((pc[0] + 16, pc[1] + 16)), "角の壁の線", FL, COL["wall"], "lt", edge=COL["wall"])
# ハコブくんの線：A の x −0.33 → 半径 R の円弧 → B の z +0.33
R = K["r_turn"]; zs = K["lane_robot_b"] - R; cxa = K["lane_robot"] + R
pts = [to_px(K["lane_robot"], z_lo - 1), to_px(K["lane_robot"], zs)]
for i in range(1, 41):
    th = math.pi / 2 * i / 40; pts.append(to_px(cxa - R * math.cos(th), zs + R * math.sin(th)))
pts.append(to_px(x_hi + 1, K["lane_robot_b"]))
dashed_poly(d, pts, COL["lane"] + (255,), LW["dash"])
lp = to_px(K["lane_robot"], z_lo)
text_box(d, sc((lp[0] - 14, H - 14)), "ハコブくんの線", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st); static_A = static.getchannel("A")
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = float(r["robot_px"]), float(r["robot_py"])
        lx, ly = to_px(2.0, 0.0)[0] + 0.0, py + (60 if i == 0 else -60)
        lx = to_px(1.6, 0)[0]
        ly = py + 70 * (1 if i == 0 else -1)
        d.line([sc((px, py)), sc((lx, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        Rr = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - Rr - e, py * S - Rr - e, px * S + Rr + e, py * S + Rr + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - Rr, py * S - Rr, px * S + Rr, py * S + Rr], fill=COL[who] + (255,))
        tv = vmap.get(mark_f[i], 0.0)
        text_box(d, sc((lx, ly)), f"{head} {tv:.1f}秒", FM, COL[who], "lm", edge=COL[who])
    return down(L)
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    g = num_ok(rows[f]["gap_m"]); v = num_ok(rows[f]["robot_v"]) or 0.0
    return [f"{vmap[f]:.1f} 秒", f"ハコブくんの速さ {abs(v):.2f} m/秒" + ("（下がる）" if rows[f]["mode"] == "back" else ""),
            "ハコブくんと車いす（人を含む）のすき間 " + (f"{g:.2f} m" if g is not None and g < 1.5 else "1.5 m より遠い")]
RC = 6
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24
def fill_obj(soft):
    ys, xs = np.nonzero(soft); added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added
    y0, y1 = max(0, ys.min() - PAD), min(H, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(W, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    added[y0:y1, x0:x1] = filled & ~b.astype(bool)
    return added
tmpT = tempfile.mkdtemp(prefix="m271t_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}; shown = [False] * len(MARKS); mcache = mark_layer(shown)
per = []; top_stills = {}
want = {int(round(s[0] * FPS)): s[2] for s in shot["stills"] if s[1] == "top"}
k = 0
seqset = set(seq)
for f in range(0, f1 + 1):
    r = top[f]
    for who, kx, ky in (("chair", "axle_px", "axle_py"), ("robot", "robot_px", "robot_py")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)
        if prev[who] is not None: td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        Rr = LW["trail"] * S / 2; td.ellipse([p[0] * S - Rr, p[1] * S - Rr, p[0] * S + Rr, p[1] * S + Rr], fill=COL[who] + (255,))
        prev[who] = p
    if f not in seqset: continue
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", SHOT + "_top", f"f_{f:05d}.png")).convert("RGBA")
    mkn = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_mask", f"f_{f:05d}.png")).convert("L"))
    ob = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_obj", f"f_{f:05d}.png")).convert("RGBA"))
    add_any = np.zeros((H, W), bool)
    for g in (ob[:, :, 0], ob[:, :, 1]): add_any |= fill_obj(g)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(Image.fromarray(Fn, "L"))))
    lines = hud_lines(f)
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl); x0, y0, lh = 30, 22, 62
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * len(lines) + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(down(trail)); im.alpha_composite(mcache); im.alpha_composite(down(hl))
    o = im.convert("RGB"); o.save(os.path.join(tmpT, f"v_{k:05d}.png")); k += 1
    stA = np.array(st_m.getchannel("A"))
    per.append((f, int(((stA > 0) & (Fn == 255)).sum()), int(add_any.sum())))
    if f in want: top_stills[want[f]] = o
vidT = os.path.join(VD, f"{NAME}_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmpT, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vidT], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for nm, im in top_stills.items(): im.save(os.path.join(sd, f"{SHOT}_{nm}.png"))
open(os.path.join(D, f"per271_{SHOT}.csv"), "w").write("frame,line_left_inside,added\n" + "".join(",".join(map(str, p)) + "\n" for p in per))
print("真上", vidT, k, "コマ・外形の中に残る目印の画素 合計", sum(p[1] for p in per))
```


### make_script271.py

```python
"""依頼271：要所の場面 ⑪「曲がり角で車いすと出会う」の台本 closeup271_script.json を作る（場面 corner_fast＝⑪-1・corner_slow＝⑪-2）。
229 の台本（closeup229_script.json）から 色・光・看護師の値・握りの的・画面の値を写し、廊下（rooms）は L の字に作り直す。動きは plan271.py の線と決まりで、
Python で毎コマ決めて台本に書く（270 と同じ：Unity は置いて確かめるだけ）。
・廊下：A（z の向き。手すりの間 x −0.84〜+0.84）と B（x の向き。z −0.84〜+0.84）を直角につなぐ。内側の角は壁（x>0.90・z<−0.90 は壁の塊）。鏡・ガラスは無し
・ハコブくん：A を x −0.33（229 のふだんの線）で +z へ → 右へ半径 1.53 m の円弧（0.8 m/秒で向きの変わる速さ 30°/秒＝229 の決まり）→ B を z +0.33 で +x へ
・車いす：B の内側（車いすの中心 z −0.42）を −x へ 0.8 m/秒 → 角の手前で 0.65 m/秒（229 の横を通る速さ）→ 内側の角（手すりの線の角）を中心に半径 0.42 m で左へ → A の x +0.42 を −z へ
・見つける：車いす・茂さん・大城さんの点が、角の壁の線（x 0.90）より手前に出て、ハコブくんの前の端から 6.0 m 以内（228 の見る範囲）。見つけたら braking の決まり（0.2 秒そのまま → 0.5 m/秒²）で止まる
・大城さん：ハコブくんが見えた（目から壁の角を通らない線が引けた）0.6 秒後から止める（⑪-1 だけ。270 と同じ 0.6 秒・0.8 m/秒から 1.6 秒）
・ハコブくんの出発の時刻：⑪-1 で、外形のすき間（ハコブくんと車いす・大城さんの箱）が 0 にならない範囲で一番小さくなる時刻（1/30 秒ごとに探す）
使い方：python3 make_script271.py <229 の台本> <出力の台本> <声の wav のフォルダ（新しい声）> <228 の声のフォルダ> <出力の情報 json>
"""
import json, math, os, sys, wave
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import plan271 as P

def E(k, d):
    v = os.environ.get(k)
    return type(d)(v) if v is not None else d

src, dst, wavdir, wav228, info_out = sys.argv[1:6]
S = json.load(open(src))
FPS = 30; DT = 1.0 / FPS
O = [50.0, 0.0, 0.0]
Z0R = E("Z0R", -7.0)                 # ハコブくんの出発の場所（根の z。x −0.33）
X0C = E("X0C", 8.0)                  # 車いすの後ろの車軸の始めの x（z −0.42）
TV0 = E("TV0", 1.0)                  # 動画の始まり（台本の秒）
GAP = E("GAP", 0.55)                 # セリフの間
SPINE, CHEST = 4.0, 3.0
R_YIELD_X = -0.47                    # 229 の寄る所（手すりと 0.053 m）
BACK_LEN = E("BACK_LEN", 1.0)        # 寄る時に下がる長さ（向き 15° まで）
V_BACK = 0.2                         # 下がる速さ（270 と同じ）
R2 = E("R2", 1.67)                   # 寄った位置（x −0.47）から曲がる半径（B の z +0.33 に入る）
PASS_AWAY = 1.0                      # 車いすが 1 m 以上離れたら進む
A_CH = 0.3                           # 車いすの速さを変える時の加速度（229 の 0.8 秒で 0.8↔0.65 に近い）
DETECT = 6.0

def smooth(u): u = min(1, max(0, u)); return u * u * (3 - 2 * u)

# ---------------------------------------------------------------- 声
SR = 48000
def load_wav(p):
    w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float64) / 32768.0
    assert w.getframerate() == SR and w.getnchannels() == 1, p
    return x
def voiced(x, th_db=-45.0):
    hop = 480
    e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
    on = np.where(20 * np.log10(e + 1e-9) > th_db)[0]
    return on[0] * hop / SR, (on[-1] + 1) * hop / SR
CLIPS = {
    "WA": ("nurse", os.path.join(wavdir, "O1_oshiro_wa.wav"), "わっ"),
    "H1": ("robot", os.path.join(wavdir, "H1_hakobu_shitsurei.wav"), "失礼しました。お先にどうぞ"),
    "M1": ("morita", os.path.join(wavdir, "M1_morita_bikkuri.wav"), "おお、びっくりした"),
    "H2": ("robot", os.path.join(wav228, "L4_hakobu.wav"), "お先にどうぞ"),
    "O2": ("nurse", os.path.join(wav228, "L5_oshiro.wav"), "ありがとう"),
}
clips = {}
for k, (who, fn, text) in CLIPS.items():
    x = load_wav(fn); v0, v1 = voiced(x)
    clips[k] = {"who": who, "file": os.path.basename(fn), "text": text, "x": x, "v0": v0, "v1": v1, "dur": v1 - v0, "len": len(x) / SR}

# ---------------------------------------------------------------- 線（plan271 と同じ）
def robot_pose1(s): return P.robot_pose(s, Z0R)
def chair_at(sc):
    ax, az, ps = P.chair_axle(sc, X0C)
    f = P.fwd(ps); n = np.array([ax, az]) - f * P.AX_AHEAD
    return ax, az, ps, n
def group_polys(sc):
    Pn, Pc, n, ps = P.chair_polys(sc, X0C)
    return Pn, Pc
def robot_poly(x, z, y): return P.rect(x, z, y, -P.RW, P.RW, -P.RB, P.RF)
S_ARC_C = X0C - P.RAIL                 # 車いすの道で円弧の始まり

# 寄った位置（x −0.47）からの線：まっすぐ → 半径 R2 の円弧 → B の z +0.33
def make_path2(x0, z0):
    zs = P.LANE_RB - R2; c = (x0 + R2, zs); L = R2 * math.pi / 2
    def pose(s):
        s1 = zs - z0
        if s <= s1: return x0, z0 + s, 0.0
        if s <= s1 + L:
            th = (s - s1) / R2; return c[0] - R2 * math.cos(th), c[1] + R2 * math.sin(th), math.degrees(th)
        return c[0] + (s - s1 - L), P.LANE_RB, 90.0
    return pose, zs - z0, zs - z0 + L

# 下がりながら寄る線（3 次の Hermite：始めは止まった向きの逆・終わりは −z）
def make_back(x0, z0, y0):
    p0 = np.array([x0, z0]); p1 = np.array([R_YIELD_X, z0 - BACK_LEN])
    t0 = -P.fwd(y0) * BACK_LEN; t1 = np.array([0.0, -1.0]) * BACK_LEN
    us = np.linspace(0, 1, 4001)
    pts = np.array([(2*u**3-3*u**2+1)*p0 + (u**3-2*u**2+u)*t0 + (-2*u**3+3*u**2)*p1 + (u**3-u**2)*t1 for u in us])
    d = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(pts, axis=0), axis=1))])
    tang = np.gradient(pts, axis=0)
    yaws = np.degrees(np.arctan2(-tang[:, 0], -tang[:, 1]))
    def pose(s):
        s = min(max(s, 0), d[-1]); return float(np.interp(s, d, pts[:, 0])), float(np.interp(s, d, pts[:, 1])), float(np.interp(s, d, yaws))
    return pose, d[-1], float(np.max(np.abs(yaws)))

# ---------------------------------------------------------------- 1 本を毎コマ回す
def run(shot, tau, T=60.0, full=True):
    fast = shot == "fast"
    rows = []
    # ハコブくん
    rs = 0.0; rv = 0.0; mode = "wait"; pose = robot_pose1; ev = {}
    back = None; path2 = None; arc_end_s = None; s_arc0 = P.Z_ARC - Z0R; s_arc1 = s_arc0 + P.L_ARC
    # 車いす
    cs = 0.0; cv = 0.0; cmode = "go"; passed = False; cv_b = None; c_t0 = None
    gmin = 9.0; gmin_t = None
    times = {}
    for f in range(int(T * FPS)):
        t = f * DT
        x, z, y = pose(rs)
        # ---- 大城さんがハコブくんを見る（目から壁の角を通らない線）
        ax, az, ps, nroot = chair_at(cs)
        eyeO = nroot + P.fwd(ps) * P.EYE_F
        Pr = robot_poly(x, z, y)
        if "seeO" not in ev and mode != "wait" and any(not P.blocked(eyeO, p) for p in P.sample_poly(Pr, 6)): ev["seeO"] = t
        # ---- 車いすの速さ
        if cmode == "go":
            if t < 0.2: vt = 0.0
            elif t < 1.2: vt = P.V_C * smooth((t - 0.2) / 1.0)
            else:
                vt = P.V_C if (S_ARC_C - cs) > E("SLOW_BEFORE", 0.85) and not passed else P.V_PASS
                if passed: vt = P.V_C
            if t < 1.2: cv = vt
            else: cv = cv + max(-A_CH * DT, min(A_CH * DT, vt - cv))
            if fast and "seeO" in ev and t >= ev["seeO"] + 0.6 and "bO" not in ev:
                ev["bO"] = t; cv_b = cv; cmode = "brake"
        if cmode == "brake":
            u = min(1.0, (t - ev["bO"]) / (1.6 * cv_b / 0.8)); cv = cv_b * (1 - smooth(u))
            if u >= 1.0: cmode = "stopped"; ev["stopC"] = t; cv = 0.0
        elif cmode == "stopped":
            cv = 0.0
            if "cgo" in ev and t >= ev["cgo"]: cmode = "resume"; c_t0 = t
        elif cmode == "resume":
            u = (t - c_t0) / 1.0; cv = P.V_PASS * smooth(u)
            if u >= 1.0: cmode = "go"
        # 通りすぎた：大城さんの体の後ろの端がハコブくんの後ろの端を過ぎた（A の中で）
        nb = nroot - P.fwd(ps) * (-P.NBK)
        if not passed and ps <= -179.9 and nb[1] < z - P.RB: passed = True; ev["passed"] = t
        # ---- ハコブくん
        if mode == "wait" and t >= tau - 1e-9: mode = "cruise"
        if mode == "cruise":
            vt = P.V_FAST
            front = z + P.RF
            if not fast:
                d_to = (-P.WALL - 2.0) - front
                if d_to <= (rv * rv - P.V_SLOW ** 2) / (2 * P.DEC_PLAN) + 1e-6 or y > 1e-6: vt = P.V_SLOW
            if vt > rv: rv = min(vt, rv + P.ACC * DT)
            elif vt < rv: rv = max(vt, rv - P.DEC_PLAN * DT)
            if rv >= P.V_FAST - 1e-9: ev.setdefault("cruise_at", t)
            if not fast and "cruise_at" in ev and "slow" not in ev and vt < P.V_FAST: ev["slow"] = t; ev["slow_front"] = front
            if not fast and "slow" in ev and "slow_done" not in ev and rv <= P.V_SLOW + 1e-9: ev["slow_done"] = t; ev["slow_done_front"] = front
            # 見つける
            Pn, Pc = group_polys(cs)
            eye = np.array([x, z]) + P.fwd(y) * P.RF
            hit = None
            for Pq in (Pc, Pn):
                for p in P.sample_poly(Pq, 8):
                    if p[0] >= P.WALL or P.blocked(eye, p): continue
                    if np.linalg.norm(p - eye) <= DETECT: hit = p; break
                if hit is not None: break
            if hit is not None:
                ev["det"] = t; mode = "react"; ev["det_v"] = rv
                ev["det_pt"] = [round(float(hit[0]), 4), round(float(hit[1]), 4)]
                ev["det_dist_pt"] = round(float(np.linalg.norm(hit - eye)), 4)
        elif mode == "react":
            if t - ev["det"] >= P.BR_REACT - 1e-9: mode = "brake"; ev["brake"] = t
        rv_prev = rv
        if mode == "brake":
            rv = max(0.0, rv - P.BR_DEC * DT)
        if mode in ("cruise", "react", "brake"):
            # 減速の間は台形（コマの始めと終わりの速さの平均）で進める：止まるまでの距離が braking の決まり（速さ×0.2＋速さ²÷(2×0.5)）と同じになる
            rs += (0.5 * (rv_prev + rv) if mode == "brake" else rv) * DT
            if mode == "brake" and rv <= 0: mode = "stopped"; ev["stopR"] = t + DT; ev["stopR_pose"] = list(pose(rs))
        elif mode == "back":
            # 下がる：0.2 m/秒（加速・減速 0.4 m/秒²）・長さ back[1]
            bs, bL = ev["_bs"], back[1]
            rem = bL - bs
            vt = V_BACK if rem > rv * rv / (2 * 0.4) + 1e-6 else 0.0
            rv = min(vt, rv + 0.4 * DT) if vt > rv else max(0.0, rv - 0.4 * DT)
            if vt == 0.0 and rv < 1e-6 or rem < 1e-4: rv = 0.0
            bs = min(bL, bs + rv * DT); ev["_bs"] = bs
            if rv == 0.0 and bs > 0.5 * bL: mode = "stopped2"; ev["back_end"] = t + DT; ev["back_end_pose"] = list(back[0](bs))
        elif mode == "go2":
            # 進む（⑪-1：0.8 m/秒・⑪-2：曲がり終えるまで 0.4 → 0.8）
            vt = P.V_FAST if fast or rs >= arc_end_s else P.V_SLOW
            rv = min(vt, rv + P.ACC * DT) if vt > rv else max(vt, rv - P.DEC_PLAN * DT)
            rs += rv * DT
            if "turn_end" not in ev and rs >= arc_end_s: ev["turn_end"] = t + DT
        # 止まった後
        if mode == "stopped":
            if fast and "H1_end" in times and "back0" not in ev and t >= times["H1_end"] + 0.3:
                x0, z0, y0 = pose(rs); back = make_back(x0, z0, y0); ev["back0"] = t; ev["_bs"] = 0.0; mode = "back"; ev["back_yaw_max"] = back[2]; ev["back_len"] = back[1]
            if not fast and passed and "resume" not in ev:
                g = min(P.poly_dist(robot_poly(*pose(rs)), q) for q in group_polys(cs))
                if g >= PASS_AWAY: ev["resume"] = t; ev["resume_gap"] = g; mode = "go2"; arc_end_s = s_arc1; ev["turn_start_s"] = s_arc0
        if mode == "stopped2":
            if "cgo" not in ev: ev["cgo"] = t + 0.5
            if passed and "resume" not in ev:
                x0, z0, y0 = back[0](ev["_bs"])
                g = min(P.poly_dist(robot_poly(x0, z0, y0), q) for q in group_polys(cs))
                if g >= PASS_AWAY:
                    ev["resume"] = t; ev["resume_gap"] = g
                    p2, s_a0, s_a1 = make_path2(x0, z0); pose = p2; rs = 0.0; arc_end_s = s_a1; mode = "go2"; ev["turn_start_s"] = s_a0
        if mode in ("back", "stopped2") and back is not None:
            x, z, y = back[0](ev["_bs"])
        else:
            x, z, y = pose(rs)
        # 声の時刻（止まった後に決まるもの）
        if fast:
            if "bO" in ev and "WA_on" not in times:
                times["WA_on"] = ev["bO"]; times["WA_end"] = times["WA_on"] + clips["WA"]["dur"]
            if "stopR" in ev and "WA_end" in times and "H1_on" not in times:
                times["H1_on"] = max(ev["stopR"] + 0.3, times["WA_end"] + GAP); times["H1_end"] = times["H1_on"] + clips["H1"]["dur"]
                times["M1_on"] = times["H1_end"] + GAP; times["M1_end"] = times["M1_on"] + clips["M1"]["dur"]
        else:
            if "stopR" in ev and "H2_on" not in times:
                times["H2_on"] = ev["stopR"] + 0.3; times["H2_end"] = times["H2_on"] + clips["H2"]["dur"]
                times["O2_on"] = times["H2_end"] + GAP; times["O2_end"] = times["O2_on"] + clips["O2"]["dur"]
        cs += cv * DT
        ax, az, ps, nroot = chair_at(cs)
        Pn, Pc = group_polys(cs)
        Pr = robot_poly(x, z, y)
        g = min(P.poly_dist(Pr, Pn), P.poly_dist(Pr, Pc)) if (not full or True) else 0
        if g < gmin: gmin = g; gmin_t = t
        rows.append({"t": t, "x": x, "z": z, "yaw": y, "v": rv, "mode": mode, "cs": cs, "cv": cv, "cmode": cmode, "ax": ax, "az": az, "ps": ps, "nx": float(nroot[0]), "nz": float(nroot[1]), "g": g})
        if not full and mode in ("stopped",) and cmode in ("stopped",) and t > ev.get("stopR", 1e9) + 1.0: break
        if not full and not fast and mode == "stopped" and t > ev.get("stopR", 1e9) + 0.5: break
        if full and "turn_end" in ev and t >= ev["turn_end"] + E("END_AFTER", 2.5): break
    return rows, ev, times, gmin, gmin_t

# ---------------------------------------------------------------- 出発の時刻：⑪-1 で外形のすき間が 0 にならない範囲で一番小さい所
search = []
best = None
for k in range(int(E("TAU0", 0.5) * FPS), int(E("TAU1", 2.5) * FPS) + 1):
    tau = k / FPS
    rows, ev, times, gm, gmt = run("fast", tau, T=16.0, full=False)
    search.append([round(tau, 4), round(gm, 4), round(gmt, 3) if gmt is not None else None, round(ev.get("det", -1), 3)])
    if gm > 0 and (best is None or gm < best[1]): best = (tau, gm)
TAU = best[0]
print("出発の時刻", TAU, "すき間の最小（箱）", round(best[1], 4), file=sys.stderr)

SHOTS = {}
for shot in ("fast", "slow"):
    rows, ev, times, gm, gmt = run(shot, TAU)
    SHOTS[shot] = (rows, ev, times, gm, gmt)
    print(shot, {k: (round(v, 3) if isinstance(v, float) else v) for k, v in ev.items() if not k.startswith("_")}, "gmin", round(gm, 4), gmt, file=sys.stderr)

# ---------------------------------------------------------------- 廊下（L の字）
def box(name, mn, mx, mat, solid=False, rail=False, shadow=False):
    r = {"name": name, "min": [round(O[0] + mn[0], 4), round(mn[1], 4), round(mn[2], 4)], "max": [round(O[0] + mx[0], 4), round(mx[1], 4), round(mx[2], 4)], "mat": mat}
    if solid: r["solid"] = True
    if rail: r["rail"] = True
    if shadow: r["shadow"] = True
    return r
AZ0 = -14.0; BX1 = 14.0
rooms = [
    box("廊下_床A", (-1.05, -0.2, AZ0), (1.05, 0.0, 1.05), "floor"),
    box("廊下_床B", (1.05, -0.2, -1.05), (BX1, 0.0, 1.05), "floor"),
    box("廊下_外の壁A（−x）", (-1.05, 0.0, AZ0), (-0.90, 2.6, 1.05), "wall", solid=True),
    box("廊下_外の壁B（+z）", (-0.90, 0.0, 0.90), (BX1, 2.6, 1.05), "wall", solid=True),
    box("廊下_内側の角の壁", (0.90, 0.0, AZ0), (BX1, 2.6, -0.90), "wall", solid=True),
    box("廊下_外の巾木A", (-0.90, 0.0, AZ0), (-0.892, 0.08, 0.90), "dark", solid=True),
    box("廊下_外の巾木B", (-0.892, 0.0, 0.892), (BX1, 0.08, 0.90), "dark", solid=True),
    box("廊下_内の巾木A", (0.892, 0.0, AZ0), (0.90, 0.08, -0.90), "dark", solid=True),
    box("廊下_内の巾木B", (0.90, 0.0, -0.90), (BX1, 0.08, -0.892), "dark", solid=True),
    # 手すり（手すりの間 1.68 m。内側の角の所は角で切る）
    box("廊下_外の手すりA", (-0.875, 0.765, AZ0 + 0.3), (-0.84, 0.8, 0.84), "wood", solid=True, rail=True, shadow=True),
    box("廊下_外の手すりB", (-0.84, 0.765, 0.84), (BX1 - 0.3, 0.8, 0.875), "wood", solid=True, rail=True, shadow=True),
    box("廊下_内の手すりA", (0.84, 0.765, AZ0 + 0.3), (0.875, 0.8, -0.92), "wood", solid=True, rail=True, shadow=True),
    box("廊下_内の手すりB", (0.92, 0.765, -0.875), (BX1 - 0.3, 0.8, -0.84), "wood", solid=True, rail=True, shadow=True),
]
# 病室の扉（外の壁に 1 つずつ。飾り：手すりは扉の前で切らない＝扉は手すりの後ろ）
for nm, (a, b) in (("A", (-5.6, -4.3)), ):
    rooms += [box(f"廊下_扉{nm}_枠", (-0.90, 0.0, a - 0.06), (-0.888, 2.13, b + 0.06), "dark"),
              box(f"廊下_扉{nm}", (-0.898, 0.012, a), (-0.876, 2.045, b), "cloth"),
              box(f"廊下_扉{nm}_窓", (-0.876, 1.35, b - 0.2), (-0.874, 1.8, b - 0.1), "paper")]
for nm, (a, b) in (("B", (4.3, 5.6)), ):
    rooms += [box(f"廊下_扉{nm}_枠", (a - 0.06, 0.0, 0.888), (b + 0.06, 2.13, 0.90), "dark"),
              box(f"廊下_扉{nm}", (a, 0.012, 0.876), (b, 2.045, 0.898), "cloth"),
              box(f"廊下_扉{nm}_窓", (a + 0.1, 1.35, 0.874), (a + 0.2, 1.8, 0.876), "paper")]

# ---------------------------------------------------------------- 場面ごとの台本
def walk_segs(mv):
    out = []; a = None
    for i, m in enumerate(mv):
        if m and a is None: a = i
        if not m and a is not None: out.append((a * DT, i * DT)); a = None
    if a is not None: out.append((a * DT, len(mv) * DT))
    return out
STEP_T = 0.5
TURN_STEP_MIN_DEG = E("TURN_STEP_MIN_DEG", 3.0); TURN_STEP_DZ = E("TURN_STEP_DZ", -0.12); TURN_STEP_DX = E("TURN_STEP_DX", -0.04)
STEP_TURN_DEG = E("STEP_TURN_DEG", 20.0)   # 曲がる間は 1 歩で向きが変わる量をこれまでにする（足が車いすの後ろに入らないように。1 歩 0.3 秒まで短く）
def walk_steps(segs, NF, yaws):
    st = []; foot = "R"
    def per(t):
        i0 = min(NF - 1, int(round(t * FPS))); i1 = min(NF - 1, int(round((t + STEP_T) * FPS)))
        dy = abs(yaws[i1] - yaws[i0])
        return STEP_T if dy <= STEP_TURN_DEG else max(0.3, STEP_T * STEP_TURN_DEG / dy)
    for (a, b) in segs:
        t = max(a, 0.2) if a < 0.25 else a - 0.05
        while t + per(t) <= b + 0.25 + 1e-6:
            pp = per(t)
            i0 = max(0, min(NF - 1, int(round((t - 0.3) * FPS)))); i1 = min(NF - 1, int(round((t + pp + 0.3) * FPS)))
            if abs(yaws[i1] - yaws[i0]) > TURN_STEP_MIN_DEG:      # 曲がる間：足を根の後ろ寄りに着く（車いすの転倒防止のバーに足が入らないように）
                st.append([round(t, 4), round(t + pp, 4), foot, round(TURN_STEP_DX * (1 if foot == "R" else -1), 4), round(TURN_STEP_DZ, 4)])
            else:
                st.append([round(t, 4), round(t + pp, 4), foot])
            t += pp; foot = "L" if foot == "R" else "R"
        if b < (NF - 1) * DT - 0.5:
            st.append([round(t, 4), round(t + STEP_T * 0.9, 4), foot]); foot = "L" if foot == "R" else "R"
    return st

HOP = SR // FPS
LADDER = ["closed", "small", "mid", "large"]
def frame_rms(x, NF): return np.array([np.sqrt(np.mean(x[i * HOP:(i + 1) * HOP] ** 2)) if i * HOP < len(x) else 0 for i in range(NF)])
def ladder(track, NF, rest, speak):
    rms = frame_rms(track, NF)
    ref = np.percentile(rms[rms > 0.01], 90) if (rms > 0.01).any() else 1.0
    lvl = np.convolve(rms / ref, np.ones(3) / 3, mode="same")
    target = np.where(speak, np.digitize(lvl, [0.15, 0.35, 0.65]), 0)
    for i in range(NF):
        if not speak[i]: target[i] = rest[i]
    for i in range(1, NF - 1):
        if target[i] != target[i - 1] and target[i] != target[i + 1]: target[i] = target[i - 1]
    step = np.zeros(NF, int)
    for i in range(NF):
        prev = step[i - 1] if i else rest[0]
        step[i] = prev + int(np.clip(target[i] - prev, -1, 1)) if i % 2 == 0 else prev
    return step

shots_out = []; tops = {}; info = {"tau": TAU, "tau_gap_box": round(best[1], 4), "search": search, "shots": {}}
q = lambda t: round(round(t * FPS) / FPS, 4)
for shot in ("fast", "slow"):
    rows, ev, times, gm, gmt = SHOTS[shot]
    fast = shot == "fast"
    name = "corner_fast" if fast else "corner_slow"
    NF = len(rows); DUR = NF * DT
    on = {k[:-3]: v for k, v in times.items() if k.endswith("_on")}
    end = {k[:-4]: v for k, v in times.items() if k.endswith("_end")}
    # 音
    tracks = {w: np.zeros(int(DUR * SR) + SR) for w in ("nurse", "robot", "morita")}
    place = {}
    for k in on:
        c = clips[k]; s0 = on[k] - c["v0"]; i0 = int(round(s0 * SR))
        tracks[c["who"]][i0:i0 + len(c["x"])] += c["x"]
        place[k] = {"who": c["who"], "file": c["file"], "text": c["text"], "clip_start_s": round(s0, 4), "voice_on_s": round(on[k], 4), "voice_off_s": round(end[k], 4), "voice_len_s": round(c["dur"], 4), "clip_len_s": round(c["len"], 4)}
    def speak_mask(names):
        m = np.zeros(NF, bool)
        for k in names: m[int(math.floor(on[k] * FPS)):min(NF, int(math.ceil(end[k] * FPS)))] = True
        return m
    rob_names = ["H1"] if fast else ["H2"]
    robot_mouth = [LADDER[s] for s in ladder(tracks["robot"], NF, np.full(NF, 2), speak_mask(rob_names))]
    nurse_mouth = [int(s) for s in ladder(tracks["nurse"], NF, np.zeros(NF, int), speak_mask([] if fast else ["O2"]))]   # 「わっ」は口 surprised（話す口は使わない）
    m_step = ladder(tracks["morita"], NF, np.zeros(NF, int), speak_mask(["M1"] if fast else []))
    mix = (tracks["nurse"] + tracks["robot"] + tracks["morita"])[: int(round(DUR * SR))]
    ao = os.environ.get("AUDIO_DIR", "")
    if ao:
        pk = np.max(np.abs(mix)); assert pk < 1.0, pk
        w = wave.open(os.path.join(ao, f"mix271_{name}.wav"), "w"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
        w.writeframes((np.clip(mix, -1, 1) * 32767).astype(np.int16).tobytes()); w.close()
    # 大城さんの根・向き（毎コマ）と歩き
    nyaw = [r["ps"] for r in rows]
    keys = lambda vals: [[0.0, round(vals[0], 5)]] + [[round(rows[i]["t"], 4), round(vals[i], 5), "lin"] for i in range(1, NF)]
    moving = [r["cv"] > 0.004 for r in rows]
    segs = walk_segs(moving)
    steps = walk_steps(segs, NF, nyaw)
    walk = [[0, 0], [0.2, 0], [0.6, 1]]
    for (a, b) in segs:
        if a > 0.25: walk += [[round(a, 4), 0], [round(a + 0.6, 4), 1]]
        if b < (NF - 1) * DT - 0.5: walk += [[round(b - 0.6, 4), 1], [round(b, 4), 0]]
    # 大城さんの顔：自分の声の間はハコブくんの画面のほうへ（体から 35° まで）
    EYE = (0.0, 1.50, -0.09)
    def rob_at(t): return rows[min(NF - 1, max(0, int(round(t * FPS))))]
    look = [("WA", on.get("WA"), end.get("WA"))] if fast else [("O2", on.get("O2"), end.get("O2"))]
    hy = [[0, 0.0]]; hn = [[0, 8.0]]; lw = []
    for nm, a, b in look:
        t0, t1, t2, t3 = a - 0.45, a - 0.1, b + 0.35, b + 0.8
        lw.append([round(t1, 3), round(t2, 3)])
        for f in range(max(1, int(t0 * FPS) - 1), int(t3 * FPS) + 2):
            t = f * DT
            w = 0.0 if t < t0 or t > t3 else smooth((t - t0) / (t1 - t0)) if t < t1 else (1 - smooth((t - t2) / (t3 - t2))) if t > t2 else 1.0
            r = rob_at(t); by = r["ps"]
            ex = r["nx"] + math.sin(math.radians(by)) * 0.09; ez = r["nz"] + math.cos(math.radians(by)) * 0.09
            sx = r["x"] + math.sin(math.radians(r["yaw"])) * 0.37; sz = r["z"] + math.cos(math.radians(r["yaw"])) * 0.37
            want = math.degrees(math.atan2(sx - ex, sz - ez)); yy = ((want - by + 180) % 360) - 180; yy = max(-35, min(35, yy))
            pitch = math.degrees(math.atan2(1.50 - 0.96, math.hypot(sx - ex, sz - ez)))
            hy.append([round(t, 4), round(w * yy, 3), "lin"]); hn.append([round(t, 4), round(8.0 * (1 - w) + w * pitch, 3), "lin"])
        hy.append([round(t3 + 2 * DT, 4), 0.0]); hn.append([round(t3 + 2 * DT, 4), 8.0])
    if fast:
        n_mouth = [[0, "flat"], [round(on["WA"] - 0.05, 4), "surprised"], [round(end["H1"], 4), "flat"]]
    else:
        n_mouth = [[0, "flat"]]
    # 茂さん：口（話す間 talk）・まばたき。顔の向きは変えない
    m_mouth = [[0, "flat"]]; prev = "flat"
    for i in range(NF):
        mm = "talk" if m_step[i] >= 1 else "flat"
        if mm != prev: m_mouth.append([round(i * DT, 4), mm]); prev = mm
    # 画面
    if fast:
        scr = [[0, "face"], [round(ev["brake"], 4), "stop"], [round(on["H1"], 4), "yield"], [round(ev["resume"], 4), "face"]]
        happy = None
    else:
        hf, ht = end["O2"], end["O2"] + 1.5
        scr = [[0, "face"], [round(on["H2"], 4), "yield"], [round(hf, 4), "yield_happy"], [round(ht, 4), "face"]]
        happy = [round(hf, 4), round(ht, 4)]
    # ハコブくん（毎コマ）
    robot = [[round(r["x"], 5), round(r["z"], 5), round(r["yaw"], 4), round(r["v"], 4), r["mode"]] for r in rows]
    # カメラ
    def face_cam(t, side):
        r = rob_at(t); by = math.radians(r["ps"])
        fx, fz = math.sin(by), math.cos(by); rx_, rz_ = math.cos(by), -math.sin(by)
        hx, hz = r["nx"] + fx * 0.05, r["nz"] + fz * 0.05
        cx, cz = hx + fx * 1.45 + rx_ * side, hz + fz * 1.45 + rz_ * side
        return {"pos": [round(cx, 4), 1.48, round(cz, 4)], "look": [round(hx, 4), 1.50, round(hz, 4)], "fov": 24}
    CAM = {
        "main": {"pos": [-0.85, 7.5, 0.85], "look": [1.0, 0.0, -1.5], "fov": 50},
        "screen_close": {"follow": "robot_pose", "pos": [0.0, 1.23, 1.15], "look": [0.0, 0.962, 0.29], "fov": 24},
        "chk_grip": {"follow": "nurse_pose", "pos": [-0.65, 1.55, 0.55], "look": [-0.05, 0.92, 0.27], "fov": 34},
        "chk_side": {"follow": "nurse_pose", "pos": [-1.6, 1.2, 0.6], "look": [0.0, 0.6, 0.6], "fov": 40},
    }
    if fast:
        CAM["face"] = face_cam(0.5 * (on["WA"] + end["WA"]), -0.35)
        cuts = [[0, "main"], [q(on["WA"] - 0.4), "face"], [q(end["WA"] + 0.45), "screen_close"], [q(end["H1"] + 0.3), "main"]]
    else:
        CAM["face"] = face_cam(0.5 * (on["O2"] + end["O2"]), 0.35)
        cuts = [[0, "main"], [q(on["H2"] - 0.1), "screen_close"], [q(end["H2"] + 0.25), "face"], [q(end["O2"] + 0.25), "screen_close"], [q(end["O2"] + 1.5 + 0.1), "main"]]
    stills = [
        [q(ev["det"] - 1.0), "main", "s1_unseen_main"],
        [q(ev["det"]), "main", "s2_found_main"], [q(ev["det"]), "top", "s2_found_top"],
        [q(ev["stopR"]), "main", "s3_stopped_main"], [q(ev["stopR"]), "top", "s3_stopped_top"],
        [2.0, "chk_grip", "chk_grip_2s"], [2.0, "chk_side", "chk_side_2s"],
    ]
    if fast:
        stills += [[q(on["WA"] + 0.2), "face", "s4_wa_face"], [q(ev["back_end"]), "top", "chk_yielded_top"], [q(ev.get("passed", ev["resume"])), "main", "s5_pass_main"]]
        i_turn = int(round((ev["bO"] + ev["stopC"]) * 0.5 * FPS)); stills += [[q(i_turn * DT), "chk_grip", "chk_grip_brake"]]
    else:
        stills += [[q(on["O2"] + 0.3), "face", "s4_arigatou_face"], [q(ev.get("passed", ev["resume"])), "main", "s5_pass_main"]]
    # 円弧の中の車いす（握りの確かめ）
    i_arc = [i for i, r in enumerate(rows) if -170 < r["ps"] < -100]
    if i_arc: stills += [[q(i_arc[len(i_arc) // 2] * DT), "chk_grip", "chk_grip_turn"], [q(i_arc[len(i_arc) // 2] * DT), "chk_side", "chk_side_turn"]]
    stills.sort(key=lambda s: s[0])
    vto = round((NF - 1) * DT, 4)
    c271 = {"video_from": TV0, "video_to": vto, "wc_ahead_m": P.WC_AHEAD, "robot": robot, "screen": scr, "happy": happy,
            "robot_mouth": robot_mouth, "nurse_mouth": nurse_mouth, "nurse_mouth_scale": [1.0, 1.2, 1.8, 2.4],
            "morita": {"head_yaw": [[0, 0.0]], "head_nod": [[0, 0.0]], "mouth": m_mouth, "neck_share": 0.4,
                       "blink": {"every_min_s": 3.0, "every_max_s": 5.0, "close_s": 0.15, "seed": 228}, "eye_min_scale": 0.1},
            "grip": {"x": 0.225, "y": 0.910, "z_behind_root": 0.3336, "r": 0.0155},
            "lines": place, "events": {k: v for k, v in ev.items() if not k.startswith("_")}, "times": times,
            "corner": {"wall": P.WALL, "rail": P.RAIL, "lane_robot": P.LANE_R, "lane_robot_b": P.LANE_RB, "r_turn": P.R_TURN, "lane_chair": P.LANE_C, "r_chair": P.R_C,
                       "detect_range_m": DETECT, "braking": {"react_s": P.BR_REACT, "decel_mps2": P.BR_DEC, "notice_margin_m": P.NOTICE},
                       "tau": TAU, "robot_z0": Z0R, "chair_axle_x0": X0C}}
    sh = {"name": name, "about": "⑪-1 角でも 0.8 m/秒のまま" if fast else "⑪-2 角の手前で 0.4 m/秒", "origin": O, "duration": round(DUR, 4), "video": True,
          "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]}, "box_events": [], "card_events": [], "presses": [], "card": False,
          "check_open": [], "check_close": [], "check_above": [], "transitions": [], "swing_ramp": 0.15, "lift_pow": 0.5,
          "nurse": {"x": keys([r["nx"] for r in rows]), "z": keys([r["nz"] for r in rows]), "yaw": keys(nyaw), "walk": walk,
                    "spine": [[0, SPINE]], "chest": [[0, CHEST]], "head_yaw": hy, "head_nod": hn, "mouth": n_mouth, "talk": [[0, 0]],
                    "L_w": [[0, 1.0]], "R_w": [[0, 1.0]], "L_target": [[0, "grip_l"]], "R_target": [[0, "grip_r"]],
                    "L_curl": [[0, 30.0]], "R_curl": [[0, 30.0]], "L_thumb": [[0, 20.0]], "R_thumb": [[0, 20.0]],
                    "L_hint": [[0, "push_l"]], "R_hint": [[0, "push_r"]], "L_hint_w": [[0, 0.5]], "R_hint_w": [[0, 0.5]]},
          "steps": steps, "look_windows": lw, "cameras": CAM, "cuts": cuts, "stills": stills, "c271": c271}
    shots_out.append(sh)
    # 真上のカメラ（正射影・画面の上が +z・右が +x）
    tops[name] = {"center_x": 3.3, "center_z": -1.65, "height": 8.0, "ortho_size": 2.75, "width_px": 1920, "height_px": 1080, "up": [0, 0, 1]}
    info["shots"][name] = {"duration": round(DUR, 4), "video_len": round(DUR - TV0, 4), "events": c271["events"], "times": times, "cuts": cuts, "screen": scr, "gmin_box": round(gm, 4), "gmin_box_t": gmt,
                           "steps": len(steps), "walk_segs": segs}

out = {k: S[k] for k in ("fps", "width", "height", "supersample", "colors", "light", "box", "bag", "nurse", "targets", "card", "pocket", "screen_ui", "drawer_parts", "hints", "check_stand_parts")}
out["about"] = "依頼271：⑪ 曲がり角で車いすと出会う（場面 corner_fast＝⑪-1・corner_slow＝⑪-2）。make_script271.py が作る。色・光・看護師・握りの的・画面の値は 229 の台本から写した。廊下（rooms）は L の字"
out["rooms"] = rooms
out["corridor"] = {"origin": O, "width_m": 1.8, "rail_gap_m": 1.68, "about": "A：x −0.90〜+0.90（手すりの間 −0.84〜+0.84）を z の向き／B：z −0.90〜+0.90 を x の向き。内側の角の壁 (0.90, −0.90)"}
out["shots"] = shots_out
json.dump(out, open(dst, "w"), ensure_ascii=False, indent=1)
json.dump(tops, open(os.path.join(os.path.dirname(dst), "closeup271_top.json"), "w"), ensure_ascii=False, indent=1)
json.dump(info, open(info_out, "w"), ensure_ascii=False, indent=1)
for k, v in info["shots"].items():
    print(k, "長さ", v["duration"], "cuts", v["cuts"], file=sys.stderr)
```


### plan271.py

```python
"""依頼271：⑪ 曲がり角で車いすと出会う — 動きの計画（Python）。
L の字の廊下（廊下 A：z の向き・x −0.84〜+0.84 が手すりの間／廊下 B：x の向き・z −0.84〜+0.84。内側の角＝壁の角 (0.90, −0.90)）。
ハコブくん：A を x −0.33 で +z へ → 右へ曲がる（円弧 半径 R）→ B を z +0.33 で +x へ。
車いす（後ろの車軸の中心）：B を z −0.42 で −x へ → 左へ曲がる（内側の角 (0.84,−0.84) を中心に半径 0.42）→ A を x +0.42 で −z へ。
見える：線分（見る所→相手の点）が内側の角の壁（x>0.90 かつ z<−0.90）を通らない。
センサー：病院の1日の形（幅 0.65 m・長さ＝止まるまでの距離＋0.3 m）。SENSOR=path なら、これから通る線に沿わせる／straight なら向きのまま。
"""
import math, json, os, sys
import numpy as np

def E(k, d):
    v = os.environ.get(k)
    return type(d)(v) if v is not None else d

FPS = 30; DT = 1.0 / FPS
# ---- 廊下
WALL = 0.90; RAIL = 0.84
CORNER = (WALL, -WALL)                   # 内側の角（壁の角）
# ---- ハコブくん
LANE_R = -0.33; LANE_RB = 0.33           # A の x・B の z（どちらも外側の手すりから 0.51 m）
R_TURN = E("R_TURN", 1.53)               # 曲がる半径（0.8 m/秒で向きの変わる速さ 30°/秒）
RW = 0.330; RF = 0.382; RB = 0.380       # 外形（根から）
V_FAST = 0.8; V_SLOW = 0.4
BR_REACT = 0.2; BR_DEC = 0.5; NOTICE = 0.3; SENSOR_W = 0.65
ACC = 0.4; DEC_PLAN = 0.4
SENSOR = E("SENSOR", "see")
DETECT = E("DETECT", 6.0)            # 228 の見る範囲
# ---- 車いす・大城さん（大城さんの根の前：握り 0.26・車いすの根 0.594・後ろの車軸 0.444）
LANE_C = 0.42; R_C = 0.42
AX_AHEAD = 0.444; WC_AHEAD = 0.594
CW = 0.326; CF = 0.640; CBK = -0.430      # 車いす（根から）
NW = 0.28; NF = 0.30; NBK = -0.20         # 大城さんの体（根から・めやす）
EYE_F = 0.10                              # 大城さんの目（根の前）
V_C = 0.8; V_PASS = 0.65; T_SL = 0.8

def stop_dist(v): return v * BR_REACT + v * v / (2 * BR_DEC)

# ---------------------------------------------------------------- 線
Z_ARC = LANE_RB - R_TURN                 # 円弧の始まりの z
C_ARC = (LANE_R + R_TURN, Z_ARC)
L_ARC = R_TURN * math.pi / 2
def robot_pose(s, z0):
    """s：始め（z0）から線に沿った長さ → x, z, 向き（度。0＝+z・90＝+x）"""
    s1 = Z_ARC - z0
    if s <= s1: return LANE_R, z0 + s, 0.0
    if s <= s1 + L_ARC:
        th = (s - s1) / R_TURN
        return C_ARC[0] - R_TURN * math.cos(th), C_ARC[1] + R_TURN * math.sin(th), math.degrees(th)
    return C_ARC[0] + (s - s1 - L_ARC), LANE_RB, 90.0

CC = (RAIL, -RAIL)                       # 車いすが回る中心（手すりの線の角）
L_CARC = R_C * math.pi / 2
def chair_axle(s, x0):
    """s：始め（車軸 x0, z −0.42）から → 車軸 x, z, 向き（度。−90＝−x・−180＝−z）"""
    s1 = x0 - RAIL
    if s <= s1: return x0 - s, -LANE_C, -90.0
    if s <= s1 + L_CARC:
        ps = -90.0 - math.degrees((s - s1) / R_C)
        p = math.radians(ps)
        return CC[0] + R_C * math.cos(p), CC[1] - R_C * math.sin(p), ps
    return LANE_C, CC[1] - (s - s1 - L_CARC), -180.0

def fwd(yaw): y = math.radians(yaw); return np.array([math.sin(y), math.cos(y)])
def rgt(yaw): y = math.radians(yaw); return np.array([math.cos(y), -math.sin(y)])
def rect(cx, cz, yaw, x0, x1, z0, z1):
    f, r, c = fwd(yaw), rgt(yaw), np.array([cx, cz])
    return np.array([c + r * a + f * b for a, b in ((x0, z0), (x1, z0), (x1, z1), (x0, z1))])

def seg_seg(a, b, c, d):
    def pt_seg(p, a, b):
        ab = b - a; u = np.clip(np.dot(p - a, ab) / max(1e-12, np.dot(ab, ab)), 0, 1); return np.linalg.norm(a + ab * u - p)
    return min(pt_seg(a, c, d), pt_seg(b, c, d), pt_seg(c, a, b), pt_seg(d, a, b))
def overlap(P, Q):
    for poly in (P, Q):
        for i in range(len(poly)):
            e = poly[(i + 1) % len(poly)] - poly[i]; n = np.array([-e[1], e[0]])
            a = P @ n; b = Q @ n
            if a.max() < b.min() or b.max() < a.min(): return False
    return True
def poly_dist(P, Q):
    if overlap(P, Q): return 0.0
    return min(seg_seg(P[i], P[(i + 1) % len(P)], Q[j], Q[(j + 1) % len(Q)]) for i in range(len(P)) for j in range(len(Q)))

def blocked(a, b):
    """線分 a→b が内側の角の壁（x>0.90 かつ z<−0.90）を通るか"""
    (ax, az), (bx, bz) = a, b
    # 区間 [0,1] のうち x>WALL の所と z<−WALL の所が重なるか
    def rng(p, q, thr, greater):
        if abs(q - p) < 1e-12: return (0.0, 1.0) if ((p > thr) if greater else (p < thr)) else None
        u = (thr - p) / (q - p)
        inc = (q > p) if greater else (q < p)
        lo, hi = (max(0.0, u), 1.0) if inc else (0.0, min(1.0, u))
        return (lo, hi) if lo < hi else None
    r1 = rng(ax, bx, WALL, True); r2 = rng(az, bz, -WALL, False)
    if r1 is None or r2 is None: return False
    return max(r1[0], r2[0]) < min(r1[1], r2[1]) - 1e-9

def sample_poly(P, n=6):
    out = []
    for i in range(len(P)):
        a, b = P[i], P[(i + 1) % len(P)]
        for k in range(n): out.append(a + (b - a) * k / n)
    return out

def sensor_polys(s, z0, setv):
    L = stop_dist(setv) + NOTICE
    if SENSOR == "straight":
        x, z, y = robot_pose(s, z0)
        return [rect(x, z, y, -SENSOR_W / 2, SENSOR_W / 2, RF, RF + L)]
    out = []; n = 6
    for k in range(n):
        sa = s + RF + L * k / n; sb = s + RF + L * (k + 1) / n
        xa, za, ya = robot_pose(sa - RF, z0); xb, zb, yb = robot_pose(sb - RF, z0)
        pa = np.array([xa, za]) + fwd(ya) * RF; pb = np.array([xb, zb]) + fwd(yb) * RF
        ra, rb = rgt(ya) * SENSOR_W / 2, rgt(yb) * SENSOR_W / 2
        out.append(np.array([pa - ra, pa + ra, pb + rb, pb - rb]))
    return out

def pip(p, P):
    s = None
    for i in range(len(P)):
        a, b = P[i], P[(i + 1) % len(P)]
        c = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
        if abs(c) < 1e-12: continue
        if s is None: s = c > 0
        elif s != (c > 0): return False
    return True

def chair_polys(sc, x0):
    ax, az, ps = chair_axle(sc, x0)
    f = fwd(ps); n = np.array([ax, az]) - f * AX_AHEAD
    return rect(n[0], n[1], ps, -NW, NW, NBK, NF), rect(n[0], n[1], ps, -CW, CW, WC_AHEAD + CBK, WC_AHEAD + CF), n, ps

def simulate(tau, z0, x0, shot, chair_stop=True, verbose=False, T=40.0):
    """shot：fast｜slow。戻り：記録"""
    rs = 0.0; rv = 0.0; mode = "wait"; t_det = None; t_brake = None; t_stopR = None
    cs = 0.0; cv = 0.0; c_mode = "go"; t_seeO = None; t_bO = None; cv_b = None
    log = []; gmin = 9; gmin_t = None
    for f in range(int(T * FPS)):
        t = f * DT
        # ---- 車いす（予定の速さ）
        ax, az, ps = chair_axle(cs, x0)
        to_arc = (x0 - RAIL) - cs
        if t < 0.2: cvt = 0.0
        elif t < 1.2: cvt = V_C * (lambda u: u * u * (3 - 2 * u))((t - 0.2) / 1.0)
        else:
            cvt = V_C if to_arc > 0.58 else V_PASS
        if c_mode == "brake":
            u = min(1.0, (t - t_bO) / (1.6 * cv_b / 0.8))
            cvt = cv_b * (1 - u * u * (3 - 2 * u))
            if u >= 1.0: c_mode = "stopped"
        if c_mode == "stopped": cvt = 0.0
        cv = cvt if c_mode in ("brake", "stopped") else (cv + max(-0.75 * DT, min(0.75 * DT, cvt - cv)) if t >= 1.2 else cvt)
        # ---- ハコブくん
        setv = V_FAST if shot == "fast" else V_SLOW
        x, z, y = robot_pose(rs, z0)
        front = z + RF
        if mode == "wait" and t >= tau: mode = "cruise"
        if mode == "cruise":
            vt = V_FAST
            if shot == "slow":
                # 前の端が角の壁の線（z −0.90）の 2.0 m 手前で 0.4 になるように
                d_to = (-WALL - 2.0) - front
                if y < 1e-6 and d_to <= (rv * rv - V_SLOW * V_SLOW) / (2 * DEC_PLAN) + 1e-6: vt = V_SLOW
                if y > 1e-6 or d_to < 0: vt = V_SLOW
            if vt > rv: rv = min(vt, rv + ACC * DT)
            elif vt < rv: rv = max(vt, rv - DEC_PLAN * DT)
            # センサー（見える物だけ）
            sens = sensor_polys(rs, z0, rv)
            P_n, P_c, nroot, _ = chair_polys(cs, x0)
            eye = np.array([x, z]) + fwd(y) * RF
            hit = False
            for P in (P_c, P_n):
                for p in sample_poly(P, 8):
                    if p[0] >= WALL: continue          # 角の壁の線（x 0.90）より手前に出た所だけ見える（依頼文のとおり）
                    if blocked(eye, p): continue
                    if SENSOR == "see":
                        if np.linalg.norm(p - eye) <= DETECT: hit = True; break
                    elif any(pip(p, S) for S in sens): hit = True; break
                if hit: break
            if hit and t_det is None:
                t_det = t; mode = "react"
        elif mode == "react":
            if t - t_det >= BR_REACT - 1e-9: mode = "brake"; t_brake = t
        if mode == "brake":
            rv = max(0.0, rv - BR_DEC * DT)
            if rv <= 0: mode = "stopped"; t_stopR = t
        if mode in ("cruise", "react", "brake"): rs += rv * DT
        # ---- 大城さんがハコブくんを見る
        x, z, y = robot_pose(rs, z0)
        P_n, P_c, nroot, nps = chair_polys(cs, x0)
        eyeO = nroot + fwd(nps) * EYE_F
        Pr = rect(x, z, y, -RW, RW, -RB, RF)
        if t_seeO is None and t > 0.3 and any(not blocked(eyeO, p) for p in sample_poly(Pr, 6)) and mode != "wait":
            t_seeO = t
        if shot == "fast" and chair_stop and t_seeO is not None and c_mode == "go" and t >= t_seeO + 0.6:
            c_mode = "brake"; t_bO = t; cv_b = cv
        cs += cv * DT
        P_n, P_c, nroot, nps = chair_polys(cs, x0)
        g = min(poly_dist(Pr, P_n), poly_dist(Pr, P_c))
        if g < gmin: gmin = g; gmin_t = t
        log.append((t, x, z, y, rv, mode, cs, cv, c_mode, g))
        if mode == "stopped" and c_mode == "stopped" and t > (t_stopR or 0) + 1: break
        if mode == "stopped" and shot == "slow" and t > t_stopR + 0.5: break
    return dict(t_det=t_det, t_brake=t_brake, t_stopR=t_stopR, t_seeO=t_seeO, t_bO=t_bO, gmin=gmin, gmin_t=gmin_t, log=log, mode=mode)

if __name__ == "__main__":
    z0 = E("Z0", -9.0); x0 = E("X0", 8.0)
    for tau in np.arange(E("T0", 0.0), E("T1", 6.0), E("TS", 0.1)):
        r = simulate(tau, z0, x0, "fast")
        L = r["log"][-1]
        dd = None
        if r["t_det"] is not None:
            i = int(round(r["t_det"] * FPS)); dd = r["log"][i][9]
        print(f"tau {tau:5.2f} det {r['t_det']} stopR {r['t_stopR']} seeO {r['t_seeO']} gmin {r['gmin']:.3f}@{r['gmin_t']} gap_at_det {dd} end x{L[1]:.2f} z{L[2]:.2f} yaw{L[3]:.1f} chair_s {L[6]:.2f} {L[8]}")
```


### run271.sh

```bash
#!/bin/bash
# 依頼271 使い方: run271.sh <出力フォルダ> <場面 corner_fast|corner_slow> <コマ on|off> [静止画 on|off] [views] [from] [to]
OUT="$1"; SH="$2"; FR="${3:-off}"; ST="${4:-off}"; VW="${5:-main,top}"; FROM="${6:--1}"; TO="${7:-1e9}"
UNTIL=$(python3 -c "print($TO + 0.05 if $TO < 1e8 else 1e9)")
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup271.Run \
   -c271Out "$OUT" -c271Shot "$SH" -c271Frames "$FR" -c271Stills "$ST" -c271Views "$VW" -c271From "$FROM" -c271To "$TO" -c271Until "$UNTIL" -logFile "$OUT/unity_${FROM}_${TO}.log"
echo "exit $?"
```


### screen271.py

```python
#!/usr/bin/env python3
"""依頼271：帯（黄 #F2C230）「止まります」だけの絵 c270_back_band.png（screen237.py の band() と同じ描き方。帯の下は透明）。
確かめ：同じ描き方で「お届け完了」→ c223_done_band.png・「お待ちしています」→ c235_wait_band.png・「通れません」（黄）→ c237_stuck_band.png と画素まで同じ
使い方：python3 screen271.py <台本の JSON（screen_ui）> <Textures フォルダ> <screen218.py のフォルダ> <出力フォルダ>"""
import importlib.util, json, sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
js = json.load(open(sys.argv[1])); tex = Path(sys.argv[2]); s218dir, out = sys.argv[3], Path(sys.argv[4])
spec = importlib.util.spec_from_file_location("s218", str(Path(s218dir) / "screen218.py")); m = importlib.util.module_from_spec(spec)
argv0 = sys.argv; sys.argv = sys.argv[:1]; spec.loader.exec_module(m); sys.argv = argv0
S = js["screen_ui"]
def band(text, k=0.46, color=None):
    W = int(S["tex_w"]); H = int(round(W / float(S["aspect"]))); R = int(S["corner_r"] * H)
    mask = Image.new("L", (W, H), 0); ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, H - 1], radius=R, fill=255)
    bh = int(0.2 * H)
    img = Image.new("RGBA", (W, H), m.hexc(S["bg"])); d = ImageDraw.Draw(img)
    d.rectangle([0, 0, W, bh], fill=m.hexc(color or S["band"], int(S.get("band_alpha", 235))))
    d.text((W // 2, bh // 2), text, font=m.font(bh * k), fill=m.hexc(S["fg"]) if color is None else (30, 30, 30, 255), anchor="mm")
    a = img.split()[3]; img.putalpha(Image.composite(a, Image.new("L", (W, H), 0), mask))
    b = np.array(img); b[bh + 1:, :, :] = 0
    return b
for txt, fn, col in (("お届け完了", "c223_done_band.png", None), ("お待ちしています", "c235_wait_band.png", None), ("通れません", "c237_stuck_band.png", "#F2C230"), ("下がります", "c270_back_band.png", "#F2C230"), ("お先にどうぞ", "c228_yield_band.png", None)):
    ref = np.array(Image.open(tex / fn).convert("RGBA")); chk = band(txt, color=col)
    print("確かめ：", txt, "を描くと", fn, "と同じ", chk.shape == ref.shape and bool((chk == ref).all()))
Image.fromarray(band("止まります", color="#F2C230")).save(out / "c271_stop_band.png"); print("作った絵: c271_stop_band.png 止まります（黄・帯だけ）")
```



## 作業ログ ― 依頼279 のコード（KIOXIA の 20261123_closeup270/v279/tools/）


### cmp279.py

```python
import json,sys
def L(t):
    s=open(f"/tmp/c279/{t}/log.txt").read(); return json.loads(s[s.index("\n{")+1:])
o,n=L("old"),L("new")
for a,b in zip(o["shots"],n["shots"]):
    print("==",a["variant"],"dur",a["duration"],"->",b["duration"],"frames",a["frames"],"->",b["frames"])
    for sec in ("events","on"):
        for k in a[sec]:
            va,vb=a[sec][k],b[sec].get(k)
            if va!=vb: print(f" {sec}.{k}: {va} -> {vb}" + (f"  Δ{round(vb-va,4)}" if isinstance(va,(int,float)) and isinstance(vb,(int,float)) else ""))
    for k in a:
        if k not in("events","on","variant","duration","frames") and a[k]!=b[k]: print(" ",k,a[k],"->",b[k])
```


### lufs.sh

```bash
#!/bin/bash
# 1 文ずつ 48 kHz モノラルにして −20 LUFS にそろえる（270 と同じ：ffmpeg ebur128 で測って音量を掛ける）
src="$1"; name="$2"
ffmpeg -v error -y -i "$src" -ac 1 -ar 48000 out/${name}_raw.wav
L=$(ffmpeg -nostats -i out/${name}_raw.wav -af ebur128 -f null - 2>&1 | grep -A2 "Integrated loudness" | grep " I:" | awk '{print $2}')
G=$(python3 -c "print(round(-20.0-($L),2))")
ffmpeg -v error -y -i out/${name}_raw.wav -af "volume=${G}dB" -ar 48000 -ac 1 -c:a pcm_s16le out/${name}.wav
L2=$(ffmpeg -nostats -i out/${name}.wav -af ebur128 -f null - 2>&1 | grep -A2 "Integrated loudness" | grep " I:" | awk '{print $2}')
ffmpeg -v error -y -i out/${name}.wav -c:a libmp3lame -b:a 128k out/${name}.mp3
D=$(ffprobe -v error -show_entries format=duration -of csv=p=0 out/${name}.wav)
echo "$name 元 $L → ${G} dB → $L2 長さ $D"
rm out/${name}_raw.wav
```


### pipe279.sh

```bash
#!/bin/bash
# 依頼279：⑩ の声を差し替えた台本で、確かめ（区切らずに最後まで・静止画も）→ 区切って撮る（270 の pipe270.sh と同じ区切り）
R=/tmp/c279; O=/tmp/c279/out
run_r() { IFS=: read sh a b <<< "$1"; S=$(date +%s); $R/run270.sh $O/${sh}_r $sh on off main,top $a $b; echo "render $sh $a-$b $(( $(date +%s)-S )) s $(ls $O/${sh}_r/frames/$sh | wc -l)"; }
for sh in stretcher_alcove stretcher_back; do S=$(date +%s); $R/run270.sh $O/$sh $sh off on main,top; echo "check $sh $(( $(date +%s)-S )) s"; done
for c in stretcher_alcove:0:11 stretcher_alcove:11:22 stretcher_alcove:22:1e9 stretcher_back:0:14 stretcher_back:14:28 stretcher_back:28:42 stretcher_back:42:56 stretcher_back:56:70 stretcher_back:70:1e9; do run_r $c; done
echo ALLDONE
```
