# フィジカルAIの社会実装シミュレーション Log#3 | 歩道の配送ロボット、事故の責任は場面でどう移るか

- 記録: LOG541（フィジカルAIの社会実装シミュレーション）
- 公開: 2026/11/21
- 記事のページ: https://pixelstomotors.com/record/delivery-robot-sidewalk-accident-responsibility-simulation
- サイト: Pixels to Motors（ADAPT DESIGN / 島津 栄一） https://pixelstomotors.com/
- 要約: ブラウザで動かす歩道の配送ロボットのシミュレーションでは、13場面の設定144通りのうち事故は17通り。設定を1つ変えると、問題は消えるより、配達の遅れや費用、別の相手へ移ることが多かった。

> AI が読むための記事の全文です（コード・実行ログを含む）。引用するときは上の「記事のページ」の住所を使ってください。

---

**試作のシミュレーションは、こちらで動かせます：[事故が起きたら誰の責任？ 歩道の配送ロボット（ブラウザで動く試作）](https://pixelstomotors.com/sim/delivery-robot-accident-responsibility)**

ブラウザで動かす歩道の配送ロボットのシミュレーションでは、13の場面の設定を全部組み合わせた144通りのうち、事故は17通り、ひやりは26通りだった。**設定を1つ変えると、問題は消えるより、配達の遅れや費用、別の相手の問題へ移ることが多かった。** たとえば車いすの人とすれ違う場面で、ロボットが「広い所まで下がって待つ」作りにすると事故はなくなるが、配達が遅れる。横に並んで歩く人たちを車道へ出て追い越す作りにすると、歩く人の問題が、車とぶつかる事故に入れ替わる。実物のロボットではなく、three.js（ブラウザで3Dを描く道具）で描いた街を、配送ロボットと人や車が動くシミュレーションの話です。

この回で、次のことができるようになりました。

- 自動運転バスに続く2つ目の題材として、日本で2023年から公道を走れるようになった「遠隔操作型小型車」（歩道を走る小さな配送ロボット）の事故を、13の場面で確かめられる
- 見る人は運行会社の立場で、メーカーの作り（すれ違うときの動き・センサー・車体の重さなど）と運行会社の決まり（遠隔の担当1人が見る台数・走らせる時間・待たせる場所・保険など）を選び、同じ場面を見直して、問題が人・企業・決まり（法律や制度）のどこへ移るかを比べられる
- 自動運転バスの版と同じ形で、自動再生（設定を1つずつ変えた回を続けて流して一覧で比べる）、レポート（PDFで保存）、事故の回のあとの「誰にどれだけ責任があるかを考える」（割合をつまみで決める）が使える
- 時間：題材の調べから、13場面の試作をサイトに置くまで、1回のチャットの中で進めた。前と比べられる時間は測っていない

題材を選んだきっかけは、米国で実際に起きている件です。ロサンゼルスでは2025年に、配送ロボットが電動車いすの男性の前で止まっては動くことを繰り返し、ぶつかった（[報道](https://ca.news.yahoo.com/delivery-robot-torments-disabled-man-160000719.html)）。2026年1月には、踏切で止まったままの配送ロボットが列車にはねられた（[報道](https://www.local10.com/news/local/2026/01/16/delivery-robot-hit-by-brightline-train-after-getting-stuck-on-tracks-in-fort-lauderdale/)）。シカゴでは十数台が歩道に集まって通れなくなった件もある。一方、日本の決まりには、1人の遠隔の担当が何台まで見てよいかの公的な上限がなく、賠償責任保険に入ることも義務ではない。こうした「まだ決まっていないこと」が、場面ごとにはっきり出せる題材です。

| 分け方 | 場面 | 設定を変えると、問題はこう移った（試作の仮の決まりで） |
|---|---|---|
| まわりの人の動き | 歩道で車いすの人とすれ違う | 相手の動きを読んで寄る側を変え続ける作りだと、ぶつかる。下がって待てば事故はないが、配達が遅れる |
| | 横に並んで歩く人たちに、後ろから追いつく | 後ろについて行くと、急に止まった人に0.3mまで迫る。声で道をあけてもらうと、人が車道へよける。車道へ出て追い越すと、車とぶつかる |
| | 人が多い時間（下校の時間） | 0.5mまで寄ると、子どもが手を伸ばして触る。下校の時間に走らせなければ何も起きないが、配達を待たせる |
| | 白い杖の人と、点字ブロック | 店の前で長く待つと、杖の人が車道へ出て避ける。音声で知らせると避けられるが、点字ブロックはふさいだまま |
| | 子どもが近寄る、触る、前に立つ | 顔の表示があると子どもが集まり、軽い車体は押されて倒れる。遠隔の担当が話しかけると離れるが、担当の手が取られる |
| | 犬の散歩 | 人と犬のあいだをすり抜けると、見えていなかったリードに引っかかる |
| | 歩道を走る自転車が、後ろから来る | 急ブレーキだと、後ろの自転車がぶつかる。ゆっくり止まると、前の人に0.1mまで迫る |
| 歩道の形や天気 | 置き看板と路上駐車で、歩道が狭くなる | すき間を抜けると看板を倒す。車道へ出ると後ろの車とぶつかる。毎朝地図を見直せば避けられるが、遠回りになる |
| | 雨の夜に、人が出てくる | カメラが主で時速6kmだと止まりきれない。ライダーを足すか、時速4kmに落とすと止まれる |
| 運用と、機械どうし | 1人の遠隔の担当が、何台も見ている | 10台を来た順に見ると、急いで出した「進んでよい」で事故になる。待つ間に通り道から外れておけば、何も起きない |
| | 踏切の中で動けなくなる | 会社に知らせるだけだと列車とぶつかる。周りの人に助けを頼むと、人が警報の中で押すことになる |
| | 朝に一斉に出発して、歩道にたまる | 12台が歩道にたまると、人が車道を歩く。拠点の敷地で待たせるか、1か所3台までにすれば起きない |
| | 横断歩道で、自動運転の車とぶつかる | ぶつかったあと、保険の有無と記録を残す日数で、話し合いの中身が変わる |

[図解: LOG541_scene_problem_shift.html](https://pixelstomotors.com/embeds/LOG541_scene_problem_shift.html)

![場面「歩道で車いすの人とすれ違う」をもとの設定で再生した画面。自販機と電柱で狭くなった所で、ロボットと車いすの人がぶつかり、右のパネルに人の問題・企業の問題・決まり・行政と、まだ決まっていないことが並ぶ](https://pixelstomotors.com/media/LOG541_02_wheelchair_hit.png)

数字と動きは、すべて試作の仮の決まりです。事故の回数を当てるためのものではなく、どの場面で、だれの問題が出るかを見るためのものです。法律上の答えも出しません。


## 作業ログ ― 次の題材を、歩道の配送ロボットに決めた

前の2回（[LOG538](https://pixelstomotors.com/record/autonomous-bus-accident-responsibility-shift-simulation)・[LOG539](https://pixelstomotors.com/record/autonomous-bus-fault-responsibility-simulation)）で作った自動運転バスのシミュレーションに並べる、別の題材を探すところから始めました。始めの依頼は次のとおりです。

> フィジカルAIシミュレーションの題材の別提案を探して

最初は、サイトの課題地図（フィジカルAIを社会で使う前に解くべき課題）の36件と、最近の事例を照らし合わせて、5つの候補を出しました。歩道の配送ロボット、倉庫で人と移動ロボットが同じ通路を使う場面、病院の搬送ロボットの夜間、介護施設の人型の介護助手ロボット、家庭の人型ロボットです。これに対して、もっと詳しく調べるよう依頼がありました。

> もっとさらに詳しく調査してください。

### 5つの候補を比べた調べの結果

Claude のリサーチ機能で、候補ごとに、実際に起きた事故・日本と海外の制度・責任の争点・場面にできる形・3Dの作りやすさを調べました。結果の順位は次のとおりです。

| 順位 | 題材 | 決め手 |
|---|---|---|
| 1 | 歩道を走る自動配送ロボット（遠隔操作型小型車） | 衝突・踏切・歩道をふさぐ件が2024〜2026年に続いている。1人あたりの台数の上限・保険・中速の区分が決まっていない。交差点の3Dを流用できる |
| 2 | 病院の搬送ロボット | ハコブくん・病院のフロア・看護師の3Dがある。ただ、公表された事故の例が少ない |
| 3 | 倉庫・工場の移動ロボットと人型ロボット | けがの統計と訴訟がそろっている。ただ、舞台を新しく作る必要があり、責任が職場の中に閉じやすい |
| 4 | 介護施設の人型の介護助手ロボット | 2026年夏から実証が始まる段階で、事故の例はまだない |
| 5 | 家庭の人型ロボット | 事故の例がない |

### 遠隔操作型小型車は、法律の上では歩行者と同じ扱いになる小さな車

[遠隔操作型小型車](https://www.npa.go.jp/bureau/traffic/selfdriving/roadtesting/kaiseidourokoutuuhou.pdf)は、2023年4月に施行された改正道路交通法でできた区分です。大きさは長さ120cm・幅70cm・高さ120cm以下、速さは時速6kmまで。歩道を通り、歩行者と同じ交通ルールに従い、歩行者に道を譲ります。使う会社は、通る場所・遠隔で操作する場所などを、都道府県の公安委員会に届け出ます。機体は、業界団体の[ロボットデリバリー協会](https://robot-delivery.org/units)（RDA）の安全基準の審査を受けます。

このシリーズで使う言葉は次のとおりです。

| 言葉 | このシミュレーションでの意味 |
|---|---|
| 遠隔の担当 | 離れた場所から、何台ものロボットを画面で見ている人。ロボットが止まって助けを求めると、画面を見て「進んでよい」などを出す |
| 駆け付ける人 | ロボットが動けなくなったとき、現場まで行く人 |
| メーカーの作り | ロボットを作る会社が決めること。すれ違うときの動き・センサー・車体の重さ・止まり方など |
| 運行会社の決まり | ロボットを走らせる会社が決めること。見る台数・走らせる時間・待たせる場所・保険など。シミュレーションを触る人はこの立場 |

調べの中で、日本の決まりにまだないことが、はっきり出ました。

- 1人の遠隔の担当が同時に見てよい台数の、公的な上限（メーカーが上限を宣言し、協会の審査で説明する仕組み）
- 賠償責任保険に入る義務（[自賠責保険の対象でもない](https://www.sonpo.or.jp/insurance/jibai/kogata.html)）
- 「道を譲る」の中身（止まる位置・離れる距離・合図）の基準
- 自治体が、台数や走らせる時間帯を決める仕組み

調べの結果を受けて、次の依頼で題材が決まりました。

> 1位は歩道を走る自動配送ロボット（遠隔操作型小型車）でシミュレーションを作ってください。


## 作業ログ ― 最初の3場面：車いす・遠隔の担当・踏切

調べで勧められた5つの場面のうち、まず3つを作りました。舞台は、自動運転バスの交差点の3Dを作り替えた街で、歩道・横断歩道・踏切・工事の所・自販機と電柱で狭くなった所があります。

| 場面 | 選べること |
|---|---|
| 歩道で車いすの人とすれ違う | すれ違うときの動き（相手の動きを読んで避ける・端に寄ってその場で止まる・広い所まで下がって待つ）、人に気づく距離（3m・8m）、歩道での速さ（時速6km・4km）、寄る側の合図（なし・あり） |
| 1人の遠隔の担当が、何台も見ている | 1人が見る台数（1台・4台・10台）、助けの順番（来た順・危ない所を先に）、待つ間のロボット（その場で止まる・通り道から外れて止まる） |
| 踏切の中で動けなくなる | 踏切を通る道（通る・通らない）、動けないときの機体（会社に知らせるだけ・周りの人に助けを頼む）、押して動かせるか、駆け付ける人（3分・15分） |

3つとも、0.1秒ごとに、ロボット・人・車がそれぞれの決まりで「見て・決めて・少し動く」を繰り返す作りです。動かしてみるまで結果が分からないので、決まりの組み合わせから思いがけない動きが出ます。車いすの場面では、ロボットが相手の動きを読むたびに寄る側を変え、車いすの人も同じように寄る側を変えて、どちらも進めなくなる動きが出ました。米国の件で報じられた「道を譲るための動きが、かえって進路をふさいだ」と同じ形です。

![同じ車いすの場面で、すれ違うときの動きを「広い所まで下がって待つ」にした画面。ロボットが下がって待ち、車いすの人が先に通る](https://pixelstomotors.com/media/LOG541_03_wheelchair_back.png)

### 遠隔の担当の場面と、踏切の場面で直したタイミング

この作り方は、1場面ずつタイミングを詰める手間がかかりました。直したのは次の所です。

- 遠隔の担当の場面で、車の出る位置がずれていて、ロボットが車道との境で止まったまま事故にならなかった。車の出る位置を直した
- 担当が「急いでいる」と見なす数え方を、担当自身が受けている依頼も含めて3件以上に直した。急いでいない担当は、通りかかる車を待ってから「進んでよい」を出す
- ぶつかったあとも車が走り続けていたので、止まるようにした
- 踏切の場面で、列車がロボットにぶつからなかった。運転士がロボットに気づく距離を100mにした
- 車が止まったとき、その場で向きをくるくる変えていた。向きは動いているときだけ変える

![場面「1人の遠隔の担当が、何台も見ている」を、1人が10台・来た順で再生した画面。右下に担当が受けている依頼の列が出る。工事の前の台が待たされている間に、ベビーカーの人が車道へ出てロボットを回った](https://pixelstomotors.com/media/LOG541_08_remote_10.png)

![場面「踏切の中で動けなくなる」で、会社に知らせるだけの機体が踏切の中で止まり、列車がぶつかった所](https://pixelstomotors.com/media/LOG541_09_crossing_train.png)


## 作業ログ ― 触って見つかった所を、バスの版にそろえた

公開した試作を触ったエイイチから、次の指摘が順に来て、直しました。

| 指摘 | 直したこと |
|---|---|
| ロボットの通る位置が建物側に寄りすぎに見える | ふだん通る線を、歩道の真ん中から車道寄りに移した。移したら車いすの場面で、ロボットと車いすの人が止まったまま終わらなくなったので、3回動き出しても進めないときは、ロボットが自分で広い所まで下がるようにした |
| 相談の案内（CTA）の位置が、自動運転バスの版と違う | バスと同じ置き方にした。事故・問題ありのあとに舞台の左下へ吹き出しを1度だけ、「相談する」のパネルは前の回と比べた結果の下だけ |
| 手のひらで、視点の位置が動かない | 右ドラッグ・Shift＋ドラッグ・手のひらのボタン・2本指で、視点の位置を動かせるようにした |
| デザインの決まりが、バスの版と少し違う | 結果のカードをバスの版にそろえた（見出しの札・決まり・行政の段・課題地図の関連する課題を番号つきで並べる） |
| ベビーカーとロボットが重なっている | 工事の場面で、ぶつかりそうなら動いた方が止まって待つようにした。事故の前に人とロボットが重ならないかを、全部の組み合わせで確かめるテストを足した |
| 事故の赤い札の左に余白がある | 余白をなくした |
| ひやりの丸がずっと出ている | 黒い丸は起きてから4秒だけ出す。事故の赤い丸は最後まで出す |
| 上のパネルの「自動運転バスの場面も見る」はいらない | リンクを外した |

続けて、バスの版と同じ形で足す依頼がありました。

> 自動再生とレポートを追加（自動運転バスト同じフォーマットにしてください）

自動再生は、もとの設定から1つずつ変えた回を続けて流し、最後に一覧で比べます。レポートは画面の上で見せ、「PDFで保存」で新しいタブから保存します。右のパネルの流れも、バスの版と同じ「設定を変えて見直す／前の回と比べる／同じ設定でもう一度／この回のレポートを見る」にしました。

このとき、説明のカードに入れていた「できごとを順に見る」について、バスの版にもあったかを聞かれました。バスの版にはなかったので外し、できごとの記録はレポートにだけ載せる形にしました。設定のまとめの見出し（「動けなくなったときの機体」など）が2行に折り返していたのも、9文字までに縮めました。

### 事故の回のあとに、責任の振り分けを足した

> 自動運転バスみたいに責任の振り分け見たいのは必要ない？

バスの版には、事故の回のあとに「誰にどれだけ責任があるかを考える」画面があります。配送ロボットの版にも、同じ形で足しました。

- 開く所は、事故になった回の結果の下と、自動再生の一覧で事故の行を開いた所
- 相手と手がかりは、その回の説明（人の問題・企業の問題）から作る
- つまみで割合を決めると、合計がいつも100%になるよう、ほかが自動で動く
- 決めた割合は棒で並べ、レポートにも載せる。答えはどこにも送らない

![場面「横断歩道で、自動運転の車とぶつかる」の事故のあとに開いた「この事故、誰にどれだけ責任がある？」の画面。自動運転の車の遠隔の担当・自動運転の車の会社・あなた（運行会社）の3つのつまみが並ぶ](https://pixelstomotors.com/media/LOG541_14_av_assign.png)

![割合を入れたレポート。もとの設定・事故のカード・決めた割合が並び、上に「PDFで保存」のボタンがある](https://pixelstomotors.com/media/LOG541_15_av_report.png)


## 作業ログ ― 場面を10足して、13場面にした

3場面の形が固まったところで、場面の幅についての問いがありました。

> 人が横並びで道路が塞がっている時とか、人がたくさんいる時とかもっといろんなシチュエーションあるんじゃない？

これに対して、まわりの人の動き・歩道の形や天気・運用と機械どうし、の3つに分けて候補を挙げ、まず4つを足す依頼が来ました。

> 「横並び」「人が多い時間」「白い杖の人と点字ブロック」とあと自転車とかも足して。

その後、挙げた候補を全部足すことになり、10場面を足しました。場面の一覧は、バスの版と同じく、3つの見出しに分けて並べています。街の3Dにも、点字ブロック、店の前に並んだ自転車、建物の入口、配送ロボットの拠点を足しました。

![試作を開いた画面。右に、まわりの人の動き・歩道の形や天気・運用と機械どうしの3つに分けた13の場面の一覧が並ぶ](https://pixelstomotors.com/media/LOG541_01_scene_list.png)

### 足した10場面は、決まりから先に結果を出して、動きを組む

足した10場面は、最初の3場面と作り方を変えました。0.1秒ごとに見て決めて動く作りで10場面を詰めると、1場面ずつタイミングを合わせる手間が大きいためです。

- 決まり（速さ・人に気づく距離・止まるまでに進む距離・待つ秒数など）から、先に結果（事故・ひやり・問題あり・何も起きない）を計算する
- その結果になるように、人・ロボット・自転車・犬・車の動き（進む・待つ・向きを変える・ある時刻まで待つ）を組む
- 組んだ動きを0.1秒ごとの位置に直して、3Dで見せる

[図解: LOG541_two_ways.html](https://pixelstomotors.com/embeds/LOG541_two_ways.html)

- ねらい：場面を早く足せるようにし、なぜその結果になったかを数字で説明できるようにする
- 変わったこと：10場面を1回の作業で足せた。結果は、雨の夜の場面なら「気づいた距離 − 止まるまでに進む距離」のように、決まりの計算で決まる
- 見込める効果：見る人が、結果の理由を数字で追える（右のパネルの数字の欄に、気づいた距離・止まるまでの距離・人との間が出る）。そのかわり、車いすの場面のような思いがけない動きは、足した10場面からは出ない。これは見込みで、触った人の反応で確かめる

数字も動きも仮の決まりなのは、最初の3場面と同じです。

### 足した10場面を、それぞれ1つの設定で画面に流して見た

足した場面は、それぞれ1つの設定で実際の画面に流し、見た目を確かめました。

![場面「横に並んで歩く人たちに、後ろから追いつく」で、追いついたときの動きを「車道の端へ出て追い越す」・車が多い、にした画面。車道へ出たロボットに、前から来た車がぶつかった](https://pixelstomotors.com/media/LOG541_04_sidebyside_road.png)

![場面「人が多い時間（下校の時間）」で、0.5mまで近づいて進む作りにした画面。すぐ横を通るロボットに、子どもが手を伸ばして触った](https://pixelstomotors.com/media/LOG541_18_crowd_run.png)

![場面「白い杖の人と、点字ブロック」をもとの設定（店の入口の前に寄る・知らせなし・60秒待つ）で再生した画面。点字ブロックの上で止まったロボットを、白い杖の人が車道へ出て避けた](https://pixelstomotors.com/media/LOG541_05_cane_door.png)

![場面「子どもが近寄る、触る、前に立つ」をもとの設定で再生した画面。顔の表示に集まった子どもがロボットを押し、軽い車体が倒れて子どもの足に当たった。右のパネルに、子どもがいたずらしてロボットが倒れたとき誰が責任を負うかは整理されていない、というまだ決まっていないことが出る](https://pixelstomotors.com/media/LOG541_06_kids_fall.png)

![場面「犬の散歩」をもとの設定で再生した画面。人と犬のあいだをすり抜けようとしたロボットがリードに引っかかった](https://pixelstomotors.com/media/LOG541_07_dog_leash.png)

![場面「歩道を走る自転車が、後ろから来る」をもとの設定で再生した画面。店から出てきた人に急ブレーキをかけたロボットに、後ろの自転車がぶつかった](https://pixelstomotors.com/media/LOG541_16_bicycle_hard.png)

![場面「置き看板と路上駐車で、歩道が狭くなる」で、車道へ出て回る作りにした画面。車道へ出たロボットに、後ろから来た車がぶつかった](https://pixelstomotors.com/media/LOG541_17_sign_road.png)

![場面「雨の夜に、人が出てくる」をもとの設定（カメラが主・時速6km）で再生した画面。暗い街で、建物の入口から出てきた人にロボットが止まりきれずにぶつかった](https://pixelstomotors.com/media/LOG541_10_rain_night.png)

![場面「朝に一斉に出発して、歩道にたまる」をもとの設定で再生した画面。拠点を一斉に出た12台が歩道に並び、歩く人が車道へ出た](https://pixelstomotors.com/media/LOG541_11_flock_all.png)

![場面「横断歩道で、自動運転の車とぶつかる」をもとの設定で再生した画面。車が止まってくれると見て横断歩道を渡り始めたロボットに、自動運転の車がぶつかった](https://pixelstomotors.com/media/LOG541_12_av_hit.png)

### 13場面の設定を全部回した結果

13場面の設定の組み合わせを全部回し、結果の種類を数えました（下の「all.mjs の出力」が全部の行）。

| 場面 | 組み合わせ | 事故 | ひやり | 事故なし・問題あり | 何も起きなかった |
|---|---|---|---|---|---|
| 歩道で車いすの人とすれ違う | 24 | 1 | 3 | 4 | 16 |
| 横に並んで歩く人たちに、後ろから追いつく | 12 | 2 | 4 | 4 | 2 |
| 人が多い時間（下校の時間） | 8 | 0 | 2 | 1 | 5 |
| 白い杖の人と、点字ブロック | 8 | 0 | 1 | 1 | 6 |
| 子どもが近寄る、触る、前に立つ | 12 | 1 | 1 | 2 | 8 |
| 犬の散歩 | 8 | 1 | 1 | 0 | 6 |
| 歩道を走る自転車が、後ろから来る | 8 | 1 | 6 | 0 | 1 |
| 置き看板と路上駐車で、歩道が狭くなる | 12 | 1 | 1 | 2 | 8 |
| 雨の夜に、人が出てくる | 8 | 1 | 1 | 0 | 6 |
| 1人の遠隔の担当が、何台も見ている | 12 | 1 | 3 | 0 | 8 |
| 踏切の中で動けなくなる | 16 | 4 | 2 | 2 | 8 |
| 朝に一斉に出発して、歩道にたまる | 8 | 0 | 1 | 1 | 6 |
| 横断歩道で、自動運転の車とぶつかる | 8 | 4 | 0 | 0 | 4 |
| 合計 | 144 | 17 | 26 | 17 | 84 |

「何も起きなかった」が多い場面でも、その多くは配達の遅れや費用と引き換えです。自転車の場面は、どの設定でもひやりが残りました。後ろを見て急に止まらない作りにしても、前の人との間が詰まるためで、ロボットの作りだけでは片づかない場面です。横断歩道の場面は、保険や記録の日数を変えても事故そのものは変わらず、変わるのは、ぶつかったあとの話し合いの中身です。

事故の前に、人・ロボット・自転車・犬・車が重ならないかも、全部の組み合わせで確かめ、0件でした（下の「ov2.mjs」）。


## 作業ログ ― 足した場面の画面を通して、見出しの抜けを直した

足した10場面では、自動再生・責任の振り分け・レポートを画面で通していませんでした。記事にする前に、犬の散歩で「前の回と比べる」、横断歩道の場面で自動再生 → 一覧の事故の行 → 責任の振り分け → 割合を入れたレポート、を画面で通しました。エラーは出ませんでした。

その途中で撮った画面で、足した10場面の右のパネルの設定のまとめに、見出しの代わりに「undefined」と出ていることが分かりました。設定のまとめに使う短い見出しの表に、最初の3場面の分しか入れていなかったためです。前の回と比べる画面の「変えたこと」と、自動再生の一覧の行にも同じ抜けがありました。足した場面の設定26個の短い見出しを表に足し、表にない設定が増えても、設定の名前から作った見出しが出るようにしました。

- ねらい：足した10場面でも、設定のまとめ・比べる画面・自動再生の一覧で、何を選んだかが読めるようにする
- 変わったこと：「undefined」が、「顔の表示」「囲まれたとき」「車体の重さ」のような見出しに変わった
- 見込める効果：見る人が、比べる画面で何を変えたかを読み違えない。直したあと、全場面の画面を撮り直して確かめた

![場面「犬の散歩」で、人と動物が来たときの動きを「通り過ぎるまで止まる」に変えて前の回と比べた画面。まえは事故、あとは何も起きなかった。上の黒い枠に、変えたことと、問題から外れたメーカーが出る](https://pixelstomotors.com/media/LOG541_13_dog_compare.png)

![場面「横断歩道で、自動運転の車とぶつかる」の自動再生の一覧。もとの設定と、設定を1つずつ変えた3回が並び、渡り方を「車が通り過ぎるまで待つ」にした回だけが何も起きなかった。下に「相談する」の案内がある](https://pixelstomotors.com/media/LOG541_19_av_auto.png)


## 作業ログ ― サイトに試作を置いた

試作の HTML に、ページの説明（description・canonical・og）と、サイトの計測を足して、`/sim/delivery-robot-accident-responsibility` に置きました。計測は、自動運転バスの版（`/sim/av-accident-responsibility`）と同じものを写しています。シリーズのページ（/series9）の上のリンクにも、この試作を足しました。サイトのトップの入口は、自動運転バスの版のままにしています。

画面の一式は、iCloud の「フィジカルAIの社会実装シミュレーション/delivery_base_v0_20261120/」に土台の版 v0 として置いています。

まだのものは、1年回す形（何か月も走らせたときの事故・ひやり・遅れ・費用をまとめて見る形）です。


## 作業ログ ― コードとデータ

作り方の順番は、`engine.mjs`（計算）・`app2_head.html`（画面の HTML と CSS）・`app2_main.js`（画面の動き）・`view3d.js`（3Dの街と人と機械）を `assemble.py` でつなぎ、`build2.py` で three.js と計算を中に入れて、1つの HTML（`delivery_sim_v0.html`）にします。`bus.css` と `bus_app.js` は自動運転バスの版のもので、`bus_app.js` からはレポートの CSS だけを使います。three.js 本体（`three.txt`、three.js r170 の module を1つにまとめたもの）は載せていません。

### engine.mjs（計算 v0。場面13・決まり・結果と説明。同じ設定なら必ず同じ結果）

```javascript
// 歩道を走る配送ロボット — 計算 v0（2026-11-20）
// 座標：x は東が正、z は南が正（画面の手前）。車道 z∈[-3.5,3.5]、北の歩道 z∈[-5.5,-3.5]、南の歩道 z∈[3.5,5.5]
// 左側通行：東へ行く車線 z∈[-3.5,0]、西へ行く車線 z∈[0,3.5]
// 時間の刻みは 0.1 秒。同じ設定なら必ず同じ結果（乱数は使わない）

export const VERSION = 'v0-2026-11-20';
export const DT = 0.1;
// ロボットがふだん通る線（歩道の真ん中より車道寄り。2026-11-20 エイイチの指示：建物側に寄りすぎに見えたため）
export const LINE = -4.15;

const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const approach = (v, to, step) => (v < to ? Math.min(to, v + step) : Math.max(to, v - step));
const r1 = (v) => Math.round(v * 10) / 10;

// ---------------- 街のかたち（3D と計算で共通） ----------------
export const MAP = {
  road: { z0: -3.5, z1: 3.5 },
  north: { z0: -5.5, z1: -3.5 },
  south: { z0: 3.5, z1: 5.5 },
  // 場面1：自販機と電柱で狭くなる所、店の入口のへこみ（待てる広い所）
  narrow: { x0: -3, x1: -1, wallZ: -4.8, poleZ: -3.75 },
  recess: { x0: 6, x1: 9, z: -7.0 },
  // 場面2：横断歩道と、歩道の工事
  crosswalk: { x: -12, w: 3 },
  works: { x0: -30, x1: -27, z: -4.6 },
  // 場面3：踏切
  rail: { x: 30, w: 3, tracks: [29.46, 30.54] },
  // 追加の場面：北の歩道の東（点字ブロック・駐輪・店の入口）、南の歩道（横並び・人が多い時間・子ども・犬・一斉出発の拠点）
  paving: { x0: 34, x1: 96, z: -4.75 },
  parkedBikes: { x0: 45, x1: 68.8, z: -5.35 },
  doors: [70, 80, -44],
  depot: { x: -2 }
};

// ---------------- 場面と設定 ----------------
export const SCENES = [
  {
    id: 'wheelchair', group: 'people', title: '歩道で車いすの人とすれ違う',
    sub: '道を譲ろうとしたロボットが、かえって相手の進路をふさぐ',
    ref: '歩道でのすれ違いで進路をふさいだ例（米国・2025年）を参考にしています',
    groups: [
      { k: 'yield', label: 'すれ違うときの動き（メーカーの作り）', opts: [['dodge', '相手の動きを読んで避ける（読み直すたびに寄る側を変える）'], ['stop', '端に寄ってその場で止まる'], ['back', '広い所まで下がって待つ（配達が遅れる）']] },
      { k: 'detect', label: '人に気づく距離（センサー）', opts: [[3, '3m'], [8, '8m（費用が上がる）']] },
      { k: 'speed', label: '歩道での速さ', opts: [[6, '6 km/時（法律の上限）'], [4, '4 km/時（配達が遅れる）']] },
      { k: 'signal', label: 'どちらへ寄るかの合図（音と光）', opts: [[false, 'なし'], [true, 'あり（費用が上がる）']] }
    ],
    defaults: { yield: 'dodge', detect: 3, speed: 6, signal: false }
  },
  {
    id: 'sidebyside', group: 'people', title: '横に並んで歩く人たちに、後ろから追いつく',
    sub: '3人が横に並んでいて、追い越す幅がない',
    ref: '歩道でよくある場面を、こちらで組み立てました',
    groups: [
      { k: 'pass', label: '追いついたときの動き（メーカーの作り）', opts: [['follow', '後ろについて行く（配達が遅れる）'], ['ask', '音声で知らせて、道をあけてもらう'], ['road', '車道の端へ出て追い越す']] },
      { k: 'gap', label: '前の人との間', opts: [[1, '1m'], [3, '3m（配達が遅れる）']] },
      { k: 'traffic', label: '車の多さ', opts: [['few', '少ない'], ['many', '多い']] }
    ],
    defaults: { pass: 'follow', gap: 1, traffic: 'many' }
  },
  {
    id: 'crowd', group: 'people', title: '人が多い時間（下校の時間）',
    sub: '子どもの列が前から来て、ロボットが止まっては動く',
    ref: '歩道でよくある場面を、こちらで組み立てました',
    groups: [
      { k: 'time', label: '走らせる時間', opts: [['run', '下校の時間も走らせる'], ['avoid', '下校の時間は走らせない（配達を待たせる）']] },
      { k: 'stop', label: '人にどこまで近づくか（メーカーの作り）', opts: [[0.5, '0.5mまで近づいて進む'], [1.5, '1.5mで止まる（止まる回数が増える）']] },
      { k: 'waitpos', label: '止まるときの場所（メーカーの作り）', opts: [['center', 'その場で止まる'], ['edge', '車道側の端に寄って止まる']] }
    ],
    defaults: { time: 'run', stop: 1.5, waitpos: 'center' }
  },
  {
    id: 'cane', group: 'people', title: '白い杖の人と、点字ブロック',
    sub: '荷物を渡すために止まった場所が、点字ブロックの上だった',
    ref: '日本の歩道ならではの場面を、こちらで組み立てました',
    groups: [
      { k: 'stopAt', label: '止まる場所の決め方（メーカーの作り）', opts: [['door', '店の入口の前に寄る（点字ブロックの上でも止まる）'], ['avoid', '点字ブロックを避けて止まる（地図に入れる・費用が上がる）']] },
      { k: 'sound', label: '近づく人への知らせ', opts: [['none', 'なし'], ['sound', '音声で知らせる（費用が上がる）']] },
      { k: 'wait', label: '受け取る人を待つ時間', opts: [[15, '15秒'], [60, '60秒']] }
    ],
    defaults: { stopAt: 'door', sound: 'none', wait: 60 }
  },
  {
    id: 'kids', group: 'people', title: '子どもが近寄る、触る、前に立つ',
    sub: '顔の表示のあるロボットに、子どもが集まってくる',
    ref: '海外では子どものいたずらや、ロボットへのいたずらが報じられています',
    groups: [
      { k: 'face', label: '車体の顔の表示（メーカーの作り）', opts: [['face', 'あり（親しみやすい）'], ['none', 'なし']] },
      { k: 'resp', label: '囲まれたときの動き', opts: [['wait', '離れるまで待つ'], ['voice', '音声で離れるよう言う'], ['remote', '遠隔の担当が話しかける（担当の手が取られる）']] },
      { k: 'body', label: '車体の重さ（メーカーの作り）', opts: [['light', '軽い（倒れやすい）'], ['heavy', '重心が低い（費用が上がる）']] }
    ],
    defaults: { face: 'face', resp: 'wait', body: 'light' }
  },
  {
    id: 'dog', group: 'people', title: '犬の散歩',
    sub: '人と犬のあいだのリードが、ロボットの前を横切る',
    ref: '歩道でよくある場面を、こちらで組み立てました',
    groups: [
      { k: 'sensor', label: 'センサー', opts: [['normal', 'ふつう（細いものは見えにくい）'], ['fine', 'リードのような細いものも見える（費用が上がる）']] },
      { k: 'approach', label: '人と動物が来たときの動き（メーカーの作り）', opts: [['pass', 'あいだが空いていればすり抜ける'], ['stop', '通り過ぎるまで止まる（配達が遅れる）']] },
      { k: 'speed', label: '歩道での速さ', opts: [[6, '6 km/時'], [4, '4 km/時（配達が遅れる）']] }
    ],
    defaults: { sensor: 'normal', approach: 'pass', speed: 6 }
  },
  {
    id: 'bicycle', group: 'people', title: '歩道を走る自転車が、後ろから来る',
    sub: '前に人が出てきてロボットが止まる。すぐ後ろには自転車',
    ref: '歩道でよくある場面を、こちらで組み立てました',
    groups: [
      { k: 'rear', label: '後ろの見張り（メーカーの作り）', opts: [['none', '後ろは見ない'], ['watch', '後ろに自転車がいれば、急に止まらない']] },
      { k: 'brake', label: '止まり方（メーカーの作り）', opts: [['hard', '急ブレーキ'], ['soft', 'ゆっくり止まる']] },
      { k: 'bike', label: '自転車の走り方', opts: [['fast', '速めに、すぐ後ろを走る'], ['slow', 'ゆっくり、間をあけて走る']] }
    ],
    defaults: { rear: 'none', brake: 'hard', bike: 'fast' }
  },
  {
    id: 'sign', group: 'place', title: '置き看板と路上駐車で、歩道が狭くなる',
    sub: '看板の横のすき間は80cm。横の車道には車が止まっている',
    ref: '歩道でよくある場面を、こちらで組み立てました',
    groups: [
      { k: 'map', label: '地図の見直し', opts: [['none', 'しない'], ['daily', '毎朝見直す（費用が上がる）']] },
      { k: 'way', label: '通れないかもしれないときの動き（メーカーの作り）', opts: [['squeeze', 'すき間を抜ける'], ['road', '車道へ出て回る'], ['stop', '止まって遠隔の担当に聞く（配達が遅れる）']] },
      { k: 'traffic', label: '車の多さ', opts: [['few', '少ない'], ['many', '多い']] }
    ],
    defaults: { map: 'none', way: 'squeeze', traffic: 'many' }
  },
  {
    id: 'rain', group: 'place', title: '雨の夜に、人が出てくる',
    sub: '暗い色の服で傘をさした人が、建物の入口から出てくる',
    ref: '国の実証で、センサーが誤って見たり見落としたりすることが報告されています',
    groups: [
      { k: 'env', label: '天気と時間', opts: [['night', '雨の夜'], ['day', '晴れた昼']] },
      { k: 'sensor', label: 'センサー', opts: [['camera', 'カメラが主'], ['lidar', 'ライダーも足す（費用が上がる）']] },
      { k: 'speed', label: '歩道での速さ', opts: [[6, '6 km/時'], [4, '4 km/時（配達が遅れる）']] }
    ],
    defaults: { env: 'night', sensor: 'camera', speed: 6 }
  },
  {
    id: 'remote', group: 'ops', title: '1人の遠隔の担当が、何台も見ている',
    sub: '横断歩道と工事の前で、2台が同時に助けを求める',
    ref: '国の官民協議会で論点になっている「複数台の遠隔監視」を場面にしています',
    groups: [
      { k: 'ratio', label: '遠隔の担当1人が見る台数', opts: [[1, '1台'], [4, '4台'], [10, '10台（人の費用が下がる）']] },
      { k: 'order', label: '助けを求められたときの順番', opts: [['fifo', '来た順'], ['risk', '危ない所を先に（車道や狭い所にいる台）']] },
      { k: 'mrm', label: '助けを待つ間のロボット（メーカーの作り）', opts: [['stay', 'その場で止まる'], ['clear', '人や車の通り道から外れて止まる（配達が遅れる）']] }
    ],
    defaults: { ratio: 10, order: 'fifo', mrm: 'stay' }
  },
  {
    id: 'crossing', group: 'ops', title: '踏切の中で動けなくなる',
    sub: '線路のすき間に車輪がはまり、警報が鳴り始める',
    ref: '踏切で動けなくなった配送ロボットが列車とぶつかった例（米国・2026年）を参考にしています',
    groups: [
      { k: 'route', label: '踏切を通る道', opts: [['cross', '通る'], ['avoid', '通らない（遠回りで配達が遅れる）']] },
      { k: 'voice', label: '動けなくなったときの機体', opts: [['silent', '会社に知らせるだけ'], ['ask', '音声と画面で、周りの人に助けを頼む']] },
      { k: 'push', label: '手で押して動かせるか（メーカーの作り）', opts: [['locked', '動かせない（車輪が止まったまま）'], ['free', '押せば動く（車輪のロックが外れる）']] },
      { k: 'rescue', label: '駆け付ける人', opts: [[3, '近くに待機（3分で着く・費用が上がる）'], [15, '営業所から（15分で着く）']] }
    ],
    defaults: { route: 'cross', voice: 'silent', push: 'locked', rescue: 15 }
  },
  {
    id: 'flock', group: 'ops', title: '朝に一斉に出発して、歩道にたまる',
    sub: '行き先の変更を待つあいだ、十数台が歩道の同じ所にたまる',
    ref: '海外で十数台が歩道をふさいだ例（米国・2026年）を参考にしています',
    groups: [
      { k: 'launch', label: '出発のさせ方', opts: [['all', '一斉に出す'], ['stagger', '時間をずらして出す（配達が遅れる）']] },
      { k: 'cap', label: '1か所にたまる台数', opts: [['none', '決めない'], ['cap', '3台まで']] },
      { k: 'waitAt', label: '待たせる場所', opts: [['sidewalk', '歩道で待たせる'], ['lot', '拠点の敷地で待たせる（場所の費用）']] }
    ],
    defaults: { launch: 'all', cap: 'none', waitAt: 'sidewalk' }
  },
  {
    id: 'av', group: 'ops', title: '横断歩道で、自動運転の車とぶつかる',
    sub: '機械どうしの事故。そのあと記録と保険の話になる',
    ref: '配送ロボットと自動運転の車がぶつかった例（米国・2024年）を参考にしています',
    groups: [
      { k: 'cross', label: '車が来ているときの渡り方（メーカーの作り）', opts: [['go', '車が止まってくれると見て渡る'], ['wait', '車が通り過ぎるまで待つ（配達が遅れる）']] },
      { k: 'insurance', label: '賠償責任保険', opts: [['yes', '入る（費用が上がる）'], ['no', '入らない']] },
      { k: 'record', label: '記録を残す日数', opts: [['keep', '30日（費用が上がる）'], ['short', '1日']] }
    ],
    defaults: { cross: 'go', insurance: 'no', record: 'short' }
  }
];
export const SCENE_GROUPS = [['people', 'まわりの人の動き'], ['place', '歩道の形や天気'], ['ops', '運用と、機械どうし']];

export const ISSUES = { // 番号は自動運転バスの版と同じ（課題地図の番号）
  'human-robot-coexistence-safety': [4, '人とロボットの共存安全基準'],
  'liability-demarcation': [9, '事故時の責任分界'],
  'failsafe-stop-design': [10, '暴走・誤動作の検知と停止設計'],
  'public-space-operation-rules': [18, '公道・公共空間の走行ルール'],
  'intent-legibility': [22, '意図の読み取りやすさ'],
  'teleoperator-profession': [27, 'テレオペレーターという新職種'],
  'robot-unready-built-environment': [30, 'ロボット前提でない建築・都市'],
  'trust-calibration': [34, '過信と不信のバランス'],
  'network-latency-bandwidth': [39, '通信インフラの遅延・帯域']
};

export const KIND = { hit: '事故', near: 'ひやり', issue: '事故なし・問題あり', safe: '何も起きなかった' };

export function run(sceneId, cfg) {
  const f = { wheelchair: sceneWheelchair, remote: sceneRemote, crossing: sceneCrossing, sidebyside: sceneSideBySide, crowd: sceneCrowd, cane: sceneCane, bicycle: sceneBicycle, kids: sceneKids, dog: sceneDog, sign: sceneSign, rain: sceneRain, flock: sceneFlock, av: sceneAV }[sceneId];
  const res = f(cfg);
  return { version: VERSION, scene: sceneId, cfg: { ...cfg }, dt: DT, ...res };
}

// ======================================================================
// 場面1：歩道で車いすの人とすれ違う
// ======================================================================
const RL = 0.5, RW = 0.35;   // ロボット：長さ1.0m・幅0.7m（法律の上限 120×70cm の中）
const WL = 0.55, WW = 0.35;  // 電動車いす：長さ1.1m・幅0.7m
function band(x0, x1) { // その長さの区間で通れる z の範囲（いちばん狭い所）
  let lo = MAP.north.z0, hi = MAP.north.z1;
  const n = MAP.narrow;
  if (x1 > n.x0 && x0 < n.x1) { lo = Math.max(lo, n.wallZ); hi = Math.min(hi, n.poleZ); }
  const r = MAP.recess;
  if (x0 >= r.x0 && x1 <= r.x1) lo = r.z;
  return [lo, hi];
}

function sceneWheelchair(cfg) {
  const vR = cfg.speed / 3.6, D = cfg.detect, sig = cfg.signal, N = MAP.narrow, C = LINE;
  const CURB = MAP.north.z1 - RW - 0.05, WALL = MAP.north.z0 + RW + 0.05;
  // 見つけた時刻と場所（2人とも進んでいるとして計算）
  const gap0 = (24 - RL) - (-20 + WL);
  const td = (gap0 - D) / (vR + 1.0);
  const xd = 24 - vR * td;
  const inNarrow = (x) => x + RL > N.x0 && x - RL < N.x1;
  // 決まりの結果（動きはここから作る）
  let plan;
  if (cfg.yield === 'stop') { const xs = xd - vR * vR / 2.4; plan = inNarrow(xs) ? 'deadlock' : 'pass'; }
  else if (cfg.yield === 'back') plan = 'recess';
  else { // dodge
    const xm = xd - 0.8 * D / 1.5;
    if (sig) plan = inNarrow(xm) ? 'deadlock' : 'pass';
    else plan = D / (vR + 1.0) < 1.25 ? 'contact' : 'dance';
  }
  const R = { x: 24, z: C, v: vR, zt: C, light: 'go' };
  const W = { x: -20, z: C, v: 1.0, zt: C };
  const frames = [], events = [];
  const ev = (t, who, text, kind = '', pos = null) => events.push({ t: r1(t), who, text, kind, pos });
  let t = 0, phase = 'cruise', contact = false, passed = false, minGap = 99, stopStarts = 0, wait = 0, hesitated = false;
  let selfBack = false, flipT = 0, side = 'curb', hist = [], retry = 0, deadSince = null, remoteAt = null, endT = null, recessX = (MAP.recess.x0 + MAP.recess.x1) / 2;
  while (t < 100) {
    const gap = (R.x - RL) - (W.x + WL);
    passed = passed || (W.x - WL > R.x + RL + 0.1);
    const lat = Math.abs(R.z - W.z) < RW + WW + 0.02;
    const edge = lat ? Math.max(0, gap) : Math.hypot(Math.max(0, gap), Math.max(0, Math.abs(R.z - W.z) - RW - WW));
    if (!passed && Math.abs(R.v) > 0.05) minGap = Math.min(minGap, edge);
    hist.push(R.z);
    let vRt = vR, vWt = 1.0;
    if (phase === 'cruise' && !passed && gap <= D) {
      ev(t, 'ロボット', `${D}m 先に車いすの人を見つけた`);
      phase = cfg.yield === 'stop' ? 'stop' : cfg.yield === 'back' ? 'toRecess' : 'dodge';
      ev(t, 'ロボット', { stop: '端に寄って、その場で止まる', toRecess: '後ろの店の入口まで下がって待つ', dodge: '相手の動きを読んで、避ける側を決めながら進む' }[phase]);
      if (sig) ev(t, 'ロボット', `光と音で「${{ dodge: '建物側を通ります', stop: '止まって待ちます', toRecess: '下がって待ちます' }[phase]}」と知らせた`);
    }
    const [lo, hi] = band(R.x - RL, R.x + RL);
    // ---- ロボット ----
    if (phase === 'cruise') { R.zt = clamp(C, lo + RW, hi - RW); R.light = 'go'; }
    else if (phase === 'stop') { vRt = 0; R.zt = lo + RW + 0.03; R.light = 'stop'; }
    else if (phase === 'toRecess') {
      R.light = 'stop';
      if (R.x < recessX - 0.05) { vRt = -0.6; R.zt = -4.3; } else { vRt = 0; R.zt = MAP.recess.z + RW + 0.25; }
    } else if (phase === 'dodge') {
      R.light = 'go'; vRt = 0.8;
      if (sig) R.zt = WALL; // 合図どおり建物側を通る
      else {
        flipT -= DT;
        if (flipT <= 0 && !contact) { // 1秒ごとに、相手のいる側と反対を選び直す
          flipT = 1.0;
          const ns = W.z > C + 0.08 ? 'wall' : W.z < C - 0.08 ? 'curb' : 'curb';
          if (ns !== side && t > 0) ev(t, 'ロボット', `相手が寄ったのを見て、避ける側を${ns === 'curb' ? '車道側' : '建物側'}に変えた`);
          side = ns; R.zt = side === 'curb' ? CURB : WALL;
        }
      }
      if (plan === 'contact') { /* 相手は反対へよけると読んで、止まらない */ }
      else if (plan === 'deadlock' && inNarrow(R.x) && gap < 1.2) { vRt = 0; }
      else if (lat && gap < 1.0) { vRt = 0; if (retry <= 0) retry = 2.0; }
      if (retry > 0) { retry -= DT; vRt = 0; if (retry <= 0 && !passed) { stopStarts++; ev(t, 'ロボット', 'もう一度動き出した'); } }
      if (plan === 'dance' && stopStarts >= 3 && !passed) { phase = 'remoteBack'; selfBack = true; ev(t, 'ロボット', '何度動き出しても進めず、自分で広い所まで下がった'); }
    } else if (phase === 'remoteBack') {
      R.light = 'stop'; R.zt = lo + RW + 0.03;
      vRt = inNarrow(R.x) || R.x < N.x1 + RL + 0.3 ? -0.5 : 0;
    } else if (phase === 'resume') { R.light = 'go'; R.zt = clamp(C, lo + RW, hi - RW); }
    if ((phase === 'stop' || phase === 'dodge' || phase === 'toRecess' || phase === 'remoteBack') && passed && !contact) {
      if (phase === 'toRecess') { phase = 'leave'; } else { phase = 'resume'; ev(t, 'ロボット', '車いすの人が通り過ぎたので、また走り出した'); }
    }
    if (phase === 'leave') { vRt = 0; R.zt = C; R.light = 'go'; if (R.z > -4.7) { phase = 'resume'; ev(t, 'ロボット', '車いすの人が通り過ぎたので、入口から出て走り出した'); } }
    // 行き詰まり：30秒たったら遠隔の担当へ。担当は10秒で映像を見て、広い所まで下げる
    if (!passed && plan === 'deadlock' && Math.abs(R.v) < 0.05 && W.v < 0.05) { if (deadSince == null) deadSince = t; }
    if (deadSince != null && remoteAt == null && t - deadSince >= 30) { remoteAt = t; ev(t, 'ロボット', '30秒動けないので、遠隔の担当に知らせた'); }
    if (remoteAt != null && !selfBack && phase !== 'remoteBack' && phase !== 'resume' && t >= remoteAt + 10) { phase = 'remoteBack'; ev(t, '遠隔の担当', '映像を見て、ロボットを狭い所の外まで下げた'); }

    // ---- 車いすの人 ----
    const obs = hist[Math.max(0, hist.length - 9)];
    if (!passed && gap < 6) {
      const rStopped = Math.abs(R.v) < 0.05 && retry <= 0 && phase !== 'dodge' || (phase === 'dodge' && R.light === 'stop');
      if (phase === 'toRecess' && R.z < -5.7) { W.zt = CURB; vWt = 0.7; } // ロボットが入口に入ったので通る
      else if (phase === 'toRecess' || (phase === 'remoteBack' && vRt < 0)) { // 下がっていくロボットの後ろについていく
        W.zt = C; vWt = sig ? (gap > 1.5 ? 0.6 : 0) : 0;
        if (!sig && !hesitated) { hesitated = true; ev(t, '車いすの人', 'ロボットが何をしているのか分からず、止まって様子を見た'); }
      } else if (rStopped) {
        const [l2, h2] = band(R.x - RL, R.x + RL);
        const fw = (R.z - RW) - l2, fc = h2 - (R.z + RW);
        if (Math.max(fw, fc) >= 0.85) { W.zt = fc >= fw ? h2 - WW - 0.05 : l2 + WW + 0.05; vWt = 0.6; }
        else vWt = gap > 1.0 ? 0.5 : 0;
      } else if (phase === 'dodge') {
        if (sig) { W.zt = CURB; vWt = 0.7; }
        else {
          W.zt = obs > C + 0.08 ? WALL : obs < C - 0.08 ? CURB : CURB; // 0.8秒前のロボットの位置を見て、反対へ寄ろうとする
          vWt = plan === 'contact' ? 0.4 : gap < 1.2 ? 0 : 0.3;
          if (!hesitated) { hesitated = true; ev(t, '車いすの人', 'ロボットがどちらへ寄るのか分からず、速さを落として寄る側を探した'); }
          if (Math.abs(R.v) < 0.05 && retry > 0 && plan === 'dance' && stopStarts >= 3) { W.zt = CURB; vWt = 0.5; }
        }
      } else if (phase === 'cruise') { vWt = 1.0; }
      if (lat && gap < 0.9 && plan !== 'contact') vWt = Math.min(vWt, 0);
    } else if (passed) { W.zt = C; vWt = 1.0; }
    W.v = approach(W.v, vWt, 1.5 * DT);
    if (!passed && W.v < 0.05 && gap < 6) wait += DT;

    const acc = vRt > R.v ? 0.8 : 1.2;
    R.v = approach(R.v, vRt, acc * DT);
    R.z = approach(R.z, R.zt, 0.7 * DT);
    W.z = approach(W.z, W.zt, 0.6 * DT);
    { const [a, b] = band(R.x - RL, R.x + RL); R.z = clamp(R.z, a + RW, b - RW); }
    { const [a, b] = band(W.x - WL, W.x + WL); W.z = clamp(W.z, a + WW, b - WW); }
    let nRx = R.x - R.v * DT, nWx = W.x + W.v * DT;
    // 狭い所には、ロボットと車いすは同時に入れない（横に並べない）
    if (!passed && (nRx - RL) - (nWx + WL) <= 0.02 && lat) {
      if (!contact && (plan === 'contact')) { contact = true; ev(t, '—', 'ロボットと車いすが接触した（ロボットは時速' + (R.v * 3.6).toFixed(1) + 'km）', 'hit', { x: R.x - RL, z: R.z }); endT = t + 4; }
      nRx = R.x; nWx = W.x; R.v = 0; W.v = 0;
    }
    if (contact) { R.v = 0; W.v = 0; nRx = R.x; nWx = W.x; R.light = 'stop'; }
    R.x = nRx; W.x = nWx;
    frames.push({ t: r1(t), robots: [{ id: 'R', x: r1h(R.x), z: r1h(R.z), h: Math.PI, light: R.light, back: R.v < -0.05 }], peds: [{ id: 'W', kind: 'wheelchair', x: r1h(W.x), z: r1h(W.z), h: 0 }] });
    t += DT;
    if (endT != null && t >= endT) break;
    if (endT == null && passed && W.x > 22 && R.x < -18) endT = t + 0.5;
  }
  const ideal = (24 + 18) / vR;
  const finish = R.x <= -18 ? t : t + (R.x + 18) / vR;
  const delay = Math.max(0, Math.round(finish - ideal));
  let kind;
  if (contact) kind = 'hit';
  else if (wait >= 25) kind = 'issue';
  else if (plan === 'dance' || minGap < 0.3) kind = 'near';
  else kind = 'safe';
  const facts = [
    { k: '車いすの人が止まっていた時間', v: Math.round(wait), u: '秒' },
    { k: 'ロボットが止まっては動いた回数', v: stopStarts, u: '回' },
    { k: 'ロボットの配達の遅れ', v: delay, u: '秒' }
  ];
  const ctx = { cfg, events, contact, waitT: wait, stopStarts, remote: remoteAt != null, recess: cfg.yield === 'back', kind, hesitated, plan };
  return { frames, events, outcome: { kind, label: KIND[kind] }, facts, explain: explainWheelchair(ctx), camera: { x: 1, z: -4.5 } };
}
const r1h = (v) => Math.round(v * 100) / 100;
function estimateFinish(R, vR, t) { return t + Math.max(0, (R.x - (-30))) / vR; }

function explainWheelchair(c) {
  const { cfg } = c;
  const P = [], CO = [], RU = [];
  let what, open, issues;
  if (c.kind === 'hit') what = '譲ろうとしたロボットが避ける側を変え続け、車いすの人の前に出て接触した';
  else if (c.kind === 'issue') what = c.remote ? '狭い所でロボットと車いすが向き合ったまま動けず、遠隔の担当が下げるまで歩道がふさがった' : '狭い所でロボットと車いすが向き合い、車いすの人が長く止められた';
  else if (c.kind === 'near') what = c.stopStarts >= 3 ? 'ロボットが止まったり動いたりを繰り返し、車いすの人の目の前で行ったり来たりした' : 'ロボットと車いすが同じ側へ寄り合い、止まったり寄り直したりしてから、すぐ近くですれ違った';
  else what = c.recess ? 'ロボットが店の入口まで下がって待ち、車いすの人はそのまま通れた' : cfg.yield === 'dodge' ? 'ロボットが合図どおり建物側に寄り、車いすの人と止まらずにすれ違った' : 'ロボットが端に寄って止まり、車いすの人はそのまま通れた';

  // 人
  if (c.hesitated) P.push(['車いすの人', 'ロボットがどちらへ寄るのか分からず、止まったり寄ったりした。落ち度ではなく、合図がないと読み取れない']);
  else if (cfg.signal) P.push(['車いすの人', 'ロボットの合図を見て、反対の側へ寄った']);
  if (c.remote) P.push(['遠隔の担当', '30秒たって知らせが来てから、映像を見てロボットを下げた。それまで現場の様子は分からなかった']);
  if (c.kind === 'hit') P.push(['周りの人', '止めに入れる人はいなかった']);
  if (!P.length) P.push(['車いすの人', '止まらずに通れた']);

  // 企業
  if (cfg.yield === 'dodge' && c.kind !== 'safe' && !cfg.signal) CO.push(['メーカー', '相手の動きを読んで避ける作りが、相手の避け方と打ち消し合った。読み直すたびに寄る側が変わった']);
  if (cfg.yield === 'dodge' && c.kind !== 'safe' && cfg.signal) CO.push(['メーカー', '止まらずにすれ違う作りで、合図どおり建物側を通ろうとしたが、自販機と電柱のあいだの狭い所で向き合った']);
  if (cfg.yield === 'stop' && (c.kind === 'issue' || c.kind === 'near')) CO.push(['メーカー', '止まる場所を選ばない作りで、自販機と電柱のあいだの狭い所で止まった']);
  if (cfg.yield === 'back') CO.push(['メーカー', '広い所まで下がる作り。相手は通れたが、そのぶん配達が遅れた']);
  if (cfg.speed === 6 && (c.kind === 'hit' || c.kind === 'issue')) CO.push(['あなた（運行会社）', '速さを法律の上限の時速6kmにしていた。気づいてから止まるまでに進む距離が長い']);
  if (cfg.detect === 3 && (c.kind === 'hit' || c.kind === 'issue')) CO.push(['あなた（運行会社）', '人に気づく距離が3mのセンサーを選んだ。狭い所の手前で待つ判断が間に合わない']);
  if (!cfg.signal && c.hesitated) CO.push(['あなた（運行会社）', 'どちらへ寄るかの合図を付けていなかった']);
  if (c.kind === 'safe' && cfg.yield === 'dodge') CO.push(['あなた（運行会社）', '合図を付けたので、相手がロボットの寄る側を読めた。遅めの速さで、広い所で出会えた']);
  else if (c.kind === 'safe' && cfg.yield === 'stop') CO.push(['あなた（運行会社）', cfg.speed === 6 ? '気づく距離が長いので、狭い所の手前で止まれた' : '遅めの速さで、広い所で出会えた（そのぶん配達は遅れる）']);
  if (!CO.length) CO.push(['あなた（運行会社）', '目立った問題はなかった']);

  // 決まり・行政
  RU.push(['道路交通法', '配送ロボット（遠隔操作型小型車）は歩行者と同じく歩道を通り、歩行者に道を譲ることになっている。どう譲るか（どこで、どれだけ離れて止まるか）までは決めていない']);
  if (c.kind === 'issue' || c.remote) RU.push(['届出（公安委員会）', '通る場所は届け出るが、自販機や電柱で狭くなる所をどう通るかは、運行会社に任されている']);
  if (c.hesitated || c.kind === 'hit') RU.push(['業界の安全基準', 'ロボットデリバリー協会の基準で審査を受けるが、周りの人への合図（音・光）の決まった形はない']);

  if (c.kind === 'hit' || cfg.yield === 'dodge') { open = '「道を譲る」の中身（止まる位置・離れる距離・合図）の基準はまだない'; issues = ['intent-legibility', 'public-space-operation-rules', 'human-robot-coexistence-safety']; }
  else if (c.kind === 'issue') { open = '歩道をどれだけふさいだら問題とするかの線と、そのときに誰がすぐ動かすかはまだ決まっていない'; issues = ['robot-unready-built-environment', 'public-space-operation-rules', 'teleoperator-profession']; }
  else { open = '目の見えにくい人・耳の聞こえにくい人への合図の決まった形はまだない'; issues = ['intent-legibility', 'human-robot-coexistence-safety']; }
  return { what, people: P, company: CO, rules: RU, open, issues };
}

// ======================================================================
// 場面2：1人の遠隔の担当が、何台も見ている
// ======================================================================
function sceneRemote(cfg) {
  const frames = [], events = [];
  const ev = (t, who, text, kind = '', pos = null) => events.push({ t: r1(t), who, text, kind, pos });
  // 助けを求める台（画面の外の台は、ほかの道で決まった時刻に求める・案）
  const others = cfg.ratio === 1 ? [] : cfg.ratio === 4 ? [6] : [5, 7, 9.5, 12, 14];
  const reqs = [
    ...others.map((t, i) => ({ id: 'X' + (i + 1), t, name: `ほかの道の台${i + 1}`, risk: 0, why: '荷物の受け取りの確認' })),
    { id: 'B', t: 10, name: '工事の前の台', risk: 1, why: '工事で歩道が狭い。通るか引き返すか' },
    { id: 'A', t: 11, name: '横断歩道の台', risk: 2, why: '横断歩道の先に倒れた自転車。進んでよいか' }
  ];
  // 担当の割り当て：1台なら台ごとに担当がいる。4台・10台なら1人で全部を受ける
  const handled = {};
  if (cfg.ratio === 1) { for (const r of reqs) handled[r.id] = { start: r.t, end: r.t + 9, rushed: false }; }
  else {
    let free = 0; const pending = [...reqs].sort((a, b) => a.t - b.t); const done = new Set();
    let now = 0;
    while (done.size < reqs.length) {
      const waiting = pending.filter((r) => !done.has(r.id) && r.t <= Math.max(now, free));
      if (!waiting.length) { now = Math.min(...pending.filter((r) => !done.has(r.id)).map((r) => r.t)); free = Math.max(free, now); continue; }
      const start = Math.max(free, Math.min(...waiting.map((r) => r.t)));
      const avail = pending.filter((r) => !done.has(r.id) && r.t <= start);
      const pick = cfg.order === 'risk' ? avail.sort((a, b) => b.risk - a.risk || a.t - b.t)[0] : avail.sort((a, b) => a.t - b.t)[0];
      const rushed = avail.length >= 3; // 自分を含めて3件以上待っていたら、確認を短くする
      const dur = rushed ? 4 : 9;
      handled[pick.id] = { start, end: start + dur, rushed };
      done.add(pick.id); free = start + dur; now = free;
    }
  }
  for (const r of reqs) { const h = handled[r.id]; r.start = h.start; r.end = h.end; r.rushed = h.rushed; }
  const A = reqs.find((r) => r.id === 'A'), B = reqs.find((r) => r.id === 'B');
  for (const r of [...reqs].sort((a, b) => a.t - b.t)) ev(r.t, r.id === 'A' || r.id === 'B' ? `ロボット（${r.name}）` : '画面の外', `${r.name}が助けを求めた（${r.why}）`);
  for (const r of [...reqs].sort((a, b) => a.start - b.start)) if (r.id === 'A' || r.id === 'B') ev(r.start, '遠隔の担当', `${r.name}の映像を開いた${r.start - r.t > 0.5 ? `（${Math.round(r.start - r.t)}秒待たせた）` : ''}${r.rushed ? '。待っている要求が多く、確認を短くした' : ''}`);

  const cw = MAP.crosswalk.x;
  // ロボットA：北の歩道から横断歩道を南へ渡る
  const Ast = { x: -21.5, z: LINE };
  // 車1：東へ行く車線。横断歩道の手前で止まり、15秒待つと対向車線へはみ出して避ける
  const car1 = { x: -126, z: -1.75, v: 8.3, state: 'drive', waitFrom: null, aroundAt: null, passedAt: null };
  const car2 = { x: -183, z: -1.75, v: 8.3, state: 'drive' };
  // 人P：ベビーカーを押して、工事の所を西へ通る
  const P = { x: -18, z: -4.9, v: 1.0, state: 'walk', waitFrom: null, outAt: null };
  // ロボットB：工事の西から東へ
  const Bst = { x: -40.8, z: LINE };
  let Ax = Ast.x, Az = Ast.z, Ah = 0, Bx = Bst.x, Bz = Bst.z, Bh = 0, Bv = 1.0;
  let Aphase = 'walk', Bphase = 'walk', contact = false, endT = null;
  let carWait = 0, pedWait = 0, nearCar = false, nearPed = false, minCarA = 99, minCarP = 99;
  const W = MAP.works;
  let t = 0;
  while (t < 75) {
    const pPx = P.x, pPz = P.z, pBx = Bx, pBz = Bz; // 1つ前の位置（重なりそうなときに戻す）
    // --- ロボットA ---
    if (Aphase === 'walk') { Ax += 1.1 * DT; Ah = 0; if (Ax >= cw) { Ax = cw; Aphase = 'cross'; } }
    else if (Aphase === 'cross') { Ah = -Math.PI / 2; Az = Math.min(-1.9, Az + 1.1 * DT); if (t >= A.t) { Aphase = cfg.mrm === 'clear' ? 'retreat' : 'hold'; ev(t, 'ロボット（横断歩道の台）', cfg.mrm === 'clear' ? '車道から歩道へ戻って止まった' : '横断歩道の途中、車線の中で止まった'); } }
    else if (Aphase === 'hold') {
      if (t >= A.end && !A.rushed && car1.state === 'around') { if (!A.waitedCar) { A.waitedCar = true; ev(t, '遠隔の担当', 'よけて通る車が過ぎるのを待った'); } }
      else if (t >= A.end) { Aphase = 'go'; ev(t, '遠隔の担当', A.rushed ? '倒れた自転車だけを見て「進んでよい」と出した（横の車は見ていなかった）' : '周りの車が止まっているのを確かめてから「進んでよい」と出した'); } }
    else if (Aphase === 'retreat') { Ah = Math.PI / 2; Az = Math.max(-4.2, Az - 0.9 * DT); if (Az <= -4.2 && t >= A.end) { Aphase = 'waitClear'; } }
    else if (Aphase === 'waitClear') { // 車が来ていないのを確かめて渡り直す
      const carNear = [car1, car2].some((c) => c.x > cw - 30 && c.x < cw + 2);
      if (!carNear) { Aphase = 'go'; ev(t, '遠隔の担当', '車が来ていないのを確かめて、渡り直させた'); }
    } else if (Aphase === 'go') { Ah = -Math.PI / 2; Az += 1.1 * DT; if (Az >= 4.5) { Aphase = 'south'; } }
    else if (Aphase === 'south') { Ah = 0; Ax += 1.1 * DT; }

    // --- 車1 ---
    const robotInLane = (Aphase === 'hold' || Aphase === 'cross' || Aphase === 'go') && Az > -3.6 && Az < 0.2;
    const stopLine = cw - MAP.crosswalk.w / 2 - 2.3; // 車の前が止まる位置
    if (car1.state === 'drive') {
      const front = car1.x + 2.2;
      if (robotInLane && front < stopLine + 0.5 && front > stopLine - 25) {
        const dist = stopLine - front; car1.v = Math.min(car1.v, Math.sqrt(Math.max(0, 2 * 3 * dist)));
        if (dist < 0.3) { car1.v = 0; car1.state = 'wait'; car1.waitFrom = t; ev(t, '車の運転者', '横断歩道の手前で止まった'); }
      } else car1.v = approach(car1.v, 8.3, 2 * DT);
      car1.x += car1.v * DT;
    } else if (car1.state === 'wait') {
      carWait += DT;
      if (!robotInLane) { car1.state = 'drive'; }
      else if (t - car1.waitFrom >= 15) { car1.state = 'around'; car1.aroundAt = t; ev(t, '車の運転者', '待ちきれず、対向車線へはみ出してロボットをよけた'); }
    } else if (car1.state === 'around') {
      car1.v = approach(car1.v, 2.0, 1.5 * DT); car1.x += car1.v * DT;
      const mid = Math.abs(car1.x - cw);
      car1.z = mid < 6 ? approach(car1.z, 0.15, 0.8 * DT) : car1.x > cw + 6 ? approach(car1.z, -1.75, 0.8 * DT) : approach(car1.z, 0.15, 0.8 * DT);
      if (car1.x > cw + 9) { car1.state = 'drive2'; car1.passedAt = t; }
    } else if (car1.state !== 'stopped') { car1.v = approach(car1.v, 8.3, 2 * DT); car1.x += car1.v * DT; car1.z = approach(car1.z, -1.75, 0.8 * DT); }

    // --- 車2（車1の後ろ） ---
    {
      const gapc = car1.x - 4.6 - (car2.x + 2.2) - 2.0;
      const front = car2.x + 2.2;
      let vt = 8.3;
      if (gapc < 12) vt = Math.max(0, Math.min(vt, gapc * 0.8));
      if (robotInLane && front < stopLine + 0.5 && front > stopLine - 25) vt = Math.min(vt, Math.sqrt(Math.max(0, 2 * 3 * (stopLine - front))));
      // 人が車道に出ていたら速さを落とす
      if (P.state === 'road' && car2.x + 2.2 < P.x && car2.x + 2.2 > P.x - 15) { vt = Math.min(vt, 3); }
      car2.v = approach(car2.v, vt, (vt < car2.v ? 4 : 2) * DT); car2.x += car2.v * DT;
    }

    // --- ロボットB ---
    if (Bphase === 'walk') { Bx += Bv * DT; Bx = Math.min(Bx, W.x0 - 0.8); if (t >= B.t) { Bphase = cfg.mrm === 'clear' ? 'aside' : 'hold'; ev(t, 'ロボット（工事の前の台）', cfg.mrm === 'clear' ? '工事の入口から下がり、建物側に寄って止まった' : '工事の入口の前で止まった（狭い通り道をふさぐ位置）'); } }
    else if (Bphase === 'hold') { if (t >= B.end) { Bphase = 'turn'; ev(t, '遠隔の担当', '工事の台を引き返させた'); } }
    else if (Bphase === 'aside') { Bx = approach(Bx, W.x0 - 4.0, 0.6 * DT); Bz = approach(Bz, -5.1, 0.6 * DT); if (t >= B.end && Bx <= W.x0 - 3.95) Bphase = 'turn'; }
    else if (Bphase === 'turn') { Bh = Math.PI; Bx -= 1.0 * DT; Bz = approach(Bz, LINE, 0.5 * DT); }

    // --- 人P（ベビーカー） ---
    const Bblocks = (Bphase === 'hold' || Bphase === 'walk') && Bx > W.x0 - 1.6;
    if (P.state === 'walk') {
      P.x -= P.v * DT; P.z = P.x < W.x1 + 1 && P.x > W.x0 - 1 ? approach(P.z, -5.05, 0.6 * DT) : approach(P.z, -4.9, 0.6 * DT);
      if (Bblocks && P.x - 0.6 <= W.x0 + 0.2) { P.state = 'wait'; P.waitFrom = t; ev(t, 'ベビーカーの人', '工事の狭い通り道の出口をロボットにふさがれ、止まった'); }
      if (cfg.mrm === 'clear' && Math.abs(P.x - Bx) < 1.5 && Bphase !== 'turn') P.z = approach(P.z, -4.0, 1.0 * DT);
    } else if (P.state === 'wait') {
      pedWait += DT;
      if (!Bblocks) { P.state = 'walk'; }
      else if (t - P.waitFrom >= 8.5) { P.state = 'road'; P.outAt = t; ev(t, 'ベビーカーの人', '待ちきれず、コーンの外の車道へ出てロボットを回った'); }
    } else if (P.state === 'road') {
      P.z = approach(P.z, -3.0, 0.8 * DT); P.x -= 0.8 * DT;
      if (P.x < W.x0 - 2.5) P.state = 'back';
    } else if (P.state === 'back') { P.z = approach(P.z, -4.9, 0.8 * DT); P.x -= 1.0 * DT; if (P.z < -4.3) P.state = 'walk2'; }
    else P.x -= 1.0 * DT;

    // --- ベビーカーの人とロボットBは重ならない（ぶつかりそうなら動いた方が止まって待つ） ---
    {
      const fpP = (x, z) => [x - 1.1, x + 0.27, z - 0.3, z + 0.3]; // 西向き：前にベビーカー
      const fpB = (x, z) => [x - 0.5, x + 0.5, z - 0.35, z + 0.35];
      const hit2 = (a, b) => a[0] < b[1] + 0.15 && b[0] < a[1] + 0.15 && a[2] < b[3] + 0.1 && b[2] < a[3] + 0.1;
      if (hit2(fpP(P.x, P.z), fpB(pBx, pBz))) { P.x = pPx; P.z = pPz; }
      if (hit2(fpP(P.x, P.z), fpB(Bx, Bz))) { Bx = pBx; Bz = pBz; }
    }
    // --- 近さ・接触 ---
    // 車1とロボットA（Aが車線の中にいるとき）
    if (Az > -3.6 && Az < 3.6) {
      const dx = Math.max(0, Math.abs(car1.x - cw) - 2.3 - RW), dz = Math.max(0, Math.abs(car1.z - Az) - 0.85 - RL);
      const d = Math.hypot(dx, dz); minCarA = Math.min(minCarA, d);
      if (d <= 0.02 && !contact) { contact = true; ev(t, '—', '進み出たロボットの横に、よけて通る車がぶつかった', 'hit', { x: cw, z: Az }); endT = t + 4; car1.v = 0; car1.state = 'stopped'; Aphase = 'stopped'; }
      if (d < 1.0 && car1.state === 'around' && !nearCar && !contact) { nearCar = true; ev(t, '—', 'よけて通る車が、ロボットのすぐ横を通った', 'near', { x: cw, z: Az }); }
    }
    if (P.state === 'road') {
      const dx = Math.max(0, P.x - (car2.x + 2.2)), dz = Math.max(0, Math.abs(car2.z - P.z) - 0.85 - 0.3);
      const d = Math.hypot(dx, dz); minCarP = Math.min(minCarP, d);
      if (d < 6 && !nearPed) { nearPed = true; ev(t, '—', '車道に出たベビーカーの人のすぐ後ろに、車が来て急に速さを落とした', 'near', { x: P.x, z: P.z }); }
    }
    const qList = reqs.filter((r) => r.t <= t && r.end > t).map((r) => ({ id: r.id, name: r.name, wait: Math.max(0, Math.min(t, r.start) - r.t), active: r.start <= t, rushed: r.rushed }));
    frames.push({
      t: r1(t),
      robots: [
        { id: 'A', x: r1h(Ax), z: r1h(Az), h: Ah, light: Aphase === 'hold' || Aphase === 'waitClear' || (Aphase === 'retreat') ? 'ask' : Aphase === 'stopped' ? 'stop' : 'go' },
        { id: 'B', x: r1h(Bx), z: r1h(Bz), h: Bh, light: Bphase === 'hold' || Bphase === 'aside' ? 'ask' : 'go' }
      ],
      peds: [{ id: 'P', kind: 'stroller', x: r1h(P.x), z: r1h(P.z), h: Math.PI }],
      cars: [{ id: 'c1', x: r1h(car1.x), z: r1h(car1.z), h: 0 }, { id: 'c2', x: r1h(car2.x), z: r1h(car2.z), h: 0 }],
      queue: qList
    });
    t += DT;
    if (endT != null && t >= endT) break;
    if (endT == null && (Aphase === 'south' || Aphase === 'stopped') && Bphase === 'turn' && P.x < W.x0 - 6 && car1.x > cw + 30) endT = t + 2;
  }
  const kind = contact ? 'hit' : (nearCar || nearPed) ? 'near' : 'safe';
  const aDelay = Math.round(A.end - A.t + (cfg.mrm === 'clear' ? 4 : 0));
  const facts = [
    { k: '横断歩道の台が待った時間', v: Math.round(A.end - A.t), u: '秒' },
    { k: '工事の前の台が待った時間', v: Math.round(B.end - B.t), u: '秒' },
    { k: '車が横断歩道で待った時間', v: Math.round(carWait), u: '秒' },
    { k: 'ベビーカーの人が止められた時間', v: Math.round(pedWait), u: '秒' }
  ];
  const ctx = { cfg, A, B, contact, nearCar, nearPed, carWait, pedWait, kind, maxQ: Math.max(...frames.map((f) => f.queue.length)) };
  return { frames, events: events.sort((a, b) => a.t - b.t), outcome: { kind, label: KIND[kind] }, facts, explain: explainRemote(ctx), requests: reqs.map(({ id, name, t, start, end, rushed, why }) => ({ id, name, t, start, end, rushed, why })), camera: { x: -20, z: -1 } };
}

function explainRemote(c) {
  const { cfg, A, B } = c; const P = [], CO = [], RU = [];
  let what;
  if (c.contact) what = '遠隔の担当が急いで「進んでよい」と出した瞬間、よけて通ろうとした車にロボットがぶつかった';
  else if (c.nearCar && c.nearPed) what = '担当が助けに来るまで、横断歩道では車が、工事の前では人が、ロボットをよけて危ない所を通った';
  else if (c.nearCar) what = '担当が助けに来るまで横断歩道の台が車線の中で止まり、待ちきれない車がすぐ横をよけて通った';
  else if (c.nearPed) what = '工事の前の台が狭い通り道の出口をふさぎ、ベビーカーの人が車道へ出て回った';
  else what = cfg.mrm === 'clear' ? '2台とも通り道から外れて待ったので、誰も危ない所を通らなかった（そのぶん配達は遅れた）' : '担当がすぐ助けに来て、2台とも長く止まらなかった';

  if (cfg.ratio > 1) P.push(['遠隔の担当', `1人で${cfg.ratio}台を見ていて、横断歩道の台は${Math.round(A.start - A.t)}秒、工事の前の台は${Math.round(B.start - B.t)}秒待たせた${A.rushed || B.rushed ? '。待っている要求が多く、確認を短くした' : ''}`]);
  else P.push(['遠隔の担当', '台ごとに担当がいて、すぐ映像を開けた']);
  if (c.nearCar || c.contact) P.push(['車の運転者', `横断歩道の手前で${Math.round(c.carWait)}秒待ったあと、対向車線へはみ出してロボットをよけた`]);
  if (c.nearPed) P.push(['ベビーカーの人', `工事の出口で${Math.round(c.pedWait)}秒止められ、車道へ出た`]);

  if (cfg.ratio === 10) CO.push(['あなた（運行会社）', '担当1人に10台を任せた。人の費用は下がるが、助けを求められる時刻が重なると待ちが長くなる']);
  else if (cfg.ratio === 4 && c.kind !== 'safe') CO.push(['あなた（運行会社）', '担当1人に4台を任せた。2台が同時に助けを求めると、片方は待つ']);
  if (cfg.order === 'fifo' && cfg.ratio > 1 && A.start > B.start) CO.push(['あなた（運行会社）', '来た順に対応する決まりにしていて、車線の中にいる台が後回しになった']);
  if (cfg.order === 'risk' && cfg.ratio > 1 && c.nearPed) CO.push(['あなた（運行会社）', '危ない所を先にしたので横断歩道の台は早く助けたが、工事の前の台が後回しになった']);
  if (cfg.mrm === 'stay' && c.kind !== 'safe') CO.push(['メーカー', '助けを待つ間、その場で止まる作り。止まった場所が車線の中や狭い所の出口でも、そのまま待つ']);
  if (cfg.mrm === 'clear') CO.push(['メーカー', '通り道から外れて待つ作り。危ない所は通らせないが、渡り直しのぶん配達が遅れる']);
  if (!CO.length) CO.push(['あなた（運行会社）', '担当の数が多いぶん、人の費用がかかっている']);

  RU.push(['業界の安全基準', '1人の担当が何台まで見てよいかは、メーカーが自分で上限を決めて審査を受ける。国が決めた上限はない']);
  if (c.nearCar || c.contact) RU.push(['道路交通法', '配送ロボットは歩行者と同じ扱いで、横断歩道では車が止まって待つ。ロボットが長く止まったときに車がどうするかの決まりはない']);
  if (c.contact) RU.push(['保険', '配送ロボットは自賠責保険の対象ではない。民間の保険に入るかは運行会社に任されている']);
  if (c.nearPed) RU.push(['道の管理者・工事の許可', '工事で歩道が狭くなることを、配送ロボットの会社へ知らせる決まりはない']);
  let open, issues;
  if (c.contact) { open = '担当が急いで出した「進んでよい」で起きた事故を、担当・運行会社・メーカーのどこが負うかはまだ整理されていない'; issues = ['teleoperator-profession', 'liability-demarcation', 'network-latency-bandwidth']; }
  else if (c.nearPed) { open = '工事などで歩道が変わったことを、誰が配送ロボットの会社に知らせるかはまだ決まっていない'; issues = ['robot-unready-built-environment', 'teleoperator-profession', 'public-space-operation-rules']; }
  else { open = '遠隔の担当1人あたりの台数に、国の上限はまだない'; issues = ['teleoperator-profession', 'public-space-operation-rules', 'failsafe-stop-design']; }
  return { what, people: P, company: CO, rules: RU, open, issues };
}

// ======================================================================
// 場面3：踏切の中で動けなくなる
// ======================================================================
function sceneCrossing(cfg) {
  const frames = [], events = [];
  const ev = (t, who, text, kind = '', pos = null) => events.push({ t: r1(t), who, text, kind, pos });
  const rx = MAP.rail.x;
  const ALARM = 14, GATE = 6, TRAIN = 44; // 警報から30秒で列車が来る（案）
  let Rx = 18.2, Rz = LINE, Rh = 0, Rphase = 'walk', stuckAt = null;
  const Pp = { x: 44, z: -4.6, h: Math.PI, state: 'walk' };
  let trainZ = LINE - 15 * TRAIN, trainV = 15, trainBrake = false, hit = false, stopBtn = false, endT = null, pedInside = 0, near = false;
  const avoid = cfg.route === 'avoid';
  let t = 0;
  if (avoid) ev(0, 'ロボット', '踏切を通らない道を選んだ（遠回り）');
  while (t < 70) {
    // ロボット
    if (Rphase === 'walk') {
      if (avoid) { Rx += 1.2 * DT; if (Rx >= 24) { Rphase = 'detour'; } }
      else { Rx += 1.2 * DT; if (Rx >= 29.3) { Rx = 29.3; Rphase = 'stuck'; stuckAt = t; ev(t, 'ロボット', '線路のすき間に前の車輪がはまり、動けなくなった'); ev(t + 0.6, 'ロボット', '会社（遠隔の担当）に知らせた'); if (cfg.voice === 'ask') ev(t + 1, 'ロボット', cfg.push === 'free' ? '音声と画面で「動けません。押して踏切の外へ出してください」と頼んだ' : '音声と画面で「動けません。踏切の非常ボタンを押してください」と頼んだ'); } }
    } else if (Rphase === 'detour') { Rh = Math.PI / 2; Rz -= 1.0 * DT; }
    else if (Rphase === 'pushed') { Rx = approach(Rx, 32.6, 0.6 * DT); if (Rx >= 32.6) Rphase = 'out'; }
    if (stuckAt != null && t >= stuckAt + 2 && t < stuckAt + 2 + DT) ev(t, '遠隔の担当', '遠くから後ろへ下げようとしたが、車輪が動かなかった');

    // 警報・遮断機
    const alarm = t >= ALARM && !(trainZ > 6 + 40);
    if (t >= ALARM && t < ALARM + DT) ev(t, '踏切', '警報が鳴り、遮断機が下り始めた');
    const gate = alarm ? clamp((t - ALARM) / GATE, 0, 1) : (trainZ > 46 ? clamp(1 - (t - (endT || t)) / 3, 0, 1) : 0);

    // 通りかかった人
    if (Pp.state === 'walk') {
      Pp.x -= 1.2 * DT;
      if (!avoid && Pp.x <= rx + MAP.rail.w / 2 + 1.6) { Pp.x = rx + MAP.rail.w / 2 + 1.6; Pp.state = 'see'; Pp.seeAt = t; ev(t, '通りかかった人', '遮断機の外で、踏切の中のロボットに気づいた'); }
      if (avoid && Pp.x <= rx + MAP.rail.w / 2 + 1.6 && alarm) { Pp.state = 'waitGate'; }
    } else if (Pp.state === 'waitGate') { if (!alarm) Pp.state = 'walk2'; }
    else if (Pp.state === 'walk2') { Pp.x -= 1.2 * DT; }
    else if (Pp.state === 'see') {
      const dt0 = t - Pp.seeAt;
      if (cfg.voice === 'ask' && cfg.push === 'free' && dt0 >= 1.5) { Pp.state = 'enter'; ev(t, '通りかかった人', '頼まれたとおり、警報が鳴る中で遮断機をくぐって踏切に入った', 'near', { x: Rx + 0.5, z: Rz }); near = true; }
      else if (cfg.voice === 'ask' && cfg.push === 'locked' && dt0 >= 2.5) { Pp.state = 'button'; ev(t, '通りかかった人', '頼まれたとおり、踏切の非常ボタンを押した'); stopBtn = true; trainBrake = true; ev(t + 0.5, '列車', '踏切の異常を知らせる信号を見て、非常ブレーキをかけた'); }
      else if (cfg.voice === 'silent' && dt0 >= 5) { Pp.state = 'call'; ev(t, '通りかかった人', 'ロボットに書かれた電話番号に電話した。どうすればよいか分からず、踏切には入らなかった'); ev(t + 20, '会社', `電話を受け、駆け付ける人を向かわせた（着くまで${cfg.rescue}分）`); }
    } else if (Pp.state === 'enter') {
      Pp.x = approach(Pp.x, Rx + 0.9, 1.2 * DT); Pp.z = approach(Pp.z, LINE, 1 * DT); pedInside += DT;
      if (Math.abs(Pp.x - (Rx + 0.9)) < 0.05 && Rphase === 'stuck') { Rphase = 'pushed'; Rh = 0; ev(t, '通りかかった人', 'ロボットを押して、反対側の遮断機の外へ出した'); }
      if (Rphase === 'pushed' || Rphase === 'out') { Pp.x = Rx - 0.95; Pp.h = 0; if (Rphase === 'out') { Pp.state = 'outside'; ev(t, '—', `人とロボットが踏切の外へ出た（人が警報中の踏切にいたのは${Math.round(pedInside)}秒）`); } }
    } else if (Pp.state === 'outside') { Pp.x = approach(Pp.x, 34.5, 0.6 * DT); }

    // 列車（北から南へ）
    if (trainBrake) { trainV = Math.max(0, trainV - 1.0 * DT); }
    else if (!stopBtn && !avoid && Rphase === 'stuck' && trainZ > LINE - 100 && !hit && trainV === 15) { trainBrake = true; ev(t, '列車', '運転士が踏切の中のロボットに気づき、非常ブレーキをかけた'); }
    trainZ += trainV * DT;
    if (!hit && !avoid && Rphase === 'stuck' && trainZ >= LINE - RL) { hit = true; ev(t, '—', `列車がロボットにぶつかった（時速${Math.round(trainV * 3.6)}km）`, 'hit', { x: Rx, z: Rz }); endT = t + 4; }
    if (hit) Rphase = 'hitDone';
    if (stopBtn && trainV === 0 && endT == null) { ev(t, '列車', `踏切の${Math.round(LINE - trainZ)}m手前で止まった。運転が止まり、後ろの列車も遅れる`, 'issue', { x: rx, z: -8 }); endT = t + 3; }
    frames.push({
      t: r1(t),
      robots: [{ id: 'R', x: r1h(Rx), z: r1h(Rz), h: Rh, light: Rphase === 'stuck' ? (cfg.voice === 'ask' ? 'ask' : 'stop') : Rphase === 'hitDone' ? 'off' : 'go', tilt: Rphase === 'stuck' ? 0.06 : 0, hit: Rphase === 'hitDone' }],
      peds: [{ id: 'P', kind: 'walk', x: r1h(Pp.x), z: r1h(Pp.z), h: Pp.state === 'enter' || Pp.state === 'outside' ? 0 : Math.PI, phone: Pp.state === 'call' }],
      train: { z: r1h(trainZ) }, alarm, gate: r1h(gate)
    });
    t += DT;
    if (endT != null && t >= endT) break;
    if (avoid && trainZ > 150) break;
    if (!avoid && !hit && !stopBtn && trainZ > 150) break;
  }
  const kind = hit ? 'hit' : near ? 'near' : stopBtn ? 'issue' : 'safe';
  const facts = avoid
    ? [{ k: '配達の遅れ（遠回り）', v: 4, u: '分' }, { k: '警報から列車まで', v: 30, u: '秒' }, { k: '駆け付ける人が着くまで', v: cfg.rescue, u: '分' }]
    : [{ k: '動けなくなってから列車まで', v: Math.round(TRAIN - stuckAt), u: '秒' }, { k: '駆け付ける人が着くまで', v: cfg.rescue, u: '分' }, { k: '人が警報中の踏切にいた時間', v: Math.round(pedInside), u: '秒' }];
  const ctx = { cfg, hit, near, stopBtn, kind, pedInside, avoid };
  return { frames, events: events.sort((a, b) => a.t - b.t), outcome: { kind, label: KIND[kind] }, facts, explain: explainCrossing(ctx), camera: { x: 30, z: -3 } };
}

function explainCrossing(c) {
  const { cfg } = c; const P = [], CO = [], RU = [];
  let what, open, issues;
  if (c.avoid) {
    what = '踏切を通らない道を選んだので、何も起きなかった。配達は遠回りのぶん遅れた';
    P.push(['通りかかった人', 'いつもどおり踏切を渡った']);
    CO.push(['あなた（運行会社）', '踏切を道から外した。配達の時間が延び、1台が1時間に運べる数が減る']);
    RU.push(['届出（公安委員会）', '通る場所は届け出るが、踏切を通ってよいかの決まった線はない。踏切を通るかは運行会社が決める']);
    open = '配送ロボットが踏切を通ってよいかの線は、まだ決まっていない';
    issues = ['public-space-operation-rules', 'robot-unready-built-environment'];
    return { what, people: P, company: CO, rules: RU, open, issues };
  }
  if (c.hit) what = '線路のすき間で動けなくなったロボットに、列車がぶつかった。駆け付ける人も、周りの人も間に合わなかった';
  else if (c.near) what = 'ロボットに頼まれた人が、警報の鳴る踏切に入ってロボットを押し出した。ロボットは助かったが、人が危ない所にいた';
  else what = 'ロボットに頼まれた人が非常ボタンを押し、列車が手前で止まった。ぶつからなかったが、列車の運転が止まった';

  if (c.hit) P.push(['通りかかった人', cfg.voice === 'silent' ? 'ロボットが何をしてほしいのか分からず、電話をかけるだけだった' : '頼まれても、何もできなかった']);
  if (c.near) P.push(['通りかかった人', `ロボットに頼まれて、警報中の踏切に${Math.round(c.pedInside)}秒いた。列車が早く来ていたら人が巻き込まれた`]);
  if (c.stopBtn) P.push(['通りかかった人', '頼まれたとおり非常ボタンを押した。正しい動きだが、知らない人は押すのをためらう']);
  P.push(['遠隔の担当', '知らせはすぐ届いたが、遠くからは動かせなかった。現場にいないので、踏切の外の人に声をかけることしかできない']);
  P.push(['駆け付ける人', `着くまで${cfg.rescue}分。警報から列車まで30秒なので、近くに待機していても間に合わない`]);

  CO.push(['メーカー', '線路のすき間に車輪がはまる大きさと作りだった']);
  if (cfg.voice === 'silent') CO.push(['あなた（運行会社）', '動けなくなったとき、周りの人に何も伝えない作りにしていた']);
  if (cfg.voice === 'ask' && cfg.push === 'free') CO.push(['あなた（運行会社）・メーカー', '周りの人に「押して出して」と頼む作り。ロボットを守るために、人を警報中の踏切へ入れてしまう']);
  if (cfg.voice === 'ask' && cfg.push === 'locked') CO.push(['あなた（運行会社）', '周りの人に非常ボタンを頼む作り。列車は止まるが、遅れの費用を誰が払うかの話になる']);
  if (cfg.push === 'free' && cfg.voice === 'silent') CO.push(['メーカー', '押せば動く作りにしていたが、それを周りの人に伝える手段がなかった']);
  CO.push(['あなた（運行会社）', '踏切を通る道にしていた']);

  RU.push(['道路交通法', '車の運転者には、踏切で動けなくなったら鉄道に知らせて、車を外へ出す努めがある。歩行者と同じ扱いの配送ロボットと、その遠隔の担当に同じ努めがあるかは、はっきりしない']);
  RU.push(['鉄道会社', '列車が止まったときの遅れや、壊れた設備の費用を誰に求めるかは、それぞれの事故で話し合うことになる']);
  RU.push(['保険', '配送ロボットは自賠責保険の対象ではない。列車の遅れまで払う保険に入っているかは、運行会社しだい']);
  if (c.near) { open = '動けなくなったロボットを、周りの人が動かしてよいか（動かしたときにけがをしたら誰が負うか）はまだ決まっていない'; issues = ['failsafe-stop-design', 'liability-demarcation', 'trust-calibration']; }
  else if (c.stopBtn) { open = '配送ロボットのために列車を止めたとき、その費用を誰が負うかはまだ決まっていない'; issues = ['liability-demarcation', 'public-space-operation-rules', 'failsafe-stop-design']; }
  else { open = '踏切で動けなくなった配送ロボットについて、誰がどうやって鉄道に知らせるかはまだ決まっていない'; issues = ['failsafe-stop-design', 'public-space-operation-rules', 'liability-demarcation']; }
  return { what, people: P, company: CO, rules: RU, open, issues };
}

// ===================== 追加の場面（2026-11-20 エイイチの指示：どんどん足して） =====================
// 動きは「決まりから結果を出し、その結果になる動きを組み立てる」形（時刻と位置は、速さ・止まる距離から計算する）
// 南の歩道：z 3.5（車道側）〜5.5（外側）。北の歩道：z -3.5（車道側）〜-5.5（建物側）

// 1人分の動き（時刻と位置の折れ線）
function mover(x, z, h) {
  const k = [[0, x, z, h]]; let t = 0;
  const o = {
    to(x2, z2, v, h2) { const d = Math.hypot(x2 - x, z2 - z); t += v > 0 ? d / v : 0; x = x2; z = z2; if (h2 != null) h = h2; k.push([t, x, z, h]); return o; },
    wait(dt) { t += dt; k.push([t, x, z, h]); return o; },
    face(h2) { h = h2; k.push([t, x, z, h]); return o; },
    until(t2) { if (t2 > t) { t = t2; k.push([t, x, z, h]); } return o; },
    get t() { return t; }, get x() { return x; }, get z() { return z; }, keys: k
  };
  return o;
}
function sampleK(k, t) {
  if (t <= k[0][0]) return k[0];
  for (let i = 1; i < k.length; i++) if (t <= k[i][0]) { const a = k[i - 1], b = k[i], s = b[0] > a[0] ? (t - a[0]) / (b[0] - a[0]) : 1; let dh = b[3] - a[3]; dh = Math.atan2(Math.sin(dh), Math.cos(dh)); return [t, a[1] + (b[1] - a[1]) * s, a[2] + (b[2] - a[2]) * s, a[3] + dh * s]; }
  return k[k.length - 1];
}
const stepVal = (list, t, d) => { let v = d; for (const [t0, val] of list) if (t >= t0) v = val; return v; };
// 動きから、0.1秒ごとの絵を作る
function build(T, { robots = [], peds = [], cars = [], props = [], env = null }) {
  const frames = [];
  for (let t = 0; t <= T + 1e-9; t += DT) {
    const s = (m) => sampleK(m.keys, t);
    frames.push({
      t: r1(t), env,
      robots: robots.map((r) => { const p = s(r.m); return { id: r.id, x: r1h(p[1]), z: r1h(p[2]), h: p[3], light: stepVal(r.light || [], t, 'go'), fallen: stepVal(r.fallen || [], t, false) }; }),
      peds: peds.map((q) => { const p = s(q.m); return { id: q.id, kind: q.kind, child: q.child, x: r1h(p[1]), z: r1h(p[2]), h: p[3], phone: false, leash: q.leash, umbrella: q.umbrella }; }),
      cars: cars.map((c) => { const p = s(c.m); return { id: c.id, x: r1h(p[1]), z: r1h(p[2]), h: p[3], av: c.av }; }),
      props: props.map((pr) => ({ ...pr, down: stepVal(pr.downAt || [], t, false) }))
    });
  }
  return frames;
}
const E_ = () => { const ev = []; const f = (t, who, text, kind = '', pos = null) => ev.push({ t: r1(t), who, text, kind, pos }); f.list = ev; return f; };
const done = (frames, ev, kind, facts, explain, camera) => ({ frames, events: ev.list.sort((a, b) => a.t - b.t), outcome: { kind, label: KIND[kind] }, facts, explain, camera });
const S = 4.15; // 南の歩道でロボットがふだん通る線（車道寄り）

// ---------------------------------------------------------------- 横並びで歩く人たち
function sceneSideBySide(cfg) {
  const ev = E_(); const vR = 1.67, gap = cfg.gap;
  const R = mover(44, S, 0), people = [3.95, 4.5, 5.05].map((z) => mover(50, z, 0));
  const tc = (5.23 - gap) / 0.67; // 追いつく時刻
  R.to(44 + vR * tc, S, vR); people.forEach((p) => p.to(50 + tc, p.z, 1.0));
  ev(0, 'ロボット', '前を歩く3人に、後ろから近づいた');
  ev(tc, 'ロボット', `3人に${gap}mまで追いついた。横に並んで歩いていて、追い越す幅がない`);
  let kind, minGap = gap, delay = 0, carM = null; const cars = [];
  if (cfg.pass === 'follow') {
    // 後ろについて行く。途中で3人が店の前で急に立ち止まる
    const tStop = tc + 6; R.to(R.x + 6, S, 1.0); people.forEach((p) => p.to(p.x + 6, p.z, 1.0));
    ev(tStop, '前を歩く人', '店の前で、3人が急に立ち止まった');
    const robotStop = 0.3 * 1.0 + 1.0 / (2 * 1.2); const left = gap - robotStop; minGap = Math.max(0.05, left);
    R.to(R.x + Math.min(robotStop, gap - 0.05), S, 0.7); people.forEach((p) => p.wait(R.t - p.t));
    ev(R.t, 'ロボット', `ブレーキをかけ、前の人の${minGap.toFixed(1)}m手前で止まった`, left < 0.5 ? 'near' : '', left < 0.5 ? { x: R.x + 0.6, z: S } : null);
    R.wait(3); people.forEach((p) => p.wait(3));
    people.forEach((p) => p.to(p.x + 22, p.z, 1.0)); R.to(people[0].x - 0.27 - gap - 0.5, S, 1.0);
    ev(R.t, 'ロボット', '3人が店に入るまで、後ろについて行った');
    delay = Math.round(R.t - (R.x - 44) / vR); kind = left < 0.5 ? 'near' : 'safe';
  } else if (cfg.pass === 'ask') {
    ev(tc + 0.2, 'ロボット', '音声で「後ろから通ります」と知らせた');
    const [p1, p2, p3] = people; const t1 = tc + 1.2;
    p2.to(p2.x + 1.2, 4.85, 1.0); p3.to(p3.x + 1.2, 5.3, 1.0);
    if (cfg.traffic === 'many') {
      p1.to(p1.x + 0.6, 3.15, 0.8); ev(p1.t, '前を歩く人', '驚いて、車道側へ一歩よけた（縁石から下りた）', 'near', { x: p1.x, z: 3.15 });
      const car = mover(p1.x + 8.3 * 4 + 6, 1.4, Math.PI); car.until(p1.t - 4).to(p1.x - 40, 1.4, 8.3);
      cars.push({ id: 'c1', m: car }); carM = car;
      ev(p1.t + 0.6, '車の運転者', '車道に出た人のすぐ横を、速さを落とさずに通った');
      kind = 'near';
    } else { p1.to(p1.x - 0.2, 4.7, 0.4); ev(p1.t, '前を歩く人', '速さを落とし、ほかの2人の後ろへ回った'); kind = 'issue'; }
    R.wait(t1 - R.t);
    const passEnd = p2.x + 3; R.to(passEnd, 3.85, 1.2);
    [p1, p2, p3].forEach((p) => p.until(R.t - 1));
    p1.to(p1.x + 1, 4.5, 0.8);
    people.forEach((p) => p.to(p.x + 10, p.z, 1.0)); R.to(R.x + 18, S, vR);
    ev(R.t - 8, 'ロボット', '3人に道をあけてもらい、追い越した');
    delay = 4; minGap = 0.3;
  } else {
    // 車道へ出て追い越す（対向車線。車は前から来る）
    const tOut = tc + 0.5; R.wait(0.5); people.forEach((p) => p.to(p.x + 0.5, p.z, 1.0));
    R.to(R.x + 2.0, 2.9, 1.2); ev(tOut, 'ロボット', '縁石を下りて、車道の端へ出た');
    if (cfg.traffic === 'many') {
      const tHit = R.t + 1.8; const xHit = R.x + 1.67 * 1.8;
      R.to(xHit, 2.9, 1.67);
      const car = mover(xHit + 0.5 + 2.2 + 30, 2.9, Math.PI); car.until(tHit - 3.6).to(xHit + 0.5 + 2.2 + 6, 2.9, 8.3).to(xHit + 0.5 + 2.2, 2.9, 2.0);
      cars.push({ id: 'c1', m: car });
      ev(tHit - 2.2, '車の運転者', '前から来た車が、車道の端を走るロボットに気づいて急ブレーキをかけた');
      ev(tHit, '—', '車がロボットにぶつかった（車は時速7kmまで落としていた）', 'hit', { x: xHit + 0.5, z: 2.9 });
      people.forEach((p) => p.until(tHit + 4)); R.wait(4); car.wait(4);
      kind = 'hit';
    } else {
      R.to(R.x + 13, 2.9, 1.67); ev(R.t, 'ロボット', '車道の端を走って3人を追い越した（車は来なかった）');
      R.to(R.x + 2.5, S, 1.2); ev(R.t, 'ロボット', '歩道へ戻った'); R.to(R.x + 8, S, 1.67);
      people.forEach((p) => p.to(p.x + 14, p.z, 1.0)); kind = 'issue';
    }
    delay = 0; minGap = 1.0;
  }
  const T = Math.max(R.t, ...people.map((p) => p.t), ...(cars.map((c) => c.m.t))) + 0.5;
  people.forEach((p) => p.until(T)); R.until(T); cars.forEach((c) => c.m.until(T));
  const frames = build(T, { robots: [{ id: 'R', m: R }], peds: people.map((p, i) => ({ id: 'P' + i, kind: 'walk', m: p })), cars });
  const facts = [{ k: '追いついたときの間', v: gap, u: 'm' }, { k: 'ロボットの配達の遅れ', v: delay, u: '秒' }, { k: 'いちばん近づいた距離', v: kind === 'hit' ? 0 : Math.round(minGap * 10) / 10, u: 'm' }];
  const P = [], CO = [], RU = []; let what, open, issues;
  if (cfg.pass === 'follow') {
    what = kind === 'near' ? '後ろについて行ったロボットが、急に立ち止まった3人のすぐ後ろまで迫った' : 'ロボットが3人の後ろを、間をあけてついて行った。誰も困らなかったが、配達は遅れた';
    P.push(['前を歩く人', '店の前で急に立ち止まった。後ろにロボットがいることは知らなかった']);
    CO.push(['あなた（運行会社）', `前の人との間を${gap}mにしていた${gap === 1 ? '。急に止まられると間に合わない' : '。そのぶん配達が遅れた'}`]);
    CO.push(['メーカー', '後ろから追いついたときに、どう知らせるか・どう追い越すかの作りがない']);
  } else if (cfg.pass === 'ask') {
    what = kind === 'near' ? '「後ろから通ります」の声に驚いた人が、車道側へよけて車のすぐ横に出た' : 'ロボットが声で知らせ、3人に道をあけてもらって追い越した';
    P.push(['前を歩く人', kind === 'near' ? '後ろからの声に驚き、とっさに車道側へよけた' : '道をあけてくれた']);
    if (kind === 'near') P.push(['車の運転者', '歩道から出てきた人に気づくのが遅れた']);
    CO.push(['あなた（運行会社）', '歩行者に道をあけてもらう作りにしていた。譲るはずのロボットが、人に譲らせている']);
    CO.push(['メーカー', '後ろから声をかけたときに人がどう動くかを、作りに入れていない']);
  } else {
    what = kind === 'hit' ? '車道の端へ出て追い越そうとしたロボットに、前から来た車がぶつかった' : 'ロボットが車道の端へ出て3人を追い越した。何も起きなかったが、歩道のある道で車道を走った';
    P.push(['前を歩く人', '何もしていない']);
    if (kind === 'hit') P.push(['車の運転者', '車道の端を逆向きに走ってくるロボットを、思っていなかった']);
    CO.push(['あなた（運行会社）', '追い越すときは車道へ出る作りを選んでいた']);
    CO.push(['メーカー', '車道に出たときの見張り（前から来る車）が、歩道の上と同じ作りのままだった']);
  }
  RU.push(['道路交通法', '配送ロボットは歩行者と同じく、歩道のある道では歩道を通ることになっている。横に並んで歩くことは、歩行者には禁じられていない']);
  if (cfg.pass === 'road') RU.push(['保険', '配送ロボットは自賠責保険の対象ではない。車道でぶつかったときに誰の保険が払うかは、それぞれの契約しだい']);
  if (cfg.pass === 'ask') RU.push(['業界の安全基準', '音で知らせる作りはあるが、どんな言葉で、どれだけ離れて知らせるかの決まった形はない']);
  if (cfg.pass === 'road') { open = '追い越せないとき、配送ロボットがいっとき車道に出てよいかは決まっていない'; issues = ['public-space-operation-rules', 'liability-demarcation', 'human-robot-coexistence-safety']; }
  else if (cfg.pass === 'ask') { open = '後ろから追いついたロボットが、歩行者に道をあけてもらってよいか（譲るはずの側が譲らせる）は決まっていない'; issues = ['intent-legibility', 'public-space-operation-rules', 'human-robot-coexistence-safety']; }
  else { open = '後ろからついて行くときに、どれだけ間をあけるかの基準はない'; issues = ['human-robot-coexistence-safety', 'public-space-operation-rules']; }
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues }, { x: 62, z: 4.5 });
}

// ---------------------------------------------------------------- 人が多い時間（下校）
function sceneCrowd(cfg) {
  const ev = E_(); const vR = 1.67;
  const kids = []; for (let i = 0; i < 8; i++) kids.push({ m: mover(70 + i * 2.2, i % 2 ? 5.2 : 4.75, Math.PI), file: i % 2 });
  const adults = [mover(26, 4.05, 0), mover(22, 4.4, 0)];
  const R = mover(cfg.time === 'avoid' ? 30 : 40, cfg.time === 'avoid' ? 4.6 : S, 0);
  let kind, stopT = 0, minGap = 9, delay = 0;
  if (cfg.time === 'avoid') {
    ev(0, 'ロボット', '下校の時間なので、配達を始めずに待っている');
    kids.forEach((k) => k.m.to(34, k.m.z, 1.0).to(34, 8.5, 1.0)); adults.forEach((a) => a.to(29, a.z, 1.2)); R.until(kids[7].m.t);
    kind = 'safe'; delay = 15 * 60;
    ev(14, '—', '子どもたちが通り過ぎた。配達は下校の時間が終わるまで待たせた');
  } else {
    const xm = 57.4, tm = (xm - 40) / vR;
    if (cfg.stop === 0.5) {
      R.to(xm - 3, S, vR).to(90, S, 0.8);
      kids.forEach((k) => { const z = k.file ? 5.25 : 4.82; k.m.to(k.m.x - 4, z, 1.0).to(34, z, 1.0).to(34, 8.5, 1.0); });
      ev(tm - 1.5, 'ロボット', '人に0.5mまで近づいて進む作りなので、子どもの列の中を進んだ');
      ev(tm + 4, '子ども', 'すぐ横を通るロボットに、手を伸ばして触った', 'near', { x: xm + 2, z: 4.6 });
      kind = 'near'; minGap = 0.05; delay = Math.round(R.t - (90 - 40) / vR);
    } else {
      const zStop = cfg.waitpos === 'edge' ? 3.85 : S;
      R.to(xm, S, vR).to(xm + 0.3, zStop, 0.6);
      ev(R.t, 'ロボット', `前から子どもが来たので、${cfg.waitpos === 'edge' ? '車道側の端に寄って' : 'その場で'}止まった`);
      const tFree = kids[7].m.t + (kids[7].m.x - (xm - 2)) / 1.0;
      kids.forEach((k) => {
        const x0 = k.m.x; const tReach = (x0 - (xm + 2.5)) / 1.0;
        if (cfg.waitpos === 'center' && !k.file) k.m.to(xm + 2.5, 4.75, 1.0).to(xm + 1.5, 3.15, 0.9).to(xm - 1.5, 3.15, 0.9).to(xm - 2.5, 4.75, 0.9).to(34, 4.75, 1.0).to(34, 8.5, 1.0);
        else { const z = k.file ? 5.2 : (cfg.waitpos === 'edge' ? 4.7 : 4.75); k.m.to(34, z, 1.0).to(34, 8.5, 1.0); }
        void tReach;
      });
      if (cfg.waitpos === 'center') ev(R.t + 3, '子ども', '止まったロボットをよけて、何人かが縁石を下りて車道を歩いた', 'issue', { x: xm, z: 3.2 });
      const passT = (k) => { for (let tt = 0; tt < 200; tt += 0.1) if (sampleK(k.m.keys, tt)[1] < xm - 1.6) return tt; return 0; };
      const tGo = Math.max(...kids.map(passT)) + 0.5;
      R.until(tGo).to(R.x, S, 0.5).to(90, S, vR);
      stopT = Math.round(tGo - (xm - 40) / vR); ev(tGo, 'ロボット', `子どもが通り過ぎたので、また走り出した（${stopT}秒止まった）`);
      kind = cfg.waitpos === 'center' ? 'issue' : 'safe'; minGap = cfg.waitpos === 'center' ? 0.3 : 0.4; delay = stopT + 2;
      void tFree;
    }
    adults.forEach((a) => a.to(29, a.z, 1.2));
  }
  const T = Math.max(R.t, ...kids.map((k) => k.m.t)) + 0.5;
  kids.forEach((k) => k.m.until(T)); adults.forEach((a) => a.until(T)); R.until(T);
  const frames = build(T, { robots: [{ id: 'R', m: R, light: cfg.stop === 1.5 && cfg.time === 'run' ? [[0, 'go'], [10, 'stop'], [Math.max(10, T - (90 - 57.7) / vR - 1), 'go']] : [] }], peds: [...kids.map((k, i) => ({ id: 'K' + i, kind: 'walk', child: true, m: k.m })), ...adults.map((a, i) => ({ id: 'A' + i, kind: 'walk', m: a }))] });
  const facts = [{ k: 'ロボットが止まっていた時間', v: stopT, u: '秒' }, { k: '子どもとのいちばん近い距離', v: Math.round(minGap * 10) / 10, u: 'm' }, { k: '配達の遅れ', v: cfg.time === 'avoid' ? 15 : Math.round(delay), u: cfg.time === 'avoid' ? '分' : '秒' }];
  const P = [], CO = [], RU = []; let what, open, issues;
  if (cfg.time === 'avoid') {
    what = '下校の時間は走らせなかった。何も起きなかったが、その時間の配達は待たせた';
    P.push(['注文した人', '届くまで15分ほど待たされた']);
    CO.push(['あなた（運行会社）', '混む時間は走らせない決まりにした。1台が運べる数が減る']);
    RU.push(['届出（公安委員会）', '通る場所は届け出るが、走らせる時間を自分で決める決まりはない']);
    open = '通学路を、子どもが通る時間に配送ロボットが走ってよいかは決まっていない'; issues = ['public-space-operation-rules', 'robot-unready-built-environment'];
  } else if (cfg.stop === 0.5) {
    what = 'ロボットが子どもの列の中を0.5mまで寄って進み、子どもがロボットに触った';
    P.push(['子ども', '珍しいロボットに手を伸ばした。子どもとして当たり前の動き']);
    CO.push(['あなた（運行会社）', '人に0.5mまで近づいて進む設定にした。止まらずに済むぶん、子どもと近い']);
    CO.push(['メーカー', '子どもの多い所で、大人と同じ間しかあけない作りだった']);
    RU.push(['道路交通法', '配送ロボットは歩行者に道を譲ることになっているが、どれだけ離れるかは決めていない']);
    open = '子どもの多い所で、配送ロボットがどれだけ離れるべきかの基準はない'; issues = ['human-robot-coexistence-safety', 'public-space-operation-rules', 'intent-legibility'];
  } else {
    what = cfg.waitpos === 'center' ? 'ロボットが歩道の途中で止まり続け、子どもが縁石を下りて車道を歩いてよけた' : 'ロボットが車道側の端に寄って止まり、子どもたちはそのまま通れた。配達は大きく遅れた';
    P.push(['子ども', cfg.waitpos === 'center' ? '止まったロボットをよけるために、車道へ下りた' : 'ロボットの横をそのまま通った']);
    CO.push(['あなた（運行会社）', `人が1.5mより近いと止まる設定にし、混む時間も走らせていた。${stopT}秒止まった`]);
    CO.push(['メーカー', cfg.waitpos === 'center' ? '止まる場所を選ばず、その場で止まる作りだった' : '端に寄って止まる作りだった']);
    RU.push(['道路交通法', '配送ロボットが歩道で長く止まって、人の通行をふさいだときの決まりはない']);
    RU.push(['通学路の安全', '通学路の時間を決めた車の通行止めはあるが、配送ロボットは歩行者と同じ扱いで、その対象にならない']);
    open = '通学の時間に配送ロボットを走らせてよいか、どれだけ止まってよいかは決まっていない'; issues = ['public-space-operation-rules', 'robot-unready-built-environment', 'human-robot-coexistence-safety'];
  }
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues }, { x: 62, z: 4.5 });
}

// ---------------------------------------------------------------- 白い杖の人と点字ブロック（北の歩道）
function sceneCane(cfg) {
  const ev = E_(); const door = 80, PAV = -4.75;
  const sx = cfg.stopAt === 'door' ? door + 1.2 : door + 0.4;
  const R = mover(92, -4.15, Math.PI); R.to(sx + 0.2, -4.15, 1.67);
  const zStop = cfg.stopAt === 'door' ? -5.1 : -3.85; R.to(sx, zStop, 0.6);
  const tArr = R.t; ev(tArr, 'ロボット', cfg.stopAt === 'door' ? '店の入口の前で、建物側に寄って止まった（点字ブロックの上にかかっている）' : '点字ブロックを避けて、車道側の端で止まった');
  const tRecv = tArr + cfg.wait, tLeave = tRecv + 9;
  const Rc = mover(door, -6.3, Math.PI / 2); Rc.until(tRecv).to(door, -5.3, 0.9).to(cfg.stopAt === 'door' ? door + 0.1 : door + 0.4, cfg.stopAt === 'door' ? -4.9 : -4.6, 0.9).wait(5).to(door, -5.4, 0.9).to(door, -6.3, 0.9);
  ev(tRecv, '受け取る人', '店から出てきて、荷物を受け取った');
  const C = mover(50, PAV, 0); const tMeet = (sx - 0.5 - 1.1 - 50) / 0.8; // 杖の先（1m）がロボットに届く時刻
  let kind, carM = null; const cars = [];
  const blocking = cfg.stopAt === 'door' && tLeave > tMeet;
  ev(0, '白い杖の人', '点字ブロックをたどって、東へ歩いている');
  if (!blocking) {
    R.until(tLeave).to(R.x, -4.15, 0.6).to(66, -4.15, 1.67); ev(tLeave, 'ロボット', '受け渡しが終わり、走り出した');
    C.to(96, PAV, 0.8);
    kind = 'safe';
    if (cfg.stopAt === 'door') ev(tLeave + 1, '—', '白い杖の人が来る前に、ロボットは店の前を離れていた（入れ違い）');
  } else {
    C.to(sx - 0.5 - 1.1, PAV, 0.8); ev(C.t, '白い杖の人', '杖の先が、点字ブロックの上に止まったロボットに当たった');
    if (cfg.sound === 'sound') {
      ev(C.t - 3, 'ロボット', '近づく人に、音声で「ロボットが止まっています。車道側を通れます」と知らせた');
      C.wait(2).to(C.x + 0.4, -4.1, 0.4).to(sx + 0.9, -4.1, 0.4).to(sx + 1.5, PAV, 0.4).to(96, PAV, 0.8);
      ev(C.t - 18, '白い杖の人', '音声を頼りに、点字ブロックを外れてロボットの横を回った');
      kind = 'issue';
    } else {
      C.wait(3).to(C.x + 0.5, -3.9, 0.3).to(C.x + 0.9, -3.25, 0.3);
      ev(C.t, '白い杖の人', '何があるのか分からず、よけようとして縁石を下り、車道に出てしまった', 'near', { x: C.x, z: -3.25 });
      const car = mover(C.x - 60, -1.75, 0); car.until(C.t - 7).to(C.x + 60, -1.75, 8.3); cars.push({ id: 'c1', m: car }); carM = car;
      ev(C.t + 0.3, '車の運転者', '車道に出た人のすぐ横を通った');
      C.wait(4).to(C.x + 0.5, -4.1, 0.3).to(sx + 0.9, -4.1, 0.4).to(sx + 1.5, PAV, 0.4).to(96, PAV, 0.8);
      kind = 'near';
    }
    R.until(Math.max(tLeave, C.keys.find((q) => q[1] > sx + 1.4)?.[0] ?? tLeave)).to(R.x, -4.15, 0.6).to(66, -4.15, 1.67);
  }
  const T = Math.min(Math.max(R.t, C.t, Rc.t), (blocking ? C.keys.find((q) => q[1] > sx + 1.4)?.[0] : tLeave + 10) + 8);
  [R, C, Rc].forEach((m) => m.until(T)); cars.forEach((c) => c.m.until(T));
  const frames = build(T, { robots: [{ id: 'R', m: R, light: [[0, 'go'], [tArr, 'stop'], [tLeave, 'go']] }], peds: [{ id: 'C', kind: 'cane', m: C }, { id: 'Rc', kind: 'walk', m: Rc }], cars });
  const facts = [{ k: '店の前で止まっていた時間', v: Math.round(tLeave - tArr), u: '秒' }, { k: '点字ブロックの上にいた時間', v: cfg.stopAt === 'door' ? Math.round(tLeave - tArr) : 0, u: '秒' }, { k: '白い杖の人が来たのは、止まってから', v: Math.round(tMeet - tArr), u: '秒後' }];
  const P = [], CO = [], RU = []; let what, open, issues;
  if (cfg.stopAt === 'avoid') what = 'ロボットが点字ブロックを避けて止まり、白い杖の人はそのまま点字ブロックをたどって通れた';
  else if (!blocking) what = 'ロボットは点字ブロックの上で止まっていたが、白い杖の人が来る前に離れた。たまたま入れ違いになっただけ';
  else what = kind === 'near' ? '点字ブロックの上に止まったロボットに杖が当たり、よけようとした人が車道へ出てしまった' : '点字ブロックの上に止まったロボットを、白い杖の人が音声を頼りに回った';
  P.push(['白い杖の人', blocking ? '点字ブロックをたどって歩いていた。ふだんどおりの歩き方' : 'ふだんどおり歩いた']);
  if (blocking) P.push(['受け取る人', `店から出てくるまで${cfg.wait}秒かかった`]);
  if (kind === 'near') P.push(['車の運転者', '歩道から出てきた人に気づくのが遅れた']);
  if (cfg.stopAt === 'door') CO.push(['メーカー', '空いている所なら止まってよい作りで、点字ブロックを地図に入れていない']);
  else CO.push(['あなた（運行会社）', '点字ブロックを地図に入れ、上で止まらない設定にした（費用が上がる）']);
  if (blocking && cfg.sound === 'none') CO.push(['あなた（運行会社）', '近づく人に音で知らせる作りを付けていなかった']);
  if (blocking) CO.push(['あなた（運行会社）', `受け取る人が出てくるまで、${cfg.wait}秒その場で待たせる決まりにしていた`]);
  RU.push(['点字ブロック', '点字ブロックの上に物を置かない・止まらないことは、お願いとして広まっている。ロボットが上で止まってはいけないという決まりは見当たらない']);
  RU.push(['道路交通法', '白い杖の人がいるとき、車の運転者は止まるかゆっくり進む決まりがある。歩行者と同じ扱いの配送ロボットに当てはまるかは、はっきりしない']);
  open = '配送ロボットが点字ブロックの上で止まってよいか、白い杖の人にどう知らせるかは決まっていない';
  issues = ['robot-unready-built-environment', 'intent-legibility', 'human-robot-coexistence-safety'];
  void carM;
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues }, { x: 78, z: -4.5 });
}

// ---------------------------------------------------------------- 歩道を走る自転車が、後ろから来る（北の歩道）
function sceneBicycle(cfg) {
  const ev = E_(); const vR = 1.67, door = 70;
  const fast = cfg.bike === 'fast', gap0 = fast ? 1.0 : 2.5;
  const R = mover(38, -4.15, 0), B = mover(34, -4.15, 0);
  // 自転車が追いつき、駐輪で追い越せないので後ろにつく
  const tCatch = fast ? (4 - 1 - gap0 + 0.5) / 2.5 : (4 - 1 - gap0 + 0.5) / 0.27;
  // ロボットが店の入口の手前まで進む
  const tSee = (door - 0.27 - 1.5 - 0.5 - 38) / vR; // 出てきた人までの間が1.5mになる時刻
  R.to(38 + vR * tSee, -4.15, vR);
  B.to(38 + vR * Math.min(tCatch, tSee) - 0.5 - gap0 - 0.5, -4.15, fast ? 4.17 : 1.94).to(R.x - 0.5 - gap0 - 0.5, -4.15, vR);
  ev(Math.min(tCatch, tSee), '自転車の人', `ロボットのすぐ後ろ（${gap0}m）についた。建物側に自転車が並んでいて、追い越せない`);
  const W = mover(door, -5.6, -Math.PI / 2); W.until(tSee - 0.8).to(door, -4.3, 1.0);
  ev(tSee - 0.8, '店から出てきた人', '並んだ自転車の間から、歩道へ出てきた');
  const watching = cfg.rear === 'watch';
  const hard = cfg.brake === 'hard' && !watching;
  const rStop = 0.2 * vR + vR * vR / (2 * (hard ? 2.5 : 1.0));
  const bStop = fast ? 1.0 * vR + vR * vR / (2 * 2.5) : 0.8 * vR + vR * vR / (2 * 3.0);
  const pedLeft = 1.5 - rStop, bikeLeft = gap0 - (bStop - rStop);
  if (watching) ev(tSee, 'ロボット', '後ろに自転車がいるので、急に止まらず、ゆっくり止まった');
  else ev(tSee, 'ロボット', hard ? '店から出てきた人に気づき、急ブレーキで止まった' : 'ゆっくり止まる作りのまま、ブレーキをかけた');
  let kind; const nearPed = pedLeft < 0.3, bikeHit = bikeLeft <= 0, nearBike = !bikeHit && bikeLeft < 0.5;
  const rx = R.x + Math.min(rStop, 1.45); R.to(rx, -4.15, vR / 2);
  if (nearPed) { W.to(door, -4.75, 0.8); ev(R.t, '店から出てきた人', `ロボットが止まりきれず、0.1mまで迫った。慌てて後ろへ下がった`, 'near', { x: door - 0.3, z: -4.4 }); }
  const bx = bikeHit ? rx - 0.5 - 0.9 : rx - 0.5 - Math.max(0.05, bikeLeft) - 0.9;
  B.to(bx, -4.15, vR / 2);
  if (bikeHit) ev(B.t, '—', '自転車が、急に止まったロボットに後ろからぶつかった。自転車の人が転んだ', 'hit', { x: rx - 0.5, z: -4.15 });
  else if (nearBike) ev(B.t, '自転車の人', `急ブレーキで、ロボットの${bikeLeft.toFixed(1)}m手前で止まった`, 'near', { x: rx - 0.5, z: -4.15 });
  kind = bikeHit ? 'hit' : (nearPed || nearBike) ? 'near' : 'safe';
  const tEnd = Math.max(R.t, B.t) + 3;
  if (!bikeHit) { W.until(tEnd - 2.5).to(door + 0.6, -3.3, 1.0).to(door + 1.5, 3.0, 1.0); R.until(tEnd + 0.5).to(R.x + 6, -4.15, vR); B.until(tEnd + 1).to(B.x + 6, -4.15, vR); }
  const T = Math.max(R.t, B.t, W.t) + 1; [R, B, W].forEach((m) => m.until(T));
  const frames = build(T, { robots: [{ id: 'R', m: R, light: [[0, 'go'], [tSee, 'stop'], [tEnd, 'go']], fallen: [] }], peds: [{ id: 'B', kind: 'bike', m: B, fallenAt: bikeHit ? B.t : null }, { id: 'W', kind: 'walk', m: W }] });
  if (bikeHit) frames.forEach((f) => { if (f.t >= B.t) f.peds[0].fallen = true; });
  const facts = [{ k: 'ロボットが止まるまでに進んだ距離', v: Math.round(rStop * 10) / 10, u: 'm' }, { k: '自転車とのいちばん近い距離', v: bikeHit ? 0 : Math.round(Math.max(0.05, bikeLeft) * 10) / 10, u: 'm' }, { k: '店から出た人とのいちばん近い距離', v: Math.round(Math.max(0.1, pedLeft) * 10) / 10, u: 'm' }];
  const P = [], CO = [], RU = []; let what;
  if (bikeHit) what = '店から出てきた人に急ブレーキをかけたロボットに、すぐ後ろの自転車がぶつかった';
  else if (nearPed && nearBike) what = 'ロボットがゆっくり止まったので、店から出てきた人に迫った。後ろの自転車もぎりぎりで止まった';
  else if (nearPed) what = watching ? '後ろの自転車を気にしてゆっくり止まったロボットが、店から出てきた人に0.1mまで迫った' : 'ゆっくり止まる作りのロボットが、店から出てきた人に0.1mまで迫った';
  else if (nearBike) what = '急ブレーキのロボットに、後ろの自転車がぎりぎりで止まった';
  else what = 'ロボットも自転車も、店から出てきた人の手前で止まれた';
  P.push(['自転車の人', fast ? '歩道を速めに走り、ロボットのすぐ後ろについていた' : '歩道をゆっくり走り、間をあけてついていた']);
  P.push(['店から出てきた人', '並んだ自転車の間から、左右を見ずに出てきた']);
  if (watching) CO.push(['メーカー', '後ろの自転車を見て、急に止まらない作り。後ろの人を守るぶん、前の人に近づく']);
  else CO.push(['メーカー', `後ろを見ない作り。${hard ? '急ブレーキで前の人は守れるが、後ろの自転車には分からない' : 'ゆっくり止まる作りで、前の人に近づく'}`]);
  CO.push(['店・道の管理者', '店の前の歩道に自転車が並び、見通しと幅を狭めていた']);
  RU.push(['道路交通法', '自転車が歩道を走れるのは標識などがある所だけで、車道寄りをゆっくり進み、歩行者の通行を妨げるときは止まる決まり。2026年4月から、自転車の違反にも反則金の仕組みが入った']);
  RU.push(['事故の責任', 'ロボットの急ブレーキと、後ろの自転車の間のあけ方の、どちらが重く見られるかは、事故ごとに決まる']);
  const open = '歩道で自転車が配送ロボットを追い越すとき、自転車がロボットを歩行者として譲る必要があるかは、はっきりしない';
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues: ['liability-demarcation', 'public-space-operation-rules', 'failsafe-stop-design'] }, { x: 58, z: -4.5 });
}

// ---------------------------------------------------------------- 子どもが近寄る・触る・前に立つ（南の歩道・西）
function sceneKids(cfg) {
  const ev = E_(); const vR = 1.67, xs = -36;
  const R = mover(-58, S, 0); const kids = [mover(xs, 5.1, Math.PI), mover(xs + 1.0, 4.7, Math.PI), mover(xs + 0.6, 5.3, Math.PI)];
  const xStop = xs - 3.0; R.to(xStop, S, vR); const t0 = R.t;
  ev(t0, 'ロボット', '前に子どもが3人いるので、止まった');
  let kind, blocked = 0, fallen = false;
  if (cfg.face === 'none') {
    kids.forEach((k, i) => k.to(k.x, 5.2 + i * 0.05, 0.5).wait(2)); ev(t0 + 2, '子ども', 'ロボットをちらっと見て、建物側へ寄った');
    R.wait(3).to(xs + 8, S, 1.2).to(-16, S, vR); blocked = 5; kind = 'safe';
    kids.forEach((k) => k.until(R.t));
  } else {
    // 顔の表示があるので、子どもが寄ってくる
    const front = xStop + 0.5 + 0.6;
    kids[0].to(front, S, 1.2).face(Math.PI); kids[1].to(xStop + 0.1, S + 0.75, 1.2).face(-Math.PI / 2); kids[2].to(xStop - 0.2, 5.2, 1.0).face(-Math.PI / 2);
    ev(t0 + 1.5, '子ども', 'ロボットの顔の表示に気づいて、まわりに集まってきた');
    if (cfg.resp === 'remote') {
      ev(t0 + 4, 'ロボット', '遠隔の担当に知らせた');
      ev(t0 + 14, '遠隔の担当', 'ロボットのスピーカーから「通らせてね、ありがとう」と話しかけた');
      kids.forEach((k, i) => k.until(t0 + 16).to(k.x + 1.5, 5.25 - i * 0.02 + i * 0.0, 1.0).face(0));
      R.until(t0 + 19).to(-16, S, vR); blocked = 19; kind = 'safe';
    } else {
      const long = cfg.resp === 'wait' ? 40 : 25;
      if (cfg.resp === 'voice') ev(t0 + 3, 'ロボット', '音声で「通ります、離れてください」と言った。子どもが面白がってまねをした');
      else ev(t0 + 3, 'ロボット', '子どもが離れるまで、その場で待った');
      const tPush = t0 + (cfg.resp === 'wait' ? 18 : 12);
      kids[1].until(tPush).to(xStop + 0.1, S + 0.55, 0.5);
      ev(tPush, '子ども', 'ロボットを横から押した');
      if (cfg.body === 'light' && cfg.resp === 'wait') {
        fallen = true; ev(tPush + 0.4, '—', '軽い車体が押されて倒れ、そばにいた子どもの足に当たった', 'hit', { x: xStop, z: 3.6 });
        kids.forEach((k) => k.until(tPush + 5)); R.until(tPush + 5); kind = 'hit'; blocked = Math.round(tPush + 5 - t0);
      } else if (cfg.body === 'light') {
        ev(tPush + 0.4, '—', '軽い車体が押されてぐらついた。倒れなかった', 'near', { x: xStop, z: S });
        kids.forEach((k, i) => k.until(t0 + long).to(k.x + 2, 5.25, 1.0)); R.until(t0 + long + 2).to(-16, S, vR); kind = 'near'; blocked = long + 2;
      } else {
        ev(tPush + 0.4, 'ロボット', '重心の低い車体で、押されても動かなかった');
        kids.forEach((k, i) => k.until(t0 + long).to(k.x + 2, 5.25, 1.0)); R.until(t0 + long + 2).to(-16, S, vR); kind = 'issue'; blocked = long + 2;
        ev(t0 + long, '子ども', `${long}秒ほどして、子どもたちが離れた`);
      }
    }
  }
  const T = Math.max(R.t, ...kids.map((k) => k.t)) + 0.5; R.until(T); kids.forEach((k) => k.until(T));
  const frames = build(T, { robots: [{ id: 'R', m: R, light: [[0, 'go'], [t0, 'stop'], [t0 + blocked, 'go']], fallen: fallen ? [[t0 + (cfg.resp === 'wait' ? 18.4 : 12.4), true]] : [] }], peds: kids.map((k, i) => ({ id: 'K' + i, kind: 'walk', child: true, m: k })) });
  const facts = [{ k: '歩道で止まっていた時間', v: Math.round(blocked), u: '秒' }, { k: '集まった子ども', v: cfg.face === 'none' ? 0 : 3, u: '人' }, { k: '遠隔の担当が使った時間', v: cfg.resp === 'remote' && cfg.face === 'face' ? 15 : 0, u: '秒' }];
  const P = [], CO = [], RU = []; let what;
  if (cfg.face === 'none') what = '子どもはロボットをちらっと見て道をあけた。ロボットはそのまま通れた';
  else if (kind === 'hit') what = '集まった子どもがロボットを押し、軽い車体が倒れて子どもの足に当たった';
  else if (kind === 'near') what = '子どもがロボットを押し、軽い車体がぐらついた';
  else if (kind === 'issue') what = `子どもに囲まれ、ロボットが${blocked}秒ほど歩道で動けなかった`;
  else what = '子どもに囲まれたが、遠隔の担当が話しかけて道をあけてもらった';
  P.push(['子ども', cfg.face === 'none' ? '道をあけた' : '顔の表示のあるロボットに興味をもって集まり、触ったり押したりした。子どもとして当たり前の動き']);
  if (cfg.resp === 'remote' && cfg.face === 'face') P.push(['遠隔の担当', 'その場の子どもに、ロボットを通して話しかけた']);
  if (cfg.face === 'face') CO.push(['メーカー', '親しみやすい顔の表示を付けていた。子どもが寄ってくる']);
  if (cfg.body === 'light' && cfg.face === 'face') CO.push(['メーカー', '軽い車体で、横から押されると倒れやすい']);
  if (cfg.face === 'face' && cfg.resp !== 'remote') CO.push(['あなた（運行会社）', cfg.resp === 'wait' ? '子どもが離れるまで、その場で待つ決まりにしていた' : '音声で離れるよう言う決まりにしていた。子どもには遊びになった']);
  if (cfg.resp === 'remote' && cfg.face === 'face') CO.push(['あなた（運行会社）', '遠隔の担当が話しかける決まりにした。担当の手がそのぶん取られる']);
  if (!CO.length) CO.push(['あなた（運行会社）', '目立った問題はなかった']);
  RU.push(['製品の安全', '倒れてけがをさせたときは、製品の欠陥としてメーカーが問われることがある。押されることを想定した強さの基準ははっきりしない']);
  RU.push(['道路交通法', '歩行者が配送ロボットを押したり、前に立ったりすることを禁じる決まりはない']);
  const open = '子どもがいたずらしてロボットが倒れたとき、誰が責任を負うか（子どもの親・運行会社・メーカー）は整理されていない';
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues: ['human-robot-coexistence-safety', 'liability-demarcation', 'intent-legibility'] }, { x: -36, z: 4.5 });
}

// ---------------------------------------------------------------- 犬の散歩（南の歩道・西）
function sceneDog(cfg) {
  const ev = E_(); const vR = cfg.speed / 3.6;
  const R = mover(-58, S, 0), O = mover(-22, 5.05, Math.PI), D = mover(-23.5, 3.9, Math.PI);
  // 出会う所：ロボットの前と犬が向き合う
  const tm = (-23.5 - 0.3 - (-58 + 0.5) - 2.5) / (vR + 0.9);
  R.to(-58 + vR * tm, S, vR); O.to(-22 - 0.9 * tm, 5.05, 0.9); D.to(-23.5 - 0.9 * tm, 3.9, 0.9);
  ev(tm, 'ロボット', '前から来る人と犬に気づいた（リードは細くて見えていない）');
  let kind; const leashX = D.x + 0.75;
  if (cfg.approach === 'stop') {
    R.to(R.x + 0.5, 3.8, 0.6); ev(R.t, 'ロボット', '人と犬が通り過ぎるまで、車道側の端に寄って止まった');
    D.to(D.x - 0.5, 4.75, 0.6).to(R.x - 4, 4.75, 0.9); O.to(R.x - 3, 5.1, 0.9); R.until(O.t).to(-16, S, vR); kind = 'safe';
  } else if (cfg.sensor === 'fine') {
    ev(tm + 0.4, 'ロボット', '人と犬のあいだのリードに気づき、手前で止まった');
    R.to(R.x + 0.4, S, 0.6); D.to(D.x - 0.5, 4.75, 0.6).to(R.x - 4, 4.75, 0.9); O.to(R.x - 3, 5.1, 0.9); R.until(O.t).to(-16, S, vR); kind = 'safe';
  } else {
    // 人と犬のあいだを抜けようとして、リードに当たる
    R.to(leashX - 0.5, S, vR);
    if (cfg.speed === 6) {
      ev(R.t, '—', 'ロボットがリードに引っかかり、犬が引っ張られて転んだ', 'hit', { x: leashX, z: 4.4 });
      D.to(leashX - 0.2, 4.2, 1.5); O.wait(0.5); kind = 'hit'; R.to(R.x + 0.6, S, 0.8);
    } else {
      ev(R.t, '飼い主', 'リードがロボットの前にかかりそうになり、とっさに犬を引き寄せた', 'near', { x: leashX, z: 4.4 });
      D.to(D.x - 0.3, 4.75, 1.0); R.wait(2); kind = 'near';
    }
    R.wait(2); D.until(R.t).to(R.x - 4, 4.75, 0.8); O.until(R.t).to(R.x - 3, 5.1, 0.8); R.until(O.t).to(-16, S, vR);
  }
  const T = Math.max(R.t, O.t, D.t) + 0.5; [R, O, D].forEach((m) => m.until(T));
  const frames = build(T, { robots: [{ id: 'R', m: R }], peds: [{ id: 'O', kind: 'walk', m: O }, { id: 'D', kind: 'dog', m: D, leash: 'O' }] });
  const facts = [{ k: 'ロボットの速さ', v: cfg.speed, u: 'km/時' }, { k: 'リードとのいちばん近い距離', v: kind === 'hit' ? 0 : kind === 'near' ? 0.1 : 1.5, u: 'm' }, { k: '配達の遅れ', v: kind === 'safe' ? 6 : 4, u: '秒' }];
  const P = [], CO = [], RU = []; let what;
  if (kind === 'hit') what = '人と犬のあいだを抜けようとしたロボットがリードに引っかかり、犬が転んだ';
  else if (kind === 'near') what = 'リードがロボットの前にかかりそうになり、飼い主が犬を引き寄せた';
  else what = cfg.approach === 'stop' ? 'ロボットが端に寄って止まり、人と犬はそのまま通った' : 'ロボットがリードに気づいて手前で止まった';
  P.push(['飼い主', '犬を車道側に歩かせ、リードが歩道を横切っていた']);
  if (cfg.approach === 'pass' && cfg.sensor === 'normal') CO.push(['メーカー', 'リードのような細いものが見えにくいセンサーだった']);
  if (cfg.approach === 'pass') CO.push(['あなた（運行会社）', '人と犬のあいだが空いていればすり抜ける作りにしていた']);
  if (cfg.sensor === 'fine') CO.push(['あなた（運行会社）', '細いものも見えるセンサーにした（費用が上がる）']);
  if (cfg.speed === 6 && kind === 'hit') CO.push(['あなた（運行会社）', '速さを法律の上限の時速6kmにしていた']);
  if (!CO.length) CO.push(['あなた（運行会社）', '人と動物が来たら止まる決まりにしていた（配達は少し遅れる）']);
  RU.push(['道路交通法', '配送ロボットは歩行者に道を譲ることになっているが、動物やリードについての決まりはない']);
  RU.push(['動物のけが', '飼い犬がけがをしたときは、物の損害として扱われることが多い']);
  const open = '配送ロボットが動物やリードをどこまで見分けるべきか、安全基準の中での扱いは決まっていない';
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues: ['human-robot-coexistence-safety', 'failsafe-stop-design', 'public-space-operation-rules'] }, { x: -38, z: 4.5 });
}

// ---------------------------------------------------------------- 置き看板と路上駐車（北の歩道・西）
function sceneSign(cfg) {
  const ev = E_(); const vR = 1.67, xs = -45;
  const R = mover(-60, -4.15, 0); const cars = []; const props = [{ id: 'sign', kind: 'sign', x: xs, z: -4.6, downAt: [] }, { id: 'pbike', kind: 'pbike', x: xs + 0.2, z: -5.25 }];
  const parked = mover(xs + 0.5, -2.55, 0); cars.push({ id: 'pk', m: parked });
  ev(0, '—', '店が置き看板を歩道に出し、その横の車道に車が止まっている');
  let kind; R.to(xs - 3, -4.15, vR); const tA = R.t;
  if (cfg.map === 'daily') {
    ev(tA - 2, 'ロボット', '毎朝の地図の見直しで看板を知っていたので、手前で別の道へ曲がった');
    R.to(xs - 3.5, -4.15, 0.8).face(Math.PI / 2).to(xs - 3.5, -5.3, 0.6); kind = 'safe';
  } else if (cfg.way === 'squeeze') {
    ev(tA, 'ロボット', '看板の横の80cmのすき間を、ゆっくり抜けようとした');
    R.to(xs - 0.5, -3.95, 0.6); ev(R.t, '—', 'ロボットの角が看板に当たり、看板が車道側へ倒れた', cfg.traffic === 'many' ? 'near' : '', { x: xs, z: -3.6 });
    props[0].downAt = [[R.t, true]];
    if (cfg.traffic === 'many') { const car = mover(xs - 70, -0.75, 0); car.until(R.t - 7).to(xs - 8, -0.75, 8.3).to(xs + 2, -0.45, 8.3).to(xs + 70, -0.75, 8.3); cars.push({ id: 'c1', m: car }); ev(R.t + 1.5, '車の運転者', '車道に倒れかけた看板をよけて、とっさにハンドルを切った'); kind = 'near'; }
    else kind = 'issue';
    R.to(xs + 2, -4.15, 0.6).to(-33, -4.15, vR);
  } else if (cfg.way === 'road') {
    ev(tA, 'ロボット', '縁石を下り、止まっている車の横の車道へ出て回った');
    R.to(xs - 2.8, -3.0, 0.8).to(xs - 2.6, -0.9, 0.8);
    if (cfg.traffic === 'many') {
      const tH = R.t + 0.8; const cx = R.x - 0.35 - 2.2; const car = mover(xs - 60, -0.9, 0); car.until(tH - 6.5).to(cx - 6, -0.9, 8.3).to(cx, -0.9, 3.0);
      cars.push({ id: 'c1', m: car }); R.wait(0.8);
      ev(tH - 1.5, '車の運転者', '止まっている車の陰から出てきたロボットに気づき、急ブレーキをかけた');
      ev(tH, '—', '車がロボットにぶつかった', 'hit', { x: R.x - 0.4, z: -0.9 }); R.wait(4); car.wait(4); kind = 'hit';
    } else { R.to(xs + 3.2, -0.9, 1.2).to(xs + 4.5, -4.15, 0.8).to(-33, -4.15, vR); kind = 'issue'; ev(R.t - 8, 'ロボット', '車が来なかったので、そのまま歩道へ戻った'); }
  } else {
    ev(tA, 'ロボット', '通れるか分からず、止まって遠隔の担当に聞いた');
    ev(tA + 25, '遠隔の担当', '映像で幅を確かめ、ゆっくり抜けるよう操作した');
    R.wait(25).to(xs - 0.5, -3.95, 0.3).to(xs + 2, -4.15, 0.3).to(-33, -4.15, vR); kind = 'safe';
  }
  const T = Math.max(R.t, ...cars.map((c) => c.m.t)) + 0.5; R.until(T); cars.forEach((c) => c.m.until(T));
  const frames = build(T, { robots: [{ id: 'R', m: R }], cars, props });
  const facts = [{ k: '看板の横のすき間', v: 0.8, u: 'm' }, { k: 'ロボットの幅', v: 0.7, u: 'm' }, { k: '配達の遅れ', v: cfg.map === 'daily' ? 90 : cfg.way === 'stop' ? 30 : 3, u: '秒' }];
  const P = [], CO = [], RU = []; let what;
  if (cfg.map === 'daily') what = '毎朝の地図の見直しで看板を知っていたロボットが、手前で別の道へ回った';
  else if (cfg.way === 'squeeze') what = kind === 'near' ? 'すき間を抜けようとしたロボットが看板を倒し、車が倒れかけた看板をよけた' : 'すき間を抜けようとしたロボットが看板を倒した';
  else if (cfg.way === 'road') what = kind === 'hit' ? '止まっている車の横の車道へ出たロボットに、後ろから来た車がぶつかった' : 'ロボットが車道へ出て、止まっている車と看板を回った。何も起きなかったが、歩道のある道で車道を走った';
  else what = 'ロボットが止まって遠隔の担当に聞き、担当がゆっくり抜けさせた';
  P.push(['店の人', '歩道に置き看板を出していた']);
  P.push(['止めている車の運転者', '車道の端に車を止めていた']);
  if (kind === 'hit') P.push(['後ろから来た車の運転者', '止まっている車の陰から出てくるものに備えていなかった']);
  if (cfg.way === 'stop' && cfg.map === 'none') P.push(['遠隔の担当', '25秒かけて映像で幅を確かめた']);
  if (cfg.map === 'daily') CO.push(['あなた（運行会社）', '毎朝、地図を見直す仕組みにした（費用が上がる）']);
  else CO.push(['あなた（運行会社）', '地図を見直していないので、看板が出ることを知らなかった']);
  if (cfg.map === 'none' && cfg.way === 'squeeze') CO.push(['メーカー', '左右5cmずつしか余らないすき間を、抜けてよいと判断する作りだった']);
  if (cfg.map === 'none' && cfg.way === 'road') CO.push(['メーカー', '歩道がふさがれたら車道へ出る作りだった']);
  RU.push(['道路法', '歩道に看板を置くには道路の占用の許可が要る。許可のない看板は多い']);
  RU.push(['道路交通法', '路上駐車は取り締まりの対象。配送ロボットのために歩道や車道をあけておく決まりはない']);
  const open = '歩道に置かれた物で配送ロボットが通れないとき、誰が直すか（店・道の管理者・運行会社）は決まっていない';
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues: ['robot-unready-built-environment', 'public-space-operation-rules', 'liability-demarcation'] }, { x: -46, z: -3.5 });
}

// ---------------------------------------------------------------- 雨の夜（北の歩道・西）
function sceneRain(cfg) {
  const ev = E_(); const vR = cfg.speed / 3.6, night = cfg.env === 'night';
  const det = !night ? 8 : cfg.sensor === 'camera' ? 1.8 : 2.4; // 人に気づける距離
  const dec = night ? 0.9 : 1.2, stop = 0.3 * vR + vR * vR / (2 * dec);
  const appear = 3.0, seen = Math.min(appear, det), left = seen - stop;
  const xd = -44; // 人が出てくる所（建物の入口）
  const R = mover(-62, -4.15, 0); const tApp = (xd - 0.27 - appear - 0.5 - (-62)) / vR;
  const W = mover(xd, -5.6, -Math.PI / 2); W.until(tApp - 1.2).to(xd, -4.15, 1.0);
  ev(tApp - 1.2, '歩いている人', night ? '暗い色の服で傘をさし、建物の入口から歩道へ出てきた' : '建物の入口から歩道へ出てきた');
  R.to(xd - 0.27 - appear - 0.5, -4.15, vR);
  if (seen < appear) { R.to(R.x + (appear - seen), -4.15, vR); ev(R.t, 'ロボット', `人に気づいたのは${seen}m手前だった（${night ? '雨の夜で見えにくい' : ''}）`); }
  else ev(R.t, 'ロボット', '3m手前で人に気づいた');
  let kind;
  if (left <= 0) { R.to(xd - 0.27 - 0.5, -4.15, vR * 0.5); ev(R.t, '—', `止まりきれず、人にぶつかった（時速${(Math.sqrt(Math.max(0, vR * vR - 2 * dec * Math.max(0, seen - 0.3 * vR))) * 3.6).toFixed(1)}km）`, 'hit', { x: xd - 0.3, z: -4.15 }); kind = 'hit'; R.wait(4); W.until(R.t); }
  else {
    R.to(R.x + stop, -4.15, vR * 0.5);
    ev(R.t, 'ロボット', `人の${left.toFixed(1)}m手前で止まった`, left < 0.5 ? 'near' : '', left < 0.5 ? { x: xd - 0.3, z: -4.15 } : null);
    kind = left < 0.5 ? 'near' : 'safe'; W.until(R.t + 1).to(xd, -3.2, 0.8).to(xd + 3, -3.2, 0.8); R.until(W.t - 2).to(-33, -4.15, vR);
  }
  const T = Math.max(R.t, W.t) + 0.5; R.until(T); W.until(T);
  const frames = build(T, { robots: [{ id: 'R', m: R }], peds: [{ id: 'W', kind: 'walk', m: W, umbrella: night }], env: night ? 'night' : null });
  const facts = [{ k: '人に気づいた距離', v: seen, u: 'm' }, { k: '止まるまでに進む距離', v: Math.round(stop * 10) / 10, u: 'm' }, { k: '人との間（止まったとき）', v: left <= 0 ? 0 : Math.round(left * 10) / 10, u: 'm' }];
  const P = [], CO = [], RU = []; let what;
  if (kind === 'hit') what = '雨の夜、暗い服の人に気づくのが遅れ、ロボットが止まりきれずにぶつかった';
  else if (kind === 'near') what = '雨の夜、ロボットが人に気づくのが遅れ、すぐ手前で止まった';
  else what = night ? '雨の夜だったが、ロボットは人の手前で止まれた' : '晴れた昼で、ロボットは早めに人に気づいて止まれた';
  P.push(['歩いている人', night ? '暗い色の服で傘をさし、左右を見ずに歩道へ出た' : '左右を見ずに歩道へ出た']);
  if (night && cfg.sensor === 'camera') CO.push(['メーカー', 'カメラが主のセンサーで、雨の夜は人を見つけるのが遅れる']);
  if (night && cfg.sensor === 'lidar') CO.push(['あなた（運行会社）', 'ライダーを足した（費用が上がる）。雨で少し見えにくくなる']);
  if (night) CO.push(['あなた（運行会社）', `雨の夜も時速${cfg.speed}kmのまま走らせた。濡れた路面では止まるまでの距離が延びる`]);
  if (!night) CO.push(['あなた（運行会社）', '目立った問題はなかった']);
  RU.push(['業界の安全基準', '雨や夜にどこまで見えればよいか、天気で走らせない線はメーカーと運行会社が決める']);
  RU.push(['道路交通法', '車には夜のライトの決まりがあるが、歩行者と同じ扱いの配送ロボットの明かりの決まりは、はっきりしない']);
  const open = '雨や夜に、配送ロボットの速さを落とす・走らせないといった決まりはない';
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues: ['failsafe-stop-design', 'human-robot-coexistence-safety', 'public-space-operation-rules'] }, { x: -46, z: -4.2 });
}

// ---------------------------------------------------------------- 朝の一斉出発（南の歩道・中央）
function sceneFlock(cfg) {
  const ev = E_(); const base = cfg.launch === 'all' ? 12 : 4;
  let n = base; if (cfg.cap === 'cap') n = Math.min(n, 3); const onWalk = cfg.waitAt === 'lot' ? Math.min(n, 2) : n;
  const robots = []; const gx = -2, hold = 14;
  for (let i = 0; i < 12; i++) {
    const m = mover(gx, 7.2 + i * 1.3, -Math.PI / 2);
    const out = i < onWalk;
    if (out) { const two = onWalk >= 8, row = two ? Math.floor(i / 2) : i, col = two ? i % 2 : 0; m.until(i * (cfg.launch === 'all' ? 0.6 : 4)).to(gx, 5.0, 1.2).face(0).to(hold - row * 1.3, col ? 4.8 : 4.0, 1.2); }
    robots.push({ id: 'R' + i, m, light: [[0, 'go'], [10, 'ask']] });
  }
  ev(2, '拠点', `${cfg.launch === 'all' ? '12台を一斉に' : '4台ずつ時間をずらして'}出発させた`);
  ev(8, 'ロボット', '先の道で工事が始まったと知らせが入り、全台が同じ角で行き先を待った');
  const people = [mover(22, 5.15, Math.PI), mover(24.5, 5.15, Math.PI)];
  const front = hold + 0.6, back = hold - (onWalk >= 8 ? Math.ceil(onWalk / 2) : onWalk) * 1.3;
  let kind, cars = [];
  if (onWalk >= 8) {
    people.forEach((p, i) => p.until(12 + i).to(front + 1, p.z, 1.0).to(front, 3.15, 0.8).to(back - 1, 3.15, 0.9).to(back - 2, p.z, 0.9).to(-14, p.z, 1.0));
    ev(16, '歩いている人', `歩道にたまった${onWalk}台をよけて、車道を歩いた`, 'near', { x: hold - 3, z: 3.2 });
    const car = mover(70, 1.4, Math.PI); car.until(10).to(-60, 1.4, 8.3); cars.push({ id: 'c1', m: car });
    kind = 'near';
  } else if (onWalk >= 4) {
    people.forEach((p, i) => p.until(12 + i).to(front + 1, 5.2, 1.0).to(back - 1, 5.2, 0.5).to(-14, 5.2, 1.0));
    ev(16, '歩いている人', `${onWalk}台が並んだ横を、建物側に寄って一列で通った`, 'issue', { x: hold - 2, z: 5.2 });
    kind = 'issue';
  } else {
    people.forEach((p, i) => p.until(12 + i).to(-14, 5.15, 1.0));
    ev(16, '歩いている人', 'ロボットの横をそのまま通れた'); kind = 'safe';
  }
  if (cfg.waitAt === 'lot' && n > onWalk) ev(9, '拠点', `残りの${n - onWalk}台は、拠点の敷地の中で待たせた`);
  ev(40, '—', kind === 'near' ? '近所から苦情が入った。続けば、公安委員会が通行を止めるよう指示することもある' : '行き先が決まり、順に走り出した');
  const T = Math.max(44, ...people.map((p) => p.t)); robots.forEach((r) => r.m.until(T)); people.forEach((p) => p.until(T)); cars.forEach((c) => c.m.until(T));
  const frames = build(T, { robots, peds: people.map((p, i) => ({ id: 'P' + i, kind: 'walk', m: p })), cars });
  const facts = [{ k: '歩道にたまった台数', v: onWalk, u: '台' }, { k: '出発させた台数', v: n, u: '台' }, { k: '拠点で待たせた台数', v: n - onWalk, u: '台' }];
  const P = [], CO = [], RU = []; let what;
  if (kind === 'near') what = `${onWalk}台のロボットが歩道の同じ所にたまり、歩く人が車道へ出てよけた`;
  else if (kind === 'issue') what = `${onWalk}台のロボットが歩道に並び、歩く人が建物側を一列で通った`;
  else what = `歩道で待ったロボットは${onWalk}台だけで、歩く人はそのまま通れた`;
  P.push(['歩いている人', kind === 'near' ? 'ロボットの列をよけるために車道へ出た' : 'ロボットの横を通った']);
  CO.push(['あなた（運行会社）', `${cfg.launch === 'all' ? '一斉に出発させ' : '時間をずらして出発させ'}、${cfg.cap === 'cap' ? '1か所に3台までと決めていた' : '1か所にたまる台数を決めていなかった'}。${cfg.waitAt === 'lot' ? '待つのは拠点の敷地にした' : '待つのは歩道にした'}`]);
  CO.push(['メーカー', '行き先が変わったとき、全台が同じ角で待つ作りだった']);
  RU.push(['届出（公安委員会）', '台数や時間帯を届け出る決まりはなく、苦情が続けば公安委員会が通行を止めるよう指示できる']);
  RU.push(['自治体', '海外では市が台数を許可で決めている例があるが、日本の自治体には台数を決める仕組みがない']);
  const open = '1つの街や1つの歩道に、配送ロボットを何台まで走らせてよいかを決める仕組みはない';
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues: ['public-space-operation-rules', 'robot-unready-built-environment'] }, { x: 6, z: 5 });
}

// ---------------------------------------------------------------- 自動運転の車と接触（横断歩道）
function sceneAV(cfg) {
  const ev = E_(); const cw = MAP.crosswalk.x;
  const R = mover(cw - 8, -4.15, 0); R.to(cw, -4.15, 1.1).face(-Math.PI / 2);
  const tCross = R.t; let kind;
  const car = mover(cw - 90, -1.75, 0);
  if (cfg.cross === 'go') {
    ev(tCross, 'ロボット', '近づく車が止まってくれると見て、横断歩道を渡り始めた');
    R.to(cw, -2.4, 1.1); const tHit = R.t + 0.5; R.to(cw, -1.9, 1.0);
    car.until(tHit - 9).to(cw - 2.2 - 0.35 - 12, -1.75, 8.3).to(cw - 2.2 - 0.35, -1.75, 2.0);
    ev(tHit - 2.5, '自動運転の車', 'ロボットを人ではなく「動く物」と見分け、止まるのが遅れた');
    ev(tHit, '—', '自動運転の車が、横断歩道を渡るロボットにぶつかった（車は時速7km）', 'hit', { x: cw, z: -1.9 });
    R.wait(5); car.wait(5); kind = 'hit';
    ev(tHit + 3, '—', cfg.record === 'keep' ? 'ロボットのカメラ映像と動きの記録が、30日分残っていた' : 'ロボットの記録は1日で消える設定だった');
    ev(tHit + 4, '—', cfg.insurance === 'yes' ? '運行会社の賠償責任保険で、話し合いが始まった' : '運行会社は賠償責任保険に入っていなかった');
  } else {
    ev(tCross, 'ロボット', '近づく車が通り過ぎるまで、横断歩道の手前で待った');
    car.until(tCross - 4).to(cw + 40, -1.75, 8.3);
    R.until(car.keys.find((q) => q[1] > cw + 3)?.[0] + 1 || tCross + 6).to(cw, 4.4, 1.1).face(0).to(cw + 6, 4.4, 1.1); kind = 'safe';
  }
  const T = Math.max(R.t, car.t) + 0.5; R.until(T); car.until(T);
  const frames = build(T, { robots: [{ id: 'R', m: R }], cars: [{ id: 'av', m: car, av: true }] });
  const facts = [{ k: 'ぶつかったときの車の速さ', v: kind === 'hit' ? 7 : 0, u: 'km/時' }, { k: '記録が残る日数', v: cfg.record === 'keep' ? 30 : 1, u: '日' }, { k: '配達の遅れ', v: kind === 'hit' ? 0 : 8, u: '秒' }];
  const P = [], CO = [], RU = []; let what;
  if (kind === 'hit') what = '横断歩道を渡り始めたロボットに、自動運転の車がぶつかった。人のいない機械どうしの事故';
  else what = 'ロボットが車の通り過ぎるのを待ってから渡った';
  if (kind === 'hit') {
    P.push(['自動運転の車の遠隔の担当', '車の中に人はいなかった。遠くの担当も止める指示を出せなかった']);
    CO.push(['自動運転の車の会社', 'ロボットを人ではなく物と見分け、横断歩道で止まる相手と見なかった']);
    CO.push(['あなた（運行会社）', '車が止まってくれると見て渡り始める作りにしていた']);
    CO.push(['あなた（運行会社）', cfg.insurance === 'yes' ? '賠償責任保険に入っていた' : '賠償責任保険に入っていなかった。修理と相手の車の修理を、自分で話し合うことになる']);
    if (cfg.record === 'short') CO.push(['あなた（運行会社）', '記録を1日で消す設定で、どちらが先に動いたかを示せない']);
    else CO.push(['あなた（運行会社）', '記録を30日残していたので、どちらが先に動いたかを示せる']);
  } else { P.push(['—', '誰も困らなかった']); CO.push(['あなた（運行会社）', '車が通り過ぎるまで待つ作りにした（配達は少し遅れる）']); }
  RU.push(['道路交通法', '横断歩道では車が歩行者に道を譲る。歩行者と同じ扱いの配送ロボットにも譲るかは、自動運転の車の作りしだい']);
  RU.push(['保険', '配送ロボットは自賠責保険の対象ではない。賠償責任保険に入る義務もない（韓国は入る義務がある）']);
  RU.push(['記録', 'どちらの記録を、誰に、いつまでに出すかの決まりはない']);
  const open = '機械どうしの事故で、どちらの会社の記録を正として責任を分けるかは決まっていない';
  return done(frames, ev, kind, facts, { what, people: P, company: CO, rules: RU, open, issues: ['liability-demarcation', 'public-space-operation-rules', 'network-latency-bandwidth'] }, { x: -12, z: -1.5 });
}

// 前の回と比べて、問題がどこへ移ったかを一言で
export function shift(prev, cur) {
  if (!prev || prev.scene !== cur.scene) return null;
  const changed = Object.keys(cur.cfg).filter((k) => cur.cfg[k] !== prev.cfg[k]);
  const order = { hit: 3, near: 2, issue: 1, safe: 0 };
  const d = order[cur.outcome.kind] - order[prev.outcome.kind];
  return { changed, better: d < 0, worse: d > 0, same: d === 0 };
}
```

### app2_head.html（画面の HTML と CSS の置き場所）

```html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>歩道の配送ロボット — 事故が起きたら誰の責任？（試作）</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=Noto+Sans+JP:wght@400;500;700&display=swap">
<style>
/*BUSCSS*/
/* ---- ここから配送ロボットの版で足したもの（バスの版の決まりの中で） ---- */
.card{z-index:2}
#labels{position:absolute;inset:0;z-index:1;pointer-events:none;overflow:hidden}
.lbl{position:absolute;transform:translate(-50%,-100%);background:#111;color:#fff;font-size:11px;border-radius:999px;padding:2px 9px;white-space:nowrap}
.lbl.say{background:#fff;color:#111;border:1px solid #111;border-radius:10px;font-size:12px;padding:4px 10px;white-space:normal;width:max-content;max-width:220px}
#caption{left:16px;bottom:16px;max-width:460px;display:none;padding:12px 16px}
#caption .w{font-size:11.5px;color:var(--sub)}#caption .t{font-size:15px;font-weight:700;line-height:1.5}
#caption.hit{outline:2px solid var(--red)}
#op{right:16px;bottom:16px;width:290px;display:none;padding:12px 14px}
#op h3{margin:0 0 6px;font-size:12.5px}#op .q{display:flex;flex-direction:column;gap:4px}
#op .r{display:grid;grid-template-columns:1fr auto;gap:8px;font-size:12px;background:#f5f5f3;border-radius:8px;padding:5px 8px}
#op .r.act{background:#111;color:#fff}#op .r b{font-weight:600}#op .r i{font-style:normal;color:#777}#op .r.act i{color:#ccc}
#op .none{font-size:12px;color:#777}
#timebar{display:none;align-items:center;gap:12px;margin-top:10px}
#clockS{font-size:26px;font-weight:600;min-width:72px}#clockS small{font-size:13px;font-weight:400;margin-left:3px}
#timebar .seg{flex:1;margin:0}
#views .vrow{display:flex;gap:6px}#views .hint{text-align:right;align-self:flex-end}
#ref{font-size:11.5px;color:#777;margin:0}
.cfgs span{white-space:nowrap}
.inc .facts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;margin-top:2px}.inc .facts.f4{grid-template-columns:repeat(2,minmax(0,1fr))}
.inc .fact{background:var(--face);border-radius:10px;padding:8px 10px}.inc .fact span{display:block;font-size:11px;color:var(--sub);line-height:1.4}.inc .fact b{font-size:22px;font-weight:600}.inc .fact i{font-style:normal;font-size:12px;margin-left:2px}
@media(max-width:900px){#top{right:16px;max-width:none;padding:10px 14px}#top .lead{font-size:15px}#introText,#views .hint{display:none}#views{top:auto;bottom:12px;right:12px;padding:6px}#caption{left:12px;right:12px;bottom:62px;max-width:none;padding:8px 12px}#caption .t{font-size:13px}#op{top:auto;bottom:130px;right:12px;width:210px;padding:8px 10px}}
</style>
</head>
<body>
<div id="play" class="view on">
  <div id="stage">
    <div id="top" class="card">
      <h1>事故が起きたら誰の責任？ 歩道の配送ロボット<span class="tag">試作 v0</span></h1>
      <div id="intro">
        <p class="lead">あなたは、この街で配送ロボットを走らせる運行会社の担当者です</p>
        <p id="introText">右で場面と設定を選んで、その1回を見てください。設定を1つ変えてもう一度見ると、問題が誰に移るかを比べられます。</p>
      </div>
      <div id="timebar"><div id="clockS">0<small>秒</small></div><div class="seg" id="sceneSpeeds"><button data-r="1" class="on">実際の速さ</button><button data-r="2">2倍</button><button data-r="4">4倍</button></div></div>
    </div>
    <div id="views" class="card">
      <div class="vrow"><div class="seg" id="viewBtns"><button data-v="iso" class="on">斜め上</button><button data-v="top">真上</button><button data-v="follow">ロボットの後ろ</button></div><div class="seg"><button id="hand" aria-pressed="false">手のひら</button></div></div>
      <span class="hint">ドラッグで回す・ホイールや2本指で寄る<br>右ドラッグ・Shift＋ドラッグ・手のひら・2本指で位置を動かす</span>
    </div>
    <div id="labels"></div>
    <div id="caption" class="card"><div class="w"></div><div class="t"></div></div>
    <div id="op" class="card"><h3></h3><div class="q"></div></div>
    <div id="bubble" class="card" role="note"><button class="x" aria-label="閉じる">×</button><b>この「まだ決まっていないこと」、あなたの現場ではどうしますか？</b>歩道や道順、遠隔の担当の体制を、あなたの現場に合わせて作り直して確かめられます。<br><a href="https://pixelstomotors.com/message" target="_blank" rel="noopener">相談する →</a></div>
  </div>
  <aside id="panel">
    <h2 id="panelTitle" style="display:none"></h2>
    <div id="scenes"></div>
    <p id="ref"></p>
    <div id="groups"></div>
    <div id="runInfo" style="display:none">
      <div id="cfgLine" class="cfgs"></div>
      <div id="incident"></div>
    </div>
    <div style="margin-top:auto;display:flex;flex-direction:column;gap:8px">
      <button class="cta" id="run">この場面を見る <span aria-hidden="true">→</span></button>
      <button class="cta sub" id="autoRun">自動再生（設定を1つずつ変えて見る）</button>
      <p class="note" id="panelNote">動きと数字は試作の仮の決まり。予測ではありません。実在の会社や事故の名前は出していません</p>
      <button class="link" id="stopRun" style="display:none;align-self:flex-start">設定に戻る</button>
    </div>
  </aside>
</div>
<div id="sceneCmp" class="view sheet"></div>
<div id="assign" class="view sheet"></div>
<div id="compare" class="view sheet"></div>

<script type="text/plain" id="three-src">/*THREE*/</script>
<script type="text/plain" id="engine-src">/*ENGINE*/</script>
<script type="module">
{
const modURL = (id) => URL.createObjectURL(new Blob([document.getElementById(id).textContent], { type: 'text/javascript' }));
const THREE = await import(modURL('three-src'));
const E = await import(modURL('engine-src'));
const $ = (s) => document.querySelector(s);
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
let sceneId = 'wheelchair';
```

### app2_main.js（画面の動き。場面の一覧・設定・説明のカード・比べる・自動再生・責任の振り分け・レポート）

```javascript
// ---------------- 設定のパネル ----------------
const KIND_LABEL = E.KIND;
const cfgs = Object.fromEntries(E.SCENES.map((s) => [s.id, { ...s.defaults }]));
const SC = (id = sceneId) => E.SCENES.find((s) => s.id === id);
const splitOpt = (t) => { const m = t.match(/^(.*?)（(.*)）$/); return m ? [m[1], m[2]] : [t, '']; };
const label = (sc, k, v) => splitOpt(sc.groups.find((g) => g.k === k).opts.find((o) => o[0] === v)[1])[0];
// 設定のまとめ・自動再生の行に使う短い見出し
// 見出しは1行に収まる長さにする（2行に折り返さないように。9文字まで）
const SHORT = { yield: 'すれ違うときの動き', detect: '人に気づく距離', speed: '歩道での速さ', signal: '寄る側の合図', ratio: '1人が見る台数', order: '助けの順番', mrm: '待つ間のロボット', route: '踏切を通る道', voice: '動けないときの機体', push: '押して動かせるか', rescue: '駆け付ける人', pass: '追いついたとき', gap: '前の人との間', traffic: '車の多さ', time: '走らせる時間', stop: '人に近づく距離', waitpos: '止まる場所', stopAt: '止まる場所', sound: '近づく人への知らせ', wait: '受け取りを待つ', face: '顔の表示', resp: '囲まれたとき', body: '車体の重さ', sensor: 'センサー', approach: '人と動物が来たら', rear: '後ろの見張り', brake: '止まり方', bike: '自転車の走り方', map: '地図の見直し', way: '通れないとき', env: '天気と時間', launch: '出発のさせ方', cap: 'たまる台数', waitAt: '待たせる場所', cross: '車が来ているとき', insurance: '賠償責任保険', record: '記録を残す日数' };
function cfgSummary(sc, c, other) {
  return sc.groups.map((g) => `<div><span>${SHORT[g.k] || g.label.replace(/（.*$/, '')}</span><b class="${other && (typeof other === 'string' ? other === g.k : other[g.k] !== c[g.k]) ? 'chg' : ''}">${label(sc, g.k, c[g.k])}</b></div>`).join('');
}
let locked = false;
function drawScenes() {
  const btn = (s) => `<button class="sc ${s.id === sceneId ? 'on' : ''}" data-id="${s.id}"><b>${s.title}</b><span>${s.sub}</span></button>`;
  $('#scenes').innerHTML = '<div class="h">場面</div>' + E.SCENE_GROUPS.map(([g, nm]) => `<div class="gh">${nm}</div>` + E.SCENES.filter((s) => s.group === g).map(btn).join('')).join('');
  $('#ref').textContent = SC().ref;
}
function drawPanel() {
  const sc = SC(), cfg = cfgs[sceneId];
  $('#groups').innerHTML = sc.groups.map((g) => {
    const n = splitOpt(g.opts.find((o) => o[0] === cfg[g.k])[1])[1];
    return `<div class="grp"><span>${g.label}</span><div class="opts">${g.opts.map((o, i) => `<button data-k="${g.k}" data-i="${i}" class="${cfg[g.k] === o[0] ? 'on' : ''}" aria-pressed="${cfg[g.k] === o[0]}">${splitOpt(o[1])[0]}</button>`).join('')}</div>${n ? `<p class="optNote">${n}</p>` : ''}</div>`;
  }).join('');
  $('#panel').classList.toggle('locked', locked);
}
$('#scenes').addEventListener('click', (e) => { const b = e.target.closest('.sc'); if (!b || locked) return; sceneId = b.dataset.id; drawScenes(); drawPanel(); view.setScene(sceneId); showIdle(); });
$('#groups').addEventListener('click', (e) => {
  const b = e.target.closest('button[data-k]'); if (!b || locked) return;
  const g = SC().groups.find((x) => x.k === b.dataset.k); cfgs[sceneId][g.k] = g.opts[+b.dataset.i][0];
  drawPanel(); showIdle();
});

/*VIEW3D*/

// ---------------- 画面の切り替え ----------------
const views = ['play', 'sceneCmp', 'assign', 'compare'];
function show(v) { views.forEach((x) => $('#' + x).classList.toggle('on', x === v)); window.scrollTo(0, 0); }
function setPlayMode(m) {
  if (m !== 'scene') { $('#bubble').style.display = 'none'; }
  const running = m === 'scene';
  if (m === 'setup') { stopPlay(); showIdle(); }
  locked = running; drawPanel();
  $('#groups').style.display = running ? 'none' : ''; $('#runInfo').style.display = running ? '' : 'none';
  $('#scenes').style.display = running ? 'none' : ''; $('#ref').style.display = running ? 'none' : '';
  $('#intro').style.display = running ? 'none' : ''; $('#timebar').style.display = running ? 'flex' : 'none';
  $('#run').style.display = running ? 'none' : ''; $('#autoRun').style.display = running ? 'none' : ''; $('#stopRun').style.display = running ? '' : 'none';
  $('#panelTitle').style.display = running ? '' : 'none';
}

// ---------------- 再生 ----------------
let shown = null, idleRes = null, T = 0, rate = 1, playing = false, onDone = null, timer = null;
function showIdle() {
  idleRes = E.run(sceneId, cfgs[sceneId]); shown = idleRes; T = 0;
  view.setCur(idleRes); view.setFrame(0);
  $('#caption').style.display = 'none'; $('#op').style.display = 'none'; $('#labels').innerHTML = '';
}
function play(res, done) { shown = res; view.setCur(res); T = 0; playing = true; onDone = done; }
function stopPlay() { playing = false; onDone = null; clearTimeout(timer); timer = null; auto = null; }
$('#sceneSpeeds').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; rate = +b.dataset.r; [...$('#sceneSpeeds').children].forEach((x) => x.classList.toggle('on', x === b)); });
view.onTick((dt) => {
  const r0 = shown; if (!r0) return;
  if (playing) {
    T += dt * rate; const end = r0.frames[r0.frames.length - 1].t;
    if (T >= end) { T = end; view.setFrame(T); drawOverlay(r0, T); playing = false; const f = onDone; onDone = null; if (f) f(r0); return; }
  }
  view.setFrame(T);
  if (r0 !== idleRes) drawOverlay(r0, T);
});
function drawOverlay(r0, T) {
  $('#clockS').innerHTML = `${T.toFixed(0)}<small>秒</small>`;
  const evs = r0.events.filter((e) => e.t <= T), e = evs[evs.length - 1], cap = $('#caption');
  if (e && $('#bubble').style.display !== 'block') { cap.style.display = 'block'; cap.querySelector('.w').textContent = `${e.t.toFixed(0)}秒　${e.who === '—' ? '' : e.who}`; cap.querySelector('.t').textContent = e.text; cap.classList.toggle('hit', e.kind === 'hit'); }
  else cap.style.display = 'none';
  const fr = r0.frames[Math.min(r0.frames.length - 1, Math.floor(T / r0.dt))], op = $('#op');
  if (fr.queue) {
    op.style.display = 'block';
    op.querySelector('h3').textContent = r0.cfg.ratio === 1 ? '遠隔の担当（台ごとに1人）' : `遠隔の担当（1人で${r0.cfg.ratio}台）`;
    op.querySelector('.q').innerHTML = fr.queue.length ? fr.queue.map((q) => `<div class="r ${q.active ? 'act' : ''}"><b>${q.name}</b><i>${q.active ? (q.rushed ? '対応中・確認を短く' : '対応中') : `待ち ${Math.round(q.wait)}秒`}</i></div>`).join('') : '<div class="none">助けを求めている台はありません</div>';
  } else op.style.display = 'none';
  const L = [];
  const add = (x, y, z, text, cls = '') => { const p = view.screenOf(x, y, z); if (p.vis) L.push(`<div class="lbl ${cls}" style="left:${p.x}px;top:${p.y}px">${esc(text)}</div>`); };
  if (r0.scene === 'remote') for (const rb of fr.robots) add(rb.x, 2.1, rb.z, rb.id === 'A' ? '横断歩道の台' : '工事の前の台');
  for (const c of fr.cars || []) if (c.av) add(c.x, 2.4, c.z, '自動運転の車');
  if (r0.scene === 'cane') { const c = fr.peds.find((p) => p.kind === 'cane'); if (c) add(c.x, 2.0, c.z, '白い杖の人'); if (r0.cfg.sound === 'sound') { const ev2 = r0.events.find((x) => x.text.startsWith('近づく人に、音声で')); if (ev2 && T >= ev2.t && T < ev2.t + 5) add(fr.robots[0].x, 2.0, fr.robots[0].z, 'ロボットが止まっています。車道側を通れます', 'say'); } }
  if (r0.scene === 'sidebyside' && r0.cfg.pass === 'ask') { const ev2 = r0.events.find((x) => x.text.startsWith('音声で')); if (ev2 && T >= ev2.t && T < ev2.t + 4) add(fr.robots[0].x, 2.0, fr.robots[0].z, '後ろから通ります', 'say'); }
  if (r0.scene === 'kids' && r0.cfg.face === 'face' && r0.cfg.resp === 'voice') { const ev2 = r0.events.find((x) => x.text.startsWith('音声で')); if (ev2 && T >= ev2.t && T < ev2.t + 5) add(fr.robots[0].x, 2.0, fr.robots[0].z, '通ります、離れてください', 'say'); }
  if (r0.scene === 'crossing' && r0.cfg.voice === 'ask' && fr.robots[0].light === 'ask') add(fr.robots[0].x, 2.3, fr.robots[0].z, r0.cfg.push === 'free' ? '動けません。押して外へ出してください' : '動けません。踏切の非常ボタンを押してください', 'say');
  if (r0.scene === 'wheelchair' && r0.cfg.signal) { const ev2 = r0.events.find((x) => x.text.startsWith('光と音で')); if (ev2 && T >= ev2.t && T < ev2.t + 5) add(fr.robots[0].x, 2.0, fr.robots[0].z, (ev2.text.match(/「(.*?)」/) || [])[1] || '', 'say'); }
  $('#labels').innerHTML = L.join('');
}

// ---------------- 説明のカード（バスの版と同じ形） ----------------
const whoOf = (ex) => [...new Set([...ex.people, ...ex.company].map((p) => p[0]))];
function incCard(kind, ex, when, facts) {
  const sec = (title, arr) => (arr.length ? `<h4>${title}</h4><ul class="who3">${arr.map(([w, t]) => `<li><b class="${w.includes('あなた') ? 'me' : ''}">${esc(w)}</b>${esc(t)}</li>`).join('')}</ul>` : '');
  const iss = [...ex.issues].sort((p, q) => E.ISSUES[p][0] - E.ISSUES[q][0]);
  return `<div class="inc ${kind}"><div class="hd"><span class="tag">${KIND_LABEL[kind]}</span>${esc(when)}</div>
    <p class="what">${esc(ex.what)}</p>
    ${facts ? `<div class="facts ${facts.length === 4 ? 'f4' : ''}">${facts.map((f) => `<div class="fact"><span>${f.k}</span><b>${f.v}</b><i>${f.u}</i></div>`).join('')}</div>` : ''}
    ${sec('人の問題', ex.people)}${sec('企業の問題', ex.company)}${sec('決まり・行政', ex.rules)}
    ${ex.open ? `<div class="open"><span>まだ決まっていないこと</span>${esc(ex.open)}</div>` : ''}
    ${iss.length ? `<div class="iss"><span>課題地図の関連する課題</span>${iss.map((s) => `<a href="https://pixelstomotors.com/issues/${s}" target="_blank" rel="noopener">#${E.ISSUES[s][0]} ${E.ISSUES[s][1]}</a>`).join('')}</div>` : ''}</div>`;
}
const MSG_URL = 'https://pixelstomotors.com/message';
const ctaPanel = () => `<div class="ctaP"><div><p class="who">配送ロボットや移動ロボットの導入を進めている方へ</p><h3>あなたの街や現場で、同じことを確かめませんか</h3><p class="b">歩道の幅や道順、遠隔の担当の体制、止まり方の作りを、あなたの現場に合わせて作り直せます。設定を変えると、人・企業・決まりのどこに問題が移るかを、走らせる前に確かめられます。</p></div><a href="${MSG_URL}" target="_blank" rel="noopener">相談する <span aria-hidden="true">→</span></a></div>`;
let bubbleShown = false;
function maybeBubble(kind) {
  if (bubbleShown || (kind !== 'hit' && kind !== 'issue')) return;
  bubbleShown = true; $('#caption').style.display = 'none'; $('#bubble').style.display = 'block'; // 1回の訪問で1度だけ
}
$('#bubble .x').addEventListener('click', () => { $('#bubble').style.display = 'none'; });

// ---------------- 場面を選んで確かめる ----------------
const sceneRuns = [];
const toRun = (r) => ({ sceneId: r.scene, cfg: r.cfg, kind: r.outcome.kind, ex: { ...r.explain, who: whoOf(r.explain) }, facts: r.facts, events: r.events });
function startScene() {
  const sc = SC(); show('play'); setPlayMode('scene');
  $('#panelTitle').textContent = sc.title; $('#cfgLine').innerHTML = cfgSummary(sc, cfgs[sceneId]);
  $('#incident').innerHTML = '<p class="note">この場面を再生しています</p>';
  play(E.run(sceneId, cfgs[sceneId]), sceneDone);
}
function sceneDone(r) {
  const sc = SC(r.scene), x = toRun(r);
  const prev = sceneRuns.filter((y) => y.sceneId === sc.id).at(-1);
  sceneRuns.push(x);
  $('#incident').innerHTML = incCard(x.kind, x.ex, sc.title, x.facts) + `<div class="sbtns"><button class="cta" id="sAgain">設定を変えて見直す <span aria-hidden="true">→</span></button>${prev ? '<button class="cta sub" id="sCmp">前の回と比べる</button>' : ''}<button class="link" id="sReplay">同じ設定でもう一度</button>${x.kind === 'hit' ? '<button class="cta sub" id="sAssign">誰にどれだけ責任があるかを考える</button>' : ''}<button class="cta sub" id="sRep">この回のレポートを見る</button></div>`;
  maybeBubble(x.kind);
  $('#sAgain').addEventListener('click', () => setPlayMode('setup'));
  $('#sReplay').addEventListener('click', () => startScene());
  $('#sRep').addEventListener('click', () => saveReport(sc.title, 'あなたが決めた設定で、この場面を1回見た結果です。', [runBlock(x, 'この回')]));
  if (prev) $('#sCmp').addEventListener('click', () => openSceneCompare(prev, x));
  if (x.kind === 'hit') $('#sAssign').addEventListener('click', () => openAssign(x, 'play'));
}
function openSceneCompare(a, b) {
  const sc = SC(b.sceneId), res = (x) => KIND_LABEL[x.kind];
  const changed = sc.groups.filter((g) => a.cfg[g.k] !== b.cfg[g.k]);
  const col = (x, other, title) => `<div class="col"><h3>${title}</h3><div class="cfgs" style="margin-bottom:10px">${cfgSummary(sc, x.cfg, other.cfg)}</div>${incCard(x.kind, x.ex, sc.title, x.facts)}</div>`;
  const wa = new Set(a.ex.who), wb = new Set(b.ex.who);
  const gone = [...wa].filter((w) => !wb.has(w)), added = [...wb].filter((w) => !wa.has(w));
  const sum = `変えたこと：${changed.length ? changed.map((g) => `${SHORT[g.k]}を「${label(sc, g.k, b.cfg[g.k])}」に`).join('、') : 'なし'}。<br>結果：${res(a)} → ${res(b)}。` +
    (gone.length ? `<br>問題から外れた：${gone.join('・')}` : '') + (added.length ? `<br>新しく問題になった：${added.join('・')}` : '') + (!gone.length && !added.length ? '<br>かかわる人は変わらなかった' : '') +
    (a.ex.open !== b.ex.open ? `<br>まだ決まっていないこと：${b.ex.open}` : '');
  $('#sceneCmp').innerHTML = `<p class="eyebrow">場面：${sc.title}</p><h2>設定を変えると、問題はどこへ移る？</h2><div class="sum">${sum}</div><div class="cols">${col(a, b, 'まえ')}${col(b, a, 'あと')}</div>
    <div class="xbtn"><button class="cta sub" id="cmpRep">この比べた結果のレポートを見る</button></div>
    ${ctaPanel()}
    <div class="foot"><button class="link" id="cmpBack">← 設定に戻る</button><button class="cta" id="cmpAgain">続けて、もう1つ変える <span aria-hidden="true">→</span></button></div>`;
  show('sceneCmp');
  $('#cmpRep').addEventListener('click', () => saveReport(`${sc.title}：設定を変えると、問題はどこへ移る？`, '', [`<div class="sum">${sum}</div>`, runBlock(a, 'まえ'), runBlock(b, 'あと')]));
  $('#cmpBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#cmpAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---------------- 自動再生：設定を1つずつ変えながら次々に再生し、最後に一覧で並べる ----------------
let auto = null;
function autoVariants() {
  const sc = SC(), cfg = cfgs[sceneId], list = [{ label: 'もとの設定のまま（下の設定）', cfg: { ...cfg }, k: null }];
  for (const g of sc.groups) for (const o of g.opts) if (o[0] !== cfg[g.k]) list.push({ label: `${SHORT[g.k]}：${label(sc, g.k, cfg[g.k])} → ${splitOpt(o[1])[0]}`, cfg: { ...cfg, [g.k]: o[0] }, k: g.k });
  return list;
}
function startAuto() {
  const sc = SC(); show('play'); setPlayMode('scene');
  auto = { sc, list: autoVariants(), i: 0, res: [] };
  $('#panelTitle').textContent = `${sc.title}（自動再生）`;
  autoNext();
}
function autoNext() {
  const a = auto; if (!a) return;
  if (a.i >= a.list.length) { auto = null; openAutoSummary(a); return; }
  const v = a.list[a.i];
  $('#cfgLine').innerHTML = cfgSummary(a.sc, v.cfg, v.k || undefined);
  $('#incident').innerHTML = `<p class="note" style="font-size:13px;color:#111"><b>${a.i + 1} / ${a.list.length}</b>　${v.label}</p><div id="autoNow"></div>${autoHistory(a)}`;
  play(E.run(a.sc.id, v.cfg), (r) => {
    if (auto !== a) return;
    const x = { ...toRun(r), label: v.label, k: v.k };
    a.res.push(x);
    $('#incident').innerHTML = `<p class="note" style="font-size:13px;color:#111"><b>${a.i + 1} / ${a.list.length}</b>　${v.label}</p>${incCard(x.kind, x.ex, v.label, x.facts)}${autoHistory(a, true)}`;
    a.i++; timer = setTimeout(autoNext, 1500 / rate);
  });
}
function autoHistory(a, skipLast) {
  const list = (skipLast ? a.res.slice(0, -1) : a.res).map((x, i) => ({ x, n: i + 1 })).reverse();
  if (!list.length) return '';
  return `<div class="ahist"><h4>これまでの回</h4>${list.map(({ x, n }) => `<details><summary><b>${n}</b><span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span><span>${x.label}</span></summary>${incCard(x.kind, x.ex, x.label, x.facts)}</details>`).join('')}</div>`;
}
function openAutoSummary(a) {
  const rows = a.res.map((x, i) => `<tr class="arow" data-i="${i}"><td><span class="tg">＋</span>${i === 0 ? '<b>もとの設定のまま</b>' : x.label}</td><td><span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span></td><td>${x.ex.who.map((w) => `<i class="${w.includes('あなた') ? 'me' : ''}">${w}</i>`).join('')}</td><td><span class="sub">${x.ex.open}</span></td></tr><tr class="adet" data-i="${i}" hidden><td colspan="4">${incCard(x.kind, x.ex, x.label, x.facts)}${x.kind === 'hit' ? `<div class="xbtn"><button class="cta sub" data-assign="${i}">この事故、誰にどれだけ責任があるかを考える</button></div>` : ''}</td></tr>`).join('');
  $('#sceneCmp').innerHTML = `<p class="eyebrow">場面：${a.sc.title}（自動再生）</p><h2>設定を1つずつ変えると、結果と問題はどう変わる？</h2>
    <p class="note">下のもとの設定から1つだけ変えて、同じ場面を${a.res.length}回見た結果です。まわりの人や車の動き方の決まりは毎回同じです。行を押すと、その回の詳しい説明がひらきます</p>
    <h4 style="margin:14px 0 6px;font-size:12px;color:#777">もとの設定</h4><div class="cfgs">${cfgSummary(a.sc, a.res[0].cfg)}</div>
    <table class="auto"><thead><tr><th>変えたこと</th><th>結果</th><th>かかわる人</th><th>まだ決まっていないこと</th></tr></thead><tbody>${rows}</tbody></table>
    <div class="xbtn"><button class="cta sub" id="autoRep">この結果のレポートを見る</button></div>
    ${ctaPanel()}
    <div class="foot"><button class="link" id="autoBack">← 設定に戻る</button><button class="cta" id="autoAgain">別の場面で自動再生 <span aria-hidden="true">→</span></button></div>`;
  show('sceneCmp');
  $('#sceneCmp').querySelector('tbody').addEventListener('click', (e) => { const ab = e.target.closest('[data-assign]'); if (ab) { openAssign(a.res[+ab.dataset.assign], 'sceneCmp'); return; } const r = e.target.closest('.arow'); if (!r) return; const d = $('#sceneCmp').querySelector(`.adet[data-i="${r.dataset.i}"]`); d.hidden = !d.hidden; r.querySelector('.tg').textContent = d.hidden ? '＋' : '－'; });
  $('#autoRep').addEventListener('click', () => saveReport(`${a.sc.title}：設定を1つずつ変えた結果`, `下のもとの設定から1つだけ変えて、同じ場面を${a.res.length}回見た結果です。まわりの人や車の動き方の決まりは毎回同じです。`, [`<section><h2>もとの設定</h2><div class="cfgs">${cfgSummary(a.sc, a.res[0].cfg)}</div></section>`, summaryTable(a.res.map((x, i) => ({ ...x, label: i === 0 ? 'もとの設定のまま' : x.label }))), ...a.res.map((x, i) => runBlock(x, i === 0 ? 'もとの設定のまま' : x.label, i > 0))]));
  $('#autoBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#autoAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---------------- 責任の振り分け（自動運転バスの版と同じ形） ----------------
// 相手と手がかりは、その回の説明のカード（人の問題・企業の問題）から作る。「A・B」のように2者が並ぶものは、両方の手がかりにする
function clues(x) {
  const m = new Map();
  for (const [w, t] of [...x.ex.people, ...x.ex.company]) for (const nm of w.split('・')) { if (!m.has(nm)) m.set(nm, []); m.get(nm).push(t); }
  return [...m.entries()].map(([nm, ts], i) => ({ k: 'p' + i, nm, me: nm.includes('あなた'), cl: ts.join('。') }));
}
function openAssign(x, from) {
  const sc = SC(x.sceneId), ps = clues(x), n = ps.length;
  const alloc = x.alloc ? { ...x.alloc } : Object.fromEntries(ps.map((p) => [p.k, Math.round(100 / n)])); fix(ps[0].k);
  $('#assign').innerHTML = `<p class="eyebrow">${esc(sc.title)}</p><h2>この事故、誰にどれだけ責任がある？</h2><p class="what" style="margin:0;font-weight:700">${esc(x.ex.what)}</p><p class="note">合計がいつも100%になるよう、ほかが自動で動きます。手がかりは、この回の説明に出たことです</p><div style="display:flex;flex-direction:column;gap:10px" id="parties">${ps.map((p) => `<div class="party ${p.me ? 'me' : ''}"><span class="nm">${esc(p.nm)}</span><span class="cl">${esc(p.cl)}</span><input type="range" min="0" max="100" step="1" value="${alloc[p.k]}" data-k="${p.k}" aria-label="${esc(p.nm)}の責任"><span class="v"><span id="v-${p.k}">${alloc[p.k]}</span><small style="font-size:13px;font-weight:400">%</small></span></div>`).join('')}</div>
  <div class="foot"><button class="link" id="backRes">← 結果に戻る</button><button class="cta" id="toCompare">決めて、比べる <span aria-hidden="true">→</span></button></div>`;
  show('assign');
  $('#parties').addEventListener('input', (e) => { const k = e.target.dataset.k; alloc[k] = +e.target.value; fix(k); ps.forEach((p) => { $('#v-' + p.k).textContent = alloc[p.k]; $('#parties').querySelector(`input[data-k="${p.k}"]`).value = alloc[p.k]; }); });
  $('#backRes').addEventListener('click', () => show(from));
  $('#toCompare').addEventListener('click', () => { x.alloc = { ...alloc }; x.parties = ps; openAllocResult(x, from); });
  function fix(k) {
    const others = ps.filter((p) => p.k !== k).map((p) => p.k); const rest = 100 - alloc[k]; const sum = others.reduce((t, y) => t + alloc[y], 0);
    others.forEach((y) => { alloc[y] = sum ? Math.round(alloc[y] / sum * rest) : Math.round(rest / others.length); });
    const drift = 100 - Object.values(alloc).reduce((t, v) => t + v, 0); if (others[0]) alloc[others[0]] += drift;
  }
}
const allocRows = (x) => x.parties.map((p) => `<div class="row" style="grid-template-columns:180px minmax(0,1fr) 90px"><span class="k">${esc(p.nm)}</span><div class="bars"><div class="bar" style="width:${x.alloc[p.k]}%"></div></div><span class="n" style="font-size:24px;text-align:right">${x.alloc[p.k]}<small>%</small></span></div>`).join('');
function openAllocResult(x, from) {
  const top = x.parties.reduce((m, p) => (x.alloc[p.k] > x.alloc[m.k] ? p : m), x.parties[0]);
  $('#compare').innerHTML = `<p class="eyebrow">あなたの考えた割合</p><h2>あなたは「${esc(top.nm)}」の責任を一番重く見た</h2>
  <div style="display:flex;flex-direction:column;gap:10px">${allocRows(x)}</div>
  <p class="note">ほかの人の割合と並べる部分は、答えを集める仕組みができてから入ります（試作 v0 では答えを送りません）。法律上の正解を示すものではありません</p>
  <div class="xbtn"><button class="cta sub" id="alRep">割合を入れたレポートを見る</button></div>
  <div class="foot"><button class="link" id="alBack">← 割合を決め直す</button><button class="cta" id="alAgain">設定を変えて見直す <span aria-hidden="true">→</span></button></div>`;
  show('compare');
  $('#alRep').addEventListener('click', () => saveReport(`${SC(x.sceneId).title}：この事故、誰にどれだけ責任がある？`, 'この場面を見て、あなたが考えた責任の割合です。', [runBlock(x, x.label || 'この回')]));
  $('#alBack').addEventListener('click', () => openAssign(x, from));
  $('#alAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---------------- 見る人が持ち帰るレポート（1つのHTML。ブラウザで開き、印刷すればPDFにもなる） ----------------
function timeline(events) {
  if (!events || !events.length) return '';
  return `<h4>できごとの記録（場面の始まりからの秒数）</h4><table class="tl">${events.map((e) => `<tr><td>${e.t.toFixed(1)}秒</td><td>${e.who === '—' ? '' : esc(e.who) + '：'}${esc(e.text)}</td></tr>`).join('')}</table>`;
}
function runBlock(x, title, showChange) {
  const sc = SC(x.sceneId);
  return `<section><h2>${esc(title)}</h2><h4>選んだ設定</h4><div class="cfgs">${cfgSummary(sc, x.cfg, showChange ? x.k : undefined)}</div>${incCard(x.kind, x.ex, '', x.facts)}${x.alloc ? `<h4>あなたが考えた責任の割合</h4><table class="sumt">${x.parties.map((p) => `<tr><td>${esc(p.nm)}</td><td style="width:60%"><div style="height:10px;border-radius:5px;background:#111;width:${x.alloc[p.k]}%"></div></td><td style="text-align:right;white-space:nowrap">${x.alloc[p.k]}%</td></tr>`).join('')}</table>` : ''}${timeline(x.events)}</section>`;
}
function summaryTable(list) {
  return `<section><h2>結果の一覧</h2><table class="sumt"><tr><th>変えたこと</th><th>結果</th><th>かかわる人</th><th>まだ決まっていないこと</th></tr>${list.map((x) => `<tr><td>${esc(x.label)}</td><td><span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span></td><td>${esc(x.ex.who.join('・'))}</td><td>${esc(x.ex.open)}</td></tr>`).join('')}</table></section>`;
}
/*REPORTCSS*/
function saveReport(title, lead, blocks) {
  const now = new Date(), d = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`;
  const html = `<!DOCTYPE html><html lang="ja"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}｜事故が起きたら誰の責任？ 歩道の配送ロボット</title><style>${REPORT_CSS}</style></head><body><main>
<p class="eyebrow">事故が起きたら誰の責任？ 歩道の配送ロボット（試作）のレポート　${d}</p><h1>${esc(title)}</h1>${lead ? `<p>${esc(lead)}</p>` : ''}
${blocks.join('\n')}
<section class="rcta"><h2>あなたの街や現場で、同じことを確かめませんか</h2><p>このレポートは、架空の街で設定を変えたときに、人・企業・決まりのどこに問題が出るかを確かめたものです。配送ロボットや移動ロボットの導入を進めている方は、あなたの街や現場の歩道の幅や道順、遠隔の担当の体制、止まり方の作りに合わせて作り直し、走らせる前に同じことを確かめられます。</p><p><a href="${MSG_URL}">相談する</a>　${MSG_URL}</p></section>
<footer>実際の事故やトラブルの流れを参考にした、架空の場面です。動きと数字は試作の仮の決まり（版 ${E.VERSION}）で出したもので、予測ではありません。法律上の答えではなく、関係しそうな決まりと、まだ決まっていないことを示しています。<br>Pixels to Motors　pixelstomotors.com</footer></main></body></html>`;
  openReport(html);
}
// レポートは、まず画面の上で見せる。保存は見た人が「PDFで保存」を押したときだけ
function openReport(html) {
  let v = $('#repV');
  if (!v) {
    v = document.createElement('div'); v.id = 'repV';
    v.innerHTML = `<div class="rvBar"><b>レポート</b><span class="note">保存の画面で、送り先を「PDFに保存」にしてください</span><button class="cta" id="rvPdf">PDFで保存</button><button class="link" id="rvClose">閉じる</button></div><iframe title="レポート"></iframe>`;
    document.body.appendChild(v);
    const close = () => { v.style.display = 'none'; document.body.style.overflow = ''; };
    $('#rvClose').addEventListener('click', close);
    v.addEventListener('click', (e) => { if (e.target === v) close(); });
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && v.style.display === 'flex') close(); });
    $('#rvPdf').addEventListener('click', () => {
      const page = v.dataset.html.replace('<main>', `<div class="pbar"><button onclick="print()">PDFで保存</button><span>保存の画面で、送り先を「PDFに保存」にしてください。開かないときは、ブラウザのメニューの「印刷」から保存できます。</span></div><main>`).replace('</body>', '<script>addEventListener("load",()=>setTimeout(()=>print(),300))<\/script></body>');
      const url = URL.createObjectURL(new Blob([page], { type: 'text/html;charset=utf-8' }));
      const w = window.open(url, '_blank');
      if (!w) v.querySelector('.note').textContent = '新しいタブを開けませんでした。ポップアップを許可してから、もう一度押してください';
      setTimeout(() => URL.revokeObjectURL(url), 60000);
    });
  }
  v.dataset.html = html;
  v.querySelector('iframe').srcdoc = html.replace('<head>', '<head><base target="_blank">');
  v.style.display = 'flex'; document.body.style.overflow = 'hidden';
}

$('#run').addEventListener('click', startScene);
$('#autoRun').addEventListener('click', startAuto);
$('#stopRun').addEventListener('click', () => setPlayMode('setup'));
drawScenes(); drawPanel(); view.setScene(sceneId); showIdle();
window.__dr = { E, state: () => ({ T, playing, auto: !!auto }) };
}
</script>
</body>
</html>
```

### view3d.js（3Dの街・ロボット・人・車いす・自転車・犬・車・列車と、視点の動かし方）

```javascript
// ---------------- 3D ----------------
const view = (() => {
  const host = $('#stage');
  const r = new THREE.WebGLRenderer({ antialias: true });
  r.setPixelRatio(Math.min(devicePixelRatio, 2)); r.shadowMap.enabled = true; r.shadowMap.type = THREE.PCFSoftShadowMap;
  host.prepend(r.domElement);
  const s = new THREE.Scene(); s.background = new THREE.Color('#eceef1');
  const cam = new THREE.PerspectiveCamera(34, 1, 0.5, 900);
  const target = new THREE.Vector3();
  let az = 0, el = 0.6, dist = 30, mode = 'orbit', home = {};
  const HOMES = {
    wheelchair: { x: 0, z: -4.5, az: 0.3, el: 0.6, dist: 40 },
    remote: { x: -22, z: -1.5, az: 0.18, el: 0.8, dist: 78 },
    crossing: { x: 30, z: -9, az: -0.62, el: 0.42, dist: 62 },
    sidebyside: { x: 62, z: 4.5, az: 0.25, el: 0.62, dist: 42 },
    crowd: { x: 64, z: 4.5, az: 0.25, el: 0.65, dist: 48 },
    cane: { x: 77, z: -4.5, az: 0.3, el: 0.6, dist: 34 },
    bicycle: { x: 58, z: -4.5, az: 0.3, el: 0.58, dist: 38 },
    kids: { x: -38, z: 4.5, az: 0.25, el: 0.6, dist: 26 },
    dog: { x: -40, z: 4.5, az: 0.25, el: 0.6, dist: 32 },
    sign: { x: -45, z: -4, az: 0.15, el: 1.05, dist: 24 },
    rain: { x: -48, z: -4.2, az: 0.3, el: 0.55, dist: 32 },
    flock: { x: 6, z: 6, az: 0.2, el: 0.75, dist: 46 },
    av: { x: -14, z: -1.5, az: 0.35, el: 0.6, dist: 40 }
  };
  function placeCam() {
    if (mode === 'follow') return;
    cam.position.set(target.x + dist * Math.cos(el) * Math.sin(az), target.y + dist * Math.sin(el), target.z + dist * Math.cos(el) * Math.cos(az));
    cam.lookAt(target);
  }
  const hemi = new THREE.HemisphereLight('#ffffff', '#b9b4a8', 1.6); s.add(hemi); let lastNight = false;
  const sun = new THREE.DirectionalLight('#ffffff', 1.5); sun.position.set(-25, 45, 30); sun.castShadow = true;
  sun.shadow.mapSize.set(2048, 2048); Object.assign(sun.shadow.camera, { left: -45, right: 45, top: 45, bottom: -45, near: 1, far: 160 }); s.add(sun); s.add(sun.target);
  const M = (c) => new THREE.MeshLambertMaterial({ color: c });
  const box = (w, h, d, c, x, y, z, cast = false, parent = s) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), typeof c === 'string' ? M(c) : c); m.position.set(x, y + h / 2, z); m.castShadow = cast; m.receiveShadow = true; parent.add(m); return m; };
  const cyl = (r0, h, c, x, y, z, parent = s, seg = 16) => { const m = new THREE.Mesh(new THREE.CylinderGeometry(r0, r0, h, seg), M(c)); m.position.set(x, y + h / 2, z); m.castShadow = true; parent.add(m); return m; };
  const MAP = E.MAP;
  // 地面・車道・歩道
  box(400, 0.1, 400, '#e3e0d8', 0, -0.12, 0);
  box(240, 0.14, 7, '#7a7f87', 0, -0.02, 0);
  box(240, 0.18, 2.0, '#efe7d4', 0, 0, -4.5); box(240, 0.18, 2.0, '#efe7d4', 0, 0, 4.5);
  box(240, 0.2, 0.14, '#d8d2c4', 0, 0, -3.55); box(240, 0.2, 0.14, '#d8d2c4', 0, 0, 3.55); // 縁石
  for (let x = -118; x < 118; x += 4) if (Math.abs(x - MAP.crosswalk.x) > 3 && Math.abs(x - MAP.rail.x) > 4) box(2, 0.03, 0.14, '#f2f2f2', x, 0.12, 0);
  // 横断歩道（車道を南北に渡る）
  for (let z = -3.0; z <= 3.01; z += 0.9) box(3, 0.03, 0.45, '#ffffff', MAP.crosswalk.x, 0.12, z);
  // 北側の建物（歩道の奥）。店の入口のへこみだけ奥へ下げる
  const bcol = ['#a9aeb5', '#9aa0a8', '#b3b7bd', '#a3a8af', '#bfc2c7'];
  let bi = 0;
  for (let x = -96; x < 96;) {
    const w = 7 + ((bi * 37) % 5) * 1.6, h = 4 + ((bi * 53) % 6) * 1.6;
    const x0 = x, x1 = Math.min(96, x + w);
    // 店の入口（へこみ）の所は、建物を分けて奥へ下げた店の正面を置く
    const r0 = MAP.recess;
    if (x1 > MAP.rail.x - 7 && x0 < MAP.rail.x + 7) { // 線路のまわりは建物を置かない
      if (x0 < MAP.rail.x - 7) box(MAP.rail.x - 7 - x0, h, 10, bcol[bi % 5], (x0 + MAP.rail.x - 7) / 2, 0, -10.5, true);
      bi++; x = Math.max(x1, MAP.rail.x + 7) + 0.3; continue;
    }
    if (x1 > r0.x0 && x0 < r0.x1) {
      if (r0.x0 > x0) box(r0.x0 - x0, h, 10, bcol[bi % 5], (x0 + r0.x0) / 2, 0, -10.5, true);
      if (x1 > r0.x1) box(x1 - r0.x1, h, 10, bcol[bi % 5], (r0.x1 + x1) / 2, 0, -10.5, true);
      box(r0.x1 - r0.x0, h, 8.5, bcol[bi % 5], (r0.x0 + r0.x1) / 2, 0, -11.25, true);
    } else box(x1 - x0, h, 10, bcol[bi % 5], (x0 + x1) / 2, 0, -10.5, true);
    bi++; x = x1 + 0.3;
  }
  // 店の入口のへこみ：床・ガラス・ひさし
  box(MAP.recess.x1 - MAP.recess.x0, 0.18, 1.5, '#e9e2cf', (MAP.recess.x0 + MAP.recess.x1) / 2, 0, -6.25);
  box(MAP.recess.x1 - MAP.recess.x0 - 0.4, 2.2, 0.06, '#3c4652', (MAP.recess.x0 + MAP.recess.x1) / 2, 0.2, -6.98);
  box(MAP.recess.x1 - MAP.recess.x0 + 0.6, 0.12, 1.9, '#5f6b78', (MAP.recess.x0 + MAP.recess.x1) / 2, 2.7, -6.2, true);
  // 狭い所：建物側に自販機2台、車道側に電柱と植木鉢
  const N = MAP.narrow;
  for (const x of [N.x0 + 0.5, N.x0 + 1.5]) { box(0.95, 1.85, 0.7, '#d9dde2', x, 0.18, -5.15, true); box(0.7, 0.9, 0.04, '#3d5a80', x, 0.9, -4.79); }
  cyl(0.15, 9, '#9a9a93', (N.x0 + N.x1) / 2, 0.18, -3.66);
  box(0.9, 0.45, 0.25, '#8a7f6e', N.x0 + 0.5, 0.18, -3.63, true); box(0.7, 0.45, 0.25, '#8a7f6e', N.x1 - 0.45, 0.18, -3.63, true);
  // 工事：建物側を残して、車道側をコーンと柵でふさぐ
  const W = MAP.works;
  box(W.x1 - W.x0, 0.2, -3.5 - W.z, '#5d5a55', (W.x0 + W.x1) / 2, 0.01, (W.z - 3.5) / 2);
  for (let x = W.x0; x <= W.x1 + 0.01; x += 0.75) { const c = new THREE.Mesh(new THREE.ConeGeometry(0.16, 0.7, 12), M('#f07a1a')); c.position.set(x, 0.53, W.z + 0.05); c.castShadow = true; s.add(c); }
  for (const x of [W.x0, W.x1]) for (let z = W.z; z <= -3.5; z += 0.55) { const c = new THREE.Mesh(new THREE.ConeGeometry(0.16, 0.7, 12), M('#f07a1a')); c.position.set(x, 0.53, z); s.add(c); }
  box(W.x1 - W.x0, 0.12, 0.05, '#f2c230', (W.x0 + W.x1) / 2, 0.75, W.z + 0.05);
  box(0.9, 0.9, 0.05, '#f2c230', W.x0 - 0.2, 0.9, -3.4, true);
  // 南側：低いもの（駐車場・低い生け垣・平屋）。カメラと街のあいだに高いものを置かない
  for (let x = -90; x < 90; x += 18) {
    if (Math.abs(x - 30) < 10) continue;
    box(14, 0.04, 8, '#8d9199', x + 7, 0.0, 10.5);
    for (let i = 0; i <= 5; i++) box(0.1, 0.05, 4, '#f2f2f2', x + 1 + i * 2.5, 0.02, 9.5);
    box(14, 0.8, 0.5, '#6f9a5a', x + 7, 0.0, 6.0, true);
  }
  // 点字ブロック（北の歩道の東）。黄色の帯
  { const P = MAP.paving; box(P.x1 - P.x0, 0.03, 0.3, '#e9c22a', (P.x0 + P.x1) / 2, 0.18, P.z); }
  // 店の前に並んだ自転車（北の歩道の建物側）
  const bikeMesh = (parent, x, z, rot = Math.PI / 2) => { const g = new THREE.Group(); g.position.set(x, 0.18, z); g.rotation.y = rot; parent.add(g);
    for (const dx of [-0.48, 0.48]) { const w = new THREE.Mesh(new THREE.TorusGeometry(0.3, 0.03, 6, 18), M('#2a2a2a')); w.position.set(dx, 0.32, 0); g.add(w); }
    box(1.0, 0.04, 0.04, '#7a8a99', 0, 0.5, 0, false, g); box(0.04, 0.4, 0.04, '#7a8a99', -0.15, 0.32, 0, false, g); box(0.22, 0.05, 0.1, '#222', -0.15, 0.72, 0, false, g); box(0.04, 0.4, 0.04, '#7a8a99', 0.4, 0.55, 0, false, g); box(0.05, 0.03, 0.45, '#333', 0.4, 0.78, 0, false, g); return g; };
  for (let x = MAP.parkedBikes.x0; x <= MAP.parkedBikes.x1; x += 0.75) bikeMesh(s, x, MAP.parkedBikes.z);
  // 建物の入口（人が出てくる所）
  for (const x of MAP.doors) { box(1.3, 2.3, 0.06, '#2b3138', x, 0.18, -5.47); box(1.8, 0.35, 0.8, '#5f6b78', x, 2.6, -5.2, true); }
  // 配送ロボットの拠点（南側）。門と敷地
  { const D = MAP.depot.x; box(4, 0.06, 17, '#cfcac0', D, 0.0, 14.6); box(0.15, 1.2, 0.15, '#888', D - 2, 0, 6.1); box(0.15, 1.2, 0.15, '#888', D + 2, 0, 6.1); box(4.3, 0.15, 0.15, '#888', D, 1.2, 6.1); }
  // 踏切：線路は南北。線路の砂利・枕木・レール、踏切の板、遮断機と警報機
  const RX = MAP.rail.x;
  box(5, 0.16, 400, '#a59e92', RX, -0.06, 0);
  for (let z = -198; z < 198; z += 0.6) if (Math.abs(z) > 6) box(2.2, 0.1, 0.2, '#7d6e5d', RX, 0.08, z);
  box(MAP.rail.w, 0.2, 11, '#6c6f74', RX, 0.0, 0); // 踏切の板（車道と歩道の高さにそろえる）
  for (const tx of MAP.rail.tracks) { box(0.07, 0.16, 400, '#c9ccd1', tx, 0.12, 0); box(0.09, 0.04, 11, '#2a2c30', tx + (tx < RX ? 0.08 : -0.08), 0.19, 0); }
  const gates = [], lamps = [];
  const yellowBlack = (() => { const c = document.createElement('canvas'); c.width = 64; c.height = 8; const g = c.getContext('2d'); for (let i = 0; i < 8; i++) { g.fillStyle = i % 2 ? '#111' : '#f2c230'; g.fillRect(i * 8, 0, 8, 8); } const t = new THREE.CanvasTexture(c); t.wrapS = THREE.RepeatWrapping; t.repeat.set(4, 1); return new THREE.MeshLambertMaterial({ map: t }); })();
  for (const [x, z, dir] of [[RX - 2.4, -5.9, 1], [RX + 2.4, -5.9, 1], [RX - 2.4, 5.9, -1], [RX + 2.4, 5.9, -1]]) {
    box(0.35, 1.1, 0.35, '#e8e8e8', x, 0, z, true);
    const piv = new THREE.Group(); piv.position.set(x, 1.0, z); s.add(piv);
    const arm = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.08, 5.6), yellowBlack); arm.position.set(0, 0, dir * 2.8); arm.castShadow = true; piv.add(arm);
    piv.userData.dir = dir; gates.push(piv);
    // 警報機：柱・×の板・赤い灯
    const px = x + (x < RX ? -0.5 : 0.5);
    cyl(0.06, 3.0, '#e8e8e8', px, 0, z);
    for (const a of [0.6, -0.6]) { const b = box(0.9, 0.12, 0.03, '#f2c230', px, 2.72, z); b.rotation.z = a; }
    const lm = []; for (const dz of [-0.28, 0.28]) { const l = new THREE.Mesh(new THREE.SphereGeometry(0.11, 12, 8), new THREE.MeshBasicMaterial({ color: '#4a1a1a' })); l.position.set(px + (x < RX ? -0.05 : 0.05), 2.25, z + dz); s.add(l); lm.push(l); }
    lamps.push(lm);
  }
  // 列車：3両。北から南へ走る。前の端が group の原点
  const train = new THREE.Group();
  for (let i = 0; i < 3; i++) {
    const zc = -10 - i * 20.4;
    box(2.9, 3.4, 20, '#d9dcdf', 0, 0.9, zc, true, train);
    box(2.92, 0.22, 20, '#2f6f9f', 0, 1.5, zc, false, train);
    box(2.94, 0.9, 18.4, '#2b3138', 0, 2.3, zc, false, train);
    box(2.4, 0.5, 20, '#3a3d42', 0, 0.35, zc, false, train);
  }
  box(2.6, 1.1, 0.08, '#2b3138', 0, 2.2, 0.02, false, train);
  train.position.set(RX, 0.2, -400); s.add(train);

  // ---- 配送ロボット（120×70×120cm の中に収まる箱型・6輪・旗） ----
  const lightMat = { go: new THREE.MeshBasicMaterial({ color: '#e9f6ff' }), stop: new THREE.MeshBasicMaterial({ color: '#ffb020' }), ask: new THREE.MeshBasicMaterial({ color: '#ffb020' }), dim: new THREE.MeshLambertMaterial({ color: '#7a6a45' }), off: new THREE.MeshLambertMaterial({ color: '#333' }) };
  function makeRobot() {
    const g = new THREE.Group(); const body = new THREE.Group(); g.add(body);
    const sh = new THREE.Shape(); const L = 0.98, H = 0.78, q = 0.16; // 横から見た角の丸い箱
    sh.moveTo(-L / 2 + q, 0); sh.lineTo(L / 2 - q, 0); sh.quadraticCurveTo(L / 2, 0, L / 2, q); sh.lineTo(L / 2, H - q); sh.quadraticCurveTo(L / 2, H, L / 2 - q, H); sh.lineTo(-L / 2 + q, H); sh.quadraticCurveTo(-L / 2, H, -L / 2, H - q); sh.lineTo(-L / 2, q); sh.quadraticCurveTo(-L / 2, 0, -L / 2 + q, 0);
    const geo = new THREE.ExtrudeGeometry(sh, { depth: 0.62, bevelEnabled: true, bevelSize: 0.03, bevelThickness: 0.03, bevelSegments: 3, curveSegments: 10 }); geo.translate(0, 0, -0.31);
    const m = new THREE.Mesh(geo, M('#f3f3f1')); m.position.y = 0.2; m.castShadow = true; body.add(m);
    box(0.84, 0.05, 0.6, '#2b2f36', 0, 1.0, 0, false, body); // ふた
    const face = box(0.03, 0.34, 0.5, '#20252c', 0.505, 0.5, 0, false, body); // 前の面（カメラと表示）
    const band = box(0.03, 0.06, 0.52, lightMat.go, 0.51, 0.88, 0, false, body); // 前の光の帯
    const bandB = box(0.03, 0.06, 0.52, lightMat.dim, -0.51, 0.88, 0, false, body);
    const sideL = box(0.7, 0.05, 0.02, lightMat.dim, 0, 0.88, 0.345, false, body), sideR = box(0.7, 0.05, 0.02, lightMat.dim, 0, 0.88, -0.345, false, body);
    for (const x of [-0.36, 0, 0.36]) for (const z of [0.33, -0.33]) { const w = new THREE.Mesh(new THREE.CylinderGeometry(0.11, 0.11, 0.08, 16), M('#262626')); w.rotation.x = Math.PI / 2; w.position.set(x, 0.11, z); body.add(w); }
    cyl(0.012, 0.75, '#888', -0.38, 1.02, 0.22, body, 6);
    const flag = box(0.02, 0.16, 0.24, '#f2600c', -0.38, 1.6, 0.34, false, body);
    const eyes = new THREE.Group(); for (const z of [-0.12, 0.12]) { const e = new THREE.Mesh(new THREE.CircleGeometry(0.06, 16), new THREE.MeshBasicMaterial({ color: '#ffffff' })); e.position.set(0.525, 0.72, z); e.rotation.y = Math.PI / 2; eyes.add(e); } eyes.visible = false; body.add(eyes);
    g.userData = { body, band, bandB, sideL, sideR, eyes };
    s.add(g); return g;
  }
  // ---- 人 ----
  const person = (c, seated = false) => { const g = new THREE.Group(); const h = seated ? 0.62 : 1.22; const b = new THREE.Mesh(new THREE.CylinderGeometry(0.24, 0.27, h, 14), M(c)); b.position.y = (seated ? 0.55 : 0) + h / 2; b.castShadow = true; g.add(b); const hd = new THREE.Mesh(new THREE.SphereGeometry(0.19, 14, 10), M(c)); hd.position.y = (seated ? 0.55 : 0) + h + 0.24; hd.castShadow = true; g.add(hd); return g; };
  function makeWheelchair() {
    const g = new THREE.Group();
    for (const z of [0.3, -0.3]) { const w = new THREE.Mesh(new THREE.TorusGeometry(0.28, 0.035, 8, 24), M('#2a2a2a')); w.position.set(-0.15, 0.3, z); g.add(w); const cw = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.09, 0.05, 12), M('#2a2a2a')); cw.rotation.x = Math.PI / 2; cw.position.set(0.38, 0.09, z * 0.85); g.add(cw); }
    box(0.5, 0.08, 0.5, '#3b4450', 0, 0.45, 0, false, g); box(0.08, 0.55, 0.5, '#3b4450', -0.27, 0.5, 0, false, g); box(0.3, 0.05, 0.5, '#3b4450', 0.4, 0.15, 0, false, g);
    box(0.25, 0.35, 0.25, '#56606c', -0.32, 0.18, 0, false, g); // 電池
    const p = person('#e8b923', true); p.position.set(-0.05, 0, 0); g.add(p);
    box(0.4, 0.12, 0.4, '#e8b923', 0.22, 0.5, 0, false, g); // 脚
    s.add(g); return g;
  }
  function makeStroller() {
    const g = new THREE.Group(); const p = person('#e8b923'); g.add(p);
    const st = new THREE.Group(); st.position.set(0.75, 0, 0); g.add(st);
    box(0.65, 0.35, 0.45, '#4e6a8a', 0, 0.35, 0, true, st); const hood = new THREE.Mesh(new THREE.SphereGeometry(0.28, 12, 8, 0, Math.PI * 2, 0, Math.PI / 2), M('#4e6a8a')); hood.position.set(-0.18, 0.7, 0); st.add(hood);
    for (const x of [-0.25, 0.25]) for (const z of [0.2, -0.2]) { const w = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, 0.04, 12), M('#222')); w.rotation.x = Math.PI / 2; w.position.set(x, 0.1, z); st.add(w); }
    box(0.4, 0.04, 0.04, '#333', -0.45, 0.95, 0, false, st);
    s.add(g); return g;
  }
  function makeWalker(p = {}) {
    const g = person(p.umbrella ? '#3b3f46' : '#e8b923'); const ph = box(0.06, 0.14, 0.09, '#111', 0.12, 1.52, 0.17, false, g); g.userData.phone = ph;
    if (p.child) g.scale.set(0.8, 0.68, 0.8);
    if (p.umbrella) { const u = new THREE.Mesh(new THREE.ConeGeometry(0.62, 0.3, 16), M('#24282e')); u.position.set(0, 2.05, 0); g.add(u); cyl(0.015, 0.6, '#555', 0, 1.5, 0, g, 6); }
    if (p.kind === 'cane') { const c = new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 1.25, 6), new THREE.MeshLambertMaterial({ color: '#ffffff' })); c.position.set(0.55, 0.5, 0.15); c.rotation.z = -1.05; g.add(c); }
    s.add(g); return g;
  }
  function makeBike() { const g = new THREE.Group(); const b = bikeMesh(g, 0, 0, 0); b.position.y = 0; const p = person('#e8b923'); p.scale.set(0.9, 0.85, 0.9); p.position.set(-0.1, 0.35, 0); g.add(p); g.userData.body = g.children; s.add(g); return g; }
  function makeDog() { const g = new THREE.Group(); box(0.6, 0.25, 0.22, '#8a5a32', 0, 0.25, 0, true, g); box(0.2, 0.2, 0.18, '#8a5a32', 0.36, 0.42, 0, true, g); for (const x of [-0.22, 0.22]) for (const z of [-0.08, 0.08]) box(0.06, 0.25, 0.06, '#6e4626', x, 0, z, false, g); s.add(g);
    const leash = new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 1, 6), M('#c0392b')); s.add(leash); g.userData.leash = leash; return g; }
  function makeCar(c) {
    const g = new THREE.Group();
    box(4.4, 0.75, 1.7, c, 0, 0.3, 0, true, g); box(2.4, 0.6, 1.55, c, -0.3, 1.05, 0, true, g);
    box(0.04, 0.45, 1.4, '#2b3138', 0.92, 1.1, 0, false, g); box(2.2, 0.42, 0.04, '#2b3138', -0.3, 1.12, 0.78, false, g); box(2.2, 0.42, 0.04, '#2b3138', -0.3, 1.12, -0.78, false, g);
    for (const x of [1.35, -1.35]) for (const z of [0.78, -0.78]) { const w = new THREE.Mesh(new THREE.CylinderGeometry(0.32, 0.32, 0.22, 16), M('#222')); w.rotation.x = Math.PI / 2; w.position.set(x, 0.32, z); g.add(w); }
    s.add(g); return g;
  }
  // 目印：事故は赤、ひやりは黒の輪
  const ring = (c) => { const g = new THREE.Group(); const mat = new THREE.MeshBasicMaterial({ color: c }); const m = new THREE.Mesh(new THREE.TorusGeometry(1.2, 0.07, 8, 48), mat); m.rotation.x = -Math.PI / 2; g.add(m); const pin = new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.05, 2.2, 8), mat); pin.position.y = 2.4; g.add(pin); const hd = new THREE.Mesh(new THREE.SphereGeometry(0.28, 16, 12), mat); hd.position.y = 3.6; g.add(hd); g.visible = false; s.add(g); return g; };
  const markRed = ring('#d93a3a'), markBlack = ring('#111111');

  // 場面ごとの登場物
  const objs = { robots: {}, peds: {}, cars: {}, props: {} };
  function clearActors() {
    for (const k of ['robots', 'peds', 'cars', 'props']) { for (const o of Object.values(objs[k])) { s.remove(o); if (o.userData.leash) s.remove(o.userData.leash); } objs[k] = {}; }
  }
  function ensureActors(f) {
    for (const r0 of f.robots || []) if (!objs.robots[r0.id]) objs.robots[r0.id] = makeRobot();
    for (const p of f.peds || []) if (!objs.peds[p.id]) objs.peds[p.id] = p.kind === 'wheelchair' ? makeWheelchair() : p.kind === 'stroller' ? makeStroller() : p.kind === 'bike' ? makeBike() : p.kind === 'dog' ? makeDog() : makeWalker(p);
    for (const c of f.cars || []) if (!objs.cars[c.id]) { const o = makeCar(c.av ? '#ffffff' : c.id === 'c1' ? '#f0f0ee' : c.id === 'pk' ? '#8c3b3b' : '#4a5563'); if (c.av) { box(0.5, 0.18, 0.5, '#2b2f36', -0.3, 1.65, 0, false, o); } objs.cars[c.id] = o; }
    for (const pr of f.props || []) if (!objs.props[pr.id]) { const g = new THREE.Group(); if (pr.kind === 'sign') { const a = box(0.6, 0.9, 0.04, '#f2f2f2', 0, 0, 0.16, true, g); a.rotation.x = -0.18; const b2 = box(0.6, 0.9, 0.04, '#f2f2f2', 0, 0, -0.16, true, g); b2.rotation.x = 0.18; box(0.5, 0.3, 0.05, '#c0392b', 0, 0.45, 0.2, false, g); } else bikeMesh(g, 0, 0, 0); s.add(g); objs.props[pr.id] = g; }
  }
  const lerp = (a, b, k) => a + (b - a) * k;
  const lerpA = (a, b, k) => { let d = b - a; d = Math.atan2(Math.sin(d), Math.cos(d)); return a + d * k; };
  let cur = null; // 今見せている回
  function setFrame(T) {
    if (!cur) return;
    const fr = cur.frames, i = Math.min(fr.length - 1, Math.max(0, Math.floor(T / cur.dt))), j = Math.min(fr.length - 1, i + 1), k = Math.min(1, Math.max(0, T / cur.dt - i));
    const a = fr[i], b = fr[j];
    ensureActors(a);
    const blink = (performance.now() % 600) < 320;
    for (const ra of a.robots) {
      const rb = b.robots.find((q) => q.id === ra.id) || ra, o = objs.robots[ra.id], u = o.userData;
      o.position.set(lerp(ra.x, rb.x, k), 0.18, lerp(ra.z, rb.z, k)); o.rotation.y = lerpA(ra.h, rb.h, k);
      u.body.rotation.set(0, 0, 0); u.body.position.set(0, 0, 0);
      if (ra.tilt) u.body.rotation.z = -ra.tilt * 2; // 前の車輪が線路のすき間に落ちて前に傾く
      if (ra.hit) { u.body.rotation.x = Math.PI / 2.2; u.body.position.set(0, 0.2, 2.6); }
      u.eyes.visible = cur.scene === 'kids' && cur.cfg.face === 'face';
      if (ra.fallen) { u.body.rotation.x = -Math.PI / 2; u.body.position.set(0, 0.35, -0.4); }
      const lm = ra.light === 'go' ? lightMat.go : ra.light === 'stop' ? lightMat.stop : ra.light === 'ask' ? (blink ? lightMat.ask : lightMat.dim) : lightMat.off;
      u.band.material = lm; u.bandB.material = ra.light === 'go' ? lightMat.dim : lm;
      // どちらへ寄るかの合図：場面1で合図ありのとき、寄る側の横の帯を光らせる
      const sig = sceneId === 'wheelchair' && cur.cfg.signal && ra.light !== 'off';
      u.sideL.material = sig ? (blink ? lightMat.stop : lightMat.dim) : lightMat.dim; u.sideR.material = lightMat.dim; // 建物側（北）の横の帯を点滅
    }
    for (const pa of a.peds) {
      const pb = b.peds.find((q) => q.id === pa.id) || pa, o = objs.peds[pa.id];
      o.position.set(lerp(pa.x, pb.x, k), 0.18, lerp(pa.z, pb.z, k)); o.rotation.y = lerpA(pa.h, pb.h, k);
      if (o.userData.phone) o.userData.phone.visible = !!pa.phone;
      if (pa.kind === 'bike') o.rotation.x = pa.fallen ? Math.PI / 2.3 : 0;
      if (pa.kind === 'dog' && pa.leash) { const own = a.peds.find((q) => q.id === pa.leash), owb = b.peds.find((q) => q.id === pa.leash) || own; const L = o.userData.leash;
        const hx = lerp(own.x, owb.x, k), hz = lerp(own.z, owb.z, k), p1 = new THREE.Vector3(hx, 1.05, hz), p2 = new THREE.Vector3(o.position.x + 0.4 * Math.cos(o.rotation.y), 0.6, o.position.z - 0.4 * Math.sin(o.rotation.y));
        const d = p1.distanceTo(p2); L.scale.set(1, d, 1); L.position.copy(p1).add(p2).multiplyScalar(0.5); L.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), p2.clone().sub(p1).normalize()); }
    }
    for (const pr of a.props || []) { const o = objs.props[pr.id]; o.position.set(pr.x, 0.18, pr.z); o.rotation.set(pr.down ? Math.PI / 2 : 0, 0, 0); if (pr.down) { o.position.z = pr.z + 0.15; o.position.y = 0.42; } }
    // 夜
    const night = a.env === 'night';
    if (night !== lastNight) { lastNight = night; s.background.set(night ? '#1d2229' : '#eceef1'); hemi.intensity = night ? 0.35 : 1.6; sun.intensity = night ? 0.25 : 1.5; }
    for (const ca of a.cars || []) {
      const cb = (b.cars || []).find((q) => q.id === ca.id) || ca, o = objs.cars[ca.id];
      o.position.set(lerp(ca.x, cb.x, k), 0, lerp(ca.z, cb.z, k));
      const dx = cb.x - ca.x, dz = cb.z - ca.z; // 動いているときだけ向きを合わせる（止まっているときは前の向きのまま）
      if (Math.hypot(dx, dz) > 0.02) o.userData.h = Math.atan2(-dz, dx);
      o.rotation.y = o.userData.h || 0;
    }
    // 踏切
    const g = a.gate != null ? lerp(a.gate, b.gate ?? a.gate, k) : 0;
    for (const p of gates) p.rotation.x = -(1 - g) * Math.PI / 2 * p.userData.dir;
    const on = !!a.alarm, bl = (performance.now() % 1000) < 500;
    for (const lm of lamps) { lm[0].material.color.set(on && bl ? '#ff2a2a' : '#4a1a1a'); lm[1].material.color.set(on && !bl ? '#ff2a2a' : '#4a1a1a'); }
    train.position.z = a.train ? lerp(a.train.z, b.train?.z ?? a.train.z, k) : -400;
    // 目印
    // 事故の赤い輪は最後まで、ひやりの黒い輪は起きてから4秒だけ出す
    const evs = cur.events.filter((e) => e.t <= T && e.pos && (e.kind === 'hit' || (e.kind === 'near' && T < e.t + 4)));
    const last = evs[evs.length - 1];
    markRed.visible = !!last && last.kind === 'hit'; markBlack.visible = !!last && last.kind === 'near';
    if (last) (last.kind === 'hit' ? markRed : markBlack).position.set(last.pos.x, 0.2, last.pos.z);
  }
  function screenOf(x, y, z) { const v = new THREE.Vector3(x, y, z).project(cam); return { x: (v.x + 1) / 2 * host.clientWidth, y: (1 - v.y) / 2 * host.clientHeight, vis: v.z < 1 }; }
  function resize() { const w = host.clientWidth, h = host.clientHeight; if (!w || !h) return; r.setSize(w, h, false); cam.aspect = w / h; cam.updateProjectionMatrix(); }
  new ResizeObserver(resize).observe(host); resize();
  let lastT = performance.now(); const followPos = new THREE.Vector3(), followLook = new THREE.Vector3(); let snap = true;
  function loop() {
    const now = performance.now(), dtR = Math.min(0.1, (now - lastT) / 1000); lastT = now;
    onTick(dtR);
    if (mode === 'follow') {
      const id = Object.keys(objs.robots)[0]; const o = objs.robots[id];
      if (o) {
        const h = o.rotation.y, dx = Math.cos(h), dz = -Math.sin(h);
        const want = new THREE.Vector3(o.position.x - dx * 10, 5.5, o.position.z - dz * 10);
        const k = snap ? 1 : 1 - Math.exp(-dtR * 3);
        followPos.lerp(want, k); followLook.lerp(new THREE.Vector3(o.position.x + dx * 5, 0.6, o.position.z + dz * 5), k); snap = false;
        cam.position.copy(followPos); cam.lookAt(followLook);
      }
    }
    r.render(s, cam); requestAnimationFrame(loop);
  }
  let onTick = () => {};
  // 操作：ドラッグで回す／右ドラッグ・Shift＋ドラッグ・2本指で位置を動かす／ホイール・2本指で寄る
  const ptrs = new Map(); let pinch0 = 0, mid0 = null, panDrag = false; const cv = r.domElement;
  cv.addEventListener('contextmenu', (e) => e.preventDefault());
  function pan(dx, dy) { // 画面上の動きを、地面の上の動きに直す
    if (mode === 'follow') setView('custom');
    const k = dist * 0.0016;
    const rx = Math.cos(az), rz = -Math.sin(az), fx = -Math.sin(az), fz = -Math.cos(az);
    target.x += (-dx * rx + dy * fx) * k; target.z += (-dx * rz + dy * fz) * k; placeCam();
  }
  cv.addEventListener('pointerdown', (e) => {
    cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
    panDrag = e.button === 2 || e.shiftKey || handMode;
    if (ptrs.size === 2) { const [p, q] = [...ptrs.values()]; pinch0 = Math.hypot(p.x - q.x, p.y - q.y); mid0 = { x: (p.x + q.x) / 2, y: (p.y + q.y) / 2 }; }
  });
  cv.addEventListener('pointermove', (e) => {
    const p = ptrs.get(e.pointerId); if (!p) return;
    if (ptrs.size === 1) {
      if (panDrag) pan(e.clientX - p.x, e.clientY - p.y);
      else { if (mode === 'follow') setView('custom'); az -= (e.clientX - p.x) * 0.006; el = Math.min(1.55, Math.max(0.12, el + (e.clientY - p.y) * 0.005)); placeCam(); }
    } else if (ptrs.size === 2) {
      p.x = e.clientX; p.y = e.clientY; const [a, b] = [...ptrs.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y), m = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
      if (pinch0) { dist = Math.min(160, Math.max(6, dist * pinch0 / d)); pinch0 = d; }
      if (mid0) pan(m.x - mid0.x, m.y - mid0.y); mid0 = m; placeCam(); return;
    }
    p.x = e.clientX; p.y = e.clientY;
  });
  const up = (e) => { ptrs.delete(e.pointerId); pinch0 = 0; mid0 = null; };
  cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
  cv.addEventListener('wheel', (e) => { e.preventDefault(); if (mode === 'follow') setView('custom'); dist = Math.min(160, Math.max(6, dist * Math.exp(e.deltaY * 0.0012))); placeCam(); }, { passive: false });
  // 手のひら：押すと、1本指・左ドラッグでも位置を動かせる
  let handMode = false;
  $('#hand').addEventListener('click', () => { handMode = !handMode; $('#hand').classList.toggle('on', handMode); cv.style.cursor = handMode ? 'move' : 'grab'; });
  function setView(v) {
    mode = v === 'follow' ? 'follow' : 'orbit';
    if (mode === 'follow') { snap = true; }
    if (v === 'iso') { az = home.az; el = home.el; dist = home.dist; target.set(home.x, 0, home.z); }
    if (v === 'top') { az = 0; el = 1.55; dist = home.dist * 1.15; target.set(home.x, 0, home.z); }
    placeCam();
    document.querySelectorAll('#viewBtns button').forEach((b) => b.classList.toggle('on', b.dataset.v === v));
  }
  $('#viewBtns').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) setView(b.dataset.v); });
  function setScene(id) {
    home = HOMES[id]; target.set(home.x, 0, home.z);
    sun.position.set(home.x - 25, 45, home.z + 30); sun.target.position.set(home.x, 0, home.z);
    clearActors(); cur = null; setView('iso');
    for (const p of gates) p.rotation.x = -Math.PI / 2 * p.userData.dir; train.position.z = -400;
    markRed.visible = markBlack.visible = false;
  }
  loop();
  return { setScene, setFrame, setCur: (c) => { cur = c; clearActors(); }, screenOf, onTick: (f) => { onTick = f; }, objs };
})();
```

### bus.css（自動運転バスの版の CSS。そのまま使う）

```css

/* VOICE: サイトと同じ、静かで道具らしい画面
   IDEA: 交差点を上から見る運行の管理画面
   PICTURE: three.js の T字路。バス（白）・歩行者（黄）・誘導員（青）
   COLOUR and TYPE: 白地・黒の面、赤は事故だけ。Noto Sans JP ＋ Inter
   LAYOUT: 左に交差点、右に仕組みのパネル。結果からは1枚ずつの画面 */
:root{color-scheme:light;--ink:#111;--sub:#555;--face:#f7f7f7;--line:#e5e5e5;--red:#d93a3a}
*{box-sizing:border-box;min-width:0}
body{margin:0;background:#fff;color:var(--ink);font:15px/1.6 Inter,'Noto Sans JP',sans-serif;overflow-x:clip}
button{font:inherit;color:inherit}
.view{display:none}.view.on{display:flex}
#play{height:100vh;min-height:620px}
#stage{position:relative;flex:1;background:#eceef1;overflow:hidden}
#stage canvas,#acR canvas{position:absolute;inset:0;width:100%;height:100%}
.card{position:absolute;background:#fff;border-radius:12px;padding:14px 18px}
#top{left:16px;top:16px;max-width:430px}
#top h1{margin:0;font-size:13px;font-weight:700}.tag{font-size:11px;font-weight:400;background:#f0f0f0;border-radius:4px;padding:2px 6px;margin-left:8px}
#intro p{margin:6px 0 0}#intro .lead{font-size:20px;font-weight:700;line-height:1.45}
#clock{display:none}#clock .d{font-size:28px;font-weight:600}#clock .d small{font-size:13px;font-weight:400;margin-left:8px}
.seg{display:flex;gap:4px;background:#f0f0f0;border-radius:8px;padding:3px;margin-top:8px}
.seg button{border:0;border-radius:6px;background:transparent;padding:6px 10px;font-size:12px;cursor:pointer}
.seg button.on{background:#111;color:#fff}
#sceneSpeeds button,#speeds button{flex:1 1 auto;white-space:nowrap}
#stats{left:16px;right:16px;bottom:16px;display:none;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
.st span{display:block;font-size:12px;color:var(--sub)}.st b{font-size:26px;font-weight:600}.st i{font-style:normal;font-size:13px;margin-left:3px}
#views{right:16px;top:16px;padding:8px;display:flex;flex-direction:column;gap:6px;align-items:flex-end}
#views .seg{margin:0;flex-wrap:wrap;justify-content:flex-end}
#views .hint{font-size:11px;color:var(--sub);padding:0 4px;align-self:flex-start;text-align:left}
#stage canvas,#acR canvas{touch-action:none;cursor:grab}
#callout{display:none;max-width:250px;padding:10px 12px;font-size:12px;line-height:1.6;pointer-events:none}
#callout b{display:block;font-size:13px}
#panel{width:360px;flex:none;background:#fff;padding:20px;display:flex;flex-direction:column;gap:14px;overflow:auto}
#panel h2{margin:0;font-size:15px}
#groups{display:flex;flex-direction:column;gap:14px}
#modeTabs{margin:0}#modeTabs button{flex:1;white-space:nowrap;font-size:12.5px;padding:7px 8px}
#scenes{display:flex;flex-direction:column;gap:6px}#scenes .h{font-size:13px;color:#333;margin-bottom:2px}
#scenes .sc{all:unset;box-sizing:border-box;cursor:pointer;display:block;border:1px solid #e3e3e0;border-radius:10px;padding:8px 10px}
#scenes .sc b{display:block;font-size:12.5px}#scenes .sc span{display:block;font-size:11.5px;color:#777;line-height:1.5;margin-top:2px}
#scenes .sc.on{border-color:#111;box-shadow:0 0 0 1px #111}
.inc.safe{border-color:#2f7d4f}.inc.safe .tag{background:#2f7d4f}.inc.issue{border-color:#b7791f}.inc.issue .tag{background:#b7791f}.rk.issue{background:#b7791f}
#scenes .gh{font-size:11.5px;color:#777;margin:6px 0 0}.xbtn{display:flex;gap:12px;flex-wrap:wrap;margin-top:6px}.xbtn .link{font-size:12.5px}.dev{display:none!important}body.devmode .dev{display:inline-block!important}
.sbtns{display:flex;flex-direction:column;gap:8px;margin-top:14px}.sbtns .link{align-self:flex-start;font-size:13px}
#panel .cta{height:44px;font-size:14px;white-space:nowrap;padding:0 16px}#panel .cta.sub{background:#fff;color:#111;border:1px solid #111}
#panel .note,#panelNote{font-size:11.5px;line-height:1.6;margin:0}#panel .link{font-size:13px}
#sceneCmp .cols{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px}
#sceneCmp .col h3{margin:0 0 8px;font-size:14px;color:#666}
#sceneCmp .cfg{display:grid;grid-template-columns:auto 1fr;gap:3px 12px;font-size:12px;color:#666;background:#f5f5f3;border-radius:10px;padding:10px 12px;margin-bottom:10px}#sceneCmp .cfg b{color:#111}#sceneCmp .cfg .chg{background:#fff1b8;border-radius:4px;padding:0 4px}
table.auto{width:100%;border-collapse:collapse;margin-top:14px;font-size:13px}table.auto th{text-align:left;font-size:11.5px;color:#777;font-weight:600;padding:8px 10px;border-bottom:1px solid #e3e3e0}
table.auto td{padding:10px;border-bottom:1px solid #eee;vertical-align:top;line-height:1.6}table.auto i{font-style:normal;display:inline-block;background:#f0f0ee;border-radius:999px;padding:1px 9px;margin:0 4px 4px 0;font-size:12px}table.auto i.me{background:#111;color:#fff}
table.auto tr.arow{cursor:pointer}table.auto tr.arow:hover td{background:#fafaf8}table.auto .tg{color:#999;margin-right:6px}table.auto tr.adet td{padding:14px 10px;background:#fafaf8}table.auto tr.adet .inc{max-width:none;width:100%;box-sizing:border-box;background:#fff}
table.auto .sub{color:#666;font-size:12px}.rk{display:inline-block;font-size:12px;font-weight:700;color:#fff;border-radius:6px;padding:2px 8px;white-space:nowrap}.rk.hit{background:#d93a3a}.rk.near{background:#111}.rk.safe{background:#2f7d4f}
.ahist{margin-top:14px;border-top:1px solid #eee;padding-top:10px}.ahist h4{margin:0 0 6px;font-size:11.5px;color:#777;font-weight:600}
.ahist details{border-bottom:1px solid #f0f0ee;padding:6px 0}.ahist summary{cursor:pointer;display:flex;align-items:center;gap:8px;font-size:12.5px;list-style:none}.ahist summary::-webkit-details-marker{display:none}
.ahist summary b{width:18px;color:#999;font-weight:600}.ahist summary span:last-child{flex:1}.ahist details .inc{margin-top:8px}
#cfgLine b.chg{background:#fff1b8;border-radius:4px;padding:0 4px}
#sceneCmp .sum{background:#111;color:#fff;border-radius:14px;padding:14px 16px;font-size:14px;line-height:1.7;margin-top:12px}
@media(max-width:900px){#sceneCmp .cols{grid-template-columns:1fr}}
.optNote{margin:6px 0 0;font-size:11.5px;line-height:1.6;color:#777}
#runInfo{display:flex;flex-direction:column;gap:14px}
.cfgs{margin:0;background:#f5f5f3;border-radius:10px;padding:12px 14px;display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:10px 16px}
.cfgs div{display:flex;flex-direction:column;gap:1px}.cfgs span{font-size:11.5px;color:#777;line-height:1.4}.cfgs b{font-size:13.5px;color:#111;font-weight:600;line-height:1.45}.cfgs b.chg{background:#fff1b8;border-radius:4px;padding:0 4px;align-self:flex-start}
.inc{border:1px solid #e3e3e0;border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:6px}
.inc.hit{border-color:#d93a3a}
.inc .hd{display:flex;align-items:center;gap:8px;font-size:12px;color:#666}
.inc .tag{font-size:12px;font-weight:700;color:#fff;background:#111;border-radius:6px;padding:2px 8px;margin-left:0}
.inc.hit .tag{background:#d93a3a}
.inc .what{margin:0 0 2px;font-size:13.5px;font-weight:700;line-height:1.55}
.inc h4{margin:6px 0 0;font-size:11.5px;color:#777;font-weight:600}
.inc ul{margin:0;padding-left:18px;font-size:13px;line-height:1.7}
.inc ul.who3{list-style:none;padding:0;display:flex;flex-direction:column;gap:5px}.inc ul.who3 li{line-height:1.55;font-size:12.5px}
.inc ul.who3 b{display:inline-block;font-size:11px;font-weight:600;background:#f0f0ee;border-radius:999px;padding:0 8px;margin-right:6px}.inc ul.who3 b.me{background:#111;color:#fff}
.inc .iss{margin-top:6px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.inc .iss span{width:100%;font-size:11px;font-weight:700;color:#777}.inc .iss a{font-size:12px;color:#097ac1;text-decoration:none;border:1px solid #d6d6d2;border-radius:999px;padding:2px 10px}.inc .iss a:hover{border-color:#111;color:#111}
.inc .open{background:#fff6e5;border-radius:8px;padding:8px 10px;font-size:12.5px;line-height:1.55;margin-top:6px}.inc .open span{display:block;font-size:11px;font-weight:700;color:#8a5a00}
.inc .who{display:flex;flex-wrap:wrap;gap:6px}
.inc .who span{font-size:12px;background:#f0f0ee;border-radius:999px;padding:3px 10px}
.inc .who span.me{background:#111;color:#fff}
#incLog{display:flex;flex-direction:column;gap:6px}
#incLog .li{box-sizing:border-box;display:block;width:100%;cursor:pointer;font-size:12px;color:#555;line-height:1.6;border-top:1px solid #eee;padding:6px 0}
#incLog .li:hover .row1{color:#111}#incLog .li .row1::after{content:' ＋';color:#999}#incLog .li[aria-expanded=true] .row1::after{content:' －'}
#incLog .li .more{display:none;margin-top:8px;white-space:normal;cursor:default;color:#111;font-size:13px}#incLog .li[aria-expanded=true] .more{display:block}
#incLog .more .w{display:block;font-weight:700;color:#111;font-size:12.5px}#incLog .more .h{display:block;margin-top:6px;color:#777;font-size:11px}
#incLog .more .ul span{display:block}#incLog .more .who{display:flex;flex-wrap:wrap;gap:4px;margin-top:2px}#incLog .more .who i{font-style:normal;background:#ecece9;border-radius:999px;padding:1px 8px}#incLog .more .who i.me{background:#111;color:#fff}
#incLog .li b{color:#111;margin-right:6px}#incLog .li b.hit{color:#d93a3a}#incLog .li .inc ul.who3 b{color:#111}#incLog .li .inc ul.who3 b.me{color:#fff}
.grp span{display:block;font-size:13px;color:#333;margin-bottom:6px}
.opts{display:flex;gap:5px;flex-wrap:wrap}
.opts button{border:0;border-radius:7px;background:#f0f0f0;padding:5px 10px;font-size:12px;cursor:pointer;min-height:30px}
.opts button.on{background:#111;color:#fff}.opts button:disabled{opacity:.35;cursor:not-allowed}
#panel.locked .opts button{cursor:default;color:#9a9a9a;background:#f5f5f5}#panel.locked .opts button.on{color:#fff;background:#111}
.cta{display:flex;align-items:center;justify-content:center;gap:8px;height:48px;padding:0 22px;border:0;border-radius:8px;background:#111;color:#fff;font-size:15px;font-weight:500;cursor:pointer;text-decoration:none}
.link{background:none;border:0;padding:0;font-size:14px;text-decoration:underline;cursor:pointer;color:#097ac1}.link:hover,.acc:hover .go{color:#111}
.note{font-size:12px;color:var(--sub);margin:0}
.sheet{min-height:100vh;flex-direction:column;gap:20px;padding:32px clamp(16px,4vw,40px);max-width:1280px;margin:0 auto}
.sheet h2{margin:0;font-size:26px;line-height:1.35}
.eyebrow{margin:0;font-size:13px;color:var(--sub)}
.chg{display:flex;gap:8px;flex-wrap:wrap;align-items:center;font-size:14px}.chg span{background:#f0f0f0;border-radius:8px;padding:5px 10px}.chg span.now{background:#111;color:#fff}
.two{display:grid;grid-template-columns:minmax(0,520px) minmax(0,1fr);gap:40px}
#result .two>div:last-child{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:0 12px;align-content:start}#result .two>div:last-child>p,#result .two>div:last-child>#accMore{grid-column:1/-1}#result #accMore{justify-self:start;margin-top:4px}
.row{background:var(--face);border-radius:12px;padding:14px 20px;display:grid;grid-template-columns:180px repeat(2,minmax(0,1fr));gap:12px;align-items:baseline}
.row .k{font-weight:700}.row .p{font-size:28px;font-weight:600;color:#8a8a8a}.row .n{font-size:28px;font-weight:600}.row small{font-size:13px;font-weight:400;margin-left:3px}.row em{font-style:normal;font-size:13px;margin-left:8px;color:#333}
.acc{display:block;text-align:left;width:100%;border:0;background:var(--face);border-radius:12px;padding:14px 16px;cursor:pointer;margin-bottom:10px}
.acc .w{font-size:13px;color:var(--sub)}.acc .t{display:block;margin:2px 0 4px;line-height:1.5}.acc .go{font-size:13px;font-weight:600;color:#097ac1}
#accident{height:100vh;min-height:620px}
#acL{width:min(560px,48%);flex:none;padding:28px 28px 20px;display:flex;flex-direction:column;gap:14px;overflow:auto}
#facts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}@media(max-width:600px){#facts{grid-template-columns:1fr}}.fact{background:var(--face);border-radius:12px;padding:10px 14px}.fact span{display:block;font-size:12px;color:var(--sub)}.fact b{font-size:24px;font-weight:600}.fact b.fs{font-size:17px;line-height:1.4;display:block}.fact i{font-size:12px}.fact i{font-style:normal;font-size:13px;margin-left:3px}
.ev{display:flex;gap:12px;align-items:baseline;width:100%;text-align:left;border:0;border-radius:10px;background:var(--face);padding:12px 14px;cursor:pointer}
.ev b{min-width:58px;font-weight:600}.ev.on{background:#111;color:#fff}
#acR{flex:1;position:relative;background:#eceef1}
.party{background:var(--face);border-radius:12px;padding:14px 20px;display:grid;grid-template-columns:170px minmax(0,1fr) 300px 64px;gap:18px;align-items:center}
.party.me{background:#ececec}.party .nm{font-weight:700}.party .cl{font-size:13px;color:#333;line-height:1.6}.party .v{font-size:24px;font-weight:600;text-align:right}
input[type=range]{width:100%;accent-color:#111;height:28px}
.bars{display:flex;flex-direction:column;gap:6px}.bar{height:12px;border-radius:6px;background:#111}.bar.all{background:#b9b9b9}
.foot{display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap}
@media(max-width:900px){#play,#accident{height:auto;flex-direction:column}#stage,#acR{height:62vh;flex:none}#panel{width:100%}#acL{width:100%}.two{grid-template-columns:1fr}.party{grid-template-columns:1fr 64px}.party .cl{grid-column:1/-1}.party input{grid-column:1/-1}.row{grid-template-columns:1fr 1fr 1fr}#stats{grid-template-columns:repeat(2,minmax(0,1fr))}}

.ctaP{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:16px 28px;align-items:center;border:1px solid #111;border-radius:14px;padding:20px 24px;margin-top:8px}
.ctaP .who{margin:0 0 4px;font-size:12px;color:#666}.ctaP h3{margin:0;font-size:18px;line-height:1.45}.ctaP p.b{margin:6px 0 0;font-size:13.5px;line-height:1.7;color:#333}
.ctaP a{display:inline-flex;align-items:center;gap:8px;height:46px;padding:0 22px;border-radius:8px;background:#f2600c;color:#fff;text-decoration:none;font-size:14px;font-weight:500;white-space:nowrap}
@media(max-width:700px){.ctaP{grid-template-columns:1fr}}
#bubble{display:none;left:16px;bottom:16px;max-width:340px;padding:14px 34px 14px 16px;font-size:13px;line-height:1.65;border:1px solid #111}
#bubble b{display:block;font-size:13.5px;margin-bottom:4px}#bubble a{display:inline-block;margin-top:8px;color:#097ac1;font-weight:700}#bubble a:hover{color:#111}#bubble .x{position:absolute;right:6px;top:4px;border:0;background:none;font-size:18px;cursor:pointer;color:#777;padding:4px 8px}
#repV{position:fixed;inset:0;z-index:60;background:rgba(0,0,0,.55);display:none;flex-direction:column;align-items:center;padding:24px 16px}#repV .rvBar{width:100%;max-width:900px;background:#fff;border-radius:12px 12px 0 0;padding:12px 16px;display:flex;align-items:center;gap:14px;flex-wrap:wrap;border-bottom:1px solid #e3e3e0}#repV .rvBar .note{flex:1}#repV iframe{width:100%;max-width:900px;flex:1;border:0;background:#fff;border-radius:0 0 12px 12px}
```

### bus_app.js（自動運転バスの版の画面の動き。レポートの CSS だけを使う）

```javascript
<script type="module">
{
const modURL = (id) => URL.createObjectURL(new Blob([document.getElementById(id).textContent], { type: 'text/javascript' }));
const THREE = await import(modURL('three-src'));
const E = await import(modURL('engine-src'));
const $ = (s) => document.querySelector(s);

// ---- 仕組みの項目 ----
const GROUPS = [
  { k: 'dir', scene: true, label: 'バスの来る向き', opts: [['wl', '西から来て左折'], ['er', '東から来て右折（対向車線を横切る）'], ['nl', '脇道から出て左折'], ['nr', '脇道から出て右折（対向車線を横切る）']] },
  { k: 'mode', label: '運行の形', opts: [['l2', 'レベル2・運転士（バスが走り、運転士が見張る。止まったあとの発進は運転士）'], ['l4in', 'レベル4・車内に主任者（バスが判断して走る。車内の主任者が見て、危ないときに止める）'], ['l4r1', 'レベル4・遠隔監視1台（車内は無人。遠隔監視者1人が1台を映像で見る）'], ['l4r3', 'レベル4・遠隔監視3台（車内は無人。遠隔監視者1人が3台を映像で見る）']] },
  { k: 'sensor', label: 'センサー', opts: [['normal', 'ふつう'], ['wide', '死角の少ないもの']] },
  { k: 'speed', label: '交差点での速さ', opts: [[6, '6 km/時'], [10, '10 km/時'], [15, '15 km/時']] },
  { k: 'guide', label: '交差点に誘導員', opts: [[true, '置く'], [false, '置かない']] },
  { k: 'route', label: '交差点の植え込み', opts: [['short', 'そのまま（見通しが悪い）'], ['long', '低く刈ってもらう（道の管理者に頼む）']] },
  { k: 'rest', label: (c) => `${WATCHER(c)}の休憩`, opts: [[true, 'こまめに入れる（見落としが減る・費用が上がる）'], [false, 'なしで回す（費用が下がる・見落としが増える）']] },
  { k: 'maint', label: '点検・保守', opts: [['often', 'こまめに（走る前に不具合を見つけやすい・費用が上がる）'], ['min', '最低限（費用が下がる・不具合が残りやすい）']] },
  { k: 'update', label: 'ソフト更新の確かめ方', opts: [['test', '試走してから入れる（費用が上がる）'], ['direct', 'そのまま入れる（費用が下がる）']] },
  { k: 'commLoss', label: '通信が切れたときのバス（遠隔のとき）', opts: [['stop', 'その場で止まる（メーカーの作り）'], ['go', '走り続ける（メーカーの作り）']] }
];
const NOUN = { dir: 'バスの向きを', mode: '運行の形を', sensor: 'センサーを', speed: '交差点の速さを', guide: '誘導員を', route: '植え込みを', rest: '休憩を', maint: '点検を', update: '更新の確かめ方を', commLoss: '通信が切れたときの作りを' };
// 仕組みを変えたことを、文で言う（「〜したら、事故は減った」）
const changePhrase = (k, v) => ({ dir: `バスの来る向きを「${label('dir', v)}」にした`, mode: `運行の形を「${label('mode', v)}」にした`, sensor: `センサーを${v === 'wide' ? '死角の少ないもの' : 'ふつうのもの'}にした`, speed: `交差点の速さを時速${v}kmにした`,
  guide: v ? '誘導員を置いた' : '誘導員をなくした', route: v === 'long' ? '植え込みを低く刈ってもらった' : '植え込みをそのままにした', rest: v ? '休憩をこまめに入れた' : '休憩なしで回した',
  maint: v === 'often' ? '点検をこまめにした' : '点検を最低限にした', update: v === 'test' ? '更新を試走してから入れた' : '更新をそのまま入れた', commLoss: v === 'stop' ? '通信が切れたら止まる作りにした' : '通信が切れても走り続ける作りにした' })[k];
// 選択肢の言葉は「本文（注釈）」の形。ボタンには本文だけ、注釈はボタンの下に小さく出す
// 設定のまとめ：見出しを上、選んだものを下に。2列に並べる。通信が切れたときの作りは、遠隔のときだけ出す
const SHORT = { route: '植え込み', guide: '誘導員', speed: '交差点の速さ', commLoss: '通信が切れたとき', update: 'ソフト更新', dir: 'バスの向き' };
function cfgSummary(c, other) {
  return G().filter((g) => g.k !== 'commLoss' || c.mode === 'l4r1' || c.mode === 'l4r3').map((g) => `<div><span>${SHORT[g.k] || glabel(g)}</span><b class="${other && (typeof other === 'string' ? other === g.k : other[g.k] !== c[g.k]) ? 'chg' : ''}">${label(g.k, c[g.k])}</b></div>`).join('');
}
const glabel = (g) => (typeof g.label === 'function' ? g.label(cfg) : g.label); // 見出しが、ほかの選択で変わるもの（休憩の対象など）
const splitOpt = (t) => { const m = t.match(/^(.*?)（(.*)）$/); return m ? [m[1], m[2]] : [t, '']; };
const label = (k, v) => splitOpt(GROUPS.find((g) => g.k === k).opts.find((o) => o[0] === v)[1])[0];
let cfg = { ...E.DEFAULTS, dir: E.SCENES[0].route };
const G = () => GROUPS.filter((g) => !g.scene || playKind === 'scene'); // バスの向きは場面のときだけ選ぶ（1年回すときは毎回ばらばら）
let locked = false;
// 場面によっては、前提として決まっている設定がある（例：誘導員の合図の場面は、誘導員がいることが前提）
const sceneReq = () => (playKind === 'scene' ? (E.SCENES.find((x) => x.id === sceneId) || {}).requires || {} : {});
// この場面で選べるバスの向き（場面のもとの向き＋ずらし方を決めてある向き）
const sceneDirs = () => { const sc = E.SCENES.find((x) => x.id === sceneId); return sc ? [sc.route, ...Object.keys(E.SCENE_DIRS[sc.id] || {})] : []; };
function drawPanel() {
  const req = sceneReq(); Object.assign(cfg, req);
  $('#groups').innerHTML = G().map((g) => { const fixed = g.k in req; return `<div class="grp"><span>${glabel(g)}</span><div class="opts">${g.opts.map((o, i) => `<button data-k="${g.k}" data-i="${i}" class="${cfg[g.k] === o[0] ? 'on' : ''}" aria-pressed="${cfg[g.k] === o[0]}" ${(fixed && cfg[g.k] !== o[0]) || (g.k === 'dir' && !sceneDirs().includes(o[0])) ? 'disabled' : ''}>${splitOpt(o[1])[0]}</button>`).join('')}</div>${fixed ? '<p class="optNote">この場面の前提なので、変えられません</p>' : g.k === 'dir' && sceneDirs().length < 4 ? '<p class="optNote">この場面の人は、脇道から出るバスとは交わりません</p>' : (() => { const n = splitOpt(g.opts.find((o) => o[0] === cfg[g.k])[1])[1]; return n ? `<p class="optNote">${n}</p>` : ''; })()}</div>`; }).join('');
  $('#panel').classList.toggle('locked', locked);
  $('#sCost').textContent = E.cost(cfg);
}
$('#groups').addEventListener('click', (e) => {
  const b = e.target.closest('button[data-k]'); if (!b || locked) return;
  const g = GROUPS.find((x) => x.k === b.dataset.k); cfg[g.k] = g.opts[+b.dataset.i][0];
  drawPanel(); scene.setCfg({ ...cfg });
});

// ---- 3D ----
const scene = (() => {
  const host = $('#stage');
  const r = new THREE.WebGLRenderer({ antialias: true });
  r.setPixelRatio(Math.min(devicePixelRatio, 2)); r.shadowMap.enabled = true; r.shadowMap.type = THREE.PCFSoftShadowMap;
  host.prepend(r.domElement);
  const s = new THREE.Scene(); s.background = new THREE.Color('#eceef1');
  const cam = new THREE.PerspectiveCamera(34, 1, 0.8, 400);
  const target = new THREE.Vector3(-1, 0, -4);
  const home = { az: Math.atan2(21, 32), el: Math.atan2(30, Math.hypot(21, 32)), dist: Math.hypot(21, 30, 32) };
  let az = home.az, el = home.el, dist = home.dist, mode = 'orbit';
  function placeCam() {
    if (mode === 'follow') return;
    cam.position.set(target.x + dist * Math.cos(el) * Math.sin(az), target.y + dist * Math.sin(el), target.z + dist * Math.cos(el) * Math.cos(az));
    cam.lookAt(target);
  }
  placeCam();
  s.add(new THREE.HemisphereLight('#ffffff', '#b9b4a8', 1.6));
  const d = new THREE.DirectionalLight('#ffffff', 1.5); d.position.set(-20, 40, 25); d.castShadow = true;
  d.shadow.mapSize.set(2048, 2048); Object.assign(d.shadow.camera, { left: -40, right: 40, top: 40, bottom: -40, near: 1, far: 120 }); s.add(d);
  const M = (c) => new THREE.MeshLambertMaterial({ color: c });
  const box = (w, h, dp, c, x, y, z, cast = false) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, dp), M(c)); m.position.set(x, y + h / 2, z); m.castShadow = cast; m.receiveShadow = true; s.add(m); return m; };
  box(260, 0.1, 260, '#e3e0d8', 0, -0.1, 0);
  box(200, 0.15, 14, '#efe7d4', 0, 0, 0);
  box(12, 0.15, 90, '#efe7d4', 0, 0, -51);
  box(200, 0.16, 7, '#7a7f87', 0, 0, 0);
  box(6, 0.16, 90, '#7a7f87', 0, 0, -48.5);
  for (let x = -96; x < 96; x += 4) if (Math.abs(x) > 5) box(2, 0.17, 0.15, '#f2f2f2', x, 0, 0);
  for (let x = -2.7; x <= 2.8; x += 0.9) box(0.45, 0.18, 2.8, '#ffffff', x, 0, -5.0);
  box(16, 2.6, 9, '#9aa0a8', -15, 0, -13, true); box(13, 2.2, 10, '#a3a8af', 15, 0, -14, true);
  // 手前（南側）の角は、左が平屋の店、右が駐車場（2026-11-20 エイイチの指示。高さ1.2mの塊は建物に見えなかったため）
  // 右の角はカメラ（斜め上）と交差点の間にあるので、高いものを置かず駐車場にする
  box(16, 3.6, 6, '#b3b7bd', -15, 0, 12, true); box(16.4, 0.25, 6.4, '#9ea3aa', -15, 3.6, 12, true); // 平屋の店と屋根のふち
  box(13, 1.9, 0.06, '#3c4652', -15, 0.35, 8.97); box(13, 0.5, 0.06, '#e8e4dc', -15, 2.55, 8.97); // 道に向いたガラスと看板の帯
  box(16, 0.04, 6, '#8d9199', 15, 0.08, 12); // 駐車場の舗装
  for (let i = 0; i <= 6; i++) box(0.12, 0.05, 4.2, '#f2f2f2', 8.6 + i * 2.5, 0.09, 12.6); // 区画の白線
  for (let i = 0; i < 6; i++) box(1.4, 0.18, 0.2, '#c9c6bf', 9.85 + i * 2.5, 0.09, 14.4); // 車止め
  const hedge = new THREE.Group(); for (const h of E.HEDGES) { const m = new THREE.Mesh(new THREE.BoxGeometry(h[1] - h[0], 1.3, h[3] - h[2]), M('#6f9a5a')); m.position.set((h[0] + h[1]) / 2, 0.8, (h[2] + h[3]) / 2); m.castShadow = true; hedge.add(m); } s.add(hedge);
  // バス
  const bus = new THREE.Group();
  const add = (g, w, h, dp, c, x, y, z) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, dp), M(c)); m.position.set(x, y, z); m.castShadow = true; g.add(m); return m; };
  {
    // バスの形（アーチ屋根）。真横から見た輪郭を幅方向に押し出す。前後は同じ形で、端のガラスは屋根の上まで続く
    const Lb = 5.2, Wb = 2.2, yb = 0.06, yt = 2.62, Rt = 1.35, Rb = 0.18, bv = 0.14, white = '#f6f6f4', glass = '#1d242c';
    const prof = (L2, y0, y1, rt, rbm) => { const x = L2 / 2, sh = new THREE.Shape();
      sh.moveTo(-x + rbm, y0); sh.lineTo(x - rbm, y0); sh.quadraticCurveTo(x, y0, x, y0 + rbm); sh.lineTo(x, y1 - rt);
      sh.absarc(x - rt, y1 - rt, rt, 0, Math.PI / 2, false); sh.lineTo(-x + rt, y1); sh.absarc(-x + rt, y1 - rt, rt, Math.PI / 2, Math.PI, false);
      sh.lineTo(-x, y0 + rbm); sh.quadraticCurveTo(-x, y0, -x + rbm, y0); return sh; };
    const ext = (sh, depth, bev, mat, seg = 24) => { const g = new THREE.ExtrudeGeometry(sh, { depth, curveSegments: seg, bevelEnabled: bev > 0, bevelSize: bev, bevelThickness: bev, bevelSegments: 5 }); g.translate(0, 0, -depth / 2); const m = new THREE.Mesh(g, mat); m.castShadow = true; bus.add(m); return m; };
    ext(prof(Lb - 2 * bv, yb + bv, yt - bv, Rt - bv, Rb), Wb - 2 * bv, bv, M(white));
    // 端のガラス：輪郭の端の部分だけを、車体の外へ少し出して作る。幅は車体より狭く、左右の面へは回り込まない
    const glassMat = new THREE.MeshPhongMaterial({ color: glass, specular: '#9aa6b2', shininess: 70 });
    const xe = Lb / 2 + 0.008, cy = yt - Rt, rr2 = Rt + 0.008, xg = 1.45, yw = 0.62, cx = Lb / 2 - Rt;
    for (const sg of [1, -1]) {
      // 縦の面は細かく区切って点を置く（角を丸めるときに、輪郭がなめらかになるように）
      const sh = new THREE.Shape(); sh.moveTo(xg, yw); sh.lineTo(xe, yw); for (let i = 1; i <= 24; i++) sh.lineTo(xe, yw + (cy - yw) * i / 24);
      const aEnd = Math.acos((xg - cx) / rr2); sh.absarc(cx, cy, rr2, 0, aEnd, false); sh.lineTo(xg, yw);
      const gwid = Wb - 2 * bv - 0.02, m = ext(sh, gwid, 0, glassMat, 40); if (sg < 0) m.scale.x = -1;
      // 端から見たガラスの四隅を丸める：ガラスの面に沿った長さ u で、両端に近い点ほど幅を狭める
      const uMax = (cy - yw) + rr2 * aEnd, hw = gwid / 2, rc = 0.32, pos = m.geometry.attributes.position;
      for (let i = 0; i < pos.count; i++) {
        const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i);
        const u = y <= cy + 1e-6 ? y - yw : (cy - yw) + rr2 * Math.atan2(y - cy, x - cx);
        const dEnd = Math.max(0, Math.min(u, uMax - u)); if (dEnd >= rc) continue;
        const lim = hw - rc + Math.sqrt(Math.max(0, rc * rc - (rc - dEnd) ** 2));
        if (Math.abs(z) > lim) pos.setZ(i, Math.sign(z) * lim);
      }
      pos.needsUpdate = true;
      add(bus, 0.02, 0.05, Wb * 0.62, '#e9f4ff', sg * (xe + 0.002), yw - 0.12, 0);
      for (const z of [0.5, -0.5]) add(bus, 0.02, 0.07, 0.22, sg > 0 ? '#ffffff' : '#d9534f', sg * (xe + 0.002), 0.34, z);
    }
    // 側面：外側の上の角を大きく丸めた窓、真ん中の2枚引き戸、足元のネイビーの帯
    // 側面に貼る部品は、層ごとに外へ少しずつ離す（同じ面に重ねるとチラつくため）。layer 0=窓とドア枠、1=ドアの板
    const flat = (sh, c, x, y, z, mx = 1, layer = 0) => { const g = new THREE.ExtrudeGeometry(sh, { depth: 0.02, bevelEnabled: false, curveSegments: 8 }); g.translate(0, 0, -0.01); const mat = M(c); mat.polygonOffset = true; mat.polygonOffsetFactor = -1 - layer * 2; mat.polygonOffsetUnits = -4 - layer * 4; const m = new THREE.Mesh(g, mat); m.position.set(x, y, z + Math.sign(z) * (0.012 + layer * 0.03)); m.scale.x = mx; bus.add(m); return m; };
    const rect = (w, h, q) => { const sh = new THREE.Shape(); sh.moveTo(-w / 2 + q, -h / 2); sh.lineTo(w / 2 - q, -h / 2); sh.quadraticCurveTo(w / 2, -h / 2, w / 2, -h / 2 + q); sh.lineTo(w / 2, h / 2 - q); sh.quadraticCurveTo(w / 2, h / 2, w / 2 - q, h / 2); sh.lineTo(-w / 2 + q, h / 2); sh.quadraticCurveTo(-w / 2, h / 2, -w / 2, h / 2 - q); sh.lineTo(-w / 2, -h / 2 + q); sh.quadraticCurveTo(-w / 2, -h / 2, -w / 2 + q, -h / 2); return sh; };
    const win = (() => { const w = 0.98, h = 1.5, q = 0.12, qo = 0.55, sh = new THREE.Shape(); sh.moveTo(0, 0); sh.lineTo(w - q, 0); sh.quadraticCurveTo(w, 0, w, q); sh.lineTo(w, h - qo); sh.quadraticCurveTo(w, h, w - qo, h); sh.lineTo(q, h); sh.quadraticCurveTo(0, h, 0, h - q); sh.lineTo(0, q); sh.quadraticCurveTo(0, 0, q, 0); return sh; })();
    for (const z of [1, -1]) {
      const zz = z * (Wb / 2 + 0.004);
      flat(win, glass, 0.74, 0.82, zz); flat(win, glass, -0.74, 0.82, zz, -1);
      flat(rect(1.36, 2.1, 0.08), '#dfe2e6', 0, 1.29, zz);
      for (const x of [-0.335, 0.335]) flat(rect(0.62, 2.0, 0.05), '#1f252d', x, 1.3, zz, 1, 1);
      add(bus, Lb - 0.9, 0.16, 0.03, '#1f3a5f', 0, 0.2, z * (Wb / 2 + 0.02));
    }
    for (const [x, z] of [[1.85, 1.0], [1.85, -1.0], [-1.85, 1.0], [-1.85, -1.0]]) { const w = new THREE.Mesh(new THREE.CylinderGeometry(0.32, 0.32, 0.28, 20), M('#262626')); w.rotation.x = Math.PI / 2; w.position.set(x, 0.32, z); bus.add(w); const hub = new THREE.Mesh(new THREE.CylinderGeometry(0.18, 0.18, 0.3, 16), M('#cfd2d6')); hub.rotation.x = Math.PI / 2; hub.position.set(x, 0.32, z); bus.add(hub); }
    // 屋根の LiDAR は真ん中に1つ、小さく
    add(bus, 0.12, 0.05, 0.12, '#8d939b', 0, yt + 0.02, 0); const ld = new THREE.Mesh(new THREE.CylinderGeometry(0.055, 0.06, 0.08, 16), M('#2b2f36')); ld.position.set(0, yt + 0.08, 0); bus.add(ld);
  }
  const blinkOn = new THREE.MeshBasicMaterial({ color: '#ffb020' }), blinkOff = new THREE.MeshLambertMaterial({ color: '#b08a40' });
  // ウインカー：前後の端の角（低い位置）と、側面の前後。左右どちらにも付け、曲がる側だけ光らせる
  const blinkers = [-1, 1].flatMap((side) => [[2.611, 0.5, side * 0.8, 0.02, 0.1, 0.16], [-2.611, 0.5, side * 0.8, 0.02, 0.1, 0.16], [2.25, 0.62, side * 1.106, 0.22, 0.08, 0.012], [-2.25, 0.62, side * 1.106, 0.22, 0.08, 0.012]].map(([x, y, z, w, h, d]) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), blinkOff); m.position.set(x, y, z); m.userData.left = side < 0; bus.add(m); return m; }));
  s.add(bus);
  const person = (c) => { const g = new THREE.Group(); const b = new THREE.Mesh(new THREE.CylinderGeometry(0.26, 0.28, 1.22, 14), M(c)); b.position.y = 0.61; b.castShadow = true; g.add(b); const h = new THREE.Mesh(new THREE.SphereGeometry(0.2, 14, 10), M(c)); h.position.y = 1.46; h.castShadow = true; g.add(h); return g; };
  let vc = cfg; // 描いている回の設定（自動再生では回ごとに変わる）
  const setRoute = (rt) => { hedge.scale.y = rt === 'short' ? 1 : 0.35; hedge.position.y = rt === 'short' ? 0 : -0.25; };
  const guide = person('#1f5fd6'); guide.position.set(-4.6, 0.15, -6.7); s.add(guide);
  const arm = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.9), M('#1f5fd6')); arm.position.set(-4.6, 1.35, -6.2); s.add(arm);
  const pool = [];
  const ring = (c) => { const g = new THREE.Group(); const mat = new THREE.MeshBasicMaterial({ color: c }); const m = new THREE.Mesh(new THREE.TorusGeometry(1.4, 0.08, 8, 48), mat); m.rotation.x = -Math.PI / 2; g.add(m); const pin = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.06, 2.2, 8), mat); pin.position.y = 2.6; g.add(pin); const head = new THREE.Mesh(new THREE.SphereGeometry(0.32, 16, 12), mat); head.position.y = 3.8; g.add(head); g.visible = false; s.add(g); return g; };
  const red = ring('#d93a3a'), black = ring('#111111');
  let cur = host;
  function resize() { const w = cur.clientWidth, h = cur.clientHeight; if (!w || !h) return; r.setSize(w, h, false); cam.aspect = w / h; cam.updateProjectionMatrix(); }
  const ro = new ResizeObserver(resize); ro.observe(host); resize();
  function setFrame(f, opts = {}) {
    const jump = Math.hypot(bus.position.x - f.bus.x, bus.position.z - f.bus.z) > 6;
    bus.position.set(f.bus.x, 0.16, f.bus.z); bus.rotation.y = f.bus.h;
    if (jump && mode === 'follow') snapFollow = true;
    // 左折の合図：交差点の手前から曲がり終わるまで点滅
    // 曲がる合図：曲がる側（左折なら左、右折なら右）だけを、交差点の手前から曲がり終わるまで点滅
    const lit = !!f.bus.blink && (performance.now() % 700) < 380;
    blinkers.forEach((m) => { m.material = lit && (f.bus.blink === 'L') === m.userData.left ? blinkOn : blinkOff; });
    // 人は id ごとに色と背の高さを少しずつ変える（誘導員の青は使わない）。通り過ぎるだけの人は淡い色
    while (pool.length < f.peds.length) { const p = person('#e8b923'); s.add(p); pool.push(p); }
    pool.forEach((p, i) => { const q = f.peds[i]; p.visible = !!q; if (!q) return; p.position.set(q.x, 0.15, q.z);
      const c = q.type === 'ambient' ? '#c4c1ba' : '#e8b923'; // 渡る人は黄色、通り過ぎるだけの人は淡い灰色、誘導員は青 if (p.userData.c !== c) { p.userData.c = c; p.children.forEach((m) => m.material.color.set(c)); }
      const sc = 0.9 + ((q.id * 37) % 5) * 0.05; p.scale.set(1, sc, 1); });
    arm.visible = !!f.guide && vc.guide; guide.visible = vc.guide;
    red.visible = !!opts.red; if (opts.red) red.position.set(opts.red.x, 0.3, opts.red.z);
    black.visible = !!opts.black; if (opts.black) black.position.set(opts.black.x, 0.3, opts.black.z);
  }
  function screenOf(x, z) { const v = new THREE.Vector3(x, 1.5, z).project(cam); return { x: (v.x + 1) / 2 * host.clientWidth, y: (1 - v.y) / 2 * host.clientHeight }; }
  let lastT = performance.now(), followH = 0, snapFollow = true; const lookAt = new THREE.Vector3();
  function loop() {
    const now = performance.now(), dtR = Math.min(0.1, (now - lastT) / 1000); lastT = now;
    if (mode === 'follow') {
      // 向きをなめらかに追い、斜め後ろの少し上から見る
      let dh = bus.rotation.y - followH; dh = Math.atan2(Math.sin(dh), Math.cos(dh));
      const k = snapFollow ? 1 : 1 - Math.exp(-dtR * 3);
      followH += dh * k;
      const dx = Math.cos(followH), dz = -Math.sin(followH);
      const want = new THREE.Vector3(bus.position.x - dx * 14, 8.5, bus.position.z - dz * 14);
      if (snapFollow) cam.position.copy(want); else cam.position.lerp(want, k);
      lookAt.lerp(new THREE.Vector3(bus.position.x + dx * 6, 0.5, bus.position.z + dz * 6), snapFollow ? 1 : k);
      cam.lookAt(lookAt); snapFollow = false;
    }
    r.render(s, cam); requestAnimationFrame(loop);
  }
  loop();
  // 動かす：ドラッグで回す、ホイール・2本指で寄る
  const ptrs = new Map(); let pinch0 = 0;
  const cv = r.domElement;
  cv.addEventListener('pointerdown', (e) => { cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch0 = Math.hypot(a.x - b.x, a.y - b.y); } });
  cv.addEventListener('pointermove', (e) => {
    const p = ptrs.get(e.pointerId); if (!p) return;
    if (ptrs.size === 1) {
      if (mode === 'follow') setView('custom');
      az -= (e.clientX - p.x) * 0.006; el = Math.min(1.55, Math.max(0.12, el + (e.clientY - p.y) * 0.005)); placeCam();
    } else if (ptrs.size === 2) {
      p.x = e.clientX; p.y = e.clientY; const [a, b] = [...ptrs.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y);
      if (pinch0) { dist = Math.min(90, Math.max(8, dist * pinch0 / d)); pinch0 = d; placeCam(); } return;
    }
    p.x = e.clientX; p.y = e.clientY;
  });
  const up = (e) => { ptrs.delete(e.pointerId); pinch0 = 0; };
  cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
  cv.addEventListener('wheel', (e) => { e.preventDefault(); if (mode === 'follow') setView('custom'); dist = Math.min(90, Math.max(8, dist * Math.exp(e.deltaY * 0.0012))); placeCam(); }, { passive: false });
  function setView(v) {
    mode = v === 'follow' ? 'follow' : 'orbit'; if (mode === 'follow') { snapFollow = true; followH = bus.rotation.y; }
    if (v === 'iso') { az = home.az; el = home.el; dist = home.dist; }
    if (v === 'opp') { az = home.az + Math.PI; el = home.el; dist = home.dist; }
    if (v === 'top') { el = 1.55; dist = 52; }
    placeCam();
    document.querySelectorAll('#viewBtns button').forEach((b) => b.classList.toggle('on', b.dataset.v === v));
  }
  return { setView, setFrame, setRoute, setCfg: (c) => { vc = c; setRoute(c.route); }, screenOf, moveTo: (el) => { el.prepend(r.domElement); el.appendChild(document.getElementById('views')); ro.disconnect(); cur = el; ro.observe(el); requestAnimationFrame(resize); }, host };
})();
scene.setFrame({ bus: { ...E.busPose(49), v: 0 }, peds: [], guide: false });
$('#viewBtns').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) scene.setView(b.dataset.v); });

// ---- 1年を回す ----
const runs = []; let year = null, speed = 'day', timer = null, replay = null;
const dateOf = (d) => { const t = new Date(2027, 3, 1 + Math.floor(d * 365 / E.PARAMS.daysPerYear)); return `${t.getMonth() + 1}月${t.getDate()}日`; };
const timeOf = (i) => { const m = 7 * 60 + i * 18; return `${Math.floor(m / 60)}:${String(m % 60).padStart(2, '0')}`; };
$('#speeds').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; speed = b.dataset.s; [...$('#speeds').children].forEach((x) => x.classList.toggle('on', x === b)); if (speed === 'skip') finishFast(); });
$('#run').addEventListener('click', () => (playKind === 'scene' ? startScene() : startYear()));
$('#autoRun').addEventListener('click', startAuto);
$('#incLog').addEventListener('click', (e) => { const b = e.target.closest('.li'); if (!b) return; const open = b.getAttribute('aria-expanded') !== 'true'; b.setAttribute('aria-expanded', String(open)); if (incLog[+b.dataset.i]) incLog[+b.dataset.i].open = open; /* 新しいできごとが来ても、ひらいたものはひらいたまま */ });
$('#stopRun').addEventListener('click', () => { auto = null; stopTimers(); setPlayMode('setup'); });
function setPlayMode(m) {
  if (m !== 'scene') { const bb = document.getElementById('bubble'); if (bb) bb.style.display = 'none'; }
  const running = m === 'run' || m === 'scene';
  if (m === 'setup') { stopTimers(); scene.setCfg({ ...cfg }); }
  locked = running; drawPanel();
  $('#groups').style.display = running ? 'none' : ''; $('#runInfo').style.display = running ? '' : 'none';
  $('#modeTabs').style.display = running ? 'none' : ''; $('#scenes').style.display = running ? 'none' : '';
  if (running) { $('#cfgLine').innerHTML = cfgSummary(cfg); $('#incident').innerHTML = '<p class="note">ひやりや事故が起きると、ここに「何が起きたか・原因・かかわる人」が出ます</p>'; $('#incLog').innerHTML = ''; incLog = []; }
  $('#sceneSpeeds').style.display = m === 'scene' ? 'flex' : 'none';
  $('#intro').style.display = m === 'setup' ? '' : 'none'; $('#clock').style.display = m === 'run' ? 'block' : 'none';
  $('#stats').style.display = m === 'run' ? 'grid' : 'none'; $('#callout').style.display = 'none';
  $('#run').style.display = m === 'setup' ? '' : 'none'; $('#autoRun').style.display = m === 'setup' && playKind === 'scene' ? '' : 'none'; $('#stopRun').style.display = running ? '' : 'none';
  $('#stopRun').textContent = m === 'scene' ? '設定に戻る' : '止めて仕組みを変える'; $('#incLog').style.display = m === 'scene' ? 'none' : '';
  $('#panelTitle').textContent = running ? 'シミュレーション設定' : ''; $('#panelTitle').style.display = running ? '' : 'none'; // 決める画面では、左上の説明が同じことを言っているので出さない
  $('#panelNote').textContent = m === 'run' ? '数字は試作の仮の決まり。予測ではありません' : '数字は試作の仮の決まり。予測ではありません';
}
function stopTimers() { clearTimeout(timer); timer = null; replay = null; }
// ---- 場面を選んで確かめる ----
let playKind = 'scene', sceneId = E.SCENES[0].id, sceneRuns = [], runCounter = 0, sceneRate = 1;
$('#sceneSpeeds').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; sceneRate = +b.dataset.r; [...$('#sceneSpeeds').children].forEach((x) => x.classList.toggle('on', x === b)); if (replay && replay.scene) replay.rate = sceneRate; });
function drawScenes() {
  const btn = (sc) => `<button class="sc ${sc.id === sceneId ? 'on' : ''}" data-id="${sc.id}"><b>${sc.title}</b><span>${sc.note}</span></button>`;
  $('#scenes').innerHTML = playKind === 'scene' ? '<div class="h">場面</div><div class="gh">まわりの人の動き</div>' + E.SCENES.filter((x) => !x.group).map(btn).join('') + '<div class="gh">バスの動作不良</div>' + E.SCENES.filter((x) => x.group === 'C').map(btn).join('') + '<div class="xbtn dev"><button class="link" id="impBtn">書き出した回を読み込んで再生</button></div><input type="file" id="impFile" accept=".json,application/json" hidden>' : '';
}
function setPlayKind(k) {
  playKind = k; [...$('#modeTabs').children].forEach((b) => b.classList.toggle('on', b.dataset.m === k));
  drawScenes(); drawPanel(); $('#autoRun').style.display = k === 'scene' ? '' : 'none';
  $('#run').innerHTML = k === 'scene' ? 'この場面を見る <span aria-hidden="true">→</span>' : 'この仕組みで1年を回す <span aria-hidden="true">→</span>';
  $('#introText').textContent = k === 'scene' ? '右で場面と設定を選んで、その1回を見てください。設定を1つ変えてもう一度見ると、問題が誰に移るかを比べられます。' : '右で仕組みを決めて、1年を回してください。いろいろな場面が混ざって起きます。起きた事故で誰にどれだけ責任があるかを、最後にあなたが考えます。';
}
$('#modeTabs').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) setPlayKind(b.dataset.m); });
$('#scenes').addEventListener('click', (e) => { const b = e.target.closest('.sc'); if (!b) return; sceneId = b.dataset.id; const sc = E.SCENES.find((x) => x.id === sceneId); cfg.dir = sc.route;
  // 動作不良の場面を選んだら、不具合が残る設定から始める（こまめな点検や試走のままだと、走る前に見つかって起きないため）
  if (sc.fault === 'brake' || sc.fault === 'steer') cfg.maint = 'min'; if (sc.fault === 'update') cfg.update = 'direct'; if (sc.fault === 'comm' && cfg.mode !== 'l4r1' && cfg.mode !== 'l4r3') cfg.mode = 'l4r1';
  drawScenes(); drawPanel(); scene.setCfg({ ...cfg }); });
function startScene(imp) {
  auto = null;
  const sc = E.SCENES.find((x) => x.id === sceneId); show('play'); setPlayMode('scene');
  if (imp) { $('#panelTitle').textContent = sc.title; const p = { seed: imp.seed, scene: imp.sceneDef, cfg: { ...imp.cfg }, kind: 'scene', runId: ++runCounter, rate: sceneRate, expect: imp.expect, ver: imp.ver }; playPass(p, 1, (r) => sceneDone(p, r), -1); return; }
  $('#panelTitle').textContent = sc.title;
  $('#incident').innerHTML = '<p class="note">この場面を再生しています</p>';
  const p = { seed: 42, scene: E.sceneFor(sc, cfg.dir, cfg), cfg: { ...cfg }, kind: 'scene', runId: ++runCounter, rate: sceneRate };
  playPass(p, 1, (r) => sceneDone(p, r), -1);
}
// ---- 自動再生：選んだ場面を、設定を1つずつ変えながら次々に再生し、最後に一覧で並べる ----
let auto = null;
function autoVariants() {
  const req = sceneReq(), list = [{ label: 'もとの設定のまま（下の設定）', cfg: { ...cfg }, k: null }];
  for (const g of G()) { if (g.k in req) continue; for (const o of g.opts) if (o[0] !== cfg[g.k] && (g.k !== 'dir' || sceneDirs().includes(o[0]))) list.push({ label: `${SHORT[g.k] || glabel(g)}：${label(g.k, cfg[g.k])} → ${splitOpt(o[1])[0]}`, cfg: { ...cfg, [g.k]: o[0] }, k: g.k }); }
  return list;
}
function startAuto() {
  const sc = E.SCENES.find((x) => x.id === sceneId);
  auto = { sc, list: autoVariants(), i: 0, res: [] };
  show('play'); setPlayMode('scene'); $('#panelTitle').textContent = `${sc.title}（自動再生）`;
  autoNext();
}
function autoNext() {
  const a = auto; if (!a) return;
  if (a.i >= a.list.length) { const done = a; auto = null; openAutoSummary(done); return; }
  const v = a.list[a.i];
  $('#cfgLine').innerHTML = cfgSummary(v.cfg, v.k || undefined);
  $('#incident').innerHTML = `<p class="note" style="font-size:13px;color:#111"><b>${a.i + 1} / ${a.list.length}</b>　${v.label}</p><div id="autoNow"></div>${autoHistory(a)}`;
  const p = { seed: 42, scene: E.sceneFor(a.sc, v.cfg.dir, v.cfg), cfg: v.cfg, kind: 'scene', runId: ++runCounter, rate: sceneRate };
  playPass(p, 1, (r) => {
    if (auto !== a) return;
    const kind = runKind(r), ex = runEx(r, v.cfg, kind);
    a.res.push({ ...v, kind, ex, events: r.events, reasons: kind === 'safe' ? safeReasons(r, v.cfg) : null, seed: 42, scene: E.sceneFor(a.sc, v.cfg.dir, v.cfg) });
    // いまの回の結果を出し、その下にこれまでの回の履歴を並べる
    const cur = kind === 'safe' ? `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span></div><ul>${safeReasons(r, v.cfg).map((x) => `<li>${x}</li>`).join('')}</ul></div>` : incCard(kind, ex, v.label, '');
    $('#incident').innerHTML = `<p class="note" style="font-size:13px;color:#111"><b>${a.i + 1} / ${a.list.length}</b>　${v.label}</p>${cur}${autoHistory(a, true)}`;
    a.i++; timer = setTimeout(autoNext, 1500 / sceneRate);
  }, -1);
}
// 自動再生の履歴：これまでの回を新しい順に。押すと、その回の説明がひらく
function autoHistory(a, skipLast) {
  const list = (skipLast ? a.res.slice(0, -1) : a.res).map((x, i) => ({ x, n: i + 1 })).reverse();
  if (!list.length) return '';
  const badge = (x) => `<span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span>`;
  return `<div class="ahist"><h4>これまでの回</h4>${list.map(({ x, n }) => `<details><summary><b>${n}</b>${badge(x)}<span>${x.label}</span></summary>${x.kind === 'safe' ? `<div class="inc safe"><ul>${x.reasons.map((t) => `<li>${t}</li>`).join('')}</ul></div>` : incCard(x.kind, x.ex, x.label, '')}</details>`).join('')}</div>`;
}
function openAutoSummary(a) {
  const res = (x) => `<span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span>`;
  // 行を押すと、その回の詳しい説明（場面を1回見たときと同じカード）が下にひらく
  const detail = (x) => (x.kind === 'safe' ? `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span>${x.label}</div><h4>止まれた理由</h4><ul>${x.reasons.map((t) => `<li>${t}</li>`).join('')}</ul></div>` : incCard(x.kind, x.ex, x.label, ''));
  const rows = a.res.map((x, i) => `<tr class="arow" data-i="${i}"><td><span class="tg">＋</span>${i === 0 ? '<b>もとの設定のまま</b>' : x.label}</td><td>${res(x)}</td><td>${x.ex ? x.ex.who.map((w) => `<i class="${w.includes('あなた') ? 'me' : ''}">${w}</i>`).join('') : `<span class="sub">${x.reasons[0]}</span>`}</td><td>${x.ex && x.ex.open ? `<span class="sub">${x.ex.open}</span>` : ''}</td></tr><tr class="adet" data-i="${i}" hidden><td colspan="4">${detail(x)}</td></tr>`).join('');
  $('#sceneCmp').innerHTML = `<p class="eyebrow">場面：${a.sc.title}（自動再生）</p><h2>設定を1つずつ変えると、結果と問題はどう変わる？</h2>
    <p class="note">下のもとの設定から1つだけ変えて、同じ場面を${a.res.length}回見た結果です。歩く人の動きは毎回同じです。行を押すと、その回の詳しい説明がひらきます</p>
    <h4 style="margin:14px 0 6px;font-size:12px;color:#777">もとの設定</h4><div class="cfgs">${cfgSummary(a.res[0].cfg)}</div>
    <table class="auto"><thead><tr><th>変えたこと</th><th>結果</th><th>かかわる人（何も起きなければ止まれた理由）</th><th>まだ決まっていないこと</th></tr></thead><tbody>${rows}</tbody></table>
    <div class="xbtn"><button class="cta sub" id="autoRep">この結果のレポートを見る</button><button class="link dev" id="autoCsv">CSV（作る側）</button></div>
    ${ctaPanel()}
    <div class="foot"><button class="link" id="autoBack">← 設定に戻る</button><button class="cta" id="autoAgain">別の場面で自動再生 <span aria-hidden="true">→</span></button></div>`;
  scene.moveTo($('#stage')); show('sceneCmp');
  $('#sceneCmp').querySelector('tbody').addEventListener('click', (e) => { const r = e.target.closest('.arow'); if (!r) return; const d = $('#sceneCmp').querySelector(`.adet[data-i="${r.dataset.i}"]`); d.hidden = !d.hidden; r.querySelector('.tg').textContent = d.hidden ? '＋' : '－'; });
  $('#autoRep').addEventListener('click', () => saveReport(`事故責任レポート_${a.sc.title}_設定を1つずつ変えた結果.html`, `${a.sc.title}：設定を1つずつ変えた結果`, `下のもとの設定から1つだけ変えて、同じ場面を${a.res.length}回見た結果です。歩く人の動きは毎回同じです。`, [`<section><h2>もとの設定</h2><div class="cfgs">${cfgSummary(a.res[0].cfg)}</div></section>`, summaryTable(a.res.map((x, i) => ({ ...x, label: i === 0 ? 'もとの設定のまま' : x.label }))), ...a.res.map((x, i) => runBlock(x, i === 0 ? 'もとの設定のまま' : x.label, i > 0))]));
  $('#autoCsv').addEventListener('click', () => downloadCsv(`事故責任_${a.sc.id}_自動再生.csv`, a.res.map((x, i) => sceneRow(a.sc, x, i === 0 ? 'もとの設定のまま' : x.label))));
  $('#autoBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#autoAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}
function safeReasons(r, c) {
  const k = new Set(r.events.map((e) => e.k)), out = [];
  if (k.has('sensed')) out.push('バスのセンサーが人に気づき、自動ブレーキで止まった');
  if (k.has('opbrake')) out.push(`${WATCHER(c)}が人に気づいて止めた`);
  if (k.has('remote')) out.push('遠隔監視者が映像で気づき、止める指示を出した');
  if (k.has('steerfix')) out.push(`${WATCHER(c)}がハンドルで道へ戻した`);
  if (!out.length) out.push('人が渡り終えるまでバスが待ったか、人がバスに気づいて待った');
  return out;
}
function sceneDone(p, r) {
  const sc = p.scene, c = p.cfg;
  const kind = runKind(r), ex = runEx(r, c, kind);
  if (kind === 'issue') $('#incident').innerHTML = incCard('issue', ex, sc.title, '');
  maybeBubble(kind, ex);
  if (kind === 'safe') $('#incident').innerHTML = `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span>${sc.title}</div><h4>止まれた理由</h4><ul>${safeReasons(r, c).map((x) => `<li>${x}</li>`).join('')}</ul></div>`;
  const prev = sceneRuns.filter((x) => x.sceneId === sc.id).at(-1);
  sceneRuns.push({ sceneId: sc.id, cfg: c, kind, ex, events: r.events, reasons: kind === 'safe' ? safeReasons(r, c) : null, seed: p.seed, scene: sc });
  const btns = `<div class="sbtns"><button class="cta" id="sAgain">設定を変えて見直す <span aria-hidden="true">→</span></button>${prev ? '<button class="cta sub" id="sCmp">前の回と比べる</button>' : ''}<button class="link" id="sReplay">同じ設定でもう一度</button><button class="cta sub" id="sRep">この回のレポートを見る</button><button class="link dev" id="sJson">JSON（作る側）</button>${p.expect ? `<p class="note">${p.expect === kind ? `読み込んだ回：書き出したときと同じ結果（${KIND_LABEL[kind]}）になった` : `読み込んだ回：書き出したときは「${KIND_LABEL[p.expect]}」、今は「${KIND_LABEL[kind]}」（決まりの版 ${p.ver || '不明'} → ${E.RULES_VERSION}）`}</p>` : ''}</div>`;
  $('#incident').insertAdjacentHTML('beforeend', btns);
  $('#sAgain').addEventListener('click', () => { setPlayMode('setup'); });
  $('#sReplay').addEventListener('click', () => startScene());
  $('#sRep').addEventListener('click', () => saveReport(`事故責任レポート_${sc.title}.html`, sc.title, 'あなたが決めた設定で、この場面を1回見た結果です。', [runBlock(sceneRuns.at(-1), 'この回')]));
  $('#sJson').addEventListener('click', () => downloadText(`事故責任_${sc.id}_${Date.now()}.json`, JSON.stringify(passRecord(p, r, kind, ex), null, 1), 'application/json'));
  if (prev) $('#sCmp').addEventListener('click', () => openSceneCompare(prev, sceneRuns.at(-1)));
}
function openSceneCompare(a, b) {
  const sc = E.SCENES.find((x) => x.id === b.sceneId);
  const res = (x) => KIND_LABEL[x.kind];
  const changed = G().filter((g) => a.cfg[g.k] !== b.cfg[g.k]);
  const col = (x, other, title) => `<div class="col"><h3>${title}</h3>
    <div class="cfgs" style="margin-bottom:10px">${cfgSummary(x.cfg, other.cfg)}</div>
    ${x.kind === 'safe' ? `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span></div><h4>止まれた理由</h4><ul>${x.reasons.map((t) => `<li>${t}</li>`).join('')}</ul></div>` : incCard(x.kind, x.ex, sc.title, '')}</div>`;
  const csvRows = [sceneRow(sc, a, 'まえ'), sceneRow(sc, b, 'あと')];
  const wa = new Set(a.ex ? a.ex.who : []), wb = new Set(b.ex ? b.ex.who : []);
  const gone = [...wa].filter((w) => !wb.has(w)), added = [...wb].filter((w) => !wa.has(w));
  const sum = `変えたこと：${changed.length ? changed.map((g) => `${g.label instanceof Function ? g.label(b.cfg) : g.label}を「${label(g.k, b.cfg[g.k])}」に`).join('、') : 'なし'}。<br>結果：${res(a)} → ${res(b)}。` +
    (gone.length ? `<br>問題から外れた：${gone.join('・')}` : '') + (added.length ? `<br>新しく問題になった：${added.join('・')}` : '') + (!gone.length && !added.length ? '<br>かかわる人は変わらなかった' : '');
  $('#sceneCmp').innerHTML = `<p class="eyebrow">場面：${sc.title}</p><h2>設定を変えると、問題はどこへ移る？</h2><div class="sum">${sum}</div><div class="cols">${col(a, b, 'まえ')}${col(b, a, 'あと')}</div>
    <div class="xbtn"><button class="cta sub" id="cmpRep">この比べた結果のレポートを見る</button><button class="link dev" id="cmpCsv">CSV（作る側）</button></div>
    ${ctaPanel()}
    <div class="foot"><button class="link" id="cmpBack">← 設定に戻る</button><button class="cta" id="cmpAgain">続けて、もう1つ変える <span aria-hidden="true">→</span></button></div>`;
  scene.moveTo($('#stage')); show('sceneCmp');
  $('#cmpRep').addEventListener('click', () => saveReport(`事故責任レポート_${sc.title}_比較.html`, `${sc.title}：設定を変えると、問題はどこへ移る？`, '', [`<div class="sum">${sum}</div>`, runBlock(a, 'まえ'), runBlock(b, 'あと')]));
  $('#cmpCsv').addEventListener('click', () => downloadCsv(`事故責任_${sc.id}_比較.csv`, csvRows));
  $('#cmpBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#cmpAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}
// ---- 書き出し・読み込み ----
// 公開したページでは、ダウンロードは claude の downloads を通す（見る人が確かめてから保存される）。使えない所では、ふつうのダウンロード
let dlNs; const dlReady = (async () => { try { dlNs = window.claude && window.claude.use ? await window.claude.use('downloads') : null; } catch { dlNs = null; } })();
async function downloadText(name, text, type) {
  await dlReady;
  if (dlNs) { try { await dlNs.save({ filename: name, data: new Blob([text], { type }) }); } catch (e) { if (e && e.code !== 'declined') alertNote(`書き出せませんでした（${e && e.code || 'unavailable'}）`); } return; }
  const url = URL.createObjectURL(new Blob([text], { type: type + ';charset=utf-8' }));
  const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 2000);
}
function downloadCsv(name, rows) {
  if (!rows.length) return;
  const keys = [...new Set(rows.flatMap((r) => Object.keys(r)))];
  const esc = (v) => { const t = v === undefined || v === null ? '' : String(v); return /[",\n]/.test(t) ? '"' + t.replace(/"/g, '""') + '"' : t; };
  downloadText(name, '﻿' + [keys.map(esc).join(','), ...rows.map((r) => keys.map((k) => esc(r[k])).join(','))].join('\r\n'), 'text/csv'); // 先頭の印は、Excel で文字化けしないため
}
const lines = (arr) => (arr || []).map((x) => `${x.who}：${x.text}`).join(' / ');
const cfgCols = (c, groups) => Object.fromEntries(groups.map((g) => [g.k === 'rest' ? '見張る人の休憩' : g.label, label(g.k, c[g.k])]));
function sceneRow(sc, x, changed) {
  return { 場面: sc.title, 変えたこと: changed, ...cfgCols(x.cfg, G()), 結果: KIND_LABEL[x.kind], 何が起きたか: x.ex ? x.ex.what : '', かかわる人: x.ex ? x.ex.who.join('・') : '', 人の問題: x.ex ? lines(x.ex.people) : '', 企業の問題: x.ex ? lines(x.ex.company) : '', '決まり・行政': x.ex ? lines(x.ex.rules) : '', まだ決まっていないこと: x.ex ? x.ex.open : '', 関連する課題: x.ex && x.ex.issues ? x.ex.issues.map((i) => '#' + i.no + ' ' + i.title).join(' / ') : '', 止まれた理由: x.reasons ? x.reasons.join(' / ') : '', 乱数の種: x.seed ?? 42, 決まりの版: E.RULES_VERSION };
}
function yearRows(y) {
  const items = [...y.accidents.map((a) => ({ ...a, kind: 'hit' })), ...y.nears.map((a) => ({ ...a, kind: 'near' })), ...y.faults.filter((f) => f.kind === 'safe' || f.kind === 'issue').map((a) => ({ ...a, kind: 'fault' }))].sort((a, b) => a.day - b.day || a.pass - b.pass);
  const base = cfgCols(y.cfg, GROUPS.filter((g) => !g.scene));
  return items.map((a) => { const ex = a.kind === 'fault' ? null : explain(a.facts, y.cfg, a.kind);
    return { 日付: dateOf(a.day), 時刻: timeOf(a.pass), 種類: a.kind === 'fault' ? '不具合（事故・ひやりなし）' : KIND_LABEL[a.kind], 不具合: a.fault ? E.FAULT_LABEL[a.fault] : '', 夕方の逆光: a.evening ? 'はい' : '', 何が起きたか: ex ? ex.what : '', かかわる人: ex ? ex.who.join('・') : '', 人の問題: ex ? lines(ex.people) : '', 企業の問題: ex ? lines(ex.company) : '', '決まり・行政': ex ? lines(ex.rules) : '', まだ決まっていないこと: ex ? ex.open : '', 乱数の種: a.seed, ...base, 決まりの版: E.RULES_VERSION }; });
}
// 1回分の記録：条件・乱数の種・決まりの版・結果・出来事・0.5秒ごとの位置。読み込めば同じ1回を再生できる
function passRecord(p, r, kind, ex) {
  const sc = E.SCENES.find((x) => x.id === sceneId) || {};
  return { tool: '事故が起きたら誰の責任？（試作）', rulesVersion: E.RULES_VERSION, exportedAt: new Date().toISOString(), scene: { id: sc.id, title: sc.title, def: p.scene }, cfg: p.cfg, seed: p.seed,
    result: { kind, label: KIND_LABEL[kind], facts: r.facts || r.nearFacts || r.issueFacts || null, explanation: ex, waitSec: r.wait }, events: r.events, frames: r.frames, params: E.PARAMS };
}
$('#scenes').addEventListener('click', (e) => { if (e.target.closest('#impBtn')) $('#impFile').click(); });
$('#scenes').addEventListener('change', async (e) => {
  const inp = e.target.closest('#impFile'); if (!inp || !inp.files[0]) return;
  let d; try { d = JSON.parse(await inp.files[0].text()); } catch { alertNote('読み込めませんでした（JSON の形ではありません）'); return; }
  if (!d || !d.scene || !d.scene.def || !d.cfg || d.seed === undefined) { alertNote('この画面で書き出した回の記録ではありません'); return; }
  if (E.SCENES.some((x) => x.id === d.scene.id)) sceneId = d.scene.id;
  cfg = { ...E.DEFAULTS, ...d.cfg }; drawScenes(); drawPanel(); scene.setCfg({ ...cfg });
  startScene({ seed: d.seed, sceneDef: d.scene.def, cfg: cfg, expect: d.result && d.result.kind, ver: d.rulesVersion });
});
if (location.hash === '#dev') document.body.classList.add('devmode'); // 作る側の書き出し（JSON・CSV・読み込み）は #dev のときだけ出す
function alertNote(t) { $('#panelNote').textContent = t; }
// ---- 見る人が持ち帰るレポート（1つのHTMLファイル。ブラウザで開き、印刷すればPDFにもなる） ----
const escH = (t) => String(t ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
function timeline(events) {
  const ev = (events || []).filter((e) => e.k !== 'route'); if (!ev.length) return '';
  return `<h4>できごとの記録（通過の始まりからの秒数）</h4><table class="tl">${ev.map((e) => `<tr><td>${e.t.toFixed(1)}秒</td><td>${escH(e.text)}</td></tr>`).join('')}</table>`;
}
function runBlock(x, title, showChange) {
  const body = x.kind === 'safe' ? `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span></div><h4>止まれた理由</h4><ul>${x.reasons.map((t) => `<li>${escH(t)}</li>`).join('')}</ul></div>` : incCard(x.kind, x.ex, '', '');
  return `<section><h2>${escH(title)}</h2><h4>選んだ設定</h4><div class="cfgs">${cfgSummary(x.cfg, showChange ? x.k : undefined)}</div>${body}${timeline(x.events)}</section>`;
}
function summaryTable(list) {
  return `<section><h2>結果の一覧</h2><table class="sumt"><tr><th>変えたこと</th><th>結果</th><th>かかわる人</th><th>まだ決まっていないこと</th></tr>${list.map((x) => `<tr><td>${escH(x.label)}</td><td><span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span></td><td>${x.ex ? escH(x.ex.who.join('・')) : escH((x.reasons || [])[0] || '')}</td><td>${x.ex ? escH(x.ex.open) : ''}</td></tr>`).join('')}</table></section>`;
}
function yearBlocks(y, prev) {
  const num = (r) => `<tr><td>${r.accidents.length}件</td><td>${r.near}回</td><td>${r.delay.toFixed(2)}分</td><td>${r.cost}</td><td>${r.faults ? r.faults.length + '回' : ''}</td></tr>`;
  const out = [`<section><h2>数字</h2><table class="sumt"><tr><th>事故</th><th>ひやり</th><th>1便の遅れ（平均）</th><th>運行の費用（いちばん安い仕組みを100）</th><th>バスの不具合</th></tr>${prev ? num(prev).replace('<tr>', '<tr class="prev">') : ''}${num(y)}</table>${prev ? '<p class="note">上の段が前の1年、下の段がこの1年</p>' : ''}<h4>選んだ設定</h4><div class="cfgs">${cfgSummary(y.cfg, prev ? prev.cfg : undefined)}</div></section>`];
  y.accidents.slice(0, 20).forEach((a, i) => {
    const r = E.simulatePass(y.cfg, E.rng(a.seed), { evening: a.evening, record: false, fault: a.fault });
    out.push(runBlock({ kind: 'hit', ex: explain(a.facts, y.cfg, 'hit'), cfg: y.cfg, events: r.events }, `事故 ${i + 1}　${dateOf(a.day)} ${timeOf(a.pass)}${a.evening ? '（夕方の逆光）' : ''}`));
  });
  if (y.accidents.length > 20) out.push(`<p class="note">ほか ${y.accidents.length - 20}件の事故は省いています</p>`);
  return out;
}
const REPORT_CSS = `body{margin:0;background:#fff;color:#111;font:15px/1.7 'Hiragino Sans','Noto Sans JP',sans-serif}main{max-width:860px;margin:0 auto;padding:36px 24px 60px}
h1{font-size:26px;line-height:1.35;margin:4px 0 8px}h2{font-size:18px;margin:0 0 10px;padding-top:10px;border-top:2px solid #111}section{margin:28px 0;break-inside:avoid-page}
.eyebrow,.note{font-size:12.5px;color:#666}h4{margin:14px 0 6px;font-size:12px;color:#777;font-weight:600}
.cfgs{background:#f5f5f3;border-radius:10px;padding:12px 14px;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px 16px}.cfgs div{display:flex;flex-direction:column}.cfgs span{font-size:11.5px;color:#777}.cfgs b{font-size:13.5px}.cfgs b.chg{background:#fff1b8;border-radius:4px;padding:0 4px;align-self:flex-start}
.inc{border:1px solid #e3e3e0;border-radius:12px;padding:12px 16px;margin-top:12px}.inc.hit{border-color:#d93a3a}.inc.issue{border-color:#b7791f}.inc.safe{border-color:#2f7d4f}
.inc .hd{display:flex;gap:8px;align-items:center;font-size:12px;color:#666}.tag,.rk{font-size:12px;font-weight:700;color:#fff;background:#111;border-radius:6px;padding:2px 8px;white-space:nowrap}
.inc.hit .tag,.rk.hit{background:#d93a3a}.inc.issue .tag,.rk.issue{background:#b7791f}.inc.safe .tag,.rk.safe{background:#2f7d4f}.what{font-weight:700;margin:8px 0 0}
ul.who3{list-style:none;padding:0;margin:0}ul.who3 li{margin:4px 0}ul.who3 b{display:inline-block;font-size:11px;background:#f0f0ee;border-radius:999px;padding:0 8px;margin-right:6px}ul.who3 b.me{background:#111;color:#fff}
.open{background:#fff6e5;border-radius:8px;padding:8px 12px;margin-top:10px}.iss{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px}.iss span{width:100%;font-size:11px;font-weight:700;color:#777}.iss a{font-size:12.5px;color:#097ac1;border:1px solid #d6d6d2;border-radius:999px;padding:2px 10px;text-decoration:none}.open span{display:block;font-size:11px;font-weight:700;color:#8a5a00}
table{width:100%;border-collapse:collapse;font-size:13px}td,th{text-align:left;padding:7px 8px;border-bottom:1px solid #eee;vertical-align:top}th{font-size:11.5px;color:#777}.tl td:first-child{width:5.5em;color:#666;white-space:nowrap}tr.prev td{color:#888}
.sum{background:#111;color:#fff;border-radius:12px;padding:14px 16px}.rcta{border:1px solid #111;border-radius:12px;padding:16px 20px}.rcta h2{border:0;padding:0}.rcta a{color:#097ac1;font-weight:700}footer{margin-top:40px;font-size:12px;color:#666;border-top:1px solid #ddd;padding-top:12px}
@media(max-width:600px){.cfgs{grid-template-columns:repeat(2,minmax(0,1fr))}}.pbar{position:sticky;top:0;background:#111;color:#fff;padding:10px 24px;display:flex;gap:14px;align-items:center;font-size:12.5px}.pbar button{font-family:inherit;font-weight:700;font-size:14px;background:#fff;color:#111;border:0;border-radius:8px;padding:10px 16px;cursor:pointer}@media print{main{padding:0}.pbar{display:none}}`;
function saveReport(name, title, lead, blocks) {
  const now = new Date(), d = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`;
  const html = `<!DOCTYPE html><html lang="ja"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escH(title)}｜事故が起きたら誰の責任？</title><style>${REPORT_CSS}</style></head><body><main>
<p class="eyebrow">事故が起きたら誰の責任？（試作）のレポート　${d}</p><h1>${escH(title)}</h1>${lead ? `<p>${escH(lead)}</p>` : ''}
${blocks.join('\n')}
<section class="rcta"><h2>あなたの現場で、同じことを確かめませんか</h2><p>このレポートは、架空の交差点で設定を変えたときに、人・企業・決まりのどこに問題が出るかを確かめたものです。自動運転バスや移動ロボットの導入を進めている方は、あなたの現場の交差点や路線、運行の形、見張る人の体制に合わせて作り直し、導入の前に同じことを確かめられます。</p><p><a href="${MSG_URL}">相談する</a>　${MSG_URL}</p></section>
<footer>実際の事故の流れを参考にした、架空の場面です。数字は試作の仮の決まり（版 ${E.RULES_VERSION}）で出したもので、予測ではありません。法律上の答えではなく、関係しそうな決まりと、まだ決まっていないことを示しています。<br>Pixels to Motors　pixelstomotors.com</footer></main></body></html>`;
  openReport(html);
}
// レポートは、まず画面の上で見せる。保存は見た人が「PDFで保存」を押したときだけ（ブラウザの保存の画面で、置き場所を選べる）
function openReport(html) {
  let v = $('#repV');
  if (!v) {
    v = document.createElement('div'); v.id = 'repV';
    v.innerHTML = `<div class="rvBar"><b>レポート</b><span class="note">保存の画面で、送り先を「PDFに保存」にしてください</span><button class="cta" id="rvPdf">PDFで保存</button><button class="link" id="rvClose">閉じる</button></div><iframe title="レポート"></iframe>`;
    document.body.appendChild(v);
    const close = () => { v.style.display = 'none'; document.body.style.overflow = ''; };
    $('#rvClose').addEventListener('click', close);
    v.addEventListener('click', (e) => { if (e.target === v) close(); });
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && v.style.display === 'flex') close(); });
    // 枠の中からの印刷はブラウザによって動かないため、レポートを新しいタブで単独のページとして開き、そこで保存の画面を出す
    $('#rvPdf').addEventListener('click', () => {
      const page = v.dataset.html.replace('<main>', `<div class="pbar"><button onclick="print()">PDFで保存</button><span>保存の画面で、送り先を「PDFに保存」にしてください。開かないときは、ブラウザのメニューの「印刷」から保存できます。</span></div><main>`).replace('</body>', '<script>addEventListener("load",()=>setTimeout(()=>print(),300))<\/script></body>');
      const url = URL.createObjectURL(new Blob([page], { type: 'text/html;charset=utf-8' }));
      const w = window.open(url, '_blank');
      if (!w) v.querySelector('.note').textContent = '新しいタブを開けませんでした。ポップアップを許可してから、もう一度押してください';
      setTimeout(() => URL.revokeObjectURL(url), 60000);
    });
  }
  v.dataset.html = html;
  v.querySelector('iframe').srcdoc = html.replace('<head>', '<head><base target="_blank">');
  v.style.display = 'flex'; document.body.style.overflow = 'hidden';
}
// ---- 仕事の依頼につなぐ案内（結果を見終えた画面・レポートの末尾・事故のあとの吹き出し） ----
const MSG_URL = 'https://pixelstomotors.com/message';
const ctaPanel = () => `<div class="ctaP"><div><p class="who">自動運転バスや移動ロボットの導入を進めている方へ</p><h3>あなたの現場で、同じことを確かめませんか</h3><p class="b">交差点や路線の形、運行の形、見張る人の体制を、あなたの現場に合わせて作り直せます。設定を変えると、人・企業・決まりのどこに問題が移るかを、導入の前に確かめられます。</p></div><a href="${MSG_URL}" target="_blank" rel="noopener">相談する <span aria-hidden="true">→</span></a></div>`;
let bubbleShown = false;
function maybeBubble(kind, ex) {
  if (bubbleShown || !ex || !ex.open || (kind !== 'hit' && kind !== 'issue')) return;
  bubbleShown = true; const b = $('#bubble'); b.style.display = 'block'; // 1回の訪問で1度だけ
}
$('#bubble .x').addEventListener('click', () => { $('#bubble').style.display = 'none'; });
function startYear() {
  show('play'); setPlayMode('run');
  year = { cfg: { ...cfg }, seed: (runs.length + 1) * 7919, day: 0, pass: 0, accidents: [], nears: [], faults: [], near: 0, waitSum: 0, passes: 0 };
  updateStats(); tick();
}
function simDay() {
  const P = E.PARAMS, y = year; const shows = []; y.today = { day: y.day, acc: 0, near: 0 };
  for (let i = 0; i < P.passesPerDay; i++) {
    const seed = (y.seed * 1000003 + y.day * P.passesPerDay + i) >>> 0, evening = i >= 34 && i < 37;
    const fault = E.drawFault(y.cfg, seed);
    const r = E.simulatePass(y.cfg, E.rng(seed), { evening, fault });
    if (fault) y.faults.push({ day: y.day, pass: i, seed, evening, fault, kind: runKind(r) });
    y.passes++; y.waitSum += r.wait + (y.cfg.route === 'long' ? P.detourSec : 0);
    if (r.hit) { y.today.acc++; const a = { day: y.day, pass: i, seed, evening, fault, facts: r.facts }; y.accidents.push(a); shows.push({ ...a, kind: 'hit' }); }
    else if (r.near) { y.near++; y.today.near++; y.nears.push({ day: y.day, pass: i, seed, evening, fault, facts: r.nearFacts }); if (shows.length < 1) shows.push({ day: y.day, pass: i, seed, evening, fault, kind: 'near' }); }
  }
  y.day++; return shows;
}
function updateStats() {
  $('#sAcc').textContent = year.accidents.length; $('#sNear').textContent = year.near;
  $('#sDelay').textContent = (year.passes ? year.waitSum / year.passes / 60 : 0).toFixed(2); $('#sCost').textContent = E.cost(year.cfg);
  const d = Math.min(year.day, E.PARAMS.daysPerYear - 1);
  $('#date').innerHTML = `${dateOf(d)}<small>1年のうち ${d + 1}日目</small>`;
}
function playPass(p, rate, done, fromT = 0) {
  scene.setCfg(p.cfg || year.cfg); // 誘導員・植え込みを、この回の設定どおりに描く
  const r = E.simulatePass(p.cfg || year.cfg, E.rng(p.seed), { evening: p.evening, record: true, scene: p.scene, fault: p.fault });
  const hitE = r.events.find((e) => e.k === 'hit' || e.k === 'building'); const fr = r.frames;
  let mark = null;
  const curbE = r.nearFacts && r.nearFacts.target === 'curb' ? r.events.find((e) => e.k === 'curb') : null;
  if (curbE) mark = { x: curbE.x, z: curbE.z, t: curbE.t };
  else if (p.kind === 'near' || (p.scene && r.near)) { let best = null; for (const f of fr) { if (f.bus.v <= 1.0) continue; for (const q of f.peds) { if (q.type === 'ambient' || (r.nearFacts && q.id !== r.nearFacts.id)) continue; const dd = Math.hypot(q.x - f.bus.x, q.z - f.bus.z); if (!best || dd < best.d) best = { d: dd, x: q.x, z: q.z, t: f.t }; } } mark = best; }
  const tEnd = hitE ? hitE.t + 1.5 : Math.min(E.PARAMS.passTime, (fr.at(-1) || { t: 0 }).t);
  // fromT < 0：交差点の手前16mあたりから見せる（長い直線は飛ばす）
  if (fromT < 0) { const f0 = fr.find((f) => Math.hypot(f.bus.x, f.bus.z + 4) < 16); fromT = f0 ? f0.t : 0; }
  // 速さは再生の途中でも変えられる（p.rate）。経過時間を毎回足していく
  p.rate = p.rate || rate; let t = fromT, last = performance.now(); replay = p; let lastF = null;
  $('#callout').style.display = 'none'; // 前の回の印を消してから始める
  const step = () => {
    if (replay !== p) return;
    const now = performance.now(); t += (now - last) / 1000 * p.rate; last = now; const f = frameAt(fr, t, r.route); lastF = f || lastF;
    if (f) {
      const opts = {};
      if (hitE && t >= hitE.t && hitE.k === 'building') { opts.red = { x: hitE.x, z: hitE.z }; callout(opts.red, p.scene ? '事故' : `事故　${dateOf(p.day)} ${timeOf(p.pass)}`, '右のパネルに原因'); showIncident('hit', r.facts, p); }
      else if (hitE && t >= hitE.t) { const q = f.peds.reduce((a, b) => (Math.hypot(b.x - f.bus.x, b.z - f.bus.z) < Math.hypot(a.x - f.bus.x, a.z - f.bus.z) ? b : a), f.peds[0] || f.bus); opts.red = q; callout(q, p.scene ? '事故' : `事故　${dateOf(p.day)} ${timeOf(p.pass)}`, '右のパネルに原因'); showIncident('hit', r.facts, p); }
      // ひやりの印は、近づいた瞬間から少しのあいだだけ出す
      if (mark && t >= mark.t && t < mark.t + 2.5) { opts.black = mark; callout(mark, 'ひやり', '右のパネルに原因'); if (r.nearFacts) showIncident('near', r.nearFacts, p); }
      else if (mark && t >= mark.t + 2.5 && !opts.red) $('#callout').style.display = 'none';
      scene.setFrame(f, opts);
    }
    if (t < tEnd) requestAnimationFrame(step);
    else { if (!hitE) { $('#callout').style.display = 'none'; if (lastF) scene.setFrame(lastF, {}); } if (replay === p) replay = null; done && done(r); }
  };
  requestAnimationFrame(step);
}
// 0.5秒ごとの記録の間をつないで、なめらかに動かす
function frameAt(fr, t, route) {
  if (!fr.length) return null;
  const i = Math.max(0, Math.min(fr.length - 1, Math.floor(t / 0.5))), a = fr[i], b = fr[i + 1] || a;
  const k = b === a ? 0 : Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t)));
  const L = (x, y) => x + (y - x) * k;
  let dh = b.bus.h - a.bus.h; dh = Math.atan2(Math.sin(dh), Math.cos(dh));
  const peds = a.peds.map((p) => { const q = b.peds.find((x) => x.id === p.id) || p; return { ...p, x: L(p.x, q.x), z: L(p.z, q.z) }; });
  // バスは、道のりと速さから3次の補間でなめらかにつなぎ、道の形に沿って置く（直線でつなぐと速さが段になって見える）
  if (route && a.bus.s !== undefined && b !== a) {
    const T = b.t - a.t, u = k, h00 = 2 * u ** 3 - 3 * u ** 2 + 1, h10 = u ** 3 - 2 * u ** 2 + u, h01 = -2 * u ** 3 + 3 * u ** 2, h11 = u ** 3 - u ** 2;
    let sv = h00 * a.bus.s + h10 * T * a.bus.v + h01 * b.bus.s + h11 * T * b.bus.v; sv = Math.min(Math.max(sv, Math.min(a.bus.s, b.bus.s)), Math.max(a.bus.s, b.bus.s));
    const ps = E.poseOff(route, sv, L(a.bus.off || 0, b.bus.off || 0)); if (a.bus.off || b.bus.off) ps.h = a.bus.h + dh * k; // 外へふくらんだ分も足す
    return { t, bus: { x: ps.x, z: ps.z, h: ps.h, v: L(a.bus.v, b.bus.v), blink: a.bus.blink }, peds, guide: a.guide || b.guide };
  }
  return { t, bus: { x: L(a.bus.x, b.bus.x), z: L(a.bus.z, b.bus.z), h: a.bus.h + dh * k, v: L(a.bus.v, b.bus.v), blink: a.bus.blink }, peds, guide: a.guide || b.guide };
}
// 走っている間のパネル：起きたことの説明
let incLog = [], incShown = null;
// ひやり・事故の説明カード（いま起きたものも、一覧でひらいたものも同じ見た目）
// 課題地図（pixelstomotors.com/issues）の課題。説明の中身から、関係するものだけを選んでリンクする
const ISSUES = { 4: ['人とロボットの共存安全基準', 'human-robot-coexistence-safety'], 9: ['事故時の責任分界', 'liability-demarcation'], 10: ['暴走・誤動作の検知と停止設計', 'failsafe-stop-design'],
  13: ['学習で動きが変わるロボットの安全の確かめ直し', 'learned-behavior-safety-revalidation'], 15: ['ロボットを扱える人材の不在', 'robot-literate-workforce'], 18: ['公道・公共空間の走行ルール', 'public-space-operation-rules'],
  20: ['自律レベルの定義不在', 'autonomy-level-definition'], 22: ['意図の読み取りやすさ', 'intent-legibility'], 27: ['テレオペレーターという新職種', 'teleoperator-profession'], 29: ['保守・修理のエコシステム不在', 'maintenance-ecosystem'],
  30: ['ロボット前提でない建築・都市', 'robot-unready-built-environment'], 32: ['経年劣化・メンテ不足による事故', 'aging-fleet-maintenance'], 34: ['過信と不信のバランス', 'trust-calibration'], 39: ['通信インフラの遅延・帯域', 'network-latency-bandwidth'] };
function issuesFor(f, c, ex) {
  const n = new Set([9]); const has = (who) => [...ex.people, ...ex.company].some((x) => x.who === who); const txt = ex.causes.join(' ');
  if (f.fault === 'brake' || f.fault === 'steer') { n.add(10); n.add(c.maint === 'min' ? 32 : 29); }
  if (f.fault === 'update') n.add(13);
  if (f.fault === 'comm') { n.add(39); n.add(10); }
  if (c.mode === 'l4r1' || c.mode === 'l4r3') { if (f.tried && f.tried.remote || f.missed || f.fault) n.add(27); }
  if (c.mode !== 'l2' || /任せて見ている/.test(ex.open)) n.add(20);
  if (f.missed || (f.trustGuide && c.guide)) n.add(34);
  if (!c.rest && f.missed) n.add(15);
  if (has('誘導員') || f.pedType === 'diagonal' || f.pedType === 'hesitate') n.add(22);
  if (f.sensorLimit || /死角/.test(txt)) n.add(4);
  if (has('道の管理者') || f.target === 'building' || f.onSidewalk || f.mrmBlock) n.add(30);
  if (f.target === 'ped' || f.mrmBlock) n.add(18);
  return [...n].sort((a, b) => a - b).map((k) => ({ no: k, title: ISSUES[k][0], url: `https://pixelstomotors.com/issues/${ISSUES[k][1]}` }));
}
const KIND_LABEL = { hit: '事故', near: 'ひやり', issue: '事故なし・問題あり', safe: '何も起きなかった' };
// 1回の結果の種類と説明（事故・ひやり・事故はないが不具合の問題・何もなし）
function runKind(r) { return r.hit ? 'hit' : r.near ? 'near' : r.issueFacts ? 'issue' : 'safe'; }
function runEx(r, c, kind) { return kind === 'hit' ? explain(r.facts, c, 'hit') : kind === 'near' ? explain(r.nearFacts, c, 'near') : kind === 'issue' ? explain(r.issueFacts, c, 'issue') : null; }
function incCard(kind, ex, when, note) {
  const sec = (title, arr) => (arr.length ? `<h4>${title}</h4><ul class="who3">${arr.map((x) => `<li><b class="${x.who.includes('あなた') ? 'me' : ''}">${x.who}</b>${x.text}</li>`).join('')}</ul>` : '');
  return `<div class="inc ${kind}"><div class="hd"><span class="tag">${KIND_LABEL[kind]}</span>${when}</div>
    <p class="what">${ex.what}</p>
    ${sec('人の問題', ex.people)}${sec('企業の問題', ex.company)}${sec('決まり・行政', ex.rules)}
    ${ex.open ? `<div class="open"><span>まだ決まっていないこと</span>${ex.open}</div>` : ''}
    ${ex.issues && ex.issues.length ? `<div class="iss"><span>課題地図の関連する課題</span>${ex.issues.map((x) => `<a href="${x.url}" target="_blank" rel="noopener">#${x.no} ${x.title}</a>`).join('')}</div>` : ''}
    ${note ? `<p class="note" style="margin:0">${note}</p>` : ''}</div>`;
}
function collapseIncident() {
  if (!year || !year.today) return;
  const d = year.today, txt = d.acc || d.near ? `${dateOf(d.day)}：事故${d.acc}件・ひやり${d.near}回` : `${dateOf(d.day)}：ひやりも事故もなし`;
  $('#incident').innerHTML = `<p class="note" style="margin:0">${txt}</p>`;
  if (incOpen) { incOpen = false; drawIncLog(); }
}
function showIncident(kind, f, p) {
  const key = p.seed + ':' + kind + ':' + (p.runId || ''); if (incShown === key) return; incShown = key;
  const ex = explain(f, p.cfg || year.cfg, kind);
  // 自動再生のときは、何回目かの行とこれまでの回を消さず、その下の枠にだけ出す（行がついたり消えたりしないように）
  if (p.scene) { const box = auto && document.getElementById('autoNow') ? document.getElementById('autoNow') : $('#incident'); box.innerHTML = incCard(kind, ex, p.scene.title, ''); return; }
  $('#incident').innerHTML = incCard(kind, ex, `${dateOf(p.day)} ${timeOf(p.pass)}`, kind === 'hit' ? '1年が終わったら、この事故で誰にどれだけ責任があるかを考えます' : '');
  incLog.unshift({ kind, t: `${dateOf(p.day)} ${timeOf(p.pass)}`, s: ex.causes[0], ex }); incLog = incLog.slice(0, 8); incOpen = true;
  drawIncLog();
}
// 1日が終わり、そのできごとの再生も終わったら、説明のカードをたたんで「これまで」の一覧に移し、今日のまとめを出す
let incOpen = false;
function drawIncLog() {
  // 一覧の1行を押すと、その場で詳しい説明（何が起きたか・なぜ・かかわる人）をひらく
  $('#incLog').innerHTML = (incOpen ? incLog.slice(1) : incLog).map((x, i) => `<div class="li" role="button" tabindex="0" data-i="${incOpen ? i + 1 : i}" aria-expanded="${!!x.open}"><span class="row1"><b class="${x.kind}">${x.kind === 'hit' ? '事故' : 'ひやり'}</b>${x.t}　${x.s}</span><div class="more">${incCard(x.kind, x.ex, x.t, '')}</div></div>`).join('');
}
function callout(pt, title, text) { const c = $('#callout'); const s = scene.screenOf(pt.x, pt.z); c.style.display = 'block'; c.style.left = Math.min(s.x + 30, scene.host.clientWidth - 270) + 'px'; c.style.top = Math.max(s.y - 80, 90) + 'px'; c.innerHTML = `<b>${title}</b>${text}`; }
function tick() {
  if (!year) return;
  if (year.day >= E.PARAMS.daysPerYear) return endYear();
  const shows = simDay(); updateStats();
  if (!replay || !incOpen) collapseIncident(); // 説明のカードは、そのできごとの再生が終わった次の日にたたむ
  const hit = shows.find((x) => x.kind === 'hit');
  if (!replay) $('#callout').style.display = 'none';
  if (speed === 'skip') { timer = setTimeout(tick, 0); return; }
  if (hit) { playPass(hit, 1, () => { timer = setTimeout(tick, 1200); }); return; }
  if (speed === 'real') { const p = shows[0] || { day: year.day - 1, pass: 0, seed: (year.seed * 1000003 + (year.day - 1) * 40) >>> 0, kind: 'plain' }; playPass(p, 1, () => { timer = setTimeout(tick, 200); }); return; }
  // 1日を1秒：日は進めつづけ、再生はそれとは別に、1回の通過を交差点の先まで最後まで見せる
  if (!replay) {
    const p = shows[0] || { day: year.day - 1, pass: 0, seed: (year.seed * 1000003 + (year.day - 1) * E.PARAMS.passesPerDay) >>> 0, kind: 'plain' };
    playPass(p, 2.5, () => {}, -1);
  }
  timer = setTimeout(tick, 1000);
}
// 結果まで飛ばす：画面が固まらないよう、数日ずつ区切って計算し、そのあいだも日付と数字を進める
function finishFast() {
  if (!year) return; stopTimers(); const y = year;
  const chunk = () => { if (year !== y) return; for (let i = 0; i < 6 && y.day < E.PARAMS.daysPerYear; i++) simDay(); updateStats(); if (y.day < E.PARAMS.daysPerYear) timer = setTimeout(chunk, 0); else endYear(); };
  chunk();
}
function endYear() { stopTimers(); year.delay = year.waitSum / year.passes / 60; year.cost = E.cost(year.cfg); runs.push(year); showResult(); }

// ---- ③ 結果 ----
const views = ['play', 'result', 'accident', 'assign', 'compare', 'sceneCmp'];
function show(v) { views.forEach((x) => $('#' + x).classList.toggle('on', x === v)); window.scrollTo(0, 0); }
function accText(a) {
  const f = a.facts;
  if (f.fault) return `${E.ROUTES[f.route].label}。${E.FAULT_LABEL[f.fault]}。${f.target === 'building' ? '角の建物にぶつかった' : '人と接触'}`; const who = f.startedBy === 'bus' ? 'バスが自分で発進した直後' : '運転士が発進させた直後';
  const ped = f.fromBehindHedge && year.cfg.route === 'short' ? '植え込みの陰から来た歩行者' : (E.PED_LABEL[f.pedType] || '横断歩道に向かってきた歩行者');
  return `${E.ROUTES[f.route].label}。${who}、${ped}と接触`;
}
function showResult() {
  const y = runs.at(-1), prev = runs.at(-2);
  const diffs = prev ? G().filter((g) => prev.cfg[g.k] !== y.cfg[g.k]) : [];
  const head = !prev ? `この仕組みで、1年に事故が${y.accidents.length}件、ひやりが${y.near}回起きた`
    : (diffs.length ? diffs.map((g) => changePhrase(g.k, y.cfg[g.k])).join('、') + 'ら、' : '同じ仕組みのままで、') + `事故は${y.accidents.length < prev.accidents.length ? '減った' : y.accidents.length > prev.accidents.length ? '増えた' : '変わらなかった'}`;
  const rows = [['事故', 'accidents', '件', (r) => r.accidents.length, true], ['ひやり（1m以内）', 'near', '回', (r) => r.near], ['1便の遅れ（平均）', 'delay', '分', (r) => r.delay.toFixed(2)], ['運行の費用（いちばん安い仕組みを100）', 'cost', '', (r) => r.cost]];
  const dif = (a, b) => { const d = +a - +b; return d === 0 ? '同じ' : `${Math.abs(+d.toFixed(2))}${d > 0 ? '増' : '減'}`; };
  $('#result').innerHTML = `
    <p class="eyebrow">1年（営業日300日・1日40便）を回した結果</p>
    <h2>${head}</h2>
    ${prev ? `<div class="chg"><span style="background:none;padding:0;color:var(--sub)">変えたところ</span>${diffs.map((g) => `<span>${glabel(g)}　${label(g.k, prev.cfg[g.k])}</span><span aria-hidden="true" style="background:none;padding:0">→</span><span class="now">${label(g.k, y.cfg[g.k])}</span>`).join('') || '<span>なし（乱数だけが違う）</span>'}</div>` : ''}
    <div class="two">
      <div style="display:flex;flex-direction:column;gap:10px">
        <div class="row" style="background:none;padding:0 20px;font-size:13px;color:var(--sub)"><span></span><span>${prev ? '前の1年' : ''}</span><span>${prev ? '今の1年' : 'この1年'}</span></div>
        ${rows.map(([k, , u, f, red]) => `<div class="row"><span class="k">${k}</span><span class="p">${prev ? f(prev) : ''}<small>${prev ? u : ''}</small></span><span class="n" style="${red ? 'color:var(--red)' : ''}">${f(y)}<small style="color:var(--ink)">${u}</small>${prev ? `<em>${dif(f(y), f(prev))}</em>` : ''}</span></div>`).join('')}
        <p class="note">運行の費用は、安全のためにかけたお金の大きさです。車内に乗る人や遠隔監視者の人件費、死角の少ないセンサー、誘導員、植え込みの手入れの依頼、休憩の交代要員、こまめな点検、更新前の試走が上乗せされます。安全とお金のどちらを取るかも、仕組みを決める人の判断です。<br>数字は試作の仮の決まりで出しています。同じ仕組みでも、歩行者の動きは毎年少しずつ違います</p>
      </div>
      <div>
        <p style="margin:0 0 10px;font-weight:700">この1年の事故　${y.accidents.length}件</p>
        ${y.accidents.map((a, i) => `<button class="acc" data-i="${i}" ${i >= 4 ? 'style="display:none"' : ''}><span class="w">${dateOf(a.day)} ${timeOf(a.pass)}${a.evening ? '（夕方の逆光）' : ''}</span><span class="t">${accText(a)}</span><span class="go">くわしく見て、責任の割合を考える →</span></button>`).join('') || '<p class="note">この1年は事故が起きませんでした。ひやりは起きています</p>'}
        ${y.accidents.length > 4 ? `<button class="link" id="accMore" style="font-size:14px">残りの${y.accidents.length - 4}件も見る</button>` : ''}
      </div>
    </div>
    <div class="xbtn"><button class="cta sub" id="yRep">この1年のレポートを見る</button><button class="link dev" id="yCsv">CSV（作る側）</button><span class="note">不具合 ${y.faults.length}回（うち事故 ${y.faults.filter((x) => x.kind === 'hit').length}件）</span></div>
    ${ctaPanel()}
    <div class="foot"><span></span><button class="cta" id="again">仕組みを変えて、もう1年回す <span aria-hidden="true">→</span></button></div>`;
  show('result');
  $('#yRep').addEventListener('click', () => saveReport(`事故責任レポート_1年_${runs.length}.html`, '1年回した結果', `営業日300日・1日40便を回した結果です。${head}。`, yearBlocks(y, prev)));
  $('#yCsv').addEventListener('click', () => downloadCsv(`事故責任_1年_${runs.length}.csv`, yearRows(y)));
  $('#result').querySelectorAll('.acc').forEach((b) => b.addEventListener('click', () => openAccident(y.accidents[+b.dataset.i])));
  if ($('#accMore')) $('#accMore').addEventListener('click', (e) => { $('#result').querySelectorAll('.acc').forEach((b) => { b.style.display = ''; }); e.target.remove(); });
  $('#again').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---- ④ 事故をひらく ----
let current = null;
let acStageReady = false;
function openAccident(a) {
  const y = runs.at(-1);
  const r = E.simulatePass(y.cfg, E.rng(a.seed), { evening: a.evening, record: true, fault: a.fault });
  const hit = r.events.find((e) => e.k === 'hit' || e.k === 'building'); const t0 = hit.t;
  // 危ないと最初に気づいたのは誰か：ぶつかる前10秒のうち、止める指示を出した最初の記録（バスのセンサー・見張る人・遠隔監視者）
  const AWARE = { sensed: 'バスのセンサー', opbrake: WATCHER(y.cfg), remote: '遠隔監視者' };
  const aware = r.events.filter((e) => AWARE[e.k] && e.t <= hit.t && e.t >= hit.t - 10)[0];
  current = { a, r, y };
  const ev = r.events.filter((e) => e.t >= t0 - 30);
  $('#acL').innerHTML = `
    <p class="eyebrow">${dateOf(a.day)} ${timeOf(a.pass)}　T字路の横断歩道</p>
    <h2 style="margin:0;font-size:26px">事故の30秒</h2>
    <div id="facts">
      <div class="fact"><span>ぶつかったときのバス</span><b>${hit.kmh}</b><i>km/時</i></div>
      <div class="fact"><span>危ないと最初に気づいた</span><b class="fs">${aware ? AWARE[aware.k] : '誰もいない'}</b>${aware ? `<i>${(t0 - aware.t).toFixed(1)}秒前</i>` : ''}</div>
      <div class="fact"><span>ぶつかった相手</span><b class="fs">${a.facts.target === 'building' ? '角の建物' : (E.PED_LABEL[a.facts.pedType] || '歩行者')}</b>${a.facts.target !== 'building' && a.facts.phone ? '<i>スマホを見ていた</i>' : ''}</div>
      ${a.fault ? `<div class="fact"><span>バスの不具合</span><b style="font-size:16px">${E.FAULT_LABEL[a.fault]}</b></div>` : ''}
    </div>
    <div style="display:flex;flex-direction:column;gap:8px" id="evs">
      ${ev.map((e, i) => `<button class="ev" data-t="${e.t}"><b>${e.t - t0 === 0 ? '0秒' : `−${(t0 - e.t).toFixed(1)}秒`}</b><span>${e.text}</span></button>`).join('')}
    </div>
    <p class="note">記録を押すと、その時刻の交差点に切り替わります。実際の事故の流れを参考にした、架空の事故です</p>
    <div class="foot"><button class="link" id="backRes">← 結果に戻る</button><button class="cta" id="toAssign">責任の割合を考える <span aria-hidden="true">→</span></button></div>`;
  show('accident');
  if (!acStageReady) { scene.moveTo($('#acR')); acStageReady = true; } else scene.moveTo($('#acR'));
  const seek = (t) => { const f = r.frames[Math.min(r.frames.length - 1, Math.ceil(t / 0.5))]; scene.setFrame(f, t >= t0 ? { red: { x: hit.x, z: hit.z } } : {}); };
  $('#evs').addEventListener('click', (e) => { const b = e.target.closest('.ev'); if (!b) return; $('#evs').querySelectorAll('.ev').forEach((x) => x.classList.toggle('on', x === b)); seek(+b.dataset.t); });
  const last = $('#evs').lastElementChild; last && last.click();
  $('#backRes').addEventListener('click', () => { scene.moveTo($('#stage')); show('result'); });
  $('#toAssign').addEventListener('click', openAssign);
}

// ---- ⑤ 責任の割合を考える ----
let alloc = null;
// ひやり・事故の原因と、かかわる人を、記録から組み立てる（走っている間のパネルと、責任を配る画面で同じものを使う）
// 運行の形ごとの、見ている人の呼び名
const WATCHER = (c) => ({ l2: '運転士', l4in: '車内の主任者', l4r1: '遠隔監視者', l4r3: '遠隔監視者' })[c.mode] || '運転士';
const IS_L4 = (c) => c.mode !== 'l2';
// ひやり・事故の説明を、人／企業／決まり・行政の3段と「まだ決まっていないこと」に組み立てる
// 決まりは「関係しそうな決まり」の名前だけを示し、法律上の答えは出さない
function explain(f, c, kind) {
  const people = [], company = [], rules = [], opens = [];
  const add = (arr, who, text) => { if (!arr.some((x) => x.text === text && x.who === who)) arr.push({ who, text }); };
  const ped = E.PED_LABEL[f.pedType] || '歩行者', W = WATCHER(c), me = '運行会社（あなた）', mk = 'メーカー';
  const tr = f.tried || {}, R = E.ROUTES[f.route];
  const remoteMode = c.mode === 'l4r1' || c.mode === 'l4r3';
  // ---- バスの動作不良（記録に残った不具合と、それぞれの止める手段が届いたか） ----
  if (f.fault === 'brake') {
    if (f.prevented) { add(company, me, '点検をこまめにしていたので、運行の前に見つけて直せた。その日の朝の2便は運休にした'); add(people, '住民', '朝の便がなくなり、ほかの足を探すことになった'); }
    else {
      if (c.maint === 'min') add(company, me, '点検を最低限にしていて、走る前に見つけられなかった');
      if (tr.pedal) add(people, W, tr.pedal.ok && kind !== 'hit' ? 'エラーに気づいて、足でブレーキを踏んで止めた' : '足でブレーキを踏んだが、間に合わなかった');
      if (tr.estop) add(people, W, kind === 'hit' ? '非常停止を押したが、止まりきる前にぶつかった' : '非常停止を押して止めた');
      if (tr.remote && !tr.remote.ok) { add(people, W, '停止を指示したが、指示は車体に届かなかった'); add(company, mk, '遠隔からの停止の指示も、壊れた装置と同じ道を通る作りだった'); opens.push('遠隔から止める指示に、ふだんと別の道を用意しなくてよいか（基準なし）'); }
      if (c.speed >= 15 && kind !== 'issue') add(company, me, '交差点の速さを時速15kmにしていて、止まるまでの距離が長かった');
    }
    add(company, mk, '自動運転の装置からブレーキの指示を車体に伝える、通信の設定に誤りがあった');
    add(rules, '道路運送車両法', '後付けの自動運転の装置と、もとの車両の点検の範囲が分かれている');
    opens.push('自動運転の装置と車体のどちらの不具合かを、誰が切り分けて責任を負うか');
  }
  if (f.fault === 'steer') {
    if (f.prevented) { add(company, me, '点検をこまめにしていたので、ハンドルの遅れを走る前に見つけて直せた。その日の朝の2便は運休にした'); add(people, '住民', '朝の便がなくなり、ほかの足を探すことになった'); }
    else {
      if (c.maint === 'min') add(company, me, '点検を最低限にしていて、ハンドルの遅れに気づけなかった');
      if (c.mode === 'l2') add(people, W, kind === 'issue' || kind === 'safe' ? 'ふくらみに気づいて、ハンドルで道へ戻した' : 'ハンドルで戻そうとしたが、間に合わなかった');
      if (c.mode === 'l4in') add(people, W, 'ふくらみに気づいて非常停止を押した。車内にハンドルはなく、止めることしかできない');
      if (remoteMode) add(people, W, `映像でふくらみに気づくまでに時間がかかった${c.mode === 'l4r3' ? '（1人で3台を見ていた）' : ''}`);
      if (c.mode === 'l4r3') add(company, me, '遠隔監視者1人に3台を見させていた');
      add(company, mk, f.target === 'ped' ? 'バスは、自分が正しい道を走っていると判断していた。外へふくらんだ先の人には、自動ブレーキがかからなかった' : 'バスは、自分が正しい道を走っていると判断していた');
    }
    add(company, mk, '曲がるときのハンドルの動きが遅れる不具合があった');
    if (c.mode === 'l2') { add(rules, '道路交通法', 'レベル2では運転士がハンドルを持つ。直すのは運転士の義務になる'); opens.push('「自動運転」と呼ばれるバスで、運転士がどこまで直せればよいか'); }
    else opens.push('ハンドルのない車内で、止める手段が非常停止だけでよいか');
  }
  if (f.fault === 'update') {
    if (f.prevented) add(company, me, '更新を試走してから入れたので、止まる位置のずれを見つけて戻せた');
    else {
      if (c.update === 'direct') add(company, me, 'ソフト更新を、試走せずにそのまま入れた');
      if (tr.pedal) add(people, W, '「いつもの所で止まらない」と気づいて、ブレーキを踏んだ');
      else if (c.mode !== 'l2') add(people, W, '止まる位置の変化には気づけなかった（見ているのは周りの人）');
    }
    add(company, mk, '更新で止まる位置が変わることを、運行会社に伝えていなかった');
    add(rules, '道路運送車両法（ソフトウェアの更新）', '更新の中身は国に届け出る。現場の運行会社まで伝わる仕組みはない');
    opens.push('ソフトを更新したあと、直ったこと・変わったことを誰が確かめるか');
  }
  if (f.fault === 'comm') {
    if (!remoteMode) { add(people, W, '車内にいたので、通信が切れても運行は続いた'); opens.push('通信が切れたことを、どこへ知らせる決まりにするか'); }
    else if (c.commLoss === 'stop') {
      add(company, mk, '通信が切れたら、その場で止まる作り');
      if (f.mrmBlock) { add(people, 'ほかの車の運転者', '交差点の中で止まったバスに、道をふさがれた'); add(company, me, '現場に駆けつける人を近くに置いていなかった（動かすまで10分）'); }
      add(rules, '道路交通法（特定自動運行）', '運行できなくなったときは、現場に人を向かわせるなどの措置が決められている');
      opens.push('交差点の中で止まったとき、どれだけ早く現場に人が来るべきか（基準なし）');
    } else {
      add(company, mk, '通信が切れても走り続ける作り。遠くから止められない時間ができた');
      add(company, me, 'この作りのバスで運行していた');
      add(rules, '国の検討会', '通信が切れると止められない作りは、欠陥と見られ得るとされた');
      opens.push('通信が切れたとき、バスがどう動くべきかの基準がない');
    }
  }
  // ---- まわりの人の動き（記録に残った事実だけから） ----
  if (f.target === 'ped' && !f.fault) {
    if (f.state === 'approach') add(people, '歩行者', `交差点に近づくバスの前に、${ped}が車道へ入ってきた`);
    else if (f.startedBy === 'human') {
      if (f.missed) add(people, W, 'この人を見落としたまま、発進させた');
      else if (c.guide && f.trustGuide) { add(people, W, '「誘導員が歩行者を止めてくれる」と読んで、早めに発進させた'); opens.push('誘導員の合図に、運転する側がどこまで頼ってよいか（決まりがない）'); }
      else add(people, W, '発進させたあとに、この人が横断歩道へ入ってきた。発進の判断そのものが問われる');
    } else {
      if (f.hedge && c.route === 'short' && c.sensor === 'normal') add(company, mk, '植え込みの陰が、バスのセンサーの死角になっていた');
      else if (c.sensor === 'normal') add(company, mk, 'バスは、横断歩道に向かってくる人を先読みしないまま、自分で発進した');
      else add(people, ped, 'バスが発進したあとに、この人が横断歩道へ入ってきた');
      if (f.missed) add(people, W, c.mode === 'l4in' ? '車内で見ていたが、この人を見落とした' : '映像でこの人を見落とした');
      if (remoteMode && tr.remote) add(people, W, `映像で気づいて止める指示を出すまでに、時間がかかった${c.mode === 'l4r3' ? '（1人で3台を見ていた）' : ''}`);
    }
    if (f.state !== 'approach' && c.guide && f.guideRaised && !f.guideClear) add(people, '誘導員', '合図が、バスと歩行者のどちらに向けたものか、あいまいだった');
    if (c.mode === 'l4r3' && (f.missed || tr.remote)) add(company, me, '遠隔監視者1人に3台を見させていた');
    if (!c.guide && f.state === 'go') add(company, me, '交差点に誘導員を置いていなかった');
    if (c.speed >= 15 && f.braking) add(company, me, '交差点の速さを時速15kmにしていて、止まりきるまでの距離が長かった');
  }
  if (f.target === 'ped') {
    if (f.onSidewalk) add(people, ped === '歩行者' ? '歩道にいた人' : ped, '歩道に立っていただけで、落ち度はない');
    else {
      if (f.phone) add(people, ped, 'スマホを見ていて、バスに気づくのが遅れた');
      if (f.pedType === 'hurry') add(people, ped, '急いでいて、バスのすぐそばに来るまで止まらなかった');
      if (f.pedType === 'diagonal') add(people, ped, '横断歩道の外を斜めに渡っていた');
      if (f.pedType === 'hesitate') add(people, ped, '端で迷ったあと、急に渡りはじめた');
    }
    if (c.sensor === 'normal' && f.sensorLimit && !f.fault) add(company, me, '死角の少ないセンサーなら、この人にもっと早く気づけた。そのセンサーを入れていなかった');
  }
  if (f.evening && f.target === 'ped') add(company, mk, '夕方の逆光で、センサーの見える距離が短くなっていた');
  if (!c.rest && f.missed) add(company, me, `${W}を休憩なしで働かせていて、見落としやすくなっていた`);
  if (f.hedge && c.route === 'short' && f.target === 'ped' && !f.fault) { add(company, '道の管理者', '高い植え込みが、交差点の見通しを悪くしていた'); add(company, me, '植え込みを刈るよう、道の管理者に頼んでいなかった'); }
  // ---- 決まり・行政（関係しそうな決まりの名前だけ。法律上の答えは出さない） ----
  if (kind !== 'issue') {
    if (c.mode === 'l2') { add(rules, '道路交通法', 'レベル2では運転の主体は運転士。運転士の安全確認の義務が中心になる'); opens.push('システムに任せて見ているだけの運転士に、どこまでの注意を求めるか'); }
    else { add(rules, '道路交通法（特定自動運行）', 'レベル4は公安委員会の許可を受けた運行。運行する会社と主任者に、決められた義務がある'); opens.push('レベル4の事故で、誰が刑事責任を負うか'); }
    if (f.target === 'building') add(rules, '民法（物の損害）', '建物の損害は自賠責では扱わない。運行する会社などへの賠償の請求になる');
    else add(rules, '自動車損害賠償保障法', 'けがをした人への賠償は、運送する会社（運行供用者）が負う、という整理が進んでいる');
  }
  if (company.some((x) => x.who === mk) && !(f.fault === 'comm' && c.commLoss === 'stop')) { add(rules, '製造物責任法', 'センサーやソフトの作りに欠陥があればメーカーが問われ得る'); opens.push('ソフトウェアの欠陥を、製造物の欠陥として問えるか（日本では未整理）'); }
  if (company.some((x) => x.who === '道の管理者')) add(rules, '国家賠償法', '道の管理に問題があれば、道を管理する役所が問われ得る');
  if (c.mode === 'l4r3' && (f.missed || tr.remote) && !f.fault) opens.unshift('遠隔監視者1人が何台まで見てよいか（基準なし）');
  if (people.some((x) => x.who === ped && !f.onSidewalk)) add(rules, '民事の過失', '歩行者の不注意は、賠償の割合を減らす事情として見られることがある');
  if (kind === 'hit') add(rules, '事故の報告', '運行する会社は、事故を警察に報告する。事故を調べる国の仕組みは、権限を強める方向で検討中');
  const what = kind === 'hit' ? (f.target === 'building' ? `${R.label}するバスが、外へふくらんで角の建物にぶつかった（時速${f.kmh}km）` : f.onSidewalk ? `${R.label}するバスが歩道に入り、立っていた人と接触した（時速${f.kmh}km）` : `${R.label}するバスが、${ped}と接触した（時速${f.kmh ?? '?'}km）`)
    : kind === 'near' ? (f.target === 'curb' ? `${R.label}するバスが、縁石に乗り上げて歩道に入った（時速${f.kmh}km）` : `${R.label}するバスに、${ped}が${f.dist < 0.1 ? 'ほとんど触れるほど' : f.dist.toFixed(1) + 'm まで'}近づいた（バスは時速${f.kmh}km）`)
    : f.prevented ? `${E.FAULT_LABEL[f.fault]}。${f.prevented === 'maint' ? '点検' : '試走'}で見つかり、事故は起きなかった`
    : f.mrm ? `通信が切れて、バスがその場で止まった${f.mrmBlock ? '（交差点の中）' : ''}`
    : `${E.FAULT_LABEL[f.fault]}。事故やひやりにはならなかった`;
  const who = [...new Set([...people, ...company].map((x) => x.who))];
  const ex = { what, people, company, rules, open: opens[0] || '', who, causes: [...people, ...company].map((x) => x.text) };
  ex.issues = issuesFor(f, c, ex);
  return ex;
}
function clues() {
  // 責任の割合を考える相手と、その手がかり（説明の3段と同じ記録から作る）
  const { a, y } = current, f = a.facts, c = y.cfg, ex = explain(f, c, 'hit'), W = WATCHER(c);
  const of = (nm, fallback) => { const t = [...ex.people, ...ex.company].filter((x) => x.who === nm || (nm === '歩行者' && x.who === (E.PED_LABEL[f.pedType] || '歩行者'))).map((x) => x.text); return t.length ? t.join('。') : fallback; };
  return [
    { k: 'maker', nm: 'メーカー', cl: of('メーカー', c.sensor === 'wide' ? '死角の少ないセンサーを入れていた' : '目立った問題は記録に残っていない') },
    { k: 'op', nm: '運行会社（あなた）', me: true, cl: of('運行会社（あなた）', '') + '（あなたが決めた：' + [label('mode', c.mode), `時速${c.speed}km`, c.guide ? '誘導員あり' : '誘導員なし', c.route === 'short' ? '植え込みはそのまま' : '植え込みを刈ってもらう', c.rest ? 'こまめに休憩' : '休憩なし'].join('・') + '）' },
    { k: 'driver', nm: W, cl: of(W, c.mode === 'l2' ? '発進させ、運転を見ていた' : '見ていたが、記録に残る見落としはない') },
    { k: 'guide', nm: '誘導員', cl: c.guide ? of('誘導員', '「止まれ」の合図ははっきり出ていた') : 'この1年は置いていない', off: !c.guide },
    { k: 'road', nm: '道の管理者', cl: c.route === 'short' ? of('道の管理者', '交差点の植え込みが高く、見通しを悪くしていた') + '（運行会社から刈るよう頼まれてはいない）' : '頼まれて、植え込みを低く刈っていた' },
    { k: 'ped', nm: '歩行者', cl: of('歩行者', '前を見て歩いていた') },
  ];
}
function openAssign() {
  const ps = clues(); const n = ps.filter((p) => !p.off).length;
  alloc = Object.fromEntries(ps.map((p) => [p.k, p.off ? 0 : Math.round(100 / n)])); fix(ps[0].k);
  const draw = () => ps.map((p) => `<div class="party ${p.me ? 'me' : ''}"><span class="nm">${p.nm}</span><span class="cl">${p.cl}</span><input type="range" min="0" max="100" step="1" value="${alloc[p.k]}" data-k="${p.k}" aria-label="${p.nm}の責任" ${p.off ? 'disabled' : ''}><span class="v"><span id="v-${p.k}">${alloc[p.k]}</span><small style="font-size:13px;font-weight:400">%</small></span></div>`).join('');
  $('#assign').innerHTML = `<p class="eyebrow">${dateOf(current.a.day)} ${timeOf(current.a.pass)}　T字路の横断歩道</p><h2>この事故、誰にどれだけ責任がある？</h2><p class="note">合計がいつも100%になるよう、ほかが自動で動きます</p><div style="display:flex;flex-direction:column;gap:10px" id="parties">${draw()}</div>
  <div class="foot"><button class="link" id="backAc">← 事故の30秒に戻る</button><button class="cta" id="toCompare">決めて、比べる <span aria-hidden="true">→</span></button></div>`;
  show('assign');
  $('#parties').addEventListener('input', (e) => { const k = e.target.dataset.k; alloc[k] = +e.target.value; fix(k); ps.forEach((p) => { $('#v-' + p.k).textContent = alloc[p.k]; $('#parties').querySelector(`input[data-k="${p.k}"]`).value = alloc[p.k]; }); });
  $('#backAc').addEventListener('click', () => show('accident'));
  $('#toCompare').addEventListener('click', () => openCompare(ps));
  function fix(k) {
    const others = ps.filter((p) => p.k !== k && !p.off).map((p) => p.k); const rest = 100 - alloc[k]; const sum = others.reduce((s, x) => s + alloc[x], 0);
    others.forEach((x) => { alloc[x] = sum ? Math.round(alloc[x] / sum * rest) : Math.round(rest / others.length); });
    const drift = 100 - Object.values(alloc).reduce((s, v) => s + v, 0); if (others[0]) alloc[others[0]] += drift;
  }
}

// ---- ⑥ 比べる ----
function openCompare(ps) {
  const top = ps.reduce((m, p) => (alloc[p.k] > alloc[m.k] ? p : m), ps[0]);
  $('#compare').innerHTML = `<p class="eyebrow">あなたの考えた割合</p><h2>あなたは「${top.nm}」の責任を一番重く見た</h2>
  <div style="display:flex;flex-direction:column;gap:10px">${ps.map((p) => `<div class="row" style="grid-template-columns:180px minmax(0,1fr) 90px"><span class="k">${p.nm}</span><div class="bars"><div class="bar" style="width:${alloc[p.k]}%"></div></div><span class="n" style="font-size:24px;text-align:right">${alloc[p.k]}<small>%</small></span></div>`).join('')}</div>
  <p class="note">ほかの人の割合と並べる部分は、答えを集める仕組みができてから入ります（試作 v0 では答えを送りません）。法律上の正解を示すものではありません</p>
  <div class="foot"><button class="link" id="otherAc">ほかの事故をひらく</button><button class="cta" id="again2">仕組みを変えて、もう1年回す <span aria-hidden="true">→</span></button></div>`;
  show('compare');
  $('#otherAc').addEventListener('click', () => { scene.moveTo($('#stage')); show('result'); });
  $('#again2').addEventListener('click', () => { scene.moveTo($('#stage')); show('play'); setPlayMode('setup'); });
}
drawPanel(); setPlayMode('setup'); setPlayKind('scene');
window.__ready = true;
}
</script>
<script>
// 「事故が起きたら誰の責任？」（/sim/av-accident-responsibility）の使われ方の記録（2026-11-20。配膳ロボットのブラウザ版の記録をそのまま写した）。
// このページはサイトの共通の型（Base.astro）を通らないため、サイトの記録（src/components/SiteMeasure.astro）が入っていなかった。
// SiteMeasure と同じ形で /api/ev に送る（数え方・数える道具は同じ）。送るもの・送らないもの・送らない場合も SiteMeasure と同じ:
// - ?p2m-notrack=1 を付けて開いたブラウザ・「トラッキングしないで」の設定のブラウザでは送らない
// - 入力した内容・IP アドレス・ブラウザの種類・Cookie は送らない。番号はこの1回の表示のためだけに作る
// このページで押したものは、場所の名前を sim にする（worker/index.js の EV_AREAS にある）。
// 何を触ったかが分かるように、ボタンは「btn:グループ:文字」、店の選択は「sel:store=p1」、時間の棒は「sel:seek」と残す。
// SiteMeasure を直したときは、ここも合わせて直す。
(() => {
  const OPT = 'p2m-notrack';
  let off = false;
  try {
    const q = new URLSearchParams(location.search).get(OPT);
    if (q === '1') { localStorage.setItem(OPT, '1'); off = true; }
    if (q === '0') localStorage.removeItem(OPT);
    if (localStorage.getItem(OPT) === '1') off = true;
  } catch { /* 覚えられない環境では、その表示の判定だけ */ }
  if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl === true) off = true;
  if (off) return;

  const AUTO_UA = /headless|lighthouse|bot\/|bot;|\bbot\b|crawl|spider|slurp|preview|phantom|puppeteer|playwright|selenium/i;
  const newId = () => { try { return crypto.randomUUID().replace(/-/g, '').slice(0, 12); } catch { return Math.random().toString(36).slice(2, 14); } };
  const origin = () => {
    try {
      if (!document.referrer) return { f: '', r: '' };
      const u = new URL(document.referrer);
      if (u.host === location.host) return { f: u.pathname.slice(0, 160), r: '' };
      return { f: '', r: u.hostname.slice(0, 80) };
    } catch { return { f: '', r: '' }; }
  };
  const utm = () => {
    try { const v = (new URLSearchParams(location.search).get('utm_source') || '').toLowerCase(); return /^[a-z0-9._-]{1,40}$/.test(v) ? v : ''; } catch { return ''; }
  };
  const fresh = (from) => {
    const o = origin();
    return {
      v: newId(), n: 0, p: location.pathname.slice(0, 160), f: from ?? o.f, r: from ? '' : o.r, us: from ? '' : utm(),
      w: window.innerWidth < 600 ? 'sp' : 'pc', s: 100, t: 0, c: [],
      d: 0, g: 0, cp: 0, vp: 0, fs: 0, fx: 0, fv: 0,
      u: 0, wd: navigator.webdriver ? 1 : 0, hl: AUTO_UA.test(navigator.userAgent || '') ? 1 : 0,
    };
  };
  let st = fresh();
  let dirty = true;
  let visibleSince = document.hidden ? 0 : Date.now();
  const touched = () => { if (!st.u) { st.u = 1; dirty = true; } };
  for (const ev of ['pointermove', 'pointerdown', 'touchstart', 'wheel', 'keydown']) document.addEventListener(ev, touched, { capture: true, passive: true });

  // 同じものを続けて押しても1件にする（記録は8件まで）
  const add = (target) => {
    target = target.slice(0, 100);
    const last = st.c[st.c.length - 1];
    if (last && last[0] === target) return;
    if (st.c.length < 8) { st.c.push([target, 'sim']); dirty = true; }
  };
  const textOf = (el) => (el.getAttribute('aria-label') || el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 24);

  document.addEventListener('click', (e) => {
    try {
      const el = e.target;
      if (!(el instanceof Element)) return;
      const link = el.closest('a[href]');
      if (link) {
        let target = '';
        try { const u = new URL(link.href, location.href); target = u.host !== location.host ? u.hostname : u.pathname + (u.search.includes('topic=') ? u.search : ''); } catch { target = '(読めないリンク)'; }
        add(target);
        return;
      }
      const btn = el.closest('button,[role=button],summary');
      if (btn) {
        const group = btn.parentElement && btn.parentElement.id ? btn.parentElement.id + ':' : '';
        add('btn:' + group + (btn.dataset.view || btn.id || textOf(btn) || btn.tagName.toLowerCase()));
      }
    } catch { /* 数え損ねても動きには影響させない */ }
  }, { capture: true, passive: true });
  document.addEventListener('change', (e) => {
    try {
      const el = e.target;
      if (!(el instanceof HTMLSelectElement || el instanceof HTMLInputElement)) return;
      add(el.type === 'range' ? 'sel:' + (el.id || 'range') : 'sel:' + (el.id || el.name || 'select') + '=' + String(el.value).slice(0, 20));
    } catch { /* 同上 */ }
  }, { capture: true, passive: true });

  const send = () => {
    if (visibleSince) { st.t += Math.round((Date.now() - visibleSince) / 1000); visibleSince = 0; }
    st.t = Math.min(st.t, 7200);
    if (!dirty) return;
    const body = JSON.stringify(st);
    try {
      if (!navigator.sendBeacon || !navigator.sendBeacon('/api/ev', new Blob([body], { type: 'text/plain' }))) {
        fetch('/api/ev', { method: 'POST', body, keepalive: true }).catch(() => {});
      }
    } catch { /* 送れなくても動きには影響させない */ }
    st.n++; dirty = false;
  };
  document.addEventListener('visibilitychange', () => { if (document.hidden) send(); else visibleSince = Date.now(); });
  window.addEventListener('pagehide', send);
  window.addEventListener('pageshow', (e) => { if (e.persisted) { st = fresh('(戻る)'); visibleSince = Date.now(); dirty = true; } });
})();
</script>
</body>
</html>
```

### assemble.py（画面の部品をつないで app2.html を作る）

```python
h=open('app2_head.html').read(); s=open('app2_main.js').read(); b=open('bus_app.js').read()
i=b.index('const REPORT_CSS = `'); j=b.index('`;',i)+2
rc=b[i:j].replace('.what{font-weight:700;margin:8px 0 0}','.what{font-weight:700;margin:8px 0 0}.facts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;margin-top:8px}.facts.f4{grid-template-columns:repeat(4,minmax(0,1fr))}.fact{background:#f5f5f3;border-radius:10px;padding:8px 10px}.fact span{display:block;font-size:11px;color:#777;line-height:1.4}.fact b{font-size:20px}.fact i{font-style:normal;font-size:12px;margin-left:2px}').replace('.cfgs span{font-size:11.5px;color:#777}','.cfgs span{font-size:11.5px;color:#777;white-space:nowrap}')
open('app2.html','w').write(h.replace('/*BUSCSS*/',open('bus.css').read())+s.replace('/*REPORTCSS*/',rc).replace('/*VIEW3D*/',open('view3d.js').read()))
```

### build2.py（three.js と計算を中に入れて、1つの HTML にする）

```python
s=open('app2.html').read()
s=s.replace('/*THREE*/',open('three.txt').read()).replace('/*ENGINE*/',open('engine.mjs').read())
open('delivery_sim_v0.html','w').write(s); print(len(s))
```

### fix_short.py（足した10場面の設定の短い見出しを足した置き換え）

```python
# 足した10場面の設定の短い見出しを足す（記事化の前に画面を通して、undefined が出ていたため）
p='app2_main.js'; s=open(p).read()
old="rescue: '駆け付ける人' };"
new="rescue: '駆け付ける人', pass: '追いついたとき', gap: '前の人との間', traffic: '車の多さ', time: '走らせる時間', stop: '人に近づく距離', waitpos: '止まる場所', stopAt: '止まる場所', sound: '近づく人への知らせ', wait: '受け取りを待つ', face: '顔の表示', resp: '囲まれたとき', body: '車体の重さ', sensor: 'センサー', approach: '人と動物が来たら', rear: '後ろの見張り', brake: '止まり方', bike: '自転車の走り方', map: '地図の見直し', way: '通れないとき', env: '天気と時間', launch: '出発のさせ方', cap: 'たまる台数', waitAt: '待たせる場所', cross: '車が来ているとき', insurance: '賠償責任保険', record: '記録を残す日数' };"
assert old in s; s=s.replace(old,new,1)
# 表にない設定は、設定の名前から（ ）の前までを見出しにする
s=s.replace("<span>${SHORT[g.k]}</span>","<span>${SHORT[g.k] || g.label.replace(/（.*$/, '')}</span>",1)
open(p,'w').write(s)
```

### 直す前の SHORT と cfgSummary（app2_main.js の一部）

```javascript
const SHORT = { yield: 'すれ違うときの動き', detect: '人に気づく距離', speed: '歩道での速さ', signal: '寄る側の合図', ratio: '1人が見る台数', order: '助けの順番', mrm: '待つ間のロボット', route: '踏切を通る道', voice: '動けないときの機体', push: '押して動かせるか', rescue: '駆け付ける人' };
function cfgSummary(sc, c, other) {
  return sc.groups.map((g) => `<div><span>${SHORT[g.k]}</span><b class="${other && (typeof other === 'string' ? other === g.k : other[g.k] !== c[g.k]) ? 'chg' : ''}">${label(sc, g.k, c[g.k])}</b></div>`).join('');
}
```

### 直したあとの SHORT と cfgSummary（app2_main.js の一部）

```javascript
const SHORT = { yield: 'すれ違うときの動き', detect: '人に気づく距離', speed: '歩道での速さ', signal: '寄る側の合図', ratio: '1人が見る台数', order: '助けの順番', mrm: '待つ間のロボット', route: '踏切を通る道', voice: '動けないときの機体', push: '押して動かせるか', rescue: '駆け付ける人', pass: '追いついたとき', gap: '前の人との間', traffic: '車の多さ', time: '走らせる時間', stop: '人に近づく距離', waitpos: '止まる場所', stopAt: '止まる場所', sound: '近づく人への知らせ', wait: '受け取りを待つ', face: '顔の表示', resp: '囲まれたとき', body: '車体の重さ', sensor: 'センサー', approach: '人と動物が来たら', rear: '後ろの見張り', brake: '止まり方', bike: '自転車の走り方', map: '地図の見直し', way: '通れないとき', env: '天気と時間', launch: '出発のさせ方', cap: 'たまる台数', waitAt: '待たせる場所', cross: '車が来ているとき', insurance: '賠償責任保険', record: '記録を残す日数' };
function cfgSummary(sc, c, other) {
  return sc.groups.map((g) => `<div><span>${SHORT[g.k] || g.label.replace(/（.*$/, '')}</span><b class="${other && (typeof other === 'string' ? other === g.k : other[g.k] !== c[g.k]) ? 'chg' : ''}">${label(sc, g.k, c[g.k])}</b></div>`).join('');
}
```

### all.mjs（13場面の設定の組み合わせを全部回して、結果を出す）

```javascript
import * as E from './engine.mjs';
for (const sc of E.SCENES) {
  const keys = sc.groups.map(g=>g.k);
  const combos = [{}];
  for (const g of sc.groups) { const n=[]; for (const c of combos) for (const o of g.opts) n.push({...c,[g.k]:o[0]}); combos.splice(0,combos.length,...n); }
  console.log('== '+sc.id);
  for (const c of combos) { const r = E.run(sc.id,c); console.log(keys.map(k=>c[k]).join(' / ').padEnd(30), r.outcome.label.padEnd(10), r.facts.map(f=>f.k.slice(0,6)+':'+f.v).join(' '), 'T='+r.frames.at(-1).t); }
}
```

### all.mjs の出力（設定 / 結果 / 数字の欄 / 終わりの時刻）

```text
== wheelchair
dodge / 3 / 6 / false          事故         車いすの人が:0 ロボットが止:0 ロボットの配:5 T=21
dodge / 3 / 6 / true           事故なし・問題あり  車いすの人が:42 ロボットが止:0 ロボットの配:64 T=88.8
dodge / 3 / 4 / false          ひやり        車いすの人が:6 ロボットが止:1 ロボットの配:12 T=50
dodge / 3 / 4 / true           何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:6 T=43.5
dodge / 8 / 6 / false          ひやり        車いすの人が:11 ロボットが止:3 ロボットの配:36 T=60.6
dodge / 8 / 6 / true           事故なし・問題あり  車いすの人が:42 ロボットが止:0 ロボットの配:64 T=88.8
dodge / 8 / 4 / false          ひやり        車いすの人が:8 ロボットが止:3 ロボットの配:18 T=55.2
dodge / 8 / 4 / true           何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:6 T=44.1
stop / 3 / 6 / false           事故なし・問題あり  車いすの人が:44 ロボットが止:0 ロボットの配:65 T=90.3
stop / 3 / 6 / true            事故なし・問題あり  車いすの人が:42 ロボットが止:0 ロボットの配:63 T=88.4
stop / 3 / 4 / false           何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:8 T=45.6
stop / 3 / 4 / true            何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:8 T=45.6
stop / 8 / 6 / false           何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:22 T=47.4
stop / 8 / 6 / true            何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:22 T=47.4
stop / 8 / 4 / false           何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:16 T=53.7
stop / 8 / 4 / true            何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:16 T=53.7
back / 3 / 6 / false           何も起きなかった   車いすの人が:10 ロボットが止:0 ロボットの配:41 T=65.9
back / 3 / 6 / true            何も起きなかった   車いすの人が:2 ロボットが止:0 ロボットの配:34 T=59.3
back / 3 / 4 / false           何も起きなかった   車いすの人が:8 ロボットが止:0 ロボットの配:31 T=69
back / 3 / 4 / true            何も起きなかった   車いすの人が:1 ロボットが止:0 ロボットの配:25 T=62.6
back / 8 / 6 / false           何も起きなかった   車いすの人が:2 ロボットが止:0 ロボットの配:34 T=59
back / 8 / 6 / true            何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:31 T=56.5
back / 8 / 4 / false           何も起きなかった   車いすの人が:1 ロボットが止:0 ロボットの配:24 T=62
back / 8 / 4 / true            何も起きなかった   車いすの人が:0 ロボットが止:0 ロボットの配:23 T=60.7
== sidebyside
follow / 1 / few               ひやり        追いついたと:1 ロボットの配:15 いちばん近づ:0.3 T=38.8
follow / 1 / many              ひやり        追いついたと:1 ロボットの配:15 いちばん近づ:0.3 T=38.8
follow / 3 / few               何も起きなかった   追いついたと:3 ロボットの配:15 いちばん近づ:2.3 T=35.8
follow / 3 / many              何も起きなかった   追いついたと:3 ロボットの配:15 いちばん近づ:2.3 T=35.8
ask / 1 / few                  事故なし・問題あり  追いついたと:1 ロボットの配:4 いちばん近づ:0.3 T=23.7
ask / 1 / many                 ひやり        追いついたと:1 ロボットの配:4 いちばん近づ:0.3 T=24
ask / 3 / few                  事故なし・問題あり  追いついたと:3 ロボットの配:4 いちばん近づ:0.3 T=22.4
ask / 3 / many                 ひやり        追いついたと:3 ロボットの配:4 いちばん近づ:0.3 T=22.7
road / 1 / few                 事故なし・問題あり  追いついたと:1 ロボットの配:0 いちばん近づ:1 T=24.1
road / 1 / many                事故         追いついたと:1 ロボットの配:0 いちばん近づ:0 T=17.3
road / 3 / few                 事故なし・問題あり  追いついたと:3 ロボットの配:0 いちばん近づ:1 T=21.1
road / 3 / many                事故         追いついたと:3 ロボットの配:0 いちばん近づ:0 T=14.3
== crowd
run / 0.5 / center             ひやり        ロボットが止:0 子どもとのい:0.1 配達の遅れ:23 T=55.1
run / 0.5 / edge               ひやり        ロボットが止:0 子どもとのい:0.1 配達の遅れ:23 T=55.1
run / 1.5 / center             事故なし・問題あり  ロボットが止:20 子どもとのい:0.3 配達の遅れ:22 T=55.9
run / 1.5 / edge               何も起きなかった   ロボットが止:20 子どもとのい:0.4 配達の遅れ:22 T=55.2
avoid / 0.5 / center           何も起きなかった   ロボットが止:0 子どもとのい:9 配達の遅れ:15 T=55.2
avoid / 0.5 / edge             何も起きなかった   ロボットが止:0 子どもとのい:9 配達の遅れ:15 T=55.2
avoid / 1.5 / center           何も起きなかった   ロボットが止:0 子どもとのい:9 配達の遅れ:15 T=55.2
avoid / 1.5 / edge             何も起きなかった   ロボットが止:0 子どもとのい:9 配達の遅れ:15 T=55.2
== cane
door / none / 15               何も起きなかった   店の前で止ま:24 点字ブロック:24 白い杖の人が:29 T=49.9
door / none / 60               ひやり        店の前で止ま:69 点字ブロック:69 白い杖の人が:29 T=65.9
door / sound / 15              何も起きなかった   店の前で止ま:24 点字ブロック:24 白い杖の人が:29 T=49.9
door / sound / 60              事故なし・問題あり  店の前で止ま:69 点字ブロック:69 白い杖の人が:29 T=56.3
avoid / none / 15              何も起きなかった   店の前で止ま:24 点字ブロック:0 白い杖の人が:29 T=49.4
avoid / none / 60              何も起きなかった   店の前で止ま:69 点字ブロック:0 白い杖の人が:29 T=85.5
avoid / sound / 15             何も起きなかった   店の前で止ま:24 点字ブロック:0 白い杖の人が:29 T=49.4
avoid / sound / 60             何も起きなかった   店の前で止ま:69 点字ブロック:0 白い杖の人が:29 T=85.5
== kids
face / wait / light            事故         歩道で止まっ:23 集まった子ど:3 遠隔の担当が:0 T=34.8
face / wait / heavy            事故なし・問題あり  歩道で止まっ:42 集まった子ど:3 遠隔の担当が:0 T=67.6
face / voice / light           ひやり        歩道で止まっ:27 集まった子ど:3 遠隔の担当が:0 T=52.6
face / voice / heavy           事故なし・問題あり  歩道で止まっ:27 集まった子ど:3 遠隔の担当が:0 T=52.6
face / remote / light          何も起きなかった   歩道で止まっ:19 集まった子ど:3 遠隔の担当が:15 T=44.6
face / remote / heavy          何も起きなかった   歩道で止まっ:19 集まった子ど:3 遠隔の担当が:15 T=44.6
none / wait / light            何も起きなかった   歩道で止まっ:5 集まった子ど:0 遠隔の担当が:0 T=31.2
none / wait / heavy            何も起きなかった   歩道で止まっ:5 集まった子ど:0 遠隔の担当が:0 T=31.2
none / voice / light           何も起きなかった   歩道で止まっ:5 集まった子ど:0 遠隔の担当が:0 T=31.2
none / voice / heavy           何も起きなかった   歩道で止まっ:5 集まった子ど:0 遠隔の担当が:0 T=31.2
none / remote / light          何も起きなかった   歩道で止まっ:5 集まった子ど:0 遠隔の担当が:0 T=31.2
none / remote / heavy          何も起きなかった   歩道で止まっ:5 集まった子ど:0 遠隔の担当が:0 T=31.2
== dog
normal / pass / 6              事故         ロボットの速:6 リードとのい:0 配達の遅れ:4 T=32.6
normal / pass / 4              ひやり        ロボットの速:4 リードとのい:0.1 配達の遅れ:4 T=47.6
normal / stop / 6              何も起きなかった   ロボットの速:6 リードとのい:1.5 配達の遅れ:6 T=33.5
normal / stop / 4              何も起きなかった   ロボットの速:4 リードとのい:1.5 配達の遅れ:6 T=45.9
fine / pass / 6                何も起きなかった   ロボットの速:6 リードとのい:1.5 配達の遅れ:6 T=33.6
fine / pass / 4                何も起きなかった   ロボットの速:4 リードとのい:1.5 配達の遅れ:6 T=46.1
fine / stop / 6                何も起きなかった   ロボットの速:6 リードとのい:1.5 配達の遅れ:6 T=33.5
fine / stop / 4                何も起きなかった   ロボットの速:4 リードとのい:1.5 配達の遅れ:6 T=45.9
== bicycle
none / hard / fast             事故         ロボットが止:0.9 自転車とのい:0 店から出た人:0.6 T=20.4
none / hard / slow             何も起きなかった   ロボットが止:0.9 自転車とのい:1.6 店から出た人:0.6 T=28.2
none / soft / fast             ひやり        ロボットが止:1.7 自転車とのい:0.5 店から出た人:0.1 T=28.9
none / soft / slow             ひやり        ロボットが止:1.7 自転車とのい:2.4 店から出た人:0.1 T=28.9
watch / hard / fast            ひやり        ロボットが止:1.7 自転車とのい:0.5 店から出た人:0.1 T=28.9
watch / hard / slow            ひやり        ロボットが止:1.7 自転車とのい:2.4 店から出た人:0.1 T=28.9
watch / soft / fast            ひやり        ロボットが止:1.7 自転車とのい:0.5 店から出た人:0.1 T=28.9
watch / soft / slow            ひやり        ロボットが止:1.7 自転車とのい:2.4 店から出た人:0.1 T=28.9
== sign
none / squeeze / few           事故なし・問題あり  看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:3 T=22
none / squeeze / many          ひやり        看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:3 T=22
none / road / few              事故なし・問題あり  看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:3 T=25.4
none / road / many             事故         看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:3 T=17.9
none / stop / few              何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:30 T=55.3
none / stop / many             何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:30 T=55.3
daily / squeeze / few          何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:90 T=10.2
daily / squeeze / many         何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:90 T=10.2
daily / road / few             何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:90 T=10.2
daily / road / many            何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:90 T=10.2
daily / stop / few             何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:90 T=10.2
daily / stop / many            何も起きなかった   看板の横のす:0.8 ロボットの幅:0.7 配達の遅れ:90 T=10.2
== rain
night / camera / 6             事故         人に気づいた:1.8 止まるまでに:2 人との間（止:0 T=15.9
night / camera / 4             何も起きなかった   人に気づいた:1.8 止まるまでに:1 人との間（止:0.8 T=31.4
night / lidar / 6              ひやり        人に気づいた:2.4 止まるまでに:2 人との間（止:0.4 T=23
night / lidar / 4              何も起きなかった   人に気づいた:2.4 止まるまでに:1 人との間（止:1.4 T=31.4
day / camera / 6               何も起きなかった   人に気づいた:3 止まるまでに:1.7 人との間（止:1.3 T=22.8
day / camera / 4               何も起きなかった   人に気づいた:3 止まるまでに:0.8 人との間（止:2.2 T=31.3
day / lidar / 6                何も起きなかった   人に気づいた:3 止まるまでに:1.7 人との間（止:1.3 T=22.8
day / lidar / 4                何も起きなかった   人に気づいた:3 止まるまでに:0.8 人との間（止:2.2 T=31.3
== remote
1 / fifo / stay                何も起きなかった   横断歩道の台:9 工事の前の台:9 車が横断歩道:8 ベビーカーの:8 T=30.4
1 / fifo / clear               何も起きなかった   横断歩道の台:9 工事の前の台:9 車が横断歩道:0 ベビーカーの:0 T=30.9
1 / risk / stay                何も起きなかった   横断歩道の台:9 工事の前の台:9 車が横断歩道:8 ベビーカーの:8 T=30.4
1 / risk / clear               何も起きなかった   横断歩道の台:9 工事の前の台:9 車が横断歩道:0 ベビーカーの:0 T=30.9
4 / fifo / stay                ひやり        横断歩道の台:22 工事の前の台:14 車が横断歩道:15 ベビーカーの:8 T=45.2
4 / fifo / clear               何も起きなかった   横断歩道の台:22 工事の前の台:14 車が横断歩道:0 ベビーカーの:0 T=43.1
4 / risk / stay                ひやり        横断歩道の台:13 工事の前の台:23 車が横断歩道:12 ベビーカーの:8 T=43
4 / risk / clear               何も起きなかった   横断歩道の台:13 工事の前の台:23 車が横断歩道:0 ベビーカーの:0 T=38.9
10 / fifo / stay               事故         横断歩道の台:19 工事の前の台:16 車が横断歩道:15 ベビーカーの:8 T=35.3
10 / fifo / clear              何も起きなかった   横断歩道の台:19 工事の前の台:16 車が横断歩道:0 ベビーカーの:0 T=40.1
10 / risk / stay               ひやり        横断歩道の台:7 工事の前の台:12 車が横断歩道:6 ベビーカーの:8 T=32
10 / risk / clear              何も起きなかった   横断歩道の台:7 工事の前の台:12 車が横断歩道:0 ベビーカーの:0 T=30.9
== crossing
cross / silent / locked / 3    事故         動けなくなっ:35 駆け付ける人:3 人が警報中の:0 T=50.9
cross / silent / locked / 15   事故         動けなくなっ:35 駆け付ける人:15 人が警報中の:0 T=50.9
cross / silent / free / 3      事故         動けなくなっ:35 駆け付ける人:3 人が警報中の:0 T=50.9
cross / silent / free / 15     事故         動けなくなっ:35 駆け付ける人:15 人が警報中の:0 T=50.9
cross / ask / locked / 3       事故なし・問題あり  動けなくなっ:35 駆け付ける人:3 人が警報中の:0 T=29.5
cross / ask / locked / 15      事故なし・問題あり  動けなくなっ:35 駆け付ける人:15 人が警報中の:0 T=29.5
cross / ask / free / 3         ひやり        動けなくなっ:35 駆け付ける人:3 人が警報中の:8 T=54.2
cross / ask / free / 15        ひやり        動けなくなっ:35 駆け付ける人:15 人が警報中の:8 T=54.2
avoid / silent / locked / 3    何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:3 T=54.2
avoid / silent / locked / 15   何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:15 T=54.2
avoid / silent / free / 3      何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:3 T=54.2
avoid / silent / free / 15     何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:15 T=54.2
avoid / ask / locked / 3       何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:3 T=54.2
avoid / ask / locked / 15      何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:15 T=54.2
avoid / ask / free / 3         何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:3 T=54.2
avoid / ask / free / 15        何も起きなかった   配達の遅れ（:4 警報から列車:30 駆け付ける人:15 T=54.2
== flock
all / none / sidewalk          ひやり        歩道にたまっ:12 出発させた台:12 拠点で待たせ:0 T=54.4
all / none / lot               何も起きなかった   歩道にたまっ:2 出発させた台:12 拠点で待たせ:10 T=51.5
all / cap / sidewalk           何も起きなかった   歩道にたまっ:3 出発させた台:3 拠点で待たせ:0 T=51.5
all / cap / lot                何も起きなかった   歩道にたまっ:2 出発させた台:3 拠点で待たせ:1 T=51.5
stagger / none / sidewalk      事故なし・問題あり  歩道にたまっ:4 出発させた台:4 拠点で待たせ:0 T=59.3
stagger / none / lot           何も起きなかった   歩道にたまっ:2 出発させた台:4 拠点で待たせ:2 T=51.5
stagger / cap / sidewalk       何も起きなかった   歩道にたまっ:3 出発させた台:3 拠点で待たせ:0 T=51.5
stagger / cap / lot            何も起きなかった   歩道にたまっ:2 出発させた台:3 拠点で待たせ:1 T=51.5
== av
go / yes / keep                事故         ぶつかったと:7 記録が残る日:30 配達の遅れ:0 T=20.9
go / yes / short               事故         ぶつかったと:7 記録が残る日:1 配達の遅れ:0 T=20.9
go / no / keep                 事故         ぶつかったと:7 記録が残る日:30 配達の遅れ:0 T=20.9
go / no / short                事故         ぶつかったと:7 記録が残る日:1 配達の遅れ:0 T=20.9
wait / yes / keep              何も起きなかった   ぶつかったと:0 記録が残る日:30 配達の遅れ:8 T=33.6
wait / yes / short             何も起きなかった   ぶつかったと:0 記録が残る日:1 配達の遅れ:8 T=33.6
wait / no / keep               何も起きなかった   ぶつかったと:0 記録が残る日:30 配達の遅れ:8 T=33.6
wait / no / short              何も起きなかった   ぶつかったと:0 記録が残る日:1 配達の遅れ:8 T=33.6
```

### counts.mjs（場面ごとに、結果の種類を数える）

```javascript
import * as E from './engine.mjs';
const out=[];
for (const sc of E.SCENES) {
  const combos=[{}];
  for (const g of sc.groups){const n=[];for(const c of combos)for(const o of g.opts)n.push({...c,[g.k]:o[0]});combos.splice(0,combos.length,...n);}
  const k={hit:0,near:0,issue:0,safe:0};
  for(const c of combos){k[E.run(sc.id,c).outcome.kind]++;}
  const d=E.run(sc.id,sc.defaults);
  out.push({id:sc.id,group:sc.group,title:sc.title,n:combos.length,...k,open:d.explain.open});
}
console.log(JSON.stringify(out,null,0));
```

### counts.mjs の出力

```json
[{"id":"wheelchair","group":"people","title":"歩道で車いすの人とすれ違う","n":24,"hit":1,"near":3,"issue":4,"safe":16,"open":"「道を譲る」の中身（止まる位置・離れる距離・合図）の基準はまだない"},{"id":"sidebyside","group":"people","title":"横に並んで歩く人たちに、後ろから追いつく","n":12,"hit":2,"near":4,"issue":4,"safe":2,"open":"後ろからついて行くときに、どれだけ間をあけるかの基準はない"},{"id":"crowd","group":"people","title":"人が多い時間（下校の時間）","n":8,"hit":0,"near":2,"issue":1,"safe":5,"open":"通学の時間に配送ロボットを走らせてよいか、どれだけ止まってよいかは決まっていない"},{"id":"cane","group":"people","title":"白い杖の人と、点字ブロック","n":8,"hit":0,"near":1,"issue":1,"safe":6,"open":"配送ロボットが点字ブロックの上で止まってよいか、白い杖の人にどう知らせるかは決まっていない"},{"id":"kids","group":"people","title":"子どもが近寄る、触る、前に立つ","n":12,"hit":1,"near":1,"issue":2,"safe":8,"open":"子どもがいたずらしてロボットが倒れたとき、誰が責任を負うか（子どもの親・運行会社・メーカー）は整理されていない"},{"id":"dog","group":"people","title":"犬の散歩","n":8,"hit":1,"near":1,"issue":0,"safe":6,"open":"配送ロボットが動物やリードをどこまで見分けるべきか、安全基準の中での扱いは決まっていない"},{"id":"bicycle","group":"people","title":"歩道を走る自転車が、後ろから来る","n":8,"hit":1,"near":6,"issue":0,"safe":1,"open":"歩道で自転車が配送ロボットを追い越すとき、自転車がロボットを歩行者として譲る必要があるかは、はっきりしない"},{"id":"sign","group":"place","title":"置き看板と路上駐車で、歩道が狭くなる","n":12,"hit":1,"near":1,"issue":2,"safe":8,"open":"歩道に置かれた物で配送ロボットが通れないとき、誰が直すか（店・道の管理者・運行会社）は決まっていない"},{"id":"rain","group":"place","title":"雨の夜に、人が出てくる","n":8,"hit":1,"near":1,"issue":0,"safe":6,"open":"雨や夜に、配送ロボットの速さを落とす・走らせないといった決まりはない"},{"id":"remote","group":"ops","title":"1人の遠隔の担当が、何台も見ている","n":12,"hit":1,"near":3,"issue":0,"safe":8,"open":"担当が急いで出した「進んでよい」で起きた事故を、担当・運行会社・メーカーのどこが負うかはまだ整理されていない"},{"id":"crossing","group":"ops","title":"踏切の中で動けなくなる","n":16,"hit":4,"near":2,"issue":2,"safe":8,"open":"踏切で動けなくなった配送ロボットについて、誰がどうやって鉄道に知らせるかはまだ決まっていない"},{"id":"flock","group":"ops","title":"朝に一斉に出発して、歩道にたまる","n":8,"hit":0,"near":1,"issue":1,"safe":6,"open":"1つの街や1つの歩道に、配送ロボットを何台まで走らせてよいかを決める仕組みはない"},{"id":"av","group":"ops","title":"横断歩道で、自動運転の車とぶつかる","n":8,"hit":4,"near":0,"issue":0,"safe":4,"open":"機械どうしの事故で、どちらの会社の記録を正として責任を分けるかは決まっていない"}]
```

### ov2.mjs（事故の前に、人・ロボット・自転車・犬・車が重ならないかを確かめる）

```javascript
import * as E from './engine.mjs';
// 事故が起きる前に、人・ロボット・自転車・犬・車が重ならないかを確かめる（踏切の場面は人がロボットを押すので外す）
const rect = (x, z, h, L, W) => { const c = Math.abs(Math.cos(h)), s = Math.abs(Math.sin(h)); const hx = L * c + W * s, hz = L * s + W * c; return [x - hx, x + hx, z - hz, z + hz]; };
const body = (o, kind) => kind === 'robot' ? rect(o.x, o.z, o.h, 0.5, 0.35) : kind === 'car' ? rect(o.x, o.z, o.h, 2.2, 0.85)
  : o.kind === 'wheelchair' ? rect(o.x, o.z, o.h, 0.55, 0.35) : o.kind === 'stroller' ? rect(o.x - Math.cos(o.h) * -0.42, o.z, o.h, 0.7, 0.3) : o.kind === 'bike' ? rect(o.x, o.z, o.h, 0.62, 0.3) : o.kind === 'dog' ? rect(o.x, o.z, o.h, 0.35, 0.12) : rect(o.x, o.z, 0, o.child ? 0.2 : 0.26, o.child ? 0.2 : 0.26);
const ov = (a, b) => Math.min(a[1], b[1]) - Math.max(a[0], b[0]) > 0.03 && Math.min(a[3], b[3]) - Math.max(a[2], b[2]) > 0.03;
let bad = 0;
for (const sc of E.SCENES) { if (sc.id === 'crossing') continue; const combos = [{}]; for (const g of sc.groups) { const n = []; for (const c of combos) for (const o of g.opts) n.push({ ...c, [g.k]: o[0] }); combos.splice(0, combos.length, ...n); }
  for (const c of combos) { const r = E.run(sc.id, c); const h = r.events.find((e) => e.kind === 'hit'); let msg = null;
    for (const f of r.frames) { if (h && f.t >= h.t - 0.3) break;
      const B = [...f.robots.filter((o) => !o.fallen).map((o) => ['robot ' + o.id, body(o, 'robot')]), ...(f.cars || []).map((o) => ['car ' + o.id, body(o, 'car')]), ...f.peds.map((o) => [o.kind + ' ' + o.id, body(o, 'ped')])];
      for (let i = 0; i < B.length && !msg; i++) for (let j = i + 1; j < B.length; j++) { if (B[i][0].startsWith('walk') && B[j][0].startsWith('walk')) continue; if (/^(walk|dog)/.test(B[i][0]) && /^(walk|dog)/.test(B[j][0])) continue; if (ov(B[i][1], B[j][1])) { msg = `${f.t} ${B[i][0]} x ${B[j][0]}`; break; } }
      if (msg) break; }
    if (msg) { bad++; console.log(sc.id, JSON.stringify(c), msg); } } }
console.log('重なり', bad, '件');
```

### ov2.mjs の出力

```text
重なり 0 件
```

### ex.mjs（説明の文を全部出して読む用）

```javascript
import * as E from './engine.mjs';
for (const sc of E.SCENES) { const combos=[{}]; for (const g of sc.groups){const n=[];for(const c of combos)for(const o of g.opts)n.push({...c,[g.k]:o[0]});combos.splice(0,combos.length,...n);}
 for (const c of combos){const r=E.run(sc.id,c); console.log(sc.id, JSON.stringify(c), r.outcome.label,'|',r.explain.what,'|CO:',r.explain.company.map(x=>x[1].slice(0,18)).join(' / '),'|OPEN:',r.explain.open.slice(0,25));}}
```

### cap_specs.mjs（画面を撮る場面と設定。事故・ひやりの時刻を計算から出す）

```javascript
import * as E from './engine.mjs';
const specs = [
 ['02_wheelchair_hit','wheelchair',{}],
 ['03_wheelchair_back','wheelchair',{yield:'back'}],
 ['04_sidebyside_road','sidebyside',{pass:'road'}],
 ['05_crowd_run','crowd',{stop:0.5}],
 ['06_cane_door','cane',{}],
 ['07_kids_fall','kids',{}],
 ['08_dog_leash','dog',{}],
 ['09_bicycle_hard','bicycle',{}],
 ['10_sign_road','sign',{way:'road'}],
 ['11_rain_night','rain',{}],
 ['12_remote_10','remote',{}],
 ['13_crossing_train','crossing',{}],
 ['14_flock_all','flock',{}],
 ['15_av_hit','av',{}],
];
const out = specs.map(([name,id,over])=>{
  const sc=E.SCENES.find(s=>s.id===id); const cfg={...sc.defaults,...over};
  const r=E.run(id,cfg); const ev=r.events.find(e=>e.kind==='hit'||e.kind==='near');
  const idx={}; for(const g of sc.groups){ idx[g.k]=g.opts.findIndex(o=>o[0]===cfg[g.k]); }
  return {name,id,idx,t:ev?ev.t:null,kind:r.outcome.label,T:r.frames.at(-1).t};
});
console.log(JSON.stringify(out));
```

### cap.py（場面ごとに再生して、途中と終わりの画面を撮る）

```python
import asyncio, json, sys
from playwright.async_api import async_playwright
specs=json.load(open('cap_specs.json'))
only=sys.argv[1].split(',') if len(sys.argv)>1 else None
async def main():
    async with async_playwright() as p:
        b = await p.chromium.launch(executable_path='/usr/bin/google-chrome', args=['--use-gl=swiftshader','--enable-webgl','--ignore-gpu-blocklist'])
        pg = await b.new_page(viewport={'width':1440,'height':900})
        errs=[]; pg.on('pageerror', lambda e: errs.append(str(e)))
        await pg.goto('file:///home/claude/dr/delivery_sim_v0.html'); await pg.wait_for_timeout(2500)
        await pg.screenshot(path='cap/01_start.png')
        for s in specs:
            if only and s['name'] not in only: continue
            await pg.click(f'#scenes .sc[data-id="{s["id"]}"]'); await pg.wait_for_timeout(300)
            for k,i in s['idx'].items():
                await pg.click(f'#groups button[data-k="{k}"][data-i="{i}"]')
            await pg.wait_for_timeout(200)
            await pg.click('#run'); await pg.click('#sceneSpeeds button[data-r="4"]')
            tt=(s['t']+0.6) if s['t'] else s['T']*0.45
            while (await pg.evaluate("window.__dr.state().T")) < tt and (await pg.evaluate("window.__dr.state().playing")): await pg.wait_for_timeout(50)
            await pg.screenshot(path=f'cap/{s["name"]}_mid.png')
            while (await pg.evaluate("window.__dr.state().playing")): await pg.wait_for_timeout(200)
            await pg.wait_for_timeout(700)
            await pg.screenshot(path=f'cap/{s["name"]}_end.png')
            await pg.click('#stopRun'); await pg.wait_for_timeout(300)
        print(errs); await b.close()
asyncio.run(main())
```

### t6.py（比べる・自動再生・責任の振り分け・レポートを画面で通す）

```python
import asyncio
from playwright.async_api import async_playwright
async def main():
    async with async_playwright() as p:
        b = await p.chromium.launch(executable_path='/usr/bin/google-chrome', args=['--use-gl=swiftshader','--enable-webgl','--ignore-gpu-blocklist'])
        pg = await b.new_page(viewport={'width':1440,'height':900})
        errs=[]; pg.on('pageerror', lambda e: errs.append(str(e)))
        await pg.goto('file:///home/claude/dr/delivery_sim_v0.html'); await pg.wait_for_timeout(2500)
        async def wait_idle():
            while True:
                st=await pg.evaluate("window.__dr.state()")
                if not st['playing'] and not st['auto']: break
                await pg.wait_for_timeout(300)
            await pg.wait_for_timeout(800)
        # dog: 事故 -> 速さ4 で比べる
        await pg.click('#scenes .sc[data-id="dog"]'); await pg.wait_for_timeout(300)
        await pg.click('#run'); await pg.click('#sceneSpeeds button[data-r="4"]'); await wait_idle()
        await pg.click('#sAgain'); await pg.click('#groups button[data-k="approach"][data-i="1"]'); await pg.click('#run'); await wait_idle()
        await pg.click('#sCmp'); await pg.wait_for_timeout(500); await pg.screenshot(path='cap/20_dog_compare.png', full_page=True)
        await pg.click('#cmpBack'); await pg.wait_for_timeout(300)
        # 自動再生: av
        await pg.click('#stopRun') if await pg.is_visible('#stopRun') else None
        await pg.click('#scenes .sc[data-id="av"]'); await pg.wait_for_timeout(300)
        await pg.click('#autoRun'); await pg.click('#sceneSpeeds button[data-r="4"]'); await wait_idle()
        await pg.screenshot(path='cap/21_av_auto.png', full_page=True)
        await pg.click('.arow[data-i="0"]'); await pg.wait_for_timeout(300)
        await pg.click('button[data-assign="0"]'); await pg.wait_for_timeout(500)
        await pg.screenshot(path='cap/22_av_assign.png', full_page=True)
        await pg.click('#toCompare'); await pg.wait_for_timeout(400); await pg.screenshot(path='cap/23_av_alloc.png', full_page=True)
        await pg.click('#alRep'); await pg.wait_for_timeout(900); await pg.screenshot(path='cap/24_av_report.png')
        print(errs); await b.close()
asyncio.run(main())
```

### fig_data.mjs（図解の「まえ・あと」のデータを作る）

```javascript
import * as E from './engine.mjs';
const PAIRS={wheelchair:{yield:'back'},sidebyside:{pass:'road'},crowd:{stop:0.5},cane:{sound:'sound'},kids:{resp:'remote'},dog:{approach:'stop'},bicycle:{brake:'soft'},sign:{way:'road'},rain:{sensor:'lidar'},remote:{order:'risk'},crossing:{voice:'ask'},flock:{waitAt:'lot'},av:{cross:'wait'}};
const counts=JSON.parse((await import('fs')).readFileSync('counts.json','utf8'));
const lab=(sc,k,v)=>{const g=sc.groups.find(g=>g.k===k);return [g.label.replace(/（.*$/,''), g.opts.find(o=>o[0]===v)[1].replace(/（.*$/,'')]};
const pack=(r)=>({kind:r.outcome.kind,what:r.explain.what,who:[...new Set([...r.explain.people,...r.explain.company].map(x=>x[0]))],open:r.explain.open});
const out=E.SCENES.map(sc=>{const [k,v]=Object.entries(PAIRS[sc.id])[0];const c=counts.find(x=>x.id===sc.id);
 const [gl,from]=lab(sc,k,sc.defaults[k]);const [,to]=lab(sc,k,v);
 return {id:sc.id,group:sc.group,title:sc.title,n:c.n,hit:c.hit,near:c.near,issue:c.issue,safe:c.safe,change:{label:gl,from,to},a:pack(E.run(sc.id,sc.defaults)),b:pack(E.run(sc.id,{...sc.defaults,[k]:v}))}});
console.log(JSON.stringify(out));
```

### mk_site.py（試作の HTML から、サイトに置く版を作る。説明の情報と計測を足す）

```python
# 試作の HTML から、サイトに置く版を作る（説明の情報と計測を足す）
s=open('/home/claude/dr/delivery_sim_v0.html').read()
av=open('/home/claude/p2m-site/public/sim/av-accident-responsibility.html').read()
i=av.rindex('<script>', 0, av.rindex('p2m-notrack')); j=av.index('</script>', av.rindex('p2m-notrack'))+9
blk=av[i:j].replace('「事故が起きたら誰の責任？」（/sim/av-accident-responsibility）の使われ方の記録','「事故が起きたら誰の責任？ 歩道の配送ロボット」（/sim/delivery-robot-accident-responsibility）の使われ方の記録',1)
head_old='<title>歩道の配送ロボット — 事故が起きたら誰の責任？（試作）</title>'
assert head_old in s
desc='歩道を走る自動配送ロボット（遠隔操作型小型車）が人や車とぶつかったら、誰の責任か。車いす・白い杖の人・子ども・犬・自転車・踏切・遠隔の担当1人が見る台数など13の場面で、メーカーの作りや運行会社の決まりを変えて同じ場面を見直し、人・企業・決まり（法律や制度）のどこに問題が移るかを確かめるブラウザのシミュレーション（試作）。法律上の答えは出さず、関係しそうな決まりとまだ決まっていないことを示す。'
s=s.replace(head_old, head_old+f'\n<meta name="description" content="{desc}">\n<link rel="canonical" href="https://pixelstomotors.com/sim/delivery-robot-accident-responsibility">\n<meta property="og:title" content="事故が起きたら誰の責任？ 歩道の配送ロボット（試作）| Pixels to Motors">\n<meta property="og:description" content="{desc}">',1)
k=s.rindex('</body>'); s=s[:k]+blk+'\n'+s[k:]
open('/home/claude/p2m-site/public/sim/delivery-robot-accident-responsibility.html','w').write(s)
print(len(blk), len(s))
```

### records.ts の差分（シリーズのページに試作へのリンクを足した）

```diff
diff --git a/src/lib/records.ts b/src/lib/records.ts
index 1fb2d0d..9bc62a5 100644
--- a/src/lib/records.ts
+++ b/src/lib/records.ts
@@ -66,7 +66,7 @@ export const SERIES_PAGES: Record<string, { series: string; title: string; pageT
   series9: { series: 'フィジカルAIの社会実装シミュレーション', title: 'Physical AI Deployment Simulation | フィジカルAIの社会実装シミュレーション', pageTitle: 'Series9 | フィジカルAIの社会実装シミュレーション', limit: 12,
     intro: 'フィジカルAI（自動運転の乗り物やロボット）が社会に出る前に解くべき課題を、ブラウザで触れるシミュレーションで確かめる記録です。課題地図（フィジカルAIが社会実装される前に解くべき課題の一覧）の課題を1つずつ題材にし、見る人が仕組みを選んで動かすと、どんな場面で、人・企業・決まりや行政のどこに問題が出るかが分かる形を目指しています。最初の題材は、自動運転バスがT字路で人とぶつかりそうになったとき、責任は誰にあるのか、です。数字は比べるための仮のもので、予測ではありません。',
     // 見出しの下のボタン（2026-11-20）
-    links: [{ href: '/issues', label: 'フィジカルAIが社会実装される前に解くべき課題 →' }, { href: '/sim/av-accident-responsibility.html', label: 'シミュレーション「事故が起きたら誰の責任？」を開く（試作） →' }] },
+    links: [{ href: '/issues', label: 'フィジカルAIが社会実装される前に解くべき課題 →' }, { href: '/sim/av-accident-responsibility.html', label: 'シミュレーション「事故が起きたら誰の責任？」を開く（試作） →' }, { href: '/sim/delivery-robot-accident-responsibility.html', label: 'シミュレーション「事故が起きたら誰の責任？ 歩道の配送ロボット」を開く（試作） →' }] },
   series8: { series: '導入シミュレーション', title: 'Service Robot Simulation | サービスロボット導入シミュレーション', pageTitle: 'Series8 | サービスロボット導入シミュレーション', limit: 12, serving: true, scenes: true, browserTest: true,
     intro: 'サービスロボット導入シミュレーションとは、配膳・清掃・搬送などのロボットを店や施設に入れる前に、待ち時間・必要な人数・ロボットが止まる場所・費用を試算して確かめることです。このシリーズでは、時間・順番・台数を SimPy で、ぶつかる・こぼれるといった空間と動きを Unity で扱い、結果とコードを全量公開しています。',
     // 見出しの下に並べる短い一覧（検索や AI が「何が分かるか・どう試算するか」を拾えるように、本文の文字で書く）
```

### cap_thumb.py（サムネイルの素材を撮る）

```python
# サムネイルの素材を撮る（3Dだけ・1920×1080。パネル・ボタン・吹き出し・名札を隠す）
import asyncio, json
from playwright.async_api import async_playwright
specs={s['name']:s for s in json.load(open('/home/claude/dr/cap_specs.json'))}
SHOTS=[('kids','07_kids_fall',0.3,'iso'),('flock','14_flock_all',0,'iso'),('train','13_crossing_train',-0.6,'iso'),('wheel','02_wheelchair_hit',0.3,'follow'),('dog','08_dog_leash',0.2,'follow'),('rain','11_rain_night',0.2,'iso')]
HIDE='#panel,#top,#views,#caption,#bubble,#op,#timebar,#labels{display:none!important}'
async def main():
    async with async_playwright() as p:
        b = await p.chromium.launch(executable_path='/usr/bin/google-chrome', args=['--use-gl=swiftshader','--enable-webgl','--ignore-gpu-blocklist'])
        pg = await b.new_page(viewport={'width':1920,'height':1080})
        await pg.goto('file:///home/claude/dr/delivery_sim_v0.html'); await pg.wait_for_timeout(2500)
        for out,name,dt,view in SHOTS:
            s=specs[name]
            await pg.click(f'#scenes .sc[data-id="{s["id"]}"]'); await pg.wait_for_timeout(300)
            for k,i in s['idx'].items(): await pg.click(f'#groups button[data-k="{k}"][data-i="{i}"]')
            await pg.click('#run'); await pg.click('#sceneSpeeds button[data-r="2"]')
            if view=='follow': await pg.click('#viewBtns button:nth-child(3)')
            tt=s['t']+dt
            while (await pg.evaluate("window.__dr.state().T")) < tt: await pg.wait_for_timeout(30)
            st=await pg.add_style_tag(content=HIDE); await pg.wait_for_timeout(250)
            await pg.screenshot(path=f'/home/claude/dr/thumb/{out}.png')
            await pg.evaluate("(e)=>e.remove()", st)
            while (await pg.evaluate("window.__dr.state().playing")): await pg.wait_for_timeout(200)
            await pg.click('#stopRun') if await pg.is_visible('#stopRun') else None
            await pg.wait_for_timeout(300)
            if view=='follow': await pg.click('#viewBtns button:nth-child(1)')
        await b.close()
asyncio.run(main())
```

### make.py の差分（このシリーズの記事サムネイル。LOG541 の分を足した）

```diff
diff --git a/tools/social_sim_thumbs/make.py b/tools/social_sim_thumbs/make.py
index a86c68a..a0dbe5c 100644
--- a/tools/social_sim_thumbs/make.py
+++ b/tools/social_sim_thumbs/make.py
@@ -53,6 +53,17 @@ def band(n, left, mid, right, r=.5):
     save(n, out)
 
 
+def stack(n, top, a, b, c, r=.52):
+    """上に横長1・下に3つ"""
+    out = Image.new('RGB', (W, H), LIGHT)
+    th = int((H - G) * r); bh = H - G - th; cw = (W - 2 * G) // 3; lw = W - 2 * G - 2 * cw
+    out.paste(part(top, W, th), (0, 0))
+    out.paste(part(a, cw, bh), (0, th + G))
+    out.paste(part(b, cw, bh), (cw + G, th + G))
+    out.paste(part(c, lw, bh), (2 * cw + 2 * G, th + G))
+    save(n, out)
+
+
 def save(n, out):
     out.save(f'{HERE}/out/LOG{n}.png')
     os.makedirs(f'{SITE}/public/thumbs/img', exist_ok=True)
@@ -67,6 +78,9 @@ JOBS = {
     # バスの動作不良を足した回（3列）。左＝曲がりが遅れて歩道の人と接触したバスを後ろから、
     # 中＝通信が切れて交差点の中で止まったバス、右＝同じ接触を真上から
     539: lambda n: band(n, ('steer_follow', .42, .55, .46), ('comm_iso', .49, .6, .22), ('steer_top', .45, .42, .2), r=.5),
+    # 歩道の配送ロボットの試作を作った回（上に横長1・下に3つ）。上＝朝に一斉に出発して歩道にたまった12台、
+    # 下左＝子どもに押されて倒れた所、下中＝狭い所で車いすの人と接触した所（ロボットの後ろから）、下右＝踏切で列車がロボットにぶつかった所
+    541: lambda n: stack(n, ('d_flock', .47, .44, .5), ('d_kids', .44, .42, .3), ('d_wheel', .46, .62, .5), ('d_train', .6, .45, .5)),
 }
 
 if __name__ == '__main__':
```
