import { V as h, b as N, c as g, N as k, A as w } from "../../../../three.module-BPupfU8l.js";
import { a as f } from "../../../../three-vrm.module-BuztCP2r.js";
import T from "../vrm-ik-handler.js";
import { convert as b } from "./vmdtovrm.js";
function R(n, e) {
  return b(n, e ? z(e) : void 0);
}
function z(n) {
  const { humanoid: e } = n;
  if (!e)
    throw new Error("VRM does not have humanoid");
  const o = e.getNormalizedPose();
  e.resetNormalizedPose();
  const t = e.getNormalizedBoneNode(f.Hips), r = e.getNormalizedBoneNode(f.LeftFoot), i = e.getNormalizedBoneNode(f.LeftToes), s = e.getNormalizedBoneNode(f.RightFoot), u = e.getNormalizedBoneNode(f.RightToes);
  return e.setNormalizedPose(o), {
    hipsOffset: m(t, t),
    leftFootOffset: m(t, r),
    leftToeOffset: m(r, i),
    rightFootOffset: m(t, s),
    rightToeOffset: m(s, u)
  };
}
const V = new h();
function m(n, e) {
  if (!n || !e)
    return;
  let o = e;
  const t = [e];
  for (; o.parent && o !== n; )
    t.push(o.parent), o = o.parent;
  if (o == null)
    return;
  t.reverse();
  const r = V.set(0, 0, 0);
  for (const i of t)
    r.add(i.position);
  return r.toArray();
}
function y(n, e) {
  var t, r;
  const o = [];
  for (const { type: i, name: s, isIK: u, times: l, values: d } of n.timelines) {
    let a;
    switch (i) {
      case "morph": {
        const c = (t = e.expressionManager) == null ? void 0 : t.getExpressionTrackName(s);
        if (!c)
          continue;
        a = c;
        break;
      }
      case "position":
      case "rotation": {
        if (u) {
          const p = T.get(e).getAndEnableIK(s);
          if (!p)
            continue;
          a = p.name;
        } else {
          const c = (r = e.humanoid) == null ? void 0 : r.getNormalizedBone(
            s
          );
          if (!c)
            continue;
          a = c.node.name;
        }
        break;
      }
      default:
        continue;
    }
    switch (i) {
      case "morph":
        o.push(new k(a, l, d));
        break;
      case "position":
        o.push(
          new g(`${a}.position`, l, d)
        );
        break;
      case "rotation":
        o.push(
          new N(`${a}.quaternion`, l, d)
        );
        break;
    }
  }
  return new w(`clip${Date.now()}`, n.duration, o);
}
export {
  y as bindToVRM,
  R as convert,
  z as toOffset
};
