/** * Rig "chibi" procedural: cuerpo esférico dominante, manos y pies cortos separados, cara 3D * (ojos con reflejo, cejas, boca por expresión, mejillas), accesorios y animación procedural * sin clips. Implementa exactamente el contrato de ./types. * * Jerarquía: root → inner (escala = size, temblor) → lean (inclinación en pantalla) * ├─ pivot (giro Y 3/4 hacia `facing`) → body (squash, bote) → malla, cara, accesorios * └─ limbs (giro Y suave) → manos, pies (en "espacio de avance": +x = hacia donde mira) */ import * as THREE from 'three'; import { toonMaterial } from '../render/materials'; import { emojiMesh, emojiTexture } from '../render/emoji'; import { glyphInfo, glyphSphere, onGlyphRefresh } from './emojiFace'; import { buildOutfit, type OutfitId, type OutfitInst } from './outfits'; import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'; import type { Accessory, ChibiAnim, ChibiMotion, ChibiOptions, ChibiRig, Expression, } from './types'; // ───────────────────────────── Cachés compartidas ───────────────────────────── const geoCache = new Map(); const matCache = new Map(); function geo(key: string, make: () => THREE.BufferGeometry): THREE.BufferGeometry { let g = geoCache.get(key); if (!g) { g = make(); g.userData.shared = true; geoCache.set(key, g); } return g; } function smat(key: string, make: () => THREE.Material): THREE.Material { let m = matCache.get(key); if (!m) { m = make(); m.userData.shared = true; matCache.set(key, m); } return m; } const R = 0.5; // radio del cuerpo a size = 1 const BODY_SY = 0.95; /** Altura (en radio unidad) a la que se corta la suela del zapato. */ const SOLE_Y = 0.5; /** Escala de manos y zapatos respecto al cuerpo (diámetro 1). */ const HAND: [number, number, number] = [0.172, 0.164, 0.166]; const SHOE: [number, number, number] = [0.215, 0.2, 0.3]; const G = { sphere: () => geo('sphere', () => new THREE.SphereGeometry(1, 20, 14)), body: () => geo('body', () => new THREE.SphereGeometry(R, 40, 28)), hand: () => geo('hand', () => new THREE.SphereGeometry(1, 20, 14)), /** Zapato integrado: elipsoide con la base cortada en plano (la suela). Unidad: radio 1, suela en y = -SOLE_Y. */ shoe: () => geo('shoe', () => { const g = new THREE.SphereGeometry(1, 28, 20); const p = g.attributes.position; for (let i = 0; i < p.count; i++) { const y = p.getY(i); if (y < -SOLE_Y) p.setY(i, -SOLE_Y); // empeine: un poco más alto y redondo hacia la puntera else if (p.getZ(i) > 0) p.setY(i, y * (1 + 0.12 * p.getZ(i))); } g.computeVertexNormals(); return g; }), sole: () => geo('sole', () => { const g = new THREE.CircleGeometry(Math.sqrt(1 - SOLE_Y * SOLE_Y) * 0.985, 28); g.rotateX(Math.PI / 2); g.translate(0, -SOLE_Y - 0.004, 0); return g; }), /** Mano abierta con dedos (🤗): palma + cuatro dedos + pulgar, en unidades de radio 1. */ openHand: () => geo('openHand', () => { const parts: THREE.BufferGeometry[] = []; const palm = new THREE.SphereGeometry(1, 18, 12); palm.scale(0.95, 1, 0.6); parts.push(palm); const angs = [-0.6, -0.2, 0.2, 0.6]; for (let i = 0; i < 4; i++) { const f = new THREE.CapsuleGeometry(0.27, 0.75, 4, 10); f.scale(1, 1, 0.8); f.translate(0, 1.05, 0); f.rotateZ(-angs[i]); parts.push(f); } const th = new THREE.CapsuleGeometry(0.28, 0.5, 4, 10); th.translate(0, 0.75, 0); th.rotateZ(1.35); parts.push(th); const m = mergeGeometries(parts.map((q) => q.toNonIndexed())); m.computeVertexNormals(); return m; }), arc: (r: number, tube: number, arc: number) => geo(`arc${r}|${tube}|${arc}`, () => new THREE.TorusGeometry(r, tube, 8, 20, arc)), capsule: (r: number, len: number) => geo(`cap${r}|${len}`, () => new THREE.CapsuleGeometry(r, len, 4, 8)), extrude: (key: string, shape: () => THREE.Shape, depth: number, bevel: number) => geo(`ex:${key}`, () => { const g = new THREE.ExtrudeGeometry(shape(), { depth, bevelEnabled: true, bevelThickness: bevel, bevelSize: bevel, bevelSegments: 3, curveSegments: 16, }); g.center(); return g; }), }; function roundedRect(w: number, h: number, r: number): THREE.Shape { const s = new THREE.Shape(); const x = -w / 2, y = -h / 2; s.moveTo(x + r, y); s.lineTo(x + w - r, y); s.quadraticCurveTo(x + w, y, x + w, y + r); s.lineTo(x + w, y + h - r); s.quadraticCurveTo(x + w, y + h, x + w - r, y + h); s.lineTo(x + r, y + h); s.quadraticCurveTo(x, y + h, x, y + h - r); s.lineTo(x, y + r); s.quadraticCurveTo(x, y, x + r, y); return s; } function heartShape(): THREE.Shape { const s = new THREE.Shape(); s.moveTo(0, -0.075); s.bezierCurveTo(-0.02, -0.055, -0.085, -0.015, -0.085, 0.03); s.bezierCurveTo(-0.085, 0.075, -0.03, 0.09, 0, 0.05); s.bezierCurveTo(0.03, 0.09, 0.085, 0.075, 0.085, 0.03); s.bezierCurveTo(0.085, -0.015, 0.02, -0.055, 0, -0.075); return s; } function mouthOpenShape(): THREE.Shape { // "D" invertida: borde superior casi recto, fondo redondo. const s = new THREE.Shape(); const w = 0.13; s.moveTo(-w, 0.01); s.quadraticCurveTo(0, 0.035, w, 0.01); s.absarc(0, 0.01, w, 0, -Math.PI, true); return s; } const M = { eye: () => smat('eye', () => toonMaterial({ color: 0x3b1e0d, gloss: 0.55, rim: 0 })), line: () => smat('line', () => toonMaterial({ color: 0x3b1e0d, gloss: 0.4, rim: 0 })), eyeRobot: () => smat('eyeRobot', () => toonMaterial({ color: 0x7ff3ff, emissive: 0x3ee6ff, emissiveIntensity: 1.6, gloss: 0.6 })), white: () => smat('white', () => toonMaterial({ color: 0xffffff, emissive: 0xffffff, emissiveIntensity: 0.6, gloss: 0.4 })), brow: () => smat('brow', () => toonMaterial({ color: 0x3b1e0d, gloss: 0.4, rim: 0 })), mouth: () => smat('mouth', () => toonMaterial({ color: 0x6e1a1e, gloss: 0.7 })), tongue: () => smat('tongue', () => toonMaterial({ color: 0xff6f86, gloss: 0.7 })), teeth: () => smat('teeth', () => toonMaterial({ color: 0xfbfbff, gloss: 0.8 })), heart: () => smat('heart', () => toonMaterial({ color: 0xff2f55, emissive: 0xff1040, emissiveIntensity: 0.35, gloss: 1 })), cheek: () => smat('cheek', () => toonMaterial({ color: 0xff6f8a, gloss: 0.2, transparent: true, opacity: 0.55 })), alienEye: () => smat('alienEye', () => toonMaterial({ color: 0x0b0d1a, gloss: 1, rim: 0.9 })), glasses: () => smat('glasses', () => toonMaterial({ color: 0x15151c, gloss: 1, rim: 0.8 })), ice: () => smat('ice', () => toonMaterial({ color: 0xc6efff, emissive: 0x58c8ff, emissiveIntensity: 0.45, gloss: 1, transparent: true, opacity: 0.88 })), flame: () => smat('flame', () => toonMaterial({ color: 0xff7a1a, emissive: 0xff5200, emissiveIntensity: 1.3, gloss: 0.3 })), flameCore: () => smat('flameCore', () => toonMaterial({ color: 0xffe14a, emissive: 0xffc400, emissiveIntensity: 1.5, gloss: 0.3 })), earBlue: () => smat('earBlue', () => toonMaterial({ color: 0x2f7ee6, gloss: 0.8 })), metal: () => smat('metal', () => toonMaterial({ color: 0xc9cfe0, gloss: 0.9 })), dark: () => smat('dark', () => toonMaterial({ color: 0x1b2340, gloss: 1 })), glow: () => smat('glow', () => toonMaterial({ color: 0x8ff6ff, emissive: 0x3ee6ff, emissiveIntensity: 1.5 })), starEdge: () => smat('starEdge', () => toonMaterial({ color: 0xe8720c, gloss: 0.5, rim: 0 })), gold: () => smat('gold', () => toonMaterial({ color: 0xffd23a, emissive: 0xffa800, emissiveIntensity: 0.35, gloss: 1 })), halo: () => smat('halo', () => toonMaterial({ color: 0xfff3a0, emissive: 0xffe066, emissiveIntensity: 1.4 })), horn: () => smat('horn', () => toonMaterial({ color: 0x8e2bd6, gloss: 0.8 })), hat: () => smat('hat', () => toonMaterial({ color: 0x3b2fb8, gloss: 0.6 })), bow: () => smat('bow', () => toonMaterial({ color: 0xff5fa8, gloss: 0.8 })), alien: () => smat('alien', () => toonMaterial({ color: 0x7dff4a, emissive: 0x3cff20, emissiveIntensity: 0.6 })), gem: () => smat('gem', () => toonMaterial({ color: 0xff3a6a, emissive: 0xff2050, emissiveIntensity: 0.6, gloss: 1 })), }; function mesh(g: THREE.BufferGeometry, m: THREE.Material, shadow = false): THREE.Mesh { const o = new THREE.Mesh(g, m); o.castShadow = shadow; return o; } /** Ancla orientada hacia fuera sobre la esfera (az: giro horizontal, el: elevación). */ function anchor(az: number, el: number, push = 0, radius = R): THREE.Group { const a = new THREE.Group(); const d = new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)); a.position.copy(d).multiplyScalar(radius + push); a.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), d); return a; } // ───────────────────────────── Expresiones ───────────────────────────── type EyeKind = 'oval' | 'happy' | 'closed' | 'x' | 'heart' | 'star' | 'alien'; type MouthKind = 'open' | 'smile' | 'neutral' | 'frown' | 'smirk' | 'teeth' | 'o' | 'grin'; interface ExprDef { l: EyeKind; r: EyeKind; mouth: MouthKind; /** Ángulo de cejas: > 0 en V (enfado), < 0 preocupación; null = sin cejas. */ brow: number | null; browY?: number; cheeks: boolean; eyeScale?: number; eyeSquint?: number; tongue?: boolean; mouthScale?: number; } const EXPR: Record = { happy: { l: 'happy', r: 'happy', mouth: 'open', brow: null, cheeks: true, tongue: true }, smile: { l: 'oval', r: 'oval', mouth: 'smile', brow: null, cheeks: false }, neutral: { l: 'oval', r: 'oval', mouth: 'neutral', brow: 0, cheeks: false }, angry: { l: 'oval', r: 'oval', mouth: 'frown', brow: 0.55, browY: -0.03, cheeks: false, eyeSquint: 0.8 }, cool: { l: 'oval', r: 'oval', mouth: 'smirk', brow: null, cheeks: false }, cold: { l: 'oval', r: 'oval', mouth: 'teeth', brow: -0.35, cheeks: false, eyeScale: 0.9 }, hurt: { l: 'x', r: 'x', mouth: 'o', brow: null, cheeks: false }, surprised: { l: 'oval', r: 'oval', mouth: 'o', brow: -0.1, browY: 0.04, cheeks: false, eyeScale: 1.15 }, sad: { l: 'oval', r: 'oval', mouth: 'frown', brow: -0.45, cheeks: false }, sleepy: { l: 'closed', r: 'closed', mouth: 'o', brow: null, cheeks: true }, love: { l: 'heart', r: 'heart', mouth: 'open', brow: null, cheeks: false, tongue: true }, evil: { l: 'oval', r: 'oval', mouth: 'grin', brow: 0.5, cheeks: false, eyeSquint: 0.7 }, wink: { l: 'oval', r: 'happy', mouth: 'smile', brow: null, cheeks: true }, hug: { l: 'happy', r: 'happy', mouth: 'open', brow: null, cheeks: true, tongue: true }, determined: { l: 'oval', r: 'oval', mouth: 'smile', brow: 0.28, cheeks: false }, blush: { l: 'happy', r: 'happy', mouth: 'smile', brow: null, cheeks: true }, starstruck: { l: 'star', r: 'star', mouth: 'open', brow: null, cheeks: false, tongue: true }, alien: { l: 'alien', r: 'alien', mouth: 'smirk', brow: null, cheeks: false }, fierce: { l: 'oval', r: 'oval', mouth: 'open', brow: 0.5, browY: -0.035, cheeks: false, tongue: true, mouthScale: 0.62 }, laugh: { l: 'happy', r: 'happy', mouth: 'open', brow: null, cheeks: false, tongue: true }, }; // ───────────────────────────── Animaciones ───────────────────────────── const LOCO = new Set(['idle', 'run', 'jump', 'fall', 'land']); const DUR: Partial> = { land: 0.2, attack: 0.3, special: 0.45, hurt: 0.42, victory: 1.5, wave: 1.3, dig: 0.6, }; const LOOPS = new Set(['idle', 'run', 'jump', 'fall', 'talk', 'float', 'sleep', 'defeat', 'frozen']); type V3 = [number, number, number]; interface Pose { by: number; sx: number; sy: number; lean: number; spin: number; nod: number; shake: number; hf: V3; hb: V3; ff: V3; fb: V3; hs: number; } function newPose(): Pose { return { by: 0, sx: 1, sy: 1, lean: 0, spin: 0, nod: 0, shake: 0, hf: [0.57, -0.1, 0.06], hb: [-0.57, -0.1, 0.06], ff: [0.235, -0.4, 0.15], fb: [-0.235, -0.4, 0.13], hs: 1, }; } const set3 = (v: V3, x: number, y: number, z: number) => { v[0] = x; v[1] = y; v[2] = z; }; const clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v); const easeOut = (t: number) => 1 - (1 - t) * (1 - t); const outBack = (t: number) => { const c = 1.9; return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2); }; const dampK = (rate: number, dt: number) => 1 - Math.exp(-rate * dt); // ───────────────────────────── Rig ───────────────────────────── interface AccessoryInst { group: THREE.Group; update?: (t: number) => void } type StdMat = THREE.Material & { color?: THREE.Color; emissive?: THREE.Color; emissiveIntensity?: number; opacity: number }; /** * Cámara del juego para compensar la perspectiva: la cámara 2.5D se adelanta en la dirección de carrera y mira * a los personajes ligeramente de lado; sin compensar, el giro hacia un lado se veía casi de frente y hacia el * otro de perfil. La instala el render; sin ella (plantilla de personajes) no se compensa nada. */ let viewCamera: THREE.Camera | null = null; export function setChibiViewCamera(cam: THREE.Camera | null): void { viewCamera = cam; } const _wp = new THREE.Vector3(); export class Chibi implements ChibiRig { readonly root = new THREE.Group(); anim: ChibiAnim = 'idle'; private inner = new THREE.Group(); private lean = new THREE.Group(); private pivot = new THREE.Group(); private bodyG = new THREE.Group(); private limbs = new THREE.Group(); private face = new THREE.Group(); private emoji: string | null = null; private faces: Partial> = {}; private emojiMode: 'auto' | 'sphere' | 'flat' = 'auto'; private shownGlyph: string | null = null; private flatHead: THREE.Mesh | null = null; private baseColor = new THREE.Color(); private bodyOpacity = 1; private mouthK = 1; private handK = 1; private outfit: OutfitInst | null = null; private outfitId: OutfitId = 'none'; private soleMat!: StdMat; private openHands = false; private handIce: THREE.Object3D[] = []; /** Balanceo de brazos al correr (−1..1); NaN = brazos en coordenadas de pantalla (resto de animaciones). */ private armSwing = NaN; private baseGeo!: THREE.BufferGeometry; private offRefresh: (() => void) | null = null; private bodyMesh: THREE.Mesh; private handF: THREE.Mesh | null = null; // mano derecha (x+) private handL: THREE.Mesh | null = null; private footR: THREE.Mesh | null = null; private footL: THREE.Mesh | null = null; private bodyMat: StdMat; private handMat: StdMat; private footMat: StdMat; private ownMats: THREE.Material[] = []; private ownGeos: THREE.BufferGeometry[] = []; private eyes: Array<{ anchor: THREE.Group; kinds: Record }> = []; private brows: THREE.Group[] = []; private mouthA: THREE.Group; private mouths = {} as Record; private tongue: THREE.Mesh; private cheeks: THREE.Group[] = []; private shape: NonNullable; private expr: Expression; private nextExpr: Expression | null = null; private exprT = 0; private exprDur = 0; private blinkT = 2; private blinkPhase = 0; private accessory: Accessory = 'none'; private acc: AccessoryInst | null = null; private baseEmissive = new THREE.Color(0x000000); private baseEmissiveI = 0; private flashColor = new THREE.Color(); private flashT = 0; private flashDur = 0; private handAuto: boolean; private footAuto: boolean; // animación private t = 0; private time = 0; private animT = 0; private speed = 1; private loop = true; private forced = false; private onDone: (() => void) | null = null; private attackSide = 1; private victoryLanded = false; private runPhase = 0; private wasGround = true; private fs = 1; private yaw = 0.26; private sq = 0; private sqv = 0; private pose = newPose(); private tgt = newPose(); private motion: ChibiMotion = { vx: 0, vy: 0, onGround: true, facing: 1 }; constructor(opts: ChibiOptions) { this.shape = opts.shape ?? 'ball'; this.expr = opts.expression ?? 'happy'; this.handAuto = opts.handColor === undefined; this.footAuto = opts.footColor === undefined; const size = opts.size ?? 1; this.root.add(this.inner); this.inner.scale.setScalar(size); this.inner.add(this.lean); this.lean.add(this.pivot, this.limbs); this.pivot.add(this.bodyG); const opacity = opts.opacity ?? 1; this.bodyOpacity = opacity; const transparent = opacity < 1; const bodyColor = new THREE.Color(opts.color); this.bodyMat = this.own(toonMaterial({ color: bodyColor, gloss: 0.75, rim: 0.6, transparent, opacity, emissive: opts.emissive ?? 0x000000, emissiveIntensity: opts.emissiveIntensity ?? 1, })) as StdMat; this.handMat = this.own(toonMaterial({ color: opts.handColor ?? handTint(bodyColor), gloss: 0.7, transparent, opacity })) as StdMat; this.footMat = this.own(toonMaterial({ color: opts.footColor ?? footTint(bodyColor), gloss: 0.7, transparent, opacity })) as StdMat; this.soleMat = this.own(toonMaterial({ color: soleTint(new THREE.Color(opts.footColor ?? footTint(bodyColor))), gloss: 0.45, transparent, opacity })) as StdMat; if (opts.emissive !== undefined) { this.baseEmissive.set(opts.emissive); this.baseEmissiveI = opts.emissiveIntensity ?? 1; } // Cuerpo let bodyGeo = G.body(); if (this.shape === 'drop') bodyGeo = geo('drop', makeDrop); this.baseGeo = bodyGeo; this.baseColor.copy(bodyColor); this.bodyMesh = mesh(bodyGeo, this.bodyMat, true); this.bodyMesh.scale.set(1, BODY_SY, 0.97); this.bodyG.add(this.bodyMesh); if (this.shape === 'ghost') { const skirt = mesh(geo('skirt', makeSkirt), this.bodyMat, true); skirt.name = 'skirt'; this.bodyG.add(skirt); } if (this.shape === 'robot') this.buildRobot(); // Cara this.bodyG.add(this.face); this.face.scale.set(1, BODY_SY, 0.97); const push = this.shape === 'robot' ? 0.02 : 0; for (const side of [-1, 1]) { const a = anchor(side * 0.23, 0.16, push); const kinds = this.buildEye(side); for (const k of Object.values(kinds)) a.add(k); this.face.add(a); this.eyes.push({ anchor: a, kinds }); if (this.shape !== 'robot') { const b = anchor(side * 0.23, 0.42, 0.004); const bm = mesh(G.capsule(0.022, 0.1), M.brow()); bm.rotation.z = Math.PI / 2; b.add(bm); this.face.add(b); this.brows.push(b); const c = anchor(side * 0.4, 0.0, -0.008); const cm = mesh(G.sphere(), M.cheek()); cm.scale.set(0.075, 0.048, 0.02); c.add(cm); this.face.add(c); this.cheeks.push(c); } } this.mouthA = anchor(0, -0.25, 0.002); this.face.add(this.mouthA); this.tongue = mesh(G.sphere(), M.tongue()); this.buildMouths(); if (this.shape === 'robot') this.mouthA.traverse((o) => { const m = o as THREE.Mesh; if (m.isMesh) m.material = M.glow(); }); // Extremidades const hands = opts.hands ?? true; const feet = opts.feet ?? this.shape !== 'ghost'; const handSize = this.shape === 'ghost' ? 0.8 : 1; if (hands) { this.openHands = opts.hands === 'open'; const hg = this.openHands ? G.openHand() : G.hand(); this.handF = mesh(hg, this.handMat, true); this.handL = mesh(hg, this.handMat, true); this.handK = handSize * (this.openHands ? 0.9 : 1); this.limbs.add(this.handF, this.handL); } if (feet) { this.footR = mesh(G.shoe(), this.footMat, true); this.footL = mesh(G.shoe(), this.footMat, true); for (const f of [this.footR, this.footL]) { f.scale.set(SHOE[0], SHOE[1], SHOE[2]); f.add(mesh(G.sole(), this.soleMat)); } this.limbs.add(this.footR, this.footL); } this.applyExpression(this.expr); this.setAccessory(opts.accessory ?? 'none'); if (opts.outfit) this.setOutfit(opts.outfit); this.emojiMode = opts.emojiMode ?? 'auto'; if (opts.emoji) this.setEmoji(opts.emoji, opts.faces); this.blinkT = 1 + Math.random() * 3; this.time = Math.random() * 10; this.update(0); } // ───────── construcción ───────── private own(m: T): T { this.ownMats.push(m); return m; } private buildEye(side: number): Record { const robot = this.shape === 'robot'; const eyeMat = robot ? M.eyeRobot() : M.eye(); const oval = new THREE.Group(); const o = mesh(G.sphere(), eyeMat); o.scale.set(robot ? 0.085 : 0.06, robot ? 0.13 : 0.1, 0.03); oval.add(o); if (false) { const h1 = mesh(G.sphere(), M.white()); h1.scale.setScalar(0.029); h1.position.set(-0.024 + side * 0.004, 0.05, 0.03); const h2 = mesh(G.sphere(), M.white()); h2.scale.setScalar(0.013); h2.position.set(0.022, -0.045, 0.03); oval.add(h1, h2); } const happy = mesh(G.arc(0.078, 0.0215, Math.PI), eyeMat); happy.position.set(0, -0.03, 0.012); const closed = mesh(G.arc(0.07, 0.02, Math.PI), eyeMat); closed.rotation.z = Math.PI; closed.position.set(0, 0.0, 0.012); const x = new THREE.Group(); for (const r of [Math.PI / 4, -Math.PI / 4]) { const c = mesh(G.capsule(0.018, 0.1), eyeMat); c.rotation.z = r; x.add(c); } x.position.z = 0.012; const heart = mesh(G.extrude('heart', heartShape, 0.02, 0.014), M.heart()); heart.scale.setScalar(1.02); heart.position.y = 0.015; heart.position.z = 0.02; const star = mesh(G.extrude('eyeStar', () => { const s = new THREE.Shape(); for (let i = 0; i < 10; i++) { const a = (i / 10) * Math.PI * 2 + Math.PI / 2; const r = i % 2 === 0 ? 0.105 : 0.05; if (i === 0) s.moveTo(Math.cos(a) * r, Math.sin(a) * r); else s.lineTo(Math.cos(a) * r, Math.sin(a) * r); } s.closePath(); return s; }, 0.02, 0.016), M.gold()); star.scale.setScalar(0.86); star.position.set(0, 0.015, 0.024); const starBack = mesh(star.geometry, M.starEdge()); starBack.scale.set(1.28, 1.28, 0.6); starBack.position.z = -0.012; star.add(starBack); const alien = mesh(G.sphere(), M.alienEye()); alien.scale.set(0.085, 0.135, 0.035); alien.rotation.z = side * 0.55; alien.position.set(side * 0.035, 0.01, 0); return { oval, happy, closed, x, heart, star, alien }; } private buildMouths(): void { const a = this.mouthA; const open = new THREE.Group(); const om = mesh(G.extrude('mouthOpen', mouthOpenShape, 0.016, 0.012), M.mouth()); open.add(om); this.tongue.scale.set(0.07, 0.035, 0.02); this.tongue.position.set(0, -0.06, 0.02); open.add(this.tongue); open.position.set(0, 0.02, 0.008); const SM = Math.PI * 0.52; const smile = mesh(G.arc(0.082, 0.02, SM), M.line()); smile.rotation.z = -Math.PI / 2 - SM / 2; smile.position.set(0, 0.05, 0.01); const frown = mesh(G.arc(0.078, 0.02, SM), M.line()); frown.rotation.z = Math.PI / 2 - SM / 2; frown.position.set(0, -0.09, 0.01); const neutral = mesh(G.capsule(0.018, 0.1), M.line()); neutral.rotation.z = Math.PI / 2; neutral.position.z = 0.008; const smirk = mesh(G.arc(0.08, 0.0195, Math.PI * 0.6), M.line()); smirk.rotation.z = Math.PI * 1.25; smirk.position.set(-0.015, 0.05, 0.01); const teeth = new THREE.Group(); const tm = mesh(G.extrude('teeth', () => roundedRect(0.27, 0.12, 0.05), 0.016, 0.012), M.teeth()); teeth.add(tm); const lineH = mesh(G.capsule(0.006, 0.22), M.mouth()); lineH.rotation.z = Math.PI / 2; lineH.position.z = 0.022; teeth.add(lineH); for (const x of [-0.07, 0, 0.07]) { const l = mesh(G.capsule(0.006, 0.08), M.mouth()); l.position.set(x, 0, 0.022); teeth.add(l); } teeth.position.set(0, 0.0, 0.006); const o = mesh(G.extrude('mouthO', () => { const s = new THREE.Shape(); s.absellipse(0, 0, 0.042, 0.055, 0, Math.PI * 2, false, 0); return s; }, 0.016, 0.01), M.mouth()); o.position.z = 0.006; const grin = new THREE.Group(); const gm = mesh(G.extrude('mouthOpen', mouthOpenShape, 0.016, 0.012), M.mouth()); grin.add(gm); const gt = mesh(G.extrude('grinTeeth', () => roundedRect(0.2, 0.03, 0.012), 0.01, 0.006), M.teeth()); gt.position.set(0, -0.0, 0.02); grin.add(gt); grin.scale.set(1.2, 0.75, 1); grin.rotation.z = -0.12; grin.position.set(0, 0.015, 0.008); this.mouths = { open, smile, neutral, frown, smirk, teeth, o, grin }; for (const m of Object.values(this.mouths)) a.add(m); } private buildRobot(): void { const visor = mesh(geo('visor', () => new THREE.SphereGeometry(0.508, 36, 18, Math.PI / 2 - 0.8, 1.6, Math.PI / 2 - 0.52, 0.72)), M.dark()); visor.scale.set(1, BODY_SY, 0.97); this.bodyG.add(visor); for (const side of [-1, 1]) { const ear = mesh(geo('ear', () => new THREE.CylinderGeometry(0.15, 0.15, 0.1, 24)), M.earBlue(), true); ear.rotation.z = Math.PI / 2; ear.position.set(side * 0.49, 0.02, 0); const ring = mesh(geo('earRing', () => new THREE.TorusGeometry(0.085, 0.022, 8, 24)), M.glow()); ring.rotation.y = Math.PI / 2; ring.position.set(side * 0.535, 0.02, 0); this.bodyG.add(ear, ring); } } // ───────── API ───────── setEmoji(emoji: string | null, faces?: Partial>): void { if (faces) this.faces = faces; else if (emoji !== this.emoji) this.faces = {}; this.emoji = emoji; this.applyGlyph(emoji ? this.faces[this.expr] ?? emoji : null); if (emoji && !this.offRefresh) this.offRefresh = onGlyphRefresh(() => { const g = this.shownGlyph; this.shownGlyph = null; this.applyGlyph(g); }); } /** Muestra un glifo como cara (esfera proyectada o cabeza con relieve), o vuelve a los rasgos 3D con null. */ private applyGlyph(glyph: string | null): void { if (glyph === this.shownGlyph) return; this.shownGlyph = glyph; if (this.flatHead) { this.bodyG.remove(this.flatHead); (this.flatHead.material as THREE.Material).dispose(); this.flatHead = null; } const mat = this.bodyMat as StdMat & { map: THREE.Texture | null; needsUpdate: boolean }; const hadMap = !!mat.map; if (!glyph) { this.bodyMesh.visible = true; this.bodyMesh.geometry = this.baseGeo; mat.map = null; mat.color?.copy(this.baseColor); if (hadMap) mat.needsUpdate = true; this.face.visible = true; return; } this.face.visible = false; const info = glyphInfo(glyph); const sphere = this.emojiMode === 'sphere' || (this.emojiMode === 'auto' && info.round); if (sphere) { this.bodyMesh.visible = true; this.bodyMesh.geometry = glyphSphere(glyph); mat.map = emojiTexture(glyph, 256); mat.color?.set(0xffffff); if (!hadMap) mat.needsUpdate = true; if (this.handAuto) this.handMat.color?.copy(handTint(info.skin)); if (this.footAuto) this.footMat.color?.copy(footTint(info.skin)); } else { this.bodyMesh.visible = false; mat.map = null; if (hadMap) mat.needsUpdate = true; this.flatHead = emojiMesh(glyph, R * 2 * 1.38, this.bodyOpacity < 1 ? { opacity: this.bodyOpacity } : {}); this.flatHead.position.set(0, 0.04, 0.02); if (this.handAuto) this.handMat.color?.copy(info.skin); if (this.footAuto) this.footMat.color?.copy(footTint(info.skin)); this.bodyG.add(this.flatHead); } } setExpression(e: Expression, seconds = 0.14): void { if (this.emoji) { this.expr = e; this.nextExpr = null; this.applyGlyph(this.faces[e] ?? this.emoji); return; } if (e === this.expr && !this.nextExpr) return; if (seconds <= 0) { this.nextExpr = null; this.applyExpression(e); return; } this.nextExpr = e; this.exprT = 0; this.exprDur = seconds; } get expression(): Expression { return this.nextExpr ?? this.expr; } private applyExpression(e: Expression): void { this.expr = e; const d = EXPR[e]; this.eyes.forEach((eye, i) => { const kind = i === 0 ? d.l : d.r; for (const [k, o] of Object.entries(eye.kinds)) o.visible = k === kind; const s = d.eyeScale ?? 1; eye.kinds.oval.scale.set(s, s * (d.eyeSquint ?? 1), s); }); this.brows.forEach((b, i) => { b.visible = d.brow !== null; const side = i === 0 ? -1 : 1; const ang = d.brow ?? 0; b.children[0].rotation.set(0, 0, Math.PI / 2 + side * ang); b.children[0].position.set(0, d.browY ?? 0, 0); }); for (const [k, m] of Object.entries(this.mouths)) m.visible = k === d.mouth; this.tongue.visible = !!d.tongue; this.mouthK = d.mouthScale ?? 1; for (const c of this.cheeks) c.visible = d.cheeks; } setColor(c: THREE.ColorRepresentation): void { const col = new THREE.Color(c); this.baseColor.copy(col); if (this.shownGlyph) return; this.bodyMat.color?.copy(col); if (this.handAuto) this.handMat.color?.copy(handTint(col)); if (this.footAuto) { this.footMat.color?.copy(footTint(col)); this.soleMat.color?.copy(soleTint(footTint(col))); } } /** Atuendo 3D (pelo, sombrero, uniforme, mochila…). Puede imponer el color de los zapatos. */ setOutfit(id: OutfitId): void { if (id === this.outfitId) return; if (this.outfit) { this.bodyG.remove(this.outfit.group); this.outfit = null; } this.outfitId = id; const o = buildOutfit(id); if (!o) return; o.group.scale.set(1, BODY_SY, 0.97); this.bodyG.add(o.group); this.outfit = o; if (o.foot !== undefined) { this.footAuto = false; this.footMat.color?.set(o.foot); this.soleMat.color?.set(o.sole ?? o.foot); } else if (o.sole !== undefined) this.soleMat.color?.set(o.sole); } setAccessory(a: Accessory): void { if (this.acc) { this.bodyG.remove(this.acc.group); disposeOwned(this.acc.group); this.acc = null; } this.accessory = a; for (const o of this.handIce) o.parent?.remove(o); this.handIce.length = 0; if (a === 'none') return; this.acc = buildAccessory(a); if (this.acc) this.bodyG.add(this.acc.group); if (a === 'iceCrown' && !this.openHands) { // carámbanos que cuelgan de las manos (en unidades de la mano, radio 1) const drip = geo('icicle', () => { const k = new THREE.ConeGeometry(1, 1, 10, 1); k.rotateX(Math.PI); k.translate(0, -0.5, 0); return k; }); for (const h of [this.handF, this.handL]) { if (!h) continue; for (const [x, z, r, len] of [[-0.3, 0.1, 0.26, 1.15], [0.28, 0.05, 0.2, 0.8]] as const) { const d = mesh(drip, M.ice(), true); d.scale.set(r, len, r); d.position.set(x, -0.82, z); h.add(d); this.handIce.push(d); } } } } get currentAccessory(): Accessory { return this.accessory; } setEmissive(c: THREE.ColorRepresentation, intensity: number): void { this.baseEmissive.set(c); this.baseEmissiveI = intensity; this.applyEmissive(0); } play(anim: ChibiAnim, opts: { loop?: boolean; speed?: number; onDone?: () => void } = {}): void { const prevDone = this.onDone; this.onDone = null; if (prevDone && !LOOPS.has(this.anim)) prevDone(); this.anim = anim; this.animT = 0; this.speed = opts.speed ?? 1; this.loop = opts.loop ?? LOOPS.has(anim); this.onDone = opts.onDone ?? null; this.forced = !this.loop || !LOCO.has(anim); if (anim === 'attack') this.attackSide = -this.attackSide; if (anim === 'victory') this.victoryLanded = false; if (anim === 'land') this.squash(-0.22); if (anim === 'hurt') this.squash(-0.3); } squash(amount: number): void { this.sq = clamp(this.sq + amount, -0.45, 0.45); this.sqv = 0; } flash(color: THREE.ColorRepresentation, seconds: number): void { this.flashColor.set(color); this.flashT = seconds; this.flashDur = Math.max(0.001, seconds); } private applyEmissive(k: number): void { for (const m of [this.bodyMat, this.handMat, this.footMat]) { if (!m.emissive) continue; m.emissive.copy(this.baseEmissive); let i = this.baseEmissiveI; if (k > 0) { if (i === 0) m.emissive.copy(this.flashColor); else m.emissive.lerp(this.flashColor, k); i = i + (1.2 - i) * k; } m.emissiveIntensity = i; } // La cabeza-emoji tiene su propio material: el destello la aclara. if (this.flatHead) (this.flatHead.material as StdMat).emissiveIntensity = 0.28 + 1.1 * Math.max(0, k); } /** Mira hacia un lado sin moverse (diálogos). */ faceDir(dir: number): void { this.fs = dir < 0 ? -1 : 1; } update(dt: number, motion?: ChibiMotion): void { this.time += dt; if (viewCamera && this.root.parent) { this.root.getWorldPosition(_wp); const cp = viewCamera.position; this.inner.rotation.y = Math.atan2(cp.x - _wp.x, Math.max(1, cp.z - _wp.z)); } if (motion) { this.motion = motion; if (motion.facing) this.fs = motion.facing < 0 ? -1 : 1; } const mo = this.motion; // Selección automática de locomoción if (motion && !this.forced) { let want: ChibiAnim; if (motion.onGround) { if (!this.wasGround && motion.vy <= 0.5) want = 'land'; else want = Math.abs(motion.vx) > 0.4 ? 'run' : 'idle'; } else want = motion.vy > 0 ? 'jump' : 'fall'; if (want === 'land') this.play('land'); else if (want !== this.anim) { this.anim = want; this.animT = 0; this.loop = true; } } if (motion) this.wasGround = motion.onGround; this.animT += dt * this.speed; const d = DUR[this.anim] ?? 1; if (!this.loop && this.animT >= d) { const cb = this.onDone; this.onDone = null; this.forced = false; this.anim = mo.onGround ? (Math.abs(mo.vx) > 0.4 ? 'run' : 'idle') : mo.vy > 0 ? 'jump' : 'fall'; this.animT = 0; this.loop = true; cb?.(); } if (this.anim === 'run') this.runPhase += dt * (9 + Math.abs(mo.vx) * 1.05); this.computePose(this.tgt, Math.min(this.animT / d, 1)); // Suavizado hacia la pose objetivo const k = dampK(this.anim === 'attack' || this.anim === 'special' ? 40 : 20, dt); const p = this.pose, q = this.tgt; p.by += (q.by - p.by) * k; p.sx += (q.sx - p.sx) * k; p.sy += (q.sy - p.sy) * k; p.lean += (q.lean - p.lean) * k; p.spin += (q.spin - p.spin) * (this.anim === 'victory' ? 1 : k); p.nod += (q.nod - p.nod) * k; p.shake = q.shake; p.hs += (q.hs - p.hs) * k; for (const key of ['hf', 'hb', 'ff', 'fb'] as const) { for (let i = 0; i < 3; i++) p[key][i] += (q[key][i] - p[key][i]) * k; } // Muelle de squash & stretch // Muelle del squash & stretch en subpasos cortos: con fotogramas largos (tirones, pestaña en segundo // plano) la integración directa se volvía inestable y la escala crecía sin límite. let rest = Math.min(dt, 0.1); while (rest > 1e-6) { const h = Math.min(rest, 1 / 120); this.sqv += (-340 * this.sq - 15 * this.sqv) * h; this.sq += this.sqv * h; rest -= h; } if (!Number.isFinite(this.sq) || !Number.isFinite(this.sqv)) this.sq = this.sqv = 0; this.sq = clamp(this.sq, -0.6, 0.6); // Giro 3/4 suave hacia facing // Al correr, la cara se gira claramente hacia la dirección de carrera (perfil de tres cuartos). const yawT = this.fs * (this.anim === 'run' ? 0.78 : 0.26); this.yaw += (yawT - this.yaw) * dampK(11, dt); // Aplicar const fs = this.fs; const sy = p.sy * (1 + this.sq); const sx = p.sx * (1 - this.sq * 0.55); this.inner.position.x = p.shake; this.lean.rotation.z = -fs * p.lean; this.pivot.rotation.set(p.nod, this.yaw + fs * p.spin, 0); this.bodyG.scale.set(sx, sy, sx); this.bodyG.position.y = p.by + R * BODY_SY * (sy - 1) * 0.6; this.limbs.rotation.y = this.yaw * 0.35; const handFront = fs > 0 ? this.handF : this.handL; const handBack = fs > 0 ? this.handL : this.handF; const footFront = fs > 0 ? this.footR : this.footL; const footBack = fs > 0 ? this.footL : this.footR; const hy = p.by * 0.8 + this.bodyG.position.y * 0.3; if (handFront && handBack) { handFront.position.set(fs * p.hf[0] * sx, p.hf[1] * sy + hy, p.hf[2]); handBack.position.set(fs * p.hb[0] * sx, p.hb[1] * sy + hy, p.hb[2]); if (!Number.isNaN(this.armSwing) && this.handF && this.handL) { // Corriendo: manos a los costados del propio cuerpo (girado hacia la carrera) que se balancean en // su eje adelante/atrás, una contra la otra, como un braceo real. const a = this.yaw - this.limbs.rotation.y; const ca = Math.cos(a), sa = Math.sin(a); const sw = this.armSwing; for (const [hm, side] of [[this.handF, 1], [this.handL, -1]] as const) { const fwd = side * sw * fs * 0.22; const lx = side * 0.58 * sx; const lz = 0.02 + fwd; hm.position.set(lx * ca + lz * sa, -0.13 * sy + hy + 0.03 * Math.max(0, fwd / 0.22), -lx * sa + lz * ca); } } // Las manos nunca se hunden en el cuerpo: así conservan su tamaño aparente. for (const hm of [handFront, handBack]) { const minR = 0.6 * sx; const d = Math.hypot(hm.position.x, hm.position.z); if (d > 1e-4 && d < minR) { hm.position.x *= minR / d; hm.position.z *= minR / d; } } const s = p.hs; const k = s * this.handK; handFront.scale.set(HAND[0] * k, HAND[1] * k, HAND[2] * k); handBack.scale.set(HAND[0] * k, HAND[1] * k, HAND[2] * k); if (this.openHands) { // palmas hacia delante, dedos abiertos hacia fuera y arriba handFront.position.x += fs * 0.07; handFront.position.z += 0.16; handFront.position.y += 0.02; handBack.position.x -= fs * 0.07; handBack.position.z += 0.16; handBack.position.y += 0.02; handFront.rotation.set(0, 0, -fs * 1.0); handBack.rotation.set(0, Math.PI, -fs * 1.0); } } if (footFront && footBack) { footFront.position.set(fs * p.ff[0], p.ff[1], p.ff[2]); footBack.position.set(fs * p.fb[0], p.fb[1], p.fb[2]); footFront.rotation.y = footBack.rotation.y = fs * 0.35; // al levantar el pie se ve la suela plana footFront.rotation.x = -Math.max(0, p.ff[1] + 0.4) * 3.2; footBack.rotation.x = -Math.max(0, p.fb[1] + 0.4) * 3.2; } this.updateFace(dt); this.acc?.update?.(this.time); const skirt = this.bodyG.getObjectByName('skirt'); if (skirt) skirt.rotation.y = this.time * 0.8; // Destello if (this.flashT > 0) { this.flashT -= dt; this.applyEmissive(Math.max(0, this.flashT / this.flashDur)); } else if (this.flashDur > 0) { this.flashDur = 0; this.applyEmissive(0); } } private updateFace(dt: number): void { // Transición de expresión: los rasgos se aplastan, se cambian y rebotan. let f = 1; if (this.nextExpr) { this.exprT += dt; const u = this.exprT / this.exprDur; if (u >= 0.5 && this.expr !== this.nextExpr) this.applyExpression(this.nextExpr); if (u >= 1) this.nextExpr = null; f = 1 - Math.sin(Math.min(u, 1) * Math.PI) * 0.85; } // Parpadeo automático this.blinkT -= dt; if (this.blinkT <= 0) { this.blinkPhase = 0.13; this.blinkT = 2 + Math.random() * 3.5; if (Math.random() < 0.2) this.blinkT = 0.25; // doble parpadeo } let blink = 1; if (this.blinkPhase > 0) { this.blinkPhase -= dt; blink = 0.1 + 0.9 * Math.abs(this.blinkPhase / 0.13 * 2 - 1); } const frozen = this.anim === 'frozen'; for (const e of this.eyes) { e.anchor.scale.set(1, f * (frozen ? 1 : blink), 1); } let mouthY = f; if (this.anim === 'talk') mouthY *= 0.55 + 0.45 * Math.abs(Math.sin(this.time * 13)); this.mouthA.scale.set(1.2 * this.mouthK, mouthY * 1.15 * this.mouthK, 1); for (const b of this.brows) b.scale.set(1, f, 1); } private computePose(p: Pose, u: number): void { const t = this.animT; const mo = this.motion; // Neutral p.by = 0; p.sx = 1; p.sy = 1; p.lean = 0; p.spin = 0; p.nod = 0; p.shake = 0; p.hs = 1; set3(p.hf, 0.56, -0.1, 0.06); set3(p.hb, -0.56, -0.1, 0.06); set3(p.ff, 0.235, -0.4, 0.15); set3(p.fb, -0.235, -0.4, 0.13); this.armSwing = NaN; switch (this.anim) { case 'idle': { const b = Math.sin(this.time * 2.6); p.by = 0.012 * b; p.sy = 1 + 0.025 * b; p.sx = 1 - 0.014 * b; p.nod = 0.03 * Math.sin(this.time * 1.3); const ph = this.time % 3.6; if (ph < 0.42) { const h = Math.sin((ph / 0.42) * Math.PI); p.by += 0.08 * h; p.sy += 0.05 * h; p.ff[1] += 0.05 * h; p.fb[1] += 0.05 * h; } p.hf[1] = -0.1 + 0.02 * b; p.hb[1] = -0.1 + 0.02 * Math.sin(this.time * 2.6 + 0.6); break; } case 'run': { const k = clamp(Math.abs(mo.vx) / 7.5, 0.35, 1.3); const s = Math.sin(this.runPhase), c = Math.cos(this.runPhase); p.by = 0.07 * Math.abs(s) * k; p.sy = 1 + 0.06 * Math.cos(this.runPhase * 2) * k; p.sx = 1 - 0.03 * Math.cos(this.runPhase * 2) * k; p.lean = 0.2 * k; p.spin = 0.08 * s; set3(p.ff, 0.14 + 0.24 * s * k, -0.42 + 0.13 * Math.max(0, c) * k, 0.12); set3(p.fb, -0.14 - 0.24 * s * k, -0.42 + 0.13 * Math.max(0, -c) * k, 0.02); // Braceo natural en el marco del cuerpo (ver bodyArms): las dos manos van a los costados y se // balancean adelante/atrás en oposición, al compás de los pies, girando con el cuerpo. this.armSwing = s * k; break; } case 'jump': { const k = clamp(mo.vy / 15, 0, 1); p.sy = 1 + 0.16 * k; p.sx = 1 - 0.09 * k; p.lean = 0.08; set3(p.hf, 0.55, 0.14 + 0.08 * k, 0.08); set3(p.hb, -0.6, 0.22 + 0.08 * k, 0.02); set3(p.ff, 0.15, -0.36, 0.1); set3(p.fb, -0.2, -0.44, 0.02); break; } case 'fall': { const k = clamp(-mo.vy / 20, 0, 1); p.sy = 1 + 0.07 * k; p.sx = 1 - 0.04 * k; set3(p.hf, 0.62, 0.22 + 0.05 * Math.sin(this.time * 22), 0.06); set3(p.hb, -0.62, 0.25 + 0.05 * Math.sin(this.time * 22 + 2), 0.02); set3(p.ff, 0.2, -0.48, 0.1); set3(p.fb, -0.18, -0.46 + 0.03 * Math.sin(this.time * 18), 0.02); break; } case 'land': { const e = 1 - u; p.by = -0.05 * e; p.sx = 1 + 0.1 * e; p.sy = 1 - 0.1 * e; set3(p.hf, 0.62, -0.18, 0.08); set3(p.hb, -0.62, -0.18, 0.04); set3(p.ff, 0.26, -0.42, 0.1); set3(p.fb, -0.26, -0.42, 0.04); break; } case 'attack': { const wf = u < 0.28 ? easeOut(u / 0.28) : u < 0.42 ? 1 - (u - 0.28) / 0.14 : 0; const pf = u < 0.28 ? 0 : u < 0.45 ? outBack((u - 0.28) / 0.17) : 1 - easeOut((u - 0.45) / 0.55); p.spin = -0.45 * wf + 0.4 * pf; p.lean = -0.1 * wf + 0.2 * pf; p.sx = 1 + 0.1 * pf - 0.04 * wf; p.sy = 1 - 0.06 * pf + 0.04 * wf; p.by = -0.02 * wf; const punch = this.attackSide > 0 ? p.hf : p.hb; const other = this.attackSide > 0 ? p.hb : p.hf; const baseX = this.attackSide > 0 ? 0.56 : -0.4; set3(punch, baseX - 0.2 * wf + (0.98 - baseX) * pf, -0.04 + 0.08 * pf, 0.08 + 0.25 * pf); set3(other, this.attackSide > 0 ? -0.6 : 0.5, -0.12, 0); p.hs = 1 + 0.25 * pf; set3(p.ff, 0.28 * pf + 0.18, -0.42, 0.1); set3(p.fb, -0.28, -0.42, 0.02); break; } case 'special': { const ch = u < 0.25 ? easeOut(u / 0.25) : u < 0.35 ? 1 - (u - 0.25) / 0.1 : 0; const rel = u < 0.25 ? 0 : u < 0.4 ? outBack((u - 0.25) / 0.15) : u < 0.75 ? 1 : 1 - easeOut((u - 0.75) / 0.25); p.sx = 1 - 0.08 * ch + 0.14 * rel; p.sy = 1 - 0.1 * ch - 0.05 * rel; p.lean = -0.12 * ch + 0.22 * rel; p.spin = -0.25 * ch + 0.15 * rel; p.by = -0.04 * ch; set3(p.hf, 0.4 - 0.1 * ch + 0.45 * rel, 0.02 + 0.08 * rel, 0.14 + 0.1 * rel); set3(p.hb, -0.45 + 0.9 * rel, -0.02 + 0.02 * rel, -0.12 * rel + 0.02); p.hs = 1 + 0.2 * rel; set3(p.ff, 0.26, -0.42, 0.1); set3(p.fb, -0.28, -0.42, 0.02); break; } case 'hurt': { const e = 1 - u; p.spin = Math.sin(u * Math.PI * 3) * 0.55 * e; p.lean = -0.4 * e; p.by = 0.06 * Math.sin(u * Math.PI); p.sx = 1 + 0.12 * e; p.sy = 1 - 0.1 * e; p.nod = -0.25 * e; p.shake = 0.03 * Math.sin(t * 70) * e; set3(p.hf, 0.72, 0.32 * e, 0.08); set3(p.hb, -0.72, 0.36 * e, 0.02); set3(p.ff, 0.24, -0.4 + 0.08 * e, 0.1); set3(p.fb, -0.28, -0.42, 0.02); break; } case 'victory': { if (t < 0.5) { const h = Math.sin((t / 0.5) * Math.PI); p.by = 0.7 * h; p.spin = Math.PI * 2 * easeOut(t / 0.5); p.sy = 1 + 0.12 * h; p.sx = 1 - 0.06 * h; set3(p.hf, 0.6, 0.35, 0.05); set3(p.hb, -0.6, 0.35, 0.05); set3(p.ff, 0.18, -0.36, 0.08); set3(p.fb, -0.18, -0.36, 0.04); } else { if (!this.victoryLanded) { this.victoryLanded = true; this.squash(-0.25); this.pose.spin = 0; } const w = Math.sin(t * 9); p.spin = 0; p.sy = 1 + 0.04 * Math.sin(t * 7); p.lean = -0.06; set3(p.hf, 0.42 + 0.04 * w, 0.66, 0.14); set3(p.hb, -0.5, -0.22, 0.14); p.hs = 1.08; set3(p.ff, 0.22, -0.42, 0.1); set3(p.fb, -0.24, -0.42, 0.04); } break; } case 'talk': { p.by = 0.015 * Math.abs(Math.sin(this.time * 9)); p.sy = 1 + 0.02 * Math.sin(this.time * 9); p.nod = 0.05 * Math.sin(this.time * 4.5); set3(p.hf, 0.6, -0.02 + 0.09 * Math.sin(this.time * 5), 0.18); set3(p.hb, -0.58, -0.08 + 0.04 * Math.sin(this.time * 3.3), 0.04); break; } case 'wave': { const w = Math.sin(t * 14); p.spin = 0.08; p.lean = -0.04 * w; p.by = 0.01 * Math.abs(w); set3(p.hf, 0.56 + 0.1 * w, 0.48, 0.14); break; } case 'float': { p.by = 0.09 * Math.sin(this.time * 2.1); p.sy = 1 + 0.03 * Math.sin(this.time * 2.1 + 1); set3(p.hf, 0.66, 0.04 + 0.07 * Math.sin(this.time * 2.1 + 1), 0.06); set3(p.hb, -0.66, 0.04 + 0.07 * Math.sin(this.time * 2.1 + 1.4), 0.02); set3(p.ff, 0.16, -0.5 + 0.03 * Math.sin(this.time * 2.1), 0.08); set3(p.fb, -0.16, -0.5 + 0.03 * Math.sin(this.time * 2.1 + 0.5), 0.04); break; } case 'sleep': { const b = Math.sin(this.time * 1.5); p.sy = 0.92 + 0.04 * b; p.sx = 1.06 - 0.02 * b; p.by = -0.04; p.lean = 0.12; p.nod = 0.12; set3(p.hf, 0.56, -0.24, 0.12); set3(p.hb, -0.56, -0.24, 0.04); break; } case 'defeat': { p.lean = -1.3; p.by = -0.16; p.sy = 0.94; p.nod = -0.2; set3(p.hf, 0.45, 0.25, 0.1); set3(p.hb, -0.62, -0.18, 0.02); set3(p.ff, 0.3, -0.25, 0.1); set3(p.fb, 0.05, -0.3, 0.02); break; } case 'dig': { const c = Math.sin(t * 22); p.lean = 0.28; p.nod = 0.25; p.by = -0.03 + 0.02 * c; p.sy = 1 - 0.04 * c; set3(p.hf, 0.48, -0.32 + 0.14 * c, 0.2); set3(p.hb, 0.3, -0.32 - 0.14 * c, -0.1); break; } case 'frozen': { p.shake = 0.012 * Math.sin(this.time * 75); set3(p.hf, 0.6, 0.05, 0.06); set3(p.hb, -0.6, 0.05, 0.02); break; } } } dispose(): void { this.root.parent?.remove(this.root); this.offRefresh?.(); if (this.flatHead) (this.flatHead.material as THREE.Material).dispose(); if (this.acc) disposeOwned(this.acc.group); for (const m of this.ownMats) m.dispose(); for (const g of this.ownGeos) g.dispose(); this.ownMats.length = 0; } } export function createChibi(opts: ChibiOptions): ChibiRig { return new Chibi(opts); } // ───────────────────────────── Ayudantes de color y forma ───────────────────────────── function handTint(c: THREE.Color): THREE.Color { const hsl = c.getHSL({ h: 0, s: 0, l: 0 }); return c.clone().offsetHSL(hsl.h > 0.08 && hsl.h < 0.2 ? -0.004 : 0, 0.0, -0.01); } function footTint(c: THREE.Color): THREE.Color { const hsl = c.getHSL({ h: 0, s: 0, l: 0 }); return c.clone().offsetHSL(hsl.h > 0.08 && hsl.h < 0.2 ? -0.035 : -0.01, 0.04, -0.07); } function soleTint(c: THREE.Color): THREE.Color { return c.clone().offsetHSL(0, 0.0, -0.09); } function makeDrop(): THREE.BufferGeometry { const pts: THREE.Vector2[] = []; const n = 28; for (let i = 0; i <= n; i++) { const a = Math.PI - (i / n) * Math.PI; // de abajo a arriba const x = 0.62 * Math.sin(a) * Math.pow(Math.sin(a / 2), 1.1); const y = 0.62 - ((1 - Math.cos(a)) / 2) * 1.1; pts.push(new THREE.Vector2(Math.max(x, 0.0001), y)); } return new THREE.LatheGeometry(pts, 32); } function makeSkirt(): THREE.BufferGeometry { const g = new THREE.CylinderGeometry(R, R * 1.06, 0.42, 36, 3, true); const pos = g.attributes.position as THREE.BufferAttribute; for (let i = 0; i < pos.count; i++) { const y = pos.getY(i); if (y < -0.2) { const a = Math.atan2(pos.getZ(i), pos.getX(i)); pos.setY(i, y + Math.sin(a * 6) * 0.06); } } g.translate(0, -0.2, 0); g.computeVertexNormals(); return g; } function disposeOwned(root: THREE.Object3D): void { root.traverse((o) => { const m = o as THREE.Mesh; if (m.geometry && !m.geometry.userData.shared) m.geometry.dispose(); const mat = m.material as THREE.Material | undefined; if (mat && !Array.isArray(mat) && !mat.userData.shared) mat.dispose(); }); } // ───────────────────────────── Accesorios ───────────────────────────── function onTop(obj: THREE.Object3D, az: number, el: number, push = 0): THREE.Group { const a = anchor(az, el, push); a.add(obj); return a; } function buildAccessory(a: Accessory): AccessoryInst | null { const g = new THREE.Group(); g.scale.set(1, BODY_SY, 0.97); switch (a) { case 'sunglasses': { const lensGeo = G.extrude('lens', () => { const s = new THREE.Shape(); s.moveTo(-0.11, 0.06); s.lineTo(0.11, 0.06); s.quadraticCurveTo(0.12, -0.08, 0.0, -0.075); s.quadraticCurveTo(-0.12, -0.08, -0.11, 0.06); return s; }, 0.02, 0.014); for (const side of [-1, 1]) { const l = mesh(lensGeo, M.glasses(), true); const an = onTop(l, side * 0.25, 0.17, 0.05); l.rotation.z = side * 0.06; l.scale.set(1.3, 1.55, 1); const shine = mesh(G.capsule(0.009, 0.05), M.white()); shine.rotation.z = -0.7; shine.position.set(-0.04, 0.02, 0.022); l.add(shine); g.add(an); const arm = mesh(G.capsule(0.014, 0.22), M.glasses()); arm.rotation.x = Math.PI / 2; arm.position.set(side * 0.42, 0.2, -0.05); arm.rotation.y = side * 0.4; g.add(arm); } const bridge = mesh(G.capsule(0.016, 0.07), M.glasses()); bridge.rotation.z = Math.PI / 2; g.add(onTop(bridge, 0, 0.25, 0.045)); return { group: g }; } case 'iceCrown': { // Escarcha en lo alto de la cabeza con carámbanos que cuelgan (como el emoji 🥶). const drip = geo('icicle', () => { const k = new THREE.ConeGeometry(1, 1, 10, 1); k.rotateX(Math.PI); k.translate(0, -0.5, 0); return k; }); const caps: Array<[number, number, number]> = [[-0.75, 0.82, 0.2], [0.62, 0.95, 0.17], [0.0, 1.2, 0.13]]; for (const [az, el, s] of caps) { const cap = mesh(G.sphere(), M.ice(), true); cap.scale.set(s, s * 0.42, s); g.add(onTop(cap, az, el, -0.012)); } const drips: Array<[number, number, number, number]> = [ // acimut, elevación, radio, largo [-0.98, 0.6, 0.04, 0.2], [-0.72, 0.62, 0.05, 0.3], [-0.5, 0.7, 0.035, 0.16], [0.48, 0.74, 0.04, 0.2], [0.72, 0.7, 0.05, 0.28], [0.95, 0.64, 0.035, 0.15], ]; for (const [az, el, r, len] of drips) { const d = mesh(drip, M.ice(), true); d.scale.set(r, len, r); const cel = Math.cos(el); d.position.set(Math.sin(az) * cel * (R + 0.012), Math.sin(el) * R + 0.015, Math.cos(az) * cel * (R + 0.012)); g.add(d); } return { group: g }; } case 'flameHair': { const cone = geo('flame', () => new THREE.ConeGeometry(0.13, 0.42, 12, 1)); const flames: THREE.Mesh[] = []; const defs: Array<[number, number, number, number, boolean]> = [ // x, z, inclinación z, escala, núcleo [0, 0, 0, 1.25, false], [-0.17, 0.05, 0.45, 0.95, false], [0.17, 0.05, -0.45, 0.95, false], [-0.08, -0.14, 0.2, 0.9, false], [0.1, -0.14, -0.25, 0.85, false], [0, 0.07, 0, 0.7, true], [-0.15, 0.08, 0.4, 0.55, true], [0.15, 0.08, -0.4, 0.55, true], ]; for (const [x, z, rz, s, core] of defs) { const f = mesh(cone, core ? M.flameCore() : M.flame(), !core); f.position.set(x, 0.5 + 0.13 * s, z + (core ? 0.04 : 0)); f.rotation.z = rz; f.scale.setScalar(s); f.userData.s = s; f.userData.ph = Math.random() * 6; flames.push(f); g.add(f); } return { group: g, update: (t) => { for (const f of flames) { const s = f.userData.s as number; const k = 1 + 0.18 * Math.sin(t * 13 + f.userData.ph) + 0.08 * Math.sin(t * 29 + f.userData.ph); f.scale.set(s * (1.05 - 0.1 * (k - 1)), s * k, s); } }, }; } case 'steam': { const puffs: Array<{ m: THREE.Mesh; mat: StdMat; side: number; ph: number }> = []; for (let i = 0; i < 4; i++) { const mat = toonMaterial({ color: 0xffffff, gloss: 0.1, transparent: true, opacity: 0.8 }) as StdMat; const m = mesh(G.sphere(), mat); g.add(m); puffs.push({ m, mat, side: i % 2 ? 1 : -1, ph: i * 0.5 }); } return { group: g, update: (t) => { for (const p of puffs) { const u = ((t * 0.9 + p.ph) % 1); p.m.position.set(p.side * (0.36 + 0.18 * u), 0.38 + 0.4 * u, 0.05); p.m.scale.setScalar(0.05 + 0.09 * u); p.mat.opacity = 0.85 * (1 - u); } }, }; } case 'antenna': { const stick = mesh(geo('stick', () => new THREE.CylinderGeometry(0.018, 0.022, 0.24, 8)), M.metal(), true); stick.position.y = 0.58; const ball = mesh(G.sphere(), M.glow(), true); ball.scale.setScalar(0.065); ball.position.y = 0.72; g.add(stick, ball); return { group: g, update: (t) => { ball.position.x = 0.015 * Math.sin(t * 5); } }; } case 'alienAntennae': { for (const side of [-1, 1]) { const stick = mesh(geo('astick', () => new THREE.CylinderGeometry(0.016, 0.02, 0.3, 8)), M.alien(), true); stick.position.set(side * 0.2, 0.58, 0); stick.rotation.z = -side * 0.4; const ball = mesh(G.sphere(), M.alien(), true); ball.scale.setScalar(0.07); ball.position.set(side * 0.27, 0.74, 0); g.add(stick, ball); } return { group: g }; } case 'horns': { const cone = geo('horn', () => new THREE.ConeGeometry(0.075, 0.24, 12)); for (const side of [-1, 1]) { const h = mesh(cone, M.horn(), true); h.position.set(side * 0.26, 0.47, 0.02); h.rotation.z = -side * 0.5; g.add(h); } return { group: g }; } case 'halo': { const h = mesh(geo('halo', () => new THREE.TorusGeometry(0.22, 0.035, 10, 32)), M.halo()); h.rotation.x = Math.PI / 2; h.position.y = 0.7; g.add(h); return { group: g, update: (t) => { h.position.y = 0.7 + 0.025 * Math.sin(t * 2.5); } }; } case 'hat': { const brim = mesh(geo('brim', () => new THREE.CylinderGeometry(0.42, 0.42, 0.04, 32)), M.hat(), true); brim.position.y = 0.42; const top = mesh(geo('hatTop', () => new THREE.CylinderGeometry(0.24, 0.27, 0.28, 32)), M.hat(), true); top.position.y = 0.56; const band = mesh(geo('band', () => new THREE.CylinderGeometry(0.275, 0.275, 0.06, 32)), M.gold()); band.position.y = 0.46; const hg = new THREE.Group(); hg.add(brim, top, band); hg.rotation.z = -0.12; g.add(hg); return { group: g }; } case 'crown': { const ring = mesh(geo('crownRing', () => new THREE.CylinderGeometry(0.22, 0.2, 0.12, 24, 1, true)), M.gold(), true); ring.position.y = 0.5; g.add(ring); const spike = geo('crownSpike', () => new THREE.ConeGeometry(0.05, 0.13, 8)); for (let i = 0; i < 5; i++) { const a = (i / 5) * Math.PI * 2; const s = mesh(spike, M.gold(), true); s.position.set(Math.sin(a) * 0.2, 0.62, Math.cos(a) * 0.2); const ball = mesh(G.sphere(), M.gold()); ball.scale.setScalar(0.028); ball.position.set(Math.sin(a) * 0.2, 0.69, Math.cos(a) * 0.2); g.add(s, ball); } const gem = mesh(G.sphere(), M.gem()); gem.scale.set(0.04, 0.05, 0.02); gem.position.set(0, 0.5, 0.21); g.add(gem); return { group: g }; } case 'helmet': { const h = mesh(geo('helmet', () => new THREE.SphereGeometry(0.53, 32, 16, 0, Math.PI * 2, 0, Math.PI * 0.42)), M.metal(), true); g.add(h); const crest = mesh(G.capsule(0.04, 0.3), M.gold(), true); crest.rotation.x = Math.PI / 2; crest.position.set(0, 0.53, -0.02); g.add(crest); return { group: g }; } case 'bow': { const bg = new THREE.Group(); for (const side of [-1, 1]) { const l = mesh(G.sphere(), M.bow(), true); l.scale.set(0.12, 0.08, 0.05); l.position.x = side * 0.1; l.rotation.z = side * 0.3; bg.add(l); } const knot = mesh(G.sphere(), M.bow()); knot.scale.setScalar(0.045); bg.add(knot); g.add(onTop(bg, 0.45, 0.78, 0.02)); return { group: g }; } case 'visor': { const v = mesh(geo('visorAcc', () => new THREE.SphereGeometry(0.515, 36, 12, Math.PI / 2 - 0.8, 1.6, Math.PI / 2 - 0.32, 0.3)), M.glow()); g.add(v); return { group: g }; } } return null; }