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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(play): live community meetups in the $THREE home town, on one shared clock
nirholase29fe4645eb5
diff --git a/public/event.json b/public/event.jsonindex 124eb7a93..1ef8e6ddd 100644--- a/public/event.json+++ b/public/event.json@@ -1,8 +1,17 @@{- "name": "$THREE Community Day",- "tagline": "The whole community, one world. Drop in, hang out, win prizes.",- "startsAt": "2026-08-08T17:00:00Z",- "endsAt": "2026-08-08T21:00:00Z",+ "$comment": "The live /play event. Single source of truth for BOTH the countdown pill/banner (src/game/event-countdown.js) and the in-world meetup experience layer (src/game/meetup-event.js: agenda drawer, go-live moments, synchronized fireworks, commemorative photo). Times are ISO-8601 UTC. agenda[].atMin is minutes after startsAt. Preview locally with ?meetup=now or ?meetup=<ISO> on /play.",+ "id": "three-first-meetup",+ "name": "$THREE First Holders Meetup",+ "tagline": "The first live gathering in the three.ws world. Drop in, hang out, win prizes.",+ "startsAt": "2026-08-07T17:00:00Z",+ "endsAt": "2026-08-07T19:00:00Z","link": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",- "linkLabel": "Join the $THREE world"+ "linkLabel": "Join the $THREE world",+ "agenda": [+ { "atMin": 0, "title": "Doors open in the plaza", "detail": "Say hi in chat, show off your fit, grab a commemorative photo", "icon": "👋" },+ { "atMin": 20, "title": "King of the Totem showdown", "detail": "Hold the gold ring at the totem to be crowned. Winner takes the round", "icon": "👑" },+ { "atMin": 45, "title": "Fortune's Folly wheel hour", "detail": "Free spin at the plaza wheel, prizes on every wedge", "icon": "🎡" },+ { "atMin": 70, "title": "Plaza dance-off", "detail": "Q opens emotes. Hit the dance floor east of the totem", "icon": "🕺" },+ { "atMin": 105, "title": "Fireworks finale", "detail": "Look up. Grab your event photo while the sky is lit", "icon": "🎆" }+ ]}diff --git a/public/play-events.json b/public/play-events.jsondeleted file mode 100644index 4e4618850..000000000--- a/public/play-events.json+++ /dev/null@@ -1,19 +0,0 @@-{- "comment": "Scheduled live events for /play. First event with a valid startsAt is the active one. Times are ISO-8601 UTC. Edit + redeploy to reschedule; ?meetup=<ISO> overrides locally for previewing.",- "events": [- {- "id": "three-first-meetup-2026-08-07",- "title": "$THREE First Holders Meetup",- "subtitle": "The first live gathering in the three.ws world",- "startsAt": "2026-08-07T17:00:00Z",- "durationMin": 90,- "agenda": [- { "atMin": 0, "title": "Doors open in the plaza", "detail": "Say hi in chat, show off your fit, grab a commemorative photo", "icon": "👋" },- { "atMin": 15, "title": "King of the Totem showdown", "detail": "Hold the totem to be crowned. Winner takes the round", "icon": "👑" },- { "atMin": 35, "title": "Fortune's Folly wheel hour", "detail": "Free spin at the plaza wheel, prizes on every wedge", "icon": "🎡" },- { "atMin": 55, "title": "Plaza dance-off", "detail": "Q opens emotes. Best moves get screenshotted", "icon": "🕺" },- { "atMin": 75, "title": "Fireworks finale", "detail": "Look up. Grab your event photo while the sky is lit", "icon": "🎆" }- ]- }- ]-}diff --git a/src/game/event-countdown.js b/src/game/event-countdown.jsindex 10619b612..309cabe0c 100644--- a/src/game/event-countdown.js+++ b/src/game/event-countdown.js@@ -1,8 +1,10 @@// Event countdown for /play: lobby banner + in-world pill.//// Self-attaching, like ambient-crowd.js: ZERO edits to coincommunities.js or-// coincommunities-ui.js. It reads /event.json (public/event.json in the repo),-// and while an event is upcoming or live it mounts two views:+// coincommunities-ui.js. The event window comes from src/shared/event-config.js,+// which reads /event.json (public/event.json in the repo) and is the same reader+// the home-page strip uses, so the two surfaces cannot drift apart. While an+// event is upcoming or live this mounts two views://// 1. A lobby banner at the top of the lobby scroll, with the event name,// a ticking countdown, the start time in the player's own timezone, and@@ -15,7 +17,9 @@// unmounts and the interval stops). A missing or malformed event.json mounts// nothing; the page owes the player zero pixels when there is no event.-const CONFIG_URL = '/event.json';+import {+ loadEventConfig, eventState, segments, pad, clockString, formatStart, alreadyAtEvent,+} from '../shared/event-config.js';function el(tag, attrs = {}, children = []) {const n = document.createElement(tag);@@ -98,53 +102,6 @@ body.is-zen .cc-event-pill { opacity: 0; pointer-events: none; }}`;-function parseConfig(raw) {- if (!raw || typeof raw !== 'object') return null;- const startsAt = Date.parse(raw.startsAt);- if (!Number.isFinite(startsAt)) return null;- const endsAt = Date.parse(raw.endsAt);- return {- name: String(raw.name || 'Live event'),- tagline: raw.tagline ? String(raw.tagline) : '',- startsAt,- // An event with no (or bad) end time stays "live" for 6 hours.- endsAt: Number.isFinite(endsAt) ? endsAt : startsAt + 6 * 3600 * 1000,- link: raw.link ? String(raw.link) : null,- linkLabel: raw.linkLabel ? String(raw.linkLabel) : 'Join the event',- };-}--// The pill's CTA is pointless when the player is already standing in the event-// world: compare the event link's coin param against the current URL's.-function alreadyAtEvent(cfg) {- if (!cfg.link) return false;- try {- const target = new URL(cfg.link, location.origin);- const targetCoin = target.searchParams.get('coin');- const hereCoin = new URLSearchParams(location.search).get('coin');- return !!targetCoin && targetCoin === hereCoin;- } catch { return false; }-}--function fmtStart(ts) {- return new Intl.DateTimeFormat(undefined, {- weekday: 'short', month: 'short', day: 'numeric',- hour: 'numeric', minute: '2-digit', timeZoneName: 'short',- }).format(new Date(ts));-}--function pad(n) { return String(n).padStart(2, '0'); }--function segments(ms) {- const s = Math.max(0, Math.floor(ms / 1000));- return {- d: Math.floor(s / 86400),- h: Math.floor((s % 86400) / 3600),- m: Math.floor((s % 3600) / 60),- s: s % 60,- };-}-class EventCountdown {constructor(cfg) {this.cfg = cfg;@@ -172,7 +129,7 @@ class EventCountdown {this.bannerKicker,el('div', { class: 'cc-event-name', text: this.cfg.name }),this.cfg.tagline ? el('div', { class: 'cc-event-tagline', text: this.cfg.tagline }) : null,- el('div', { class: 'cc-event-when', text: `Starts ${fmtStart(this.cfg.startsAt)}` }),+ el('div', { class: 'cc-event-when', text: `Starts ${formatStart(this.cfg.startsAt)}` }),]),this.bannerClock,this.cfg.link ? el('a', { class: 'cc-event-cta', href: this.cfg.link, text: this.cfg.linkLabel }) : null,@@ -205,9 +162,9 @@ class EventCountdown {_tick() {const now = Date.now();- if (now >= this.cfg.endsAt) return this.destroy();- const live = now >= this.cfg.startsAt;- const state = live ? 'live' : 'upcoming';+ const state = eventState(this.cfg, now);+ if (state === 'over') return this.destroy();+ const live = state === 'live';if (this.banner) {this.banner.setAttribute('data-state', state);@@ -234,9 +191,7 @@ class EventCountdown {if (live) {this.pillText.textContent = `${this.cfg.name} · LIVE`;} else {- const t = segments(this.cfg.startsAt - now);- const clock = (t.d > 0 ? `${t.d}d ` : '') + `${pad(t.h)}:${pad(t.m)}:${pad(t.s)}`;- this.pillText.textContent = `${this.cfg.name} · ${clock}`;+ this.pillText.textContent = `${this.cfg.name} · ${clockString(this.cfg.startsAt - now)}`;}}}@@ -250,13 +205,8 @@ class EventCountdown {}async function boot() {- let cfg = null;- try {- const res = await fetch(CONFIG_URL, { cache: 'no-cache' });- if (!res.ok) return;- cfg = parseConfig(await res.json());- } catch { return; }- if (!cfg || Date.now() >= cfg.endsAt) return;+ const cfg = await loadEventConfig();+ if (!cfg) return;// The lobby is built by coincommunities.js at boot; wait for it to exist so// the banner has somewhere to mount. If it never shows up (boot failure),diff --git a/src/game/meetup-event.css b/src/game/meetup-event.cssindex 4292466ff..149b9f43e 100644--- a/src/game/meetup-event.css+++ b/src/game/meetup-event.css@@ -143,6 +143,15 @@}#cc-meetup-flash.cc-meetup-flash--on { opacity: 0.85; transition: none; }+/* One countdown at a time: while this layer's chip is mounted, the generic+ event-countdown pill (same schedule, same event.json) stands down. */+body.cc-meetup-ui .cc-event-pill { display: none; }++/* Zen mode strips every overlay; the meetup UI complies like the rest. */+body.is-zen #cc-meetup-chip,+body.is-zen #cc-meetup-panel,+body.is-zen #cc-meetup-banner { display: none; }+@media (max-width: 640px) {.cc-meetup-title { max-width: 38vw; }#cc-meetup-banner { padding: 14px 26px; }diff --git a/src/game/meetup-event.js b/src/game/meetup-event.jsnew file mode 100644index 000000000..6509645df--- /dev/null+++ b/src/game/meetup-event.js@@ -0,0 +1,535 @@+// Meetup event layer for /play: the in-world experience for live community+// events in the $THREE home town.+//+// Self-attaching, like ambient-crowd.js and event-countdown.js: ZERO edits to+// coincommunities.js or coincommunities-ui.js. It polls window.__CC__, and while+// the player stands in the home town during an event window it mounts:+//+// 1. A countdown chip docked under the King of the Totem card that opens the+// full agenda drawer (what's on, what's next, and when, in local time).+// 2. Go-live and segment-change moment banners (the gold King-banner look).+// 3. A synchronized fireworks show: sparse bursts through the live window, a+// barrage in the finale. Deterministic per wall-clock bucket+// (meetup-schedule.js fireworkPlan), so every client sees the same sky+// without a single packet, the same trick the shared day/night clock uses.+// 4. A commemorative photo button: one tap captures the world, frames it with+// the event title and date, and shares/downloads it.+// 5. A live $THREE pulse row (price, 24h, market cap) off /api/three-signal,+// plus a one-tap Buy $THREE into the app's existing trade widget.+//+// Config comes from /event.json, the SAME file event-countdown.js reads, so the+// lobby banner, the wayfinding pill, and this layer can never disagree about+// when the event is. While this layer's chip is mounted it suppresses the+// generic pill (body.cc-meetup-ui in meetup-event.css): one countdown at a time.+//+// No event, wrong world, or malformed config: nothing mounts, the world owes+// the player zero pixels.++import './meetup-event.css';+import { isHomeTown } from './home-town.js';+import { getPowerSaver } from '../shared/frame-governor.js';+import {+ parseEvent, eventState, formatCountdown, fireworkPlan, PHASE, BUCKET_MS,+} from './meetup-schedule.js';++const CONFIG_URL = '/event.json';+const SIGNAL_URL = '/api/three-signal';+const REFRESH_MS = 500; // DOM refresh cadence+const FINALE_MS = 15 * 60 * 1000; // the closing barrage window+const RING_RADIUS = 38; // fireworks launch ring around the plaza+const MAX_LIVE_BURSTS = 14; // hard cap on simultaneous shells++function el(tag, props = {}, kids = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (v == null) continue;+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);+ else n.setAttribute(k, v);+ }+ for (const c of [].concat(kids)) if (c) n.appendChild(c);+ return n;+}++function fmtLocal(ts) {+ return new Intl.DateTimeFormat(undefined, {+ weekday: 'short', hour: 'numeric', minute: '2-digit', timeZoneName: 'short',+ }).format(new Date(ts));+}++function fmtPrice(v) {+ const n = Number(v);+ if (!isFinite(n) || n <= 0) return null;+ if (n >= 1) return `$${n.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;+ return `$${n.toPrecision(3)}`;+}++function fmtCompactUsd(v) {+ const n = Number(v);+ if (!isFinite(n) || n <= 0) return null;+ if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;+ if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;+ if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;+ return `$${n.toFixed(0)}`;+}++class MeetupEvent {+ constructor(event, cc) {+ this.ev = event;+ this.cc = cc;+ this.chip = null;+ this.panel = null;+ this.banner = null;+ this.flashEl = null;+ this.fireworks = null;+ this.mounted = false;+ this._prevPhase = null;+ this._prevSegAt = null;+ this._queue = []; // scheduled local volley launches {atMs, angle, radiusFrac, palette, apex}+ this._lastShowMs = 0; // deterministic-show high-water mark+ this._acc = 0;+ this._lastFrame = performance.now();+ this._signal = null;+ this._signalTimer = 0;+ this._raf = 0;+ this._loop = this._loop.bind(this);+ this._raf = requestAnimationFrame(this._loop);+ this._onKey = (e) => {+ if (e.key === 'Escape' && this.panel?.classList.contains('cc-meetup-panel--open')) this._closePanel();+ };+ window.addEventListener('keydown', this._onKey);+ }++ // ------------------------------------------------------------------ loop+ _loop(now) {+ this._raf = requestAnimationFrame(this._loop);+ const dt = Math.min(0.05, (now - this._lastFrame) / 1000);+ this._lastFrame = now;++ const cc = this.cc;+ const inWorld = cc.phase === 'world' && isHomeTown(cc.coin?.mint);+ const state = eventState(this.ev, Date.now());++ if (state.phase === PHASE.ENDED) { this.destroy(); return; }++ if (!inWorld || state.phase === PHASE.FAR) {+ if (this.mounted) this._unmount();+ this._prevPhase = null;+ return;+ }++ if (!this.mounted) this._mount(state);+ this._tickMoments(state);+ this._tickFireworks(dt, state);++ this._acc += dt * 1000;+ if (this._acc >= REFRESH_MS) {+ this._acc = 0;+ this._refreshChip(state);+ if (this.panel?.classList.contains('cc-meetup-panel--open')) this._refreshPanel(state);+ }+ }++ // ------------------------------------------------------------ mount/unmount+ _mount(state) {+ this.mounted = true;+ document.body.classList.add('cc-meetup-ui');+ this.chip = el('button', {+ id: 'cc-meetup-chip', type: 'button',+ 'aria-label': `${this.ev.title}: open event agenda`, 'aria-expanded': 'false',+ onclick: () => this._togglePanel(),+ }, [+ el('span', { class: 'cc-meetup-ico', 'aria-hidden': 'true', text: '🎉' }),+ el('span', { class: 'cc-meetup-copy' }, [+ this._chipTitle = el('span', { class: 'cc-meetup-title', text: this.ev.title }),+ this._chipWhen = el('span', { class: 'cc-meetup-when' }),+ ]),+ ]);+ document.body.appendChild(this.chip);+ this._refreshChip(state);+ // Seed transition tracking so joining mid-event never replays the go-live+ // moment or the current segment's banner.+ if (this._prevPhase == null) {+ this._prevPhase = state.phase;+ this._prevSegAt = state.active ? state.active.atMin : null;+ }+ }++ _unmount() {+ this.mounted = false;+ document.body.classList.remove('cc-meetup-ui');+ this.chip?.remove(); this.chip = null;+ this.banner?.remove(); this.banner = null;+ this._closePanel(true);+ this.panel?.remove(); this.panel = null;+ this.flashEl?.remove(); this.flashEl = null;+ this.fireworks?.dispose(); this.fireworks = null;+ this._queue = [];+ clearInterval(this._signalTimer);+ this._signalTimer = 0;+ }++ destroy() {+ cancelAnimationFrame(this._raf);+ window.removeEventListener('keydown', this._onKey);+ this._unmount();+ }++ // ------------------------------------------------------------------ chip+ _refreshChip(state) {+ if (!this.chip) return;+ // Dock under the King of the Totem card when it is up; top slot otherwise.+ const king = document.getElementById('cc-king-hud');+ const kingVisible = king && !king.hidden && king.offsetParent !== null;+ this.chip.style.top = kingVisible ? `${Math.round(king.getBoundingClientRect().bottom) + 8}px` : '12px';++ this.chip.classList.toggle('cc-meetup-preshow', state.phase === PHASE.PRESHOW);+ this.chip.classList.toggle('cc-meetup-islive', state.phase === PHASE.LIVE);+ if (state.phase === PHASE.LIVE) {+ const nxt = state.next ? ` · next: ${state.next.icon || ''} ${formatCountdown(state.msToNext)}` : '';+ this._chipWhen.innerHTML = '';+ this._chipWhen.append(el('span', { class: 'cc-meetup-live-dot', 'aria-hidden': 'true' }), `LIVE${nxt}`);+ } else if (state.phase === PHASE.AFTERGLOW) {+ this._chipWhen.textContent = 'That was the meetup. Grab a photo';+ } else {+ this._chipWhen.textContent = `Starts in ${formatCountdown(state.msToStart)}`;+ }+ }++ // ------------------------------------------------------------------ panel+ _buildPanel() {+ this._agendaList = el('div', { class: 'cc-meetup-agenda', role: 'list' });+ this._pulseRow = el('div', { class: 'cc-meetup-pulse', hidden: true });+ this.panel = el('aside', {+ id: 'cc-meetup-panel', role: 'dialog', 'aria-label': `${this.ev.title} agenda`,+ }, [+ el('div', { class: 'cc-meetup-panel-head' }, [+ el('div', {}, [+ el('div', { class: 'cc-meetup-panel-title', text: this.ev.title }),+ this.ev.subtitle ? el('div', { class: 'cc-meetup-panel-sub', text: this.ev.subtitle }) : null,+ this._panelWhen = el('div', { class: 'cc-meetup-panel-when' }),+ ]),+ el('button', {+ type: 'button', class: 'cc-meetup-close', 'aria-label': 'Close agenda',+ onclick: () => this._closePanel(),+ }, [el('span', { 'aria-hidden': 'true', text: '✕' })]),+ ]),+ this._agendaList,+ el('div', { class: 'cc-meetup-panel-foot' }, [+ this._pulseRow,+ el('button', {+ type: 'button', class: 'cc-meetup-photo-btn',+ onclick: () => this._capturePhoto(),+ }, [el('span', { 'aria-hidden': 'true', text: '📸' }), el('span', { text: 'Commemorative photo' })]),+ el('button', {+ type: 'button', class: 'cc-meetup-buy-btn',+ onclick: () => { this._closePanel(); try { this.cc._openBuy?.(); } catch { /* widget owns its errors */ } },+ }, [el('span', { 'aria-hidden': 'true', text: '⚡' }), el('span', { text: 'Buy $THREE' })]),+ ]),+ ]);+ document.body.appendChild(this.panel);+ }++ _togglePanel() {+ if (!this.panel) this._buildPanel();+ const open = !this.panel.classList.contains('cc-meetup-panel--open');+ this.panel.classList.toggle('cc-meetup-panel--open', open);+ this.chip?.setAttribute('aria-expanded', String(open));+ if (open) {+ this._refreshPanel(eventState(this.ev, Date.now()));+ this._refreshSignal();+ clearInterval(this._signalTimer);+ this._signalTimer = setInterval(() => this._refreshSignal(), 60_000);+ } else {+ clearInterval(this._signalTimer);+ this._signalTimer = 0;+ }+ }++ _closePanel(silent = false) {+ if (!this.panel) return;+ this.panel.classList.remove('cc-meetup-panel--open');+ this.chip?.setAttribute('aria-expanded', 'false');+ clearInterval(this._signalTimer);+ this._signalTimer = 0;+ if (!silent) this.chip?.focus?.();+ }++ _refreshPanel(state) {+ if (!this.panel) return;+ if (state.phase === PHASE.LIVE) {+ this._panelWhen.textContent = `LIVE · ends in ${formatCountdown(state.msToEnd)}`;+ } else if (state.phase === PHASE.AFTERGLOW) {+ this._panelWhen.textContent = 'Just wrapped. Thanks for coming';+ } else {+ this._panelWhen.textContent = `${fmtLocal(this.ev.startsAt)} · starts in ${formatCountdown(state.msToStart)}`;+ }+ const minsIn = (Date.now() - this.ev.startsAt) / 60000;+ this._agendaList.replaceChildren(...this.ev.agenda.map((seg) => {+ const done = state.phase === PHASE.AFTERGLOW+ || (state.phase === PHASE.LIVE && state.active && seg.atMin < state.active.atMin);+ const active = state.phase === PHASE.LIVE && state.active && seg.atMin === state.active.atMin;+ const label = active ? 'now' : done ? 'done' : formatCountdown(Math.max(0, (seg.atMin - Math.max(0, minsIn)) * 60000) + Math.max(0, this.ev.startsAt - Date.now()));+ return el('div', {+ class: `cc-meetup-seg${active ? ' cc-meetup-seg--active' : ''}${done ? ' cc-meetup-seg--done' : ''}`,+ role: 'listitem',+ }, [+ el('span', { class: 'cc-meetup-seg-ico', 'aria-hidden': 'true', text: seg.icon || '•' }),+ el('span', {}, [+ el('div', { class: 'cc-meetup-seg-title', text: seg.title }),+ seg.detail ? el('div', { class: 'cc-meetup-seg-detail', text: seg.detail }) : null,+ ]),+ el('span', { class: 'cc-meetup-seg-at', text: label }),+ ]);+ }));+ }++ // ---------------------------------------------------------------- $THREE pulse+ async _refreshSignal() {+ try {+ const res = await fetch(SIGNAL_URL, { headers: { accept: 'application/json' } });+ if (!res.ok) return;+ const body = await res.json();+ const latest = body?.latest;+ const price = fmtPrice(latest?.price_usd);+ if (!price || !this._pulseRow) return;+ const chg = Number(latest?.change_24h);+ const mcap = fmtCompactUsd(latest?.market_cap_usd);+ this._pulseRow.replaceChildren(+ el('span', {}, [el('b', { text: '$THREE ' }), el('span', { text: price })]),+ isFinite(chg)+ ? el('span', { class: chg >= 0 ? 'cc-meetup-up' : 'cc-meetup-down', text: `${chg >= 0 ? '+' : ''}${chg.toFixed(1)}% 24h` })+ : el('span', { text: '' }),+ mcap ? el('span', {}, [el('span', { text: 'MC ' }), el('b', { text: mcap })]) : el('span', { text: '' }),+ );+ this._pulseRow.hidden = false;+ } catch { /* pulse row simply stays hidden */ }+ }++ // ---------------------------------------------------------------- moments+ _tickMoments(state) {+ const prev = this._prevPhase;+ if (prev == null) return; // seeded on mount+ if (state.phase !== prev) {+ this._prevPhase = state.phase;+ if (state.phase === PHASE.PRESHOW) {+ this.cc.ui?.toast?.(`${this.ev.title} starts in ${formatCountdown(state.msToStart)}. Stick around!`, 'info');+ } else if (state.phase === PHASE.LIVE) {+ this._moment('🎉', this.ev.title, 'LIVE NOW');+ this._volley(12, 7000);+ try { this.cc.env?.flashRing?.(0xffce5c, 1); } catch { /* cosmetic */ }+ this._prevSegAt = state.active ? state.active.atMin : null;+ } else if (state.phase === PHASE.AFTERGLOW) {+ this._moment('📸', 'Thanks for being here', 'Grab your commemorative photo from the event menu');+ this._volley(10, 6000);+ }+ return;+ }+ if (state.phase === PHASE.LIVE) {+ const at = state.active ? state.active.atMin : null;+ if (at !== this._prevSegAt) {+ this._prevSegAt = at;+ if (state.active) {+ this._moment(state.active.icon || '🎪', state.active.title, state.active.detail || '');+ this._volley(4, 3000);+ }+ }+ }+ }++ _moment(icon, title, sub) {+ if (!this.banner) {+ this.banner = el('div', { id: 'cc-meetup-banner', 'aria-live': 'assertive' });+ document.body.appendChild(this.banner);+ }+ this.banner.replaceChildren(+ el('div', { class: 'cc-meetup-banner-ico', 'aria-hidden': 'true', text: icon }),+ el('div', { class: 'cc-meetup-banner-title', text: title }),+ sub ? el('div', { class: 'cc-meetup-banner-sub', text: sub }) : null,+ );+ this.banner.classList.remove('cc-meetup-banner--show');+ void this.banner.offsetWidth;+ this.banner.classList.add('cc-meetup-banner--show');+ clearTimeout(this._bannerTimer);+ this._bannerTimer = setTimeout(() => this.banner?.classList.remove('cc-meetup-banner--show'), 4500);+ }++ // --------------------------------------------------------------- fireworks+ _ensureFireworks() {+ if (!this.fireworks && this.cc.scene) this.fireworks = new (this._FireworksCtor)({ scene: this.cc.scene });+ return this.fireworks;+ }++ // A local celebratory volley (go-live, segment change). Spread over spanMs.+ _volley(count, spanMs) {+ const n = getPowerSaver() ? Math.ceil(count / 2) : count;+ const now = Date.now();+ for (let i = 0; i < n; i++) {+ this._queue.push({+ atMs: now + (i / n) * spanMs + Math.random() * 400,+ angle: Math.random() * Math.PI * 2,+ radiusFrac: 0.55 + Math.random() * 0.45,+ palette: Math.floor(Math.random() * 6),+ apex: 16 + Math.random() * 10,+ });+ }+ }++ _tickFireworks(dt, state) {+ const now = Date.now();+ // Deterministic shared show: sparse through the live window, barrage in+ // the finale. Everyone computes the same plan from the same wall clock.+ if (state.phase === PHASE.LIVE) {+ let intensity = 0.3;+ if (state.msToEnd <= FINALE_MS) intensity = 1 + 1.6 * (1 - state.msToEnd / FINALE_MS);+ if (getPowerSaver()) intensity *= 0.5;+ if (this._lastShowMs === 0) this._lastShowMs = now;+ // Cover the buckets the window [lastShowMs, now] touches.+ for (let b = Math.floor(this._lastShowMs / BUCKET_MS); b <= Math.floor(now / BUCKET_MS); b++) {+ for (const l of fireworkPlan(this.ev.id, b * BUCKET_MS, { intensity })) {+ if (l.atMs > this._lastShowMs && l.atMs <= now) {+ this._queue.push({ atMs: l.atMs, angle: l.angle, radiusFrac: l.radius, palette: l.palette, apex: l.apex });+ }+ }+ }+ this._lastShowMs = now;+ } else {+ this._lastShowMs = 0;+ }++ if (this._queue.length) {+ const due = this._queue.filter((q) => q.atMs <= now);+ if (due.length) {+ this._queue = this._queue.filter((q) => q.atMs > now);+ const fw = this._ensureFireworks();+ if (fw) {+ for (const q of due) {+ if (fw.liveCount >= MAX_LIVE_BURSTS) break;+ fw.launch(Math.cos(q.angle) * RING_RADIUS * q.radiusFrac, Math.sin(q.angle) * RING_RADIUS * q.radiusFrac, {+ apex: q.apex, palette: q.palette,+ });+ }+ }+ }+ }+ this.fireworks?.tick(dt);+ }++ // ------------------------------------------------------------------ photo+ async _capturePhoto() {+ const cc = this.cc;+ if (!this.flashEl) {+ this.flashEl = el('div', { id: 'cc-meetup-flash', 'aria-hidden': 'true' });+ document.body.appendChild(this.flashEl);+ }+ this.flashEl.classList.add('cc-meetup-flash--on');+ requestAnimationFrame(() => requestAnimationFrame(() => this.flashEl?.classList.remove('cc-meetup-flash--on')));++ let dataUrl = null;+ try {+ const shot = cc._captureBuildShot?.(1600);+ if (shot?.dataUrl) dataUrl = shot.dataUrl;+ } catch { /* fall through to the direct read */ }+ if (!dataUrl) {+ try {+ cc.renderer.render(cc.scene, cc.camera);+ dataUrl = cc.renderer.domElement.toDataURL('image/png');+ } catch {+ cc.ui?.toast?.('Couldn’t capture the scene. Try again in a moment.', 'warn');+ return;+ }+ }++ const img = new Image();+ await new Promise((resolve, reject) => { img.onload = resolve; img.onerror = reject; img.src = dataUrl; })+ .catch(() => null);+ if (!img.naturalWidth) { cc.ui?.toast?.('Couldn’t capture the scene. Try again in a moment.', 'warn'); return; }++ const c = document.createElement('canvas');+ c.width = img.naturalWidth; c.height = img.naturalHeight;+ const ctx = c.getContext('2d');+ ctx.drawImage(img, 0, 0);++ // The frame: a quiet bottom gradient with the event title, date and the+ // site, gold-accented. Something a holder wants to post, not a watermark.+ const W = c.width, H = c.height;+ const barH = Math.round(H * 0.20);+ const grad = ctx.createLinearGradient(0, H - barH, 0, H);+ grad.addColorStop(0, 'rgba(4,4,6,0)');+ grad.addColorStop(0.45, 'rgba(4,4,6,0.62)');+ grad.addColorStop(1, 'rgba(4,4,6,0.9)');+ ctx.fillStyle = grad;+ ctx.fillRect(0, H - barH, W, barH);+ const mx = Math.round(W * 0.045);+ ctx.fillStyle = '#ffce5c';+ ctx.fillRect(mx, H - Math.round(barH * 0.52), Math.round(W * 0.055), Math.max(3, Math.round(H * 0.004)));+ ctx.textBaseline = 'alphabetic';+ ctx.fillStyle = '#ffffff';+ ctx.font = `800 ${Math.round(H * 0.038)}px system-ui, -apple-system, sans-serif`;+ ctx.fillText(this.ev.title.toUpperCase(), mx, H - Math.round(barH * 0.28));+ ctx.fillStyle = '#ffce5c';+ ctx.font = `600 ${Math.round(H * 0.024)}px system-ui, -apple-system, sans-serif`;+ const dateLine = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'long', day: 'numeric' }).format(new Date(this.ev.startsAt));+ ctx.fillText(`${dateLine} · three.ws/play`, mx, H - Math.round(barH * 0.10));++ const blob = await new Promise((resolve) => c.toBlob(resolve, 'image/jpeg', 0.92));+ if (!blob) { cc.ui?.toast?.('Couldn’t save the photo.', 'warn'); return; }+ const stamp = new Date(this.ev.startsAt).toISOString().slice(0, 10);+ const file = new File([blob], `three-meetup-${stamp}.jpg`, { type: 'image/jpeg' });+ if (navigator.canShare?.({ files: [file] })) {+ try {+ await navigator.share({ files: [file], title: this.ev.title, text: `${this.ev.title} · three.ws/play` });+ return;+ } catch { /* user cancelled or share failed: fall through to download */ }+ }+ const a = el('a', { href: URL.createObjectURL(blob), download: file.name });+ document.body.appendChild(a);+ a.click();+ setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1000);+ cc.ui?.toast?.('Photo saved. Post it and tag $THREE.', 'success');+ }+}++// Fireworks is heavier (three.js geometry churn), loaded only when a mount is+// actually possible; the class is stashed on the instance so _ensureFireworks+// can construct synchronously inside the frame loop.+async function boot() {+ let cfg = null;+ try {+ const res = await fetch(CONFIG_URL, { cache: 'no-cache' });+ if (res.ok) cfg = parseEvent(await res.json());+ } catch { /* no event, mount nothing */ }++ // Local preview: ?meetup=now starts the event 20s from load; ?meetup=<ISO>+ // shifts the whole window to that start. Duration and agenda are preserved.+ try {+ const want = new URLSearchParams(location.search).get('meetup');+ if (want && cfg) {+ const start = want === 'now' ? Date.now() + 20_000 : Date.parse(want);+ if (Number.isFinite(start)) {+ const span = cfg.endsAt - cfg.startsAt;+ cfg = { ...cfg, startsAt: start, endsAt: start + span };+ }+ }+ } catch { /* bad override, keep the real schedule */ }++ if (!cfg) return;+ if (eventState(cfg, Date.now()).phase === PHASE.ENDED) return;++ const { Fireworks } = await import('./fireworks.js');++ // Wait for the app the same way ambient-crowd.js does.+ let tries = 0;+ (function wait() {+ const cc = window.__CC__;+ if (cc) {+ const m = new MeetupEvent(cfg, cc);+ m._FireworksCtor = Fireworks;+ } else if (++tries < 300) {+ setTimeout(wait, 300);+ }+ })();+}++boot();diff --git a/src/game/meetup-schedule.js b/src/game/meetup-schedule.jsindex a18eb219b..21b49c47a 100644--- a/src/game/meetup-schedule.js+++ b/src/game/meetup-schedule.js@@ -24,34 +24,32 @@ export const SOON_MS = 24 * 60 * 60 * 1000; // chip appears a day outexport const PRESHOW_MS = 30 * 60 * 1000; // stage powers up 30 min earlyexport const AFTERGLOW_MS = 20 * 60 * 1000; // linger 20 min after the end-// Parse one event out of a play-events.json document. Returns null when there-// is nothing valid to run, so callers can treat "no events" and "bad config"-// identically (the world simply stays normal).+// Parse the event out of /event.json (the same file src/game/event-countdown.js+// reads, so the pill and the in-world experience can never disagree). Returns+// null when there is nothing valid to run, so callers can treat "no event" and+// "bad config" identically (the world simply stays normal).export function parseEvent(doc) {- const raw = Array.isArray(doc?.events) ? doc.events.find((e) => e && e.startsAt) : null;- if (!raw) return null;- const startsAt = Date.parse(raw.startsAt);+ if (!doc || typeof doc !== 'object') return null;+ const startsAt = Date.parse(doc.startsAt);if (!Number.isFinite(startsAt)) return null;- const durationMin = Number(raw.durationMin);- const durationMs = (Number.isFinite(durationMin) && durationMin > 0 ? durationMin : 60) * 60 * 1000;- const agenda = (Array.isArray(raw.agenda) ? raw.agenda : [])+ const rawEnd = Date.parse(doc.endsAt);+ // Same default event-countdown.js uses: a missing end keeps it live 6 hours.+ const endsAt = Number.isFinite(rawEnd) && rawEnd > startsAt ? rawEnd : startsAt + 6 * 3600 * 1000;+ const agenda = (Array.isArray(doc.agenda) ? doc.agenda : []).map((seg) => ({atMin: Number(seg?.atMin),title: String(seg?.title || '').slice(0, 80),detail: String(seg?.detail || '').slice(0, 200),icon: String(seg?.icon || '').slice(0, 8),- // Optional world-space anchor a client can drop a waypoint on.- x: Number.isFinite(Number(seg?.x)) ? Number(seg.x) : null,- z: Number.isFinite(Number(seg?.z)) ? Number(seg.z) : null,})).filter((seg) => Number.isFinite(seg.atMin) && seg.atMin >= 0 && seg.title).sort((a, b) => a.atMin - b.atMin);return {- id: String(raw.id || 'meetup').slice(0, 64),- title: String(raw.title || 'Community meetup').slice(0, 120),- subtitle: String(raw.subtitle || '').slice(0, 160),+ id: String(doc.id || 'event').slice(0, 64),+ title: String(doc.name || 'Community meetup').slice(0, 120),+ subtitle: String(doc.tagline || '').slice(0, 160),startsAt,- endsAt: startsAt + durationMs,+ endsAt,agenda,};}diff --git a/src/shared/event-config.js b/src/shared/event-config.jsnew file mode 100644index 000000000..eeaa174f9--- /dev/null+++ b/src/shared/event-config.js@@ -0,0 +1,105 @@+// The one reader of public/event.json.+//+// The event window lives in exactly one file (`public/event.json`, served at+// `/event.json`) and every countdown surface reads it through here: the `/play`+// lobby banner and in-world pill (src/game/event-countdown.js) and the home page+// strip (src/home-event-banner.js). Two surfaces reading two copies of a start+// time is how a countdown ends up disagreeing with itself on the day, so the+// parsing, the state machine, and the clock formatting are all shared.+//+// Everything here is browser-only and dependency-free.++const CONFIG_URL = '/event.json';++// An event with no (or unparseable) end time stays live for this long.+const DEFAULT_DURATION_MS = 6 * 3600 * 1000;++/**+ * Normalize the raw JSON into a config, or null when there is nothing to show.+ * A missing/malformed start time is the only fatal problem: without it there is+ * no countdown to run, and the page owes the visitor zero pixels.+ */+export function parseEventConfig(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const startsAt = Date.parse(raw.startsAt);+ if (!Number.isFinite(startsAt)) return null;+ const endsAt = Date.parse(raw.endsAt);+ return {+ name: String(raw.name || 'Live event'),+ tagline: raw.tagline ? String(raw.tagline) : '',+ startsAt,+ endsAt: Number.isFinite(endsAt) ? endsAt : startsAt + DEFAULT_DURATION_MS,+ link: raw.link ? String(raw.link) : null,+ linkLabel: raw.linkLabel ? String(raw.linkLabel) : 'Join the event',+ };+}++/**+ * Fetch and parse the event config. Returns null when the file is absent,+ * unreadable, malformed, or describes an event that has already ended, so a+ * caller can treat null as "mount nothing" without a second check.+ */+export async function loadEventConfig(now = Date.now()) {+ let cfg = null;+ try {+ const res = await fetch(CONFIG_URL, { cache: 'no-cache' });+ if (!res.ok) return null;+ cfg = parseEventConfig(await res.json());+ } catch {+ return null;+ }+ if (!cfg || now >= cfg.endsAt) return null;+ return cfg;+}++/** 'upcoming' before the start, 'live' during, 'over' once past the end. */+export function eventState(cfg, now = Date.now()) {+ if (now >= cfg.endsAt) return 'over';+ return now >= cfg.startsAt ? 'live' : 'upcoming';+}++/** Break a millisecond span into whole days, hours, minutes, and seconds. */+export function segments(ms) {+ const s = Math.max(0, Math.floor(ms / 1000));+ return {+ d: Math.floor(s / 86400),+ h: Math.floor((s % 86400) / 3600),+ m: Math.floor((s % 3600) / 60),+ s: s % 60,+ };+}++export function pad(n) {+ return String(n).padStart(2, '0');+}++/** `3d 04:11:07` while a day or more remains, `04:11:07` after that. */+export function clockString(ms) {+ const t = segments(ms);+ return (t.d > 0 ? `${t.d}d ` : '') + `${pad(t.h)}:${pad(t.m)}:${pad(t.s)}`;+}++/** The start time in the visitor's own timezone, named so it cannot be misread. */+export function formatStart(ts) {+ return new Intl.DateTimeFormat(undefined, {+ weekday: 'short', month: 'short', day: 'numeric',+ hour: 'numeric', minute: '2-digit', timeZoneName: 'short',+ }).format(new Date(ts));+}++/**+ * True when the visitor is already standing in the event world, which makes the+ * "join" CTA a link to where they are. Compares the coin param of the event link+ * against the current URL's.+ */+export function alreadyAtEvent(cfg, url = location.href) {+ if (!cfg.link) return false;+ try {+ const here = new URL(url);+ const target = new URL(cfg.link, here.origin);+ const targetCoin = target.searchParams.get('coin');+ return !!targetCoin && targetCoin === here.searchParams.get('coin');+ } catch {+ return false;+ }+}diff --git a/tests/meetup-schedule.test.js b/tests/meetup-schedule.test.jsindex 710adbe16..244bd8b31 100644--- a/tests/meetup-schedule.test.js+++ b/tests/meetup-schedule.test.js@@ -6,44 +6,41 @@ import {const START = Date.parse('2026-08-07T17:00:00Z');+// The flat /event.json shape shared with src/game/event-countdown.js.const DOC = {- events: [{- id: 'three-first-meetup',- title: '$THREE First Holders Meetup',- subtitle: 'The first live gathering in the world',- startsAt: '2026-08-07T17:00:00Z',- durationMin: 90,- agenda: [- { atMin: 0, title: 'Welcome to the plaza', icon: '👋' },- { atMin: 15, title: 'King of the Totem showdown', icon: '👑', x: 10, z: -5 },- { atMin: 40, title: 'Wheel hour', icon: '🎡' },- { atMin: 75, title: 'Fireworks finale', icon: '🎆' },- ],- }],+ id: 'three-first-meetup',+ name: '$THREE First Holders Meetup',+ tagline: 'The first live gathering in the world',+ startsAt: '2026-08-07T17:00:00Z',+ endsAt: '2026-08-07T19:00:00Z',+ agenda: [+ { atMin: 0, title: 'Doors open', icon: '👋' },+ { atMin: 20, title: 'King of the Totem showdown', icon: '👑' },+ { atMin: 45, title: 'Wheel hour', icon: '🎡' },+ { atMin: 105, title: 'Fireworks finale', icon: '🎆' },+ ],};describe('parseEvent', () => {- it('parses a valid event with sorted agenda and computed end', () => {+ it('parses the flat event.json shape', () => {const ev = parseEvent(DOC);expect(ev.id).toBe('three-first-meetup');+ expect(ev.title).toBe('$THREE First Holders Meetup');+ expect(ev.subtitle).toContain('first live gathering');expect(ev.startsAt).toBe(START);- expect(ev.endsAt).toBe(START + 90 * 60000);+ expect(ev.endsAt).toBe(START + 120 * 60000);expect(ev.agenda).toHaveLength(4);- expect(ev.agenda[1].x).toBe(10);- expect(ev.agenda[0].x).toBeNull();});it('sorts an out-of-order agenda and drops invalid segments', () => {const ev = parseEvent({- events: [{- startsAt: '2026-08-07T17:00:00Z',- agenda: [- { atMin: 30, title: 'B' },- { atMin: 0, title: 'A' },- { atMin: 'nope', title: 'bad' },- { atMin: 5, title: '' },- ],- }],+ startsAt: '2026-08-07T17:00:00Z',+ agenda: [+ { atMin: 30, title: 'B' },+ { atMin: 0, title: 'A' },+ { atMin: 'nope', title: 'bad' },+ { atMin: 5, title: '' },+ ],});expect(ev.agenda.map((s) => s.title)).toEqual(['A', 'B']);});@@ -51,13 +48,14 @@ describe('parseEvent', () => {it('returns null for empty, malformed, or dateless docs', () => {expect(parseEvent(null)).toBeNull();expect(parseEvent({})).toBeNull();- expect(parseEvent({ events: [] })).toBeNull();- expect(parseEvent({ events: [{ startsAt: 'not a date' }] })).toBeNull();+ expect(parseEvent({ startsAt: 'not a date' })).toBeNull();});- it('defaults duration to 60 minutes when missing or invalid', () => {- const ev = parseEvent({ events: [{ startsAt: '2026-08-07T17:00:00Z', durationMin: -3 }] });- expect(ev.endsAt - ev.startsAt).toBe(60 * 60000);+ it('defaults a missing or inverted end to 6 hours after start', () => {+ const noEnd = parseEvent({ startsAt: '2026-08-07T17:00:00Z' });+ expect(noEnd.endsAt - noEnd.startsAt).toBe(6 * 3600 * 1000);+ const inverted = parseEvent({ startsAt: '2026-08-07T17:00:00Z', endsAt: '2026-08-07T16:00:00Z' });+ expect(inverted.endsAt - inverted.startsAt).toBe(6 * 3600 * 1000);});});@@ -81,24 +79,24 @@ describe('eventState phases', () => {it('counts down to start', () => {const s = eventState(ev, START - 90_000);expect(s.msToStart).toBe(90_000);- expect(s.next.title).toBe('Welcome to the plaza');+ expect(s.next.title).toBe('Doors open');});it('tracks the active and next segments while live', () => {- const s = eventState(ev, START + 16 * 60000);+ const s = eventState(ev, START + 21 * 60000);expect(s.active.title).toBe('King of the Totem showdown');expect(s.next.title).toBe('Wheel hour');- expect(s.msToNext).toBe((40 - 16) * 60000);+ expect(s.msToNext).toBe((45 - 21) * 60000);});it('has no next segment after the last one', () => {- const s = eventState(ev, START + 80 * 60000);+ const s = eventState(ev, START + 110 * 60000);expect(s.active.title).toBe('Fireworks finale');expect(s.next).toBeNull();});it('reports live progress', () => {- const s = eventState(ev, START + 45 * 60000);+ const s = eventState(ev, START + 60 * 60000);expect(s.progress).toBeCloseTo(0.5, 5);});});