Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(play): change your avatar from inside the world, and wire the new HUD surfaces

nirholas470840568533
diff --git a/pages/play.html b/pages/play.html
index 9893f9286..f85b8378c 100644
--- a/pages/play.html
+++ b/pages/play.html
@@ -153,6 +153,7 @@
<script type="module" src="/src/game/coincommunities.js"></script>
<script type="module" src="/src/game/ambient-crowd.js"></script>
<script type="module" src="/src/game/event-countdown.js"></script>
+ <script type="module" src="/src/game/meetup-event.js"></script>
<script src="/brand.js" defer></script>
<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
<script type="module" src="/i18n.js"></script>
diff --git a/src/game/avatar-switcher.js b/src/game/avatar-switcher.js
new file mode 100644
index 000000000..502a942a0
--- /dev/null
+++ b/src/game/avatar-switcher.js
@@ -0,0 +1,327 @@
+// In-world avatar switcher (/play). The lobby's avatar bar is unreachable once
+// a world is entered (it lives inside the hidden lobby DOM), so this panel puts
+// the whole avatar toolset behind the HUD's Avatar button and the V hotkey:
+// your saved three.ws avatars, community quick picks, the shared gallery
+// picker, a paste-a-URL/id field, a .glb/.vrm upload, and the full in-app
+// creator. Every pick routes through one handler the scene owns
+// (`onPick(value, meta)` in coincommunities.js `_applyAvatarSwap`), which
+// rebuilds the local rig and broadcasts the change so peers re-render it live.
+// The panel never touches the rig or the network itself, so it stays a pure
+// view that can be torn down with the world.
+//
+// Server side already supports mid-session swaps: WalkRoom's `avatar` message
+// (rate-limited, host-allow-listed via multiplayer/src/avatar-url.js) updates
+// the Player schema field every peer's RemotePlayer.setAvatar reacts to.
+
+import { log } from '../shared/log.js';
+
+function el(tag, attrs = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k === 'dataset') Object.assign(n.dataset, v);
+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2).toLowerCase(), v);
+ else if (v === true) n.setAttribute(k, '');
+ else n.setAttribute(k, v);
+ }
+ for (const c of [].concat(kids)) {
+ if (c == null || c === false) continue;
+ n.append(c.nodeType ? c : document.createTextNode(String(c)));
+ }
+ return n;
+}
+
+const DEFAULT_AVATAR = '/avatars/default.glb';
+
+export class AvatarSwitcher {
+ /**
+ * @param {HTMLElement} host container the panel renders into
+ * @param {object} h handlers:
+ * current():string the active cc-avatar value (id/url/sentinel)
+ * onPick(value, {label}):Promise<{ok:boolean, reason?:string, downgraded?:boolean}>
+ */
+ constructor(host, h = {}) {
+ this.host = host;
+ this.h = h;
+ this.root = null;
+ this._picking = false;
+ this._mineLoaded = false;
+ this._quickLoaded = false;
+ }
+
+ mount() {
+ if (!this.root) this._build();
+ if (!this.root.isConnected) this.host.appendChild(this.root);
+ if (!this._mineLoaded) this._renderMine();
+ if (!this._quickLoaded) this._renderQuick();
+ this._markActive(this.h.current?.() || '');
+ }
+
+ unmount() {
+ this.root?.remove();
+ }
+
+ dispose() {
+ this.unmount();
+ this._creator?.dispose?.();
+ this._creator = null;
+ this.root = null;
+ }
+
+ // ---------------------------------------------------------------- build
+ _build() {
+ this.status = el('div', { class: 'cc-avsw-status', role: 'status', 'aria-live': 'polite', hidden: true });
+
+ this.mineGrid = el('div', { class: 'cc-avsw-grid', role: 'list', 'aria-label': 'Your saved avatars' });
+ this.quickGrid = el('div', { class: 'cc-avsw-grid', role: 'list', 'aria-label': 'Quick picks' });
+
+ this.pasteInput = el('input', {
+ type: 'text', class: 'cc-avsw-paste-input',
+ placeholder: 'Paste a .glb / .vrm URL or avatar id',
+ 'aria-label': 'Avatar URL or id',
+ onkeydown: (e) => { if (e.key === 'Enter') { e.preventDefault(); this._pasteApply(); } e.stopPropagation(); },
+ });
+ const pasteBtn = el('button', {
+ type: 'button', class: 'cc-avsw-btn', text: 'Wear it',
+ onclick: () => this._pasteApply(),
+ });
+
+ this.uploadFile = el('input', {
+ type: 'file', accept: '.glb,.vrm,model/gltf-binary', class: 'cc-avsw-file',
+ 'aria-label': 'Upload a .glb or .vrm avatar',
+ onchange: (e) => { const f = e.target.files?.[0]; if (f) this._upload(f); e.target.value = ''; },
+ });
+ const uploadBtn = el('label', { class: 'cc-avsw-btn cc-avsw-upload', title: 'Upload a .glb or .vrm from your device' }, [
+ el('span', { 'aria-hidden': 'true', text: '⬆' }), ' Upload', this.uploadFile,
+ ]);
+ const galleryBtn = el('button', {
+ type: 'button', class: 'cc-avsw-btn', title: 'Browse your avatars and the public gallery with live previews',
+ onclick: (e) => this._openGallery(e.currentTarget),
+ }, [el('span', { 'aria-hidden': 'true', text: '🖼' }), ' Gallery']);
+ const createBtn = el('button', {
+ type: 'button', class: 'cc-avsw-btn cc-avsw-create', title: 'Create a brand-new avatar, from scratch or from a photo',
+ onclick: (e) => this._openCreator(e.currentTarget),
+ }, [el('span', { 'aria-hidden': 'true', text: '✦' }), ' Create new']);
+
+ this.root = el('div', { class: 'cc-avsw' }, [
+ this.status,
+ el('div', { class: 'cc-avsw-section' }, [
+ el('div', { class: 'cc-avsw-title', text: 'Your avatars' }),
+ this.mineGrid,
+ ]),
+ el('div', { class: 'cc-avsw-section' }, [
+ el('div', { class: 'cc-avsw-title', text: 'Quick picks' }),
+ this.quickGrid,
+ ]),
+ el('div', { class: 'cc-avsw-section' }, [
+ el('div', { class: 'cc-avsw-title', text: 'Bring your own' }),
+ el('div', { class: 'cc-avsw-row' }, [this.pasteInput, pasteBtn]),
+ el('div', { class: 'cc-avsw-actions' }, [createBtn, galleryBtn, uploadBtn]),
+ ]),
+ ]);
+ }
+
+ _setStatus(state, msg) {
+ if (!this.status) return;
+ this.status.hidden = false;
+ this.status.setAttribute('data-state', state);
+ this.status.textContent = msg;
+ clearTimeout(this._statusTimer);
+ if (state === 'done' || state === 'error') {
+ this._statusTimer = setTimeout(() => { if (this.status) this.status.hidden = true; }, state === 'done' ? 4000 : 8000);
+ }
+ }
+
+ // One chip per wearable option. `value` is what the scene resolves (id, URL,
+ // or the guest sentinel); the thumbnail falls back to a glyph when the poster
+ // is missing or dead so the chip is never an empty square.
+ _chip({ value, label, thumb, glyph }) {
+ const face = thumb
+ ? el('img', {
+ class: 'cc-avsw-thumb', src: thumb, alt: '', loading: 'lazy',
+ onerror: (e) => { e.target.replaceWith(el('span', { class: 'cc-avsw-glyph', 'aria-hidden': 'true', text: glyph || '🧑' })); },
+ })
+ : el('span', { class: 'cc-avsw-glyph', 'aria-hidden': 'true', text: glyph || '🧑' });
+ const btn = el('button', {
+ type: 'button', class: 'cc-avsw-chip', role: 'listitem',
+ title: label, 'aria-label': `Wear ${label}`,
+ onclick: (e) => this._pick(value, label, e.currentTarget),
+ }, [face, el('span', { class: 'cc-avsw-chip-name', text: label })]);
+ btn.dataset.value = value;
+ return btn;
+ }
+
+ _markActive(value) {
+ if (!this.root) return;
+ for (const chip of this.root.querySelectorAll('.cc-avsw-chip')) {
+ chip.classList.toggle('is-active', !!value && chip.dataset.value === value);
+ }
+ }
+
+ // ---------------------------------------------------------------- pick
+ async _pick(value, label, btn) {
+ const v = (value || '').trim();
+ if (!v || this._picking) return;
+ this._picking = true;
+ this.root?.classList.add('is-busy');
+ btn?.classList.add('is-busy');
+ this._setStatus('working', `Switching to ${label}…`);
+ try {
+ const res = await this.h.onPick?.(v, { label });
+ if (res?.ok) {
+ this._markActive(v);
+ this._setStatus('done', res.downgraded
+ ? `Wearing a lighter stand-in for ${label} on this device.`
+ : `You're now wearing ${label}.`);
+ } else if (res?.reason === 'load-failed') {
+ this._setStatus('error', `Couldn't load ${label}, so your current avatar is unchanged.`);
+ } else if (res?.reason !== 'stale') {
+ this._setStatus('error', 'That switch didn’t go through. Try again.');
+ }
+ } catch (err) {
+ log.warn('[avatar-switcher] pick failed:', err?.message);
+ this._setStatus('error', 'Avatar switch failed. Try again.');
+ } finally {
+ this._picking = false;
+ btn?.classList.remove('is-busy');
+ this.root?.classList.remove('is-busy');
+ }
+ }
+
+ _pasteApply() {
+ const v = this.pasteInput?.value.trim();
+ if (!v) { this._setStatus('error', 'Paste a model URL or avatar id first.'); return; }
+ this._pick(v, 'your pasted avatar');
+ }
+
+ // ---------------------------------------------------------------- lists
+ async _renderMine() {
+ this._mineLoaded = true;
+ this.mineGrid.textContent = '';
+ for (let i = 0; i < 3; i++) this.mineGrid.appendChild(el('div', { class: 'cc-avsw-chip cc-avsw-skel', 'aria-hidden': 'true' }));
+ let block = null;
+ try {
+ const r = await fetch('/api/avatars/mine?limit=60', { credentials: 'include', headers: { accept: 'application/json' } });
+ if (r.status === 401) {
+ block = el('div', { class: 'cc-avsw-note' }, [
+ el('a', { href: '/login?next=/play', class: 'cc-avsw-link', text: 'Sign in' }),
+ ' to wear the avatars saved to your three.ws account.',
+ ]);
+ } else if (!r.ok) {
+ throw new Error(`HTTP ${r.status}`);
+ } else {
+ const data = await r.json();
+ const avatars = Array.isArray(data?.avatars) ? data.avatars : [];
+ if (!avatars.length) {
+ block = el('div', { class: 'cc-avsw-note' }, [
+ 'No saved avatars yet. ',
+ el('a', { href: '/create', target: '_blank', rel: 'noopener', class: 'cc-avsw-link', text: 'Create one' }),
+ ' or use Create new below.',
+ ]);
+ } else {
+ this.mineGrid.textContent = '';
+ for (const a of avatars) {
+ this.mineGrid.appendChild(this._chip({
+ value: a.id, label: a.name || 'Untitled avatar', thumb: a.thumb_url, glyph: '🧑',
+ }));
+ }
+ this._markActive(this.h.current?.() || '');
+ return;
+ }
+ }
+ } catch (err) {
+ log.warn('[avatar-switcher] failed to load saved avatars:', err?.message);
+ block = el('div', { class: 'cc-avsw-note' }, [
+ 'Couldn’t load your avatars. ',
+ el('button', {
+ type: 'button', class: 'cc-avsw-link cc-avsw-retry', text: 'Retry',
+ onclick: () => this._renderMine(),
+ }),
+ ]);
+ }
+ this.mineGrid.textContent = '';
+ this.mineGrid.appendChild(block);
+ }
+
+ async _renderQuick() {
+ this._quickLoaded = true;
+ this.quickGrid.textContent = '';
+ this.quickGrid.appendChild(this._chip({ value: DEFAULT_AVATAR, label: 'Default', glyph: '🧍' }));
+ try {
+ const r = await fetch('/api/explore?source=avatar&only3d=1&limit=9', { headers: { accept: 'application/json' } });
+ if (!r.ok) return;
+ const data = await r.json();
+ for (const it of (data.items || [])) {
+ if (!it.glbUrl) continue;
+ this.quickGrid.appendChild(this._chip({
+ value: it.glbUrl, label: it.name || 'Avatar', thumb: it.image, glyph: '🙂',
+ }));
+ }
+ this._markActive(this.h.current?.() || '');
+ } catch { /* offline: the default chip still works */ }
+ }
+
+ // ---------------------------------------------------------------- bring your own
+ async _upload(file) {
+ if (this._picking) return;
+ this._setStatus('working', 'Checking your model…');
+ try {
+ const { validateGlb, uploadGlb } = await import('./avatar-upload.js');
+ await validateGlb(file);
+ this._setStatus('working', 'Uploading… 0%');
+ const url = await uploadGlb(file, (p) => this._setStatus('working', `Uploading… ${Math.round(p * 100)}%`));
+ await this._pick(url, file.name || 'your upload');
+ } catch (err) {
+ this._setStatus('error', err?.message || 'Upload failed.');
+ }
+ }
+
+ async _openGallery(btn) {
+ btn?.classList.add('is-busy');
+ try {
+ const { openAvatarPicker } = await import('../avatar-gallery-picker.js');
+ const a = await openAvatarPicker({
+ source: 'both', showModes: false,
+ title: 'Choose your avatar', ctaLabel: 'Wear this avatar',
+ });
+ if (a) await this._pick(a.id || a.model_url, a.name || 'that avatar');
+ } catch (err) {
+ log.warn('[avatar-switcher] gallery picker failed:', err?.message);
+ this._setStatus('error', 'Couldn’t open the gallery. Try again.');
+ } finally {
+ btn?.classList.remove('is-busy');
+ }
+ }
+
+ // The full in-app creator (design from scratch or from a photo). The exported
+ // GLB is staged locally via playAs (guest sentinel), so the scene shows it
+ // instantly from the local blob and uploads it in the background before
+ // broadcasting the public URL to peers, the same flow the lobby uses.
+ async _openCreator(btn) {
+ btn?.classList.add('is-busy');
+ try {
+ const [{ AvatarCreator }, { playAs, GUEST_SENTINEL }] = await Promise.all([
+ import('../avatar-creator.js'),
+ import('./play-handoff.js'),
+ ]);
+ this._creator?.dispose?.();
+ this._creator = new AvatarCreator(document.body, async (blob, meta = {}) => {
+ try {
+ await playAs({ blob, source: meta.provider || 'three-ws-create', dest: null });
+ await this._pick(GUEST_SENTINEL, 'your new avatar');
+ } catch (err) {
+ log.warn('[avatar-switcher] could not adopt created avatar:', err?.message);
+ this._setStatus('error', 'Couldn’t save your new avatar. Please try again.');
+ }
+ });
+ await this._creator.openDefaultEditor();
+ } catch (err) {
+ log.warn('[avatar-switcher] avatar creator failed to open:', err?.message);
+ this._setStatus('error', 'Couldn’t open the avatar creator. Try uploading a .glb instead.');
+ } finally {
+ btn?.classList.remove('is-busy');
+ }
+ }
+}
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index d0aa4df31..78a0a8a74 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -17,6 +17,7 @@ import { COMPOSITE_PIECES } from './build-voxels.js';
import { PROP_CATALOG, GALLERY_PROP_PREFIX, registerGalleryProp } from './world-objects.js';
import { makeIntroReopener } from './play-intro.js';
import { getPowerSaver, setPowerSaver, onPowerSaverChange } from '../shared/frame-governor.js';
+import { getMe } from '../account.js';
import { log } from '../shared/log.js';
// localStorage throws in private mode and in third-party iframe contexts where
@@ -86,6 +87,21 @@ function _ewSectorPath(cx, cy, ir, or_, s, e) {
}
// ── end emote wheel helpers ──────────────────────────────────────────────────
+// Wrap a URL for use inside a CSS `url(...)` value without letting it break out
+// of the declaration. A coin's image is network-controlled (pump.fun metadata,
+// or the ?image= deep-link param); proxiedImageURL only encodes http/ipfs/ar
+// URLs, so any other value reaches us raw. A crafted string like
+// `x");position:fixed;inset:0;background:url(//evil)` would otherwise escape the
+// declaration and paint a full-screen overlay for everyone in the lobby. We
+// refuse dangerous schemes and percent-encode the characters that could close
+// the url() or the rule, so the worst a hostile value can do is fail to load.
+function cssBgImage(url) {
+ if (!url || typeof url !== 'string') return '';
+ if (/^\s*(javascript|vbscript|data\s*:\s*text\/html)/i.test(url)) return '';
+ const safe = url.replace(/["'()\\\s<>]/g, (c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'));
+ return `background-image:url("${safe}")`;
+}
+
function el(tag, props = {}, kids = []) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(props)) {
@@ -146,6 +162,33 @@ export class CommunityUI {
this._buildHud();
this._buildStructures();
this._buildPropPalette();
+ this._hydrateAccountIdentity();
+ }
+
+ // Signed-in identity (W10): a logged-in player enters the world AS their
+ // three.ws account — default the nameplate to their display name and show
+ // the @handle peers will see (and can follow/DM) beside the name field.
+ // Anonymous visitors keep the plain guest field; getMe() resolves null.
+ async _hydrateAccountIdentity() {
+ let me = null;
+ try { me = await getMe(); } catch { return; }
+ if (!me) return;
+ this.me = me;
+ if (!this.nameInput.value.trim()) {
+ const n = String(me.display_name || me.username || '').trim().slice(0, 24);
+ if (n) { this.nameInput.value = n; lsSet('cc-name', n); }
+ }
+ if (me.username && this.nameRow && !this._identityChip) {
+ this._identityChip = el('a', {
+ class: 'cc-identity-chip',
+ href: `/u/${encodeURIComponent(me.username)}`,
+ target: '_blank',
+ rel: 'noopener',
+ title: 'Signed in — players you meet can open your profile, follow you, and message you',
+ text: `@${me.username}`,
+ });
+ this.nameRow.appendChild(this._identityChip);
+ }
}
// ---------------------------------------------------------------- lobby
@@ -236,7 +279,7 @@ export class CommunityUI {
makeIntroReopener(() => this.h.onDropIn?.()),
]),
this.avatarBar = el('div', { class: 'cc-avatar-bar' }, [
- el('div', { class: 'cc-name-row' }, [
+ this.nameRow = el('div', { class: 'cc-name-row' }, [
el('label', { class: 'cc-name-label', for: 'cc-name-input', text: 'Your name' }),
this.nameInput,
]),
@@ -929,7 +972,7 @@ export class CommunityUI {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.h.onEnter(c, ''); }
},
}, [
- el('div', { class: 'cc-card-img', style: c.image ? `background-image:url("${c.image}")` : '' }, [liveBadge, holdersBadge]),
+ el('div', { class: 'cc-card-img', style: cssBgImage(c.image) }, [liveBadge, holdersBadge]),
el('div', { class: 'cc-card-body' }, [
el('div', { class: 'cc-card-name', text: c.name || 'Unnamed coin' }),
el('div', { class: 'cc-card-meta' }, [
@@ -1031,6 +1074,25 @@ export class CommunityUI {
this.friendsBtn.classList.toggle('is-active', !!open);
}
+ // Avatar-switcher drawer state: keeps the HUD button's aria-expanded honest
+ // and lets CSS mark it active while the panel is up.
+ setAvatarPanelOpen(open) {
+ if (!this.avatarBtn) return;
+ this.avatarBtn.setAttribute('aria-expanded', String(!!open));
+ this.avatarBtn.classList.toggle('is-active', !!open);
+ }
+
+ // Mirror an avatar picked from the in-world switcher into the lobby bar's
+ // state (chip highlight + custom field) WITHOUT firing onAvatarChange: the
+ // scene already rebuilt the rig and broadcast the change, and re-firing the
+ // handler would send it twice.
+ reflectAvatar(value) {
+ this.avatar = value || DEFAULT_AVATAR;
+ lsSet('cc-avatar', this.avatar);
+ for (const chip of this.presetRow.children) chip.classList.toggle('cc-on', chip._url === this.avatar);
+ this.customInput.value = (this.avatar === DEFAULT_AVATAR || !/^https?:|^\//.test(this.avatar)) ? '' : this.avatar;
+ }
+
// Creator gate config (R24). A small modal where the coin's creator sets the
// token amount a wallet must hold to enter the Holders world, or removes the
// requirement. `onSave(minTokens)` returns a promise that resolves to the saved
@@ -1179,7 +1241,7 @@ export class CommunityUI {
nodes = [
el('div', { class: 'cc-gate-lock', text: '🛠' }),
title('Holder check is offline'),
- msg(`We can’t verify ${sym} holdings right now. That’s on our side, not yours, and your tokens are unaffected. The open world is live for everyone.`),
+ msg(`We can’t verify holdings of ${sym} right now. That’s on our side, not yours, and your tokens are unaffected. The open world is live for everyone.`),
actions(
btn('Enter the open world', 'general', 'cc-gate-primary'),
btn('Try again', 'recheck'),
@@ -1252,6 +1314,14 @@ export class CommunityUI {
'aria-label': 'Open cosmetics shop',
onclick: () => this.h.onShop?.(),
}, [el('span', { class: 'cc-shop-btn-ico', 'aria-hidden': 'true', text: '🛍️' }), el('span', { class: 'cc-shop-btn-text', text: 'Shop' })]);
+ // Change avatar without leaving the world: opens the in-world switcher
+ // drawer (saved avatars, quick picks, gallery, upload, creator). Touch
+ // equivalent of the V hotkey.
+ this.avatarBtn = el('button', {
+ class: 'cc-avatarbtn', type: 'button', title: 'Change your avatar (V)',
+ 'aria-label': 'Change your avatar', 'aria-expanded': 'false',
+ onclick: () => this.h.onAvatarPanel?.(),
+ }, [el('span', { class: 'cc-avatarbtn-ico', 'aria-hidden': 'true', text: '🧍' }), el('span', { class: 'cc-avatarbtn-text', text: 'Avatar' })]);
// Open the "My Cosmetics" wardrobe — equip owned items, persists across worlds.
this.wardrobeBtn = el('button', {
class: 'cc-wardrobe-btn', type: 'button', title: 'My Cosmetics — equip your owned looks',
@@ -1292,6 +1362,7 @@ export class CommunityUI {
]),
this.friendsBtn,
this.jobsBtn,
+ this.avatarBtn,
this.wardrobeBtn,
this.shopBtn,
this.gateBtn,
@@ -1759,8 +1830,23 @@ export class CommunityUI {
this.propUploadFile,
]);
+ // Forge-in-world: describe an item (or attach a reference photo) and the free
+ // forge lane turns it into a real GLB prop, armed for placement like an upload.
+ // The button toggles an inline form row; generation itself is driven by the
+ // game (h.onForgeProp), which reports progress through the shared status strip.
+ this.forgeBtn = el('button', {
+ class: 'cc-prop-forge-btn', type: 'button', 'aria-expanded': 'false',
+ title: 'Forge a new prop from a text prompt or photo (free)',
+ onclick: () => this.toggleForge(),
+ }, [
+ el('span', { 'aria-hidden': 'true', text: '✨' }),
+ el('span', { class: 'cc-prop-forge-text', text: 'Forge' }),
+ ]);
+ this._buildForgeRow();
+
const head = el('div', { class: 'cc-prop-head' }, [
el('span', { class: 'cc-prop-title', text: 'Props' }),
+ this.forgeBtn,
this.propSearch,
this.propUploadBtn,
this.propRotateBtn,
@@ -1768,10 +1854,88 @@ export class CommunityUI {
this._galleryStatus = el('div', { class: 'cc-prop-gstatus', role: 'status', 'aria-live': 'polite', hidden: true });
- this.propPalette = el('div', { id: 'cc-props', hidden: true, 'aria-label': 'Build props' }, [head, this.propRow, this._galleryStatus]);
+ this.propPalette = el('div', { id: 'cc-props', hidden: true, 'aria-label': 'Build props' }, [head, this.forgeRow, this.propRow, this._galleryStatus]);
document.body.appendChild(this.propPalette);
}
+ // The inline forge form: prompt input, optional reference image, submit. Typing
+ // swallows keys so WASD/build hotkeys never fire mid-sentence, matching the
+ // gallery search box above it.
+ _buildForgeRow() {
+ this._forgeFile = null;
+ this.forgePrompt = el('input', {
+ type: 'text', class: 'cc-forge-prompt', maxlength: '300', autocomplete: 'off',
+ placeholder: 'Describe an item: a glowing campfire, a neon arcade cabinet…',
+ 'aria-label': 'Describe the item to forge',
+ onkeydown: (e) => { e.stopPropagation(); if (e.key === 'Enter') this._submitForge(); if (e.key === 'Escape') this.forgePrompt.blur(); },
+ });
+ this.forgeAttachFile = el('input', {
+ type: 'file', accept: 'image/png,image/jpeg,image/webp', class: 'cc-upload-file',
+ onchange: (e) => { this._setForgeFile(e.target.files?.[0] || null); e.target.value = ''; },
+ });
+ this._forgeAttachText = el('span', { class: 'cc-forge-attach-text', text: 'Photo' });
+ this.forgeAttachBtn = el('label', {
+ class: 'cc-forge-attach', title: 'Attach a reference photo (optional): the forge builds the item in it',
+ }, [el('span', { 'aria-hidden': 'true', text: '📎' }), this._forgeAttachText, this.forgeAttachFile]);
+ this.forgeAttachClear = el('button', {
+ class: 'cc-forge-attach-clear', type: 'button', hidden: true,
+ title: 'Remove the attached photo', 'aria-label': 'Remove the attached photo',
+ onclick: () => this._setForgeFile(null),
+ }, [el('span', { 'aria-hidden': 'true', text: '✕' })]);
+ this.forgeGo = el('button', {
+ class: 'cc-forge-go', type: 'button', title: 'Forge it (free, about 30 seconds)',
+ onclick: () => this._submitForge(),
+ }, ['Forge']);
+ this.forgeRow = el('div', { class: 'cc-forge-row', hidden: true }, [
+ this.forgePrompt, this.forgeAttachBtn, this.forgeAttachClear, this.forgeGo,
+ ]);
+ }
+
+ /** Show/hide the forge form. Pass a boolean to force a state. */
+ toggleForge(force) {
+ if (!this.forgeRow) return;
+ const on = typeof force === 'boolean' ? force : this.forgeRow.hidden;
+ this.forgeRow.hidden = !on;
+ this.forgeBtn.classList.toggle('cc-on', on);
+ this.forgeBtn.setAttribute('aria-expanded', String(on));
+ if (on) this.forgePrompt.focus();
+ }
+
+ _setForgeFile(file) {
+ this._forgeFile = file || null;
+ this._forgeAttachText.textContent = file ? (file.name || 'photo').slice(0, 14) : 'Photo';
+ this.forgeAttachBtn.classList.toggle('cc-on', !!file);
+ this.forgeAttachClear.hidden = !file;
+ }
+
+ _submitForge() {
+ if (this._forgeBusy) return;
+ const prompt = this.forgePrompt.value.trim();
+ const file = this._forgeFile;
+ if (!prompt && !file) {
+ this.setPropUploadStatus('Describe the item in a few words (or attach a photo).', true);
+ this.forgePrompt.focus();
+ return;
+ }
+ this.h.onForgeProp?.({ prompt, file });
+ }
+
+ /** Lock the forge form while a generation is in flight (one at a time). */
+ setForgeBusy(on) {
+ this._forgeBusy = !!on;
+ if (!this.forgeGo) return;
+ this.forgeGo.disabled = this._forgeBusy;
+ this.forgeGo.textContent = this._forgeBusy ? 'Forging…' : 'Forge';
+ this.forgePrompt.disabled = this._forgeBusy;
+ }
+
+ /** Reset the forge form after a successful generation. */
+ clearForgeForm() {
+ if (!this.forgeRow) return;
+ this.forgePrompt.value = '';
+ this._setForgeFile(null);
+ }
+
// One placeable-prop button. Built-in props show their emoji glyph; gallery models
// show a real thumbnail (falling back to the glyph when a model has no render yet).
_propButton(p) {
@@ -2413,6 +2577,16 @@ export class CommunityUI {
_sendChat() {
const text = this.chatInput.value.trim();
if (!text) return;
+ // `/forge <prompt>` forges an item without opening the build palette: the
+ // finished prop lands armed for placement, announced by a local system line.
+ const forge = text.match(/^\/forge\s+(.+)/i);
+ if (forge) {
+ this.chatInput.value = '';
+ const prompt = forge[1].trim();
+ this.addChat({ name: 'Forge', text: `Forging "${prompt.slice(0, 80)}"… it will land in your props when ready.`, mine: true });
+ this.h.onForgeProp?.({ prompt, fromChat: true });
+ return;
+ }
this.h.onChat(text);
this.chatInput.value = '';
}
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index eaf493a6c..4aa1c580d 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -982,6 +982,13 @@ html[data-bg="transparent"] #cc-lobby {
content: attr(data-wanted); margin-left: 5px; color: #ff5a4d;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.9), 0 0 8px rgba(255, 90, 77, 0.6);
}
+/* Verified three.ws account (W10): the @handle beside the display name marks a
+ signed-in platform profile — click opens the real profile card. */
+.cc-label .cc-label-handle {
+ margin-left: 5px; color: #9db8ff; font-weight: 600; font-size: 0.9em;
+ text-shadow: 0 1px 3px rgba(0, 0, 0, 0.9), 0 0 8px rgba(90, 130, 255, 0.45);
+}
+.cc-label.cc-verified:hover .cc-label-handle { color: #c6d6ff; }
.cc-bubble {
background: #fff; color: var(--cc-ink); font-size: 13px; font-weight: 600; text-align: center;
padding: 7px 12px; border-radius: var(--cc-radius); max-width: 220px; white-space: normal;
@@ -1131,6 +1138,13 @@ html[data-bg="transparent"] #cc-lobby {
}
.cc-name-input::placeholder { color: var(--cc-dim); font-weight: 400; }
.cc-name-input:focus { border-color: var(--cc-edge-hi); }
+/* Signed-in identity chip (W10): the @handle peers will see beside your name. */
+.cc-identity-chip {
+ flex: 0 0 auto; font-size: 12px; font-weight: 650; padding: 4px 10px; border-radius: 999px;
+ color: #9db8ff; text-decoration: none; border: 1px solid rgba(120, 150, 255, 0.35);
+ background: rgba(90, 130, 255, 0.1); transition: background 0.15s ease, color 0.15s ease;
+}
+.cc-identity-chip:hover, .cc-identity-chip:focus-visible { background: rgba(90, 130, 255, 0.22); color: #c6d6ff; }
/* Transient toast (avatar fell back, buy panel unavailable, …). */
#cc-toast {
@@ -1670,11 +1684,77 @@ html[data-bg="transparent"] #cc-lobby {
.cc-prop-gstatus.cc-err { color: #ff8a8a; cursor: pointer; }
.cc-prop-gstatus.cc-err:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }
+/* Forge-in-world: the toggle sits with the palette head controls; the form row
+ slides in between the head and the prop row. */
+.cc-prop-forge-btn {
+ display: inline-flex; align-items: center; gap: 5px;
+ height: 30px; padding: 0 10px; border-radius: var(--cc-radius-sm);
+ border: 1px solid rgba(102, 255, 140, 0.45); background: var(--cc-panel); color: var(--cc-text);
+ font-size: 11.5px; font-weight: 600; white-space: nowrap; cursor: pointer;
+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
+ transition: background 0.12s, border-color 0.12s, transform 0.08s;
+}
+.cc-prop-forge-btn:hover { background: rgba(102, 255, 140, 0.12); border-color: #66ff8c; }
+.cc-prop-forge-btn:active { transform: translateY(1px); }
+.cc-prop-forge-btn:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }
+.cc-prop-forge-btn.cc-on { background: rgba(102, 255, 140, 0.16); border-color: #66ff8c; }
+.cc-forge-row {
+ display: flex; align-items: center; gap: 6px; padding: 7px;
+ background: var(--cc-panel); border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);
+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
+ animation: cc-build-in 0.16s ease;
+}
+.cc-forge-row[hidden] { display: none; }
+.cc-forge-prompt {
+ flex: 1 1 auto; min-width: 0; height: 30px; padding: 0 10px;
+ border-radius: var(--cc-radius-sm); border: 1px solid var(--cc-edge);
+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text);
+ font: inherit; font-size: 12px;
+ transition: background 0.12s, border-color 0.12s;
+}
+.cc-forge-prompt::placeholder { color: var(--cc-dim); }
+.cc-forge-prompt:focus { outline: none; border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); }
+.cc-forge-prompt:disabled { opacity: 0.55; }
+.cc-forge-attach {
+ display: inline-flex; align-items: center; gap: 4px; flex: 0 0 auto;
+ height: 30px; padding: 0 9px; border-radius: var(--cc-radius-sm);
+ border: 1px solid var(--cc-edge); background: rgba(255, 255, 255, 0.04); color: var(--cc-dim);
+ font-size: 11px; font-weight: 600; white-space: nowrap; cursor: pointer;
+ transition: background 0.12s, border-color 0.12s, color 0.12s;
+}
+.cc-forge-attach:hover { background: rgba(255, 255, 255, 0.1); color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.cc-forge-attach:focus-within { outline: 2px solid #66ff8c; outline-offset: 2px; }
+.cc-forge-attach.cc-on { color: var(--cc-text); border-color: rgba(102, 255, 140, 0.45); }
+.cc-forge-attach-text { max-width: 96px; overflow: hidden; text-overflow: ellipsis; }
+.cc-forge-attach-clear {
+ display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto;
+ width: 24px; height: 30px; border-radius: var(--cc-radius-sm);
+ border: 1px solid var(--cc-edge); background: transparent; color: var(--cc-dim);
+ font-size: 11px; cursor: pointer;
+ transition: background 0.12s, color 0.12s, border-color 0.12s;
+}
+.cc-forge-attach-clear:hover { background: rgba(255, 138, 138, 0.12); color: #ff8a8a; border-color: #ff8a8a; }
+.cc-forge-attach-clear:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }
+.cc-forge-attach-clear[hidden] { display: none; }
+.cc-forge-go {
+ flex: 0 0 auto; height: 30px; padding: 0 14px; border-radius: var(--cc-radius-sm);
+ border: 1px solid #66ff8c; background: rgba(102, 255, 140, 0.14); color: var(--cc-text);
+ font: inherit; font-size: 12px; font-weight: 700; cursor: pointer;
+ transition: background 0.12s, transform 0.08s, opacity 0.12s;
+}
+.cc-forge-go:hover { background: rgba(102, 255, 140, 0.24); }
+.cc-forge-go:active { transform: translateY(1px); }
+.cc-forge-go:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }
+.cc-forge-go:disabled { opacity: 0.55; cursor: progress; }
+
@media (pointer: coarse) { #cc-props { bottom: 150px; } }
@media (max-width: 560px) {
#cc-props { bottom: 156px; width: 96vw; }
.cc-prop { min-width: 48px; }
.cc-prop-search { max-width: none; }
+ .cc-prop-forge-text { display: none; }
+ .cc-forge-attach-text { display: none; }
}
/* ---------------- share-a-build sheet (R20) ---------------- */
@@ -1977,6 +2057,25 @@ html[data-bg="transparent"] #cc-lobby {
.cc-wardrobe-btn-ico { font-size: 14px; line-height: 1; }
@media (max-width: 480px) { .cc-wardrobe-btn-text { display: none; } }
+/* "Avatar" switcher button — mirrors the shop/wardrobe buttons; is-active marks
+ the drawer open (aria-expanded is set alongside by setAvatarPanelOpen). */
+.cc-avatarbtn {
+ flex: none; pointer-events: auto;
+ display: inline-flex; align-items: center; gap: 7px;
+ margin-left: 4px; padding: 9px 13px;
+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ font-weight: 700; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase;
+ cursor: pointer; white-space: nowrap; appearance: none; -webkit-appearance: none; font-family: inherit;
+ transition: transform 0.12s ease, border-color 0.12s ease, background 0.12s ease;
+}
+.cc-avatarbtn:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); transform: translateY(-1px); }
+.cc-avatarbtn:active { transform: translateY(1px); }
+.cc-avatarbtn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-avatarbtn.is-active { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.1); }
+.cc-avatarbtn-ico { font-size: 14px; line-height: 1; }
+@media (max-width: 480px) { .cc-avatarbtn-text { display: none; } }
+
/* "Jobs" board button (W08) — mirrors the shop/wardrobe buttons. */
.cc-jobs-btn {
flex: none; pointer-events: auto;
@@ -2083,6 +2182,109 @@ html[data-bg="transparent"] #cc-lobby {
border-top: 1px solid var(--cc-edge);
}
+/* In-world avatar switcher panel. Reuses the friends-panel drawer frame
+ (.cc-avatar-panel rides the same .cc-friends-panel classes); everything
+ below styles the panel's own content (avatar-switcher.js). */
+.cc-avsw-body { overflow-y: auto; }
+.cc-avsw { display: flex; flex-direction: column; gap: 16px; padding: 12px 14px 16px; }
+.cc-avsw.is-busy { cursor: progress; }
+
+.cc-avsw-status {
+ flex: none; padding: 8px 10px; border-radius: var(--cc-radius);
+ font-size: 12px; line-height: 1.4;
+ border: 1px solid var(--cc-edge); background: rgba(255, 255, 255, 0.04);
+ color: var(--cc-text);
+}
+.cc-avsw-status[data-state="working"]::before {
+ content: ""; display: inline-block; width: 9px; height: 9px; margin-right: 7px;
+ border: 2px solid var(--cc-dim); border-top-color: transparent; border-radius: 50%;
+ animation: cc-avsw-spin 0.8s linear infinite; vertical-align: -1px;
+}
+@keyframes cc-avsw-spin { to { transform: rotate(360deg); } }
+@media (prefers-reduced-motion: reduce) { .cc-avsw-status[data-state="working"]::before { animation: none; } }
+.cc-avsw-status[data-state="done"] { border-color: rgba(126, 231, 135, 0.4); }
+.cc-avsw-status[data-state="error"] { border-color: rgba(255, 107, 107, 0.5); color: #ffb3b3; }
+
+.cc-avsw-section { display: flex; flex-direction: column; gap: 8px; }
+.cc-avsw-title {
+ font-size: 11px; font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase;
+ color: var(--cc-dim);
+}
+
+.cc-avsw-grid {
+ display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
+}
+.cc-avsw-chip {
+ appearance: none; -webkit-appearance: none; font-family: inherit;
+ display: flex; flex-direction: column; align-items: center; gap: 6px;
+ padding: 8px 6px; border-radius: var(--cc-radius);
+ background: rgba(255, 255, 255, 0.03); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); cursor: pointer;
+ transition: transform 0.12s ease, border-color 0.12s ease, background 0.12s ease;
+}
+.cc-avsw-chip:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.07); transform: translateY(-1px); }
+.cc-avsw-chip:active { transform: translateY(1px); }
+.cc-avsw-chip:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-avsw-chip.is-active { border-color: var(--cc-accent, #7ee787); background: rgba(255, 255, 255, 0.08); }
+.cc-avsw-chip.is-busy { opacity: 0.6; cursor: progress; }
+.cc-avsw-thumb {
+ width: 100%; aspect-ratio: 1; max-width: 84px; object-fit: cover;
+ border-radius: calc(var(--cc-radius) - 3px); background: rgba(255, 255, 255, 0.05);
+}
+.cc-avsw-glyph {
+ width: 100%; aspect-ratio: 1; max-width: 84px;
+ display: grid; place-items: center; font-size: 26px;
+ border-radius: calc(var(--cc-radius) - 3px); background: rgba(255, 255, 255, 0.05);
+}
+.cc-avsw-chip-name {
+ max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ font-size: 11px; font-weight: 600; letter-spacing: 0.01em;
+}
+.cc-avsw-skel {
+ pointer-events: none; min-height: 108px;
+ background: linear-gradient(100deg, rgba(255, 255, 255, 0.03) 40%, rgba(255, 255, 255, 0.08) 50%, rgba(255, 255, 255, 0.03) 60%);
+ background-size: 200% 100%;
+ animation: cc-avsw-shimmer 1.2s linear infinite;
+}
+@keyframes cc-avsw-shimmer { to { background-position: -200% 0; } }
+@media (prefers-reduced-motion: reduce) { .cc-avsw-skel { animation: none; } }
+
+.cc-avsw-note { grid-column: 1 / -1; font-size: 12px; line-height: 1.5; color: var(--cc-dim); }
+.cc-avsw-link {
+ appearance: none; -webkit-appearance: none; font-family: inherit; font-size: inherit;
+ background: none; border: none; padding: 0; cursor: pointer;
+ color: var(--cc-text); text-decoration: underline;
+}
+.cc-avsw-link:hover { color: #fff; }
+.cc-avsw-link:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+.cc-avsw-row { display: flex; gap: 8px; }
+.cc-avsw-paste-input {
+ flex: 1 1 auto; min-width: 0; padding: 9px 11px;
+ background: var(--cc-bg2, rgba(255, 255, 255, 0.04)); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ font-size: 13px; font-family: inherit;
+}
+.cc-avsw-paste-input:focus-visible { outline: 2px solid #fff; outline-offset: 1px; }
+.cc-avsw-actions { display: flex; flex-wrap: wrap; gap: 8px; }
+.cc-avsw-btn {
+ appearance: none; -webkit-appearance: none; font-family: inherit;
+ flex: none; display: inline-flex; align-items: center; gap: 6px;
+ padding: 9px 12px; border-radius: var(--cc-radius);
+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text);
+ border: 1px solid var(--cc-edge);
+ font-weight: 700; font-size: 12px; letter-spacing: 0.03em;
+ cursor: pointer; white-space: nowrap;
+ transition: transform 0.12s ease, border-color 0.12s ease, background 0.12s ease;
+}
+.cc-avsw-btn:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); transform: translateY(-1px); }
+.cc-avsw-btn:active { transform: translateY(1px); }
+.cc-avsw-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-avsw-btn.is-busy { opacity: 0.6; cursor: progress; }
+.cc-avsw-upload { position: relative; }
+.cc-avsw-file { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
+.cc-avsw-upload:focus-within { outline: 2px solid #fff; outline-offset: 2px; }
+
/* Creator-only holders-gate button (R24) — mirrors the shop button, accented. */
.cc-gate-cfg-btn {
flex: none; pointer-events: auto;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 2058fcdfc..7b13e69d0 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -55,11 +55,13 @@ import {
import { validatePropModel, uploadPropModel } from './avatar-upload.js';
import { proxiedImageURL } from '../ipfs.js';
import {
- loadManifest, getEmoteDefs, getAllEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,
+ loadManifest, getEmoteDefs, getAllEmoteDefs, resolveAvatarUrl, buildAvatar, releaseAvatar, playEmoteClip,
CLIP_IDLE, CLIP_WALK,
} from './avatar-rig.js';
-import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosmetics } from './play-handoff.js';
+import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosmetics, setPlayAvatar } from './play-handoff.js';
+import { AvatarSwitcher } from './avatar-switcher.js';
import { getPresenceTicket, friendsClient } from '../friends.js';
+import { getMe } from '../account.js';
import { FriendsPanel } from './friends-panel.js';
import { showPlayIntro, makeIntroReopener } from './play-intro.js';
import { applyLoadout } from './cosmetics-loadout.js';
@@ -145,6 +147,10 @@ const RUN_TIMESCALE = 1.7; // speed the walk cycle up so a sprint reads as a run
const JUMP_VELOCITY = 5.5; // m/s upward kick on Space; ~1m apex under GRAVITY
const GRAVITY = 15; // m/s^2 pulling the jumper back down
const REMOTE_LERP = 0.18;
+// Past this ground distance a peer's nameplate is a couple of unreadable pixels,
+// so it isn't projected or written to the DOM at all. Bounds the per-frame label
+// cost by how many people are NEAR you, not by how many are in the world.
+const LABEL_RANGE_M = 60;
const JOY_DEADZONE = 0.12; // swallow tiny stick grazes so the avatar doesn't drift
const UNDO_LIMIT = 50; // how many build actions Ctrl/Cmd+Z can walk back
const LONG_PRESS_MS = 420; // hold-to-break threshold for touch (no right-click there)
@@ -187,16 +193,26 @@ class RemotePlayer {
scene.add(this.rig);
// Public identity riding the server schema — who this peer is (name), the
- // three.ws agent they pilot, and their verified account wallet. These feed
- // the avatar inspector (I / click a nameplate), never invented client-side.
+ // three.ws agent they pilot, their verified account wallet, and their
+ // verified three.ws username (W10, bound server-side from the signed
+ // presence ticket). These feed the avatar inspector (I / click a
+ // nameplate), never invented client-side.
this.name = player.name || 'guest';
this.agent = player.agent || '';
this.account = player.account || '';
+ this.username = player.username || '';
this.onInspect = null; // set by CoinCommunities right after construction
this.label = document.createElement('div');
this.label.className = 'cc-label';
- this.label.textContent = player.name || 'guest';
+ // Two spans instead of bare textContent: a verified player's nameplate
+ // carries their @handle beside the display name, and both voice (::before)
+ // and wanted stars (::after) already occupy the label's pseudo-elements.
+ this._nameEl = document.createElement('span');
+ this._nameEl.className = 'cc-label-name';
+ this._nameEl.textContent = player.name || 'guest';
+ this.label.appendChild(this._nameEl);
+ this._handleEl = null;
// The nameplate doubles as the peer's click target: labels are cheap,
// always visible, and don't need a skinned-mesh raycast. pointer-events is
// off for .cc-label globally (bubbles must never block the look-drag), so
@@ -205,6 +221,7 @@ class RemotePlayer {
this.label.style.cursor = 'pointer';
this.label.title = 'Inspect this player (I)';
this.label.addEventListener('click', (e) => { e.stopPropagation(); this.onInspect?.(); });
+ this._updateHandleBadge();
document.body.appendChild(this.label);
this.bubble = null;
@@ -237,6 +254,9 @@ class RemotePlayer {
try { this.cosmetics?.dispose(); } catch {}
this.cosmetics = null;
this._cosApplied = null;
+ // Deref the shared template + free per-rig materials BEFORE the sweep;
+ // rig.clear() alone leaks the old model's GPU buffers on every swap.
+ releaseAvatar(this.rig);
this.rig.clear();
this.anim = new AnimationManager();
// Tag this load so a slower in-flight GLB can't attach to the rig after the
@@ -319,11 +339,35 @@ class RemotePlayer {
this.label.classList.remove('cc-wanted');
}
}
+ // Verified three.ws identity on the nameplate (W10): the @handle beside the
+ // display name marks a signed-in platform account — the signal that clicking
+ // opens a real profile you can follow and message, not just a guest card.
+ _updateHandleBadge() {
+ if (this.username) {
+ if (!this._handleEl) {
+ this._handleEl = document.createElement('span');
+ this._handleEl.className = 'cc-label-handle';
+ this.label.appendChild(this._handleEl);
+ }
+ this._handleEl.textContent = `@${this.username}`;
+ this.label.classList.add('cc-verified');
+ this.label.title = `View @${this.username}'s profile (I)`;
+ } else {
+ this._handleEl?.remove();
+ this._handleEl = null;
+ this.label.classList.remove('cc-verified');
+ this.label.title = 'Inspect this player (I)';
+ }
+ }
apply(player) {
this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z; this.targetYaw = player.yaw;
- if (player.name) { this.name = player.name; this.label.textContent = player.name; }
+ if (player.name) { this.name = player.name; this._nameEl.textContent = player.name; }
if (player.agent !== undefined) this.agent = player.agent || '';
if (player.account !== undefined) this.account = player.account || '';
+ if (player.username !== undefined && (player.username || '') !== this.username) {
+ this.username = player.username || '';
+ this._updateHandleBadge();
+ }
if (player.voice !== undefined && !!player.voice !== this.voice) {
this.voice = !!player.voice;
this.label.classList.toggle('cc-invoice', this.voice);
@@ -383,6 +427,10 @@ class RemotePlayer {
try { this.cosmetics?.dispose(); } catch {}
this._removeGlowRing();
this._removeItLabel();
+ // Free this peer's share of the avatar model before dropping the rig; a
+ // join→leave churn cycle used to keep every departed peer's geometry and
+ // textures on the GPU for the rest of the session.
+ releaseAvatar(this.rig);
this.scene.remove(this.rig);
this.label.remove();
this.bubble?.remove();
@@ -502,6 +550,8 @@ export class CoinCommunities {
onBuy: () => this._openBuy(),
onShop: () => this._toggleShop(),
onWardrobe: () => this._toggleWardrobe(),
+ // In-world avatar switcher: change your look without leaving the world.
+ onAvatarPanel: () => this._toggleAvatarPanel(),
onJobs: () => this._toggleQuests(),
// Friends panel (W09) — presence + DMs across every coin world.
onFriends: () => this._toggleFriends(),
@@ -521,6 +571,8 @@ export class CoinCommunities {
onRotateProp: () => this._rotateProp(),
// P3.3: bring your own prop: validate, upload, arm it for placement.
onUploadProp: (file) => this._uploadProp(file),
+ // Forge-in-world: generate a brand-new prop from a prompt or photo.
+ onForgeProp: (req) => this._forgeProp(req),
onShareBuild: () => this._shareBuild(),
onOpenFeatured: () => this._openFeatured(),
onPublishBuild: (meta) => this._publishBuild(meta),
@@ -1245,6 +1297,15 @@ export class CoinCommunities {
// we did, so our local copies are duplicates. Retire them, and hand any props
// built while offline to the room so they become part of the shared world.
this.net.on('synced', () => this._onRoomSynced());
+ // Coming back from a backgrounded tab is the one drop the socket never
+ // reports: iOS Safari suspends the page, the OS reaps the connection, and
+ // no close event is ever delivered — the HUD keeps saying "connected" over
+ // a dead wire. Probe on every return to the foreground (and on the network
+ // coming back) so a two-minute tab switch resyncs like any other drop.
+ this._onResume = () => { if (!document.hidden) this.net?.resume(); };
+ document.addEventListener('visibilitychange', this._onResume);
+ addEventListener('online', this._onResume);
+ addEventListener('focus', this._onResume);
if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));
this.net.on('status', ({ status, error }) => {
@@ -1257,11 +1318,15 @@ export class CoinCommunities {
this._failedNotified = true;
this.ui.toast('Lost the connection to the world — chat and shared builds are paused. Tap the status pill to reconnect.', 'warn');
}
+ // Retries exhausted: this is a single-player world now, so the peers
+ // frozen mid-stride are a lie. Clear them rather than leave a crowd of
+ // statues nobody can talk to. A manual retry re-streams the real roster.
+ if (status === 'failed') { this._markRemotesStale(); this._pruneStaleRemotes(); }
if (status === 'online') this._failedNotified = false;
// Every (re)connect re-streams the server's authoritative build, so wipe
// the local layer first. On a manual retry out of single-player this also
// hands authority back: the solo build gives way to the shared world's.
- if (status === 'connecting') { this.voxels?.clear(); this._undoStack = []; this._syncBudget(); this._resetBuildPerms(); }
+ if (status === 'connecting') { this.voxels?.clear(); this._undoStack = []; this._syncBudget(); this._resetBuildPerms(); this._markRemotesStale(); }
// Building is available with a live server (synced + persisted for
// everyone) and in solo single-player mode (local-only) once multiplayer
// has been given up. The connecting window is the only time it's off, so
@@ -1370,7 +1435,13 @@ export class CoinCommunities {
this.net.on('inv', (delta) => this.playSystems?.applyInv(delta));
this.net.on('xpgain', (g) => this.playSystems?.onXpGain(g));
this.net.on('levelup', (l) => this.playSystems?.onLevelup(l));
- this.net.on('notice', (n) => this.playSystems?.onNotice(n));
+ this.net.on('notice', (n) => {
+ // Live-event announcements (an operator broadcast via the server's
+ // /internal/announce) get the centre-screen treatment; every other
+ // notice stays a play-systems activity toast.
+ if (n?.kind === 'event') return this._onEventAnnounce(n);
+ this.playSystems?.onNotice(n);
+ });
// Friends (W09): live DMs + request/accept pushed by the social hub over this
// world's socket. The FriendsClient owns all social state — it updates its
// threads/unread counts and notifies the panel, open or not, so a DM that
@@ -1775,13 +1846,21 @@ export class CoinCommunities {
clearTimeout(this._passRefreshTimer);
this._passRefreshTimer = null;
if (this.voice) { this.voice.dispose(); this.voice = null; }
+ if (this._onResume) {
+ document.removeEventListener('visibilitychange', this._onResume);
+ removeEventListener('online', this._onResume);
+ removeEventListener('focus', this._onResume);
+ this._onResume = null;
+ }
if (this.net) { this.net.destroy(); this.net = null; }
+ clearTimeout(this._announceTimer);
if (this.vehicles) { this.vehicles.dispose(); this.vehicles = null; }
if (this.combat) { this.combat.dispose(); this.combat = null; }
if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }
if (this.playActivities) { this.playActivities.dispose(); this.playActivities = null; }
if (this.wheelStation) { this.wheelStation.dispose(); this.wheelStation = null; }
this._disposeFriends();
+ this._disposeAvatarPanel();
if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }
if (this.intelKiosk) { this.intelKiosk.dispose(); this.intelKiosk = null; }
if (this.worldLife) { this.worldLife.dispose(); this.worldLife = null; }
@@ -1793,6 +1872,7 @@ export class CoinCommunities {
this._previewPresetId = null; this._previewLayers = false; this._previewItem = null;
for (const [, r] of this.remotes) r.dispose();
this.remotes.clear();
+ this._pendingStale = null;
closeAvatarInspector(); // whoever it showed just left the world with us
if (this._totem) { this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }
if (this._screen) {
@@ -1846,7 +1926,7 @@ export class CoinCommunities {
// King of the Totem (R07): tear down the zone + crown marker and hide the HUD.
this._disposeKingZone();
this.ui.hideKingHud();
- if (this.localRig) { this.scene.remove(this.localRig); this.localRig = null; }
+ if (this.localRig) { releaseAvatar(this.localRig); this.scene.remove(this.localRig); this.localRig = null; }
if (this._nipple) { this._nipple.destroy(); this._nipple = null; }
this.phase = 'lobby';
try { history.replaceState(null, '', location.pathname); } catch { /* non-fatal */ }
@@ -1860,6 +1940,20 @@ export class CoinCommunities {
this._drawScreen(); // keep the jumbotron's LIVE count in sync
}
+ // A live-event announcement from the operator webhook. Always lands as a
+ // toast; when it carries a title, the combat HUD's objective card doubles as
+ // a centre-screen banner for the announcement's duration. The card has no
+ // other writer in /play today, so a timed clear can't stomp anything.
+ _onEventAnnounce(n) {
+ if (n.text) this.ui?.toast?.(n.text, 'info');
+ const hud = this.combat?.hud;
+ if (!n.title || !hud?.setObjective) return;
+ hud.setObjective({ title: n.title, detail: n.detail || n.text || '', color: '#ffd76a' });
+ clearTimeout(this._announceTimer);
+ const holdMs = Math.min(120_000, Number(n.durationMs) > 0 ? Number(n.durationMs) : 12_000);
+ this._announceTimer = setTimeout(() => hud.clearObjective(), holdMs);
+ }
+
// ------------------------------------------------------------- avatar inspector
// I (or clicking a nameplate / avatar) opens the shared inspector on whoever
// you're looking at: identity, reputation, wallet — the same server truth every
@@ -1879,12 +1973,21 @@ export class CoinCommunities {
world: 'play',
agentId: rp.agent,
wallet: rp.account,
+ // Verified three.ws profile (W10): bound server-side from the signed
+ // presence ticket, so the inspector can trust it enough to render the
+ // real profile with follow / message / creations.
+ username: rp.username,
avatarUrl: rp._avatarUrl,
facts: [
...this._worldFacts(),
...(rp.voice ? [{ label: 'Voice', value: 'in voice chat' }] : []),
],
- }, { trigger: trigger || this.canvas });
+ }, {
+ trigger: trigger || this.canvas,
+ // "Message" on an already-friend profile jumps straight into the DM
+ // thread in the in-world friends drawer instead of a page navigation.
+ onOpenDM: (userId) => this._openDmWith(userId),
+ });
}
_inspectNpc(npc) {
openAvatarInspector({
@@ -1894,9 +1997,24 @@ export class CoinCommunities {
facts: [
{ label: 'Role', value: npc.role === 'vendor' ? 'Vendor — real paid service' : npc.role === 'quest' ? 'Quest giver' : 'Townsperson' },
...(npc.def?.prompt ? [{ label: 'Offers', value: npc.def.prompt }] : []),
- { label: 'Talk', value: 'walk up and press E' },
...this._worldFacts(),
],
+ // Talk works from the card at any distance: it runs the NPC's real role
+ // action (conversation, counter, board), the same as walking up for E.
+ actions: [{
+ label: npc.def?.prompt || 'Talk',
+ primary: true,
+ onClick: () => {
+ try {
+ npc.interact({
+ player: this.localPos,
+ ui: this.ui,
+ net: this.net,
+ world: this.worldLife?.world,
+ });
+ } catch { /* role action failed; the NPC stays silent rather than crash */ }
+ },
+ }],
}, { trigger: this.canvas });
}
_inspectSelf() {
@@ -1905,6 +2023,7 @@ export class CoinCommunities {
name: this.net?.name || lsGet('cc-name') || 'You',
world: 'play',
wallet: this.account || '',
+ username: this.me?.username || '',
avatarUrl: this.net?.avatar,
facts: this._worldFacts(),
}, { trigger: this.canvas });
@@ -2181,6 +2300,18 @@ export class CoinCommunities {
this._offFriends = fc.subscribe(() => this._bumpFriendsBadge());
fc.refresh();
this._bumpFriendsBadge();
+ // Own account profile (W10): who *we* are on the platform, for the self
+ // inspector card. getMe() resolves null for anonymous visitors and caches
+ // per page, so this is one cheap request per world entry.
+ getMe().then((u) => { this.me = u || null; }).catch(() => { this.me = null; });
+ }
+
+ // Open the friends drawer directly on a DM thread — the inspector's
+ // "Message" action for a player who is already a friend.
+ _openDmWith(userId) {
+ if (!userId) return;
+ this._openFriends();
+ friendsClient().openThread(userId);
}
_bumpFriendsBadge() {
@@ -2279,6 +2410,145 @@ export class CoinCommunities {
this._friendsOpen = false;
}
+ // ── In-world avatar switcher ──────────────────────────────────────────────
+ // The lobby's avatar bar disappears the moment a world opens, which used to
+ // mean changing your look required leaving (tearing the whole world down).
+ // This drawer (HUD Avatar button / V) hosts AvatarSwitcher; every pick lands
+ // in _applyAvatarSwap below, which rebuilds the local rig in place and
+ // broadcasts the new look so peers re-render it live (the server has accepted
+ // mid-session `avatar` messages all along; no client path ever used it).
+
+ _toggleAvatarPanel() {
+ if (this._avatarPanelOpen) this._closeAvatarPanel();
+ else this._openAvatarPanel();
+ }
+
+ _openAvatarPanel() {
+ if (this._avatarPanelOpen || this.phase !== 'world') return;
+ if (!this._avatarPanelEl) {
+ // Same right-docked drawer frame as the friends panel: head, scrolling
+ // body, hotkey hint. The panel content itself lives in avatar-switcher.js.
+ const close = document.createElement('button');
+ close.className = 'cc-friends-panel-close';
+ close.type = 'button';
+ close.setAttribute('aria-label', 'Close avatar panel');
+ close.textContent = '✕';
+ close.addEventListener('click', () => this._closeAvatarPanel());
+
+ const title = document.createElement('div');
+ title.className = 'cc-friends-panel-title';
+ title.textContent = 'Avatar';
+
+ const head = document.createElement('div');
+ head.className = 'cc-friends-panel-head';
+ head.append(title, close);
+
+ const body = document.createElement('div');
+ body.className = 'cc-friends-panel-body cc-avsw-body';
+
+ const hint = document.createElement('div');
+ hint.className = 'cc-friends-panel-hint';
+ hint.textContent = 'Press V to toggle · Esc to close';
+
+ const root = document.createElement('aside');
+ root.className = 'cc-friends-panel cc-avatar-panel';
+ root.setAttribute('role', 'dialog');
+ root.setAttribute('aria-modal', 'false');
+ root.setAttribute('aria-label', 'Change avatar');
+ root.append(head, body, hint);
+ document.body.appendChild(root);
+
+ this._avatarPanelEl = root;
+ this._avatarPanelCloseEl = close;
+ this._avatarSwitcher = new AvatarSwitcher(body, {
+ // A ?avatar= deep link is what the player is actually wearing this
+ // session, so it wins the active-chip highlight until they pick.
+ current: () => this._urlAvatar || this.ui.getAvatar(),
+ onPick: (value) => this._applyAvatarSwap(value),
+ });
+ }
+ this._avatarSwitcher.mount();
+ this._avatarPanelOpen = true;
+ requestAnimationFrame(() => this._avatarPanelEl?.classList.add('is-open'));
+ this.ui?.setAvatarPanelOpen?.(true);
+ // Release held WASD so the avatar doesn't keep walking while focus moves
+ // into the panel's inputs (same rule as the friends drawer).
+ this.keys.clear();
+ this._avatarPanelCloseEl?.focus();
+ }
+
+ _closeAvatarPanel() {
+ if (!this._avatarPanelOpen) return;
+ this._avatarPanelOpen = false;
+ this._avatarPanelEl?.classList.remove('is-open');
+ this._avatarSwitcher?.unmount();
+ this.ui?.setAvatarPanelOpen?.(false);
+ }
+
+ _disposeAvatarPanel() {
+ this._avatarSwitcher?.dispose();
+ this._avatarSwitcher = null;
+ this._avatarPanelEl?.remove();
+ this._avatarPanelEl = null;
+ this._avatarPanelCloseEl = null;
+ this._avatarPanelOpen = false;
+ }
+
+ // Swap the live local avatar to `input` (avatar id, GLB/VRM URL, or the guest
+ // sentinel for a just-created model) without leaving the world. Builds the
+ // replacement into a staging group first, so the current avatar keeps standing
+ // while the new one downloads and a failed load costs nothing; then tears down
+ // every bone-bound attachment (shop preview, accessory manager, durable
+ // loadout), moves the new model onto the same rig, re-dresses it, persists the
+ // pick, and broadcasts a peer-loadable URL (the server rejects ids and blob:
+ // URLs, so the guest path uploads first, exactly like world entry).
+ async _applyAvatarSwap(input) {
+ const value = (input || '').trim();
+ if (!value) return { ok: false, reason: 'empty' };
+ const rig = this.localRig;
+ if (this.phase !== 'world' || !rig) return { ok: false, reason: 'not-in-world' };
+ const epoch = this._enterEpoch;
+ const token = (this._avatarSwapToken = (this._avatarSwapToken || 0) + 1);
+ const isGuest = value === GUEST_SENTINEL;
+ const url = await resolveAvatarUrl(value);
+ const staging = new Group();
+ const anim = new AnimationManager();
+ const built = await buildAvatar(staging, url, anim, { clips: 'locomotion' });
+ // Stale: a newer swap superseded this one, or the world was left/re-entered
+ // mid-download. Abandon the staged model; the rig it was meant for is gone
+ // or already wearing something newer.
+ const stale = token !== this._avatarSwapToken || epoch !== this._enterEpoch || this.localRig !== rig;
+ if (stale || built.fallback) {
+ releaseAvatar(staging);
+ return stale ? { ok: false, reason: 'stale' } : { ok: false, reason: 'load-failed' };
+ }
+ // Old skeleton teardown. The R21 preview manager and the R23 durable
+ // loadout are both bone-bound to the outgoing model; drop them before the
+ // sweep and re-dress the new skeleton after.
+ this.unequipCosmeticPreview();
+ this._accessoryMgr = null;
+ try { this.localCosmetics?.dispose(); } catch { /* already gone */ }
+ this.localCosmetics = null; this._localCosWire = null;
+ // releaseAvatar removes only what buildAvatar added (model clone or capsule
+ // stand-in) and frees its GPU share; non-avatar rig children (tag glow
+ // ring, "it" label anchor) stay put.
+ releaseAvatar(rig);
+ while (staging.children.length) rig.add(staging.children[0]);
+ this.localAnim = anim;
+ this.localHeight = built.height;
+ this._applyLocalCosmetics(getPlayCosmetics());
+ // An explicit pick outlives a ?avatar= deep link and becomes the saved
+ // avatar every world reads next session; mirror it into the lobby bar so
+ // leaving the world shows the same selection (without re-firing the lobby's
+ // change handler, which would double-broadcast).
+ this._urlAvatar = '';
+ if (!isGuest) setPlayAvatar(value);
+ this.ui.reflectAvatar?.(value);
+ if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));
+ else this.net?.setAvatar(url);
+ return { ok: true, downgraded: !!built.downgraded };
+ }
+
// Open/close the "My Cosmetics" wardrobe panel (R23). Lazy-built on first open;
// each profile echo from the server keeps it fresh so the equipped state always
// reflects the server-authoritative result.
@@ -2715,8 +2985,9 @@ export class CoinCommunities {
// Typing anywhere else (friends DM box, search fields, modal inputs) must
// reach the caret untouched — no hotkeys, no Enter hijack, no Space eaten.
if (isTypingTarget(e.target)) return;
- // Esc closes the friends drawer before anything else claims the key.
+ // Esc closes the friends/avatar drawers before anything else claims the key.
if (e.key === 'Escape' && this._friendsOpen) { e.preventDefault(); this._closeFriends(); return; }
+ if (e.key === 'Escape' && this._avatarPanelOpen) { e.preventDefault(); this._closeAvatarPanel(); return; }
if (e.key === 'Enter' && this.phase === 'world') { e.preventDefault(); this.ui.focusChat(); return; }
// Space jumps on foot; while driving it's the handbrake instead (held,
// released in the keyup handler below) — never scrolls the page either way.
@@ -2790,6 +3061,13 @@ export class CoinCommunities {
this._toggleFriends();
return;
}
+ // V opens the avatar switcher: change your look without leaving the
+ // world. The HUD Avatar button is the touch equivalent.
+ if (k === 'v' && !this.buildHud.active && !e.repeat) {
+ e.preventDefault();
+ this._toggleAvatarPanel();
+ return;
+ }
// Z toggles zen mode (every overlay hidden, just the world). Plain Z
// only: Ctrl/Cmd+Z stays the build-mode undo above.
if (k === 'z' && !this.buildHud.active && !e.ctrlKey && !e.metaKey && !e.repeat) {
@@ -3123,6 +3401,47 @@ export class CoinCommunities {
}
}
+ // Forge-in-world: generate a brand-new prop from a text prompt (or a reference
+ // photo) on the free forge lane, then hand the finished GLB to the exact same
+ // pipeline uploads use: register it in the palette, arm it, and the next click
+ // places it into the shared world (obj:spawn carries the URL, so every player
+ // in the server renders it, and the room persists it like any other build).
+ // Reachable from the palette's Forge form and the chat command `/forge <prompt>`.
+ async _forgeProp({ prompt, file, fromChat } = {}) {
+ if (this._propForging) {
+ this.ui.toast('One forge at a time: yours is still cooking.', 'warn');
+ return;
+ }
+ this._propForging = true;
+ this.ui.setForgeBusy(true);
+ const status = (m) => this.ui.setPropUploadStatus(m || '');
+ try {
+ const out = await forgeWorldProp({ prompt, file, onStatus: status });
+ const def = registerUploadedProp(out.url, { name: out.name });
+ this.ui.addUploadedProp({ id: def.id, name: def.name });
+ // A chat-forged item arrives with the palette closed: open build mode so
+ // the armed ghost (and the palette entry) are actually visible.
+ if (fromChat && this.buildHud && !this.buildHud.active && !this.buildHud.root.hidden) {
+ this.buildHud.setActive(true);
+ }
+ this._pickProp(def.id);
+ this.ui.clearForgeForm();
+ status('');
+ this.ui.toast(`"${out.name}" is forged: click in the world to place it for everyone.`, 'info');
+ if (!out.durable) {
+ this.ui.toast('This model is on temporary storage, so the world may refuse it. If placing fails, forge it again.', 'warn');
+ }
+ } catch (err) {
+ if (err instanceof ForgeError && err.cancelled) return;
+ const message = err instanceof ForgeError ? err.message : 'The forge hit an error. Try again in a moment.';
+ this.ui.setPropUploadStatus(message, true);
+ this.ui.toast(message, 'warn');
+ } finally {
+ this._propForging = false;
+ this.ui.setForgeBusy(false);
+ }
+ }
+
// Rotate the armed prop a quarter-turn and re-preview it in place.
_rotateProp() {
if (!this.buildProp) return;
@@ -3340,6 +3659,9 @@ export class CoinCommunities {
// gets persisted by the authority) instead of stranding in a local doc.
_onRoomSynced() {
this._roomSynced = true;
+ // The roster in this snapshot is now the truth: retire anyone the server
+ // didn't re-announce (they left while we were disconnected).
+ this._pruneStaleRemotes();
this._worldStore?.setArmed(false);
const handoff = [...(this._offlineBuilt?.values() || [])];
this.worldObjects?.dropLocal();
@@ -4075,18 +4397,40 @@ export class CoinCommunities {
_updateLabels() {
const w = this.renderer.domElement.clientWidth, h = this.renderer.domElement.clientHeight;
+ // One scratch vector for the whole sweep, and one style write per node only
+ // when the value actually changed. This runs every frame for every peer, so
+ // at event scale (100 in one plaza) the naive version allocated ~300 Vector3
+ // per frame and re-wrote ~300 transforms whether or not anything moved — a
+ // steady GC drip plus a style recalc on a crowd standing still.
+ const v = this._labelProj || (this._labelProj = new Vector3());
+ const cam = this.camera;
const place = (node, pos, dy) => {
- const v = new Vector3(pos.x, pos.y + dy, pos.z).project(this.camera);
- if (v.z > 1 || v.z < -1) { node.style.display = 'none'; return; }
- node.style.display = '';
- node.style.transform = `translate(-50%, -100%) translate(${(v.x * 0.5 + 0.5) * w}px, ${(-v.y * 0.5 + 0.5) * h}px)`;
+ v.set(pos.x, pos.y + dy, pos.z).project(cam);
+ if (v.z > 1 || v.z < -1) {
+ if (node._ccHidden !== true) { node.style.display = 'none'; node._ccHidden = true; }
+ return;
+ }
+ if (node._ccHidden !== false) { node.style.display = ''; node._ccHidden = false; }
+ const t = `translate(-50%, -100%) translate(${(v.x * 0.5 + 0.5) * w}px, ${(-v.y * 0.5 + 0.5) * h}px)`;
+ if (node._ccT !== t) { node.style.transform = t; node._ccT = t; }
};
+ const hide = (node) => { if (node._ccHidden !== true) { node.style.display = 'none'; node._ccHidden = true; } };
// Anchor name + bubble to each avatar's real head height so they sit just
- // above the head regardless of how tall/short the GLB is.
+ // above the head regardless of how tall/short the GLB is. Past LABEL_RANGE_M
+ // a nameplate is a couple of unreadable pixels, so it is hidden rather than
+ // projected: the cost of a distant crowd stops scaling with its size.
+ const cx = this.localPos.x, cz = this.localPos.z;
for (const [, r] of this.remotes) {
- place(r.label, r.rig.position, r.height + 0.2);
- if (r.bubble) place(r.bubble, r.rig.position, r.height + 0.7);
- if (r._itLabel) place(r._itLabel, r.rig.position, r.height + 0.65);
+ const p = r.rig.position;
+ if ((p.x - cx) ** 2 + (p.z - cz) ** 2 > LABEL_RANGE_M * LABEL_RANGE_M) {
+ hide(r.label);
+ if (r.bubble) hide(r.bubble);
+ if (r._itLabel) hide(r._itLabel);
+ continue;
+ }
+ place(r.label, p, r.height + 0.2);
+ if (r.bubble) place(r.bubble, p, r.height + 0.7);
+ if (r._itLabel) place(r._itLabel, p, r.height + 0.65);
}
if (this._localBubble && this.localRig) place(this._localBubble, this.localPos, (this.localHeight || 1.7) + 0.7);
if (this._localItLabel && this.localRig) place(this._localItLabel, this.localPos, (this.localHeight || 1.7) + 0.65);
diff --git a/src/game/spin-wheel-ui.js b/src/game/spin-wheel-ui.js
index 34462e904..d20beb41b 100644
--- a/src/game/spin-wheel-ui.js
+++ b/src/game/spin-wheel-ui.js
@@ -18,6 +18,7 @@
// Loaded as its own lazy chunk (dynamic import on first wheel interaction) so the
// Solana signing path never weighs down the main /play bundle.
+import './spin-wheel.css';
import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
const NETWORK = 'mainnet';
@@ -89,6 +90,32 @@ class SpinWheel {
];
net.spinInfo();
this._drawWheel();
+ // The documented `error` phase was previously unreachable: if `spinInfo`
+ // never arrives (WS down, dropped packet) the modal sat on "Loading the
+ // wheel…" forever with both buttons dead. Arm a timeout that turns that
+ // dead end into a real, retryable error state.
+ this._loadTimer = setTimeout(() => {
+ if (this.phase === 'loading') this._loadFailed();
+ }, 12_000);
+ }
+
+ // Loading never resolved — show an actionable error with a retry that re-asks
+ // the server, instead of an indefinite spinner.
+ _loadFailed() {
+ this.phase = 'error';
+ this._statusNode(el('span', {}, [
+ "Couldn't reach the wheel. ",
+ el('button', { class: 'kg-spin-retry', type: 'button', onclick: () => this._retryLoad() }, 'Try again'),
+ ]), 'err');
+ }
+
+ _retryLoad() {
+ if (this._closed) return;
+ this.phase = 'loading';
+ this._status('Loading the wheel…', '');
+ if (this._loadTimer) clearTimeout(this._loadTimer);
+ this._loadTimer = setTimeout(() => { if (this.phase === 'loading') this._loadFailed(); }, 12_000);
+ try { this.net.spinInfo(); } catch { this._loadFailed(); }
}
// ----------------------------------------------------------------- view
@@ -135,12 +162,13 @@ class SpinWheel {
// ----------------------------------------------------------- server in
_onInfo(m) {
+ if (this._loadTimer) { clearTimeout(this._loadTimer); this._loadTimer = null; }
this.info = m;
this._infoAt = Date.now(); // anchor the local clock to the server's `now`
this.segments = Array.isArray(m.segments) ? m.segments : [];
this._renderLegend();
this._drawWheel();
- if (this.phase === 'loading') this.phase = 'ready';
+ if (this.phase === 'loading' || this.phase === 'error') { this.phase = 'ready'; this._status('', ''); }
this._sync();
this._startCountdown();
}
@@ -160,6 +188,9 @@ class SpinWheel {
// Land the wheel on the server's chosen segment, then reveal the prize.
if (m.mode === 'free' && Number.isFinite(m.nextFreeSpinAt) && this.info) this.info.nextFreeSpinAt = m.nextFreeSpinAt;
this._pendingResult = m;
+ // Headless (modal already closed mid-settle): skip the flourish and deliver
+ // the result straight to the background pill.
+ if (this._headless) { this._reveal(m); return; }
this._animateTo(m.index, () => this._reveal(m));
}
@@ -183,15 +214,25 @@ class SpinWheel {
this.phase = 'ready';
this._prep = null;
this._sig = null;
+ this._paymentLive = false;
this._status(this._denyText(m), 'err');
+ if (this._headless) { this._pillDone(); return; }
this._sync();
}
_denyText(m) {
- const min = m?.minLevel ?? this.info?.minLevel ?? 5;
+ // The gate is a server constant (spin-wheel.js MIN_AVG_LEVEL) that rides in on
+ // every spinInfo/spinDenied. Never invent a number for it: a wrong minimum in
+ // this copy sends players off to grind for a level they don't need.
+ const min = m?.minLevel ?? this.info?.minLevel ?? null;
switch (m?.reason) {
- case 'level': return `You need an average skill level of ${min} to spin. You're at ${m?.avgLevel ?? this.info?.avgLevel ?? 0}. Train your skills and come back.`;
+ case 'level': return min == null
+ ? `Your skills are still too low to spin. You're at ${m?.avgLevel ?? this.info?.avgLevel ?? 0}. Train them and come back.`
+ : `You need an average skill level of ${min} to spin. You're at ${m?.avgLevel ?? this.info?.avgLevel ?? 0}. Train your skills and come back.`;
case 'not_at_wheel': return 'Step up to the wheel to spin.';
+ // The wheel can award wood, stone or coal, so it refuses to spin unless
+ // there is room for all three. Otherwise a win lands as a few cash.
+ case 'pack_full': return 'Your pack is too full for a prize. Sell or bank some of it at the general store, then spin.';
case 'no_wheel': return 'There is no wheel in this realm.';
case 'cooldown': return 'Your free spin isn’t ready yet.';
case 'token_unavailable': return 'Paid spins are unavailable right now.';
@@ -265,6 +306,11 @@ class SpinWheel {
const conn = new Connection(SOLANA_RPC[NETWORK], 'confirmed');
const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, maxRetries: 3 });
this._sig = sig;
+ // Past this point real money has moved. If the player now closes the modal
+ // (e.g. dismissing the wallet overlay with Escape), the spin must NOT be
+ // abandoned: keep the server subscriptions alive and deliver the outcome in
+ // a background pill. See close().
+ this._paymentLive = true;
const url = solanaTxExplorerUrl(NETWORK, sig);
this._statusNode(el('span', {}, ['Confirming payment — ', el('a', { href: url, target: '_blank', rel: 'noopener', text: 'view ↗' }), '…']), 'ok');
@@ -307,9 +353,11 @@ class SpinWheel {
this._stopSpin();
this.phase = 'ready';
this._prep = null;
+ this._paymentLive = false;
const msg = err?.message || 'Payment failed.';
const friendly = /reject|denied|cancel|user/i.test(msg) ? 'Cancelled in wallet.' : msg;
this._status(friendly, 'err');
+ if (this._headless) { this._pillDone(); return; }
this._sync();
}
@@ -323,12 +371,30 @@ class SpinWheel {
const seg = this.segments?.[m.index];
const label = m.label || seg?.label || 'a prize';
let line = `You won ${label}!`;
- if (m.overflow > 0) line += ` (${m.overflow} waiting in a bag at your feet — your pack was full)`;
+ // A prize that didn't fit was converted to cash server-side (grantSegment's
+ // last-resort fallback). Say so: a silent conversion reads as a lost prize.
+ if (m.lost > 0) {
+ line += m.got > 0
+ ? ` Your pack only held ${m.got} of them, so the rest paid out as ${m.refunded} cash.`
+ : ` Your pack was full, so it paid out as ${m.refunded} cash instead.`;
+ }
this.resultLine.textContent = line;
this.resultLine.dataset.kind = seg ? kindOf(seg) : 'stone';
+ this._paymentLive = false;
+ // Modal was dismissed mid-settle: deliver the win (and the on-chain receipt)
+ // in the background pill, then finish teardown.
+ if (this._headless) {
+ const kids = [line + ' '];
+ if (m.mode === 'paid' && sig) {
+ kids.push(el('a', { href: solanaTxExplorerUrl(NETWORK, sig), target: '_blank', rel: 'noopener', text: 'view on Solscan ↗' }));
+ }
+ this._pill(el('span', {}, kids), 'ok');
+ this._pillDone();
+ return;
+ }
if (m.mode === 'paid' && sig) {
const url = solanaTxExplorerUrl(NETWORK, sig);
- this._statusNode(el('span', {}, ['Paid spin settled on-chain — ', el('a', { href: url, target: '_blank', rel: 'noopener', text: 'view on Solscan ↗' })]), 'ok');
+ this._statusNode(el('span', {}, ['Paid spin settled on-chain. ', el('a', { href: url, target: '_blank', rel: 'noopener', text: 'view on Solscan ↗' })]), 'ok');
} else {
this._status(m.mode === 'paid' ? 'Paid spin settled on-chain.' : 'Free spin used.', 'ok');
}
@@ -439,6 +505,13 @@ class SpinWheel {
el('i', { class: 'kg-spin-dot', style: `background:${(SEG_COLORS[k] || SEG_COLORS.stone).fill}` }),
`${labels[k]} ${Math.round(odds[k])}%`,
])),
+ // These chips group 20 equal wedges by prize kind. The per-wedge table is
+ // published, read from the server's own paytable, so link straight to it
+ // rather than making a player take the summary on trust.
+ el('a', {
+ class: 'kg-spin-paytable', href: '/play/economy#wheel', target: '_blank', rel: 'noopener',
+ text: 'Full paytable ↗', title: 'Every wedge and its real odds, from the server’s own table',
+ }),
);
}
@@ -485,7 +558,9 @@ class SpinWheel {
// Reconcile the whole UI with the current phase + eligibility.
_sync() {
const lvlOk = this._levelOk();
- const min = this.info?.minLevel ?? 5;
+ // The gate level is always the server's own MIN_AVG_LEVEL, carried on spinInfo.
+ // The banner only renders once info has landed, so it never has to guess.
+ const min = this.info?.minLevel;
// Level gate banner — the designed "not eligible" state with a how-to.
if (this.info && !lvlOk) {
this.gate.hidden = false;
@@ -513,19 +588,73 @@ class SpinWheel {
}
_setBusy(on, text) { if (text != null) this._status(text, ''); }
- _status(text, kind) { this.status.textContent = text || ''; this.status.dataset.kind = kind || ''; }
- _statusNode(node, kind) { this.status.replaceChildren(node); this.status.dataset.kind = kind || ''; }
+ _status(text, kind) {
+ if (this._headless) { this._pill(text, kind); return; }
+ this.status.textContent = text || ''; this.status.dataset.kind = kind || '';
+ }
+ _statusNode(node, kind) {
+ if (this._headless) { this._pill(node, kind); return; }
+ this.status.replaceChildren(node); this.status.dataset.kind = kind || '';
+ }
+
+ // Background settle pill: the modal is gone but a paid spin is still resolving.
+ // Delivers the same status text/result to a small fixed pill so a confirmed
+ // payment is never silently lost when the player dismisses the modal.
+ _pill(content, kind) {
+ if (this._pillDismissed) return;
+ if (!this._pillEl) {
+ this._pillEl = el('div', { class: 'kg-spin-pill', role: 'status', 'aria-live': 'polite' });
+ document.body.appendChild(this._pillEl);
+ }
+ if (typeof content === 'string') this._pillEl.textContent = content;
+ else this._pillEl.replaceChildren(content);
+ this._pillEl.dataset.kind = kind || '';
+ }
+
+ // A settle that reached a terminal state while headless: leave the pill up
+ // briefly so the outcome is read, then remove it and finish teardown.
+ _pillDone() {
+ this._pillDismissed = true;
+ const elp = this._pillEl;
+ if (elp) setTimeout(() => elp.remove(), 6000);
+ this._teardown();
+ }
// ---------------------------------------------------------------- close
close() {
if (this._closed) return;
+ // Real money is mid-flight (payment broadcast, result not yet in). Detach the
+ // modal but keep the server subscriptions alive so the spin still settles;
+ // the outcome lands in a background pill via _headless routing.
+ if (this._paymentLive && (this.phase === 'paying' || this.phase === 'spinning')) {
+ this._headless = true;
+ this._stopSpin();
+ if (this._countdownTimer) { clearInterval(this._countdownTimer); this._countdownTimer = null; }
+ window.removeEventListener('keydown', this._onKey);
+ this.overlay?.remove();
+ this.overlay = null;
+ if (_open === this) _open = null;
+ this._pill('Your paid spin is still settling…', '');
+ try { this.onClose?.(); } catch {}
+ return;
+ }
+ this._closed = true;
+ this._teardown();
+ }
+
+ // Release timers, subscriptions and DOM. Safe to call from either the normal
+ // close or the headless-settle completion.
+ _teardown() {
this._closed = true;
this._stopSpin();
- if (this._countdownTimer) clearInterval(this._countdownTimer);
+ if (this._countdownTimer) { clearInterval(this._countdownTimer); this._countdownTimer = null; }
+ if (this._loadTimer) { clearTimeout(this._loadTimer); this._loadTimer = null; }
for (const off of this._offs || []) { try { off(); } catch {} }
+ this._offs = [];
window.removeEventListener('keydown', this._onKey);
this.overlay?.remove();
+ this.overlay = null;
if (_open === this) _open = null;
- try { this.onClose?.(); } catch {}
+ if (!this._headless) { try { this.onClose?.(); } catch {} }
}
}
diff --git a/src/game/spin-wheel.css b/src/game/spin-wheel.css
new file mode 100644
index 000000000..64fe1d173
--- /dev/null
+++ b/src/game/spin-wheel.css
@@ -0,0 +1,184 @@
+/* Wheel of Fortune — styles for the openSpinWheel modal in spin-wheel-ui.js.
+ Imported by that module so the modal carries its own styles wherever it is
+ opened (it ships as its own lazy chunk, so it cannot rely on
+ coincommunities.css having loaded first).
+
+ The design tokens below are scoped to the modal root so the file is fully
+ self-contained: on /play they shadow the identical :root tokens from
+ coincommunities.css (same values, no visual change). */
+
+.kg-spin-overlay {
+ --cc-bg2: #101010;
+ --cc-panel-solid: #0c0c0c;
+ --cc-edge: rgba(255, 255, 255, 0.12);
+ --cc-edge-hi: rgba(255, 255, 255, 0.55);
+ --cc-text: #f5f5f6;
+ --cc-dim: #8c8c92;
+ --cc-faint: #5a5a60;
+ --cc-accent: #ffffff;
+ --cc-ink: #060607;
+ --cc-shadow: 0 16px 50px rgba(0, 0, 0, 0.7);
+ --cc-glow: 0 0 14px rgba(255, 255, 255, 0.35);
+ --cc-radius: 4px;
+ --cc-radius-sm: 2px;
+ --kg-gold: #f5c542;
+ --kg-wood: #b98955;
+ --kg-stone: #aab3c2;
+ --kg-coal: #9aa2b0;
+}
+
+.kg-spin-overlay {
+ position: fixed; inset: 0; z-index: 80;
+ display: flex; align-items: center; justify-content: center; padding: 18px;
+ background: rgba(4, 4, 6, 0.66); backdrop-filter: blur(6px);
+ animation: kg-spin-fade 0.18s ease;
+}
+@keyframes kg-spin-fade { from { opacity: 0; } to { opacity: 1; } }
+
+.kg-spin-card {
+ width: 100%; max-width: 440px; max-height: calc(100dvh - 36px);
+ overflow-y: auto; overscroll-behavior: contain;
+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);
+ padding: 16px 18px 18px; color: var(--cc-text);
+ font: 14px/1.45 ui-sans-serif, system-ui, sans-serif;
+ animation: kg-spin-rise 0.18s ease;
+}
+@keyframes kg-spin-rise { from { transform: translateY(10px) scale(0.99); } to { transform: none; } }
+/* Attention pulse when openSpinWheel() re-focuses an already-open modal. */
+.kg-spin-card.kg-spin-flash { animation: kg-spin-pulse 0.5s ease; }
+@keyframes kg-spin-pulse {
+ 0%, 100% { box-shadow: var(--cc-shadow); }
+ 40% { box-shadow: var(--cc-shadow), 0 0 0 2px var(--cc-edge-hi); }
+}
+
+.kg-spin-head { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 12px; }
+.kg-spin-title { flex: 1; min-width: 0; font-weight: 800; font-size: 16px; letter-spacing: 0.02em; }
+.kg-spin-sub2 { display: block; margin-top: 2px; color: var(--cc-dim); font-weight: 600; font-size: 11.5px; letter-spacing: 0.06em; }
+.kg-spin-close {
+ flex: none; width: 32px; height: 32px; border-radius: var(--cc-radius-sm);
+ background: none; border: 1px solid var(--cc-edge); color: var(--cc-dim);
+ cursor: pointer; font-size: 13px; line-height: 1;
+ transition: border-color 0.12s ease, color 0.12s ease;
+}
+.kg-spin-close:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
+.kg-spin-close:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+/* ── The wheel itself ───────────────────────────────────────────────────── */
+.kg-spin-wheelwrap {
+ position: relative; width: min(320px, 100%); margin: 0 auto 12px;
+}
+.kg-spin-canvas { display: block; width: 100%; height: auto; aspect-ratio: 1; }
+.kg-spin-pointer {
+ position: absolute; top: -4px; left: 50%; transform: translateX(-50%);
+ width: 0; height: 0;
+ border-left: 11px solid transparent; border-right: 11px solid transparent;
+ border-top: 18px solid var(--cc-accent);
+ filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.6));
+}
+.kg-spin-hub {
+ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
+ width: 44px; height: 44px; border-radius: 50%;
+ display: flex; align-items: center; justify-content: center;
+ background: var(--cc-panel-solid); border: 2px solid var(--cc-edge-hi);
+ color: var(--kg-gold); font-size: 18px;
+ box-shadow: 0 0 18px rgba(0, 0, 0, 0.55);
+}
+
+/* ── Result + level gate ────────────────────────────────────────────────── */
+.kg-spin-result {
+ min-height: 22px; margin-bottom: 10px; text-align: center;
+ font-weight: 800; font-size: 15px;
+}
+.kg-spin-result[data-kind='gold'] { color: var(--kg-gold); }
+.kg-spin-result[data-kind='wood'] { color: var(--kg-wood); }
+.kg-spin-result[data-kind='stone'] { color: var(--kg-stone); }
+.kg-spin-result[data-kind='coal'] { color: var(--kg-coal); }
+
+.kg-spin-gate {
+ margin-bottom: 12px; padding: 10px 12px;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+}
+.kg-spin-gate[hidden] { display: none; }
+.kg-spin-gate-h { font-weight: 800; font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--cc-dim); margin-bottom: 4px; }
+.kg-spin-gate-b { color: var(--cc-text); font-size: 12.5px; line-height: 1.5; }
+
+/* ── Spin actions ───────────────────────────────────────────────────────── */
+.kg-spin-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px; }
+.kg-spin-action { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
+.kg-spin-btn {
+ width: 100%; padding: 12px 8px;
+ background: var(--cc-accent); color: var(--cc-ink);
+ border: 1px solid var(--cc-accent); border-radius: var(--cc-radius);
+ font-weight: 800; font-size: 13.5px; letter-spacing: 0.03em; cursor: pointer;
+ box-shadow: var(--cc-glow);
+ transition: transform 0.12s ease, box-shadow 0.12s ease, opacity 0.12s ease;
+}
+.kg-spin-btn:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 0 22px rgba(255, 255, 255, 0.55); }
+.kg-spin-btn:active:not(:disabled) { transform: translateY(1px); }
+.kg-spin-btn:disabled { opacity: 0.45; cursor: default; box-shadow: none; }
+.kg-spin-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+/* The paid spin is the secondary action: quieter than the free one. */
+.kg-spin-btn.kg-spin-paid {
+ background: var(--cc-bg2); color: var(--cc-text); border-color: var(--cc-edge); box-shadow: none;
+}
+.kg-spin-btn.kg-spin-paid:hover:not(:disabled) { border-color: var(--cc-edge-hi); box-shadow: none; }
+.kg-spin-sub {
+ color: var(--cc-dim); font-size: 11px; line-height: 1.4; text-align: center;
+ font-variant-numeric: tabular-nums; min-height: 15px;
+}
+.kg-spin-sub[data-ready='1'] { color: var(--cc-text); }
+
+/* ── Status line + odds legend ──────────────────────────────────────────── */
+.kg-spin-status {
+ min-height: 18px; margin-bottom: 10px; text-align: center;
+ font-size: 12.5px; line-height: 1.45; color: var(--cc-dim); word-break: break-word;
+}
+.kg-spin-status[data-kind='ok'] { color: var(--cc-text); }
+.kg-spin-status[data-kind='err'] { color: #d88a8a; }
+.kg-spin-status a { color: inherit; text-decoration: underline; }
+.kg-spin-retry {
+ background: none; border: none; padding: 0; margin-left: 4px;
+ color: var(--cc-text); text-decoration: underline; cursor: pointer; font: inherit;
+}
+.kg-spin-retry:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+.kg-spin-legend { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; justify-content: center; }
+.kg-spin-legend-h { color: var(--cc-faint); font-size: 10.5px; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; }
+.kg-spin-chip { display: inline-flex; align-items: center; gap: 5px; color: var(--cc-dim); font-size: 11.5px; font-variant-numeric: tabular-nums; }
+.kg-spin-dot { width: 8px; height: 8px; border-radius: 50%; flex: none; }
+.kg-spin-paytable {
+ color: var(--cc-dim); font-size: 11.5px; text-decoration: none;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.22); transition: color 0.15s ease, border-color 0.15s ease;
+}
+.kg-spin-paytable:hover { color: var(--cc-text); border-bottom-color: currentColor; }
+.kg-spin-paytable:focus-visible { outline: 2px solid #fff; outline-offset: 3px; border-radius: 2px; }
+
+/* ── Background-settle pill ─────────────────────────────────────────────────
+ Shown after the player closes the modal while a paid spin is still settling:
+ the flow keeps running headless and this pill delivers the outcome. */
+.kg-spin-pill {
+ position: fixed; left: 50%; bottom: calc(18px + env(safe-area-inset-bottom, 0px));
+ transform: translateX(-50%); z-index: 81;
+ max-width: min(420px, calc(100vw - 32px));
+ padding: 10px 16px; border-radius: 999px;
+ background: var(--cc-panel-solid, #0c0c0c); border: 1px solid rgba(255, 255, 255, 0.12);
+ box-shadow: 0 16px 50px rgba(0, 0, 0, 0.7);
+ color: #f5f5f6; font: 12.5px/1.4 ui-sans-serif, system-ui, sans-serif;
+ text-align: center; animation: kg-spin-fade 0.18s ease;
+}
+.kg-spin-pill[data-kind='err'] { color: #d88a8a; }
+
+/* ── Small screens ──────────────────────────────────────────────────────── */
+@media (max-width: 420px) {
+ .kg-spin-overlay { padding: 10px; align-items: flex-end; }
+ .kg-spin-card { max-height: calc(100dvh - 20px); padding: 14px 14px 16px; }
+ .kg-spin-wheelwrap { width: min(260px, 100%); }
+ .kg-spin-actions { grid-template-columns: 1fr; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .kg-spin-overlay, .kg-spin-card, .kg-spin-pill { animation: none; }
+ .kg-spin-card.kg-spin-flash { animation: none; box-shadow: var(--cc-shadow), 0 0 0 2px var(--cc-edge-hi); }
+ .kg-spin-btn, .kg-spin-close { transition: none; }
+}
diff --git a/src/shared/cinematic-render.js b/src/shared/cinematic-render.js
index d9ec49705..c92440b56 100644
--- a/src/shared/cinematic-render.js
+++ b/src/shared/cinematic-render.js
@@ -100,8 +100,10 @@ export async function loadEnvironment(renderer, scene, preset = 'studio') {
try {
let hdrTexture = _envCache.get(preset);
if (!hdrTexture) {
- const { RGBELoader } = await import('three/addons/loaders/RGBELoader.js');
- hdrTexture = await new RGBELoader().loadAsync(HDRI_PRESETS[preset]);
+ // HDRLoader is the same decoder RGBELoader wraps; RGBELoader is a
+ // deprecated alias since three r180 and logs a warning on every use.
+ const { HDRLoader } = await import('three/addons/loaders/HDRLoader.js');
+ hdrTexture = await new HDRLoader().loadAsync(HDRI_PRESETS[preset]);
_envCache.set(preset, hdrTexture);
}
const envMap = pmrem.fromEquirectangular(hdrTexture).texture;