Spaces:
Running

hugging-space / src /warpField.ts
Chunte's picture
Chunte HF Staff
Hugging Partnership: v9 press arc test build
0a0ec90 verified
Raw History Blame Contribute Delete
13.8 kB
// Version 6 (reverted) — logo squish as one smooth push field. Kept for side-by-side comparison
// in the Version dropdown; the live engine is warp.ts.
//
//
// The logo is moved through one smooth push field (a soft warp of the space), not edge by
// edge: every logo point moves by the push at its location, so both sides of a stroke move
// together. Strokes bend and thin smoothly and can't develop wobbles, S-curves or kinks, and
// the field changes slowly enough across a stroke that the outline never folds over.
//
// 1. Edge push — inside Huggy, points are pushed away from Huggy's centre, strongest around
// the hug direction (Huggy → logo centre), easing in past the bend start (~0.15R inside the
// rim, from the Figma references). Logo edges facing Huggy dent into a
// round concave curve (Figma: Pydantic 32 px, OpenRouter 42 px, Fal 24 px deep).
// 2. Pocket push — where Huggy swells into a pocket (hole / gap), the swell pushes its
// surroundings outward with a smooth falloff, so the opening grows and a bar between two
// pockets bends as a whole instead of being pinched from both sides. It never pushes back
// toward Huggy's centre (that would fight the edge push and bend strokes into an S).
// Both grow with the global squish level (how deep the logo is in Huggy), up to their max.
// Implemented by warping the logo's own vector paths (any shape → cubic Béziers, subdivided).
import { BODY } from './huggy';
import { CLS_POCKET, type LogoSampler } from './logo';
import { parsePath, shapeToPath, type SubPath } from './pathdata';
export interface FieldParams {
strength: number; // max edge push in scene px
pocketStrength: number; // max pocket push in scene px
startDepth: number; // how far inside Huggy's rim the edge push starts (fraction of R)
zeroDeg: number; // the edge push fades (cosine) to nothing at this angle from the hug direction
fullDepth: number; // squish reaches full strength when the logo is this deep past the bend start (×R)
}
// Defaults from the designer's recorded sweet spots (Pydantic + Fal, 2026-11-06).
const DEFAULT_FIELD: FieldParams = {
strength: 30,
pocketStrength: 12,
startDepth: 0.14,
zeroDeg: 71,
fullDepth: 0.53,
};
const GEOMETRY = 'path,rect,circle,ellipse,line,polyline,polygon';
const SKIP_INSIDE = 'defs,clipPath,mask,pattern,marker,symbol';
const GEOMETRY_ATTRS = ['x', 'y', 'width', 'height', 'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'y1', 'x2', 'y2', 'points'];
interface Item {
el: SVGPathElement;
// Root-space (logo viewBox units) points: per subpath, start + 3 per segment.
pts: Float64Array[];
closed: boolean[];
toLocal: DOMMatrix; // root → element local
original: string;
}
export class FieldWarp {
private items: Item[] = [];
params: FieldParams = { ...DEFAULT_FIELD };
constructor(
root: SVGSVGElement,
private vbX: number,
private vbY: number,
maxDim: number,
) {
const rootCTM = root.getScreenCTM();
if (!rootCTM) return;
const rootInv = rootCTM.inverse();
const maxSeg = maxDim * 0.02; // subdivide so each piece is ≤ 2% of the logo size
for (const node of Array.from(root.querySelectorAll(GEOMETRY))) {
if (node.closest(SKIP_INSIDE)) continue;
const fill = getComputedStyle(node).fill;
// Stroke-only shapes can't be thinned by moving their centre line; leave them as is.
if (fill === 'none') continue;
const d = shapeToPath(node);
if (!d) continue;
let el: SVGPathElement;
if (node.tagName.toLowerCase() === 'path') {
el = node as SVGPathElement;
} else {
el = document.createElementNS('http://www.w3.org/2000/svg', 'path');
for (const a of Array.from(node.attributes)) {
if (!GEOMETRY_ATTRS.includes(a.name)) el.setAttribute(a.name, a.value);
}
el.setAttribute('d', d);
node.replaceWith(el);
}
const elCTM = el.getScreenCTM();
if (!elCTM) continue;
const toRoot = rootInv.multiply(elCTM);
const toLocal = toRoot.inverse();
const subs = parsePath(d);
const pts: Float64Array[] = [];
const closed: boolean[] = [];
for (const sp of subs) {
const arr = subdivide(sp, toRoot, maxSeg);
pts.push(arr);
closed.push(sp.closed);
}
this.items.push({ el, pts, closed, toLocal, original: d });
}
}
get count() {
return this.items.length;
}
/**
* Re-shape the logo for the current placement / hug amount. `bodyRadius(angle)` is Huggy's
* current (squished) outline radius, used to find where Huggy swells into a pocket.
*/
apply(
sampler: LogoSampler | null,
hug: number,
touching: Set<number>,
bodyRadius: (angle: number) => number,
squish = 1,
) {
const level = Math.max(0, Math.min(1, hug)) * Math.max(0, Math.min(1, squish));
if (!sampler || level < 0.002) {
for (const it of this.items) it.el.setAttribute('d', it.original);
return;
}
const s = sampler;
const field = new PushField(s, this.params, level, sampleSwell(s, bodyRadius), touching);
const pl = s.pl;
const cos = Math.cos(-pl.rot);
const sin = Math.sin(-pl.rot);
for (const it of this.items) {
const m = it.toLocal;
let d = '';
for (let k = 0; k < it.pts.length; k++) {
const arr = it.pts[k];
const count = arr.length / 2;
const sx = new Float64Array(count);
const sy = new Float64Array(count);
for (let j = 0; j < count; j++) {
const p = s.toScene(arr[2 * j] - this.vbX, arr[2 * j + 1] - this.vbY);
sx[j] = p.x;
sy[j] = p.y;
}
const { dx, dy } = smoothAlong(sx, sy, it.closed[k], (x, y) => field.at(x, y));
const out: string[] = [];
for (let j = 0; j < count; j++) {
const qx = arr[2 * j] + (cos * dx[j] - sin * dy[j]) / pl.scale;
const qy = arr[2 * j + 1] + (sin * dx[j] + cos * dy[j]) / pl.scale;
out.push(`${(m.a * qx + m.c * qy + m.e).toFixed(2)} ${(m.b * qx + m.d * qy + m.f).toFixed(2)}`);
}
d += `M${out[0]}`;
for (let j = 1; j + 2 < out.length; j += 3) d += `C${out[j]} ${out[j + 1]} ${out[j + 2]}`;
if (it.closed[k]) d += 'Z';
}
it.el.setAttribute('d', d);
}
}
}
function smooth01(v: number) {
const t = Math.max(0, Math.min(1, v));
return t * t * (3 - 2 * t);
}
interface SwellPt {
x: number;
y: number;
w: number; // 0..1 from the swell height there
}
const SWELL_SIGMA = 40; // px: how far the swell's push reaches
/** Points inside pockets where Huggy currently swells (beyond its rest circle). */
function sampleSwell(s: LogoSampler, bodyRadius: (angle: number) => number): SwellPt[] {
const R = BODY.r;
const pts: SwellPt[] = [];
for (let deg = 0; deg < 360; deg += 2) {
const th = (deg * Math.PI) / 180;
const r = bodyRadius(th);
const h = r - R;
if (h < 1.5) continue;
const w = smooth01(h / 20);
const c = Math.cos(th);
const sn = Math.sin(th);
for (const rr of [R - 25, R, r - 3]) {
const x = BODY.cx + c * rr;
const y = BODY.cy + sn * rr;
if (s.cls(x, y) === CLS_POCKET) pts.push({ x, y, w });
}
}
return pts;
}
/**
* The smooth push field. Its rises and falloffs are kept at least ~1.7× wider than the push
* itself, so the warp can't fold the outline over.
*/
class PushField {
private Rout = BODY.r + BODY.strokeWidth / 2;
private A: number;
private B: number;
private p0: number;
private rise: number;
private axis: number;
private zero: number;
constructor(
private s: LogoSampler,
p: FieldParams,
level: number,
private swell: SwellPt[],
private touching: Set<number>,
) {
this.A = p.strength * level;
this.B = p.pocketStrength * level;
this.p0 = p.startDepth * this.Rout;
// Wide, gentle ramp-in so the dent eases in instead of forming an elbow.
this.rise = Math.max(0.2 * this.Rout, 2.5 * this.A);
this.axis = Math.atan2(s.pl.cy - BODY.cy, s.pl.cx - BODY.cx);
this.zero = (p.zeroDeg * Math.PI) / 180;
}
at(x: number, y: number): { x: number; y: number } {
if (this.touching.size) {
// Only the logo pieces that touch Huggy move.
const n = this.s.normal(x, y);
const c = this.s.comp(x - n.x * 2, y - n.y * 2);
if (c >= 0 && !this.touching.has(c)) return { x: 0, y: 0 };
}
let vx = 0;
let vy = 0;
// Edge push: away from Huggy's centre, in a depth band past the bend start.
const rx = x - BODY.cx;
const ry = y - BODY.cy;
const dc = Math.hypot(rx, ry) || 1;
const pen = this.Rout - dc;
if (this.A > 0 && pen > this.p0) {
let da = Math.atan2(ry, rx) - this.axis;
while (da > Math.PI) da -= 2 * Math.PI;
while (da < -Math.PI) da += 2 * Math.PI;
const ang = Math.abs(da) >= this.zero ? 0 : 0.5 + 0.5 * Math.cos((Math.PI * Math.abs(da)) / this.zero);
// Ramps in past the bend start, then holds (no deep fade: a logo pushed further in must
// keep squishing at least as hard — the global squish rule).
const band = smooth01((pen - this.p0) / this.rise);
const mag = this.A * band * ang;
vx += (rx / dc) * mag;
vy += (ry / dc) * mag;
}
// Pocket push: away from where Huggy swells into a pocket, Gaussian falloff.
if (this.B > 0 && this.swell.length) {
const cut = (3 * SWELL_SIGMA) ** 2;
let peak = 0;
let ux = 0;
let uy = 0;
for (const p of this.swell) {
const dx = x - p.x;
const dy = y - p.y;
const d2 = dx * dx + dy * dy;
if (d2 > cut) continue;
const g = Math.exp(-d2 / (2 * SWELL_SIGMA * SWELL_SIGMA)) * p.w;
peak = Math.max(peak, g);
const d = Math.sqrt(d2) + 8;
ux += (dx / d) * g;
uy += (dy / d) * g;
}
const ul = Math.hypot(ux, uy);
if (peak > 0 && ul > 1e-6) {
let px = (ux / ul) * this.B * peak;
let py = (uy / ul) * this.B * peak;
// Never push back toward Huggy's centre: that would fight the edge push on the same
// stroke and bend it into an S. The opening grows by its far / side walls giving way.
const ox = rx / dc;
const oy = ry / dc;
const radial = px * ox + py * oy;
if (radial < 0) {
px -= radial * ox;
py -= radial * oy;
}
vx += px;
vy += py;
}
}
return { x: vx, y: vy };
}
}
/** Push vectors for one outline, lightly smoothed along it (cleans up control points). */
function smoothAlong(sx: Float64Array, sy: Float64Array, closed: boolean, push: (x: number, y: number) => { x: number; y: number }) {
const count = sx.length;
const dx = new Float64Array(count);
const dy = new Float64Array(count);
const dup = closed && count > 1 && Math.hypot(sx[count - 1] - sx[0], sy[count - 1] - sy[0]) < 1e-6;
const U = dup ? count - 1 : count;
const vx = new Float64Array(U);
const vy = new Float64Array(U);
for (let k = 0; k < U; k++) {
const v = push(sx[k], sy[k]);
vx[k] = v.x;
vy[k] = v.y;
}
const idx = (k: number) => (closed ? ((k % U) + U) % U : k);
const seg = new Float64Array(U);
for (let k = 0; k < U; k++) {
const j = idx(k + 1);
seg[k] = closed || k < U - 1 ? Math.hypot(sx[j] - sx[k], sy[j] - sy[k]) : 0;
}
const SIGMA = 6;
const W = SIGMA * 3;
for (let k = 0; k < U; k++) {
let ax = vx[k];
let ay = vy[k];
let ws = 1;
for (const dir of [-1, 1] as const) {
let dist = 0;
let prev = k;
for (let o = 1; o < U; o++) {
const raw = k + dir * o;
if (!closed && (raw < 0 || raw >= U)) break;
const j = idx(raw);
dist += dir === 1 ? seg[prev] : seg[j];
prev = j;
if (dist > W) break;
const w = Math.exp(-(dist * dist) / (2 * SIGMA * SIGMA));
ax += vx[j] * w;
ay += vy[j] * w;
ws += w;
}
}
dx[k] = ax / ws;
dy[k] = ay / ws;
}
if (dup) {
dx[count - 1] = dx[0];
dy[count - 1] = dy[0];
}
return { dx, dy };
}
function subdivide(sp: SubPath, toRoot: DOMMatrix, maxSeg: number): Float64Array {
const pts: number[] = [];
const tr = (x: number, y: number) => [toRoot.a * x + toRoot.c * y + toRoot.e, toRoot.b * x + toRoot.d * y + toRoot.f];
let [px, py] = tr(sp.x0, sp.y0);
pts.push(px, py);
for (const seg of sp.segs) {
const [c1x, c1y] = tr(seg[0], seg[1]);
const [c2x, c2y] = tr(seg[2], seg[3]);
const [ex, ey] = tr(seg[4], seg[5]);
const len = Math.hypot(c1x - px, c1y - py) + Math.hypot(c2x - c1x, c2y - c1y) + Math.hypot(ex - c2x, ey - c2y);
const n = Math.max(1, Math.min(64, Math.ceil(len / maxSeg)));
// Split the cubic into n equal-parameter pieces.
let a0x = px, a0y = py, a1x = c1x, a1y = c1y, a2x = c2x, a2y = c2y;
const a3x = ex, a3y = ey;
for (let i = 0; i < n; i++) {
const t = 1 / (n - i);
if (i === n - 1) {
pts.push(a1x, a1y, a2x, a2y, a3x, a3y);
break;
}
// de Casteljau at t on the remaining curve.
const b0x = a0x + (a1x - a0x) * t, b0y = a0y + (a1y - a0y) * t;
const b1x = a1x + (a2x - a1x) * t, b1y = a1y + (a2y - a1y) * t;
const b2x = a2x + (a3x - a2x) * t, b2y = a2y + (a3y - a2y) * t;
const c0x = b0x + (b1x - b0x) * t, c0y = b0y + (b1y - b0y) * t;
const c1x2 = b1x + (b2x - b1x) * t, c1y2 = b1y + (b2y - b1y) * t;
const mx = c0x + (c1x2 - c0x) * t, my = c0y + (c1y2 - c0y) * t;
pts.push(b0x, b0y, c0x, c0y, mx, my);
a0x = mx; a0y = my; a1x = c1x2; a1y = c1y2; a2x = b2x; a2y = b2y;
}
px = ex;
py = ey;
}
return new Float64Array(pts);
}