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

namespace ServiceSim.Closeups.EditorTools
{
    /// <summary>
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup228.Run \
    ///                 -c228Out <出力フォルダ> [-c228Script closeup228_script.json] [-c228Frames on|off] [-c228Stills on|off] [-c228Views main,top] [-c228From 秒] [-c228To 秒] [-c228Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames228.csv・bones228.csv・feet228.csv・wc228.csv・check228.txt・events228.txt
    /// </summary>
    public static class Closeup228
    {
        const string Root = CloseupShoot.Root;
        const string TexDir = CloseupShoot.TexDir;
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string F(float v, string f = "0.0000") { return v.ToString(f, IC); }
        const int LayerChair = 30, LayerNurse = 31;

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

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

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

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

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

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

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c228Out", "");
            if (outDir == "") throw new Exception("-c228Out がない");
            string scriptName = CloseupArgs.Get("-c228Script", "closeup228_script.json");
            bool frames = CloseupArgs.Get("-c228Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c228Stills", "on") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c228Views", "main,top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c228From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c228To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                Closeup228Morita.Import(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

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

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

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

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

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

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

                string shotName = "yield";
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c228"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                Texture2D bandTex = ScreenTex(TexDir + "/" + C["band"].S() + ".png");
                float bandOn = C["band_on"].F(), bandOff = C["band_off"].F(), happyFrom = C["happy_from"].F(), happyTo = C["happy_to"].F();
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                dir.Apply(0f, dt);
                var rs = MeasureRobot(dir);
                log.AppendLine(string.Format(IC, "ハコブくんの外形（根から）: 幅 x {0:0.000}〜{1:0.000}・奥行 z {2:0.000}〜{3:0.000}・高さ {4:0.000} m", rs.minX, rs.maxX, rs.minZ, rs.maxZ, rs.top));
                var bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c228Until", "1e9"), IC)) * fps);
                string fdirM = Path.Combine(outDir, "frames", shotName), fdirT = Path.Combine(outDir, "frames", shotName + "_top");
                bool vMain = frames && views.Contains("main"), vTop = frames && views.Contains("top");
                if (vMain) Directory.CreateDirectory(fdirM);
                if (vTop) Directory.CreateDirectory(fdirT);
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart\n");
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        if (mode == "stop" && stopped && behindN >= R.passBehind) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師
                    dir.Apply(t, dt);
                    dir.robot.position = O + new Vector3(rx, 0f, rz);
                    dir.robot.rotation = Quaternion.Euler(0f, ryaw, 0f);
                    int nml = f < nurseMouth.Count ? nurseMouth[f].I() : 0;
                    if (nml > 0) dir.nurse.mouth = "talk";
                    curMouthScale = nml > 0 ? nmScale[nml].F() : 1f;
                    dir.nurse.Step(f == 0 ? 0f : dt, iters);

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

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    bool bandNow = t >= bandOn - 1e-4f && t < bandOff - 1e-4f;
                    bool happyNow = t >= happyFrom - 1e-4f && t < happyTo - 1e-4f;
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", bandTex); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy" : rmo != "mid" ? rmo : "";
                    { var mpf = new MaterialPropertyBlock(); if (fk != "") { mpf.SetTexture("_MainTex", faceAlb[fk]); mpf.SetTexture("_EmissionMap", faceEmi[fk]); } faceR.SetPropertyBlock(mpf); }
                    string scrNow = (bandNow ? "帯" : "") + (happyNow ? "目まで笑う顔" : "基本") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.z);
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        float d = RobotDist(rs, lr, Mathf.Min(gap, 1.5f));
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[k]);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        foreach (var s in solids)
                        {
                            if (w.x < s.min.x - 0.3f || w.x > s.max.x + 0.3f || w.z < s.min.z - 0.3f || w.z > s.max.z + 0.3f) continue;
                            if (InBox(w, s.min, s.max)) { rsHit = true; if (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

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

                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

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

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn);

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && inRange)
                    {
                        syncProxies(); scaleMouth();
                        if (vMain) { SetCam(dir.cam, shot["cameras"][camName], O, dir); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirM, string.Format("f_{0:00000}.png", f))); }
                        if (vTop) { SetCam(dir.cam, shot["cameras"][shot["top_camera"].S()], O, dir); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f))); }
                    }
                    for (int s = 0; stillsOn && s < (stills != null ? stills.Count : 0); s++)
                    {
                        if (Mathf.RoundToInt(stills[s][0].F() * fps) != f) continue;
                        syncProxies(); scaleMouth();
                        SetCam(dir.cam, shot["cameras"][stills[s][1].S()], O, dir);
                        string sn = stills[s][2].S();
                        string sd = Path.Combine(outDir, sn.StartsWith("chk_") ? "stills_check" : "stills"); Directory.CreateDirectory(sd);
                        SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(sd, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames228.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones228.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet228.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc228.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check228.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events228.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C228] done\n" + log + "\n" + tab);
        }

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

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

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

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

        /// <summary>カメラ：pos・look は廊下の原点から。follow が "robot" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</summary>
        static void SetCam(Camera cam, JsonValue C, Vector3 O, CloseupDirector dir)
        {
            if (C == null || C.IsNull) throw new Exception("台本にカメラが無い");
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            if (fo == "robot") add = new Vector3(0f, 0f, dir.robot.position.z - O.z);
            else if (fo == "nurse") add = new Vector3(0f, 0f, dir.nurse.transform.position.z - O.z);
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

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

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