Spaces:
Running
Running
Download index.html from Albert5151/Vrm: direct link, hf CLI and curl.
- Browser
- Download file 111 kB
-
https://huggingface.co/spaces/Albert5151/Vrm/resolve/main/index.html
- Command line
-
hf download hf://spaces/Albert5151/Vrm/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Albert5151/Vrm/resolve/main/index.html
111 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>May — 3D AI Companion</title>
<link rel="preconnect" href="https://esm.sh" crossorigin>
<link rel="preconnect" href="https://huggingface.co" crossorigin>
<style>
:root{ --safe-top:max(14px,env(safe-area-inset-top)); --safe-bottom:max(14px,env(safe-area-inset-bottom)); --accent:#6366f1; }
html,body{ margin:0;padding:0;width:100%;height:100dvh;overflow:hidden;background:#07090e;color:#f3f4f6;
font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;
user-select:none;-webkit-user-select:none;touch-action:none;-webkit-tap-highlight-color:transparent;}
#c{position:absolute;inset:0;z-index:0;outline:none}
#ui{position:absolute;inset:0;z-index:10;pointer-events:none;display:flex;flex-direction:column;justify-content:space-between}
.ia{pointer-events:auto}
::-webkit-scrollbar{width:4px;height:4px}
::-webkit-scrollbar-thumb{background:rgba(255,255,255,.18);border-radius:4px}
.noscroll::-webkit-scrollbar{display:none}
@keyframes slideUp{from{transform:translateY(101%)}to{transform:translateY(0)}}
@keyframes popIn{from{opacity:0;transform:scale(.96) translateY(8px)}to{opacity:1;transform:none}}
.sheet-open{animation:slideUp .32s cubic-bezier(.2,.9,.2,1) forwards;display:flex!important}
.sheet-closed{transform:translateY(101%);transition:transform .3s cubic-bezier(.2,.9,.2,1)}
.bubble{animation:popIn .18s cubic-bezier(.2,.9,.2,1);box-shadow:0 12px 34px rgba(0,0,0,.55)}
/* ---------- custom dropdown (no native <select>) ---------- */
.dd-btn{width:100%;display:flex;align-items:center;justify-content:space-between;gap:10px;
background:rgba(0,0,0,.42);border:1px solid rgba(255,255,255,.12);border-radius:11px;
padding:9px 12px;font-size:12px;color:#fff;cursor:pointer;text-align:left}
.dd-btn:hover{background:rgba(255,255,255,.06);border-color:rgba(255,255,255,.2)}
.dd-btn.on{border-color:var(--accent);box-shadow:0 0 0 3px rgba(99,102,241,.16)}
.dd-btn .lb{display:flex;flex-direction:column;gap:1px;min-width:0}
.dd-btn .lb b{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dd-btn .lb small{font-size:9px;color:#9ca3af;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dd-cv{display:inline-block;flex:none;color:#9ca3af}
.dd-btn.on .dd-cv{transform:rotate(180deg);color:var(--accent)}
.dd-menu{position:fixed;z-index:9999;background:#11131a;
border:1px solid rgba(255,255,255,.14);border-radius:13px;padding:5px;overflow-y:auto;
box-shadow:0 18px 50px rgba(0,0,0,.72);opacity:0;transform:translateY(-7px) scale(.97);
pointer-events:none;transition:opacity .15s,transform .15s}
.dd-menu.on{opacity:1;transform:none;pointer-events:auto}
.dd-it{display:flex;align-items:center;gap:9px;padding:8px 10px;border-radius:9px;font-size:12px;
color:#d1d5db;cursor:pointer;line-height:1.25}
.dd-it:hover,.dd-it.hi{background:rgba(255,255,255,.08);color:#fff}
.dd-it.sel{background:rgba(99,102,241,.2);color:#c7d2fe}
.dd-it .tk{flex:none;width:14px;text-align:center;color:var(--accent);opacity:0}
.dd-it.sel .tk{opacity:1}
.dd-it small{display:block;font-size:9px;color:#8b93a7}
/* ---------- controls ---------- */
.card{background:rgba(255,255,255,.045);border:1px solid rgba(255,255,255,.09);border-radius:14px;padding:13px;display:flex;flex-direction:column;gap:11px}
.lbl{font-size:9.5px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#8b93a7}
.row{display:flex;align-items:center;justify-content:space-between;gap:10px}
.tg{position:relative;width:40px;height:22px;border-radius:99px;background:rgba(255,255,255,.14);
border:1px solid rgba(255,255,255,.1);cursor:pointer;flex:none;transition:background .2s}
.tg::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;
background:#fff;transition:transform .2s cubic-bezier(.3,1.4,.5,1)}
.tg.on{background:var(--accent)}
.tg.on::after{transform:translateX(18px)}
input[type=range]{-webkit-appearance:none;width:100%;background:transparent;height:16px}
input[type=range]::-webkit-slider-runnable-track{height:4px;background:rgba(255,255,255,.16);border-radius:3px}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;height:15px;width:15px;border-radius:50%;
background:var(--accent);margin-top:-5.5px;box-shadow:0 2px 7px rgba(0,0,0,.5);cursor:pointer}
input[type=range]::-moz-range-track{height:4px;background:rgba(255,255,255,.16);border-radius:3px}
input[type=range]::-moz-range-thumb{height:15px;width:15px;border:0;border-radius:50%;background:var(--accent)}
.chip{padding:6px 9px;border-radius:9px;font-size:10px;font-weight:600;cursor:pointer;
background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.09);color:#cbd5e1;
text-align:center;line-height:1.3}
.chip:hover{background:rgba(255,255,255,.1);color:#fff}
.chip.act{background:rgba(99,102,241,.26);border-color:var(--accent);color:#e0e7ff}
.tab{padding:6px 13px;border-radius:99px;font-size:11px;font-weight:600;white-space:nowrap;cursor:pointer;
background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.07);color:#94a3b8}
.tab.act{background:var(--accent);border-color:transparent;color:#fff}
.inp{width:100%;background:rgba(0,0,0,.42);border:1px solid rgba(255,255,255,.12);border-radius:11px;
padding:9px 12px;font-size:12px;color:#fff;outline:none;transition:border-color .15s}
.inp:focus{border-color:var(--accent)}
.bar{position:absolute;top:0;left:0;height:2px;background:linear-gradient(90deg,#6366f1,#22d3ee);
z-index:60;width:0;opacity:0;transition:width .25s,opacity .3s}
/* perf: backdrop-filter over a live WebGL canvas is the costliest UI effect — solid glass instead */
.backdrop-blur-sm,.backdrop-blur-md,.backdrop-blur-xl,.backdrop-blur-2xl{-webkit-backdrop-filter:none!important;backdrop-filter:none!important;background-color:rgba(10,12,18,.8)!important}
.dd-menu{-webkit-backdrop-filter:none!important;backdrop-filter:none!important}
#sheet{background-color:rgba(12,14,20,.97)!important}
#bub{background-color:rgba(8,10,16,.9)!important}
/* lightweight: flat UI — no glows, shadows, gradients or per-frame blur */
#ui *,#sheet *,.dd-menu,.dd-menu *,.bubble{box-shadow:none!important}
#bSend{background:#6366f1!important}
.cp{width:100%;height:40px;padding:2px;border:1px solid rgba(255,255,255,.18);border-radius:10px;background:transparent;cursor:pointer}
.sw{height:26px;border-radius:8px;border:1px solid rgba(255,255,255,.16);cursor:pointer}
@media (prefers-reduced-motion:reduce){*{animation-duration:.01ms!important;transition-duration:.01ms!important}}
</style>
<style>*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.19 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-x-0{left:0;right:0}.bottom-0{bottom:0}.z-50{z-index:50}.col-span-2{grid-column:span 2/span 2}.ml-auto{margin-left:auto}.mr-1\.5{margin-right:.375rem}.mt-1\.5{margin-top:.375rem}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.contents{display:contents}.hidden{display:none}.h-1{height:.25rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-8{height:2rem}.max-h-52{max-height:13rem}.max-h-72{max-height:18rem}.max-h-\[86vh\]{max-height:86vh}.w-10{width:2.5rem}.w-2{width:.5rem}.w-8{width:2rem}.w-full{width:100%}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.resize{resize:both}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-3\.5{gap:.875rem}.gap-x-3{-moz-column-gap:.75rem;column-gap:.75rem}.gap-y-0\.5{row-gap:.125rem}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-t-3xl{border-top-left-radius:1.5rem;border-top-right-radius:1.5rem}.border{border-width:1px}.border-t{border-top-width:1px}.border-none{border-style:none}.border-white\/10{border-color:hsla(0,0%,100%,.1)}.border-white\/15{border-color:hsla(0,0%,100%,.15)}.bg-amber-400{--tw-bg-opacity:1;background-color:rgb(251 191 36/var(--tw-bg-opacity,1))}.bg-black\/45{background-color:rgba(0,0,0,.45)}.bg-black\/55{background-color:rgba(0,0,0,.55)}.bg-green-500{--tw-bg-opacity:1;background-color:rgb(34 197 94/var(--tw-bg-opacity,1))}.bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.bg-transparent{background-color:transparent}.bg-white\/10{background-color:hsla(0,0%,100%,.1)}.bg-white\/20{background-color:hsla(0,0%,100%,.2)}.bg-white\/5{background-color:hsla(0,0%,100%,.05)}.bg-gradient-to-tr{background-image:linear-gradient(to top right,var(--tw-gradient-stops))}.from-indigo-600{--tw-gradient-from:#4f46e5 var(--tw-gradient-from-position);--tw-gradient-to:rgba(79,70,229,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.to-cyan-500{--tw-gradient-to:#06b6d4 var(--tw-gradient-to-position)}.p-1{padding:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.pb-2{padding-bottom:.5rem}.pb-3{padding-bottom:.75rem}.pr-1{padding-right:.25rem}.text-center{text-align:center}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-\[10\.5px\]{font-size:10.5px}.text-\[10px\]{font-size:10px}.text-\[11\.5px\]{font-size:11.5px}.text-\[11px\]{font-size:11px}.text-\[9px\]{font-size:9px}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-relaxed{line-height:1.625}.tracking-wider{letter-spacing:.05em}.text-amber-300{--tw-text-opacity:1;color:rgb(252 211 77/var(--tw-text-opacity,1))}.text-amber-400{--tw-text-opacity:1;color:rgb(251 191 36/var(--tw-text-opacity,1))}.text-cyan-300\/70{color:rgba(103,232,249,.7)}.text-cyan-300\/80{color:rgba(103,232,249,.8)}.text-gray-200{--tw-text-opacity:1;color:rgb(229 231 235/var(--tw-text-opacity,1))}.text-gray-300{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity,1))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.text-green-400{--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity,1))}.text-indigo-300{--tw-text-opacity:1;color:rgb(165 180 252/var(--tw-text-opacity,1))}.text-indigo-400{--tw-text-opacity:1;color:rgb(129 140 248/var(--tw-text-opacity,1))}.text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.shadow,.shadow-2xl{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px rgba(0,0,0,.25);--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-\[0_-12px_50px_rgba\(0\2c 0\2c 0\2c \.85\)\]{--tw-shadow:0 -12px 50px rgba(0,0,0,.85);--tw-shadow-colored:0 -12px 50px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_8px_\#22c55e\]{--tw-shadow:0 0 8px #22c55e;--tw-shadow-colored:0 0 8px var(--tw-shadow-color)}.shadow-\[0_0_8px_\#22c55e\],.shadow-\[0_0_8px_\#ef4444\]{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_8px_\#ef4444\]{--tw-shadow:0 0 8px #ef4444;--tw-shadow-colored:0 0 8px var(--tw-shadow-color)}.shadow-\[0_0_8px_\#fbbf24\]{--tw-shadow:0 0 8px #fbbf24;--tw-shadow-colored:0 0 8px var(--tw-shadow-color)}.shadow-\[0_0_8px_\#fbbf24\],.shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.outline-none{outline:2px solid transparent;outline-offset:2px}.blur{--tw-blur:blur(8px)}.blur,.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-2xl{--tw-backdrop-blur:blur(40px)}.backdrop-blur-2xl,.backdrop-blur-md{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur:blur(12px)}.backdrop-blur-sm{--tw-backdrop-blur:blur(4px)}.backdrop-blur-sm,.backdrop-blur-xl{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur:blur(24px)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.hover\:bg-white\/10:hover{background-color:hsla(0,0%,100%,.1)}.hover\:bg-white\/20:hover{background-color:hsla(0,0%,100%,.2)}.active\:scale-95:active{--tw-scale-x:.95;--tw-scale-y:.95}.active\:scale-95:active,.active\:scale-\[\.98\]:active{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.active\:scale-\[\.98\]:active{--tw-scale-x:.98;--tw-scale-y:.98}.disabled\:opacity-40:disabled{opacity:.4}</style>
<script type="importmap">
{ "imports": {
"three": "https://esm.sh/three@0.160.0",
"three/addons/": "https://esm.sh/three@0.160.0/examples/jsm/",
"@pixiv/three-vrm": "https://esm.sh/@pixiv/three-vrm@3.3.4?deps=three@0.160.0",
"@pixiv/three-vrm-animation": "https://esm.sh/@pixiv/three-vrm-animation@3.3.4?deps=three@0.160.0,@pixiv/three-vrm@3.3.4"
}}
</script>
</head>
<body>
<div id="c"></div>
<div id="loadBar" class="bar"></div>
<div id="ui">
<div class="w-full flex justify-between items-start px-3.5" style="padding-top:var(--safe-top)">
<div class="ia flex items-center gap-2 bg-black/45 backdrop-blur-md border border-white/10 rounded-full px-3 py-1.5 shadow-lg">
<div id="dot" class="w-2 h-2 rounded-full bg-green-500 shadow-[0_0_8px_#22c55e]"></div>
<span id="stat" class="text-[11px] font-medium text-gray-200">Booting…</span>
</div>
<div class="ia flex items-center gap-1 bg-black/45 backdrop-blur-md border border-white/10 rounded-full p-1 shadow-lg">
<div id="fps" class="text-[10px] font-bold text-green-400 px-2">-- FPS</div>
<button id="bCam" class="w-8 h-8 grid place-items-center rounded-full bg-white/5 hover:bg-white/10 text-gray-200" title="Recenter" aria-label="Recenter camera"><span class="text-lg">⌖</span></button>
<button id="bSet" class="w-8 h-8 grid place-items-center rounded-full bg-white/5 hover:bg-white/10 text-gray-200" title="Studio" aria-label="Open studio settings"><span class="text-lg">⚙</span></button>
</div>
</div>
<div class="px-4 mt-1.5">
<div id="hud" class="inline-flex flex-wrap gap-x-3 gap-y-0.5 bg-black/45 backdrop-blur-sm border border-white/10 rounded-md px-2 py-1 font-mono text-[9px] text-cyan-300/80"></div>
</div>
<div class="flex-1 flex flex-col justify-end items-center px-3.5 pb-3 gap-3" style="padding-bottom:var(--safe-bottom)">
<div id="bub" class="bubble hidden flex-col gap-1 bg-black/72 backdrop-blur-xl border border-white/15 rounded-2xl px-5 py-3 w-full max-w-md">
<div class="flex items-center gap-2 text-[11px] font-semibold text-indigo-300">
<span class="">♪</span><span id="bubWho">May</span>
<span id="bubMood" class="ml-auto text-[9px] font-medium text-gray-400 uppercase tracking-wider"></span>
</div>
<p id="bubTxt" class="text-sm text-white leading-relaxed"></p>
</div>
<div class="ia flex w-full max-w-md bg-black/55 backdrop-blur-xl border border-white/15 rounded-full p-1 shadow-2xl">
<input id="msg" aria-label="Message" type="text" class="flex-1 bg-transparent border-none outline-none text-sm text-white px-4 placeholder-gray-500" placeholder="Talk to May…" autocomplete="off">
<button id="bSend" aria-label="Send message" class="w-10 h-10 grid place-items-center rounded-full bg-gradient-to-tr from-indigo-600 to-cyan-500 text-white shadow-lg active:scale-95 transition disabled:opacity-40"><span class="">➤</span></button>
</div>
</div>
</div>
<div id="sheet" class="sheet-closed ia fixed inset-x-0 bottom-0 z-50 hidden flex-col bg-[#0c0e14]/96 backdrop-blur-2xl border-t border-white/10 rounded-t-3xl max-h-[86vh] shadow-[0_-12px_50px_rgba(0,0,0,.85)]">
<div class="flex justify-center py-2.5"><div class="w-10 h-1 bg-white/20 rounded-full"></div></div>
<div class="flex justify-between items-center px-5 pb-2">
<h3 class="text-sm font-semibold flex items-center gap-2"><span class="text-indigo-400">✦</span> Studio</h3>
<button id="bClose" class="w-8 h-8 grid place-items-center rounded-full bg-white/10 text-gray-300 hover:bg-white/20"><span class="">✕</span></button>
</div>
<div id="tabs" class="flex px-4 gap-1.5 overflow-x-auto noscroll pb-2"></div>
<div id="panels" class="flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-3.5" style="padding-bottom:calc(var(--safe-bottom) + 10px)"></div>
</div>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { VRMLoaderPlugin, VRMUtils } from '@pixiv/three-vrm';
import { VRMAnimationLoaderPlugin, createVRMAnimationClip, VRMLookAtQuaternionProxy } from '@pixiv/three-vrm-animation';
/* ════════════════════════════ CONFIG ════════════════════════════ */
const BUCKET = 'https://huggingface.co/buckets/Albert5151/vrm/resolve/';
const AVATARS = [
{ id:'May', name:'May', desc:'VRoid · full 57-morph face rig', url: BUCKET+'May.vrm?download=true' },
{ id:'Emma', name:'Emma', desc:'Optimized', url: BUCKET+'Emma.vrm?download=true' },
{ id:'Uni', name:'Uni', desc:'Standard', url: BUCKET+'Uni.vrm?download=true' },
{ id:'Jemmi', name:'Jemmi', desc:'Standard', url: BUCKET+'Jemmi.vrm?download=true' },
{ id:'Shinano', name:'Shinano', desc:'Standard', url: BUCKET+'Shinano.vrm?download=true' },
];
const VRMA_ZIP = BUCKET+'all_vrma.zip?download=true';
const MODELS = [
{ id:'gemini-2.5-flash-lite', name:'Gemini 2.5 Flash Lite', desc:'Fastest' },
{ id:'gemini-2.5-flash', name:'Gemini 2.5 Flash', desc:'Balanced' },
{ id:'gemini-2.0-flash-lite', name:'Gemini 2.0 Flash Lite', desc:'Legacy fast' },
{ id:'gemini-2.0-flash', name:'Gemini 2.0 Flash', desc:'Legacy' },
];
const VOICES = [
{ id:'en-US-AriaNeural', name:'Aria', desc:'English (US) · Female' },
{ id:'en-US-JennyNeural', name:'Jenny', desc:'English (US) · Warm' },
{ id:'en-US-AnaNeural', name:'Ana', desc:'English (US) · Young' },
{ id:'en-GB-SoniaNeural', name:'Sonia', desc:'English (UK) · Female' },
{ id:'ja-JP-NanamiNeural', name:'Nanami', desc:'Japanese · Anime' },
{ id:'zh-CN-XiaoxiaoNeural', name:'Xiaoxiao', desc:'Chinese · Female' },
{ id:'zh-CN-XiaoyiNeural', name:'Xiaoyi', desc:'Chinese · Female 2' },
];
const GROUND_MODES = [
{ id:'auto', name:'Auto ground (recommended)', desc:'Pins soles to the floor every frame' },
{ id:'soft', name:'Soft ground', desc:'Gentle correction, allows hops' },
{ id:'off', name:'Off', desc:'Raw animation placement' },
];
const K = 'may5_';
const g = (k,d)=>{ try{ const v=localStorage.getItem(K+k); return v===null?d:v; }catch(e){ return d; } };
const gn = (k,d)=>{ const v=parseFloat(g(k,NaN)); return isFinite(v)?v:d; };
const gb = (k,d)=>{ const v=g(k,null); return v===null?d:v==='1'; };
try{ if(localStorage.getItem(K+'perfv')!=='3'){ ['dpr','fpsCap','adaptive'].forEach(k=>localStorage.removeItem(K+k)); localStorage.setItem(K+'perfv','3'); } }catch(e){}
const CFG = {
blinkTalk:gb('blinkTalk',false), outline:gb('outline',false),
avatar:g('avatar','May'), key:g('key',''), model:g('model','gemini-2.5-flash-lite'), voice:g('voice','en-US-AriaNeural'),
dpr:gn('dpr',Math.min(1.5,window.devicePixelRatio||1)), adaptive:gb('adaptive',true),
shadows:gb('shadows',false), gravity:gn('gravity',0.1), spring:gb('spring',true),
ground:g('ground','auto'), facing:gn('facing',0.35), motionFix:gb('motionFix',true),
life:gn('life',1), blinkRate:gn('blinkRate',1), saccade:gn('saccade',1), breath:gn('breath',1),
lookUser:gb('lookUser',true), microMove:gb('microMove',true),
pupil:gn('pupil',1), pupilAuto:gb('pupilAuto',true), moodDrift:gb('moodDrift',true),
trackHead:gb('trackHead',true), bg:g('bg','#07090e'),
lockPos:gb('lockPos',true), fpsCap:gn('fpsCap',60), hud:gb('hud',false), customName:g('customName',''),
};
const save=()=>{ try{ for(const [k,v] of Object.entries(CFG))
localStorage.setItem(K+k, typeof v==='boolean'?(v?'1':'0'):String(v)); }catch(e){} };
/* ════════════════════════ CUSTOM DROPDOWN ════════════════════════
Hand-built menu widget — no native <select>, no external JS lib.
Menu is portalled to <body> with fixed positioning so it is never
clipped by the scrolling sheet, and flips up when short on space. */
class Dropdown {
static open = null;
static bound = false;
constructor(mount,{items,value,onChange}){
this.items=items; this.value=value; this.onChange=onChange; this.hi=-1; this.isOpen=false;
this.btn=document.createElement('button'); this.btn.type='button'; this.btn.className='dd-btn';
this.btn.innerHTML='<span class="lb"><b></b><small></small></span><span class="dd-cv">▾</span>';
this.t=this.btn.querySelector('b'); this.s=this.btn.querySelector('small');
mount.appendChild(this.btn);
this.menu=document.createElement('div'); this.menu.className='dd-menu'; document.body.appendChild(this.menu);
this.btn.addEventListener('click',e=>{ e.stopPropagation(); this.toggle(); });
this.btn.addEventListener('keydown',e=>{
if(e.key==='ArrowDown'||e.key==='Enter'||e.key===' '){ e.preventDefault(); if(!this.isOpen)this.show(); else this.move(1); }
else if(e.key==='ArrowUp'){ e.preventDefault(); this.move(-1); }
else if(e.key==='Escape') this.hide();
});
if(!Dropdown.bound){
Dropdown.bound=true;
addEventListener('pointerdown',e=>{ if(e.target.closest?.('.dd-menu,.dd-btn')) return; Dropdown.open?.hide(); },true);
addEventListener('resize',()=>Dropdown.open?.hide());
addEventListener('keydown',e=>{ if(e.key==='Escape') Dropdown.open?.hide(); });
document.getElementById('panels').addEventListener('scroll',()=>Dropdown.open?.hide(),{passive:true});
}
this.render(); this.sync();
}
render(){
this.menu.innerHTML='';
this.items.forEach((it,i)=>{
const d=document.createElement('div');
d.className='dd-it'+(it.id===this.value?' sel':'');
d.innerHTML=`<span class="tk">✓</span><span>${it.name}${it.desc?`<small>${it.desc}</small>`:''}</span>`;
d.addEventListener('pointerdown',e=>e.stopPropagation());
d.addEventListener('click',()=>{ this.set(it.id,true); this.hide(); });
d.addEventListener('pointerenter',()=>{ this.hi=i; this.paint(); });
this.menu.appendChild(d);
});
}
paint(){ [...this.menu.children].forEach((c,i)=>c.classList.toggle('hi',i===this.hi)); }
move(d){ this.hi=(this.hi+d+this.items.length)%this.items.length; this.paint();
this.menu.children[this.hi]?.scrollIntoView({block:'nearest'}); this.set(this.items[this.hi].id,true); }
sync(){ const it=this.items.find(i=>i.id===this.value)||this.items[0];
if(!it) return; this.t.textContent=it.name; this.s.textContent=it.desc||''; this.s.style.display=it.desc?'':'none';
[...this.menu.children].forEach((c,i)=>c.classList.toggle('sel',this.items[i].id===this.value)); }
set(v,fire){ if(v===this.value&&fire) return; this.value=v; this.sync(); if(fire) this.onChange?.(v); }
toggle(){ this.isOpen?this.hide():this.show(); }
show(){
Dropdown.open&&Dropdown.open!==this&&Dropdown.open.hide();
Dropdown.open=this; this.isOpen=true; this.btn.classList.add('on');
const r=this.btn.getBoundingClientRect();
const below=innerHeight-r.bottom-12, above=r.top-12;
const up=below<170&&above>below;
this.menu.style.width=r.width+'px'; this.menu.style.left=r.left+'px';
this.menu.style.maxHeight=Math.min(260,(up?above:below))+'px';
if(up){ this.menu.style.top='auto'; this.menu.style.bottom=(innerHeight-r.top+6)+'px'; }
else { this.menu.style.bottom='auto'; this.menu.style.top=(r.bottom+6)+'px'; }
this.hi=this.items.findIndex(i=>i.id===this.value); this.paint();
requestAnimationFrame(()=>this.menu.classList.add('on'));
}
hide(){ this.isOpen=false; this.btn.classList.remove('on'); this.menu.classList.remove('on'); if(Dropdown.open===this)Dropdown.open=null; }
}
/* ══════════════════════ UI CONTROL BUILDERS ══════════════════════ */
const el=(t,c,h)=>{ const e=document.createElement(t); if(c)e.className=c; if(h!==undefined)e.innerHTML=h; return e; };
const pickFiles=(accept,multi,cb)=>{ const i=document.createElement('input'); i.type='file'; i.accept=accept; i.multiple=!!multi;
i.onchange=()=>{ if(i.files&&i.files.length) cb([...i.files]); }; i.click(); };
const CUSTOM_URL=new URL('__may_custom.vrm',location.href).href;
const DPR_MIN=Math.min(.85,devicePixelRatio||1), DPR_MAX=Math.min(1.75,devicePixelRatio||1.5); /* adaptive floor .85× with MSAA stays clean */
/* Fuzzy name similarity 0..1 — names are only a loose hint, never a promise. */
const norm=s=>String(s||'').toLowerCase().replace(/[^a-z0-9]/g,'');
const bigrams=s=>{ const a=new Set(); for(let i=0;i<s.length-1;i++) a.add(s.slice(i,i+2)); return a; };
function sim(a,b){ a=norm(a); b=norm(b); if(!a||!b) return 0; if(a===b) return 1;
if(a.includes(b)||b.includes(a)) return .75+.2*Math.min(a.length,b.length)/Math.max(a.length,b.length);
const A=bigrams(a),B=bigrams(b); if(!A.size||!B.size) return 0; let n=0; for(const x of A) if(B.has(x)) n++; return 2*n/(A.size+B.size); }
const IDLE_KEYS=['caring','innocent','neutral4','confusion','embarrassment'];
const Ctl={
card(p,title){ const c=el('div','card'); if(title)c.appendChild(el('div','lbl',title)); p.appendChild(c); return c; },
drop(p,label,items,value,onChange){ const w=el('div','flex flex-col gap-1.5');
if(label)w.appendChild(el('div','lbl',label)); p.appendChild(w);
return new Dropdown(w,{items,value,onChange}); },
slider(p,{label,min,max,step,value,fmt,on}){
const w=el('div','flex flex-col gap-1.5'); const r=el('div','row');
const t=el('span','text-[11px] font-medium text-gray-300',label);
const v=el('span','text-[11px] font-bold text-indigo-300');
fmt=fmt||(x=>x.toFixed(2)); v.textContent=fmt(value);
r.append(t,v); const i=el('input'); i.type='range'; i.min=min; i.max=max; i.step=step; i.value=value;
i.addEventListener('input',()=>{ const x=parseFloat(i.value); v.textContent=fmt(x); on(x); });
w.append(r,i); p.appendChild(w); return {set:x=>{i.value=x;v.textContent=fmt(x);}}; },
toggle(p,label,value,on){ const r=el('div','row');
r.appendChild(el('span','text-[11px] font-medium text-gray-300',label));
const t=el('div','tg'+(value?' on':'')); t.tabIndex=0;
const flip=()=>{ const nv=!t.classList.contains('on'); t.classList.toggle('on',nv); on(nv); };
t.addEventListener('click',flip); t.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();flip();}});
r.appendChild(t); p.appendChild(r); return {set:v=>t.classList.toggle('on',v)}; },
btn(p,label,icon,on,cls){ const b=el('button',
cls||'w-full rounded-xl py-2.5 text-[11.5px] font-bold bg-white/6 border border-white/10 hover:bg-white/12 active:scale-[.98] transition',
label);
b.addEventListener('click',on); p.appendChild(b); return b; },
grid(p,cols){ const d=el('div',`grid gap-1.5`); d.style.gridTemplateColumns=`repeat(${cols},minmax(0,1fr))`; p.appendChild(d); return d; },
};
/* ═══════════════════════ MOOD / EMOTION LIBRARY ═══════════════════════
Two parallel descriptions per mood:
m → granular VRoid Fcl_* morphs (brow + eye + mouth + teeth) — huge nuance
e → VRM preset expressions, fallback for non-VRoid avatars
Plus: iris dilation, eyelid bias, head/gaze bias, motion energy. */
const MOODS = {
neutral: {i:1.00,m:{},e:{}},
happy: {i:1.06,m:{BRW_Joy:.6,EYE_Joy:.35,MTH_Joy:.7},e:{happy:.85},h:{p:-.03}},
joyful: {i:1.16,m:{BRW_Joy:.9,EYE_Joy:.55,MTH_Joy:1,MTH_Large:.22,HA_Fung1:.2},e:{happy:1},h:{p:-.05},en:1.4},
laugh: {i:1.10,m:{BRW_Joy:1,EYE_Joy:.85,MTH_Joy:1,MTH_A:.45,HA_Fung1:.35},e:{happy:1,aa:.35},h:{p:-.07},en:1.5},
smile: {i:1.03,m:{BRW_Fun:.5,EYE_Fun:.4,MTH_Fun:.6},e:{happy:.4,relaxed:.35}},
grin: {i:1.05,m:{BRW_Fun:.6,MTH_Joy:.8,MTH_SkinFung:.4,EYE_Fun:.3},e:{happy:.7}},
love: {i:1.26,m:{BRW_Fun:.7,EYE_Joy:.5,MTH_Fun:.7},e:{happy:.75,relaxed:.45},h:{r:.06,p:-.02}},
shy: {i:1.12,m:{BRW_Sorrow:.5,EYE_Sorrow:.3,EYE_Close:.16,MTH_Small:.5},e:{relaxed:.45,sad:.3},h:{p:.06,y:.1},gz:{x:.24,y:-.16}},
proud: {i:1.00,m:{BRW_Fun:.4,MTH_Fun:.55,EYE_Fun:.2},e:{happy:.45},h:{p:-.06},lid:.14},
relaxed: {i:1.00,m:{BRW_Fun:.45,EYE_Fun:.3,MTH_Fun:.4},e:{relaxed:.85},lid:.1,en:.85},
sad: {i:0.95,m:{BRW_Sorrow:.85,EYE_Sorrow:.7,MTH_Sorrow:.7},e:{sad:.9},h:{p:.1},gz:{y:-.2},en:.7},
cry: {i:0.90,m:{BRW_Sorrow:1,EYE_Sorrow:.9,EYE_Close:.35,MTH_Sorrow:1,MTH_Down:.3},e:{sad:1},h:{p:.14},blink:1.8,en:.8},
disappointed:{i:0.96,m:{BRW_Sorrow:.55,EYE_Sorrow:.4,MTH_Sorrow:.45,MTH_Down:.25},e:{sad:.55},lid:.15,h:{p:.08},en:.7},
lonely: {i:0.97,m:{BRW_Sorrow:.6,EYE_Sorrow:.45,MTH_Small:.4},e:{sad:.6},lid:.2,gz:{y:-.18,x:.2},en:.6},
angry: {i:0.86,m:{BRW_Angry:.9,EYE_Angry:.7,MTH_Angry:.6},e:{angry:.9},blink:.7,en:1.2},
furious: {i:0.78,m:{BRW_Angry:1,EYE_Angry:1,MTH_Angry:.9,MTH_Large:.3,HA_Fung2:.3},e:{angry:1},blink:.5,en:1.6},
annoyed: {i:0.93,m:{BRW_Angry:.5,EYE_Angry:.35,MTH_Angry:.3,MTH_Small:.3},e:{angry:.45},lid:.1},
pout: {i:0.98,m:{BRW_Sorrow:.4,BRW_Angry:.3,MTH_Small:.6,MTH_Up:.3,EYE_Sorrow:.25},e:{sad:.35,angry:.25},h:{y:.08}},
surprised: {i:1.30,m:{BRW_Surprised:.9,EYE_Surprised:.8,EYE_Spread:.5,MTH_Surprised:.7,MTH_O:.3},e:{surprised:1,Surprised:1},h:{p:-.08},blink:.25,en:1.3},
shocked: {i:1.38,m:{BRW_Surprised:1,EYE_Surprised:1,EYE_Spread:.85,MTH_Surprised:1,MTH_Large:.4},e:{surprised:1,Surprised:1},blink:.15,en:1.5},
fear: {i:1.26,m:{BRW_Sorrow:.6,BRW_Surprised:.5,EYE_Surprised:.7,EYE_Spread:.5,MTH_Surprised:.5,MTH_Small:.3},e:{surprised:.65,sad:.5},h:{p:.05},blink:1.6,en:1.4},
nervous: {i:1.15,m:{BRW_Sorrow:.5,EYE_Surprised:.3,MTH_Small:.45},e:{sad:.4,surprised:.25},blink:1.7,gz:{x:.3},en:1.2},
disgust: {i:0.90,m:{BRW_Angry:.5,EYE_Angry:.4,EYE_Sorrow:.25,MTH_Angry:.4,MTH_Down:.35},e:{angry:.4,sad:.4},h:{y:.1,r:.04}},
curious: {i:1.12,m:{BRW_Surprised:.45,EYE_Spread:.3,MTH_Small:.25},e:{surprised:.3,happy:.18},h:{r:.09,p:-.03}},
confused: {i:1.05,m:{BRW_Sorrow:.35,BRW_Surprised:.3,EYE_Sorrow:.2,MTH_Small:.4},e:{sad:.3,surprised:.28},h:{r:.12},gz:{y:.14,x:-.2}},
thinking: {i:1.02,m:{BRW_Sorrow:.3,EYE_Sorrow:.15,MTH_Small:.45},e:{sad:.2},lid:.12,gz:{y:.2,x:-.28},h:{r:.06}},
smug: {i:0.98,m:{BRW_Fun:.35,EYE_Joy:.2,MTH_Fun:.5,MTH_SkinFung_L:.5},e:{happy:.4,angry:.15},lid:.2,h:{p:.05,y:.07}},
determined: {i:0.95,m:{BRW_Angry:.4,EYE_Angry:.25,MTH_Close:.4},e:{angry:.3,happy:.1},lid:.1,en:1.15},
sleepy: {i:0.90,m:{EYE_Close:.5,BRW_Sorrow:.2,MTH_Small:.3},e:{relaxed:.6},lid:.5,h:{p:.08},en:.45},
bored: {i:0.95,m:{BRW_Sorrow:.25,EYE_Close:.22,MTH_Small:.35},e:{relaxed:.3,sad:.15},lid:.28,gz:{x:.28},en:.65},
pain: {i:0.87,m:{BRW_Sorrow:.7,BRW_Angry:.4,EYE_Close:.45,MTH_Angry:.5,MTH_Large:.25},e:{angry:.45,sad:.6},blink:1.5,en:1.1},
wink: {i:1.08,m:{BRW_Fun:.5,EYE_Close_L:1,MTH_Joy:.6},e:{happy:.6,blinkLeft:1}},
};
const MOOD_KEYS = Object.keys(MOODS);
/* ════════════════════════════ UI SHELL ════════════════════════════ */
class UI{
static init(){
this.dot=document.getElementById('dot'); this.stat=document.getElementById('stat');
this.bub=document.getElementById('bub'); this.bubTxt=document.getElementById('bubTxt');
this.bubWho=document.getElementById('bubWho'); this.bubMood=document.getElementById('bubMood');
this.sheet=document.getElementById('sheet'); this.hud=document.getElementById('hud');
this.bar=document.getElementById('loadBar'); this.timer=null;
this.fixInfo=el('div','font-mono text-[9px] text-cyan-300/70 leading-relaxed'); this.built=null;
document.getElementById('bSet').onclick=()=>{ if(!this.built) this.buildPanels();
this.sheet.classList.remove('hidden','sheet-closed');
void this.sheet.offsetWidth; this.sheet.classList.add('sheet-open'); };
document.getElementById('bClose').onclick=()=>{ Dropdown.open?.hide();
this.sheet.classList.remove('sheet-open'); this.sheet.classList.add('sheet-closed');
setTimeout(()=>this.sheet.classList.add('hidden'),300); };
document.getElementById('bCam').onclick=()=>Gfx.frame('bust');
}
static syncAvatars(){ const d=this.ddAvatar; if(!d) return;
d.items=AVATARS.map(a=>({id:a.id,name:a.name,desc:a.desc})); d.render(); d.set(CFG.avatar); }
static status(t,s='ok'){ this.stat.textContent=t;
this.dot.className='w-2 h-2 rounded-full '+(s==='busy'?'bg-amber-400 shadow-[0_0_8px_#fbbf24]':
s==='err'?'bg-red-500 shadow-[0_0_8px_#ef4444]':'bg-green-500 shadow-[0_0_8px_#22c55e]'); }
static progress(p){ this.bar.style.opacity=p>0&&p<1?1:0; this.bar.style.width=(p*100)+'%'; }
static say(text,mood){ this.bubWho.textContent=CFG.avatar; this.bubMood.textContent=mood||'';
this.bubTxt.textContent=text; this.bub.classList.remove('hidden'); this.bub.classList.add('flex');
clearTimeout(this.timer); this.timer=setTimeout(()=>this.quiet(),Math.max(3200,text.length*78)); }
static quiet(){ this.bub.classList.add('hidden'); this.bub.classList.remove('flex'); }
static buildPanels(){
const tabs=document.getElementById('tabs'), panels=document.getElementById('panels');
const names=['Avatar','Motion','Face','Life','Engine','AI'];
this.pages={}; this.built={};
const make={ Avatar:()=>this.pAvatar(this.pages.Avatar), Motion:()=>{ this.pMotion(this.pages.Motion); this.motions(); },
Face:()=>{ this.pFace(this.pages.Face); this.rawChannels(); this.markMood(Mood.key); },
Life:()=>this.pLife(this.pages.Life), Engine:()=>this.pEngine(this.pages.Engine), AI:()=>this.pAI(this.pages.AI) };
const show=n=>{ Dropdown.open?.hide();
if(!this.built[n]){ this.built[n]=1; make[n](); }
[...tabs.children].forEach(c=>c.classList.toggle('act',c.textContent===n));
for(const k in this.pages){ const on=k===n; this.pages[k].classList.toggle('hidden',!on); this.pages[k].classList.toggle('flex',on); }
panels.scrollTop=0; };
names.forEach(n=>{ const b=el('button','tab',n); b.onclick=()=>show(n); tabs.appendChild(b);
const pg=el('div','flex-col gap-3.5 hidden'); panels.appendChild(pg); this.pages[n]=pg; });
show('Avatar');
}
static pAvatar(p){
const c=Ctl.card(p,'Model');
this.ddAvatar=Ctl.drop(c,null,AVATARS.map(a=>({id:a.id,name:a.name,desc:a.desc})),CFG.avatar,v=>{
CFG.avatar=v; save(); Avatar.swap(v);
});
Ctl.btn(c,'Upload your own VRM','upload-simple',()=>pickFiles('.vrm,.glb',false,f=>Avatar.loadFile(f[0])),'chip py-2');
c.appendChild(el('p','text-[10px] text-gray-500','Tip: drag & drop .vrm / .vrma files anywhere. Your uploaded model is remembered on this device.'));
const c2=Ctl.card(p,'Camera');
const gr=Ctl.grid(c2,3);
[['Face','face'],['Bust','bust'],['Full','full']].forEach(([n,m])=>{
const b=el('div','chip',n); b.onclick=()=>Gfx.frame(m); gr.appendChild(b); });
Ctl.toggle(c2,'Camera tracks head',CFG.trackHead,v=>{CFG.trackHead=v;save();});
Ctl.btn(c2,'Save screenshot (PNG)','camera',()=>Gfx.shot(),'chip py-2');
const c3=Ctl.card(p,'Background color');
const ci=document.createElement('input'); ci.type='color'; ci.className='cp'; ci.value=/^#[0-9a-f]{6}$/i.test(CFG.bg)?CFG.bg:'#07090e';
ci.addEventListener('input',()=>Gfx.setBg(ci.value));
ci.addEventListener('change',()=>{ CFG.bg=ci.value; save(); });
c3.appendChild(ci);
const gb2=Ctl.grid(c3,6);
['#07090e','#11131c','#1b1030','#0f2027','#2b1b1b','#e8e6e3'].forEach(col=>{
const b=el('div','sw'); b.style.background=col;
b.onclick=()=>{ ci.value=col; Gfx.setBg(col); CFG.bg=col; save(); }; gb2.appendChild(b); });
}
static pMotion(p){
const c=Ctl.card(p,'Motion library');
const s=el('input','inp'); s.placeholder='Search 70+ motions…'; s.type='text';
s.oninput=()=>this.motions(s.value); c.appendChild(s);
this.mList=el('div','grid grid-cols-2 gap-1.5 max-h-52 overflow-y-auto pr-1'); c.appendChild(this.mList);
const r=Ctl.grid(c,2);
Ctl.btn(r,'Idle loop','repeat',()=>Avatar.idle(true),'chip py-2');
Ctl.btn(r,'Random','shuffle',()=>{ const n=Avatar.names[Math.floor(Math.random()*Avatar.names.length)]; Avatar.play(n); },'chip py-2');
Ctl.btn(c,'Add your own .vrma motions','upload-simple',()=>pickFiles('.vrma',true,f=>Avatar.addMotions(f)),'chip py-2');
const c2=Ctl.card(p,'Position stabiliser');
c2.appendChild(el('p','text-[10.5px] leading-relaxed text-gray-400',
'These VRMA files declare a bogus rest-hips height (~0.11 m instead of ~0.81 m), so the loader amplifies the hips track by <b class="text-amber-300">6–8×</b> and the avatar sinks or flies. The stabiliser rescales, re-bases and grounds every clip.'));
Ctl.toggle(c2,'Rescale + re-base hips track',CFG.motionFix,v=>{CFG.motionFix=v;save();Avatar.clips.clear();Avatar.idle(true);});
Ctl.toggle(c2,'Lock position (never drift or move)',CFG.lockPos,v=>{CFG.lockPos=v;save();Avatar.clips.clear();Avatar.idle(true);});
Ctl.drop(c2,'Floor contact',GROUND_MODES,CFG.ground,v=>{CFG.ground=v;save();});
c2.appendChild(this.fixInfo);
}
static pFace(p){
const c=Ctl.card(p,'Emotion — '+MOOD_KEYS.length+' presets');
this.moodGrid=Ctl.grid(c,4);
MOOD_KEYS.forEach(k=>{ const b=el('div','chip'+(k==='neutral'?' act':''),k);
b.dataset.mood=k; b.onclick=()=>{ Mood.set(k,Mood.intensity,0,true); }; this.moodGrid.appendChild(b); });
Ctl.slider(c,{label:'Intensity',min:0,max:1,step:.05,value:1,on:x=>{Mood.intensity=x;Mood.set(Mood.key,x,0,true);}});
this.rawCard=Ctl.card(p,'Raw rig channels');
this.rawBox=el('div','flex flex-col gap-2 max-h-72 overflow-y-auto pr-1'); this.rawCard.appendChild(this.rawBox);
Ctl.btn(this.rawCard,'Clear manual overrides','eraser',()=>{ FaceRig.overrides.clear(); this.rawSliders?.forEach(s=>s.set(0)); },'chip py-2');
}
static pLife(p){
const c=Ctl.card(p,'Liveliness');
Ctl.slider(c,{label:'Blink frequency',min:0,max:2.5,step:.05,value:CFG.blinkRate,
fmt:x=>x<.01?'off':x.toFixed(2)+'×',on:x=>{CFG.blinkRate=x;save();}});
Ctl.slider(c,{label:'Random eye movement (idle only)',min:0,max:2.5,step:.05,value:CFG.saccade,
fmt:x=>x<.01?'off':x.toFixed(2)+'×',on:x=>{CFG.saccade=x;save();}});
Ctl.toggle(c,'Blink while talking',CFG.blinkTalk,v=>{CFG.blinkTalk=v;save();});
const c2=Ctl.card(p,'Attention');
Ctl.toggle(c2,'Look at you / cursor',CFG.lookUser,v=>{CFG.lookUser=v;save();});
const gr=Ctl.grid(Ctl.card(p,'Trigger'),3);
[['Blink','blink'],['Double','double'],['Wink','wink'],['Glance','glance'],['Startle','startle'],['Yawn','yawn']]
.forEach(([n,a])=>{ const b=el('div','chip',n); b.onclick=()=>Life.trigger(a); gr.appendChild(b); });
}
static pEngine(p){
const c=Ctl.card(p,'Renderer');
this.sDpr=Ctl.slider(c,{label:'Resolution scale',min:.5,max:2,step:.05,value:CFG.dpr,
fmt:x=>x.toFixed(2)+'×',on:x=>{CFG.dpr=x;save();Gfx.setDpr(x);}});
Ctl.toggle(c,'Adaptive performance',CFG.adaptive,v=>{CFG.adaptive=v;save();});
Ctl.drop(c,'Frame rate cap',[{id:'0',name:'Display rate (max)'},{id:'60',name:'60 FPS'},{id:'30',name:'30 FPS',desc:'Battery saver'}],String(CFG.fpsCap),v=>{CFG.fpsCap=+v;save();});
Ctl.toggle(c,'Debug HUD',CFG.hud,v=>{CFG.hud=v;save();UI.hud.style.display=v?'':'none';});
Ctl.toggle(c,'Ink outlines (heavier, ~2× draw calls)',CFG.outline,v=>{CFG.outline=v;save();Avatar.applyOutline(v);});
this.stats=el('div','font-mono text-[9px] text-cyan-300/70 leading-relaxed'); Ctl.card(p,'Diagnostics').appendChild(this.stats);
Ctl.btn(Ctl.card(p,'Data'),'Reset all settings','arrow-counter-clockwise',()=>{ if(!confirm('Reset all settings and reload?')) return;
try{ Object.keys(localStorage).filter(k=>k.startsWith(K)).forEach(k=>localStorage.removeItem(k)); }catch(e){} location.reload(); },'chip py-2');
}
static pAI(p){
const c=Ctl.card(p,'Gemini');
const i=el('input','inp'); i.type='password'; i.placeholder='API key (stored locally)'; i.value=CFG.key;
i.oninput=()=>{CFG.key=i.value.trim();save();}; c.appendChild(i);
Ctl.drop(c,'Model',MODELS,CFG.model,v=>{CFG.model=v;save();});
const c2=Ctl.card(p,'Voice');
const known=VOICES.some(x=>x.id===CFG.voice);
if(!known){ CFG.voice='en-US-AriaNeural'; save(); }
this.ddVoice=Ctl.drop(c2,'Edge TTS voice',VOICES,CFG.voice,v=>{CFG.voice=v;save();});
Ctl.btn(c2,'Test voice','speaker-high',async()=>{ UI.status('Testing voice…','busy');
try{ await AudioSys.speak([{t:'Hi! This is how I sound with this voice.',s:1,p:1}],null,'happy'); }catch(e){ console.warn(e); UI.status('Voice failed','err'); } },'chip py-2');
c2.appendChild(el('p','text-[10px] text-gray-500','Without a key May still reacts locally with moods and motions.'));
}
static motions(q=''){
if(!this.mList) return;
const f=q.trim().toLowerCase();
const list=Avatar.names.filter(n=>!f||n.toLowerCase().includes(f));
this.mList.innerHTML='';
if(!list.length){ this.mList.appendChild(el('div','col-span-2 text-[10px] text-gray-500 text-center py-3','No motions')); return; }
const fr=document.createDocumentFragment();
list.forEach(n=>{ const b=el('div','chip flex items-center justify-between gap-1'+(Avatar.current===n?' act':''),
`<span class="truncate">${n}</span><span>▸</span>`);
b.dataset.m=n; b.onclick=()=>{ Avatar.play(n); [...this.mList.children].forEach(x=>x.classList.remove('act')); b.classList.add('act'); };
fr.appendChild(b); });
this.mList.appendChild(fr);
}
static markMood(k){ this.moodGrid&&[...this.moodGrid.children].forEach(c=>c.classList.toggle('act',c.dataset.mood===k)); }
static rawChannels(){
if(!this.rawBox) return;
this.rawBox.innerHTML=''; this.rawSliders=[];
const ch=FaceRig.channelList();
if(!ch.length){ this.rawBox.appendChild(el('div','text-[10px] text-gray-500','No addressable channels.')); return; }
this.rawCard.firstChild.textContent=`Raw rig channels (${ch.length})`;
ch.forEach(name=>{ const s=Ctl.slider(this.rawBox,{label:name,min:0,max:1,step:.02,value:0,
on:x=>{ x<0.005?FaceRig.overrides.delete(name):FaceRig.overrides.set(name,x); }});
this.rawSliders.push(s); });
}
}
/* ════════════════════════════ GRAPHICS ════════════════════════════ */
class Gfx{
static init(){
this.scene=new THREE.Scene(); this.scene.background=new THREE.Color(CFG.bg); document.body.style.background=CFG.bg;
this.camera=new THREE.PerspectiveCamera(34,innerWidth/innerHeight,0.1,20);
this.camera.position.set(0,1.32,1.45);
this.renderer=new THREE.WebGLRenderer({antialias:true,powerPreference:'high-performance',
stencil:false});
this.renderer.setPixelRatio(CFG.dpr); this.renderer.setSize(innerWidth,innerHeight);
this.renderer.outputColorSpace=THREE.SRGBColorSpace;
this.renderer.toneMapping=THREE.ACESFilmicToneMapping; this.renderer.toneMappingExposure=1.0;
this.renderer.info.autoReset=false; this.renderer.debug.checkShaderErrors=false;
document.getElementById('c').appendChild(this.renderer.domElement);
this.renderer.domElement.addEventListener('webglcontextlost',e=>{ e.preventDefault(); UI.status('Graphics reset…','busy'); });
this.renderer.domElement.addEventListener('webglcontextrestored',()=>UI.status(`${CFG.avatar} ready`));
this.controls=new OrbitControls(this.camera,this.renderer.domElement);
this.controls.target.set(0,1.25,0); this.controls.enableDamping=true; this.controls.dampingFactor=.08;
this.controls.minDistance=.25; this.controls.maxDistance=4; this.controls.maxPolarAngle=Math.PI/2+.06;
this.controls.enablePan=false;
this.lights();
this._v=new THREE.Vector3(); this._v2=new THREE.Vector3();
this.pointer=new THREE.Vector2(0,0); this.pointerActive=false; this._pt=0;
addEventListener('resize',()=>{ this.camera.aspect=innerWidth/innerHeight;
this.camera.updateProjectionMatrix(); this.renderer.setSize(innerWidth,innerHeight); },{passive:true});
const dom=this.renderer.domElement;
const mv=e=>{ this.pointer.set((e.clientX/innerWidth)*2-1,-(e.clientY/innerHeight)*2+1);
this.pointerActive=true; this._pt=performance.now(); };
dom.addEventListener('pointermove',mv,{passive:true});
dom.addEventListener('pointerdown',mv,{passive:true});
}
static lights(){ /* basic: one ambient + one key light */
this.scene.add(new THREE.AmbientLight(0xfff3e8,.95));
const sun=new THREE.DirectionalLight(0xffeedd,1.5); sun.position.set(1.4,3,2.2); this.scene.add(sun);
}
static setBg(c){ CFG.bg=c; this.scene.background.set(c); document.body.style.background=c; }
static setDpr(v){ this.renderer.setPixelRatio(Math.min(v,2.5)); }
static shot(){ this.renderer.render(this.scene,this.camera);
this.renderer.domElement.toBlob(b=>{ if(!b) return; const a=document.createElement('a'); a.href=URL.createObjectURL(b);
a.download=`${CFG.avatar}-${Date.now()}.png`; a.click(); setTimeout(()=>URL.revokeObjectURL(a.href),4000); },'image/png'); }
static frame(mode='bust'){
if(!Avatar.vrm) return;
const head=Avatar.bones.head||Avatar.rawHead;
if(!head) return;
head.updateWorldMatrix(true,false); head.getWorldPosition(this._v);
const cfg={face:[0,.02,.55],bust:[0,-.1,1.1],full:[0,-.52,2.15]}[mode]||[0,-.1,1.1];
this.controls.target.set(this._v.x,this._v.y+cfg[1],this._v.z);
this.camera.position.set(this._v.x,this._v.y+cfg[1]+.04,this._v.z+cfg[2]);
this.controls.update();
}
static follow(dt){
if(!CFG.trackHead) return;
const head=Avatar.bones.head; if(!head) return;
head.getWorldPosition(this._v); this._v.y-=.1;
this.controls.target.lerp(this._v,Math.min(dt*2.2,1));
}
/* world point the avatar should look at: the cursor projected onto a plane
through her head, or simply the camera (= you) when the pointer is idle */
static gazePoint(out,headPos){
if(this.pointerActive&&performance.now()-this._pt<4500){
this._v2.set(this.pointer.x,this.pointer.y,.5).unproject(this.camera).sub(this.camera.position);
if(this._v2.lengthSq()>1e-8){
this._v2.normalize();
const d=headPos?this.camera.position.distanceTo(headPos):1.2;
return out.copy(this.camera.position).addScaledVector(this._v2,d);
}
}
return out.copy(this.camera.position);
}
}
/* ══════════════ FACE RIG — granular morphs + VRM expressions ══════════════
VRoid models expose ~57 Fcl_* morph targets (brows / eyes / mouth / teeth)
while the VRM blendshape list only exposes 14 combos. We address the raw
morphs directly for far more nuance, and fall back to VRM preset
expressions on models that do not ship the VRoid rig.
NOTE: VRMUtils.combineMorphs() is deliberately NOT used — it would bake the
morphs away and destroy this granular control. */
class FaceRig{
static bind(vrm){
this.vrm=vrm; this.mgr=vrm.expressionManager||null;
this.morphs=new Map(); this.exp=new Map();
this.frameM=new Map(); this.frameE=new Map();
this.doneM=new Map(); this.doneE=new Map();
this.overrides=new Map(); this.cache=new Map();
this.gen=(this.gen||0)+1; this.prevM=new Set(); this._fun=undefined;
vrm.scene.traverse(o=>{
if(!o.isMesh||!o.morphTargetDictionary||!o.morphTargetInfluences) return;
for(const [n,i] of Object.entries(o.morphTargetDictionary)){
const k=n.toLowerCase();
if(!this.morphs.has(k)) this.morphs.set(k,[]);
this.morphs.get(k).push([o,i]);
}
});
if(this.mgr){ for(const e of (this.mgr.expressions||[])){
const n=e.expressionName||e.name; if(n) this.exp.set(n.toLowerCase(),n); } }
this.vroid=this.morphs.has('fcl_eye_close');
this.hasBlinkLR=this.vroid?this.morphs.has('fcl_eye_close_l'):this.exp.has('blinkleft');
console.info(`[FaceRig] ${this.morphs.size} morph channels, ${this.exp.size} expressions, VRoid rig: ${this.vroid}`);
}
/* resolve a mood key (e.g. "BRW_Joy") or expression alias to a real channel */
static mKey(k){ let v=this.cache.get('m'+k); if(v!==undefined) return v;
const t=('fcl_'+k).toLowerCase(); v=this.morphs.has(t)?t:(this.morphs.has(k.toLowerCase())?k.toLowerCase():null);
this.cache.set('m'+k,v); return v; }
static eKey(k){ let v=this.cache.get('e'+k); if(v!==undefined) return v;
v=this.exp.get(k.toLowerCase())||null; this.cache.set('e'+k,v); return v; }
static morph(k,w){ const t=this.mKey(k); if(!t) return false;
const c=this.frameM.get(t)||0; if(w>c) this.frameM.set(t,w); return true; }
static express(k,w){ const t=this.eKey(k); if(!t) return false;
const c=this.frameE.get(t)||0; if(w>c) this.frameE.set(t,w); return true; }
/* channel helpers used by Life / lipsync so callers stay rig-agnostic */
static blink(l,r){
if(this.vroid){
if(this.hasBlinkLR){ this.morph('EYE_Close_L',l); this.morph('EYE_Close_R',r); }
else this.morph('EYE_Close',Math.max(l,r));
} else {
if(this.hasBlinkLR){ this.express('blinkLeft',l); this.express('blinkRight',r); }
else this.express('blink',Math.max(l,r));
}
}
static viseme(a,i,u,e,o){
if(this.vroid){ this.morph('MTH_A',a); this.morph('MTH_I',i); this.morph('MTH_U',u);
this.morph('MTH_E',e); this.morph('MTH_O',o); }
else { this.express('aa',a); this.express('ih',i); this.express('ou',u);
this.express('ee',e); this.express('oh',o); }
}
static applyMood(spec,w){
if(w<=0.001) return;
const key=(this.vroid&&spec.m)?'m':'e';
let c=spec._c; if(!c||c.gen!==this.gen) c=spec._c={gen:this.gen};
let list=c[key];
if(!list){ list=c[key]=[]; /* resolve channel names once, not every frame */
for(const [k,v] of Object.entries(spec[key]||{})){ const t=key==='m'?this.mKey(k):this.eKey(k); if(t) list.push([t,v,k]); } }
/* mouth mode: 0 manual preview (everything), 1 idle (closed mouth), 2 speaking (lip-sync owns the jaw) */
const mode=Mood.manual?0:(AudioSys.mouthLive?2:1);
if(key==='m'){
const fm=this.frameM;
const put=(t,v)=>{ if(t&&v>(fm.get(t)||0)) fm.set(t,v); };
for(let i=0;i<list.length;i++){ const t=list[i][0], k=list[i][2]; let v=list[i][1]*w;
if(mode){
if(k==='MTH_Joy'){ if(this._fun===undefined) this._fun=this.mKey('MTH_Fun');
put(t,v*(mode===2?.1:.22)); put(this._fun,v*.75); continue; }
if(OPEN_M.has(k)||k.startsWith('HA_')){
const m=mode===2?((k==='MTH_Angry'||k==='MTH_Surprised')?.15:0):.1; if(m) put(t,v*m); continue; }
if(mode===2){ if(k==='MTH_Close') continue; if(k==='MTH_Small') v*=.3; }
}
put(t,v); }
} else {
const fe=this.frameE;
for(let i=0;i<list.length;i++){ const t=list[i][0], k=list[i][2]; let v=list[i][1]*w;
if(mode){ const q=QUIET_E[k]; if(q!==undefined) v*=(mode===2&&q<.2)?0:q; }
if(v>(fe.get(t)||0)) fe.set(t,v); }
}
}
static channelList(){ return this.vroid
? [...this.morphs.keys()].map(k=>k.replace(/^fcl_/,'')).sort()
: [...this.exp.values()].sort(); }
/* expressions must be written BEFORE vrm.update() so the manager applies them */
static flushExp(){
if(!this.mgr) return;
if(!this.vroid) for(const [k,v] of this.overrides){ const t=this.eKey(k); if(t){ const c=this.frameE.get(t)||0; this.frameE.set(t,Math.max(c,v)); } }
for(const [n,v] of this.frameE){ if(Math.abs((this.doneE.get(n)||0)-v)>.002){ this.mgr.setValue(n,v); this.doneE.set(n,v);} }
for(const [n,v] of this.doneE){ if(v!==0&&!this.frameE.has(n)){ this.mgr.setValue(n,0); this.doneE.set(n,0);} }
this.frameE.clear();
}
/* raw morphs are written AFTER vrm.update(). The expression manager zeroes every morph it
binds (eyes, A/I/U/E/O …) on EACH update, so a "skip if unchanged" cache leaves them at 0
on steady frames — that was the blink / mouth flicker. Always write what is active. */
static flushMorph(){
const fm=this.frameM;
if(this.vroid){
for(const [k,v] of this.overrides){ const t=this.mKey(k); if(t){ const c=fm.get(t)||0; fm.set(t,Math.max(c,v)); } }
/* Fcl_EYE_Close and Fcl_EYE_Close_L/R are additive → blink on top of a closing mood over-shoots the lids. Merge as max(). */
const ec=fm.get('fcl_eye_close')||0;
if(ec>0) for(const k of ['fcl_eye_close_l','fcl_eye_close_r']){ const v=fm.get(k); if(v!==undefined) fm.set(k,Math.max(0,v-ec)); }
}
for(const [n,v] of fm){ const t=this.morphs.get(n); if(!t) continue;
for(let j=0;j<t.length;j++) t[j][0].morphTargetInfluences[t[j][1]]=v; }
for(const n of this.prevM){ if(fm.has(n)) continue; const t=this.morphs.get(n); if(!t) continue;
for(let j=0;j<t.length;j++) t[j][0].morphTargetInfluences[t[j][1]]=0; }
this.prevM.clear(); for(const n of fm.keys()) this.prevM.add(n);
fm.clear();
}
}
FaceRig.morphs=new Map(); FaceRig.exp=new Map(); FaceRig.overrides=new Map();
FaceRig.frameM=new Map(); FaceRig.frameE=new Map();
FaceRig.doneM=new Map(); FaceRig.doneE=new Map(); FaceRig.cache=new Map(); FaceRig.vroid=false; FaceRig.prevM=new Set(); FaceRig.gen=0;
/* ═══════════════════ IRIS RIG — real pupil dilation ═══════════════════
Scales the iris (and, weaker, the eye-highlight) vertices in X/Y around
each eye's own centroid. Vertices are gathered through the index buffer,
so it stays correct even when VRoid primitives share one vertex buffer. */
class IrisRig{
static build(vrm){
this.parts=[]; this.last=-1;
vrm.scene.traverse(o=>{
if(!o.isMesh||!o.geometry?.attributes?.position) return;
const geo=o.geometry, pos=geo.attributes.position, idx=geo.index;
const mats=Array.isArray(o.material)?o.material:[o.material];
const groups=(geo.groups&&geo.groups.length)?geo.groups:[{start:0,count:idx?idx.count:pos.count,materialIndex:0}];
for(const gp of groups){
const mat=mats[gp.materialIndex||0]||mats[0];
const tag=`${o.name||''} ${mat?.name||''}`;
if(!/iris|pupil|hitomi|highlight/i.test(tag)) continue;
if(/eyeline|eyelash|eyebrow|eyewhite|sclera|eyeextra/i.test(tag)) continue;
const used=new Set(); const end=gp.start+gp.count;
for(let i=gp.start;i<end;i++) used.add(idx?idx.getX(i):i);
if(!used.size||used.size>8000) continue;
const arr=pos.array;
let base=this._base.get(pos); if(!base){ base=new Float32Array(arr.length); base.set(arr); this._base.set(pos,base); }
let mx=0; for(const i of used) mx+=base[i*3]; mx/=used.size;
const L=[],R=[]; for(const i of used) (base[i*3]<mx?L:R).push(i);
const clusters=[L,R].filter(a=>a.length>2).map(a=>{
let cx=0,cy=0; for(const i of a){cx+=base[i*3];cy+=base[i*3+1];}
return {ix:Uint32Array.from(a),cx:cx/a.length,cy:cy/a.length}; });
if(!clusters.length) continue;
this.parts.push({attr:pos,base,clusters,k:/highlight/i.test(tag)?.72:1});
}
});
const n=this.parts.reduce((s,p)=>s+p.clusters.reduce((q,c)=>q+c.ix.length,0),0);
this.verts=n;
console.info(`[IrisRig] ${this.parts.length} iris groups, ${n} vertices`);
}
static apply(scale){
if(!this.parts.length) return;
if(Math.abs(scale-this.last)<.01) return;
this.last=scale;
for(const p of this.parts){
const s=1+(scale-1)*p.k, a=p.attr.array, b=p.base;
for(const c of p.clusters){
const ix=c.ix, cx=c.cx, cy=c.cy;
for(let k=0;k<ix.length;k++){ const o=ix[k]*3;
a[o]=cx+(b[o]-cx)*s; a[o+1]=cy+(b[o+1]-cy)*s; }
}
p.attr.needsUpdate=true;
}
}
static reset(){ this._base=new WeakMap(); this.parts=[]; this.verts=0; this.last=-1; }
}
IrisRig.reset();
/* ═══════════════════════ MOOD STATE MACHINE ═══════════════════════ */
/* Mouth discipline: when she is NOT talking, mouth-opening shapes are almost fully suppressed.
Smiles stay (Joy is swapped for the closed 'Fun' smile). Manual mood buttons are exempt. */
const OPEN_M=new Set(['MTH_A','MTH_I','MTH_U','MTH_E','MTH_O','MTH_Large','MTH_Surprised','MTH_Angry']);
const QUIET_E={aa:.08,ih:.08,ou:.08,ee:.08,oh:.08,surprised:.45,angry:.5};
class Mood{
static init(){ this.key='neutral'; this.intensity=1; this.w=0; this.target=1;
this.spec=MOODS.neutral; this.prev=MOODS.neutral; this.pw=0; this.hold=0; this.driftT=5+Math.random()*5;
this.rate=9; this.manual=false; this.soft=false; }
static set(name,intensity=1,hold=0,manual=false,soft=false){
if(!MOODS[name]) name='neutral';
const changed = name!==this.key;
if(changed){ this.prev=this.spec; this.pw=this.w; this.w=0; }
this.key=name; this.spec=MOODS[name]; this.intensity=intensity;
this.target=intensity; this.hold=hold; this.manual=manual; this.soft=soft; this.rate=soft?3.2:9;
if(manual) this.driftT=14+Math.random()*10;
UI.markMood(name);
}
static update(dt){
this.w=THREE.MathUtils.damp(this.w,this.target,this.rate,dt);
this.pw=THREE.MathUtils.damp(this.pw,0,this.rate*.8,dt);
if(this.pw>.004) FaceRig.applyMood(this.prev,this.pw);
FaceRig.applyMood(this.spec,this.w);
if(this.hold>0){ this.hold-=dt; if(this.hold<=0) this.set('neutral',1,0,false,this.soft); }
}
static get energy(){ return (this.spec.en||1); }
static get iris(){ return 1+((this.spec.i||1)-1)*this.w; }
static get lid(){ return (this.spec.lid||0)*this.w; }
static get blinkBias(){ return 1+((this.spec.blink||1)-1)*this.w; }
}
/* ══════════════════════════ LIFE SYSTEM ══════════════════════════
Randomised blinks (incl. doubles & half-blinks), ocular saccades with
micro-tremor, smooth pursuit toward you, breathing, weight shift,
head/neck/spine micro-motion and pupil dilation dynamics. */
const noise=(t,s)=>Math.sin(t*1.13+s)*.6+Math.sin(t*2.31+s*1.7)*.28+Math.sin(t*0.47+s*2.9)*.12;
class Life{
static init(){
this.t=0;
this.blinkT=0; this.nextBlink=1+Math.random()*2.5; this.bl=0; this.br=0;
this.phase='idle'; this.p=0; this.queue=0; this.half=false; this.asym=0;
this.gx=0; this.gy=0; this.tx=0; this.ty=0; this.vx=0; this.vy=0;
this.sacT=0; this.nextSac=.6; this.away=0;
this.pupil=1; this.pupilV=0; this.flash=0;
this.shiftT=3; this.shift=0; this.shiftTo=0;
this.attention=1; this.lookTarget=new THREE.Object3D();
this._v=new THREE.Vector3(); this._v2=new THREE.Vector3(); this._up=new THREE.Vector3(0,1,0);
this._r=new THREE.Vector3(); this._q=new THREE.Quaternion(); this._e=new THREE.Euler();
this.yawn=0;
this.brT=2+Math.random()*2; this.brP=1; this.brD=1; this.brK='BRW_Surprised'; this.brA=0;
}
static attach(scene,vrm){
if(!this.lookTarget.parent) scene.add(this.lookTarget);
if(vrm.lookAt){ vrm.lookAt.target=this.lookTarget; vrm.lookAt.autoUpdate=true; }
}
static trigger(a){
if(a==='blink'){ this.phase='close'; this.p=0; this.half=false; }
else if(a==='double'){ this.phase='close'; this.p=0; this.queue=1; this.half=false; }
else if(a==='wink'){ Mood.set('wink',1,1.4); this.asym=1; this.phase='close'; this.p=0; }
else if(a==='glance'){ this.away=1.2; this.tx=(Math.random()<.5?-1:1)*(.3+Math.random()*.35); this.ty=(Math.random()-.5)*.25; this.nextSac=1.2; }
else if(a==='startle'){ Mood.set('surprised',1,1.6); this.flash=1; this.phase='open'; this.p=0; }
else if(a==='yawn'){ Mood.set('sleepy',.9,3.2); this.yawn=1; }
}
static update(dt,vrm){
this.t+=dt;
const L=CFG.life;
this.attention=THREE.MathUtils.damp(this.attention,AudioSys.speaking?1:(this.away>0?.25:.8),3,dt);
/* ---- saccades: quick jumps + drift + tremor ---- */
const talking=AudioSys.eyeLock; /* audio actually playing → no random eye movement */
if(CFG.saccade>0.01&&!talking){
this.sacT+=dt*CFG.saccade;
if(this.away>0) this.away-=dt;
if(this.sacT>=this.nextSac){
this.sacT=0;
const big=Math.random()<.16;
if(big){ this.away=.8+Math.random()*1.6;
this.tx=(Math.random()<.5?-1:1)*(.22+Math.random()*.34); this.ty=(Math.random()-.45)*.3;
this.nextSac=.9+Math.random()*1.6; if(Math.random()<.55) this.queue=Math.max(this.queue,0); }
else { const s=.055;
this.tx=(Math.random()-.5)*s*2.4; this.ty=(Math.random()-.5)*s*1.7;
this.nextSac=.35+Math.random()*1.5; }
if(Math.random()<.22){ this.blinkT=Math.max(this.blinkT,this.nextBlink-.12); }
}
} else { this.tx=this.ty=0; this.away=0; this.sacT=0; } /* talking → eyes lock calmly on you */
const gz=talking?null:Mood.spec.gz;
const btx=this.tx+(gz?gz.x*Mood.w:0), bty=this.ty+(gz?gz.y*Mood.w:0);
/* critically-damped smooth-damp: gives the saccade "snap" and is stable at
any dt (a plain Euler spring blows up to NaN when a frame hitches) */
const om=20, x=om*dt, ex=1/(1+x+.48*x*x+.235*x*x*x);
let ch=this.gx-btx, tp=(this.vx+om*ch)*dt;
this.vx=(this.vx-om*tp)*ex; this.gx=btx+(ch+tp)*ex;
ch=this.gy-bty; tp=(this.vy+om*ch)*dt;
this.vy=(this.vy-om*tp)*ex; this.gy=bty+(ch+tp)*ex;
if(!isFinite(this.gx)||!isFinite(this.gy)){ this.gx=this.gy=this.vx=this.vy=0; }
const trem=CFG.microMove&&!talking?.0016*L:0;
const ox=this.gx+noise(this.t*7.3,1.7)*trem, oy=this.gy+noise(this.t*6.1,4.2)*trem;
/* ---- where the eyes point ---- */
const head=Avatar.bones.head;
if(head&&vrm.lookAt){
head.updateWorldMatrix(true,false); head.getWorldPosition(this._v);
if(CFG.lookUser) Gfx.gazePoint(this._v2,this._v); else this._v2.copy(this._v).add(Avatar.forward);
this._v2.sub(this._v);
let d=this._v2.length();
if(d<1e-4){ this._v2.copy(Avatar.forward); d=Avatar.forward.length(); }
d=Math.max(.35,d); this._v2.normalize();
this._q.setFromAxisAngle(this._up,ox); this._v2.applyQuaternion(this._q);
this._r.crossVectors(this._v2,this._up);
if(this._r.lengthSq()>1e-8){ this._r.normalize();
this._q.setFromAxisAngle(this._r,oy); this._v2.applyQuaternion(this._q); }
this.lookTarget.position.copy(this._v).addScaledVector(this._v2,d);
this.lookTarget.updateMatrixWorld();
}
/* ---- blinking ---- */
const rate=CFG.blinkRate*Mood.blinkBias;
if(rate>0.01&&(!talking||CFG.blinkTalk)){ /* blinks only while idle (unless toggled) */
this.blinkT+=dt*rate;
if(this.phase==='idle'&&this.blinkT>=this.nextBlink){
this.phase='close'; this.p=0; this.half=Math.random()<.14;
if(Math.random()<.13) this.queue=1;
}
}
if(this.phase==='close'){ this.p+=dt/(this.half?.07:.085);
if(this.p>=1){ this.p=1; this.phase='open'; } }
else if(this.phase==='open'){ this.p-=dt/(this.half?.12:.15);
if(this.p<=0){ this.p=0; this.phase='idle'; this.blinkT=0; this.asym=0;
if(this.queue>0){ this.queue--; this.nextBlink=.11; } else this.nextBlink=1.1+Math.random()*3.6; } }
const shape=this.half?.55:1;
let bv=(this.p<1?this.p*this.p*(3-2*this.p):1)*shape;
{ const mm=Mood.spec.m||{}; /* happy/smug eyes are already closed arcs: shrink the blink so lids don't over-shoot */
bv*=1-Math.min(.9,((mm.EYE_Joy||0)*.85+(mm.EYE_Fun||0)*.4)*Mood.w); }
const lid=Mood.lid+this.yawn*.35;
let bL=Math.min(1,bv+lid), bR=Math.min(1,bv+lid);
if(this.asym>0) bR=lid; /* wink */
else { const d=noise(this.t*.9,9.1)*.05; bL=Math.min(1,Math.max(0,bL+d)); bR=Math.min(1,Math.max(0,bR-d)); }
FaceRig.blink(bL,bR);
if(this.yawn>0) this.yawn=Math.max(0,this.yawn-dt*.35);
}
}
/* ══════════════════════════ AVATAR ══════════════════════════ */
const BONE_LIST=['hips','spine','chest','upperChest','neck','head','leftShoulder','rightShoulder',
'leftFoot','rightFoot','leftToes','rightToes'];
class Avatar{
static init(){
this.vrm=null; this.mixer=null; this.action=null; this.current=null;
this.blobs={}; this.names=[]; this.clips=new Map(); this.timer=null;
this.bones={}; this.rest={}; this.animated=new Set(); this.prevAnimated=new Set();
this.groundY=0; this.sole=.02; this.restHips=.8; this.yaw=0; this.token=0;
this.forward=new THREE.Vector3(0,0,1.5);
this._v=new THREE.Vector3(); this._q=new THREE.Quaternion(); this._e=new THREE.Euler();
this.fixLog=''; this._poseTok=0; this._sb=null; this.baseYaw=0; this.restYaw=0;
this.loader=new GLTFLoader();
this.loader.register(p=>new VRMLoaderPlugin(p));
this.loader.register(p=>new VRMAnimationLoaderPlugin(p));
this.idlePool=[]; this.anchor=new THREE.Vector2(); this.restHipsXZ=[0,0];
this.cur=null; this.old=[]; this.thenFn=null; this.nextIdle=null; this._playTok=0; this.lead=1.1;
}
/* ---------- cached network fetch ---------- */
static async fetchBuf(url,onProg){
try{ const c=await caches.open('may-assets-v1'); const hit=await c.match(url);
if(hit) return await hit.arrayBuffer();
const res=await fetch(url); if(!res.ok) throw new Error('HTTP '+res.status);
const clone=res.clone(); const buf=await this.readProg(res,onProg);
c.put(url,clone).catch(()=>{}); return buf;
}catch(e){
const res=await fetch(url); if(!res.ok) throw new Error('HTTP '+res.status);
return await this.readProg(res,onProg);
}
}
static async readProg(res,onProg){
const total=+(res.headers.get('content-length')||0);
if(!res.body||!total) return await res.arrayBuffer();
const rd=res.body.getReader(); const chunks=[]; let got=0;
for(;;){ const {done,value}=await rd.read(); if(done) break;
chunks.push(value); got+=value.length; onProg?.(got/total); }
const out=new Uint8Array(got); let o=0; for(const ch of chunks){ out.set(ch,o); o+=ch.length; }
return out.buffer;
}
static async swap(id){
const a=AVATARS.find(x=>x.id===id)||AVATARS[0];
try{ await this.load(a.url,a.name); }
catch(e){ console.warn(e); UI.status('Load failed: '+a.name,'err'); }
}
static async load(url,label,buf0){
const tk=++this.token;
UI.status(`Loading ${label}…`,'busy'); UI.progress(0.01);
const buf=buf0||await this.fetchBuf(url,p=>UI.progress(p*.8));
if(tk!==this.token) return;
UI.progress(.85);
const gltf=await this.loader.parseAsync(buf,'');
if(tk!==this.token) return;
const vrm=gltf.userData.vrm;
if(!vrm) throw new Error('not a VRM');
/* dispose previous */
if(this.vrm){ this.mixer?.stopAllAction(); Gfx.scene.remove(this.vrm.scene);
VRMUtils.deepDispose(this.vrm.scene); this.clips.clear(); this.vrm=null; }
/* --- optimisation pass ---
removeUnnecessaryVertices: VRoid bakes every face primitive onto ONE
3989-vertex buffer with 57 morph targets; compacting per primitive cuts
morph-texture memory dramatically. combineSkeletons reduces draw-call
bone uniforms. combineMorphs is intentionally skipped (see FaceRig). */
try{ VRMUtils.removeUnnecessaryVertices(gltf.scene); }catch(e){ console.warn('rmVerts',e); }
try{ VRMUtils.combineSkeletons(gltf.scene); }catch(e){ console.warn('combineSkel',e); }
/* rotateVRM0 sets scene.rotation.y = PI on VRM 0.x models (May is 0.0).
Never clobber it — every later yaw write is baseYaw + our own offset. */
VRMUtils.rotateVRM0(vrm);
this.baseYaw=vrm.scene.rotation.y||0;
try{ this.shrinkTextures(vrm.scene,2048); }catch(e){ console.warn('texture shrink',e); }
const aniso=Math.min(8,Gfx.renderer.capabilities.getMaxAnisotropy()); /* crisper textures at angles, zero blur */
vrm.scene.traverse(o=>{ o.frustumCulled=false;
if(o.isMesh){
for(const m of (Array.isArray(o.material)?o.material:[o.material])) for(const k of ['map','normalMap','emissiveMap','shadeMultiplyTexture'])
if(m&&m[k]&&m[k].anisotropy<aniso) m[k].anisotropy=aniso; } });
this.vrm=vrm; vrm.scene.position.set(0,0,0);
Gfx.scene.add(vrm.scene);
vrm.humanoid?.resetNormalizedPose?.();
vrm.scene.updateMatrixWorld(true);
/* normalise height to 1.6 m for consistent framing */
const box=new THREE.Box3().setFromObject(vrm.scene); const sz=box.getSize(new THREE.Vector3());
const s=1.6/(sz.y||1.6); vrm.scene.scale.setScalar(s); vrm.scene.updateMatrixWorld(true);
/* cache bones + rest rotations */
this.bones={}; this.rest={};
for(const b of BONE_LIST){
const n=vrm.humanoid?.getNormalizedBoneNode(b); if(!n) continue;
this.bones[b]=n; this.rest[b]=n.quaternion.clone();
}
this.rawHead=vrm.humanoid?.getRawBoneNode('head');
this.rawFeet=[vrm.humanoid?.getRawBoneNode('leftFoot'),vrm.humanoid?.getRawBoneNode('rightFoot')].filter(Boolean);
this.restHips=vrm.humanoid?.normalizedRestPose?.hips?.position?.[1]
?? (this.bones.hips?.position.y||0.8);
/* sole offset: distance from foot bone to the floor at rest */
const box2=new THREE.Box3().setFromObject(vrm.scene);
let fy=Infinity; for(const f of this.rawFeet){ f.updateWorldMatrix(true,false); fy=Math.min(fy,f.getWorldPosition(this._v).y); }
this.sole=isFinite(fy)?Math.max(0,fy-box2.min.y):0.02;
this.groundY=0; this.yaw=0;
/* rest yaw of the hips: the reference the face-forward lock steers back to */
const hp=this.bones.hips;
if(hp){ hp.updateWorldMatrix(true,false); hp.getWorldQuaternion(this._q);
this._v.set(0,0,1).applyQuaternion(this._q); this.restYaw=Math.atan2(this._v.x,this._v.z); }
else this.restYaw=this.baseYaw;
/* position anchor: where the hips sit at rest — the lock pins them here forever */
if(hp){ hp.getWorldPosition(this._v); this.anchor.set(this._v.x,this._v.z); } else this.anchor.set(0,0);
const rp=vrm.humanoid?.normalizedRestPose?.hips?.position; this.restHipsXZ=rp?[rp[0],rp[2]]:[0,0];
/* own the proxy so createVRMAnimationClip neither warns nor invents one */
if(vrm.lookAt&&!vrm.scene.children.some(o=>o instanceof VRMLookAtQuaternionProxy)){
const px=new VRMLookAtQuaternionProxy(vrm.lookAt); px.name='VRMLookAtQuaternionProxy'; vrm.scene.add(px);
}
FaceRig.bind(vrm);
Life.attach(Gfx.scene,vrm);
vrm.springBoneManager=null; /* physics removed: VRMA fully drives hair/cloth bones' parents, nothing simulated */
this.mixer=new THREE.AnimationMixer(vrm.scene);
this.action=null; this.current=null; this.animated.clear();
this.cur=null; this.old=[]; this.thenFn=null; this.nextIdle=null; this._playTok++;
Gfx.frame('bust'); this.applyOutline(CFG.outline);
UI.rawChannels(); UI.progress(1);
UI.fixInfo.textContent=`rig ${FaceRig.vroid?'VRoid granular':'VRM presets'}`;
UI.status(`${label} ready`);
Mood.set('neutral',1,0);
if(this.names.length) this.idle(true);
return true;
}
/* ---------- user uploads ---------- */
static customEntry(name){
if(AVATARS.some(a=>a.id===name&&!a.custom)) name+=' (custom)';
const e={id:name,name,desc:'Uploaded · saved on this device',url:CUSTOM_URL,custom:true};
const i=AVATARS.findIndex(a=>a.custom); if(i>=0) AVATARS[i]=e; else AVATARS.push(e); return e;
}
static async restoreCustom(){
try{ if(CFG.customName&&await (await caches.open('may-assets-v1')).match(CUSTOM_URL)) this.customEntry(CFG.customName); }catch(e){}
}
static async loadFile(file){
try{
const buf=await file.arrayBuffer();
const e=this.customEntry(file.name.replace(/\.(vrm|glb)$/i,'').slice(0,24)||'Custom');
if(await this.load(null,e.name,buf)){
CFG.avatar=e.id; CFG.customName=e.id; save(); UI.syncAvatars();
try{ await (await caches.open('may-assets-v1')).put(CUSTOM_URL,new Response(buf)); }catch(_){}
} else { const i=AVATARS.indexOf(e); if(i>=0&&e.id!==CFG.customName) AVATARS.splice(i,1); }
}catch(e){ console.warn(e); UI.status('Not a valid VRM file','err'); }
}
static addMotions(files){
const ok=files.filter(f=>/\.vrma$/i.test(f.name)); if(!ok.length){ UI.status('Only .vrma files are supported','err'); return; }
for(const f of ok){ const k=f.name.replace(/\.vrma$/i,''); this.blobs[k]=f; this.clips.delete(k); if(!this.names.includes(k)) this.names.push(k); }
this.names.sort(); this.buildIdlePool(); UI.motions(); UI.status(`Added ${ok.length} motion${ok.length>1?'s':''}`);
if(this.vrm&&ok.length===1) this.play(ok[0].name.replace(/\.vrma$/i,''));
}
/* ═══ VRMA POSITION STABILISER ═══
These VRMA declare rest-hips ≈0.11 m (real value ≈0.81 m) so three-vrm
multiplies the hips translation by 6–8×, flinging the avatar under the
floor. We detect the implausible rest value, undo that scale, re-base the
curve to an upright reference frame, high-pass X/Z so travel is removed
but sway survives, and clamp anything still extreme. */
static stabilise(clip,vrma){
const keep=[]; let note='';
let bogus=1;
const ra=vrma?.restHipsPosition?.y;
if(CFG.motionFix&&ra!==undefined&&(ra<0.35||ra>1.6)&&ra!==0){
bogus=this.restHips/ra;
note=`rest ${ra.toFixed(3)}m → undo ×${bogus.toFixed(2)}`;
}
for(const tr of clip.tracks){
const n=tr.name, ln=n.toLowerCase();
if(/expression|blendshape|morph/i.test(ln)) continue; /* mood engine owns the face */
if(/lookatquaternionproxy/i.test(ln)) continue; /* gaze engine owns the eyes */
if(ln.endsWith('.scale')) continue; /* never trust scale */
if(ln.endsWith('.position')){
const isHips=/hips|root|armature/i.test(ln);
if(!isHips) continue; /* drop all other translation: keeps rig intact */
if(CFG.motionFix) this.fixHips(tr,bogus);
if(CFG.lockPos) this.lockXZ(tr);
keep.push(tr); continue;
}
keep.push(tr);
}
clip.tracks=keep;
this.fixLog=note||'clip within normal range';
return clip;
}
static fixHips(tr,bogus){
const v=tr.values, n=v.length/3;
if(n<1) return;
if(bogus!==1) for(let i=0;i<v.length;i++) v[i]/=bogus; /* recover raw metres */
/* Y: re-base to an upright reference (90th percentile) so the pose sits at
rest height, keeping crouches / hops as relative motion */
const ys=new Float64Array(n); for(let i=0;i<n;i++) ys[i]=v[i*3+1];
const sorted=Float64Array.from(ys).sort();
const ref=sorted[Math.min(n-1,Math.floor(n*0.9))];
const dy=this.restHips-ref;
for(let i=0;i<n;i++) v[i*3+1]=this.restHips+THREE.MathUtils.clamp(ys[i]+dy-this.restHips,-0.45,0.35);
/* X/Z: subtract a moving average → net travel gone, sway preserved */
for(const ax of [0,2]){
const a=new Float64Array(n); for(let i=0;i<n;i++) a[i]=v[i*3+ax];
const pre=new Float64Array(n+1); for(let i=0;i<n;i++) pre[i+1]=pre[i]+a[i];
const w=Math.max(1,Math.round(n*0.22));
for(let i=0;i<n;i++){
const s=Math.max(0,i-w), e=Math.min(n,i+w+1);
const avg=(pre[e]-pre[s])/(e-s);
v[i*3+ax]=THREE.MathUtils.clamp((a[i]-avg)*0.85,-0.14,0.14);
}
}
}
/* hard root lock: hips X/Z pinned to the rest pose, so no clip can walk, drift or sway the avatar */
static lockXZ(tr){ const v=tr.values, x=this.restHipsXZ[0], z=this.restHipsXZ[1];
for(let i=0;i<v.length;i+=3){ v[i]=x; v[i+2]=z; } }
static async clip(name){
if(this.clips.has(name)) return this.clips.get(name);
const blob=this.blobs[name]; if(!blob||!this.vrm) return null;
try{
const gltf=await this.loader.parseAsync(await blob.arrayBuffer(),'');
const vrma=gltf.userData.vrmAnimations?.[0]; if(!vrma) return null;
const c=this.stabilise(createVRMAnimationClip(vrma,this.vrm),vrma);
this.clips.set(name,c);
if(this.clips.size>26){ const k=this.clips.keys().next().value; this.clips.delete(k); }
return c;
}catch(e){ console.warn('clip',name,e); return null; }
}
/* Eased, complementary crossfade (weights always sum to 1 → no dip toward the bind pose, no pop). */
static async play(name,{loop=false,fade=1.1,then}={}){
if(!this.vrm||!this.blobs[name]) return;
const tok=++this._playTok;
const c=await this.clip(name); if(!c||!this.vrm||tok!==this._playTok) return;
if(!this.mixer) this.mixer=new THREE.AnimationMixer(this.vrm.scene);
let a=this.mixer.clipAction(c), clone=false;
if((this.cur&&this.cur.a===a)||this.old.some(o=>o.a===a)){ a=this.mixer.clipAction(c.clone()); clone=true; } /* same clip twice in a row */
a._clone=clone;
a.reset(); a.setLoop(loop?THREE.LoopRepeat:THREE.LoopOnce,Infinity); a.clampWhenFinished=true;
a.setEffectiveTimeScale(1); a.setEffectiveWeight(0); a.play();
for(const o of this.old) o.w0=o.a.getEffectiveWeight();
if(this.cur) this.old.push({a:this.cur.a,w0:this.cur.a.getEffectiveWeight()});
const now=new Set(); for(const t of c.tracks) now.add(t.name.split('.')[0]);
this.cur={a,t:0,d:this.old.length?fade:Math.min(fade,.6),now};
this.action=a; this.current=name;
this.animated=new Set([...now,...this.animated]);
UI.fixInfo.textContent=`▸ ${name} · ${c.duration.toFixed(2)}s · ${c.tracks.length} tracks · ${this.fixLog}`;
const chain=(then===undefined)?()=>this.idle():then;
this.thenFn=(chain&&!loop)?chain:null;
this.lead=Math.min(1.1,c.duration*.45);
if(this.thenFn){ /* pre-parse the next clip now so the switch never hitches */
const n=this.nextIdle=this.pickIdle();
if(n) setTimeout(()=>{ if(this.nextIdle===n) this.clip(n); },700);
}
}
static fadeStep(dt){
const c=this.cur; if(!c) return;
c.t=Math.min(c.d,c.t+dt);
const x=c.d>0?c.t/c.d:1, k=x*x*x*(x*(x*6-15)+10); /* smootherstep */
c.a.setEffectiveWeight(k);
for(const o of this.old) o.a.setEffectiveWeight(o.w0*(1-k));
if(c.t>=c.d&&this.old.length){
for(const o of this.old){ o.a.stop(); if(o.a._clone) this.mixer.uncacheClip(o.a.getClip()); }
this.old.length=0; this.animated=c.now;
}
}
/* idle = exactly these 5 (best fuzzy match per key; the file name only has to look ~20% like it) */
static buildIdlePool(){
const used=new Set(); this.idlePool=[];
for(const k of IDLE_KEYS){
let best=null,bs=.2;
for(const n of this.names){ if(used.has(n)) continue; const v=sim(n,k); if(v>bs){ bs=v; best=n; } }
if(best){ used.add(best); this.idlePool.push(best); }
}
if(!this.idlePool.length) this.idlePool=this.names.slice(0,2);
}
/* weighted-random pick among the closest few matches → "confusion" may become the sad one, lol */
static loose(q){
if(!this.names.length) return null;
if(q&&this.blobs[q]) return q;
const sc=this.names.map(n=>[n,sim(n,q||'')]).sort((a,b)=>b[1]-a[1]).slice(0,4);
let tot=0; for(const x of sc) tot+=x[1]+.2; let r=Math.random()*tot;
for(const x of sc){ r-=x[1]+.2; if(r<=0) return x[0]; }
return sc[0][0];
}
static pickIdle(){
const pool=this.idlePool.length?this.idlePool:this.names; if(!pool.length) return null;
const r=()=>pool[Math.floor(Math.random()*pool.length)];
let n=r(); if(n===this.current&&pool.length>1&&Math.random()<.65) n=r();
return n;
}
static idle(force){
if(!this.vrm||!this.names.length) return;
const n=(this.nextIdle&&this.blobs[this.nextIdle])?this.nextIdle:this.pickIdle(); this.nextIdle=null;
if(n) this.play(n,{fade:1.1,then:()=>this.idle()});
}
static act(name){ if(!this.blobs[name]) return this.idle();
this.play(name,{fade:.9,then:()=>this.idle()}); }
/* ---------- perf helpers ---------- */
static applyOutline(on){
if(!this.vrm) return;
this.vrm.scene.traverse(o=>{ if(!o.isMesh||!Array.isArray(o.material)) return;
for(const m of o.material) if(m&&m.isMToonMaterial&&(m.isOutline||m.side===THREE.BackSide)) m.visible=!!on; });
}
static shrinkTextures(root,max){
const KEYS=['map','emissiveMap','normalMap','shadeMultiplyTexture','shadingShiftTexture','matcapTexture','rimMultiplyTexture','outlineWidthMultiplyTexture','uvAnimationMaskTexture'];
const seen=new Map();
root.traverse(o=>{ if(!o.isMesh) return;
for(const m of (Array.isArray(o.material)?o.material:[o.material])){ if(!m) continue;
for(const k of KEYS){ const t=m[k]; if(!t||!t.isTexture||!t.image) continue;
const im=t.image, w=im.width||im.videoWidth, h=im.height||im.videoHeight;
if(!w||!h||Math.max(w,h)<=max) continue;
let c=seen.get(im);
if(!c){ const sc=max/Math.max(w,h); c=document.createElement('canvas');
c.width=Math.max(1,Math.round(w*sc)); c.height=Math.max(1,Math.round(h*sc));
const x=c.getContext('2d'); x.imageSmoothingEnabled=true; x.imageSmoothingQuality='high'; x.drawImage(im,0,0,c.width,c.height);
seen.set(im,c); }
t.image=c; t.needsUpdate=true; } } });
}
static async loadMotions(url){
try{
UI.status('Loading motions…','busy');
if(!window.JSZip) await new Promise((r,j)=>{ const s=document.createElement('script');
s.src='https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js'; s.onload=r; s.onerror=j; document.head.appendChild(s); });
const buf=await this.fetchBuf(url,p=>UI.progress(p));
const zip=await window.JSZip.loadAsync(buf);
const jobs=[];
zip.forEach((path,e)=>{ if(!e.dir&&/\.vrma$/i.test(path)){
const n=path.split('/').pop().replace(/\.vrma$/i,'');
jobs.push(e.async('blob').then(b=>{ this.blobs[n]=b; if(!this.names.includes(n)) this.names.push(n); })); } });
await Promise.all(jobs);
this.names.sort();
this.buildIdlePool();
UI.progress(1); UI.motions(); UI.status(`${CFG.avatar} ready`);
if(this.vrm) this.idle(true);
}catch(e){ console.warn('motions',e); UI.status('Motions unavailable','err'); }
}
/* additive procedural pose on top of the animation */
static pose(name,rx,ry,rz){
const n=this.bones[name]; if(!n) return;
if(!this.animated.has(n.name)){ const r=this.rest[name]; if(r) n.quaternion.copy(r); }
if(!rx&&!ry&&!rz) return;
this._e.set(rx,ry,rz,'YXZ'); this._q.setFromEuler(this._e); n.quaternion.multiply(this._q);
}
/* absolute floor solver — the final safety net for any broken clip */
static solveGround(dt){
const vrm=this.vrm; if(!vrm) return;
vrm.scene.position.x=0; vrm.scene.position.z=0;
if(CFG.lockPos&&this.bones.hips){ /* runtime anchor: cancels any residual hips offset (blends, procedural, odd clips) */
const h=this.bones.hips; h.updateWorldMatrix(true,false); h.getWorldPosition(this._v);
vrm.scene.position.x=this.anchor.x-this._v.x; vrm.scene.position.z=this.anchor.y-this._v.z;
}
if(CFG.ground==='off'||!this.rawFeet.length){ vrm.scene.position.y=0; this.groundY=0; return; }
let low=Infinity;
for(const f of this.rawFeet){ f.updateWorldMatrix(true,false); low=Math.min(low,f.getWorldPosition(this._v).y); }
if(!isFinite(low)) return;
const err=low-this.sole; /* >0 floating, <0 sunk */
const soft=CFG.ground==='soft';
let want=this.groundY-err;
/* asymmetric budget: lifting a sunk avatar is always right, pushing one
down is usually a jump or a seated pose, so it stays small and slow */
want=THREE.MathUtils.clamp(want,soft?-0.06:-0.12,0.6);
const rate=(want>this.groundY)?(soft?5:13):(soft?1.1:2.2);
this.groundY=THREE.MathUtils.damp(this.groundY,want,rate,dt);
vrm.scene.position.y=this.groundY;
}
/* proportional yaw controller: slowly cancels rotation a clip accumulates so
she drifts back to facing you, without fighting deliberate turns */
static solveFacing(dt){
const vrm=this.vrm, h=this.bones.hips; if(!vrm||!h) return;
if(CFG.facing<=0.01){
this.yaw=THREE.MathUtils.damp(this.yaw,0,2,dt);
vrm.scene.rotation.y=this.baseYaw+this.yaw; return;
}
h.updateWorldMatrix(true,false); h.getWorldQuaternion(this._q);
this._v.set(0,0,1).applyQuaternion(this._q);
let err=Math.atan2(this._v.x,this._v.z)-this.restYaw;
while(err>Math.PI) err-=Math.PI*2; while(err<-Math.PI) err+=Math.PI*2;
this.yaw=THREE.MathUtils.clamp(this.yaw-err*Math.min(1,dt*CFG.facing*1.1),-Math.PI,Math.PI);
vrm.scene.rotation.y=this.baseYaw+this.yaw;
}
static step(dt){
if(!this.vrm) return;
this.fadeStep(dt);
if(this.mixer) this.mixer.update(dt);
const c=this.cur;
if(this.thenFn&&c&&c.a.time>=c.a.getClip().duration-this.lead){ const f=this.thenFn; this.thenFn=null; f(); }
}
}
/* ═══════════════════ AUDIO / LIP-SYNC ═══════════════════ */
class AudioSys{
static init(){ this.ctx=null; this.an=null; this.speaking=false; this.playing=false;
this.tok=null; this.client=null; this.vis={a:0,i:0,u:0,e:0,o:0}; this.el=null; this.src=null;
this.eyeUntil=0; this.tail=0; this.ref=.05; this.env=0; this.cls={a:.4,f:.3,d:.3}; this._wake=null;
}
static get eyeLock(){ return this.playing||performance.now()<this.eyeUntil; }
static get mouthLive(){ return this.playing||performance.now()<this.tail; }
static async ensure(){
if(!this.ctx){ this.ctx=new (window.AudioContext||window.webkitAudioContext)();
this.an=this.ctx.createAnalyser(); this.an.fftSize=1024; this.an.smoothingTimeConstant=.15; this.an.minDecibels=-95;
this.tf=new Float32Array(this.an.fftSize); this.ff=new Float32Array(this.an.frequencyBinCount);
this.an.connect(this.ctx.destination);
this.el=new Audio(); this.el.crossOrigin='anonymous';
this.src=this.ctx.createMediaElementSource(this.el); this.src.connect(this.an); }
if(this.ctx.state==='suspended') await this.ctx.resume();
}
/* ---- Gradio Edge-TTS space (Unmid/Zerogpu, route /speech) ---- */
static getGradioClient(){ /* lazy singleton; the in-flight promise is shared, so warm-up + first speech never connect twice */
if(!this._clientP){
this._clientP=import('https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js')
.then(({Client})=>Client.connect('Unmid/Zerogpu'))
.then(c=>{ this.client=c; return c; })
.catch(e=>{ this._clientP=null; this.client=null; throw e; }); /* failed connect → next call retries */
}
return this._clientP;
}
static gradio(){ return this.getGradioClient(); }
static async tts(ch,retry=true){
try{
const c=await this.getGradioClient();
const speed=Math.min(1.5,Math.max(.8,+ch.s||1)), pitch=Math.min(1.5,Math.max(.7,+ch.p||1));
const r=await c.predict('/speech',[String(ch.t), CFG.voice, speed, pitch]);
let d=r.data?.[0];
if(d&&typeof d==='object') d=d.url||(d.path?`${String(c.config?.root||'').replace(/\/$/,'')}/gradio_api/file=${d.path}`:null);
if(!d) throw new Error('no audio in response');
return d;
}catch(e){ console.warn('[TTS]',e);
if(retry){ this._clientP=null; this.client=null; return this.tts(ch,false); }
UI.status('Voice failed — check console [TTS]','err');
return null; }
}
static cancel(){ this.tok=null; this.speaking=false; this.playing=false; this.eyeUntil=0; this.tail=0;
try{ this.el?.pause(); }catch(e){} this._wake?.(); UI.quiet(); }
static async speak(chunks,vrma,mood){
await this.ensure();
const tok={}; this.tok=tok; this.speaking=true;
const m=mood&&MOODS[mood]?mood:'happy';
let started=false;
/* motion + emotion begin exactly when the first sound starts — never while TTS is still rendering */
const begin=()=>{ if(started) return; started=true; Mood.set(m,.95,0); if(vrma&&Avatar.blobs[vrma]) Avatar.act(vrma); };
const q=[this.tts(chunks[0])];
for(let i=0;i<chunks.length;i++){
if(this.tok!==tok) break;
const url=await q[i];
if(this.tok!==tok) break;
if(i+1<chunks.length) q[i+1]=this.tts(chunks[i+1]);
if(!url){ begin(); UI.say(chunks[i].t,mood);
await new Promise(r=>setTimeout(r,Math.min(2600,chunks[i].t.length*55))); continue; }
await new Promise(r=>{
let fin=false; const done=()=>{ if(fin) return; fin=true; this.playing=false;
const n=performance.now(); this.eyeUntil=n+450; this.tail=n+250; this._wake=null; r(); };
this._wake=done;
this.el.onended=done; this.el.onerror=done;
this.el.onplaying=()=>{ this.playing=true; begin(); UI.say(chunks[i].t,mood); };
this.el.src=url; this.el.play().catch(done); });
}
if(this.tok===tok){ this.speaking=false; this.playing=false;
Mood.set(m,.35,2.5);
UI.quiet(); UI.status(`${CFG.avatar} ready`); }
}
/* ---- lip sync ----
Real speech is a train of syllables: the jaw opens on each vowel and closes in between.
Loudness (relative to a slow-moving peak) drives HOW MUCH the mouth opens, a gate closes it in
pauses, and the spectrum (dark / open / bright) picks WHICH vowel shape — so it moves like talking,
not like a flapping jaw. */
static update(dt){
const v=this.vis;
if(!this.playing||!this.an){
const r=Math.exp(-dt*20); let sum=0; this.env*=r;
for(const k in v){ v[k]*=r; sum+=v[k]; }
if(sum>.004) FaceRig.viseme(v.a,v.i,v.u,v.e,v.o); else if(sum>0){ for(const k in v) v[k]=0; FaceRig.viseme(0,0,0,0,0); }
return; }
this.an.getFloatTimeDomainData(this.tf); this.an.getFloatFrequencyData(this.ff);
const tf=this.tf, n=tf.length; let ss=0; for(let i=0;i<n;i++) ss+=tf[i]*tf[i];
const rms=Math.sqrt(ss/n);
const bw=this.ctx.sampleRate/this.an.fftSize, ff=this.ff, top=Math.min(ff.length-1,Math.floor(9000/bw));
let b1=0,b2=0,b3=0,b4=0,bh=0;
for(let i=Math.max(1,Math.floor(200/bw));i<=top;i++){ const f=i*bw, p=Math.pow(10,ff[i]/10);
if(f<550) b1+=p; else if(f<1100) b2+=p; else if(f<1900) b3+=p; else if(f<3200) b4+=p; else if(f>=4500) bh+=p; }
const tot=b1+b2+b3+b4+1e-12;
/* level: normalised to a slowly decaying peak so any voice / volume maps to the same mouth range */
this.ref=Math.max(rms,this.ref*Math.exp(-dt/2.5),.02);
let lvl=rms<.006?0:rms/this.ref; lvl=Math.max(0,Math.min(1,(lvl-.14)/.86));
const open=Math.pow(lvl,.85);
this.env+=(open-this.env)*(1-Math.exp(-dt*(open>this.env?42:34)));
/* vowel colour, smoothed ~50 ms so shapes don't chatter */
const wa=Math.min(1,(b2+.5*b3)/tot*1.6), wf=Math.min(1,(b4+.6*b3)/tot*5), wd=Math.min(1,b1/tot*1.2)*(1-wf*.7), ws=wa+wf+wd+1e-6;
const ks=1-Math.exp(-dt*20), c=this.cls;
if(lvl>0){ c.a+=(wa/ws-c.a)*ks; c.f+=(wf/ws-c.f)*ks; c.d+=(wd/ws-c.d)*ks; }
const fric=Math.min(1,bh/(bh+tot*4+1e-12)), e=Math.min(1,this.env*1.3), cl=1-fric*.75;
const t={ a:Math.min(.85,e*(c.a*.9+c.f*.2+c.d*.25)*cl), e:e*c.f*.55*cl, i:e*c.f*.35+fric*e*.3,
o:e*c.d*.7*cl, u:e*c.d*.35*cl };
for(const k in t){ const kk=1-Math.exp(-dt*(t[k]>v[k]?38:30)); v[k]+=(t[k]-v[k])*kk; }
FaceRig.viseme(v.a,v.i,v.u,v.e,v.o);
}
}
/* ═══════════════════════════ AI ═══════════════════════════ */
class AI{
static prompt(){
const anims=Avatar.names.slice(0,120).join(', ');
return `You are ${CFG.avatar}, a warm, playful, emotionally expressive 3D anime companion.
Reply with ONE minified JSON object only. No markdown fences.
Schema:
{"vrma":"<animation name>","emotion":"<mood>","speech":[{"p":1.1,"s":1.0,"t":"first clause,"},{"p":1.2,"s":1.05,"t":"second clause."}]}
Voice acting: happy → p 1.15-1.4 ; excited → p 1.3-1.5 s 1.1-1.3 ; sad → p 0.75-0.9 s 0.8-0.95 ; angry → p 1.2-1.4 s 1.2-1.4 ; thinking → p 0.85-1.0 s 0.85.
Moods (these must truly match the content): ${MOOD_KEYS.join(', ')}
Animations (names are only LOOSE hints, treat each name as only ~20% relevant to how the motion really looks): ${anims}
Animation rule: never choose by literal name. Pick ANY animation whose vibe could loosely fit the moment, even if the name says something else. Example: "confusion" can be used for sad or worried, "embarrassment" for shy, flattered or guilty, "caring" for comforting, "innocent" for teasing or playful. Mix it up, surprise the user a little, and avoid repeating the last animation (${Avatar.current||'none'}). The mood and the speech carry the real emotion; the animation is just color.
Rules: 2-4 speech chunks, natural commas, keep each chunk under 90-120 chars. be naughty and playful sometimes adds oo. ah. oh. wirds rarely to add a depth`;
}
static local(text){
const t=text.toLowerCase();
const pick=(m,v,words)=>words.some(w=>t.includes(w))?{m,v}:null;
const r=pick('joyful','joy',['yay','awesome','great','love it','amazing','happy'])
||pick('love','love',['love you','cute','beautiful','pretty'])
||pick('sad','sadness',['sad','sorry','cry','miss you','lonely'])
||pick('angry','anger',['angry','mad','stupid','hate'])
||pick('surprised','surprise',['what','wow','really','no way','omg'])
||pick('shy','embarrassment',['shy','blush','embarrass'])
||pick('curious','curiosity',['why','how','who','what if','tell me'])
||pick('thinking','confusion',['think','maybe','hmm','guess'])
||{m:'happy',v:'joy'};
const lines={
joyful:["That makes me really happy,","thank you for telling me!"],
love:["You're so sweet,","you're going to make me blush."],
sad:["Oh… that sounds heavy,","I'm right here with you."],
angry:["Hey, that's not okay,","I won't let that slide."],
surprised:["Wait, really?","I did not see that coming!"],
shy:["Ah— um,","you're being unfair saying that…"],
curious:["Ooh, tell me more,","I want to understand it properly."],
thinking:["Hmm, let me think about that,","give me a second."],
happy:["I'm listening,","tell me everything."],
}[r.m];
return { vrma:r.v, emotion:r.m, speech:lines.map((t,i)=>({p:1+i*.08,s:1,t})) };
}
static async send(text){
UI.status('Thinking…','busy'); AudioSys.cancel(); Mood.set('thinking',.7,0);
let res;
if(!CFG.key) res=this.local(text);
else{
try{
const body={contents:[{role:'user',parts:[{text:this.prompt()+'\nUser says: '+text}]}],
generationConfig:{responseMimeType:'application/json',temperature:.85,maxOutputTokens:400}};
const r=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${CFG.model}:generateContent?key=${encodeURIComponent(CFG.key)}`,
{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
if(!r.ok) throw new Error('HTTP '+r.status);
const d=await r.json();
const raw=d.candidates?.[0]?.content?.parts?.[0]?.text||'{}';
res=JSON.parse(raw.match(/\{[\s\S]*\}/)?.[0]||raw);
}catch(e){ console.warn('ai',e); UI.status('AI offline — local mode','err'); res=this.local(text); }
}
const vrma=Avatar.loose(res.vrma||res.emotion); /* exact if it exists, otherwise a loose (~20%) match */
if(Array.isArray(res.speech)&&res.speech.length) await AudioSys.speak(res.speech,vrma,res.emotion);
else{ Mood.set(res.emotion||'happy',.9,4); vrma&&Avatar.act(vrma); UI.status(`${CFG.avatar} ready`); }
}
}
/* ═══════════════════════════ LOOP ═══════════════════════════ */
const clock=new THREE.Clock();
let frames=0,last=performance.now(),hudT=0,avg=60,lowT=0,highT=0,dprCeil=Infinity;
const fpsEl=document.getElementById('fps');
let lastT=0;
function tick(ts=performance.now()){
if(CFG.fpsCap&&ts-lastT<1000/CFG.fpsCap-3) return;
lastT=ts;
const dt=Math.min(clock.getDelta(),.05);
Gfx.controls.update();
if(Avatar.vrm){
const vrm=Avatar.vrm;
Avatar.step(dt);
Mood.update(dt);
Life.update(dt,vrm);
AudioSys.update(dt);
FaceRig.flushExp();
vrm.update(dt);
FaceRig.flushMorph();
Avatar.solveGround(dt);
}
Gfx.follow(dt);
Gfx.renderer.render(Gfx.scene,Gfx.camera);
frames++;
const now=performance.now();
if(now-last>=1000){
const f=frames*1000/(now-last); avg=avg*.5+f*.5; frames=0; last=now;
if(fpsEl){ fpsEl.textContent=Math.round(f)+' FPS';
fpsEl.className='text-[10px] font-bold px-2 '+(f>=48?'text-green-400':f>=28?'text-amber-400':'text-red-400'); }
if(CFG.adaptive){
const tg=CFG.fpsCap||60, lo=tg*.8, hi=tg*.95;
if(f<lo){ lowT++; highT=0; if(lowT>=2&&CFG.dpr>DPR_MIN){ dprCeil=Math.max(DPR_MIN,CFG.dpr-.1); CFG.dpr=Math.max(DPR_MIN,CFG.dpr-.15); Gfx.setDpr(CFG.dpr); UI.sDpr?.set(CFG.dpr); save(); lowT=0; } }
else if(f>hi){ highT++; lowT=0; if(highT>=6&&CFG.dpr<Math.min(DPR_MAX,dprCeil)){ CFG.dpr=Math.min(DPR_MAX,CFG.dpr+.1); Gfx.setDpr(CFG.dpr); UI.sDpr?.set(CFG.dpr); save(); highT=0; } }
else { lowT=0; highT=0; }
}
const r=Gfx.renderer.info.render, fr=Math.max(1,Math.round(f));
if(UI.stats&&!UI.sheet.classList.contains('hidden')) UI.stats.innerHTML=
`draws ${Math.round(r.calls/fr)}/frame · tris ${(r.triangles/fr/1000).toFixed(1)}k · dpr ${CFG.dpr.toFixed(2)}<br>`+
`morph ch ${FaceRig.morphs?.size||0} · clips cached ${Avatar.clips.size} · motions ${Avatar.names.length}`;
Gfx.renderer.info.reset();
}
hudT+=dt;
if(CFG.hud&&hudT>.25){ hudT=0;
const y=Avatar.groundY;
UI.hud.innerHTML=
`<span>ground ${y>=0?'+':''}${y.toFixed(3)}m</span>`+
`<span>gaze ${(Life.gx*57.3).toFixed(0)}°,${(Life.gy*57.3).toFixed(0)}°</span>`+
`<span>mood ${Mood.key}</span><span>${Avatar.current||'—'}</span>`;
}
}
/* Debug / scripting bridge — lets you drive her from the console:
MAY.mood('shocked'); MAY.play('dance_1'); MAY.life.trigger('wink'); */
window.MAY={ CFG, MOODS, Mood, Life, Avatar, FaceRig, IrisRig, Gfx, AudioSys, AI,
mood:(k,i=1,h=0)=>Mood.set(k,i,h,true), play:n=>Avatar.act(n), say:t=>AI.send(t),
channels:()=>FaceRig.channelList(), life:Life };
/* ═══════════════════════════ BOOT ═══════════════════════════ */
async function boot(){
await Avatar.restoreCustom();
UI.init(); Gfx.init(); Avatar.init(); Mood.init(); Life.init(); AudioSys.init();
UI.rawChannels();
UI.hud.style.display=CFG.hud?'':'none';
addEventListener('dragover',e=>e.preventDefault());
addEventListener('drop',e=>{ e.preventDefault(); const fs=[...(e.dataTransfer?.files||[])];
const v=fs.find(f=>/\.(vrm|glb)$/i.test(f.name)); const m=fs.filter(f=>/\.vrma$/i.test(f.name));
if(v) Avatar.loadFile(v); if(m.length) Avatar.addMotions(m); });
const send=async()=>{
const i=document.getElementById('msg'), v=i.value.trim(); if(!v) return;
i.value=''; const b=document.getElementById('bSend'); b.disabled=true;
try{ await AI.send(v); } finally{ b.disabled=false; }
};
document.getElementById('bSend').onclick=send;
document.getElementById('msg').onkeydown=e=>{ if(e.key==='Enter') send(); };
Gfx.renderer.setAnimationLoop(tick);
document.addEventListener('visibilitychange',()=>{
if(document.hidden) Gfx.renderer.setAnimationLoop(null);
else { clock.getDelta(); Gfx.renderer.setAnimationLoop(tick); }
});
AudioSys.gradio().catch(e=>console.warn('[TTS] warm-up',e)); /* connect early: faster first reply + real voice list */
Avatar.loadMotions(VRMA_ZIP);
try{ await Avatar.swap(CFG.avatar); }
catch(e){ console.warn(e); UI.status('Avatar failed','err'); }
setTimeout(()=>UI.progress(0),600);
}
boot();
</script>
<script>(function(){function c(){var b=a.contentDocument||(a.contentWindow&&a.contentWindow.document);if(b){var d=b.createElement('script');d.innerHTML="window.__CF$cv$params={r:'a421d8e8e92816d4',t:'MTc5MDU4OTA2Mg=='};var a=document.createElement('script');a.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js';document.getElementsByTagName('head')[0].appendChild(a);";b.getElementsByTagName('head')[0].appendChild(d)}}if(document.body){var a=document.createElement('iframe');a.height=1;a.width=1;a.style.position='absolute';a.style.top=0;a.style.left=0;a.style.border='none';a.style.visibility='hidden';document.body.appendChild(a);if('loading'!==document.readyState)c();else if(window.addEventListener)document.addEventListener('DOMContentLoaded',c);else{var e=document.onreadystatechange||function(){};document.onreadystatechange=function(b){e(b);'loading'!==document.readyState&&(document.onreadystatechange=e,c())}}}})();</script></body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>May — 3D AI Companion</title>
<link rel="preconnect" href="https://esm.sh" crossorigin>
<link rel="preconnect" href="https://huggingface.co" crossorigin>
<style>
:root{ --safe-top:max(14px,env(safe-area-inset-top)); --safe-bottom:max(14px,env(safe-area-inset-bottom)); --accent:#6366f1; }
html,body{ margin:0;padding:0;width:100%;height:100dvh;overflow:hidden;background:#07090e;color:#f3f4f6;
font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;
user-select:none;-webkit-user-select:none;touch-action:none;-webkit-tap-highlight-color:transparent;}
#c{position:absolute;inset:0;z-index:0;outline:none}
#ui{position:absolute;inset:0;z-index:10;pointer-events:none;display:flex;flex-direction:column;justify-content:space-between}
.ia{pointer-events:auto}
::-webkit-scrollbar{width:4px;height:4px}
::-webkit-scrollbar-thumb{background:rgba(255,255,255,.18);border-radius:4px}
.noscroll::-webkit-scrollbar{display:none}
@keyframes slideUp{from{transform:translateY(101%)}to{transform:translateY(0)}}
@keyframes popIn{from{opacity:0;transform:scale(.96) translateY(8px)}to{opacity:1;transform:none}}
.sheet-open{animation:slideUp .32s cubic-bezier(.2,.9,.2,1) forwards;display:flex}
.sheet-closed{transform:translateY(101%);transition:transform .3s cubic-bezier(.2,.9,.2,1)}
.bubble{animation:popIn .18s cubic-bezier(.2,.9,.2,1);box-shadow:0 12px 34px rgba(0,0,0,.55)}
/* ---------- custom dropdown (no native <select>) ---------- */
.dd-btn{width:100%;display:flex;align-items:center;justify-content:space-between;gap:10px;
background:rgba(0,0,0,.42);border:1px solid rgba(255,255,255,.12);border-radius:11px;
padding:9px 12px;font-size:12px;color:#fff;cursor:pointer;text-align:left}
.dd-btn:hover{background:rgba(255,255,255,.06);border-color:rgba(255,255,255,.2)}
.dd-btn.on{border-color:var(--accent);box-shadow:0 0 0 3px rgba(99,102,241,.16)}
.dd-btn .lb{display:flex;flex-direction:column;gap:1px;min-width:0}
.dd-btn .lb b{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dd-btn .lb small{font-size:9px;color:#9ca3af;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dd-cv{display:inline-block;flex:none;color:#9ca3af}
.dd-btn.on .dd-cv{transform:rotate(180deg);color:var(--accent)}
.dd-menu{position:fixed;z-index:9999;background:#11131a;
border:1px solid rgba(255,255,255,.14);border-radius:13px;padding:5px;overflow-y:auto;
box-shadow:0 18px 50px rgba(0,0,0,.72);opacity:0;transform:translateY(-7px) scale(.97);
pointer-events:none;transition:opacity .15s,transform .15s}
.dd-menu.on{opacity:1;transform:none;pointer-events:auto}
.dd-it{display:flex;align-items:center;gap:9px;padding:8px 10px;border-radius:9px;font-size:12px;
color:#d1d5db;cursor:pointer;line-height:1.25}
.dd-it:hover,.dd-it.hi{background:rgba(255,255,255,.08);color:#fff}
.dd-it.sel{background:rgba(99,102,241,.2);color:#c7d2fe}
.dd-it .tk{flex:none;width:14px;text-align:center;color:var(--accent);opacity:0}
.dd-it.sel .tk{opacity:1}
.dd-it small{display:block;font-size:9px;color:#8b93a7}
/* ---------- controls ---------- */
.card{background:rgba(255,255,255,.045);border:1px solid rgba(255,255,255,.09);border-radius:14px;padding:13px;display:flex;flex-direction:column;gap:11px}
.lbl{font-size:9.5px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#8b93a7}
.row{display:flex;align-items:center;justify-content:space-between;gap:10px}
.tg{position:relative;width:40px;height:22px;border-radius:99px;background:rgba(255,255,255,.14);
border:1px solid rgba(255,255,255,.1);cursor:pointer;flex:none;transition:background .2s}
.tg::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;
background:#fff;transition:transform .2s cubic-bezier(.3,1.4,.5,1)}
.tg.on{background:var(--accent)}
.tg.on::after{transform:translateX(18px)}
input[type=range]{-webkit-appearance:none;width:100%;background:transparent;height:16px}
input[type=range]::-webkit-slider-runnable-track{height:4px;background:rgba(255,255,255,.16);border-radius:3px}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;height:15px;width:15px;border-radius:50%;
background:var(--accent);margin-top:-5.5px;box-shadow:0 2px 7px rgba(0,0,0,.5);cursor:pointer}
input[type=range]::-moz-range-track{height:4px;background:rgba(255,255,255,.16);border-radius:3px}
input[type=range]::-moz-range-thumb{height:15px;width:15px;border:0;border-radius:50%;background:var(--accent)}
.chip{padding:6px 9px;border-radius:9px;font-size:10px;font-weight:600;cursor:pointer;
background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.09);color:#cbd5e1;
text-align:center;line-height:1.3}
.chip:hover{background:rgba(255,255,255,.1);color:#fff}
.chip.act{background:rgba(99,102,241,.26);border-color:var(--accent);color:#e0e7ff}
.tab{padding:6px 13px;border-radius:99px;font-size:11px;font-weight:600;white-space:nowrap;cursor:pointer;
background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.07);color:#94a3b8}
.tab.act{background:var(--accent);border-color:transparent;color:#fff}
.inp{width:100%;background:rgba(0,0,0,.42);border:1px solid rgba(255,255,255,.12);border-radius:11px;
padding:9px 12px;font-size:12px;color:#fff;outline:none;transition:border-color .15s}
.inp:focus{border-color:var(--accent)}
.bar{position:absolute;top:0;left:0;height:2px;background:linear-gradient(90deg,#6366f1,#22d3ee);
z-index:60;width:0;opacity:0;transition:width .25s,opacity .3s}
/* perf: backdrop-filter over a live WebGL canvas is the costliest UI effect — solid glass instead */
.backdrop-blur-sm,.backdrop-blur-md,.backdrop-blur-xl,.backdrop-blur-2xl{-webkit-backdrop-filter:none;backdrop-filter:none;background-color:rgba(10,12,18,.8)}
.dd-menu{-webkit-backdrop-filter:none;backdrop-filter:none}
#sheet{background-color:rgba(12,14,20,.97)}
#bub{background-color:rgba(8,10,16,.9)}
/* lightweight: flat UI — no glows, shadows, gradients or per-frame blur */
#ui *,#sheet *,.dd-menu,.dd-menu *,.bubble{box-shadow:none}
#bSend{background:#6366f1}
.cp{width:100%;height:40px;padding:2px;border:1px solid rgba(255,255,255,.18);border-radius:10px;background:transparent;cursor:pointer}
.sw{height:26px;border-radius:8px;border:1px solid rgba(255,255,255,.16);cursor:pointer}
@media (prefers-reduced-motion:reduce){*{animation-duration:.01ms;transition-duration:.01ms}}
</style>
<style>*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.19 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-x-0{left:0;right:0}.bottom-0{bottom:0}.z-50{z-index:50}.col-span-2{grid-column:span 2/span 2}.ml-auto{margin-left:auto}.mr-1\.5{margin-right:.375rem}.mt-1\.5{margin-top:.375rem}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.contents{display:contents}.hidden{display:none}.h-1{height:.25rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-8{height:2rem}.max-h-52{max-height:13rem}.max-h-72{max-height:18rem}.max-h-\[86vh\]{max-height:86vh}.w-10{width:2.5rem}.w-2{width:.5rem}.w-8{width:2rem}.w-full{width:100%}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.resize{resize:both}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-3\.5{gap:.875rem}.gap-x-3{-moz-column-gap:.75rem;column-gap:.75rem}.gap-y-0\.5{row-gap:.125rem}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-t-3xl{border-top-left-radius:1.5rem;border-top-right-radius:1.5rem}.border{border-width:1px}.border-t{border-top-width:1px}.border-none{border-style:none}.border-white\/10{border-color:hsla(0,0%,100%,.1)}.border-white\/15{border-color:hsla(0,0%,100%,.15)}.bg-amber-400{--tw-bg-opacity:1;background-color:rgb(251 191 36/var(--tw-bg-opacity,1))}.bg-black\/45{background-color:rgba(0,0,0,.45)}.bg-black\/55{background-color:rgba(0,0,0,.55)}.bg-green-500{--tw-bg-opacity:1;background-color:rgb(34 197 94/var(--tw-bg-opacity,1))}.bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.bg-transparent{background-color:transparent}.bg-white\/10{background-color:hsla(0,0%,100%,.1)}.bg-white\/20{background-color:hsla(0,0%,100%,.2)}.bg-white\/5{background-color:hsla(0,0%,100%,.05)}.bg-gradient-to-tr{background-image:linear-gradient(to top right,var(--tw-gradient-stops))}.from-indigo-600{--tw-gradient-from:#4f46e5 var(--tw-gradient-from-position);--tw-gradient-to:rgba(79,70,229,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.to-cyan-500{--tw-gradient-to:#06b6d4 var(--tw-gradient-to-position)}.p-1{padding:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.pb-2{padding-bottom:.5rem}.pb-3{padding-bottom:.75rem}.pr-1{padding-right:.25rem}.text-center{text-align:center}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-\[10\.5px\]{font-size:10.5px}.text-\[10px\]{font-size:10px}.text-\[11\.5px\]{font-size:11.5px}.text-\[11px\]{font-size:11px}.text-\[9px\]{font-size:9px}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-relaxed{line-height:1.625}.tracking-wider{letter-spacing:.05em}.text-amber-300{--tw-text-opacity:1;color:rgb(252 211 77/var(--tw-text-opacity,1))}.text-amber-400{--tw-text-opacity:1;color:rgb(251 191 36/var(--tw-text-opacity,1))}.text-cyan-300\/70{color:rgba(103,232,249,.7)}.text-cyan-300\/80{color:rgba(103,232,249,.8)}.text-gray-200{--tw-text-opacity:1;color:rgb(229 231 235/var(--tw-text-opacity,1))}.text-gray-300{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity,1))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.text-green-400{--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity,1))}.text-indigo-300{--tw-text-opacity:1;color:rgb(165 180 252/var(--tw-text-opacity,1))}.text-indigo-400{--tw-text-opacity:1;color:rgb(129 140 248/var(--tw-text-opacity,1))}.text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.shadow,.shadow-2xl{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px rgba(0,0,0,.25);--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-\[0_-12px_50px_rgba\(0\2c 0\2c 0\2c \.85\)\]{--tw-shadow:0 -12px 50px rgba(0,0,0,.85);--tw-shadow-colored:0 -12px 50px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_8px_\#22c55e\]{--tw-shadow:0 0 8px #22c55e;--tw-shadow-colored:0 0 8px var(--tw-shadow-color)}.shadow-\[0_0_8px_\#22c55e\],.shadow-\[0_0_8px_\#ef4444\]{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_8px_\#ef4444\]{--tw-shadow:0 0 8px #ef4444;--tw-shadow-colored:0 0 8px var(--tw-shadow-color)}.shadow-\[0_0_8px_\#fbbf24\]{--tw-shadow:0 0 8px #fbbf24;--tw-shadow-colored:0 0 8px var(--tw-shadow-color)}.shadow-\[0_0_8px_\#fbbf24\],.shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.outline-none{outline:2px solid transparent;outline-offset:2px}.blur{--tw-blur:blur(8px)}.blur,.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-2xl{--tw-backdrop-blur:blur(40px)}.backdrop-blur-2xl,.backdrop-blur-md{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur:blur(12px)}.backdrop-blur-sm{--tw-backdrop-blur:blur(4px)}.backdrop-blur-sm,.backdrop-blur-xl{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur:blur(24px)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.hover\:bg-white\/10:hover{background-color:hsla(0,0%,100%,.1)}.hover\:bg-white\/20:hover{background-color:hsla(0,0%,100%,.2)}.active\:scale-95:active{--tw-scale-x:.95;--tw-scale-y:.95}.active\:scale-95:active,.active\:scale-\[\.98\]:active{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.active\:scale-\[\.98\]:active{--tw-scale-x:.98;--tw-scale-y:.98}.disabled\:opacity-40:disabled{opacity:.4}</style>
<script type="importmap">
{ "imports": {
"three": "https://esm.sh/three@0.160.0",
"three/addons/": "https://esm.sh/three@0.160.0/examples/jsm/",
"@pixiv/three-vrm": "https://esm.sh/@pixiv/three-vrm@3.3.4?deps=three@0.160.0",
"@pixiv/three-vrm-animation": "https://esm.sh/@pixiv/three-vrm-animation@3.3.4?deps=three@0.160.0,@pixiv/three-vrm@3.3.4"
}}
</script>