Files
Triforce-Source/launcher/ui/char.js
ruckus7382sfgsgdf 822ee913bc Triforce v0.9.0
Character tab, faster renderer defaults, HD rumble shipped, and the 11-30 bug pass: ending softlock below 60 fps, adult first-night lock, Intel Arc robust buffers, adult map, randomizer load order.
2026-11-30 20:55:14 -06:00

354 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ((Triforce, 11-29) The Character page: Link in 3D (char3d.js) from the player's own game, young or adult (Kokiri, Goron or
Zora tunic), and his colors (launcher/App/Backend.Character.cs, launcher/Logic/Character/LinkColors.cs). The launcher sends
state.char: game, tool {have, busy, frac, size}, parts [{id, label, group, ages, tunic, swatch}], colors {child, adult}
(the picks), applied {child, adult} | null (what the game has), appliedOn, same, busy, line, calBusy, others; and the
messages charLook {look, n, error?} (the look's files are ready), charCal {maps [{tex, file, parts, yref}]} (where each
part lies on each colour map) and charExact {age, n, colors, tex} (OOTRR's own recoloured maps for those colours).
A pick shows at once as a tint over the calibration mask, then OOTRR's exact map takes its place. Uses app.js's $, $$, S,
ACTIONS, cmd, sfx, esc, toast and its colour helpers. */
'use strict';
const CH = {
age: 'child', tunic: 'kokiri', open: null, h: 0, s: 0, v: 0,
viewer: null, look: null, want: null, n: 0, have: new Set(), sceneTex: new Set(), loading: false, error: '',
cal: null, masks: new Set(), exact: { child: null, adult: null }, cmKey: new Map(),
colors: { child: {}, adult: {}, 'linkle:child': {}, 'linkle:adult': {} }, touchedAt: 0, sendT: 0, face: false, hero: 'link',
};
/* swatches in the picker: the game's tunics first, then a spread */
const CH_SWATCH = [['#2f8f3a', 'Kokiri green'], ['#b3262c', 'Goron red'], ['#2a4fb0', 'Zora blue'], ['#1f5e2e', 'Deep forest'], ['#7d1622', 'Crimson'],
['#1c2a52', 'Midnight'], ['#4b2a84', 'Royal purple'], ['#2a8f8a', 'Lake teal'], ['#d4a634', 'Triforce gold'], ['#c8641e', 'Ember'],
['#d86a9a', 'Fairy pink'], ['#ebe7de', 'Snow'], ['#a7abb3', 'Silver'], ['#6b4a2b', 'Leather'], ['#2b2b2e', 'Charcoal'], ['#121214', 'Shadow']];
/* whole looks: each names what it changes; Original takes every part back to the game's colour */
const CH_LOOKS = [
{ id: 'original', name: 'Original', c: {} },
{ id: 'midnight', name: 'Midnight', c: { kokiri: '#1f2b4d', kokiri_pants: '#2b3352', kokiri_shirt: '#cfc8b8', kokiri_belt: '#3b2a1f', leather_trim: '#8a1f2b', boots: '#2a1d15', gloves: '#2a1d15', feathers: '#e9e5dc', goron: '#33204a', goron_trim: '#c9a24a', zora: '#1c2448', zora_shirt: '#cfd3da' } },
{ id: 'crimson', name: 'Crimson', c: { kokiri: '#8e1b22', kokiri_pants: '#5a1a1a', kokiri_shirt: '#e6dcc8', kokiri_belt: '#3b2416', leather_trim: '#d4a634', boots: '#3b2416', gloves: '#3b2416', feathers: '#f2ead8', zora: '#7a1a2a' } },
{ id: 'royal', name: 'Royal', c: { kokiri: '#3b2a7a', kokiri_pants: '#2e2458', kokiri_shirt: '#ece3cf', kokiri_belt: '#4a2f1d', leather_trim: '#d4a634', feathers: '#f5e6b0', goron: '#4b2a84', goron_trim: '#e0b84a', zora: '#3b2a7a' } },
{ id: 'snow', name: 'Snow', c: { kokiri: '#e8e6df', kokiri_pants: '#cfcac0', kokiri_shirt: '#f4f1ea', kokiri_belt: '#8a6a4a', leather_trim: '#b8963e', boots: '#e0dbd0', gloves: '#e0dbd0', feathers: '#ffffff', goron: '#e8e6df', zora: '#e8eef4' } },
{ id: 'shadow', name: 'Shadow', c: { kokiri: '#1b1b1e', kokiri_pants: '#222226', kokiri_shirt: '#3a3a3e', kokiri_belt: '#141414', leather_trim: '#6a0f18', boots: '#111113', gloves: '#111113', feathers: '#2a2a2e', hair: '#e8e8ea', goron: '#1b1b1e', zora: '#1b1b1e' } },
{ id: 'random', name: 'Random', c: null },
];
function chS() { return S.char || {}; }
function chLook() { return CH.age === 'child' ? 'child' : CH.tunic === 'kokiri' ? 'adult' : 'adult-' + CH.tunic; }
/* a colour set's key: the age, "linkle:" in front for her */
function chKey(age) { return (CH.hero === 'linkle' ? 'linkle:' : '') + (age || CH.age); }
function chCur() { return CH.colors[chKey()] || (CH.colors[chKey()] = {}); }
function chLinkle() { return chS().linkle || {}; }
function chHeroName() { return CH.hero === 'linkle' ? 'Linkle' : 'Link'; }
function chParts() {
return (chS().parts || []).filter(p => p.ages.split(',').includes(CH.age) && (CH.age === 'child' || !p.tunic || p.tunic === CH.tunic));
}
function chLin(hex) { return hexRgb(hex).map(x => { x /= 255; return x <= .04045 ? x / 12.92 : ((x + .055) / 1.055) ** 2.4; }); }
/* ---------------- the stage ---------------- */
function chViewer() {
if (CH.viewer) return CH.viewer;
const c = $('#chCanvas');
try { CH.viewer = window.Char3D && Char3D.create(c); } catch (e) { CH.viewer = null; console.error(e); }
if (!CH.viewer) { CH.error = 'This PC\'s browser engine has no WebGL 2, so Link cannot be drawn here. Colors still apply.'; drawChar(); }
new ResizeObserver(() => CH.viewer && CH.viewer.resize()).observe(c);
return CH.viewer;
}
function chLoad() {
const look = CH.hero + '/' + chLook();
if (CH.look === look || CH.want === look || !chS().game || !chViewer()) return;
if (CH.hero === 'linkle' && !chLinkle().have) return;
CH.want = look; CH.loading = true; CH.error = ''; drawChar();
cmd('char.look', { look: chLook(), have: [...CH.have] });
}
async function chFetchTex(name) {
const r = await fetch('/char/tex/' + encodeURIComponent(name) + '.bin');
if (!r.ok) return null;
const b = await r.arrayBuffer(), d = new DataView(b);
CH.have.add(name);
return { w: d.getUint32(0, true), h: d.getUint32(4, true), data: new Uint8Array(b, 8) };
}
async function chFetchBin(url) {
const r = await fetch(url); if (!r.ok) return null;
const b = await r.arrayBuffer(), d = new DataView(b);
return { w: d.getUint32(0, true), h: d.getUint32(4, true), data: new Uint8Array(b, 8) };
}
async function chOnLook(m) {
const want = (m.hero || 'link') + '/' + m.look;
if (want !== CH.want) return;
if (m.error) { CH.want = null; CH.loading = false; CH.error = m.error; drawChar(); return; }
try {
const info = await (await fetch('/char/scene/' + m.n + '.json')).json();
const mesh = await (await fetch('/char/scene/' + m.n + '.bin')).arrayBuffer();
if (want !== CH.want) return;
await CH.viewer.load(info, mesh, chFetchTex);
cmd('char.loaded', { n: m.n });
CH.look = want; CH.want = null; CH.loading = false;
CH.sceneTex = new Set(info.parts.map(p => p.alb).filter(Boolean));
CH.cmKey.clear(); CH.viewer.clearColorMaps();
chTint();
} catch (e) { CH.want = null; CH.loading = false; CH.error = 'Link could not be drawn: ' + e.message; }
drawChar();
}
/* ---------------- colours on the model: OOTRR's exact map when it matches the picks, else the live tint ---------------- */
function chTint() {
const v = CH.viewer; if (!v || !CH.look) return;
const cur = chCur(), ex = CH.exact[chKey()];
v.setNaviColor(cur.navi || (CH.hero === 'linkle' ? '#e8f070' : null));
const same = (parts, colors) => parts.every(p => (cur[p] || null) === ((colors || {})[p] || null));
const done = new Set();
for (const [tex, c] of (CH.hero === 'link' && CH.cal || new Map())) {
if (!CH.sceneTex.has(tex)) continue;
done.add(tex);
if (ex && same(c.parts, ex.colors)) { v.setTint(tex, null); chUseExact(tex, ex); continue; }
chUseExact(tex, null);
const slots = c.parts.map((p, i) => cur[p] ? chTintSlot(cur[p], c.ym[i], c.qm[i], c.ty[i], c.g ? c.g[i] : 1) : null);
if (slots.some(Boolean) && chMask(tex, c.file)) v.setTint(tex, slots); else v.setTint(tex, null);
}
/* (no calibration yet: the exact maps alone, when they match every pick of this age) */
if (ex) for (const tex of ex.tex) if (!done.has(tex) && CH.sceneTex.has(tex)) chUseExact(tex, Object.keys(cur).length === Object.keys(ex.colors).length && Object.keys(cur).every(k => cur[k] === ex.colors[k]) ? ex : null);
}
/* a part's live tint, as OOTRR's dye comes out: [r, g, b] the colour at the part's median texel (linear), ym that texel's
luminance, and the contrast g. OOTRR compresses brightness, so the median texel comes out near qm * (Y / ty)^0.62, mixes
the colour toward its own grey (measured 11-30 at the median texel, linear: 26% for #FF0000, 36% for #2050C0 on young
Link's belt; 30% here), and scales the shading by (y / ym)^g, flattened at the top (char3d.js). 11-30: the tint was
brighter than OOTRR's map, and painted the buckle and ring, so a pick seemed to switch when the exact map came */
function chTintSlot(hex, ym, qm, ty, g) {
const c = chLin(hex), y = Math.max(1e-4, .2126 * c[0] + .7152 * c[1] + .0722 * c[2]);
const out = qm * Math.pow(y / ty, .62), k = out / y;
return c.map(x => (x * .7 + y * .3) * k).concat(Math.max(1e-4, ym), g || 1);
}
function chUseExact(tex, ex) {
const key = ex && ex.tex.includes(tex) ? chKey() + '/' + ex.n : '';
if ((CH.cmKey.get(tex) || '') === key) return;
CH.cmKey.set(tex, key);
if (!key) { CH.viewer.setColorMap(tex, null); return; }
chFetchBin('/char/exact/' + chKey() + '/' + ex.n + '/' + encodeURIComponent(tex) + '.bin').then(t => {
if (CH.cmKey.get(tex) === key && t) CH.viewer.setColorMap(tex, t);
});
}
function chMask(tex, file) {
if (CH.masks.has(tex)) return true;
CH.masks.add(tex);
chFetchBin('/char/mask/' + encodeURIComponent(file) + '.bin').then(t => { if (t) { CH.viewer.setMask(tex, t); chTint(); } else CH.masks.delete(tex); });
return false;
}
/* ---------------- picks ---------------- */
function chNaviBoth() { const h = chCur().navi, o = CH.colors[chKey(CH.age === 'child' ? 'adult' : 'child')] || (CH.colors[chKey(CH.age === 'child' ? 'adult' : 'child')] = {}); if (h) o.navi = h; else delete o.navi; }
function chSet(part, hex, final) {
const c = chCur();
if (hex) c[part] = hex; else delete c[part];
if (part === 'navi') chNaviBoth();
CH.touchedAt = performance.now();
chTint();
if (final) drawChar(); else chPatchRow(part);
chDyeing();
clearTimeout(CH.sendT);
const go = () => cmd('char.set', { age: CH.age, part, hex: hex || null });
if (final) go(); else CH.sendT = setTimeout(go, 220);
}
function chMany(colors) {
const c = chCur();
for (const k in colors) { if (colors[k]) c[k] = colors[k]; else delete c[k]; }
if ('navi' in colors) chNaviBoth();
CH.touchedAt = performance.now();
chTint(); drawChar();
cmd('char.many', { age: CH.age, colors });
}
function chRandom() {
const out = {}, base = Math.random() * 360;
chParts().forEach((p, i) => {
const h = (base + (p.group === 'Tunic' ? 0 : p.group === 'Leather' ? 25 + Math.random() * 30 : Math.random() * 360) + (i % 3) * 8) % 360;
const s = p.group === 'Leather' ? .35 + Math.random() * .3 : .45 + Math.random() * .45;
const v = p.group === 'Leather' ? .22 + Math.random() * .25 : .35 + Math.random() * .5;
out[p.id] = rgbHex(hsvRgb(h, s, v));
});
return out;
}
/* ---------------- drawing the page ---------------- */
function drawChar() {
if (!$('#s-char')) return;
const st = chS();
// (the launcher's picks are taken unless one was made here a moment ago and is still on its way)
if (st.colors && performance.now() - CH.touchedAt > 1500) {
CH.colors = {};
for (const k of ['child', 'adult', 'linkle:child', 'linkle:adult']) CH.colors[k] = Object.assign({}, st.colors[k] || {});
}
if (st.hero && st.hero !== CH.hero) chHeroSwitch(st.hero);
$$('#chHeroes span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chhero:' + CH.hero));
$$('#chAges span').forEach(s => { s.textContent = (s.dataset.act === 'chage:child' ? 'Young ' : 'Adult ') + chHeroName(); });
$$('#chAges span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chage:' + CH.age));
$('#chTunics').style.visibility = CH.age === 'adult' ? 'visible' : 'hidden';
$$('#chTunics span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chtunic:' + CH.tunic));
$('#chTitle').textContent = (CH.age === 'child' ? 'Young ' : 'Adult ') + chHeroName() + '’s colors';
$('#chFace').textContent = CH.face ? 'Full body' : 'Face';
const wait = $('#chWait');
const lk = chLinkle();
const noLinkle = CH.hero === 'linkle' && st.game && !lk.have;
const waitText = !st.game ? 'Build the game first: Link is read from it' : noLinkle ? '' : CH.error || (CH.loading ? 'Reading ' + chHeroName() + ' from your files' : '');
wait.classList.toggle('on', !!waitText); wait.classList.toggle('err', !!(CH.error || !st.game));
$('#chWaitT').textContent = waitText;
const get = $('#chGet');
get.classList.toggle('on', !!noLinkle);
if (noLinkle) get.innerHTML = `<h3>Play as Linkle</h3><p><b>${esc(lk.name || 'Playable Linkle')}</b> by <b>${esc(lk.author || '')}</b>: Linkle from Hyrule Warriors, young and adult, with her own voice, gear and fairy, Liri. A mod from GameBanana, about 320 MB.</p>` +
(lk.busy ? `<p class="chmsg">${esc(lk.line || 'Downloading')}</p><div class="chbar"><i style="width:${(lk.frac || 0) * 100}%"></i></div>`
: `<div class="chbtns" style="justify-content:flex-start"><div class="play sm" data-f id="chGetBtn" data-act="chlinkle">Get Linkle</div><span class="lnk" data-f data-act="chpage">Her page</span></div>`);
if (CH.viewer) { if (noLinkle) CH.viewer.stop(); else if (screen === 'char') CH.viewer.start(); }
$('#chCanvas').style.visibility = noLinkle ? 'hidden' : '';
const changed = Object.keys(chCur()).length;
chDyeing();
$('#chState').textContent = changed ? changed + (changed === 1 ? ' part changed' : ' parts changed') : 'The game’s own colors';
$('#chLooks').innerHTML = CH_LOOKS.map((l, i) => `<span data-f data-act="chlook:${l.id}" id="chl${i}" class="${chLookOn(l) ? 'on' : ''}">${esc(l.name)}</span>`).join('');
chDrawRows();
chDrawFoot();
if (screen === 'char') chLoad();
}
/* "Dyeing" under the stage while OOTRR's exact maps for the picks are on their way and no live tint stands in for them */
function chDyeing() {
const cur = chCur(), ex = CH.exact[chKey()];
const match = ex && Object.keys(cur).length === Object.keys(ex.colors).length && Object.keys(cur).every(k => cur[k] === ex.colors[k]);
const el = $('#chDye'); if (el) el.classList.toggle('on', (CH.hero === 'linkle' || !!(chS().tool || {}).have) && !match && (CH.hero === 'linkle' || !CH.cal) && !!CH.look);
}
function chLookOn(l) {
if (!l.c) return false;
const cur = chCur() || {}, ids = chParts().map(p => p.id);
return ids.every(id => (cur[id] || null) === (l.c[id] || null)) && (l.id === 'original' || ids.some(id => l.c[id]));
}
function chDrawRows() {
const list = $('#chList'); if (!list) return;
const parts = chParts(), cur = chCur() || {}, applied = (chS().applied || {})[chKey()] || {};
const keep = focused && list.contains(focused) ? focused.id : null;
let html = '', group = '';
for (const p of parts) {
if (p.group !== group) { group = p.group; html += `<h4>${esc(group === 'Leather' ? 'Leather and gear' : group === 'Navi' ? 'Your fairy' : group)}</h4>`; }
const hex = cur[p.id], shown = hex || p.swatch, open = CH.open === p.id, pend = (hex || null) !== (applied[p.id] || null);
html += `<div class="chrow${open ? ' open' : ''}" data-f data-act="chpick:${p.id}" id="chp-${p.id}"><i class="chsw${hex ? '' : ' orig'}" style="--c:${shown}"></i>` +
`<b>${esc(p.label)}</b><span>${hex ? hex.toUpperCase() : 'Game’s color'}${pend ? '<u title="Not in your game yet"></u>' : ''}</span><em>${open ? 'Done' : 'Change'}</em></div>`;
if (open) html += chPicker(p, shown, !!hex);
}
html += CH.hero === 'linkle' ? `<p class="gnote chnote">Liri is one fairy for both ages. Linkle is <span class="lnk" data-act="chpage">${esc(chLinkle().name || 'a mod')}</span> by ${esc(chLinkle().author || '')}.</p>`
: '<p class="gnote chnote">Navi is one fairy for both ages: her color goes with young and adult Link.</p>';
// (the list is drawn again only when what it shows changed: a pick while dragging moves the marks, not the whole list)
if (list.dataset.html !== html) {
const top = list.scrollTop; list.innerHTML = html; list.dataset.html = html; list.scrollTop = top;
if (keep && $('#' + keep)) { focused = null; setFocus($('#' + keep)); }
}
chDrawPicker();
}
function chPicker(p, hex, set) {
return `<div class="chpick" id="chPick"><div class="chpk-l"><div class="cp-sv chsv" data-f id="chSv"><u></u></div><div class="slider cp-hue chhue" data-f id="chHue"><u></u></div></div>` +
`<div class="chpk-r"><div class="cp-f"><label>Hex<input data-f id="chHex" value="${hex.toUpperCase()}" maxlength="7" spellcheck="false" autocomplete="off"></label></div>` +
`<div class="chpre">${CH_SWATCH.map(([c, n], i) => `<span data-f data-act="chsw:${c}" id="chs${i}" title="${esc(n)}" style="--c:${c}"></span>`).join('')}</div>` +
`<div class="cp-foot"><em id="chSwName"></em>${set ? `<span class="lnk" data-f data-act="chorig:${p.id}" id="chOrig">Game’s color</span>` : ''}</div></div></div>`;
}
/* while a colour is dragged: only the row's mark and value move (the list is not drawn again under the pointer) */
function chPatchRow(part) {
const row = $('#chp-' + part); if (!row) return;
const hex = chCur()[part], p = chParts().find(x => x.id === part) || {};
const sw = row.querySelector('.chsw'); sw.style.setProperty('--c', hex || p.swatch); sw.classList.toggle('orig', !hex);
row.querySelector('span').firstChild.textContent = hex ? hex.toUpperCase() : 'Game’s color';
}
function chDrawPicker() {
const sv = $('#chSv'), hu = $('#chHue'); if (!sv || !CH.open) return;
const hex = chCur()[CH.open] || (chParts().find(p => p.id === CH.open) || {}).swatch || '#808080';
if (rgbHex(hsvRgb(CH.h, CH.s, CH.v)) !== hex) { const [r, g, b] = hexRgb(hex), mx = Math.max(r, g, b), d = mx - Math.min(r, g, b); CH.s = mx ? d / mx : 0; CH.v = mx / 255; if (d) CH.h = rgbHsl([r, g, b])[0]; }
sv.style.setProperty('--cp-h', CH.h); sv.style.setProperty('--cp-c', hex);
sv.querySelector('u').style.left = CH.s * 100 + '%'; sv.querySelector('u').style.top = (1 - CH.v) * 100 + '%';
hu.style.setProperty('--cp-c', `hsl(${CH.h}, 100%, 50%)`); hu.querySelector('u').style.left = CH.h / 360 * 100 + '%';
const f = $('#chHex'); if (f && document.activeElement !== f) { f.value = hex.toUpperCase(); f.classList.remove('bad'); }
const n = CH_SWATCH.find(x => x[0] === hex); $('#chSwName').textContent = n ? n[1] : '';
$$('.chpre span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chsw:' + hex));
}
function chDrawFoot() {
const st = chS(), t = st.tool || {}, f = $('#chFoot');
const changed = !st.same, hasApplied = !!st.applied;
let html;
if (!st.game) html = '<p class="chmsg">Build the game first: the colors go into its files.</p>';
else if (!t.have) html = t.busy ? `<p class="chmsg">Getting the color tool… ${Math.round((t.frac || 0) * 100)} %</p><div class="chbar"><i style="width:${(t.frac || 0) * 100}%"></i></div>`
: `<p class="chmsg">Picks show here now. To put them in your game, Triforce uses the randomizer’s color tool (OOTRR, ${esc(t.size || '5 MB')}, once).</p><div class="chbtns"><div class="play sm" data-f id="chGo" data-act="chinstall">Get the color tool</div></div>`;
else if (st.busy) html = `<p class="chmsg"><span class="chspin sm"></span>${esc(st.line || 'Working')}… about half a minute</p><div class="chbtns"><span class="lnk" data-f id="chStop" data-act="chstop">Stop</span></div>`;
else {
const msg = changed ? (hasApplied ? 'Changed since you applied: not in your game yet' : 'Not in your game yet')
: hasApplied ? (st.appliedOn ? '◆ In your game · every save, new or old' : 'In your game, but switched off on the Mods page') : 'Your game has its own colors';
const others = (st.others || []).length ? `<p class="chmsg warn">Over ${esc(st.others.join(', '))}, which changes Link too.</p>` : '';
html = `<p class="chmsg${changed ? ' pend' : ''}">${msg}</p>${others}<div class="chbtns">` +
(changed && st.appliedHero && st.appliedHero !== CH.hero ? `<span class="chmsg" style="margin-right:auto">Your game plays ${st.appliedHero === 'linkle' ? 'Linkle' : 'Link'} now</span>` : '') +
(changed && hasApplied ? '<span class="lnk" data-f id="chUndo" data-act="chrevert">Undo changes</span>' : '') +
(!changed && hasApplied ? '<span class="lnk" data-f id="chRemove" data-act="chremove">Use the game’s colors</span>' : '') +
`<div class="play sm${changed ? '' : ' off'}" data-f id="chGo" data-act="chapply">${changed && !Object.values(CH.colors).some(c => Object.keys(c).length) ? 'Apply the game’s colors' : 'Apply to my game'}</div></div>`;
}
if (f.dataset.html !== html) { const keep = focused && f.contains(focused) ? focused.id : null; f.innerHTML = html; f.dataset.html = html; if (keep && $('#' + keep)) { focused = null; setFocus($('#' + keep)); } }
}
/* ---------------- actions ---------------- */
function chHeroSwitch(hero) {
if (hero === CH.hero) return;
CH.hero = hero; CH.open = null; CH.look = null; CH.want = null; CH.have.clear(); CH.cmKey.clear(); CH.masks.clear();
if (CH.viewer) CH.viewer.clearTextures();
if (hero === 'linkle' && CH.tunic !== 'kokiri' && false) CH.tunic = 'kokiri';
}
ACTIONS.chhero = (h) => { if (h === CH.hero) return; chHeroSwitch(h); cmd('char.hero', { hero: h }); drawChar(); chLoad(); };
ACTIONS.chlinkle = () => cmd('char.linkle');
ACTIONS.chpage = () => cmd('open', { arg: 'linkle' });
ACTIONS.chage = (a) => { if (CH.age === a) return; CH.age = a; CH.open = null; drawChar(); chLoad(); };
ACTIONS.chtunic = (t) => { if (CH.tunic === t) return; CH.tunic = t; CH.open = null; drawChar(); chLoad(); };
ACTIONS.chturn = (d) => CH.viewer && CH.viewer.turn(+d * 0.7);
ACTIONS.chface = () => { CH.face = !CH.face; if (CH.viewer) CH.viewer.look(CH.face ? 'face' : 'body'); drawChar(); };
ACTIONS.chpick = (id) => { CH.open = CH.open === id ? null : id; chDrawRows(); if (CH.open) setTimeout(() => { const p = $('#chPick'), l = $('#chList'); if (p && l) { const over = p.offsetTop + p.offsetHeight - l.scrollTop - l.clientHeight; if (over > 0) l.scrollTop += over + 8; } }, 30); };
ACTIONS.chsw = (hex) => { chSet(CH.open, hex, true); chDrawPicker(); };
ACTIONS.chorig = (id) => { chSet(id, null, true); CH.open = null; chDrawRows(); };
ACTIONS.chlook = (id) => {
const l = CH_LOOKS.find(x => x.id === id); if (!l) return;
const src = l.c || chRandom(), out = {};
for (const p of chParts()) out[p.id] = src[p.id] || null;
chMany(out);
};
ACTIONS.chapply = () => cmd('char.apply');
ACTIONS.chinstall = () => cmd('char.install');
ACTIONS.chstop = () => cmd('char.stop');
ACTIONS.chrevert = () => { CH.touchedAt = 0; cmd('char.revert'); };
ACTIONS.chremove = () => cmd('char.remove');
/* the picker: drag in the square / on the hue, or type the hex */
document.addEventListener('pointerdown', e => {
const el = e.target.closest('#chSv, #chHue'); if (!el || !CH.open) return;
e.preventDefault(); setFocus(el, true);
const id = el.id;
const mv = ev => {
const n = $('#' + id); if (!n) return;
const b = n.getBoundingClientRect(), x = clamp01((ev.clientX - b.left) / b.width), y = clamp01((ev.clientY - b.top) / b.height);
if (id === 'chHue') CH.h = Math.round(x * 359); else { CH.s = x; CH.v = 1 - y; }
chSet(CH.open, rgbHex(hsvRgb(CH.h, CH.s, CH.v)), false); chDrawPicker();
};
mv(e);
const up = () => { removeEventListener('pointermove', mv); removeEventListener('pointerup', up); clearTimeout(CH.sendT); if (CH.open) chSet(CH.open, chCur()[CH.open] || null, true); sfx('cursor'); };
addEventListener('pointermove', mv); addEventListener('pointerup', up);
});
document.addEventListener('input', e => {
if (e.target.id !== 'chHex') return;
const v = e.target.value.trim().replace(/^#/, '');
e.target.classList.toggle('bad', /[^0-9a-f]/i.test(v) || v.length > 6);
if (/^[0-9a-f]{6}$/i.test(v) && CH.open) { chSet(CH.open, '#' + v.toLowerCase(), true); chDrawPicker(); }
});
/* arrows on the square and the hue (app.js asks this first) */
function charNudge(dx, dy) {
if (!focused || !CH.open) return false;
if (focused.id === 'chHue' && dx) CH.h = Math.max(0, Math.min(359, CH.h + dx * 5));
else if (focused.id === 'chSv' && (dx || dy)) { CH.s = clamp01(CH.s + dx * .04); CH.v = clamp01(CH.v + dy * .04); }
else return false;
chSet(CH.open, rgbHex(hsvRgb(CH.h, CH.s, CH.v)), false); chDrawPicker(); sfx('cursor');
return true;
}
/* ---------------- from the launcher ---------------- */
function charMessage(m) {
if (m.t === 'charLook') chOnLook(m);
else if (m.t === 'charCal') { CH.cal = new Map(m.maps.map(x => [x.tex, x])); chTint(); }
else if (m.t === 'charExact') { const k = m.key || m.age; CH.exact[k] = { n: m.n, colors: m.colors || {}, tex: m.tex || [] }; if (k === chKey()) chTint(); chDyeing(); }
}
function charShown(name) {
if (name !== 'char') { if (CH.viewer) CH.viewer.stop(); return; }
cmd('char.open');
const v = chViewer();
if (v) { v.start(); v.resize(); }
drawChar(); chLoad();
}