"""机・棚・コンテナ台車・立ち作業台の物を、吸着式の道具（VGC10）で続けて取って、荷台のコンテナへ入れる動きを作り、当たりを粗く確かめる。
取る物・在庫・コンテナの中の置き場所は tour_common.py。腕と道具は球の列、持っている物は点の格子で見る。
関節は端から端へまっすぐ角度を変えるとして途中を 31 か所見る。当たるときは途中の姿勢を1つか2つ探す。
置き場所では、在庫とまだ取っていない物を障害物に入れる。コンテナの中は、全部まわる順で先に入れた物を障害物に入れる。
使い方: python3 tour_poses.py   （page/arm_poses.json に tour を足す。出力は out_tour_poses.txt）"""
import sys, json, math, numpy as np
import tour_common as TC
ONLY = sys.argv[1:]; sys.argv = ['arm_poses.py', 'urdf_fixed', '/tmp/x.json']
src = open('arm_poses.py', encoding='utf-8').read().split("out = {'fold'")[0]
ns = {}; exec(compile(src, 'ap', 'exec'), ns)
fk, solve, collide, to_u, B, OBST, WALLS, LIM = (ns[k] for k in ('fk', 'solve', 'collide', 'to_u', 'B', 'OBST', 'WALLS', 'LIM'))
BASE_H = 0.698; EX = TC.EX; SF = TC.SF
DOWN = np.array([0, 0, -1.0]); FWD = np.array([-1.0, 0, 0]); XF = np.array([-1.0, 0, 0]); XR = np.array([0, 1.0, 0])
ITEMS = TC.items(); SLOTS = TC.pack(ITEMS); STOCK = TC.stock()
P = json.load(open('page/arm_poses.json')); FOLD = np.array(P['fold'])
LOG = []
def say(*a):
    s = ' '.join(str(x) for x in a); print(s); LOG.append(s)
def deg(q): return np.degrees(q).round(1).tolist()
U = lambda h: h - BASE_H
# 置き場所ごとの、ぶつかる物（アームの軸から 前 f0..f1・右 r0..r1・付け根の底から上 u0..u1、m）
def shelf_obst():
    o = []
    for h in (0.100, 0.520, 0.940, 1.360): o.append((f'棚の板{int(h*1000)}', (SF, SF + 0.45, -0.60, 1.80, U(h - 0.03), U(h))))
    for r0 in (-0.60, 0.56, 1.76): o.append(('棚の柱', (SF, SF + 0.04, r0, r0 + 0.04, U(0), U(1.8))))
    for li, h in enumerate((0.100, 0.520, 0.940, 1.360)):
        if li == 2: continue
        for j in range(3):
            if (0 + li + j) % 4 == 3 or (li == 1 and j == 1): continue
            m = (j + li) % 2; r = -0.36 + 0.36 * j
            o.append(('棚の段ボール', (SF + 0.065, SF + 0.385, r - 0.15, r + 0.15, U(h), U(h + 0.22 + 0.03 * m))))
    return o
STATION = {
    'table': [('机', (EX - 0.03, EX + 0.75, -0.75, 0.75, U(0.710), U(0.740)))],
    'stand': [('立ち作業台', (EX - 0.03, EX + 0.90, -0.75, 0.75, U(0.870), U(0.900)))],
    'shelf': shelf_obst(),
    'dolly': [('台車の箱の前の壁', (EX, EX + 0.012, -0.265, 0.265, U(0.110), U(0.331))), ('台車の箱の後ろの壁', (EX + 0.354, EX + 0.366, -0.265, 0.265, U(0.110), U(0.331))),
              ('台車の箱の左の壁', (EX, EX + 0.366, -0.265, -0.253, U(0.110), U(0.331))), ('台車の箱の右の壁', (EX, EX + 0.366, 0.253, 0.265, U(0.110), U(0.331))),
              ('台車の箱の底', (EX, EX + 0.366, -0.265, 0.265, U(0.0), U(0.124)))],
}
def in_box(i):  # コンテナに入れた物（アームの座標）
    return (f'コンテナの中の物{i+1}', B(*TC.container_box(ITEMS[i], SLOTS[i])))
def on_site(it, name):  # 置き場所にある物（アームの座標）
    w, d, h = TC.dims(it); ff, rr = TC.footprint(it)
    return (name, (it['f'] - ff / 2000, it['f'] + ff / 2000, it['r'] - rr / 2000, it['r'] + rr / 2000, U(it['z0']), U(it['z0'] + h / 1000)))
def set_j6(q, xdir):
    q = np.array(q, float); q[5] = 0
    _, _, _, ax, xa = fk(q); d = xdir - ax * (xdir @ ax); d /= np.linalg.norm(d)
    a6 = math.atan2(ax @ np.cross(xa, d), xa @ d)
    if a6 > math.pi / 2: a6 -= math.pi
    if a6 < -math.pi / 2: a6 += math.pi
    q[5] = a6; return q
def item_pts(q, it):
    (sx, sy, sz), c = TC.tool_box(it); _, _, tip, ax, xa = fk(q); ya = np.cross(ax, xa); out = []
    for z in np.linspace(c - sz / 2, c + sz / 2, 4):
        for x in np.linspace(-sx / 2, sx / 2, 3):
            for y in np.linspace(-sy / 2, sy / 2, 3): out.append(tip + (ax * z + xa * x + ya * y) / 1000)
    return out
def item_hit(q, it, extra):
    b0, b1, hw, ib0, ib1, ihw, H = WALLS; m = 0.004
    for p in item_pts(q, it):
        f, r, u = -p[0], p[1], p[2]; h = u + 0.300; back = 0.065 - f
        for name, (f0, f1, r0, r1, u0, u1) in list(OBST.items()) + list(extra):
            if f0 - m < f < f1 + m and r0 - m < r < r1 + m and u0 - m < u < u1 + m: return '持っている物が' + name
        if h < H / 1000 + m:
            o = (b0 / 1000 - m < back < b1 / 1000 + m) and abs(r) < hw / 1000 + m
            i = (ib0 / 1000 + m < back < ib1 / 1000 - m) and abs(r) < ihw / 1000 - m
            if o and not i: return '持っている物がコンテナの壁'
            if i and h < 0.014 - m: return '持っている物がコンテナの底'
    return None
def hit(q, it, extra):
    c = collide(q, True, extra)
    if c is None and it is not None: c = item_hit(q, it, extra)
    return c
def sweep(a, b, it, extra, n=31, t0=0.0):
    a, b = np.array(a), np.array(b)
    for t in np.linspace(t0, 1, n):
        c = hit(a + (b - a) * t, it, extra)
        if c is not None: return (round(float(t), 2), c)
    return None
SEEDS = ns['SEEDS'] + ns['OVER'] + ns['rand_seeds'](60)
def pose(tip, axis, xdir, extra, it=None, ref=None, front=False):
    """爪先の位置と向きに合う姿勢のうち、当たらず、ref に近いもの。front は腕を前に向けた形（J1 が ±70° の内）だけ"""
    best = None; tgt = to_u(tip[0], tip[1], tip[2] - BASE_H)   # tip の高さは地面から
    for sd in ([tuple(ref)] if ref is not None else []) + SEEDS:
        q, ok = solve(tgt, axis, sd)
        if not ok: continue
        if front and abs(q[0]) > math.radians(70): continue
        q = set_j6(q, xdir)
        if hit(q, it, extra) is not None: continue
        cost = np.abs(q - (ref if ref is not None else FOLD)).sum() + (0.6 if q[2] < 0 else 0)
        if best is None or cost < best[0]: best = (cost, q)
        CANDS.append((cost, q))
    return None if best is None else best[1]
CANDS = []
def pose_list(*a, **k):
    """pose と同じ条件で、形の違う候補を近い順に（最大 10）"""
    CANDS.clear(); pose(*a, **k); out = []
    for c, q in sorted(CANDS, key=lambda x: x[0]):
        if all(np.abs(q - o).max() > 0.2 for o in out): out.append(q)
        if len(out) >= 10: break
    return out
def first_chain(cands, p0, p1, axis, xdir, extra, it, n):
    err = '候補がない'
    for q0 in cands:
        c, e = chain(q0, p0, p1, axis, xdir, extra, it, n)
        if c is not None: return q0, c, None
        err = e
    return None, None, err
def chain(q0, p0, p1, axis, xdir, extra, it, n=6):
    """爪先をまっすぐ動かす（途中の姿勢を前の姿勢から解く）"""
    out = []; q = q0
    for t in np.linspace(0, 1, n + 1)[1:]:
        tip = tuple(np.array(p0) + (np.array(p1) - np.array(p0)) * t)
        cands = []
        for sd in [tuple(q)] + SEEDS[::4]:
            q2, ok = solve(to_u(tip[0], tip[1], tip[2] - BASE_H), axis, sd)
            if not ok: continue
            q2 = set_j6(q2, xdir)
            if abs(q2[5] - q[5]) > 1.0: q2[5] += math.copysign(math.pi, q[5] - q2[5])
            jump = float(np.abs(q2 - q).max())
            if jump > 0.6: continue
            cands.append((jump, q2))
            if sd == tuple(q) and jump < 0.3: break
        if not cands: return None, f'まっすぐ動かす途中（{t:.2f}）で、腕の形を変えずには届かない'
        cands.sort(key=lambda x: x[0]); q2 = cands[0][1]
        c = hit(q2, it, extra)
        if c is not None: return None, f'まっすぐ動かす途中（{t:.2f}）で {c} に当たる'
        out.append(q2); q = q2
    return out, None
VIAS = [np.radians(v) for v in ([0, -160, 60, -140, 90, 0], [0, -150, 80, -130, 90, 0], [0, -120, 100, -110, 0, 0], [0, -135, 90, -135, 90, 0],
        [0, -110, 110, -90, -90, 0], [0, -100, 60, -60, -90, 0], [0, -140, 110, -150, 90, 0], [0, -165, 40, -120, 90, 0], [0, -125, 140, -105, -90, 0],
        [0, -90, 90, -90, -90, 0], [0, -150, 120, -150, 90, 0], [0, -170, 100, -200, 90, 0])]
for (f, h) in ((0.065 - 0.425, 0.300 + 0.55), (EX - 0.05, 1.15), (0.0, 1.2), (0.2, 1.0)):
    q = pose((f, 0, h), DOWN, XF, [])
    if q is not None: VIAS.append(q)
def route(a, b, it, extra, label, t0=0.0):
    bad = sweep(a, b, it, extra, t0=t0)
    if bad is None: return [], None
    vs = []
    for v in VIAS:
        v = np.array(v, float).copy(); v[5] = np.array(a)[5]; vs.append(v)
    for v in vs:
        if hit(v, it, extra) is None and sweep(a, v, it, extra, t0=t0) is None and sweep(v, b, it, extra) is None:
            return [v], f'{label}：まっすぐだと {bad[1]} に当たる → 途中の姿勢を1つ通る'
    for v in vs:
        if hit(v, it, extra) is not None or sweep(a, v, it, extra, t0=t0) is not None: continue
        for w in vs:
            if hit(w, it, extra) is None and sweep(v, w, it, extra) is None and sweep(w, b, it, extra) is None:
                return [v, w], f'{label}：まっすぐだと {bad[1]} に当たる → 途中の姿勢を2つ通る'
    qb = np.array(a) + (np.array(b) - np.array(a)) * bad[0]; tp = fk(qb)[2]; ta, tb = fk(np.array(a))[2], fk(np.array(b))[2]
    loc = lambda t: f'前 {-t[0]*1000:.0f}・右 {t[1]*1000:.0f}・高さ {(t[2]+BASE_H)*1000:.0f}'
    return None, f'{label}：途中（{bad[0]}）で {bad[1]} に当たる。通り道が見つからない（吸盤：始め {loc(ta)}／当たる所 {loc(tp)}／終わり {loc(tb)}）'
def dur(a, b): return round(max(0.45, float(np.abs(np.array(b) - np.array(a)).max()) / 1.4), 2)
TOUR = {}; PROBLEMS = []
GLOBAL = [i for st in TC.ORDER for i, it in enumerate(ITEMS) if it['st'] == st]
for stn in (ONLY or TC.ORDER):   # 置き場所を名前で渡すと、そこだけ計算する（確かめ用。結果は書き出す）
    ids = [i for i, it in enumerate(ITEMS) if it['st'] == stn]
    frames = []; prev = FOLD; say(f'■ {stn}')
    def add(q, ev=None, legal_from=None):
        frames.append([np.array(q).tolist(), dur(frames[-1][0] if frames else FOLD, q), ev])
    def go(a, b, it, extra, label, t0=0.0):
        vs, note = route(a, b, it, extra, label, t0)
        if note: say('  ' + note)
        if vs is None: PROBLEMS.append(f'{stn}：{note}'); vs = []
        for v in vs: add(v)
        add(b)
    for i in ids:
        it = ITEMS[i]
        ex = (STATION[stn] + [on_site(x, '在庫') for x in STOCK if x['st'] == stn] + [on_site(ITEMS[j], 'まだ取っていない物') for j in ids if j > i]
              + [in_box(j) for j in GLOBAL[:GLOBAL.index(i)]])
        w, d, h = TC.SIZES[it['k']]; tip = TC.tip_target(it); say(f' {i+1}. {it["k"]}（{w}×{d}×{h}）{"上の面を吸う" if it["grasp"] == "top" else "前の面を吸う"}')
        # つかむ
        if it['grasp'] == 'top':
            lift = 0.06 if stn in ('table', 'stand') else max(0.06, 0.351 - (tip[2] - h / 1000))
            pre_tip = (tip[0], tip[1], tip[2] + lift)
            qpre, down, e1 = first_chain(pose_list(pre_tip, DOWN, XF, ex, None, prev, front=True), pre_tip, tip, DOWN, XF, ex, None, 4)
            if down is None: PROBLEMS.append(f'{stn} {i+1}：{e1}'); say('  ' + e1); continue
            go(prev, qpre, None, ex, '前の姿勢 → つかむ前')
            for q in down: add(q)
            frames[-1][2] = f'grab:{i}'
            up, e2 = chain(down[-1], tip, pre_tip, DOWN, XF, ex, it, 3)
            if up is None:
                say('  持ち上げ：' + e2 + '（初めは置いてある面に触れているので、そこは見ない）')
                up = [q for q in reversed(down[:-1])] + [qpre]
            if stn in ('table', 'stand'):   # 持ち上げたら、となりの物から離れるように、まっすぐ手前へ 100mm 引く
                pb = (pre_tip[0] - 0.10, pre_tip[1], pre_tip[2]); mv, e6 = chain(up[-1], pre_tip, pb, DOWN, XF, ex, it, 3)
                if mv is None: say('  手前へ引く：' + e6)
                else:
                    up = up + mv
                    pc = (EX - 0.08, 0.0, pb[2]); mv2, e7 = chain(up[-1], pb, pc, DOWN, XF, ex, it, 4)   # 机の手前で、真ん中へ寄せる
                    if mv2 is not None: up = up + mv2
            for q in up: add(q)
            last = up[-1]
        else:
            out_tip = (tip[0] - 0.04, tip[1], tip[2]); qout = pose(out_tip, FWD, XR, ex, None, prev, front=True)
            if qout is None: PROBLEMS.append(f'{stn} {i+1}：棚の手前の姿勢が見つからない'); say('  棚の手前の姿勢が見つからない'); continue
            inn, e1 = chain(qout, out_tip, tip, FWD, XR, ex, None, 6)
            if inn is None: PROBLEMS.append(f'{stn} {i+1}：差し込み {e1}'); say('  差し込み：' + e1); continue
            go(prev, qout, None, ex, '前の姿勢 → 棚の手前')
            for q in inn: add(q)
            frames[-1][2] = f'grab:{i}'
            lt = (tip[0], tip[1], tip[2] + 0.008); up, e2 = chain(inn[-1], tip, lt, FWD, XR, ex, it, 1)
            if up is None: up = [inn[-1]]; say('  少し持ち上げ：' + e2)
            back_f = SF - 0.01 - d / 1000; bk = (back_f, tip[1], lt[2])   # 物の奥の面が棚の手前の面より 10mm 手前に出るまで引く
            outq, e3 = chain(up[-1], lt, bk, FWD, XR, ex, it, 6)
            if outq is None: PROBLEMS.append(f'{stn} {i+1}：引き抜き {e3}'); say('  引き抜き：' + e3); outq = []
            # 棚から離れる：棚の手前で、まっすぐ上へ 40mm、そのあと手前へ（腕が届く 400mm まで）
            seq = up + outq; p0 = bk
            for p1 in ((bk[0], bk[1], bk[2] + 0.04), (max(0.40, bk[0] - 0.06), bk[1], bk[2] + 0.04)):
                if p1 == p0 or not seq: continue
                mv, e5 = chain(seq[-1], p0, p1, FWD, XR, ex, it, 3)
                if mv is None: say('  棚から離れる：' + e5); break
                seq += mv; p0 = p1
            for q in seq: add(q)
            last = seq[-1]
        # コンテナへ
        (sx, sy, sz), c = TC.tool_box(it); b, r, rot = SLOTS[i]; XP = XR if rot else XF
        place_h = 0.017 + (c + sz / 2) / 1000
        ptip = (0.065 - b / 1000, r / 1000, U(0.398 + place_h) + BASE_H)
        for up_h in (0.25, 0.18, 0.12):      # 置く前の高さ。奥の置き場所は高いと届かないので、低くしていく
            ppre = (ptip[0], ptip[1], ptip[2] + up_h)
            qpp, pd, e4 = first_chain(pose_list(ppre, DOWN, XP, ex, it, last), ppre, ptip, DOWN, XP, ex, it, 4)
            if pd is not None: break
        if pd is None: PROBLEMS.append(f'{stn} {i+1}：置きに下りる {e4}'); say('  置きに下りる：' + e4); continue
        go(last, qpp, it, ex, '持ったまま → コンテナの上')
        for q in pd: add(q)
        frames[-1][2] = f'put:{i}'
        add(qpp); prev = qpp
        say(f'  つかむ {deg(down[-1] if it["grasp"] == "top" else inn[-1])}｜置く {deg(pd[-1])}')
    go(prev, FOLD, None, STATION[stn] + [on_site(x, '在庫') for x in STOCK if x['st'] == stn] + [in_box(j) for j in GLOBAL[:GLOBAL.index(ids[-1]) + 1]], '最後 → 畳む')
    frames[-1][2] = 'done'
    TOUR[stn] = dict(ids=ids, frames=frames); say(f'  動きの区切り {len(frames)}・かかる時間 約{sum(f[1] for f in frames):.0f}秒')
say('■ 結果：', '全部の物を、粗い当たりの範囲で続けて取れる' if not PROBLEMS else '取れない所がある：' + ' ／ '.join(PROBLEMS))
P.setdefault('tour', {}).update(TOUR); P['tour_items'] = ITEMS; P['tour_order'] = TC.ORDER; P['tour_slots'] = SLOTS
json.dump(P, open('page/arm_poses.json', 'w'), indent=1)
open('out_tour_poses.txt', 'w').write('\n'.join(LOG) + '\n')
