☰

omoggle-fluox

source-level landmark morph for omoggle face scoring

您需要先安裝使用者腳本管理器擴展,如 Tampermonkey、Greasemonkey 或 Violentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey 或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Userscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         omoggle-fluox
// @namespace    https://omoggle.com
// @version      1.0.0
// @description  source-level landmark morph for omoggle face scoring
// @match        https://omoggle.com/*
// @match        https://*.omoggle.com/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function () {
  'use strict';

  // ─── tunables ────────────────────────────────────────────────────────────────
  const DEFAULT_STRENGTH = 0.72; // 0 = no effect, 1 = full ideal geometry
  const TARGETS = {
    canthalTilt:    4.25,   // degrees; positive = outer corner up
    eyeAspect:      0.26,   // vertical gap / eye width
    jawRatio:       0.68,   // jaw width / face height
    cheekRatio:     1.14,   // cheek width / jaw width
    midfaceRatio:   0.305,  // |lip_y - eyeLine_y| / face height
  };

  // 19 symmetric pairs for symmetry metric (left idx, right idx)
  // derived from MediaPipe 468-point canonical map
  const SYM_PAIRS = [
    [33, 263], [130, 359], [160, 387], [158, 385],
    [153, 380], [144, 373], [145, 374], [246, 466],
    [7,   249], [163, 390], [61,  291], [185, 409],
    [40,  270], [39,  269], [37,  267], [0,   17 ],
    [57,  287], [146, 375], [91,  321],
  ];

  // ─── helpers ─────────────────────────────────────────────────────────────────
  const dist  = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
  const angle = (a, b) => Math.atan2(b.y - a.y, b.x - a.x) * 180 / Math.PI;
  const lerp  = (a, b, t) => a + (b - a) * t;
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

  /**
   * Rotate point `p` around center `c` by `deg` degrees.
   */
  function rotate(p, c, deg) {
    const r = deg * Math.PI / 180;
    const cos = Math.cos(r), sin = Math.sin(r);
    const dx = p.x - c.x, dy = p.y - c.y;
    return { x: c.x + dx * cos - dy * sin, y: c.y + dx * sin + dy * cos, z: p.z };
  }

  /**
   * Project raw landmark to aspect-corrected, de-rotated p-space.
   * aspect `i` = videoW / videoH, roll `roll`, nose center `nose`.
   */
  function toP(raw, i, roll, nose) {
    const stretched = { x: raw.x * i, y: raw.y, z: raw.z };
    return rotate(stretched, { x: nose.x * i, y: nose.y }, -roll);
  }

  /**
   * Invert p-space back to raw normalized coordinates.
   */
  function fromP(p, i, roll, nose) {
    const noseP = { x: nose.x * i, y: nose.y };
    const unrot = rotate(p, noseP, roll);
    return { x: unrot.x / i, y: unrot.y, z: unrot.z };
  }

  // ─── morph ───────────────────────────────────────────────────────────────────
  function morphLandmarks(lm, videoW, videoH, strength) {
    if (!lm || lm.length < 468) return lm;

    const i    = videoW / videoH;
    const roll = angle({ x: lm[10].x * i, y: lm[10].y },
                       { x: lm[152].x * i, y: lm[152].y }) - 90;
    const nose = lm[1]; // used as rotation center

    // deep-clone only the points we will touch so the blend is clean
    const out = lm.map(p => ({ x: p.x, y: p.y, z: p.z }));

    // helper: get p-space coord, mutate, write back through fromP, blend
    function adjust(idx, mutator) {
      const orig = { x: lm[idx].x, y: lm[idx].y, z: lm[idx].z };
      const pOrig = toP(orig, i, roll, nose);
      const pNew  = mutator({ ...pOrig });
      const rawNew = fromP(pNew, i, roll, nose);
      out[idx].x = lerp(orig.x, rawNew.x, strength);
      out[idx].y = lerp(orig.y, rawNew.y, strength);
      out[idx].z = lerp(orig.z, rawNew.z, strength);
    }

    // ── 1. canthal tilt ──────────────────────────────────────────────────────
    // rotate each eye-corner line so its signed angle = TARGETS.canthalTilt
    // left eye: inner 133, outer 33 → outer should sit higher (lower y)
    // right eye: inner 362, outer 263
    for (const [inner, outer] of [[133, 33], [362, 263]]) {
      const pInner = toP(lm[inner], i, roll, nose);
      const pOuter = toP(lm[outer], i, roll, nose);
      const currentAngle = angle(pInner, pOuter);           // degrees
      const targetAngle  = -TARGETS.canthalTilt;            // negative = outer up in image coords
      const delta        = targetAngle - currentAngle;
      adjust(outer, p => rotate(p, pInner, delta));
    }

    // ── 2. eye aspect ratio ──────────────────────────────────────────────────
    // set vertical lid gap = TARGETS.eyeAspect * eye_width for each eye
    // left eye: width landmarks 33/133, vertical 159 (upper) / 145 (lower)
    // right eye: width landmarks 362/263, vertical 386 (upper) / 374 (lower)
    for (const [l, r, up, dn] of [[33, 133, 159, 145], [362, 263, 386, 374]]) {
      const pL = toP(lm[l], i, roll, nose);
      const pR = toP(lm[r], i, roll, nose);
      const eyeWidth  = dist(pL, pR);
      const targetGap = TARGETS.eyeAspect * eyeWidth;
      const midY = (toP(lm[up], i, roll, nose).y + toP(lm[dn], i, roll, nose).y) / 2;
      adjust(up, p => ({ ...p, y: midY - targetGap / 2 }));
      adjust(dn, p => ({ ...p, y: midY + targetGap / 2 }));
    }

    // ── 3. jaw width ─────────────────────────────────────────────────────────
    // jawWidth = maxJawPairDist / faceHeight(10,152)
    // jaw points: 172, 397, 150, 379, 171, 396 (symmetric pairs)
    const pTop    = toP(lm[10],  i, roll, nose);
    const pBottom = toP(lm[152], i, roll, nose);
    const faceH   = dist(pTop, pBottom);
    const faceMidX = (pTop.x + pBottom.x) / 2;

    const jawPairs = [[172, 397], [150, 379], [171, 396]];
    for (const [lj, rj] of jawPairs) {
      const pLj = toP(lm[lj], i, roll, nose);
      const pRj = toP(lm[rj], i, roll, nose);
      const currentHalf = (pRj.x - pLj.x) / 2;
      const targetHalf  = (TARGETS.jawRatio * faceH) / 2;
      const scale = currentHalf === 0 ? 1 : targetHalf / currentHalf;
      adjust(lj, p => ({ ...p, x: faceMidX - (faceMidX - p.x) * scale }));
      adjust(rj, p => ({ ...p, x: faceMidX + (p.x - faceMidX) * scale }));
    }

    // ── 4. cheekbone width ───────────────────────────────────────────────────
    // cheekWidth(234,454) / jawWidth → TARGETS.cheekRatio
    // first measure the (now-adjusted) jaw width
    const pLJaw = toP(out[150], i, roll, nose);
    const pRJaw = toP(out[379], i, roll, nose);
    const jawW   = dist(pLJaw, pRJaw);
    const targetCheekW = TARGETS.cheekRatio * jawW;
    const pLChk = toP(lm[234], i, roll, nose);
    const pRChk = toP(lm[454], i, roll, nose);
    const currentCheekW = dist(pLChk, pRChk);
    const cheekScale = currentCheekW === 0 ? 1 : targetCheekW / currentCheekW;
    adjust(234, p => ({ ...p, x: faceMidX - (faceMidX - p.x) * cheekScale }));
    adjust(454, p => ({ ...p, x: faceMidX + (p.x - faceMidX) * cheekScale }));

    // ── 5. midface ratio ─────────────────────────────────────────────────────
    // |lip(0).y - eyeLineY| / faceHeight → TARGETS.midfaceRatio
    const pLeft  = toP(lm[33],  i, roll, nose);
    const pRight = toP(lm[263], i, roll, nose);
    const eyeLineY   = (pLeft.y + pRight.y) / 2;
    const targetLipY = eyeLineY + TARGETS.midfaceRatio * faceH;
    adjust(0, p => ({ ...p, y: targetLipY }));

    // ── 6. symmetry ──────────────────────────────────────────────────────────
    // equalize each of the 19 symmetric pairs about the face vertical axis
    for (const [l, r] of SYM_PAIRS) {
      const pL = toP(out[l], i, roll, nose); // use out[] so prior adjustments count
      const pR = toP(out[r], i, roll, nose);
      const midX = (pL.x + pR.x) / 2;
      const midY = (pL.y + pR.y) / 2;
      const halfDX = Math.abs(pL.x - pR.x) / 2;
      const halfDY = Math.abs(pL.y - pR.y) / 2;
      // left point should be to the left of center
      const newPL = { ...pL, x: midX - halfDX, y: midY + halfDY };
      const newPR = { ...pR, x: midX + halfDX, y: midY - halfDY };
      const rawPL = fromP(newPL, i, roll, nose);
      const rawPR = fromP(newPR, i, roll, nose);
      out[l].x = lerp(out[l].x, rawPL.x, strength);
      out[l].y = lerp(out[l].y, rawPL.y, strength);
      out[r].x = lerp(out[r].x, rawPR.x, strength);
      out[r].y = lerp(out[r].y, rawPR.y, strength);
    }

    return out;
  }

  // ─── hook ────────────────────────────────────────────────────────────────────
  let _strength  = DEFAULT_STRENGTH;
  let _framesMorphed = 0;
  let _hooked    = false;
  let _lastError = null;
  let _ops = {
    tilt: true, eyeAspect: true, jaw: true,
    cheekbone: true, midface: true, symmetry: true,
  };

  // We intercept the webpack module system to reach FaceLandmarker before the
  // app does. Omoggle bundles MediaPipe inline — hooking the prototype works
  // even before the class name is exposed globally.

  function hookFaceLandmarker(FL) {
    if (!FL || !FL.prototype || typeof FL.prototype.detectForVideo !== 'function') return false;
    const original = FL.prototype.detectForVideo;
    FL.prototype.detectForVideo = function (video, ts, ...rest) {
      const result = original.call(this, video, ts, ...rest);
      try {
        if (result?.faceLandmarks?.[0]?.length >= 468) {
          const w = video.videoWidth  || 640;
          const h = video.videoHeight || 480;
          result.faceLandmarks[0] = morphLandmarks(result.faceLandmarks[0], w, h, _strength);
          _framesMorphed++;
        }
      } catch (e) {
        _lastError = e?.message ?? String(e);
      }
      return result;
    };
    _hooked = true;
    return true;
  }

  // Patch webpack __webpack_require__ to intercept the MediaPipe Vision module
  // the moment it is first evaluated.
  const _originalDefineProperty = Object.defineProperty.bind(Object);
  let _patchAttempted = false;

  function tryPatchWebpack() {
    if (_patchAttempted) return;
    // Omoggle's bundle exposes webpackChunk_N_E or similar on window
    const chunkKey = Object.keys(window).find(k => k.startsWith('webpackChunk'));
    if (!chunkKey) return;
    _patchAttempted = true;

    const originalPush = window[chunkKey].push.bind(window[chunkKey]);
    window[chunkKey].push = function (chunk) {
      const result = originalPush(chunk);
      // After each chunk loads, scan for FaceLandmarker in module cache
      if (!_hooked) {
        try {
          // __webpack_require__.c is the module cache (object of module objects)
          const req = window.__webpack_require__;
          if (req?.c) {
            for (const mod of Object.values(req.c)) {
              const exp = mod?.exports;
              if (!exp) continue;
              // FaceLandmarker may be a named export or default
              for (const val of Object.values(exp)) {
                if (typeof val === 'function' && val.prototype?.detectForVideo) {
                  hookFaceLandmarker(val);
                  break;
                }
              }
              if (_hooked) break;
            }
          }
        } catch (_) {}
      }
      return result;
    };
  }

  // Also try a direct global scan every 500 ms until hooked (handles lazy loads)
  function scanForFaceLandmarker() {
    if (_hooked) return;
    tryPatchWebpack();
    // Check if it leaked to window (some builds do)
    for (const key of Object.keys(window)) {
      const v = window[key];
      if (typeof v === 'function' && v.prototype?.detectForVideo) {
        hookFaceLandmarker(v);
        return;
      }
    }
  }

  const _scanInterval = setInterval(scanForFaceLandmarker, 500);
  // Stop scanning 30 s after hook lands (or give up)
  setTimeout(() => clearInterval(_scanInterval), 30_000);

  // ─── console API ─────────────────────────────────────────────────────────────
  window.__fluox = {
    get strength() { return _strength; },
    setStrength(v) { _strength = clamp(v, 0, 1); },
    bump(delta)    { _strength = clamp(_strength + delta, 0, 1); },
    reset()        { _strength = DEFAULT_STRENGTH; },
    get ops()      { return _ops; },
    get targets()  { return { ...TARGETS }; },
    diagnose() {
      return {
        hooked:       _hooked,
        strength:     _strength,
        framesMorphed: _framesMorphed,
        lastError:    _lastError,
        ops:          { ..._ops },
      };
    },
  };

  // ─── keyboard controls ───────────────────────────────────────────────────────
  document.addEventListener('keydown', e => {
    if (e.key === '=' || e.key === '+') { window.__fluox.bump(+0.05); }
    if (e.key === '-' || e.key === '_') { window.__fluox.bump(-0.05); }
    if (e.key === '0')                  { window.__fluox.reset(); }
  }, true);

  // mobile: tap left/right 10% of screen
  document.addEventListener('touchend', e => {
    const x = e.changedTouches[0]?.clientX ?? 0;
    const w = window.innerWidth;
    if (x < w * 0.1)       window.__fluox.bump(-0.05);
    else if (x > w * 0.9)  window.__fluox.bump(+0.05);
  }, true);

})();