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.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-30 20:55:14 -06:00
parent 8cb23131f9
commit 822ee913bc
86 changed files with 8128 additions and 438 deletions

View File

@@ -235,9 +235,9 @@ document.addEventListener('pointerdown', e => {
});
/* ---------------- screens ---------------- */
const MAIN = ['home', 'mods', 'rando', 'saves', 'settings'];
const MAIN = ['home', 'mods', 'rando', 'char', 'saves', 'settings'];
const FIRST_RUN = ['welcome', 'reveal', 'done'];
const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', rando: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };
const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', rando: 'fairy', char: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };
let screen = null;
function go(name) {
if (name === screen || !$('#s-' + name)) return;
@@ -256,6 +256,7 @@ function go(name) {
if (name === 'mods' && !S.mods.loaded) cmd('mods.list', { tab: S.mods.tab, q: '' });
if (name === 'saves') cmd('saves.list');
if (name === 'rando') cmd('rando.open');
if (typeof charShown === 'function') charShown(name); // (the Character page: char.js)
cmd('screen', { s: name });
}
function afterOneShot(name) { if (name === 'itemget' && (MUSIC[screen] === 'fairy' || screen === 'done')) music('fairy'); }
@@ -884,6 +885,7 @@ onHost(m => {
if (m.rando && m.rando.schema) S.randoSchema = m.rando.schema; // (OOTRR's settings come once; the rows every time)
if (m.randoMade) S.rtab = 'seeds';
if ((m.rando || m.randoMade) && typeof drawRando === 'function') drawRando();
if (m.char && typeof drawChar === 'function') drawChar();
if (m.done) { $('#doneEb').textContent = S.done.eb || ''; $('#doneLead').textContent = S.done.lead || ''; }
break;
}
@@ -896,6 +898,7 @@ onHost(m => {
case 'choice': openChoice(m); break;
case 'ask': openAsk(m); break;
case 'bench': onBench(m); break;
case 'charLook': case 'charExact': case 'charCal': if (typeof charMessage === 'function') charMessage(m); break;
case 'copy': navigator.clipboard && navigator.clipboard.writeText(m.text).then(() => toast('Copied'), () => toast('Could not copy')); break;
}
});
@@ -906,7 +909,7 @@ document.addEventListener('keydown', e => {
if (document.activeElement && document.activeElement.tagName === 'INPUT' && !['Escape', 'Enter', 'ArrowDown', 'ArrowUp', 'Tab'].includes(e.key)) return;
const k = e.key; let used = true;
const ca = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] }[k];
if (ca && colorNudge(ca[0], ca[1])) { } // (the colour picker's square and hue take the arrows first)
if (ca && (colorNudge(ca[0], ca[1]) || (typeof charNudge === 'function' && charNudge(ca[0], ca[1])))) { } // (the colour picker's square and hue take the arrows first)
else if (focused && focused.dataset.vol && (k === 'ArrowLeft' || k === 'ArrowRight')) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + (k === 'ArrowLeft' ? -.05 : .05)); sfx('cursor'); }
else if (focused && (focused.dataset.gkey || focused.dataset.rkey) && (k === 'ArrowLeft' || k === 'ArrowRight')) gNudge(k === 'ArrowLeft' ? -1 : 1);
else if (k === 'ArrowLeft') move(-1, 0); else if (k === 'ArrowRight') move(1, 0);
@@ -927,10 +930,11 @@ function pad(t) {
const gp = [...(navigator.getGamepads ? navigator.getGamepads() : [])].find(g => g && g.connected); if (!gp) return;
const B = i => gp.buttons[i] && gp.buttons[i].pressed;
const edge = (i, fn) => { const p = B(i); if (p && !held[i]) { document.body.classList.add('kb'); unlocked = true; fn(); } held[i] = p; };
const slide = d => { if (colorNudge(d, 0)) return true; if (focused && focused.dataset.vol) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + d * .05); sfx('cursor'); return true; } return gNudge(d); };
const slide = d => { if (colorNudge(d, 0) || (typeof charNudge === 'function' && charNudge(d, 0))) return true; if (focused && focused.dataset.vol) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + d * .05); sfx('cursor'); return true; } return gNudge(d); };
edge(0, () => activate(focused)); edge(1, back); edge(4, () => tab(-1)); edge(5, () => tab(1));
edge(3, toggleMute); edge(9, () => { if (MAIN.includes(screen)) go('settings'); });
edge(12, () => colorNudge(0, 1) || move(0, -1)); edge(13, () => colorNudge(0, -1) || move(0, 1)); edge(14, () => slide(-1) || move(-1, 0)); edge(15, () => slide(1) || move(1, 0));
const cn = (dx, dy) => colorNudge(dx, dy) || (typeof charNudge === 'function' && charNudge(dx, dy));
edge(12, () => cn(0, 1) || move(0, -1)); edge(13, () => cn(0, -1) || move(0, 1)); edge(14, () => slide(-1) || move(-1, 0)); edge(15, () => slide(1) || move(1, 0));
const x = gp.axes[0] || 0, y = gp.axes[1] || 0, dir = Math.abs(x) > .55 ? (x > 0 ? 'r' : 'l') : Math.abs(y) > .55 ? (y > 0 ? 'd' : 'u') : '';
if (dir && (dir !== stickDir || t - stickAt > 220)) {
document.body.classList.add('kb'); stickAt = t + (dir !== stickDir ? 160 : 0);

101
launcher/ui/char.css Normal file
View File

@@ -0,0 +1,101 @@
/* ((Triforce, 11-29) The Character page: Link on a lit stage at the left, his colors in a panel at the right. On top of
ui.css, theme.css, v3.css, proto.css and app.css (the picker reuses app.css's .cp-sv / .cp-hue / .cp-f). */
#s-char { background:
radial-gradient(520px 600px at 360px 520px, rgba(var(--gold-warm-rgb), .16) 0%, rgba(var(--gold-warm-rgb), .05) 38%, rgba(0, 0, 0, 0) 70%),
radial-gradient(900px 760px at 360px 420px, #1d1710 0%, #110e0a 52%, var(--ink) 82%); }
/* the stage: Link's canvas, under the title; a soft light from above behind him */
.chstage { position: absolute; left: 170px; top: 44px; width: 590px; height: 756px; }
.chstage canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none;
-webkit-mask: linear-gradient(90deg, transparent 0, #000 9%, #000 91%, transparent 100%); mask: linear-gradient(90deg, transparent 0, #000 9%, #000 91%, transparent 100%); }
.chstage canvas.grab { cursor: grabbing; }
.chglow { position: absolute; left: 125px; top: 0; width: 340px; height: 520px; pointer-events: none;
background: radial-gradient(closest-side, rgba(var(--gold-lit-rgb), .07), rgba(var(--gold-lit-rgb), 0)); mix-blend-mode: screen; }
.chhead { position: absolute; left: 64px; top: 96px; z-index: 2; pointer-events: none; }
.chhead > * { pointer-events: auto; }
.chhead .cont h1 { text-shadow: 0 2px 18px rgba(0, 0, 0, .75); }
/* young / adult: two halves of one gold-edged bar */
.chseg { display: inline-flex; margin-top: 18px; border: 1px solid rgba(var(--gold-rgb), .45); background: rgba(10, 9, 8, .55); }
.chseg span { padding: 9px 20px; font-size: 15px; font-weight: 600; color: var(--text2); cursor: pointer; transition: background .15s, color .15s; }
.chseg span + span { border-left: 1px solid rgba(var(--gold-rgb), .3); }
.chseg span.on { color: var(--gold-ink2); background: linear-gradient(180deg, rgb(var(--gold-bar-hi-rgb)), rgb(var(--gold-bar-rgb)) 55%, rgb(var(--gold-bar-low-rgb))); }
.chseg span:not(.on):hover { color: var(--gold-hi); }
/* the adult's tunic: three small diamonds-and-words under it */
.chtunic { display: flex; gap: 20px; margin-top: 14px; font-size: 14px; color: var(--text3); }
.chtunic span { position: relative; padding: 4px 0 6px 18px; cursor: pointer; }
.chtunic span::before { content: ''; position: absolute; left: 1px; top: 10px; width: 8px; height: 8px; transform: rotate(45deg); border: 1px solid rgba(var(--gold-rgb), .55); }
.chtunic span:nth-child(1)::before { background: #2f8f3a; } .chtunic span:nth-child(2)::before { background: #b3262c; } .chtunic span:nth-child(3)::before { background: #2a4fb0; }
.chtunic span.on { color: var(--gold-hi); font-weight: 600; box-shadow: inset 0 -2px 0 var(--gold); }
.chtunic span:not(.on):hover { color: var(--text); }
/* under the stage: turn him, look at his face */
.chview { position: absolute; left: 64px; bottom: 30px; display: flex; align-items: center; gap: 18px; font-size: 14px; z-index: 2; }
.chview .lnk { color: var(--gold); font-weight: 600; cursor: pointer; padding: 4px 2px; }
.chview #chTurnL, .chview #chTurnR { font-size: 12px; }
.chview em { font-style: normal; color: var(--text3); font-size: 13px; margin-left: 6px; }
.chwait { position: absolute; left: 170px; top: 330px; width: 590px; display: none; flex-direction: column; align-items: center; gap: 16px; color: var(--text2); font-size: 15px; pointer-events: none; }
.chwait.on { display: flex; }
.chwait.err .chspin { display: none; }
.chwait.err span { max-width: 420px; text-align: center; color: var(--text3); }
.chspin { width: 30px; height: 30px; transform: rotate(45deg); border: 2px solid rgba(var(--gold-rgb), .25); border-top-color: var(--gold-hi); animation: chspin 1.1s linear infinite; }
.chspin.sm { display: inline-block; width: 11px; height: 11px; margin: 0 10px -1px 0; border-width: 1.5px; vertical-align: 0; }
@keyframes chspin { to { transform: rotate(405deg); } }
/* the panel */
.chpanel { position: absolute; right: 48px; top: 96px; bottom: 26px; width: 468px; display: flex; flex-direction: column; padding: 22px 26px 20px; }
.chtop { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
.chtop h3 { font-family: 'Cormorant Garamond', Georgia, serif; font-weight: 700; font-size: 27px; color: var(--text); }
.chstate { font-size: 13px; color: var(--text3); white-space: nowrap; }
.chlooks { display: flex; flex-wrap: wrap; gap: 8px; margin: 14px 0 6px; }
.chlooks span { padding: 5px 12px; font-size: 13px; font-weight: 600; color: var(--text2); border: 1px solid rgba(var(--gold-rgb), .28); background: rgba(243, 234, 213, .04); cursor: pointer; transition: border-color .15s, color .15s; }
.chlooks span:hover { border-color: rgba(var(--gold-rgb), .7); color: var(--text); }
.chlooks span.on { border-color: var(--gold-hi); color: var(--gold-hi); background: rgba(var(--gold-rgb), .1); }
.chlist { flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; margin: 6px -12px 0 0; padding: 0 12px 8px 0; scrollbar-width: thin; scrollbar-color: rgba(var(--gold-rgb), .45) transparent; }
.chlist::-webkit-scrollbar { width: 6px; } .chlist::-webkit-scrollbar-track { background: transparent; }
.chlist::-webkit-scrollbar-thumb { background: rgba(var(--gold-rgb), .38); } .chlist::-webkit-scrollbar-thumb:hover { background: rgba(var(--gold-rgb), .6); }
.chlist h4 { margin: 14px 0 2px; font-family: 'Cormorant Garamond', Georgia, serif; font-style: italic; font-weight: 600; font-size: 17px; color: var(--gold-hi); }
.chrow { display: grid; grid-template-columns: 30px 1fr auto 56px; align-items: center; gap: 12px; padding: 11px 2px; border-bottom: 1px solid var(--line-soft); font-size: 15px; cursor: pointer; }
.chrow b { font-weight: 600; } .chrow > span { color: var(--text2); font-size: 13.5px; font-variant-numeric: tabular-nums; letter-spacing: .02em; }
.chrow > span u { display: inline-block; width: 6px; height: 6px; margin-left: 8px; transform: rotate(45deg) translateY(-2px); background: var(--gold-hi); text-decoration: none; }
.chrow em { font-style: normal; color: var(--gold); font-weight: 600; font-size: 14px; text-align: right; }
.chrow.open { border-bottom-color: transparent; } .chrow.open em { color: var(--gold-hi); }
.chrow:hover b { color: var(--gold-hi); }
.chsw { width: 18px; height: 18px; margin-left: 5px; transform: rotate(45deg); background: var(--c); box-shadow: 0 0 0 1px rgba(243, 234, 213, .35), 0 0 0 3px rgba(10, 9, 8, .9); }
.chsw.orig { box-shadow: 0 0 0 1px rgba(243, 234, 213, .18), 0 0 0 3px rgba(10, 9, 8, .9); opacity: .78; }
.chnote { margin-top: 14px !important; }
/* the picker under the open row */
.chpick { display: grid; grid-template-columns: 188px 1fr; gap: 22px; min-width: 0; padding: 8px 2px 18px; border-bottom: 1px solid var(--line-soft); animation: chopen .2s ease; }
@keyframes chopen { from { opacity: 0; transform: translateY(-4px); } }
.chsv { height: 118px; }
.chhue { margin-top: 24px; }
.chpk-r { min-width: 0; }
.chpick label { display: block; font-family: Commissioner, sans-serif; font-style: normal; font-weight: 600; font-size: 13px; color: var(--text3); }
.chpk-r .cp-f input#chHex { width: 112px; font-family: Commissioner, sans-serif; font-style: normal; letter-spacing: .03em; text-transform: uppercase; display: block; height: 36px; margin-top: 5px; padding: 0 12px; font: inherit; font-size: 14.5px; color: var(--text);
background: rgba(243, 234, 213, .05); border: 1px solid rgba(var(--gold-rgb), .35); outline: none; }
.chpk-r .cp-f input#chHex:focus { border-color: var(--gold-hi); } .chpk-r .cp-f input#chHex.bad { border-color: #ff8a92; color: #ffd6d9; }
.chpre { display: grid; grid-template-columns: repeat(8, 14px); gap: 12px 10px; margin: 16px 0 0 4px; }
.chpre span { width: 13px; height: 13px; transform: rotate(45deg); background: var(--c); box-shadow: 0 0 0 1px rgba(243, 234, 213, .25), 0 0 0 3px rgba(10, 9, 8, .9); cursor: pointer; }
.chpre span.on { box-shadow: 0 0 0 2px var(--text), 0 0 0 4px rgba(10, 9, 8, .9); }
.chpk-r .cp-foot { margin-top: 14px; gap: 10px; } .chpk-r .cp-foot .lnk { white-space: nowrap; }
/* the foot: where the picks stand, and Apply */
.chfoot { padding-top: 14px; border-top: 1px solid rgba(var(--gold-rgb), .25); }
.chmsg { font-size: 13.5px; color: var(--text2); line-height: 1.45; }
.chmsg.pend { color: var(--gold-hi); }
.chmsg.warn { color: var(--text3); font-size: 12.5px; margin-top: 4px; }
.chbtns { display: flex; align-items: center; justify-content: flex-end; gap: 22px; margin-top: 12px; }
.chbtns .lnk { color: var(--gold); font-weight: 600; font-size: 14px; cursor: pointer; }
.chbtns .play.sm { width: 230px; height: 50px; font-size: 21px; margin: 0; }
.chbtns .play.off { filter: saturate(.25) brightness(.6); cursor: default; }
.chbar { height: 3px; margin-top: 10px; background: rgba(var(--gold-rgb), .15); } .chbar i { display: block; height: 100%; background: var(--gold-hi); }
.chdye { display: none; color: var(--gold-hi); font-size: 13px; font-weight: 600; margin-left: 8px; } .chdye.on { display: inline-flex; align-items: center; }
/* Link or Linkle: above the ages, the same bar a little smaller */
.chhero { display: flex; width: max-content; margin-top: 16px; } .chhero span { padding: 7px 18px; font-size: 14px; }
.chhero + .chseg { margin-top: 10px; }
/* Linkle not downloaded yet: her card on the stage */
.chget { position: absolute; left: 230px; top: 300px; width: 470px; padding: 24px 28px; display: none; z-index: 3; }
.chget.on { display: block; }
.chget h3 { font-family: 'Cormorant Garamond', Georgia, serif; font-weight: 700; font-size: 27px; }
.chget p { margin-top: 8px; font-size: 14px; line-height: 1.5; color: var(--text2); }
.chget .chbtns { margin-top: 16px; }

353
launcher/ui/char.js Normal file
View File

@@ -0,0 +1,353 @@
/* ((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();
}

441
launcher/ui/char3d.js Normal file
View File

@@ -0,0 +1,441 @@
/* ((Triforce, 11-29) The Character page's stage: Link in 3D, drawn with WebGL2 from the player's own game files (the launcher
sends the posed mesh and the textures: launcher/Core/GameFiles/LinkScene.cs). Studio light: a warm key with a soft shadow
map, a cool fill, a gold rim and a sky/ground ambient; normal maps and AO; ACES tone mapping. The model turns, the lights
stay. Drag turns him, the wheel zooms, a double click looks at the face and back.
Colours: each colour map can carry a "tint" (a mask of where a part is, two parts a map at most, and the part's colour):
that is the live preview while a colour is picked; the launcher then sends OOTRR's own recoloured map (exact) in its place.
Char3D.create(canvas) -> { load(info, meshBuffer, fetchTex), setTint(texName, slots), setColorMap(texName, tex), clearColorMaps(),
look(where), resize(), stop() } with tex = {w, h, data: Uint8Array RGBA}. */
'use strict';
(function () {
const VS = `#version 300 es
layout(location=0) in vec3 aPos; layout(location=1) in vec3 aNrm; layout(location=2) in vec4 aTan; layout(location=3) in vec2 aUv; layout(location=4) in vec4 aCol;
uniform mat4 uModel, uVP, uLightVP;
out vec3 vPos; out vec3 vNrm; out vec4 vTan; out vec2 vUv; out vec4 vLight; out vec4 vCol;
void main() {
vec4 w = uModel * vec4(aPos, 1.0);
vPos = w.xyz; vNrm = mat3(uModel) * aNrm; vTan = vec4(mat3(uModel) * aTan.xyz, aTan.w); vUv = aUv;
vLight = uLightVP * w; vCol = aCol;
gl_Position = uVP * w;
}`;
const FS = `#version 300 es
precision highp float;
in vec3 vPos; in vec3 vNrm; in vec4 vTan; in vec2 vUv; in vec4 vLight; in vec4 vCol;
uniform int uDebug, uStrands;
uniform sampler2D uAlb, uNrm, uAo, uLut, uGrey, uMask, uShadow, uNrm2, uEmc;
uniform int uHasEmc;
uniform int uHasAlb, uHasNrm, uHasAo, uHasLut, uHasNrm2, uKind, uAlphaMode, uTint;
uniform vec4 uTintA, uTintB; /* rgb: the part's colour at its median texel (linear), a: that texel's luminance (0: not tinted) */
uniform vec2 uTintG; /* (11-30) each part's contrast: its texels scale as (y / a)^g, at most 3.6x the median (OOTRR flattens its top: 99% ~3.8x) */
uniform vec3 uEye; uniform float uExposure, uTile;
out vec4 frag;
float lum(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
vec3 aces(vec3 x) { const float a = 2.51, b = 0.03, c = 2.43, d = 0.59, e = 0.14; return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0); }
float shadowAt(vec3 n, vec3 l) {
vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5;
if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0 || p.z > 1.0) return 1.0;
float bias = 0.0012 + 0.0025 * (1.0 - max(dot(n, l), 0.0));
vec2 texel = 1.0 / vec2(textureSize(uShadow, 0));
float s = 0.0;
for (int y = -2; y <= 2; y++) for (int x = -2; x <= 2; x++)
s += (p.z - bias <= texture(uShadow, p.xy + vec2(x, y) * texel * 1.2).r) ? 1.0 : 0.0;
return s / 25.0;
}
void main() {
vec4 alb = uHasAlb == 1 ? texture(uAlb, vUv) : vec4(0.6, 0.6, 0.6, 1.0);
if (uHasLut == 1) {
/* young Link's hair has no colour map: the game's own hair ramp (its warm half), varied a strand at a time by the
vertex colour, darker where the strand mask says the strand turns under */
float g = texture(uGrey, vUv).r;
vec3 c = texture(uLut, vec2(0.58 + 0.38 * clamp(vCol.r, 0.0, 1.0), 0.5)).rgb;
c = mix(vec3(lum(c)), c, 0.78) * (0.72 + 0.28 * g) * mix(0.82, 1.0, clamp(vCol.g, 0.0, 1.0));
/* strands: fine stripes across the card (its u), each strand its own shade */
float su = vUv.x * float(uStrands);
float id = floor(su), fr = fract(su);
float h1 = fract(sin(id * 12.9898 + floor(vUv.y * 3.0) * 4.1) * 43758.5);
float edge = smoothstep(0.0, 0.25, fr) * smoothstep(1.0, 0.75, fr);
c *= mix(0.62, 1.08, h1) * mix(0.78, 1.0, edge);
alb = vec4(c, 1.0);
}
if (uAlphaMode == 1 && alb.a < 0.45) discard;
if (uAlphaMode == 3) { frag = vec4(0.06, 0.025, 0.02, alb.r * 0.5); return; }
if (uKind == 5) { /* Navi's body: her light */
vec3 c = alb.rgb; float f = pow(1.0 - abs(dot(normalize(vNrm), normalize(uEye - vPos))), 2.0);
frag = vec4(pow(aces(c * (1.6 + 2.2 * f)), vec3(1.0 / 2.2)), 1.0); return;
}
if (uKind == 6) { /* her wings: thin and lit, their own glow added */
vec3 e = uHasEmc == 1 ? texture(uEmc, vUv).rgb : vec3(0.0);
vec3 c = alb.rgb * 0.55 + e * 1.8;
frag = vec4(pow(aces(c), vec3(1.0 / 2.2)), clamp(alb.a * 0.7 + lum(e), 0.0, 1.0)); return;
}
if (uKind == 8) { vec3 c = alb.rgb; if (uAlphaMode == 1 && alb.a < 0.45) discard; frag = vec4(pow(aces(c * 1.4 + c * c * 0.8), vec3(1.0 / 2.2)), 1.0); return; }
if (uKind == 7) { if (alb.a < 0.3) discard; frag = vec4(pow(aces(alb.rgb * 2.0), vec3(1.0 / 2.2)), 0.55); return; }
if (uAlphaMode == 4) { frag = vec4(pow(clamp(alb.rgb * 1.4, 0.0, 1.0), vec3(1.0 / 2.2)), 0.0); return; } /* the eye's highlights: added */
vec3 base = alb.rgb;
if (uTint == 1) {
vec2 m = texture(uMask, vUv).rg;
float y = lum(base);
if (uTintA.a > 0.0 && m.r > 0.0) base = mix(base, uTintA.rgb * min(pow(clamp(y / uTintA.a, 0.0, 4.0), uTintG.x), 3.6), m.r);
if (uTintB.a > 0.0 && m.g > 0.0) base = mix(base, uTintB.rgb * min(pow(clamp(y / uTintB.a, 0.0, 4.0), uTintG.y), 3.6), m.g);
}
if (uKind == 1) base *= vec3(1.0, 0.9, 0.82); /* skin: the game's skin shading warms it */
if (uKind == 3) base = mix(base, base * 1.35, 0.6); /* eyes: the game lights them from inside */
vec3 n = normalize(vNrm);
if (!gl_FrontFacing) n = -n;
if (uHasNrm == 1) {
vec3 t = normalize(vTan.xyz - n * dot(n, vTan.xyz));
vec3 b = cross(n, t) * (vTan.w < 0.0 ? -1.0 : 1.0);
vec2 xy = texture(uNrm, vUv).rg * 2.0 - 1.0;
if (uHasNrm2 == 1) xy += (texture(uNrm2, vUv * uTile).rg * 2.0 - 1.0) * 0.6;
vec3 tn = vec3(xy, sqrt(max(1.0 - dot(xy, xy), 0.0)));
n = normalize(mat3(t, b, n) * tn);
}
float ao = uHasAo == 1 ? mix(1.0, texture(uAo, vUv).r, 0.85) : 1.0;
vec3 v = normalize(uEye - vPos);
/* lights: key (warm, upper left front, shadowed), fill (cool, right), rim (gold, behind) */
vec3 lk = normalize(vec3(-0.55, 0.72, 0.62)), lf = normalize(vec3(0.85, 0.25, 0.45)), lr = normalize(vec3(0.35, 0.55, -0.9));
vec3 ck = vec3(1.0, 0.9, 0.76) * 3.1, cf = vec3(0.46, 0.56, 0.8) * 0.8, cr = vec3(1.0, 0.78, 0.42) * 2.4;
float rough = uKind == 1 ? 0.5 : uKind == 2 ? 0.42 : uKind == 3 ? 0.12 : uKind == 4 ? 0.3 : 0.82;
float spec = uKind == 1 ? 0.35 : uKind == 2 ? 0.5 : uKind == 3 ? 1.0 : uKind == 4 ? 0.9 : 0.18;
float sh = shadowAt(n, lk);
float wrap = uKind == 1 ? 0.35 : 0.08;
float dk = max((dot(n, lk) + wrap) / (1.0 + wrap), 0.0) * sh;
float df = max((dot(n, lf) + wrap) / (1.0 + wrap), 0.0);
float fres = pow(1.0 - max(dot(n, v), 0.0), 3.0);
float dr = max(dot(n, lr), 0.0) * (0.35 + 0.65 * fres);
float sp = pow(2.0, 12.0 * (1.0 - rough));
vec3 hk = normalize(lk + v), hr = normalize(lr + v);
float sk = pow(max(dot(n, hk), 0.0), sp) * (sp + 8.0) / 25.0 * sh;
float sr = pow(max(dot(n, hr), 0.0), sp) * (sp + 8.0) / 25.0;
vec3 specCol = uKind == 4 ? base * 1.6 + 0.04 : vec3(0.04 + 0.08 * fres);
vec3 sky = vec3(0.34, 0.36, 0.42), ground = vec3(0.22, 0.16, 0.1);
vec3 amb = mix(ground, sky, n.y * 0.5 + 0.5) * 0.55;
vec3 col = base * (amb * ao + ck * dk * ao + cf * df * ao + cr * dr * 0.55)
+ specCol * spec * (ck * sk + cr * sr * 0.6) * ao;
if (uKind == 1) col += base * vec3(0.9, 0.25, 0.15) * 0.09 * (1.0 - dk);
if (uKind == 3) col += base * 0.55; /* eyes: lit from within, never black in shadow */
if (uKind == 2) {
vec3 tt = normalize(vTan.xyz);
float th = dot(tt, hk), kk = sqrt(max(1.0 - th * th, 0.0));
float s1 = pow(kk, 90.0), s2 = pow(sqrt(max(1.0 - pow(dot(tt, normalize(hk + n * 0.12)), 2.0), 0.0)), 24.0);
col += (ck * 0.05 * s1 + base * ck * 0.06 * s2) * sh * ao;
} /* skin: a little warmth where the light turns */
col = aces(col * uExposure);
frag = vec4(pow(col, vec3(1.0 / 2.2)), uAlphaMode == 2 ? alb.a : 1.0);
}`;
const SVS = `#version 300 es
layout(location=0) in vec3 aPos; layout(location=3) in vec2 aUv;
uniform mat4 uModel, uLightVP; out vec2 vUv;
void main() { vUv = aUv; gl_Position = uLightVP * uModel * vec4(aPos, 1.0); }`;
const SFS = `#version 300 es
precision mediump float; in vec2 vUv; uniform sampler2D uAlb; uniform int uCut; out vec4 o;
void main() { if (uCut == 1 && texture(uAlb, vUv).a < 0.45) discard; o = vec4(1.0); }`;
/* the floor: a dark disc lit from above, with his shadow and a gold ring at its edge */
const GVS = `#version 300 es
layout(location=0) in vec2 aXZ; uniform mat4 uVP, uLightVP; uniform float uR; out vec2 vXZ; out vec4 vLight;
void main() { vXZ = aXZ; vec4 w = vec4(aXZ.x * uR, 0.0, aXZ.y * uR, 1.0); vLight = uLightVP * w; gl_Position = uVP * w; }`;
const GFS = `#version 300 es
precision highp float; in vec2 vXZ; in vec4 vLight; uniform sampler2D uShadow; out vec4 o;
void main() {
float r = length(vXZ);
if (r > 1.0) discard;
vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5; float s = 0.0;
vec2 texel = 1.0 / vec2(textureSize(uShadow, 0));
for (int y = -3; y <= 3; y++) for (int x = -3; x <= 3; x++) s += (p.z - 0.003 <= texture(uShadow, p.xy + vec2(x, y) * texel * 2.0).r) ? 1.0 : 0.0;
s /= 49.0;
float pool = smoothstep(1.0, 0.0, r);
vec3 c = mix(vec3(0.02, 0.018, 0.014), vec3(0.2, 0.15, 0.08), pool * pool) * (0.35 + 0.65 * s);
float ring = smoothstep(0.03, 0.0, abs(r - 0.93)) * 0.9 + smoothstep(0.012, 0.0, abs(r - 0.86)) * 0.4;
c += vec3(0.88, 0.66, 0.24) * ring * 0.45;
float a = smoothstep(1.0, 0.82, r) * (0.75 + 0.25 * pool);
o = vec4(pow(c, vec3(1.0 / 2.2)) * a, a);
}`;
/* Navi's glow: a soft disc that faces the camera, added over everything */
const HVS = `#version 300 es
layout(location=0) in vec2 aXZ; uniform mat4 uVP; uniform vec3 uAt, uRight, uUp; uniform float uR; out vec2 vQ;
void main() { vQ = aXZ; gl_Position = uVP * vec4(uAt + (uRight * aXZ.x + uUp * aXZ.y) * uR, 1.0); }`;
const HFS = `#version 300 es
precision mediump float; in vec2 vQ; uniform vec3 uCol; out vec4 o;
void main() { float r = length(vQ); if (r > 1.0) discard; float a = exp(-r * r * 5.0) * 0.85 + exp(-r * r * 40.0) * 0.6; o = vec4(uCol * a, 0.0); }`;
const KIND = { cloth: 0, skin: 1, hair: 2, eye: 3, metal: 4, lash: 0, fur: 0, shade: 0, glint: 0, navi: 5, wing: 6, navifur: 7, fairy: 8 };
const SOFT = { lash: 1, shade: 1, glint: 1, wing: 1, navifur: 1 };
function compile(gl, vs, fs) {
const p = gl.createProgram();
for (const [t, s] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {
const sh = gl.createShader(t); gl.shaderSource(sh, s); gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh));
gl.attachShader(p, sh);
}
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
const u = {}; const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS);
for (let i = 0; i < n; i++) { const a = gl.getActiveUniform(p, i); u[a.name] = gl.getUniformLocation(p, a.name); }
return { p, u };
}
/* column-major 4x4 helpers */
function mul(a, b) { const o = new Float32Array(16); for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) { let s = 0; for (let k = 0; k < 4; k++) s += a[k * 4 + r] * b[c * 4 + k]; o[c * 4 + r] = s; } return o; }
function persp(fov, asp, n, f) { const t = 1 / Math.tan(fov / 2), o = new Float32Array(16); o[0] = t / asp; o[5] = t; o[10] = (f + n) / (n - f); o[11] = -1; o[14] = 2 * f * n / (n - f); return o; }
function ortho(l, r, b, t, n, f) { const o = new Float32Array(16); o[0] = 2 / (r - l); o[5] = 2 / (t - b); o[10] = -2 / (f - n); o[12] = -(r + l) / (r - l); o[13] = -(t + b) / (t - b); o[14] = -(f + n) / (f - n); o[15] = 1; return o; }
function lookAt(e, c, up) {
const z = norm([e[0] - c[0], e[1] - c[1], e[2] - c[2]]), x = norm(cross(up, z)), y = cross(z, x);
return new Float32Array([x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, e), -dot(y, e), -dot(z, e), 1]);
}
function rotY(a) { const c = Math.cos(a), s = Math.sin(a); return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]); }
function norm(v) { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; }
function cross(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; }
function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
function create(canvas) {
const gl = canvas.getContext('webgl2', { antialias: true, alpha: true, premultipliedAlpha: true, preserveDrawingBuffer: false });
if (!gl) return null;
const aniso = gl.getExtension('EXT_texture_filter_anisotropic');
const main = compile(gl, VS, FS), shadow = compile(gl, SVS, SFS), floor = compile(gl, GVS, GFS), halo = compile(gl, HVS, HFS);
const SHADOW = 2048;
const shadowTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, shadowTex);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.DEPTH_COMPONENT24, SHADOW, SHADOW);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
const shadowFb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, shadowTex, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const floorBuf = gl.createBuffer(), floorVao = gl.createVertexArray();
gl.bindVertexArray(floorVao); gl.bindBuffer(gl.ARRAY_BUFFER, floorBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
const white = tex1([255, 255, 255, 255]), flat = tex1([128, 128, 255, 255]);
function tex1(c) { const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(c)); return t; }
const S = { parts: [], vao: null, buf: [], tex: new Map(), color: new Map(), tints: new Map(), masks: new Map(), info: null,
yaw: 0.35, yawTo: 0.35, pitch: 0.04, pitchTo: 0.04, dist: 0, distTo: 0, tgt: [0, 1, 0], tgtTo: [0, 1, 0], face: false,
spin: false, idleAt: 0, dirty: true, raf: 0, gen: 0, ready: false, naviCol: [0.75, 0.88, 1.0] }; // ((11-30, the owner) no idle turn: Link turns only when dragged or with the arrows
function upload(t, srgb, clamp) {
const g = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, g);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage2D(gl.TEXTURE_2D, 0, srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8, t.w, t.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, t.data);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const wrap = clamp ? gl.CLAMP_TO_EDGE : gl.REPEAT;
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
if (aniso) gl.texParameterf(gl.TEXTURE_2D, aniso.TEXTURE_MAX_ANISOTROPY_EXT, 8);
return g;
}
/* info: LinkScene's JSON; mesh: ArrayBuffer; fetchTex(name) -> Promise<{w,h,data}|null>. Resolves once every texture is in. */
async function load(info, mesh, fetchTex) {
const gen = ++S.gen;
S.ready = false;
const vao = gl.createVertexArray(), vb = gl.createBuffer(), ib = gl.createBuffer();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, vb); gl.bufferData(gl.ARRAY_BUFFER, mesh, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh, gl.STATIC_DRAW);
gl.bindVertexArray(null);
const want = new Set();
for (const p of info.parts) for (const k of ['alb', 'nrm', 'nrm2', 'ao', 'lut', 'grey', 'emc']) if (p[k] && !S.tex.has(p[k])) want.add(p[k]);
await Promise.all([...want].map(async n => {
const t = await fetchTex(n).catch(() => null);
if (gen !== S.gen) return;
const srgb = info.parts.some(p => p.alb === n || p.lut === n || p.emc === n);
S.tex.set(n, t ? upload(t, srgb, n.startsWith('eye:') || info.parts.some(p => p.lut === n)) : null);
}));
if (gen !== S.gen) { gl.deleteVertexArray(vao); gl.deleteBuffer(vb); gl.deleteBuffer(ib); return; }
if (S.vao) { gl.deleteVertexArray(S.vao); S.buf.forEach(b => gl.deleteBuffer(b)); }
S.vao = vao; S.buf = [vb, ib]; S.info = info;
S.parts = info.parts.filter(p => !(SOFT[p.kind] && !p.alb) && !(p.alb && !S.tex.get(p.alb) && !p.lut));
const h = info.max[1] - info.min[1];
S.height = h;
const fit = body();
S.tgtTo = fit.tgt.slice(); S.distTo = fit.dist;
if (!S.dist) { S.tgt = fit.tgt.slice(); S.dist = fit.dist * 1.25; }
S.face = false;
S.ready = true; S.dirty = true;
if (!S.raf) S.raf = requestAnimationFrame(frame);
}
function body() { const h = S.height || 1.2; return { tgt: [0, h * 0.47, 0], dist: h * 2.75 }; }
function headView() { const h = S.height || 1.2; return { tgt: [0, h * 0.84, 0], dist: h * 1.2 }; }
function look(where) {
const v = where === 'face' ? headView() : body();
S.face = where === 'face'; S.tgtTo = v.tgt; S.distTo = v.dist; S.dirty = true;
if (S.face) { S.yawTo = Math.round(S.yawTo / (2 * Math.PI)) * 2 * Math.PI + 0.25; S.pitchTo = 0.02; }
}
function draw(proj, view, eye, light) {
const W = canvas.width, H = canvas.height;
const model = rotY(S.yaw);
/* shadow pass */
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb);
gl.viewport(0, 0, SHADOW, SHADOW);
gl.clear(gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.disable(gl.BLEND); gl.colorMask(false, false, false, false);
gl.useProgram(shadow.p);
gl.uniformMatrix4fv(shadow.u.uModel, false, model); gl.uniformMatrix4fv(shadow.u.uLightVP, false, light);
gl.bindVertexArray(S.vao);
bindAttrs();
gl.activeTexture(gl.TEXTURE0); gl.uniform1i(shadow.u.uAlb, 0);
for (const p of S.parts) {
if (SOFT[p.kind] || p.kind === 'eye' || p.kind === 'navi') continue;
const cut = cutOf(p);
gl.uniform1i(shadow.u.uCut, cut === 1 ? 1 : 0);
ptrs(p);
gl.bindTexture(gl.TEXTURE_2D, (p.alb && S.tex.get(p.alb)) || white);
gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff);
}
gl.colorMask(true, true, true, true);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, W, H);
gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const vp = mul(proj, view);
/* floor */
gl.useProgram(floor.p);
gl.uniformMatrix4fv(floor.u.uVP, false, vp); gl.uniformMatrix4fv(floor.u.uLightVP, false, light); gl.uniform1f(floor.u.uR, S.height * 0.46);
gl.activeTexture(gl.TEXTURE7); gl.bindTexture(gl.TEXTURE_2D, shadowTex); gl.uniform1i(floor.u.uShadow, 7);
gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.depthMask(true); gl.disable(gl.BLEND);
/* Link */
gl.useProgram(main.p);
gl.uniformMatrix4fv(main.u.uModel, false, model); gl.uniformMatrix4fv(main.u.uVP, false, vp); gl.uniformMatrix4fv(main.u.uLightVP, false, light);
gl.uniform3fv(main.u.uEye, eye); gl.uniform1f(main.u.uExposure, 0.86);
gl.uniform1i(main.u.uAlb, 0); gl.uniform1i(main.u.uNrm, 1); gl.uniform1i(main.u.uAo, 2); gl.uniform1i(main.u.uLut, 3); gl.uniform1i(main.u.uGrey, 4);
gl.uniform1i(main.u.uMask, 5); gl.uniform1i(main.u.uNrm2, 6); gl.uniform1i(main.u.uShadow, 7); gl.uniform1i(main.u.uEmc, 8);
gl.bindVertexArray(S.vao);
const opaque = S.parts.filter(p => !SOFT[p.kind]), soft = S.parts.filter(p => SOFT[p.kind]);
for (const p of opaque) drawPart(p);
gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
for (const p of soft) {
if (p.kind === 'glint') gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ZERO, gl.ONE);
drawPart(p);
if (p.kind === 'glint') gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
}
gl.depthMask(true); gl.disable(gl.BLEND);
/* Navi's glow */
const at = S.info && S.info.navi;
if (at) {
const c = Math.cos(S.yaw), s = Math.sin(S.yaw);
const w = [c * at[0] + s * at[2], at[1], -s * at[0] + c * at[2]];
const right = [view[0], view[4], view[8]], upv = [view[1], view[5], view[9]];
gl.useProgram(halo.p);
gl.uniformMatrix4fv(halo.u.uVP, false, vp); gl.uniform3fv(halo.u.uAt, w); gl.uniform3fv(halo.u.uRight, right); gl.uniform3fv(halo.u.uUp, upv);
gl.uniform1f(halo.u.uR, S.height * 0.16); gl.uniform3fv(halo.u.uCol, S.naviCol);
/* (depth-tested: when she flies behind him, his head hides her glow) */
gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); gl.depthMask(false);
gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.depthMask(true); gl.disable(gl.BLEND);
}
}
function cutOf(p) { return p.kind === 'fairy' ? 1 : p.kind === 'glint' ? 4 : p.kind === 'shade' ? 3 : p.kind === 'lash' ? 2 : (p.kind === 'hair' || p.kind === 'fur' || /Alpha|Mask|Feather|Band/.test(p.mat)) ? 1 : 0; }
function bindAttrs() {
gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]);
for (let i = 0; i < 5; i++) gl.enableVertexAttribArray(i);
}
function ptrs(p) {
const stride = 64;
gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, p.voff);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, p.voff + 12);
gl.vertexAttribPointer(2, 4, gl.FLOAT, false, stride, p.voff + 24);
gl.vertexAttribPointer(3, 2, gl.FLOAT, false, stride, p.voff + 40);
gl.vertexAttribPointer(4, 4, gl.FLOAT, false, stride, p.voff + 48);
}
function drawPart(p) {
ptrs(p);
const albName = p.alb;
const colorMap = albName && S.color.get(albName);
const t = (n) => (n && S.tex.get(n)) || null;
const alb = colorMap || t(albName);
bindTex(0, alb || white); gl.uniform1i(main.u.uHasAlb, alb ? 1 : 0);
bindTex(1, t(p.nrm) || flat); gl.uniform1i(main.u.uHasNrm, t(p.nrm) ? 1 : 0);
bindTex(2, t(p.ao) || white); gl.uniform1i(main.u.uHasAo, t(p.ao) ? 1 : 0);
const lut = !alb && t(p.lut) && t(p.grey);
bindTex(3, lut ? t(p.lut) : white); bindTex(4, lut ? t(p.grey) : white); gl.uniform1i(main.u.uHasLut, lut ? 1 : 0);
bindTex(8, t(p.emc) || white); gl.uniform1i(main.u.uHasEmc, t(p.emc) ? 1 : 0);
bindTex(6, t(p.nrm2) || flat); gl.uniform1i(main.u.uHasNrm2, t(p.nrm2) ? 1 : 0); gl.uniform1f(main.u.uTile, 1.0);
const tint = albName && S.tints.get(albName);
if (tint && S.masks.get(albName)) {
bindTex(5, S.masks.get(albName));
gl.uniform1i(main.u.uTint, 1);
gl.uniform4fv(main.u.uTintA, tint[0] ? tint[0].slice(0, 4) : [0, 0, 0, 0]); gl.uniform4fv(main.u.uTintB, tint[1] ? tint[1].slice(0, 4) : [0, 0, 0, 0]);
gl.uniform2f(main.u.uTintG, tint[0] && tint[0][4] || 1, tint[1] && tint[1][4] || 1); // ((11-30) each slot's contrast
} else { bindTex(5, white); gl.uniform1i(main.u.uTint, 0); }
gl.uniform1i(main.u.uKind, KIND[p.kind] || 0); gl.uniform1i(main.u.uDebug, window.charDebug || 0); gl.uniform1i(main.u.uStrands, window.charStrands || 80);
gl.uniform1i(main.u.uAlphaMode, cutOf(p));
if (p.kind === 'hair') gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE);
gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff);
if (p.kind === 'hair') gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
}
function bindTex(unit, t) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, t); }
let last = 0;
function frame(now) {
S.raf = requestAnimationFrame(frame);
const dt = Math.min(0.05, (now - (last || now)) / 1000); last = now;
if (!S.ready) return;
if (S.spin && !S.drag && !S.face && now - S.idleAt > 2500) { S.yawTo += dt * 0.32; }
const k = 1 - Math.pow(0.0008, dt);
const moved = Math.abs(S.yawTo - S.yaw) + Math.abs(S.pitchTo - S.pitch) + Math.abs(S.distTo - S.dist) + Math.abs(S.tgtTo[1] - S.tgt[1]);
if (moved < 1e-5 && !S.dirty) return;
S.yaw += (S.yawTo - S.yaw) * k; S.pitch += (S.pitchTo - S.pitch) * k; S.dist += (S.distTo - S.dist) * k;
for (let i = 0; i < 3; i++) S.tgt[i] += (S.tgtTo[i] - S.tgt[i]) * k;
S.dirty = false;
const W = canvas.width, H = canvas.height;
const eye = [S.tgt[0], S.tgt[1] + Math.sin(S.pitch) * S.dist, S.tgt[2] + Math.cos(S.pitch) * S.dist];
const proj = persp(26 * Math.PI / 180, W / H, 0.05, 20);
const view = lookAt(eye, S.tgt, [0, 1, 0]);
const h = S.height;
const lightDir = norm([-0.55, 0.72, 0.62]);
const lc = [lightDir[0] * 4, h * 0.5 + lightDir[1] * 4, lightDir[2] * 4];
const light = mul(ortho(-h * 0.75, h * 0.75, -h * 0.75, h * 0.75, 0.5, 9), lookAt(lc, [0, h * 0.5, 0], [0, 1, 0]));
draw(proj, view, eye, light);
}
/* input: drag turns him (and tilts the view a little), the wheel zooms, a double click looks at his face and back */
canvas.addEventListener('pointerdown', e => { S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); canvas.setPointerCapture(e.pointerId); canvas.classList.add('grab'); });
canvas.addEventListener('pointermove', e => {
if (!S.drag) return;
S.yawTo += (e.clientX - S.drag.x) * 0.011; S.pitchTo = Math.max(-0.25, Math.min(0.55, S.pitchTo + (e.clientY - S.drag.y) * 0.004));
S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); S.dirty = true;
});
const up = () => { S.drag = null; S.idleAt = performance.now(); canvas.classList.remove('grab'); };
canvas.addEventListener('pointerup', up); canvas.addEventListener('pointercancel', up);
canvas.addEventListener('wheel', e => {
e.preventDefault();
const b = body(), f = headView();
S.distTo = Math.max(f.dist * 0.8, Math.min(b.dist * 1.3, S.distTo * (e.deltaY > 0 ? 1.12 : 0.89)));
/* (closer: the view slides up toward the face) */
const t = Math.max(0, Math.min(1, (b.dist - S.distTo) / (b.dist - f.dist)));
S.tgtTo = [0, b.tgt[1] + (f.tgt[1] - b.tgt[1]) * t, 0]; S.face = t > 0.6; S.idleAt = performance.now(); S.dirty = true;
}, { passive: false });
canvas.addEventListener('dblclick', () => look(S.face ? 'body' : 'face'));
function resize() {
const r = canvas.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1);
const w = Math.max(1, Math.round(r.width * d)), h = Math.max(1, Math.round(r.height * d));
if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; S.dirty = true; }
}
resize();
return {
load, look, resize,
turn(by) { S.yawTo += by; S.idleAt = performance.now(); S.dirty = true; },
spin(on) { S.spin = on; },
/* a part's live colour: slots [[r,g,b,yref,contrast] | null, ...] in linear light, or null to stop */
/* Navi's glow colour (#rrggbb), null for her own */
setNaviColor(hex) { const c = hex ? [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255) : [0.75, 0.88, 1.0]; S.naviCol = c.map(x => Math.max(0.12, x)); S.dirty = true; },
setTint(name, slots) { if (slots) S.tints.set(name, slots); else S.tints.delete(name); S.dirty = true; },
setMask(name, t) { const old = S.masks.get(name); if (old) gl.deleteTexture(old); if (t) S.masks.set(name, upload(t, false, false)); else S.masks.delete(name); S.dirty = true; },
setColorMap(name, t) { const old = S.color.get(name); if (old) gl.deleteTexture(old); if (t) S.color.set(name, upload(t, true, false)); else S.color.delete(name); S.dirty = true; },
/* every texture let go (another hero's files carry the same names) */
clearTextures() { for (const g of S.tex.values()) if (g) gl.deleteTexture(g); S.tex.clear(); for (const g of S.color.values()) gl.deleteTexture(g); S.color.clear(); for (const g of S.masks.values()) gl.deleteTexture(g); S.masks.clear(); S.tints.clear(); S.ready = false; S.dirty = true; },
clearColorMaps() { for (const t of S.color.values()) gl.deleteTexture(t); S.color.clear(); S.tints.clear(); S.dirty = true; },
get ready() { return S.ready; },
stop() { cancelAnimationFrame(S.raf); S.raf = 0; },
start() { if (!S.raf) { S.dirty = true; S.raf = requestAnimationFrame(frame); } },
};
}
window.Char3D = { create };
})();

View File

@@ -1,6 +1,6 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Triforce</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="ui.css"><link rel="stylesheet" href="theme.css"><link rel="stylesheet" href="v3.css"><link rel="stylesheet" href="proto.css"><link rel="stylesheet" href="app.css"></head>
<link rel="stylesheet" href="ui.css"><link rel="stylesheet" href="theme.css"><link rel="stylesheet" href="v3.css"><link rel="stylesheet" href="proto.css"><link rel="stylesheet" href="app.css"><link rel="stylesheet" href="char.css"></head>
<body>
<div id="fit"><div class="win" id="win">
@@ -76,7 +76,7 @@
</section>
<!-- ============ SAVES ============ -->
<section class="screen" id="s-saves" data-first="sc0" data-back="home" data-tab="3">
<section class="screen" id="s-saves" data-first="sc0" data-back="home" data-tab="4">
<div class="scene"><div class="img" id="savesImg" style="filter:blur(26px) saturate(1.1) brightness(.5)"></div><div class="grade"></div><div class="grain"></div></div>
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="savesEb"></div><h1 style="font-size:54px">Your files</h1></div></div>
<div class="sgrid" id="sgrid"></div>
@@ -105,8 +105,24 @@
<div class="rside"><div class="benchcard fbox rcard" id="randoCard"></div><div class="rtip fbox" id="randoTip"></div></div>
</section>
<!-- ============ CHARACTER (char.js + char3d.js; launcher/App/Backend.Character.cs) ============ -->
<section class="screen" id="s-char" data-first="chHero0" data-back="home" data-tab="3">
<div class="chstage"><canvas id="chCanvas"></canvas><div class="chglow"></div></div>
<div class="chhead"><div class="cont" style="position:static;width:auto"><div class="eb" id="chEb">Your hero, in your colors</div><h1 style="font-size:54px">Character</h1></div>
<div class="chseg chhero" id="chHeroes"><span data-f id="chHero0" data-act="chhero:link">Link</span><span data-f id="chHero1" data-act="chhero:linkle">Linkle</span></div>
<div class="chseg" id="chAges"><span data-f id="chAge0" data-act="chage:child">Young Link</span><span data-f id="chAge1" data-act="chage:adult">Adult Link</span></div>
<div class="chtunic" id="chTunics"><span data-f id="chTu0" data-act="chtunic:kokiri">Kokiri Tunic</span><span data-f id="chTu1" data-act="chtunic:goron">Goron Tunic</span><span data-f id="chTu2" data-act="chtunic:zora">Zora Tunic</span></div></div>
<div class="chview"><span class="lnk" data-f id="chTurnL" data-act="chturn:-1" title="Turn left">&#9664;</span><span class="lnk" data-f id="chFace" data-act="chface">Face</span><span class="lnk" data-f id="chTurnR" data-act="chturn:1" title="Turn right">&#9654;</span><em>Drag to turn &#183; scroll to zoom</em><span class="chdye" id="chDye"><i class="chspin sm"></i>Dyeing</span></div>
<div class="chget fbox" id="chGet"></div>
<div class="chwait" id="chWait"><div class="chspin"></div><span id="chWaitT">Reading Link from your game</span></div>
<div class="chpanel fbox" id="chPanel"><div class="chtop"><h3 id="chTitle">Young Link's colors</h3><span class="chstate" id="chState"></span></div>
<div class="chlooks" id="chLooks"></div>
<div class="chlist" id="chList"></div>
<div class="chfoot" id="chFoot"></div></div>
</section>
<!-- ============ SETTINGS ============ -->
<section class="screen" id="s-settings" data-first="row0" data-back="home" data-tab="4">
<section class="screen" id="s-settings" data-first="row0" data-back="home" data-tab="5">
<div class="scene"><div class="img" id="setImg" style="filter:blur(26px) saturate(1.1) brightness(.45)"></div><div class="grade"></div><div class="grain"></div></div>
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="setEb">The launcher and your game</div><h1 style="font-size:54px">Settings</h1></div></div>
<div class="settabs" id="setTabs"></div>
@@ -125,7 +141,7 @@
</section>
<!-- ============ BENCHMARK RESULTS ============ -->
<section class="screen" id="s-bench" data-first="applyBtn" data-back="settings" data-tab="4">
<section class="screen" id="s-bench" data-first="applyBtn" data-back="settings" data-tab="5">
<div class="scene"><div class="img" id="benchImg" style="filter:blur(26px) saturate(1.1) brightness(.5)"></div><div class="grade"></div><div class="grain"></div></div>
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="benchEb"></div><h1 style="font-size:54px">Your best settings</h1></div></div>
<div class="bench"><div><div class="places" id="places"></div>
@@ -138,7 +154,7 @@
<!-- ============ shared: the bar, the sound panel, the sheet ============ -->
<div class="bar" id="bar"><div class="brand flair"><div class="mark"></div><span>Triforce</span></div>
<div class="nav" id="nav"><a data-f data-go="home">Play</a><a data-f data-go="mods">Mods</a><a data-f data-go="rando">Randomizer</a><a data-f data-go="saves">Saves</a><a data-f data-go="settings">Settings</a></div>
<div class="nav" id="nav"><a data-f data-go="home">Play</a><a data-f data-go="mods">Mods</a><a data-f data-go="rando">Randomizer</a><a data-f data-go="char">Character</a><a data-f data-go="saves">Saves</a><a data-f data-go="settings">Settings</a></div>
<div class="grow"></div><div class="state" id="pill"></div>
<div class="spk on" id="spk" data-f data-act="vol"><svg viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M15.5 9a4.5 4.5 0 0 1 0 6M18 6.5a8 8 0 0 1 0 11"/></svg></div>
<div class="wc"><span data-act="win:min"><svg viewBox="0 0 12 12"><path d="M1 6.5h10"/></svg></span><span data-act="win:max"><svg viewBox="0 0 12 12"><rect x="1.5" y="1.5" width="9" height="9"/></svg></span><span data-act="win:close"><svg viewBox="0 0 12 12"><path d="M1.5 1.5l9 9M10.5 1.5l-9 9"/></svg></span></div></div>
@@ -158,4 +174,6 @@
<script src="demo.js"></script>
<script src="app.js"></script>
<script src="rando.js"></script>
<script src="char3d.js"></script>
<script src="char.js"></script>
</body></html>