Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/patches/bbc2bf7f95c4310c # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aienos.com#121 (code only) closed derived `bbc2bf7f95c4310c` #121 Imported from GitHub aien-dev/aienos.com#121 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `f1f7df434142d3b308cb83c3759f87c6ac5fb3a0` · Head `79a206040fb86144bf79338ce09ee9ee52c46f7b` github-advanced-security[bot] commented on `scripts/allen/allen_chat.py` line 1015 on 2026-10-26 16:40 UTC ## CodeQL / Uncontrolled data used in path expression This path depends on a user-provided value . This path depends on a user-provided value . Show more details github-advanced-security[bot] commented on `scripts/allen/allen_spool.py` line 168 on 2026-10-26 16:40 UTC ## CodeQL / Uncontrolled data used in path expression This path depends on a user-provided value . This path depends on a user-provided value . Show more details github-advanced-security[bot] commented on `scripts/allen/dev_proxy.py` line 49 on 2026-10-26 16:40 UTC ## CodeQL / Uncontrolled data used in path expression This path depends on a user-provided value . This path depends on a user-provided value . Show more details github-advanced-security[bot] commented on `scripts/allen/dev_proxy.py` line 51 on 2026-10-26 16:40 UTC ## CodeQL / Uncontrolled data used in path expression This path depends on a user-provided value . This path depends on a user-provided value . Show more details github-advanced-security[bot] commented on `scripts/allen/dev_proxy.py` line 76 on 2026-10-26 16:40 UTC ## CodeQL / Uncontrolled data used in path expression This path depends on a user-provided value . This path depends on a user-provided value . Show more details github-advanced-security[bot] commented on `scripts/allen/dev_proxy.py` line 35 on 2026-10-26 16:40 UTC ## CodeQL / HTTP Response Splitting This HTTP header is constructed from a user-provided value . This HTTP header is constructed from a user-provided value . This HTTP header is constructed from a user-provided value . Show more details github-advanced-security[bot] commented on `scripts/allen/dev_proxy.py` line 35 on 2026-10-26 16:40 UTC ## CodeQL / HTTP Response Splitting This HTTP header is constructed from a user-provided value . This HTTP header is constructed from a user-provided value . This HTTP header is constructed from a user-provided value . Show more details github-advanced-security[bot] commented on `public/js/allen.js` line 1262 on 2026-10-26 16:40 UTC ## CodeQL / Inefficient regular expression This part of the regular expression may cause exponential backtracking on strings starting with '|]*)?>)/iy;\n let at = 0;\n while (prefix.exec(source)) at = prefix.lastIndex;\n const head = /\\s*]*)?>/iy;\n head.lastIndex = at;\n if (head.exec(source)) return source.slice(0, head.lastIndex) + meta + source.slice(head.lastIndex);\n const lead = /^\\s*(?:]*>\\s*)?(?:]*)?>)?/i.exec(source)[0];\n return `${lead}${meta}${source.slice(lead.length)}`;\n }\n\n" + +note JavaScript checkEntry +text js6 " /* Project files and IndexedDB records share one format. */\n function checkEntry(p) {\n if (!shape(p, ['id', 'kind', 'title', 'revision', 'content', 'provenance'], ['geom', 'minimized'])) return 'unexpected or missing fields';\n let reason = check('pane.open', { v: VERSION, id: p.id, kind: p.kind, title: p.title });\n if (!reason) reason = check('pane.update', { v: VERSION, id: p.id, revision: p.revision, content: p.content, provenance: p.provenance }, p.kind);\n if (reason) return reason;\n if (own(p, 'geom') && !(shape(p.geom, ['x', 'y', 'w', 'h']) && ['x', 'y', 'w', 'h'].every(k => finite(p.geom[k])))) return 'invalid geometry';\n if (own(p, 'minimized') && typeof p.minimized !== 'boolean') return 'invalid minimized flag';\n return '';\n }\n function checkFile(data) {\n if (!shape(data, ['format', 'v', 'panes'], ['id', 'name', 'saved', 'exported']) || data.format !== FORMAT || data.v !== VERSION) return 'this is not an Aien panes file';\n for (const k of ['id', 'name', 'saved', 'exported']) if (own(data, k) && !isText(data[k], MAX_TITLE)) return `invalid ${k}`;\n if (!Array.isArray(data.panes) || data.panes.length > MAX_PANES) return `a file holds at most ${MAX_PANES} panes`;\n for (let i = 0; i < data.panes.length; i++) {\n const reason = checkEntry(data.panes[i]);\n if (reason) return `pane ${i + 1}: ${reason}`;\n }\n return '';\n }\n function limit(message) {\n const error = new Error(message);\n error.name = 'AllenLimit';\n return error;\n }\n function storageError(error) {\n const name = error && error.name;\n if (name === 'AllenLimit') return error.message;\n if (name === 'QuotaExceededError') return 'This browser refused: it has no storage space left for this site. Export the panes as a file instead.';\n if (name === 'SecurityError' || name === 'InvalidStateError' || name === 'AllenNoStore') return 'This browser does not allow storage here, for example in private browsing. Export the panes as a file instead.';\n const detail = error && error.message ? ` (${clean(error.message, 160)})` : '';\n return `This browser refused to store the project${detail}. Export the panes as a file instead.`;\n }\n function openDb() {\n return new Promise((resolve, reject) => {\n let request;\n try {\n if (!window.indexedDB) throw Object.assign(new Error('no IndexedDB'), { name: 'AllenNoStore' });\n request = window.indexedDB.open(DB_NAME, 1);\n } catch (error) {\n reject(error);\n return;\n }\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(DB_PROJECTS)) db.createObjectStore(DB_PROJECTS, { keyPath: 'id' });\n if (!db.objectStoreNames.contains(DB_INDEX)) db.createObjectStore(DB_INDEX, { keyPath: 'id' });\n };\n request.onsuccess = () => {\n const db = request.result;\n db.onversionchange = () => db.close();\n resolve(db);\n };\n request.onerror = () => reject(request.error || new Error('IndexedDB refused'));\n request.onblocked = () => reject(new Error('another tab holds the project store open'));\n });\n }\n function ask(request) {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n async function store(mode, work) {\n const db = await openDb();\n try {\n const tx = db.transaction([DB_PROJECTS, DB_INDEX], mode);\n const done = new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onabort = () => reject(tx.error || new Error('the storage transaction was aborted'));\n });\n let value;\n try {\n value = await work(tx.objectStore(DB_PROJECTS), tx.objectStore(DB_INDEX));\n } catch (error) {\n try {\n tx.abort();\n } catch (_) {}\n await done.catch(() => {});\n throw error;\n }\n await done;\n return value;\n } finally {\n db.close();\n }\n }\n function stamp(iso) {\n const when = new Date(iso);\n return Number.isNaN(when.getTime()) ? String(iso) : when.toLocaleString();\n }\n\n" + +note JavaScript mount +text js7 " function mount(host, options) {\n if (!(host instanceof Element)) throw new TypeError('AllenPanes.mount needs an element');\n const opts = options && typeof options === 'object' ? options : {};\n const panes = new Map();\n const closedIds = new Set();\n const closed = [];\n let order = [];\n let cascade = 0;\n let current = null;\n let alive = true;\n let fitting = 0;\n const root = el('div', 'allen-panes');\n const layer = el('div', 'allen-panes-layer');\n const dock = el('nav', 'allen-panes-dock');\n dock.setAttribute('aria-label', 'Aien panes');\n const chips = el('ul', 'allen-panes-chips');\n const projectsButton = button('allen-panes-tool', 'Projects: save, open, export or import panes', 'Projects', () => projectsPane());\n const exportButton = button('allen-panes-tool', 'Export the open panes as a JSON file', 'Export', () => exportOpen());\n const reopenButton = button('allen-panes-tool', '', 'Reopen', () => reopen());\n reopenButton.hidden = true;\n dock.append(chips, projectsButton, exportButton, reopenButton);\n const live = el('p', 'allen-panes-live');\n live.setAttribute('role', 'status');\n live.setAttribute('aria-live', 'polite');\n root.append(layer, dock, live);\n host.append(root);\n const media = typeof window.matchMedia === 'function' ? window.matchMedia(SHEET) : null;\n\n function say(message) {\n live.textContent = '';\n setTimeout(() => {\n if (alive) live.textContent = message;\n }, 60);\n if (typeof opts.announce === 'function') {\n try {\n opts.announce(message);\n } catch (_) {}\n }\n }\n function refuse(name, reason) {\n if (typeof opts.onRefuse === 'function') {\n try {\n opts.onRefuse(name, reason);\n } catch (_) {}\n }\n return { ok: false, reason };\n }\n function sheet() {\n return root.dataset.layout === 'sheet';\n }\n function layout() {\n root.dataset.layout = media && media.matches ? 'sheet' : 'float';\n refit();\n }\n function bounds() {\n return { w: Math.max(root.clientWidth, MIN_W), h: Math.max(root.clientHeight, MIN_H) };\n }\n function place(rec, x, y, w, h) {\n const b = bounds();\n const nw = Math.round(Math.min(Math.max(w, MIN_W), b.w));\n const nh = Math.round(Math.min(Math.max(h, MIN_H), b.h));\n const nx = Math.round(Math.min(Math.max(x, 0), b.w - nw));\n const ny = Math.round(Math.min(Math.max(y, 0), b.h - nh));\n rec.geom = { x: nx, y: ny, w: nw, h: nh };\n rec.el.style.transform = `translate(${nx}px, ${ny}px)`;\n rec.el.style.width = `${nw}px`;\n rec.el.style.height = `${nh}px`;\n }\n function refit() {\n for (const rec of panes.values()) place(rec, rec.geom.x, rec.geom.y, rec.geom.w, rec.geom.h);\n }\n function onResize() {\n if (!fitting) fitting = requestAnimationFrame(() => {\n fitting = 0;\n if (alive) refit();\n });\n }\n function initial(rec) {\n const b = bounds();\n const w = Math.min(560, b.w - 32);\n const h = Math.min(460, b.h - 160);\n const step = (cascade % 6) * 28;\n cascade += 1;\n place(rec, b.w - w - 32 - step, 76 + step, w, h);\n }\n function topmost() {\n for (let i = order.length - 1; i >= 0; i--) if (!order[i].minimized) return order[i];\n return null;\n }\n function chipState(rec) {\n rec.chipTitle.textContent = rec.title;\n rec.chip.setAttribute('aria-label', `${rec.title}, ${NAMES[rec.kind]} pane, ${rec.minimized ? 'minimized' : 'open'}`);\n rec.chip.dataset.state = rec.minimized ? 'minimized' : 'open';\n }\n function stack() {\n const top = topmost();\n order.forEach((rec, i) => {\n rec.el.style.zIndex = String(i + 1);\n rec.el.toggleAttribute('data-top', rec === top);\n rec.chip.toggleAttribute('data-top', rec === top);\n });\n dock.dataset.empty = panes.size ? 'no' : 'yes';\n }\n function raise(rec) {\n if (order[order.length - 1] !== rec) {\n order = order.filter(r => r !== rec);\n order.push(rec);\n }\n stack();\n }\n function owner(node) {\n for (const rec of panes.values()) if (rec.el.contains(node)) return rec;\n return null;\n }\n function label(rec) {\n rec.heading.textContent = rec.title;\n rec.move.setAttribute('aria-label', `Move ${rec.title}. Drag, or use the arrow keys; Shift moves farther.`);\n rec.size.setAttribute('aria-label', `Resize ${rec.title}. Drag, or use the arrow keys; Shift resizes farther.`);\n rec.min.setAttribute('aria-label', `Minimize ${rec.title}`);\n rec.max.setAttribute('aria-label', `Maximize ${rec.title}`);\n rec.max.setAttribute('aria-pressed', String(rec.maximized));\n rec.shut.setAttribute('aria-label', `Close ${rec.title}`);\n rec.grab.setAttribute('aria-label', `Minimize ${rec.title}. On a touch screen, swipe the top of the sheet down to minimize, or sideways for the next pane.`);\n chipState(rec);\n }\n function create(key, kind, title) {\n const rec = { id: key, kind, title: clean(title, MAX_TITLE) || NAMES[kind], revision: 0, content: null, provenance: null, geom: null, minimized: false, maximized: false, svg: null, app: null, projects: null };\n const pane = el('section', 'allen-pane');\n pane.dataset.kind = kind;\n pane.tabIndex = -1;\n pane.setAttribute('role', 'region');\n pane.setAttribute('aria-roledescription', 'pane');\n const head = el('header', 'allen-pane-head');\n const heading = el('h2', 'allen-pane-title');\n heading.id = uid('allen-pane-title');\n pane.setAttribute('aria-labelledby', heading.id);\n const move = button('allen-pane-move', '', '', null);\n const badge = el('span', 'allen-pane-badge');\n badge.hidden = true;\n const controls = el('div', 'allen-pane-controls');\n const min = button('allen-pane-ctl allen-pane-min', '', '\\u2212', () => minimize(rec));\n const max = button('allen-pane-ctl allen-pane-max', '', '\\u25a1', () => maximize(rec));\n const shut = button('allen-pane-ctl allen-pane-close', '', '\\u00d7', () => close(rec, true));\n controls.append(min, max, shut);\n head.append(move, el('span', 'allen-pane-kind', NAMES[kind]), heading, badge, controls);\n const notice = el('p', 'allen-pane-notice');\n notice.setAttribute('role', 'alert');\n notice.hidden = true;\n const body = el('div', 'allen-pane-body');\n body.tabIndex = 0;\n const source = el('details', 'allen-pane-source');\n source.hidden = true;\n const foot = el('div', 'allen-pane-foot');\n foot.hidden = true;\n const size = button('allen-pane-size', '', '', null);\n const grab = button('allen-pane-grab', '', '', () => minimize(rec));\n pane.append(grab, head, notice, body, source, foot, size);\n const item = el('li', 'allen-panes-item');\n const chip = button('allen-panes-chip', '', '', () => chipClick(rec));\n const chipTitle = el('span', 'allen-panes-chip-title');\n chip.append(el('span', 'allen-panes-chip-kind', NAMES[kind]), chipTitle);\n item.append(chip);\n Object.assign(rec, { el: pane, heading, badge, notice, body, source, foot, move, size, grab, min, max, shut, item, chip, chipTitle, swallow: 0 });\n label(rec);\n pane.addEventListener('pointerdown', () => raise(rec), true);\n pane.addEventListener('focusin', () => raise(rec));\n drag(rec, head, 'move');\n swipe(rec, head);\n swipe(rec, grab);\n pane.addEventListener('click', event => {\n if (event.timeStamp > rec.swallow) return;\n rec.swallow = 0;\n event.preventDefault();\n event.stopPropagation();\n }, true);\n drag(rec, size, 'size');\n keyed(rec, move, 'move');\n keyed(rec, size, 'size');\n layer.append(pane);\n chips.append(item);\n panes.set(key, rec);\n order.push(rec);\n initial(rec);\n stack();\n return rec;\n }\n /* Bottom sheet gestures, only on the grab strip and the title bar, so the\n content keeps its own scrolling, selection and editing. Down past a\n quarter of the sheet (or a quick flick) minimizes; sideways shows the\n neighbouring pane. A swipe never reaches the button it started on. */\n function swipe(rec, zone) {\n zone.addEventListener('pointerdown', event => {\n if (!sheet() || !event.isPrimary || event.button !== 0) return;\n const start = { x: event.clientX, y: event.clientY, t: event.timeStamp };\n const height = Math.max(1, rec.el.getBoundingClientRect().height);\n let mode = '';\n let last = event;\n let frame = 0;\n const paint = () => {\n frame = 0;\n if (!alive || !mode) return;\n const dx = last.clientX - start.x;\n const dy = last.clientY - start.y;\n rec.el.style.setProperty('--allen-pane-swipe-x', mode === 'side' ? `${Math.round(dx / 2)}px` : '0px');\n rec.el.style.setProperty('--allen-pane-swipe-y', mode === 'down' ? `${Math.round(Math.max(0, dy))}px` : '0px');\n };\n const settle = () => {\n rec.el.classList.remove('is-swiping');\n rec.el.style.removeProperty('--allen-pane-swipe-x');\n rec.el.style.removeProperty('--allen-pane-swipe-y');\n };\n const onMove = e => {\n if (e.pointerId !== event.pointerId) return;\n last = e;\n const dx = e.clientX - start.x;\n const dy = e.clientY - start.y;\n if (!mode) {\n if (Math.abs(dx) < 10 && Math.abs(dy) < 10) return;\n mode = Math.abs(dy) >= Math.abs(dx) ? (dy > 0 ? 'down' : 'up') : 'side';\n try {\n zone.setPointerCapture(e.pointerId);\n } catch (_) {}\n rec.el.classList.add('is-swiping');\n }\n if (mode !== 'up' && !frame) frame = requestAnimationFrame(paint);\n };\n const onEnd = e => {\n if (e.pointerId !== event.pointerId) return;\n zone.removeEventListener('pointermove', onMove);\n zone.removeEventListener('pointerup', onEnd);\n zone.removeEventListener('pointercancel', onEnd);\n if (frame) cancelAnimationFrame(frame);\n frame = 0;\n settle();\n if (!mode) return;\n rec.swallow = e.timeStamp + 500;\n if (e.type === 'pointercancel' || !alive) return;\n const dx = e.clientX - start.x;\n const dy = e.clientY - start.y;\n const speed = Math.max(Math.abs(dx), Math.abs(dy)) / Math.max(1, e.timeStamp - start.t);\n if (mode === 'down' && (dy > height / 4 || (dy > 24 && speed > 0.6))) minimize(rec);\n else if (mode === 'side' && (Math.abs(dx) > 72 || (Math.abs(dx) > 24 && speed > 0.6))) neighbour(rec, dx < 0 ? 1 : -1);\n };\n zone.addEventListener('pointermove', onMove);\n zone.addEventListener('pointerup', onEnd);\n zone.addEventListener('pointercancel', onEnd);\n });\n }\n function neighbour(rec, dir) {\n const all = [...panes.values()];\n if (all.length < 2) return;\n const next = all[(all.indexOf(rec) + dir + all.length) % all.length];\n const had = rec.el.contains(document.activeElement);\n restore(next, had);\n say(`${next.title}, pane ${all.indexOf(next) + 1} of ${all.length}.`);\n }\n function drag(rec, handle, mode) {\n handle.addEventListener('pointerdown', event => {\n if (event.button !== 0 || sheet() || rec.maximized) return;\n const hit = event.target.closest('button');\n if (mode === 'move' && hit && hit !== rec.move) return;\n event.preventDefault();\n raise(rec);\n const start = { x: event.clientX, y: event.clientY, g: { ...rec.geom } };\n let frame = 0;\n let last = null;\n try {\n handle.setPointerCapture(event.pointerId);\n } catch (_) {}\n rec.el.classList.add(mode === 'move' ? 'is-moving' : 'is-sizing');\n const apply = () => {\n frame = 0;\n if (!last || !alive) return;\n const dx = last.clientX - start.x;\n const dy = last.clientY - start.y;\n if (mode === 'move') place(rec, start.g.x + dx, start.g.y + dy, start.g.w, start.g.h);\n else place(rec, start.g.x, start.g.y, start.g.w + dx, start.g.h + dy);\n };\n const onMove = e => {\n if (e.pointerId !== event.pointerId) return;\n last = e;\n if (!frame) frame = requestAnimationFrame(apply);\n };\n const onUp = e => {\n if (e.pointerId !== event.pointerId) return;\n handle.removeEventListener('pointermove', onMove);\n handle.removeEventListener('pointerup', onUp);\n handle.removeEventListener('pointercancel', onUp);\n if (frame) cancelAnimationFrame(frame);\n apply();\n rec.el.classList.remove('is-moving', 'is-sizing');\n };\n handle.addEventListener('pointermove', onMove);\n handle.addEventListener('pointerup', onUp);\n handle.addEventListener('pointercancel', onUp);\n });\n }\n function keyed(rec, handle, mode) {\n handle.addEventListener('keydown', event => {\n const d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];\n if (!d || event.altKey || event.ctrlKey || event.metaKey || sheet() || rec.maximized) return;\n event.preventDefault();\n const s = event.shiftKey ? BIG_STEP : STEP;\n const g = rec.geom;\n if (mode === 'move') place(rec, g.x + d[0] * s, g.y + d[1] * s, g.w, g.h);\n else place(rec, g.x, g.y, g.w + d[0] * s, g.h + d[1] * s);\n });\n handle.addEventListener('keyup', event => {\n if (!event.key.startsWith('Arrow') || sheet() || rec.maximized) return;\n const g = rec.geom;\n say(mode === 'move' ? `${rec.title} at ${g.x}, ${g.y}.` : `${rec.title} is ${g.w} by ${g.h}.`);\n });\n }\n function minimize(rec) {\n if (rec.minimized) return;\n const had = rec.el.contains(document.activeElement);\n rec.minimized = true;\n rec.el.hidden = true;\n chipState(rec);\n stack();\n if (had) rec.chip.focus();\n say(`${rec.title} minimized; it stays in the pane list.`);\n }\n function restore(rec, focus) {\n if (rec.minimized) {\n rec.minimized = false;\n rec.el.hidden = false;\n chipState(rec);\n }\n raise(rec);\n if (focus) rec.el.focus({ preventScroll: true });\n }\n function maximize(rec) {\n rec.maximized = !rec.maximized;\n rec.el.classList.toggle('is-max', rec.maximized);\n label(rec);\n raise(rec);\n }\n function chipClick(rec) {\n if (rec.minimized) restore(rec, true);\n else if (topmost() === rec) minimize(rec);\n else restore(rec, true);\n }\n function dataPane(rec) {\n return KINDS.includes(rec.kind) && rec.revision > 0;\n }\n function entry(rec) {\n return { id: rec.id, kind: rec.kind, title: rec.title, revision: rec.revision, content: copy(rec.content), provenance: copy(rec.provenance), geom: { ...rec.geom }, minimized: rec.minimized };\n }\n function reopenState() {\n const last = closed[closed.length - 1];\n reopenButton.hidden = !last;\n if (last) reopenButton.setAttribute('aria-label', `Reopen ${last.title}`);\n }\n function close(rec, byPerson, quiet) {\n if (panes.get(rec.id) !== rec) return;\n const had = rec.el.contains(document.activeElement);\n stopApp(rec);\n rec.el.remove();\n rec.item.remove();\n panes.delete(rec.id);\n order = order.filter(r => r !== rec);\n const kept = dataPane(rec);\n if (kept) {\n closed.push(entry(rec));\n while (closed.length > MAX_CLOSED) closed.shift();\n }\n reopenState();\n stack();\n if (had) {\n const next = topmost();\n if (next) next.el.focus({ preventScroll: true });\n else if (opts.returnFocus instanceof HTMLElement && opts.returnFocus.isConnected) opts.returnFocus.focus();\n else projectsButton.focus();\n }\n if (!quiet) say(byPerson ? `${rec.title} closed.${kept ? ' Reopen brings it back.' : ''}` : `Aien closed ${rec.title}.`);\n if (typeof opts.onClose === 'function') {\n try {\n opts.onClose(rec.kind === 'card' ? rec.id.slice(5) : rec.id, rec.kind, byPerson);\n } catch (_) {}\n }\n }\n function reopen() {\n const last = closed.pop();\n reopenState();\n if (!last) return;\n const rec = restoreEntry(last);\n if (rec) {\n rec.el.focus({ preventScroll: true });\n say(`${rec.title} reopened.`);\n } else {\n closed.push(last);\n reopenState();\n say(`At most ${MAX_PANES} panes can be open. Close one to make room.`);\n }\n }\n function notify(rec, message) {\n rec.notice.textContent = message;\n rec.notice.hidden = false;\n }\n function waiting(rec) {\n rec.el.setAttribute('aria-busy', 'true');\n rec.body.replaceChildren(el('p', 'allen-pane-note', 'Aien is preparing this pane.'));\n }\n\n" + +note JavaScript apply +text js8 " function apply(rec, revision, content, prov) {\n stopApp(rec);\n rec.revision = revision;\n rec.content = copy(content);\n rec.provenance = copy(prov);\n rec.svg = null;\n rec.notice.hidden = true;\n rec.el.removeAttribute('aria-busy');\n rec.body.replaceChildren();\n render(rec);\n rec.badge.textContent = STATUS_NAMES[rec.provenance.status];\n rec.badge.dataset.status = rec.provenance.status;\n rec.badge.hidden = false;\n sourceBlock(rec);\n footBlock(rec);\n }\n function section(heading) {\n const box = el('section', 'allen-pane-section');\n box.append(el('h3', 'allen-pane-h3', heading));\n return box;\n }\n function refList(heading, items) {\n const box = section(heading);\n const list = el('ol', 'allen-pane-refs');\n for (const r of items) {\n const li = el('li');\n li.append(link(r.title, r.url));\n list.append(li);\n }\n box.append(list, el('p', 'allen-pane-label', 'Links are shown as given; this page never fetched or checked them.'));\n return box;\n }\n /* A diff or patch fence gets its own Copy and Download patch. The patch\n is only ever a downloaded file; nothing here applies it. */\n function patchTool(rec) {\n let n = 0;\n return (lang, text) => {\n if (!/^(diff|patch)$/i.test(lang) || !text.trim()) return null;\n n += 1;\n const name = `${slug(rec.title) || 'allen'}${n > 1 ? `-${n}` : ''}.patch`;\n const bar = el('div', 'allen-pane-bar allen-md-tools');\n const copyButton = button('allen-pane-act', `Copy patch ${n} of ${rec.title}`, 'Copy patch', () => copyText(`${text}\\n`, copyButton));\n bar.append(copyButton, button('allen-pane-act', `Download patch ${n} of ${rec.title} as ${name}; it is not applied anywhere`, 'Download patch', () => download(name, `${text}\\n`)));\n return bar;\n };\n }\n function render(rec) {\n const c = rec.content;\n const body = rec.body;\n body.append(el('p', 'allen-pane-caveat', CAVEATS[rec.provenance.status]));\n if (rec.kind === 'math') {\n const result = el('p', 'allen-pane-math', c.text);\n result.setAttribute('aria-label', `Result: ${c.text}`);\n body.append(result);\n if (own(c, 'tex')) body.append(texBlock(c.tex, 'The engine\\u2019s formula'));\n } else if (rec.kind === 'plot') {\n const drawn = plot(c, rec.title);\n rec.svg = drawn.svg;\n body.append(drawn.figure);\n } else if (rec.kind === 'doc') {\n body.append(markdown(c.markdown, el('div', 'allen-md'), patchTool(rec)));\n if (c.citations.length) body.append(refList('Citations', c.citations));\n } else if (rec.kind === 'code' || rec.kind === 'omega') {\n body.append(el('p', 'allen-pane-label', rec.kind === 'omega' ? 'Omega source' : `${clean(c.language, 40) || 'Code'} source`));\n const pre = el('pre', 'allen-pane-code');\n pre.append(el('code', '', c.source));\n body.append(pre);\n if (own(c, 'functions') && c.functions.length) {\n const box = section('Functions');\n const list = el('ul', 'allen-pane-fns');\n for (const f of c.functions) list.append(el('li', 'allen-pane-mono', `${f.name}(${f.params.map(p => `${p.name} ${p.type}`).join(', ')}) to ${f.ret}`));\n box.append(list);\n body.append(box);\n }\n if (own(c, 'wasm')) {\n const bytes = wasmBytes(c.wasm);\n const box = section('WebAssembly');\n if (bytes) {\n box.append(el('p', 'allen-pane-note', `${bytes.length} bytes. Offered as a file only; this page does not run it.`), button('allen-pane-act', `Download the WebAssembly of ${rec.title}`, 'Download .wasm', () => download(`${slug(rec.title) || 'omega'}.wasm`, bytes)));\n } else {\n box.append(el('p', 'allen-pane-note', 'WebAssembly was attached, but it is not a valid base64 WebAssembly module.'));\n }\n body.append(box);\n }\n } else if (rec.kind === 'app') {\n body.append(el('p', 'allen-pane-note', 'Aien wrote this app. It runs only when you press Run, in a sandbox with no access to this page, your cookies or the network.'));\n const bar = el('div', 'allen-pane-bar');\n const stage = el('div', 'allen-pane-stage');\n const run = button('allen-pane-act allen-pane-run', `Run ${rec.title} in a sandbox`, 'Run', () => runApp(rec, stage, run, stop));\n const stop = button('allen-pane-act', `Stop ${rec.title}`, 'Stop', () => stopApp(rec));\n stop.hidden = true;\n bar.append(run, stop);\n body.append(bar, stage);\n rec.app = { frame: null, run, stop };\n } else if (rec.kind === 'research') {\n const notes = section('Notes');\n notes.append(markdown(c.notes, el('div', 'allen-md'), patchTool(rec)));\n body.append(notes);\n if (c.hypotheses.length) {\n const box = section('Hypotheses');\n const list = el('ul', 'allen-md-list');\n for (const h of c.hypotheses) list.append(inline(el('li'), h));\n box.append(list);\n body.append(box);\n }\n if (c.derivations.length) {\n const box = section('Derivations');\n const list = el('ol', 'allen-pane-derivations');\n for (const d of c.derivations) {\n const li = el('li');\n li.append(el('pre', 'allen-pane-pre', d));\n list.append(li);\n }\n box.append(list);\n body.append(box);\n }\n if (c.sources.length) body.append(refList('Sources', c.sources));\n } else if (rec.kind === 'data') {\n const grid = table(c.columns, c.rows);\n grid.firstChild.setAttribute('aria-labelledby', rec.heading.id);\n body.append(grid);\n }\n }\n function runApp(rec, stage, run, stop) {\n stopApp(rec);\n const frame = document.createElement('iframe');\n frame.setAttribute('sandbox', SANDBOX);\n frame.setAttribute('referrerpolicy', 'no-referrer');\n frame.setAttribute('allow', \"camera 'none'; microphone 'none'; geolocation 'none'; usb 'none'; serial 'none'; bluetooth 'none'; payment 'none'; display-capture 'none'; clipboard-read 'none'; clipboard-write 'none'; fullscreen 'none'\");\n frame.setAttribute('title', `${rec.title}, an app written by Aien, sandboxed`);\n frame.className = 'allen-pane-frame';\n frame.srcdoc = sandboxed(rec.content.html);\n stage.replaceChildren(frame);\n rec.app = { frame, run, stop };\n run.hidden = true;\n stop.hidden = false;\n stop.focus();\n }\n function stopApp(rec) {\n if (!rec.app || !rec.app.frame) return;\n const hadFocus = rec.el.contains(document.activeElement);\n rec.app.frame.remove();\n rec.app.frame = null;\n rec.app.run.hidden = false;\n rec.app.stop.hidden = true;\n if (hadFocus && rec.app.run.isConnected) rec.app.run.focus();\n }\n function sourceBlock(rec) {\n const list = el('dl', 'allen-pane-prov');\n const row = (key, value, mono) => {\n if (value === '') return;\n list.append(el('dt', '', key), el('dd', mono ? 'allen-pane-mono' : '', value));\n };\n const p = rec.provenance;\n row('Status', STATUS_NAMES[p.status]);\n row('Engine', p.engine);\n row('Expression', p.expression, true);\n row('Result', p.result, true);\n row('Source', p.source);\n row('Commit', p.commit, true);\n row('Pane', rec.id, true);\n row('Revision', String(rec.revision));\n const raw = el('pre', 'allen-pane-raw', JSON.stringify({ content: rec.content, provenance: rec.provenance }, null, 2));\n raw.setAttribute('aria-label', `Everything Aien sent for ${rec.title}, as JSON`);\n raw.tabIndex = 0;\n rec.source.replaceChildren(el('summary', 'allen-pane-summary', 'Source and provenance'), list, el('p', 'allen-pane-label', 'As received'), raw);\n rec.source.hidden = false;\n }\n function footBlock(rec) {\n const out = artefact(rec);\n if (!out) return;\n const base = slug(rec.title) || rec.kind;\n const ext = out.name.slice(out.name.lastIndexOf('.'));\n const copyButton = button('allen-pane-act', `Copy the ${out.what} of ${rec.title}`, 'Copy', () => copyText(out.copy, copyButton));\n const save = button('allen-pane-act', `Download ${rec.title} as ${ext}`, `Download ${ext}`, () => download(out.name, out.data()));\n const json = button('allen-pane-act', `Download ${rec.title} with its provenance as JSON`, 'Download .json', () => download(`${base}.json`, JSON.stringify(file([entry(rec)], rec.title), null, 2)));\n rec.foot.replaceChildren(copyButton, save, json);\n const keep = reportSave(rec);\n if (keep) rec.foot.append(...keep);\n rec.foot.hidden = false;\n }\n /* A repo report can become the visitor's own Omega project, only when the\n page supplies saveProject and only after the visitor has seen the file\n list and pressed Save. The page owns the request and the visitor's\n handle; this file never touches the network. */\n function reportSave(rec) {\n if (rec.kind !== 'doc' || typeof opts.saveProject !== 'function') return null;\n const named = REPORT.exec(rec.title);\n if (!named) return null;\n const files = reportFiles(rec.content.markdown);\n const repo = `${named[1]}/${named[2]}`;\n const ports = files.filter(f => f.path.endsWith('.om')).length;\n const box = el('div', 'allen-pane-save');\n box.hidden = true;\n const state = el('p', 'allen-projects-state');\n state.setAttribute('role', 'status');\n const open = button('allen-pane-act allen-pane-run', `Save ${rec.title} to my Omega projects`, 'Save to my Omega projects', () => {\n box.hidden = !box.hidden;\n open.setAttribute('aria-expanded', String(!box.hidden));\n if (!box.hidden) confirm.focus();\n });\n open.setAttribute('aria-expanded', 'false');\n const list = el('ul', 'allen-pane-files');\n for (const f of files) list.append(el('li', 'allen-pane-mono', `${f.path}, ${utf8(f.content)} bytes`));\n const confirm = button('allen-pane-act allen-pane-run', `Save these ${files.length} files as an Omega project`, `Save ${files.length} file${files.length === 1 ? '' : 's'}`, async () => {\n confirm.disabled = true;\n state.replaceChildren(document.createTextNode('Saving.'));\n let r;\n try {\n r = await opts.saveProject({ project: slug(`${named[1]}-${named[2]}`) || 'allen-report', title: `Omega path for ${repo}`, description: `Aien's report on ${repo}${ports ? `, with ${ports} Omega port${ports === 1 ? '' : 's'}` : ''}.`, files: files.map(f => ({ path: f.path, content: f.content })) });\n } catch (_) {\n r = null;\n }\n confirm.disabled = false;\n if (r && r.ok === true) {\n state.replaceChildren(document.createTextNode('Saved. Status: '), statusLink(r.url));\n } else {\n state.replaceChildren(document.createTextNode(r && typeof r.reason === 'string' ? clean(r.reason, 300) : 'The project could not be saved; nothing was stored.'));\n }\n });\n const cancel = button('allen-pane-act', 'Do not save the report', 'Cancel', () => {\n box.hidden = true;\n open.setAttribute('aria-expanded', 'false');\n open.focus();\n });\n const bar = el('div', 'allen-pane-bar');\n bar.append(confirm, cancel);\n box.append(el('p', 'allen-pane-note', `These files become a project under your handle in Omega projects, for Drake to review before anything is published:`), list, bar);\n return [open, box, state];\n }\n function statusLink(url) {\n if (typeof url !== 'string' || !url) return document.createTextNode('no status address was returned.');\n if (/^\\/(?!\\/)/.test(url)) {\n try {\n const here = new URL(url, window.location.href);\n if (here.origin === window.location.origin) {\n const a = el('a', 'allen-link', here.pathname + here.search);\n a.href = here.href;\n return a;\n }\n } catch (_) {}\n }\n return link(url, url);\n }\n function download(name, data) {\n const blob = new Blob([data], { type: 'application/octet-stream' });\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = name;\n a.hidden = true;\n root.append(a);\n a.click();\n a.remove();\n setTimeout(() => URL.revokeObjectURL(url), 30000);\n }\n function file(entries, name) {\n return { format: FORMAT, v: VERSION, name: clean(name || 'Aien panes', MAX_NAME), exported: new Date().toISOString(), panes: entries };\n }\n function snapshot() {\n return order.filter(dataPane).map(entry);\n }\n function exportOpen() {\n const entries = snapshot();\n if (!entries.length) {\n say('There are no panes with content to export yet.');\n return { ok: false, reason: 'nothing to export' };\n }\n download('aien-panes.json', JSON.stringify(file(entries, current ? current.name : 'Aien panes'), null, 2));\n say(`Exported ${entries.length} pane${entries.length === 1 ? '' : 's'} as a JSON file.`);\n return { ok: true, count: entries.length };\n }\n function restoreEntry(p) {\n if (panes.size >= MAX_PANES) return null;\n let key = p.id;\n for (let n = 2; panes.has(key) && n < 100; n++) key = `${p.id.slice(0, 58)}-${n}`;\n if (panes.has(key)) return null;\n const rec = create(key, p.kind, p.title);\n apply(rec, p.revision, p.content, p.provenance);\n if (p.geom) place(rec, p.geom.x, p.geom.y, p.geom.w, p.geom.h);\n if (p.minimized) {\n rec.minimized = true;\n rec.el.hidden = true;\n chipState(rec);\n }\n stack();\n return rec;\n }\n function restoreAll(data) {\n const room = MAX_PANES - panes.size;\n if (data.panes.length > room) return { ok: false, reason: `Only ${room} more pane${room === 1 ? '' : 's'} fit; close some panes first.` };\n for (const p of data.panes) restoreEntry(p);\n return { ok: true, count: data.panes.length };\n }\n\n" + +note JavaScript list +text js9 " /* Projects: IndexedDB only after an explicit save; an index store keeps\n the list cheap to read. */\n async function list() {\n try {\n const items = await store('readonly', (_, index) => ask(index.getAll()));\n items.sort((a, b) => String(b.saved).localeCompare(String(a.saved)));\n return { ok: true, projects: items.map(i => ({ id: i.id, name: i.name, saved: i.saved, count: i.count })) };\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n }\n async function save(name) {\n const entries = snapshot();\n if (!entries.length) return { ok: false, reason: 'There are no panes with content to save yet.' };\n const title = clean(name || '', MAX_NAME) || (current ? current.name : `Project ${new Date().toLocaleString()}`);\n const id = current && current.name === title ? current.id : `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;\n const record = { format: FORMAT, v: VERSION, id, name: title, saved: new Date().toISOString(), panes: entries };\n const bytes = utf8(JSON.stringify(record));\n if (bytes > MAX_PROJECT_BYTES) return { ok: false, reason: `This project is ${bytes} bytes; one project holds at most ${MAX_PROJECT_BYTES}. Export it as a file instead.` };\n try {\n await store('readwrite', async (projects, index) => {\n const existing = await ask(index.get(id));\n const count = await ask(index.count());\n if (!existing && count >= MAX_PROJECTS) throw limit(`${MAX_PROJECTS} projects are saved in this browser; delete one first, or export instead.`);\n await ask(projects.put(record));\n await ask(index.put({ id, name: title, saved: record.saved, count: entries.length }));\n });\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n current = { id, name: title };\n return { ok: true, id, name: title, count: entries.length };\n }\n async function load(id) {\n let record;\n try {\n record = await store('readonly', projects => ask(projects.get(String(id))));\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n if (!record) return { ok: false, reason: 'That project is no longer saved in this browser.' };\n const reason = checkFile(record);\n if (reason) return { ok: false, reason: `The saved project could not be read: ${reason}.` };\n const done = restoreAll(record);\n if (done.ok) current = { id: record.id, name: record.name };\n return done.ok ? { ok: true, id: record.id, name: record.name, count: done.count } : done;\n }\n async function remove(id) {\n try {\n await store('readwrite', (projects, index) => Promise.all([ask(projects.delete(String(id))), ask(index.delete(String(id)))]));\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n if (current && current.id === id) current = null;\n return { ok: true, id };\n }\n async function exportSaved(id) {\n let record;\n try {\n record = await store('readonly', projects => ask(projects.get(String(id))));\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n if (!record) return { ok: false, reason: 'That project is no longer saved in this browser.' };\n download(`${slug(record.name) || 'allen-project'}.json`, JSON.stringify(record, null, 2));\n return { ok: true, id };\n }\n async function importFile(source) {\n let text;\n if (typeof source === 'string') text = source;\n else if (source && typeof source.text === 'function' && typeof source.size === 'number') {\n if (source.size > MAX_PROJECT_BYTES) return { ok: false, reason: `A project file holds at most ${MAX_PROJECT_BYTES} bytes.` };\n try {\n text = await source.text();\n } catch (_) {\n return { ok: false, reason: 'This browser could not read the file.' };\n }\n } else return { ok: false, reason: 'Import takes a project file or its JSON text.' };\n if (utf8(text) > MAX_PROJECT_BYTES) return { ok: false, reason: `A project file holds at most ${MAX_PROJECT_BYTES} bytes.` };\n let data;\n try {\n data = JSON.parse(text);\n } catch (_) {\n return { ok: false, reason: 'That file is not JSON.' };\n }\n const reason = checkFile(data);\n if (reason) return { ok: false, reason: `That file was refused: ${reason}.` };\n return restoreAll(data);\n }\n function project(command, arg) {\n if (!alive) return Promise.resolve({ ok: false, reason: 'unmounted' });\n if (command === 'save') return save(arg);\n if (command === 'list') return list();\n if (command === 'open') return load(arg);\n if (command === 'remove') return remove(arg);\n if (command === 'export') return arg === undefined ? Promise.resolve(exportOpen()) : exportSaved(arg);\n if (command === 'import') return importFile(arg);\n if (command === undefined || command === 'panel') {\n projectsPane();\n return Promise.resolve({ ok: true });\n }\n return Promise.resolve({ ok: false, reason: 'unknown project command' });\n }\n function projectsPane() {\n let rec = panes.get('#projects');\n if (rec) {\n restore(rec, true);\n refreshProjects(rec);\n return;\n }\n if (panes.size >= MAX_PANES) {\n say(`At most ${MAX_PANES} panes can be open. Close one to make room.`);\n return;\n }\n rec = create('#projects', 'projects', 'Projects');\n const body = rec.body;\n const status = el('p', 'allen-projects-state');\n status.setAttribute('role', 'status');\n const show = r => {\n status.textContent = r.ok ? r.message : r.reason;\n };\n const form = el('form', 'allen-projects-form');\n const nameId = uid('allen-project-name');\n const nameLabel = el('label', 'allen-pane-label', 'Project name');\n nameLabel.htmlFor = nameId;\n const input = el('input', 'allen-projects-name');\n input.id = nameId;\n input.type = 'text';\n input.maxLength = MAX_NAME;\n input.autocomplete = 'off';\n input.value = current ? current.name : '';\n const submit = el('button', 'allen-pane-act allen-pane-run', 'Save project');\n submit.type = 'submit';\n form.append(nameLabel, input, submit);\n form.addEventListener('submit', async event => {\n event.preventDefault();\n submit.disabled = true;\n const r = await save(input.value);\n submit.disabled = false;\n show(r.ok ? { ok: true, message: `Saved ${r.name} with ${r.count} pane${r.count === 1 ? '' : 's'} in this browser.` } : r);\n if (r.ok) {\n input.value = r.name;\n refreshProjects(rec);\n }\n });\n const saved = el('ul', 'allen-projects-list');\n const fileId = uid('allen-project-file');\n const fileLabel = el('label', 'allen-pane-label', 'Import a project file (.json)');\n fileLabel.htmlFor = fileId;\n const picker = el('input', 'allen-projects-file');\n picker.id = fileId;\n picker.type = 'file';\n picker.accept = 'application/json,.json';\n picker.addEventListener('change', async () => {\n const chosen = picker.files && picker.files[0];\n picker.value = '';\n if (!chosen) return;\n const r = await importFile(chosen);\n show(r.ok ? { ok: true, message: `Imported ${r.count} pane${r.count === 1 ? '' : 's'}. Nothing is stored until you press Save project.` } : r);\n });\n const exporter = button('allen-pane-act', 'Export the open panes as a JSON file', 'Export open panes', () => {\n const r = exportOpen();\n show(r.ok ? { ok: true, message: `Exported ${r.count} pane${r.count === 1 ? '' : 's'}.` } : { ok: false, reason: 'There are no panes with content to export yet.' });\n });\n const tools = el('div', 'allen-pane-bar');\n tools.append(exporter);\n const academy = el('p', 'allen-pane-note allen-projects-academy');\n academy.append(link('Train your agent', ACADEMY));\n body.append(el('p', 'allen-pane-note', 'Nothing is stored until you press Save project. A project keeps the open panes, their provenance and where they sit, in this browser only. Conversations are not part of a project.'), form, status, section('Saved in this browser'), saved, fileLabel, picker, tools, academy);\n if (typeof opts.syncSummary === 'function') body.append(summaryBox(show));\n rec.projects = { saved, show };\n refreshProjects(rec);\n rec.el.focus({ preventScroll: true });\n }\n /* Only when the page supplies syncSummary (a visitor with a remember key):\n a short summary the visitor reads and edits first, sent on one explicit\n click. Panes, code and data never leave the browser this way. */\n function draft() {\n const parts = snapshot().map(p => `${NAMES[p.kind]}: ${p.title}`);\n let text = `${current ? current.name : 'Project'}: ${parts.join('; ')}`;\n while (utf8(text) > SYNC_MAX) text = text.slice(0, -1);\n return text;\n }\n function summaryBox(show) {\n const box = section('Sync a short summary');\n const areaId = uid('allen-project-summary');\n const note = el('p', 'allen-pane-note', `Only this summary is sent, at most ${SYNC_MAX} bytes, never the panes, code or data. Aien keeps one project summary for you and replaces it each time. Edit it first if you like.`);\n const areaLabel = el('label', 'allen-pane-label', 'Summary to sync');\n areaLabel.htmlFor = areaId;\n const area = el('textarea', 'allen-projects-summary');\n area.id = areaId;\n area.rows = 3;\n area.value = draft();\n const count = el('p', 'allen-pane-label');\n const recount = () => {\n const n = utf8(area.value);\n count.textContent = `${n} of ${SYNC_MAX} bytes`;\n count.dataset.over = n > SYNC_MAX ? 'yes' : 'no';\n };\n area.addEventListener('input', recount);\n recount();\n const refresh = button('allen-pane-act', 'Write the summary again from the open panes', 'Draft again', () => {\n area.value = draft();\n recount();\n });\n const send = button('allen-pane-act allen-pane-run', 'Sync this short summary to Aien\\u2019s memory of you', 'Sync short summary', async () => {\n const text = area.value.trim();\n if (!text) return show({ ok: false, reason: 'The summary is empty.' });\n if (utf8(text) > SYNC_MAX) return show({ ok: false, reason: `The summary is over ${SYNC_MAX} bytes.` });\n send.disabled = true;\n let r;\n try {\n r = await opts.syncSummary(text);\n } catch (_) {\n r = null;\n }\n send.disabled = false;\n show(r && r.ok === true ? { ok: true, message: 'Synced the summary. Aien replaced the previous one.' } : { ok: false, reason: r && typeof r.reason === 'string' ? clean(r.reason, 300) : 'Aien could not sync the summary; nothing was stored.' });\n });\n const bar = el('div', 'allen-pane-bar');\n bar.append(refresh, send);\n box.append(note, areaLabel, area, count, bar);\n return box;\n }\n async function refreshProjects(rec) {\n const ui = rec.projects;\n if (!ui) return;\n const r = await list();\n if (!r.ok) {\n ui.saved.replaceChildren(el('li', 'allen-pane-note', r.reason));\n return;\n }\n if (!r.projects.length) {\n ui.saved.replaceChildren(el('li', 'allen-pane-note', 'No projects are saved in this browser.'));\n return;\n }\n ui.saved.replaceChildren(...r.projects.map(p => projectRow(rec, p)));\n }\n function projectRow(rec, p) {\n const name = clean(p.name, MAX_NAME) || 'Untitled';\n const li = el('li', 'allen-projects-item');\n const text = el('div', 'allen-projects-text');\n text.append(el('span', 'allen-projects-title', name), el('span', 'allen-projects-meta', `${p.count} pane${p.count === 1 ? '' : 's'}, saved ${stamp(p.saved)}`));\n const acts = el('div', 'allen-pane-bar');\n const open = button('allen-pane-act', `Open project ${name}`, 'Open', async () => {\n const r = await load(p.id);\n rec.projects.show(r.ok ? { ok: true, message: `Opened ${r.name}.` } : r);\n });\n const out = button('allen-pane-act', `Export project ${name} as a JSON file`, 'Export', async () => {\n const r = await exportSaved(p.id);\n rec.projects.show(r.ok ? { ok: true, message: `Exported ${name}.` } : r);\n });\n const del = button('allen-pane-act allen-pane-danger', `Delete project ${name} from this browser`, 'Delete', async () => {\n if (del.dataset.armed !== 'yes') {\n del.dataset.armed = 'yes';\n del.textContent = 'Confirm delete';\n del.setAttribute('aria-label', `Confirm: delete project ${name} from this browser`);\n setTimeout(() => {\n if (!del.isConnected) return;\n del.dataset.armed = '';\n del.textContent = 'Delete';\n del.setAttribute('aria-label', `Delete project ${name} from this browser`);\n }, 5000);\n return;\n }\n const r = await remove(p.id);\n rec.projects.show(r.ok ? { ok: true, message: `Deleted ${name} from this browser.` } : r);\n refreshProjects(rec);\n if (rec.el.contains(document.activeElement) || !document.activeElement || document.activeElement === document.body) rec.el.focus({ preventScroll: true });\n });\n acts.append(open, out, del);\n li.append(text, acts);\n return li;\n }\n\n" + +note JavaScript event +text js10 " /* The stream and the page call these. */\n function event(name, payload) {\n if (!alive) return { ok: false, reason: 'unmounted' };\n const id = plain(payload) && typeof payload.id === 'string' ? payload.id : '';\n const rec = ID.test(id) ? panes.get(id) : undefined;\n if (name === 'pane.close' && plain(payload) && !rec) {\n const bad = check(name, payload, '');\n if (bad) return refuse(name, bad);\n closedIds.add(id);\n return { ok: true, id };\n }\n if (name === 'pane.update' && !rec) return refuse(name, 'the pane is not open');\n const reason = check(name, payload, rec ? rec.kind : '');\n if (reason) {\n if (rec && name === 'pane.update') notify(rec, `Aien sent an update this page could not show (${reason}). The last good version stays.`);\n return refuse(name, reason);\n }\n if (name === 'pane.open') {\n if (rec || closedIds.has(id)) return refuse(name, 'that pane id was already opened');\n if (panes.size >= MAX_PANES) {\n say(`Aien tried to open another pane, but at most ${MAX_PANES} can be open. Close one to make room.`);\n return refuse(name, 'too many panes');\n }\n const made = create(id, payload.kind, payload.title);\n waiting(made);\n say(`Aien opened a ${NAMES[made.kind]} pane: ${made.title}.`);\n return { ok: true, id };\n }\n if (name === 'pane.update') {\n if (payload.revision <= rec.revision) return refuse(name, 'the revision is not newer');\n apply(rec, payload.revision, payload.content, payload.provenance);\n return { ok: true, id, revision: payload.revision };\n }\n closedIds.add(id);\n close(rec, false);\n return { ok: true, id };\n }\n function open(payload) {\n if (!plain(payload)) return refuse('open', 'open takes an object');\n const id = own(payload, 'id') ? payload.id : `local-${Date.now().toString(36)}${(serial += 1)}`;\n const opened = event('pane.open', { v: VERSION, id, kind: payload.kind, title: payload.title });\n if (!opened.ok || !own(payload, 'content')) return opened;\n const rec = panes.get(id);\n const prov = own(payload, 'provenance') ? payload.provenance : { status: 'unverified', engine: '', expression: '', result: '', source: 'this page', commit: '' };\n const updated = event('pane.update', { v: VERSION, id, revision: own(payload, 'revision') ? payload.revision : rec.revision + 1, content: payload.content, provenance: prov });\n if (!updated.ok) close(rec, false, true);\n return updated;\n }\n function openNode(spec) {\n if (!alive) return { ok: false, reason: 'unmounted' };\n const node = spec && spec.node;\n if (!(node instanceof Node) || node.nodeType === Node.DOCUMENT_NODE) return refuse('openNode', 'openNode takes a node built by this page');\n const id = spec && typeof spec.id === 'string' && ID.test(spec.id) ? spec.id : `card${(serial += 1)}`;\n const key = `card:${id}`;\n let rec = panes.get(key);\n if (!rec) {\n if (panes.size >= MAX_PANES) return refuse('openNode', 'too many panes');\n rec = create(key, 'card', typeof spec.title === 'string' ? spec.title : 'Aien');\n } else if (typeof spec.title === 'string') {\n rec.title = clean(spec.title, MAX_TITLE) || rec.title;\n label(rec);\n }\n rec.body.replaceChildren(node);\n restore(rec, spec.focus === true);\n return { ok: true, id, close: () => close(rec, false) };\n }\n function cycle(dir, from) {\n const stops = [...panes.values()].filter(r => !r.minimized).map(r => r.el);\n stops.push(dock);\n const at = stops.findIndex(s => s.contains(from));\n const next = stops[(at + dir + stops.length) % stops.length];\n if (next === dock) (chips.querySelector('button') || projectsButton).focus();\n else next.focus({ preventScroll: true });\n }\n function onKey(e) {\n if (e.defaultPrevented || !alive) return;\n if (e.key === 'Escape') {\n const inside = root.contains(e.target);\n const loose = e.target === document.body || e.target === document.documentElement || e.target === document;\n if (!inside && !loose) return;\n const rec = inside ? owner(e.target) : null;\n const target = rec && !rec.minimized ? rec : topmost();\n if (!target) return;\n e.preventDefault();\n minimize(target);\n return;\n }\n if (e.key === 'F6' && root.contains(e.target)) {\n e.preventDefault();\n cycle(e.shiftKey ? -1 : 1, e.target);\n }\n }\n function destroy() {\n if (!alive) return;\n for (const rec of panes.values()) stopApp(rec);\n alive = false;\n document.removeEventListener('keydown', onKey);\n window.removeEventListener('resize', onResize);\n if (media) {\n if (typeof media.removeEventListener === 'function') media.removeEventListener('change', layout);\n else if (typeof media.removeListener === 'function') media.removeListener(layout);\n }\n if (fitting) cancelAnimationFrame(fitting);\n root.remove();\n panes.clear();\n order = [];\n closed.length = 0;\n }\n\n" + +note JavaScript prelude +text js11 " document.addEventListener('keydown', onKey);\n window.addEventListener('resize', onResize);\n if (media) {\n if (typeof media.addEventListener === 'function') media.addEventListener('change', layout);\n else if (typeof media.addListener === 'function') media.addListener(layout);\n }\n layout();\n stack();\n return { event, open, openNode, project, destroy };\n }\n\n window.AllenPanes = Object.freeze({ version: VERSION, mount, check });\n window.dispatchEvent(new CustomEvent('allen-panes-ready', { detail: { version: VERSION } }));\n})();\n" + +fn main to int +if ne PLOTMAX 1.0e100f64 +trap 3 +end +js_0 +js_1 +js_2 +js_3 +js_4 +js_5 +js_6 +js_7 +js_8 +js_9 +js_10 +js_11 +if eq get marker 0 1 +trap 3 +end +flush +ret 0 +end + +fn js_0 to void +for b ulong len js0 +byteput get js0 b +end +end + +fn js_1 to void +for b ulong len js1 +byteput get js1 b +end +end + +fn js_2 to void +for b ulong len js2 +byteput get js2 b +end +end + +fn js_3 to void +for b ulong len js3 +byteput get js3 b +end +end + +fn js_4 to void +for b ulong len js4 +byteput get js4 b +end +end + +fn js_5 to void +for b ulong len js5 +byteput get js5 b +end +end + +fn js_6 to void +for b ulong len js6 +byteput get js6 b +end +end + +fn js_7 to void +for b ulong len js7 +byteput get js7 b +end +end + +fn js_8 to void +for b ulong len js8 +byteput get js8 b +end +end + +fn js_9 to void +for b ulong len js9 +byteput get js9 b +end +end + +fn js_10 to void +for b ulong len js10 +byteput get js10 b +end +end + +fn js_11 to void +for b ulong len js11 +byteput get js11 b +end +end diff --git a/om/allen-presence/NATIVE.md b/om/allen-presence/NATIVE.md new file mode 100644 index 0000000..3c37641 --- /dev/null +++ b/om/allen-presence/NATIVE.md @@ -0,0 +1,32 @@ +# Allen's native presence + +The visual reference is the native galaxy build in [aienux at da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c](https://github.com/aien-dev/aienux/tree/da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c/native/kernel/ui). Drake identifies this galaxy experience as the Allen he uses on his iMac. The available old machine report names an earlier build; it is not evidence that the newer galaxy never ran. The reference selection follows his current observation, not that stale report. No physical iMac was accessed or changed for this work. + +## What the native source does + +- `night.c` draws the photographic Milky Way layer, catalogue stars and galaxies, then the two lensing black holes. The native opening merges the holes at 12000 ms. Allen begins to gather at 12300 ms and completes formation at 15300 ms. +- `mind.c` draws a Fibonacci-lattice cloud, its nearest-neighbour threads, pale blue-white points, a blue/violet halo and a warm heart. Idle rotation uses `spin = 349`; the source describes a turn in 48 seconds. The breathing phase uses 5500 ms. Listening, thinking and speaking change the same stateful renderer, not a replacement icon. +- `allen_ui.c` places the heart at half the width and 40 percent of the height. Its reference layout is 1920 by 1080, with a 720 by 54 input bar at `height - 150`, all scaled by its native scale factor. +- While typing, key events light pulses upward through the mind and feed the ink field. On submission the typed line rises and fades over 900 ms. Nine thoughts leave on curved paths, starting at `150 + i * 40` ms, with duration `850 + hash(i, 1, 5) % 300` ms. Literal individual glyphs flying on each keystroke are a requested web enhancement, not a claim about the old native input renderer. +- Native replies appear below Allen, not as a transcript wall. Letters start 35 ms apart, fade in over 260 ms and rise by six reference pixels over 360 ms. They change from RGB(255,212,150) to RGB(234,238,252) over 900 ms. Each word pulses his heart. The native view holds only the current reply; the web adds an explicit session-history panel. +- The spinning tube is the native dusk/sleep transition, lasting 4200 ms. **The web opening on Allen's own screen reuses the iMac dusk scene.** The home door uses the native two-hole opening. Reordering dusk as an entrance is an intentional presentation choice, not the native boot order. + +These are source constants and source descriptions, not newly measured frame-rate claims. + +## Sound + +`chirp.c` is the only native sound generator. It produces the merger chirp from night time 11360 through 12300 ms, with the merger at 12000 ms. The generated browser WAV is synthesized by `om/allen-audio/chirp.om`, not a recorded imitation. The source contains no separate tube, birth, boom or voice-like sound. The browser therefore does not invent one. WebAudio starts only from a visitor's gesture; mute is a separate local preference. See `om/allen-audio/check.sh` for the independent original-C oracle and negative control. + +## Browser boundaries + +The page skeleton, transport client and presence controller are generated by seeded Omega. The native pixel renderer is temporarily compiled from the pinned original C to WebAssembly so its integer arithmetic and pixels can be compared directly. The page labels that boundary honestly; it does not claim that the C pixels were drawn by Omega. `om/allen-scene/provenance.txt` records the native renderer, its AGPL-3.0-or-later licence at that pin, and the Omega successor (aien-dev/omega-mv draft PR 811, incomplete). + +The accessible DOM remains responsible for the input, last reply, history, consent, controls and glass panes. The transport retains its existing same-origin routes. An anonymous session sends no visitor key. Remember-me and the X pixel remain separate explicit choices. Drake's speaker label is accepted only from the authenticated session channel's human event. Model text cannot choose it. + +Reduced motion leaves a static glow and reveals text without animated travel. Hidden documents stop drawing. The corner launcher and the full-screen canvas share the same renderer. The optional history belongs to the current tab; saving a project is a separate action. + +## Reproduction + +Regenerate the presence artifacts with `OMEGA_ACCEPT_CHANGE=1 sh om/allen-presence/check.sh`, and the page with `OMEGA_ACCEPT_CHANGE=1 sh om/allen-page/check.sh`. Run the same commands without acceptance to detect drift. Native renderer and audio regeneration have their own pinned recipes under `om/allen-scene` and `om/allen-audio`. Generated artifacts and their hash sidecars must be committed with their Omega sources. + +Pixel comparisons must name the native source pin, viewport, frame time and complete state sequence. Comparing different times or a QEMU screen that contains firmware UI is not a renderer parity verdict. Native-host parity and emulator-frame parity are separate observations. Production checks use canvas `getImageData` through `tab.evaluate`, not a screenshot command that hangs in this environment. No emulator or browser result qualifies physical iMac hardware. diff --git a/om/allen-presence/check.sh b/om/allen-presence/check.sh new file mode 100755 index 0000000..d7709f1 --- /dev/null +++ b/om/allen-presence/check.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# Build-only glue. The browser integration is authored in presence.om. +set -eu +cd "$(dirname "$0")" +omc=${OMEGA_OMC:-../hive-page/omc} +pin=$(tr -d ' \n' < ../hive-page/omc.sha256) +test "$(sha256sum "$omc" | cut -d' ' -f1)" = "$pin" || exit 3 +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT HUP INT TERM +"$omc" < presence.om > "$work/generate" +chmod +x "$work/generate" +"$work/generate" > "$work/first.js" 3> "$work/first.html" +"$work/generate" > "$work/second.js" 3> "$work/second.html" +[ -s "$work/first.js" ] || exit 6 +cmp "$work/first.html" "$work/second.html" +cmp "$work/first.js" "$work/second.js" +artifact=../../public/js/allen-presence.js +if ! cmp -s "$work/first.js" "$artifact"; then + [ "${OMEGA_ACCEPT_CHANGE:-0}" = 1 ] || { printf 'Presence artifact stale; regenerate with OMEGA_ACCEPT_CHANGE=1\n' >&2; exit 4; } + cp "$work/first.js" "$artifact" +fi +if ! cmp -s "$work/first.html" launcher.html; then + [ "${OMEGA_ACCEPT_CHANGE:-0}" = 1 ] || exit 4 + cp "$work/first.html" launcher.html +fi +sha256sum launcher.html > launcher.sha256 +sha256sum "$artifact" > presence.sha256 +printf 'Allen presence generator deterministic\n' diff --git a/om/allen-presence/launcher.html b/om/allen-presence/launcher.html new file mode 100644 index 0000000..ac51801 --- /dev/null +++ b/om/allen-presence/launcher.html @@ -0,0 +1 @@ +Speak to Aien diff --git a/om/allen-presence/launcher.sha256 b/om/allen-presence/launcher.sha256 new file mode 100644 index 0000000..0bf6c24 --- /dev/null +++ b/om/allen-presence/launcher.sha256 @@ -0,0 +1 @@ +ebb434d1d98c16fb14d8d9961e456b66cb95b179285e52ab1eb413f0da896a02 launcher.html diff --git a/om/allen-presence/presence.om b/om/allen-presence/presence.om new file mode 100644 index 0000000..a1174b5 --- /dev/null +++ b/om/allen-presence/presence.om @@ -0,0 +1,31 @@ +note Browser integration authored in Omega, emitted with the pinned seeded compiler. +note Native reply cadence is 35 ms per letter; 260 ms fade and 360 ms rise, allen_ui.c. +note No network text is parsed as markup. Transport and consent retain their separate owners. +text boot "/* Generated from om/allen-presence/presence.om. */\n(() => {\n'use strict';\nconst root = document.getElementById('allen');\nconst homeDoor = Boolean(root && root.closest('[data-home-door]'));\nconst reduced = matchMedia('(prefers-reduced-motion: reduce)');\nconst byId = id => document.getElementById(id);\nlet scene = null, panes = null, subscribed = false, entered = false;\nlet reply = '', painted = 0, timer = 0, cardId = 0;\nlet resolveReady, rejectReady;\nconst ready = new Promise((resolve,reject) => { resolveReady=resolve; rejectReady=reject; });\nready.catch(() => {});\nconst dispose = [];\nfunction status(text) { const node = byId('allen-status'); if (node) node.textContent = text; }\nfunction showSession(open) {\n const panel = byId('allen-session'), trigger = byId('allen-history');\n panel.hidden = !open; trigger.setAttribute('aria-expanded', String(open));\n if (open) { panel.tabIndex = -1; panel.focus(); } else trigger.focus();\n}\nfunction paintReply() {\n clearTimeout(timer); timer=0;\n const out = byId('allen-answer');\n if (!out || document.hidden || painted >= reply.length) return;\n if (reduced.matches) { painted=reply.length; out.textContent=reply; return; }\n const letter=String.fromCodePoint(reply.codePointAt(painted));\n if (scene && !/\\s/.test(letter) && (!painted || /\\s/.test(reply[painted-1]))) scene.speak(letter);\n const span=document.createElement('span'); span.className='allen-letter'; span.textContent=letter; out.append(span);\n painted+=letter.length;\n if (painted < reply.length) timer=setTimeout(paintReply,35);\n}\nfunction replaceReply(text, speaker) {\n clearTimeout(timer); timer=0; reply=String(text); painted=0;\n byId('allen-speaker').textContent=speaker;\n const out=byId('allen-answer'); out.textContent='';\n if (speaker==='Aien') out.dataset.speaker='allen'; else delete out.dataset.speaker;\n paintReply();\n}\nfunction mountScene() {\n if (!window.AllenScene || scene) return;\n const canvas=byId('allen-universe');\n if (!canvas) return;\n scene=window.AllenScene.mount(canvas,{compact:false,interactive:true,opening:homeDoor?'idle':'dusk'});\n window.allenPresenceScene=scene;\n scene.ready.then(() => {\n byId('allen-enter').disabled=false; resolveReady(scene);\n document.dispatchEvent(new CustomEvent('allen-presence-ready'));\n }, error => { rejectReady(error); byId('allen-enter').disabled=false; status('The scene could not load. You can still chat with Aien.'); });\n}\nfunction mountPanes() {\n if (!window.AllenPanes || panes) return;\n panes=window.AllenPanes.mount(byId('allen-panes'),{});\n}\nfunction enter(options={}) {\n if (entered) return; entered=true; root.dataset.entered='true';\n byId('allen-arrival').hidden=true;\n mountScene(); mountPanes();\n if (options.scene!==false && scene && !homeDoor) scene.enter('dusk');\n // Native dusk is silent. The home-door owner starts the merger chirp on a real gesture.\n byId('allen-input').focus();\n const initial=byId('allen-log').querySelector('.allen-msg-allen .allen-p');\n if (!reply && initial) replaceReply(initial.textContent,'Aien');\n}\nfunction audioLabel() {\n const muted=window.AllenAudio ? window.AllenAudio.muted() : true;\n const button=byId('allen-mute'); button.setAttribute('aria-pressed',String(muted)); button.textContent=muted?'Sound off':'Sound on';\n}\n" +text hooks "function connect() {\n if (!root || !window.allen || subscribed) return; subscribed=true;\n const api=window.allen;\n byId('allen-log').setAttribute('aria-live','off');\n dispose.push(api.on('send',event => {\n if (!entered) enter({scene:false});\n if (!event.silent) byId('allen-guest').textContent=event.text;\n replaceReply('','Aien');\n if (scene) { scene.key(event.text); scene.mode('think'); }\n byId('allen-regenerate').disabled=true;\n }));\n dispose.push(api.on('token',event => { reply+=event.text; if (!timer) paintReply(); }));\n dispose.push(api.on('reply',event => {\n if (!event.text.startsWith(reply.slice(0,painted))) replaceReply(event.text,'Aien');\n else { reply=event.text; if (!timer) paintReply(); }\n byId('allen-regenerate').disabled=false;\n if (scene) scene.mode('idle');\n }));\n dispose.push(api.on('error',event => { status(event.message); byId('allen-regenerate').disabled=false; if (scene) scene.mode('idle'); }));\n dispose.push(api.on('human',event => replaceReply(event.text,'Drake')));\n dispose.push(api.on('card',event => {\n mountPanes();\n if (panes && panes.openNode) panes.openNode({id:'chat-'+(++cardId),title:event.type==='relay'?'Message to Drake':event.type==='introduce'?'Remember me':'Aien · '+event.type,node:event.node});\n else showSession(true);\n }));\n for (const name of ['pane.open','pane.update','pane.close']) dispose.push(api.on(name,event => { mountPanes(); if (panes) panes.event(name,event); }));\n byId('allen-regenerate').addEventListener('click',() => api.regenerate());\n byId('allen-copy').addEventListener('click',async () => {\n try { await navigator.clipboard.writeText(reply); status('Reply copied.'); } catch (_) { status('Clipboard unavailable. Select the reply to copy it.'); }\n });\n byId('allen-introduce').addEventListener('click',() => showSession(true));\n byId('allen-new').addEventListener('click',() => {\n byId('allen-guest').textContent='';\n const hello=byId('allen-log').querySelector('.allen-msg-allen .allen-p');\n replaceReply(hello?hello.textContent:'','Aien');\n });\n}\nfunction full() {\n window.allenPresence=Object.freeze({ready,enter,scene:() => scene,panes:() => panes});\n byId('allen-enter').disabled=true;\n if (homeDoor) byId('allen-arrival').hidden=true;\n mountScene(); mountPanes(); connect(); audioLabel();\n byId('allen-enter').addEventListener('click',() => enter());\n byId('allen-history').addEventListener('click',() => showSession(byId('allen-session').hidden));\n byId('allen-mute').addEventListener('click',() => { if (window.AllenAudio) { window.AllenAudio.setMuted(!window.AllenAudio.muted()); audioLabel(); } });\n byId('allen-projects').addEventListener('click',() => { mountPanes(); if (panes && panes.project) panes.project(); });\n const input=byId('allen-input');\n input.addEventListener('input',event => {\n input.style.height='36px'; input.style.height=Math.min(120,input.scrollHeight)+'px';\n if (scene && event.data && !event.isComposing) scene.key(event.data);\n });\n document.addEventListener('keydown',event => {\n if (event.key==='Escape' && !byId('allen-session').hidden) { event.preventDefault(); showSession(false); }\n if ((event.ctrlKey || event.metaKey) && event.key==='/') { event.preventDefault(); input.focus(); }\n });\n document.addEventListener('visibilitychange',() => { if (!document.hidden && painted { if (reduced.matches) { clearTimeout(timer); timer=0; painted=reply.length; byId('allen-answer').textContent=reply; } });\n document.addEventListener('allen-ready',connect);\n document.addEventListener('allen-scene-ready',mountScene);\n document.addEventListener('allen-panes-ready',mountPanes);\n window.addEventListener('pagehide',() => { clearTimeout(timer); for (const off of dispose) off(); if (scene) scene.destroy(); if (panes) panes.destroy(); if (window.AllenAudio) window.AllenAudio.stop(); },{once:true});\n}\n" +text compact "function compact() {\n const launcher = byId('aien-allen-launcher');\n if (!launcher || !window.AllenScene) return;\n const canvas = launcher.querySelector('canvas');\n const small = window.AllenScene.mount(canvas,{compact:true,interactive:false});\n const aside = byId('aien-allen-intro');\n function intro(event) {\n if (event.detail.type === 'show' && window.aienAllenIntro) small.speak(window.aienAllenIntro.text.greeting);\n if (event.detail.type === 'reply-no' && window.aienAllenIntro) small.speak(window.aienAllenIntro.text.afterNo);\n }\n document.addEventListener('aien-allen-intro',intro);\n if (aside && !aside.hidden && window.aienAllenIntro) small.speak(window.aienAllenIntro.text.greeting);\n launcher.addEventListener('click', event => {\n if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || reduced.matches) return;\n event.preventDefault();\n launcher.classList.add('allen-launch-enter');\n const finish = () => location.assign(launcher.href);\n launcher.addEventListener('transitionend',finish,{once:true}); setTimeout(finish,450);\n });\n window.addEventListener('pagehide', () => { small.destroy(); document.removeEventListener('aien-allen-intro',intro); }, {once:true});\n}\nif (root) full(); else { compact(); if (!window.AllenScene) document.addEventListener('allen-scene-ready',compact,{once:true}); }\n})();\n" +text mobile "if(root) {\n let layoutFrame=0;\n function layout() {\n layoutFrame=0;\n const viewport=window.visualViewport;\n root.style.setProperty('--allen-view-height',(viewport?viewport.height:innerHeight)+'px');\n root.style.setProperty('--allen-view-top',(viewport?viewport.offsetTop:0)+'px');\n const bottom=root.querySelector('.allen-bottom');\n if(bottom) root.style.setProperty('--allen-panes-sheet-bottom',Math.max(0,root.getBoundingClientRect().bottom-bottom.getBoundingClientRect().top+8)+'px');\n }\n function requestLayout() {if(!layoutFrame) layoutFrame=requestAnimationFrame(layout);}\n window.addEventListener('resize',requestLayout);\n if(window.visualViewport) {visualViewport.addEventListener('resize',requestLayout);visualViewport.addEventListener('scroll',requestLayout);}\n const observer=new ResizeObserver(requestLayout); const bottom=root.querySelector('.allen-bottom');if(bottom)observer.observe(bottom);\n document.addEventListener('allen-pane-request',event => {\n const d=event.detail;mountPanes();\n if(!panes || !panes.openNode || !d || !(d.node instanceof Node))return;\n const handle=panes.openNode({id:d.id,title:d.title,node:d.node,focus:false});\n if(handle) {event.preventDefault();d.handle=handle;}\n });\n window.addEventListener('pagehide',() => {observer.disconnect();cancelAnimationFrame(layoutFrame);window.removeEventListener('resize',requestLayout);if(window.visualViewport){visualViewport.removeEventListener('resize',requestLayout);visualViewport.removeEventListener('scroll',requestLayout);}},{once:true});\n requestLayout();\n}\n" +text launcher "Speak to Aien\n" +fn main to int +w = write 1 boot 0 len boot +if ne w long len boot +ret 1 +end +w = write 1 hooks 0 len hooks +if ne w long len hooks +ret 1 +end +w = write 1 mobile 0 len mobile +if ne w long len mobile +ret 1 +end +w = write 1 compact 0 len compact +if ne w long len compact +ret 1 +end +w = write 3 launcher 0 len launcher +if ne w long len launcher +ret 1 +end +ret 0 +end diff --git a/om/allen-presence/presence.sha256 b/om/allen-presence/presence.sha256 new file mode 100644 index 0000000..09d64b8 --- /dev/null +++ b/om/allen-presence/presence.sha256 @@ -0,0 +1 @@ +ab0b3f9bddb16300a7ef38d213f5e6e424ade60c0651a66e080a230f431b5ec3 ../../public/js/allen-presence.js diff --git a/om/allen-scene/.crumb b/om/allen-scene/.crumb new file mode 100644 index 0000000..df348e4 --- /dev/null +++ b/om/allen-scene/.crumb @@ -0,0 +1,6 @@ +{ + "schema_version": "1.0.0", + "name": "allen-scene", + "layer": "website", + "purpose": "Native Allen scene reuse, Omega browser controller and independent frame oracle" +} diff --git a/om/allen-scene/adapter.c b/om/allen-scene/adapter.c new file mode 100644 index 0000000..3a6681c --- /dev/null +++ b/om/allen-scene/adapter.c @@ -0,0 +1,238 @@ +/* Temporary, explicitly authorized C-on-web boundary. Native implementation: + * aien-dev/aienux@da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c/native/kernel/ui. + * Files in native/ are unchanged. Replace this adapter and those C units with + * seeded Omega -> irwasm only after native-frame/audio parity, not by renaming C. + * The web opening reuses native DUSK, then native dawn/formation; this ordering + * is a web interaction, not the original two-hole boot sequence (replay=2). + * No I/O, imports, heap allocator, threads, GPU interface or browser privileges. + */ +#include "native/night.h" +#include "native/mind.h" +#include "native/flow.h" +#include "native/chirp.h" +#include "native/sky_real.h" + +void *memset(void *p, int c, size_t n) { unsigned char *q=p; while(n--) *q++=(unsigned char)c; return p; } +void *memcpy(void *d, const void *s, size_t n) { unsigned char *q=d; const unsigned char *p=s; while(n--) *q++=*p++; return d; } + +static struct { + ck_night night; + ck_mind mind; + ck_flow flow; + ck_night_picture kept; + ck_canvas cv; + ck_af_face face; + uint32_t *rgba, *back; + void *scratch, *keep; + int32_t w,h,cx,cy,far16; + uint32_t k,t,kind,compact,word_t,key_t; + int initialized; +} ui; +static int16_t audio[2*48000]; +#define S(v) ((int32_t)(((int64_t)(v)*(int64_t)ui.k+128)/256)) +#define EXPORT __attribute__((visibility("default"))) + +/* Verbatim state law from allen_ui.c:horizon_at; only struct ownership changes. */ +static void horizon_at(uint32_t d) +{ + ck_night_dusk k = {0}; + uint32_t q = ck_smooth(ck_prog(d, 0, 3400)); + q = (q * q >> 8) * q >> 8; + k.fallen = (int64_t)ui.far16 * ui.far16 * (int64_t)q >> 8; + k.swirl = 65536u * 6 / 10; + k.calm = S(120) * 16; + k.crowd = 256 + (768 * ck_smooth(ck_prog(d, 300, 2400)) >> 8); + k.e = (int32_t)((int64_t)S(90) * 16 * ck_smooth(ck_prog(d, 0, 2000)) >> 8); + int32_t rs0 = (int32_t)((int64_t)S(60) * 16 * ck_smooth(ck_prog(d, 0, 2000)) >> 8); + k.rs = rs0 + (int32_t)((int64_t)S(60) * 16 * ck_smooth(ck_prog(d, 3400, 4200)) >> 8); + uint32_t rise = ck_smooth(ck_prog(d, 900, 2800)), fall = 256 - ck_smooth(ck_prog(d, 3100, 3900)); + k.disk = rise < fall ? rise : fall; + k.beam = 16384u + d * 65536u / 9000u; + k.keep = 256 - ck_ease_out(ck_prog(d, 2800, 4000)); + k.near = S(260) * 16, k.far = ui.far16; + k.shade = 230 * ck_smooth(ck_prog(d, 400, 2600)) >> 8; + k.fine = S(300) * 16; + ck_night_fall(&ui.night, &k); +} + +/* Verbatim merger flash from allen_ui.c:flash/unflash. */ +static int flash(uint32_t t, int32_t *rad, uint32_t *a) +{ + if (t < CK_NIGHT_MERGE_MS || t >= CK_NIGHT_MERGE_MS + 1600) return 0; + uint32_t tm = t - CK_NIGHT_MERGE_MS; + *rad = (S(40) + (int32_t)((int64_t)S(220) * ck_ease_out(ck_prog(tm, 0, 1200)) >> 8)) * 16; + uint32_t rise = ck_smooth(ck_prog(tm, 0, 120)); + *a = rise * (ck_exp_neg(tm > 120 ? (tm - 120) * 256 / 450 : 0) >> 8) * 230 >> 16; + return *a > 0; +} +static void unflash(const ck_rect *r, uint32_t t) +{ + uint32_t tm=t-CK_NIGHT_MERGE_MS; + if(ui.night.holes!=1 || tm<100) return; + uint32_t keep=256-ck_smooth(ck_prog(tm,100,400)); + int32_t hx=ui.night.hole[0].x,hy=ui.night.hole[0].y,rs=ui.night.hole[0].rs; + ck_rect box={(hx-rs)>>4,(hy-rs)>>4,(2*rs>>4)+2,(2*rs>>4)+2}; + if(rs<=16 || !ck_clip(&box,r)) return; + for(int32_t y=box.y;y=(uint32_t)rs) continue; + uint32_t in=(uint32_t)rs-d>=16?256:((uint32_t)rs-d)*16; + uint32_t k=256-(in*(256-keep)>>8); + ui.back[(size_t)y*ui.w+x]=ck_scale(ui.back[(size_t)y*ui.w+x],k); + } +} + +EXPORT int scene_init(uint32_t w,uint32_t h,uint32_t compact) +{ + if(w<64 || h<64 || w>1920 || h>1920 || (uint64_t)w*h>2073600) return 0; + memset(&ui,0,sizeof ui); + ui.w=w;ui.h=h;ui.compact=compact; + ui.k=ck_min(w*256/1920,h*256/1080); + /* Compact is a native design-scale crop, not a different particle scene. */ + if(compact) ui.k=ck_min(w,h)*256/400; + ui.cx=w/2;ui.cy=compact?h/2:h*40/100; + size_t pix=(size_t)w*h*4; + size_t night=ck_night_mem_bytes(w,h,ui.k), kept=ck_night_picture_bytes(w,h); + size_t needed=3*pix+night+kept+262144+64; +#ifdef __wasm__ + extern unsigned char __heap_base; + uintptr_t base=((uintptr_t)&__heap_base+15)&~(uintptr_t)15; + size_t end=base+needed, pages=(end+65535)/65536; + size_t have=__builtin_wasm_memory_size(0); + if(pages>have && __builtin_wasm_memory_grow(0,pages-have)==(size_t)-1) return 0; + unsigned char *p=(unsigned char*)base; +#else + static unsigned char arena[64*1024*1024]; + if(needed>sizeof arena) return 0; + unsigned char *p=arena; +#endif + ui.rgba=(uint32_t*)p;p+=pix; + ui.back=(uint32_t*)p;p+=pix; + ui.scratch=p;p+=pix; + ui.cv=(ck_canvas){ui.back,(int32_t)w,(int32_t)h}; + if(ck_night_init(&ui.night,w,h,ui.k,ui.cx,ui.cy,p,night,ui.scratch)) return 0; + p+=night;ui.keep=p;p+=kept; + ck_af_face_init(&ui.face,ck_max(8,S(18)),1250,p,262144); + for(int c=CK_AF_FIRST;c<=CK_AF_LAST;c++) (void)ck_af_glyph_get(&ui.face,(char)c); + for(int i=0;i<4;i++) { + int64_t dx=(i&1?ui.w:0)-ui.cx,dy=(i&2?ui.h:0)-ui.cy; + ui.far16=ck_max(ui.far16,(int32_t)ck_isqrt((uint64_t)(dx*dx+dy*dy))*16); + } + ck_night_picture_take(&ui.night,ui.night.sky,ui.keep,&ui.kept); + ck_mind_init(&ui.mind,ui.cx,ui.cy,ui.k,12300); + ck_flow_init(&ui.flow,w,h,ui.cx,ui.cy,ui.mind.R,ui.cx,ui.h-S(177),0); + ui.initialized=1; + return 1; +} +EXPORT uintptr_t scene_pixels(void) { return (uintptr_t)ui.rgba; } +/* Native dusk consumes the whole preceding picture, not only the sky. For a + * fresh web opening use the original unwoken UI at 20000 ms: no bar/words and + * sleeping fluid, but the fully formed mind and twinkling sky are present. + * oracle-ui.c independently exercises original allen_ui.c for this state. */ +static void opening_picture(void) +{ + ck_rect all={0,0,ui.w,ui.h}; + ck_mind_init(&ui.mind,ui.cx,ui.cy,ui.k,12300); + for(uint32_t t=0;t<=20000;t+=16) ck_mind_at(&ui.mind,t); + ck_mind_at(&ui.mind,20000); + ck_night_at(&ui.night,20000); + ck_night_base(&ui.night,&ui.cv,&all); + ck_night_lights(&ui.night,&ui.cv,&all,0,0); + ck_mind_draw(&ui.mind,&ui.cv,&all); + ck_night_picture_take(&ui.night,ui.back,ui.keep,&ui.kept); +} +EXPORT void scene_enter(uint32_t kind) +{ + if(!ui.initialized) return; + ui.kind=kind>2?0:kind;ui.t=0;ui.word_t=ui.key_t=0; + if(kind==1) opening_picture(); + ck_mind_init(&ui.mind,ui.cx,ui.cy,ui.k,kind==1?4200:12300); + ck_flow_init(&ui.flow,ui.w,ui.h,ui.cx,ui.cy,ui.mind.R,ui.cx,ui.h-S(177),0); + if(kind!=1) ck_night_picture_take(&ui.night,ui.night.sky,ui.keep,&ui.kept); +} +EXPORT void scene_key(uint32_t t) { if(ui.initialized) {ck_mind_key(&ui.mind,t);ck_flow_key(&ui.flow,t);ui.key_t=t;} } +EXPORT void scene_word(uint32_t t) { if(ui.initialized) {ck_mind_word(&ui.mind,t);ck_flow_word(&ui.flow,t);ui.word_t=t;} } +EXPORT void scene_step(uint32_t t,uint32_t mode,uint32_t voice) +{ + if(!ui.initialized) return; + ui.t=t; + ck_mind_mode(&ui.mind,(int)(mode&3),t); + ck_mind_voice(&ui.mind,voice); + int formed=t>=ui.mind.born+CK_MIND_FORM_MS; + ck_flow_mode(&ui.flow,formed?(int)(mode&3):CK_FLOW_SLEEP,t); + if(!ui.compact) ck_flow_at(&ui.flow,t); + int32_t vx=0,vy=0; + if(!ui.compact) ck_flow_velocity(&ui.flow,ui.cx,ui.cy,&vx,&vy); + ui.mind.cx=ui.cx+ck_clamp(vx*S(10)/1000,-S(10),S(10)); + ui.mind.cy=ui.cy+ck_clamp(vy*S(10)/1000,-S(10),S(10)); + ck_mind_at(&ui.mind,t); +} +/* Native allen_ui.c per-word voice envelope; no browser floating approximation. */ +EXPORT uint32_t scene_voice(uint32_t t,uint32_t word) +{ + return t>=word?ck_exp_neg((t-word)*256/200)>>8:0; +} +EXPORT void scene_draw(uint32_t shimmer,uint32_t voice) +{ + if(!ui.initialized) return; + ck_rect all={0,0,ui.w,ui.h}; + uint32_t t=ui.t; + ck_night_at(&ui.night,ui.kind==2?t:20000); + if(ui.kind==1 && t<4200) { + horizon_at(t); + ck_night_base_from(&ui.night,&ui.kept,&ui.cv,&all); + } else { + ck_night_base(&ui.night,&ui.cv,&all); + ck_night_lights(&ui.night,&ui.cv,&all,shimmer,voice*shimmer>>9); + if(!ui.compact) ck_flow_draw(&ui.flow,&ui.cv,&all,256); + int32_t rad;uint32_t a; + if(ui.kind==2 && flash(t,&rad,&a)) { + ck_glow(&ui.cv,&all,ui.cx*16+8,ui.cy*16+8,rad,CK_RGB(200,210,255),a/3); + ck_glow(&ui.cv,&all,ui.cx*16+8,ui.cy*16+8,rad/3,CK_RGB(255,240,224),a); + unflash(&all,t); + } + ck_mind_draw(&ui.mind,&ui.cv,&all); + /* Native dawn duration is 900 ms; only its placement after dusk is web-specific. */ + if(ui.kind==1 && t<5100) { + uint32_t gain=ck_prog(t,4200,5100); + for(size_t i=0;i<(size_t)ui.w*ui.h;i++) ui.back[i]=ck_scale(ui.back[i],gain); + } + } + for(size_t i=0;i<(size_t)ui.w*ui.h;i++) { + uint32_t c=ui.back[i]; + ui.rgba[i]=0xff000000u|(c&0xff00u)|(c>>16&255u)|((c&255u)<<16); + } +} +/* Pan/zoom the source's existing sky camera; no generated replacement stars. */ +EXPORT int scene_view(int32_t ra,int32_t dec,int32_t fov) +{ + if(!ui.initialized || ra<0 || ra>360000000 || dec< -89000000 || dec>89000000 || fov<10000 || fov>120000) return 0; + ck_sky_view v; + if(ra==113697000 && dec== -72757000 && fov==80000) v=ck_sky_the_view; + else ck_sky_view_at(&v,ra,dec,fov,0); + ck_night_view(&ui.night,&v,ui.scratch); + ck_night_picture_take(&ui.night,ui.night.sky,ui.keep,&ui.kept); + return 1; +} +/* Native stroke glyph drawn above RGBA: no system or external font dependency. + * Letters flying from the web input are an intentional browser enhancement. */ +EXPORT void scene_glyph(uint32_t c,int32_t x,int32_t y,uint32_t alpha) +{ + if(!ui.initialized || c<32 || c>126 || alpha>256) return; + ck_rect all={0,0,ui.w,ui.h}; + (void)ck_letter(&ui.cv,&all,&ui.face,(uint64_t)ck_max(0,x)*256,y,(char)c,CK_RGB(206,222,255),alpha,1); + const ck_af_glyph *g=ck_af_glyph_get(&ui.face,(char)c); + if(!g) return; + ck_rect box={x+g->ox,y+g->oy,g->w,g->h}; + if(!ck_clip(&box,&all)) return; + for(int32_t yy=box.y;yy>16&255u)|((col&255u)<<16); + } +} +EXPORT uintptr_t scene_audio(uint32_t from,uint32_t frames) +{ + if(frames>48000 || from>CK_CHIRP_FRAMES) return 0; + ck_chirp_fill(audio,from,frames);return (uintptr_t)audio; +} diff --git a/om/allen-scene/artifacts.sha256 b/om/allen-scene/artifacts.sha256 new file mode 100644 index 0000000..30f2227 --- /dev/null +++ b/om/allen-scene/artifacts.sha256 @@ -0,0 +1,3 @@ +d20124bd97d9215db9120a1d516b661488f890b81a8c609b602e155eb29f4cde ../../public/js/allen-scene.js +a591d98abf8052379cfb50943ac95f46f3782d42a96aa3d3d6258b5bbc6e6002 ../../public/allen/scene.wasm +3c096604be03ec955a312561e420abe09abe41070cb2f10888fdc21ab984fb55 ../../public/allen/scene.om diff --git a/om/allen-scene/check-native.sh b/om/allen-scene/check-native.sh new file mode 100755 index 0000000..56141c4 --- /dev/null +++ b/om/allen-scene/check-native.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# Run under nice -n 19 ionice -c3. This is an independent verification oracle, +# not a production dependency and not an iMac/QEMU qualification receipt. +set -eu +root=$(CDPATH= cd -- "$(dirname "$0")/../.." && pwd) +ref=${ALLEN_NATIVE_SOURCE:?Set ALLEN_NATIVE_SOURCE to a clean aienux checkout at the exact reference pin} +pin=da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c +[ "$(git -C "$ref" rev-parse HEAD)" = "$pin" ] || { printf 'Original UI reference pin mismatch\n' >&2; exit 3; } +git -C "$ref" diff --quiet "$pin" -- native/kernel/ui native/kernel/svc/allen_scene.c native/kernel/svc/allen_scene.h native/kernel/svc/allen_code.c native/kernel/svc/allen_code.h || { printf 'Original UI reference modified\n' >&2; exit 3; } +work=$(mktemp -d "${TMPDIR:-/tmp}/allen-native-oracle.XXXXXX") +trap 'rm -rf "$work"' EXIT HUP INT TERM +ui=$ref/native/kernel/ui +svc=$ref/native/kernel/svc +scene=$root/om/allen-scene +cc=${CC:-cc} +"$cc" --version +"$cc" -O2 -fno-builtin "$scene/oracle.c" "$scene/adapter.c" \ + "$ui/mind.c" "$ui/night.c" "$ui/paint.c" "$ui/allen_font.c" "$ui/flow.c" \ + "$ui/sky_real.c" "$ui/sky_data.c" "$ui/chirp.c" -o "$work/adapter-oracle" +"$cc" -O2 -fno-builtin -I"$ui" "$scene/oracle-ui.c" \ + "$ui/mind.c" "$ui/night.c" "$ui/paint.c" "$ui/allen_font.c" "$ui/flow.c" \ + "$ui/sky_real.c" "$ui/sky_data.c" "$ui/canvas.c" \ + "$svc/allen_scene.c" "$svc/allen_code.c" -o "$work/original-ui-oracle" +cd "$root" +node om/allen-scene/test-parity.cjs "$work/adapter-oracle" public/allen/scene.wasm "$work/original-ui-oracle" +node om/allen-scene/test-controller.cjs diff --git a/om/allen-scene/check.sh b/om/allen-scene/check.sh new file mode 100755 index 0000000..9fea636 --- /dev/null +++ b/om/allen-scene/check.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# Build the explicitly-authorized native C/WASM dependency and Omega controller. +# --generate: generate artifacts once, no test claims. Default: deterministic +# regeneration and exact committed-artifact checks. No package installation. +set -eu +cd "$(dirname "$0")" +omc=${OMEGA_OMC:-../hive-page/omc} +clang=${ALLEN_CLANG:-clang-18} +ld=${ALLEN_WASM_LD:-wasm-ld-18} +pin=$(tr -d ' \n' < ../hive-page/omc.sha256) +have=$(sha256sum "$omc" | cut -d' ' -f1) +[ "$pin" = "$have" ] || { printf 'Wrong Omega compiler pin\n' >&2; exit 3; } +"$clang" --version | grep -F 'clang version 18.1.3' >/dev/null || { printf 'Native dependency requires clang 18.1.3\n' >&2; exit 3; } +"$ld" --version | grep -F '18.1.3' >/dev/null || { printf 'Native dependency requires wasm-ld 18.1.3\n' >&2; exit 3; } +sha256sum -c native.sha256 +work=$(mktemp -d "${TMPDIR:-/tmp}/allen-scene.XXXXXX") +trap 'rm -rf "$work"' EXIT HUP INT TERM +build_wasm() { + "$clang" --target=wasm32 -O2 -nostdlib -ffreestanding -fno-builtin \ + -ffunction-sections -fdata-sections -fvisibility=hidden -fno-ident \ + -Wl,--no-entry -Wl,--strip-all -Wl,--export-memory -Wl,--stack-first \ + -Wl,-z,stack-size=1048576 -Wl,--max-memory=67108864 -Wl,--gc-sections \ + -Wl,--export=scene_init -Wl,--export=scene_pixels -Wl,--export=scene_enter \ + -Wl,--export=scene_key -Wl,--export=scene_word -Wl,--export=scene_step \ + -Wl,--export=scene_draw -Wl,--export=scene_view -Wl,--export=scene_glyph \ + -Wl,--export=scene_audio -Wl,--export=scene_voice -fuse-ld="$ld" \ + adapter.c native/mind.c native/night.c native/paint.c native/allen_font.c \ + native/flow.c native/sky_real.c native/sky_data.c native/chirp.c -o "$1" +} +"$omc" < scene.om > "$work/controller" +chmod +x "$work/controller" +"$work/controller" > "$work/scene.js" +build_wasm "$work/scene.wasm" +if [ "${1:-}" != --generate ]; then + "$work/controller" > "$work/again.js" + build_wasm "$work/again.wasm" + cmp "$work/scene.js" "$work/again.js" + cmp "$work/scene.wasm" "$work/again.wasm" +fi +[ -s "$work/scene.js" ] && [ -s "$work/scene.wasm" ] || exit 6 +if [ "${1:-}" = --generate ] || [ "${OMEGA_ACCEPT_CHANGE:-0}" = 1 ]; then + mkdir -p ../../public/allen + cp "$work/scene.js" ../../public/js/allen-scene.js + cp "$work/scene.wasm" ../../public/allen/scene.wasm + cp scene.om ../../public/allen/scene.om + sha256sum ../../public/js/allen-scene.js ../../public/allen/scene.wasm ../../public/allen/scene.om > artifacts.sha256 +else + cmp "$work/scene.js" ../../public/js/allen-scene.js + cmp "$work/scene.wasm" ../../public/allen/scene.wasm + cmp scene.om ../../public/allen/scene.om + sha256sum -c artifacts.sha256 +fi +printf 'Generated native scene and Omega controller (no browser claim)\n' diff --git a/om/allen-scene/native.sha256 b/om/allen-scene/native.sha256 new file mode 100644 index 0000000..9e057ab --- /dev/null +++ b/om/allen-scene/native.sha256 @@ -0,0 +1,17 @@ +e89b9eb5ffce15f2e0a55a3a6d3a83f739d0c4bd5f3047a39e9ebf0c92e686ad native/mind.c +3fafe5b2a1f967f9cee392e5cba6b52774667fc7bcf89f9deecbfeae7a6c7cdf native/mind.h +b33e1d4ab71564c3c5e0da08c5d09ce28abfbf0a236fb595c9e1d94453e05214 native/night.c +5c434bf9ac9148042ce0d70b3f181a6a2f95cab5a378c4551bf0df0c4072e099 native/night.h +7afbe5627d21bd25b70fcf32ff42c294203ad8b152019566300678f2006715e2 native/paint.c +a107f4ffecb93dc4828129ac171363a4991732ed0cc2c0be0c0f1cff16393137 native/paint.h +92d7157386e65351325d80d5036565e406145230dfb696c9804ec80888d26904 native/allen_font.c +e26c3d5bc4c7c987a256dd066146a74da3e764623979a578e2cd0ecf43547fda native/allen_font.h +74438c92860501e20206c05a1a871894576b9403cfbf1b2444aa474c803adfff native/chirp.c +6555e35525eb8315e62bbee3737f98e352f5d5b825cde5e73d6f7dcbb2327b30 native/chirp.h +0da5f6c200e67db75834c252510fdaee247492972020099bbcade0258c9ae686 native/flow.c +c85ac637e0390dccc623a304bd9e8f1982b7ccf8da57407156012d470eb92901 native/flow.h +f7074249225e1d8b952eb478ed69012afcfac0d86f93702049a35c98fe511ba3 native/sky_real.c +216a50636c0aaf987ac97874926bba1170d7527a45ae96f12d00823ac4f289a8 native/sky_real.h +0f8cc32c4e59ca0dd62fa2131f6455d878faa89cce4fb00bcae73b4d1475e227 native/sky_data.c +ff1c3c7f884bed376c1eea244132b209f407358bbc01b3ef4c12a1b4810db54f native/sky_data.h +692eb7ae80de6dad4269c9be111c29c212721400b388b5172a498d0045023c55 native/sky_data.txt diff --git a/om/allen-scene/native/.crumb b/om/allen-scene/native/.crumb new file mode 100644 index 0000000..28a400f --- /dev/null +++ b/om/allen-scene/native/.crumb @@ -0,0 +1,6 @@ +{ + "schema_version": "1.0.0", + "name": "allen-scene-native", + "layer": "dependency", + "purpose": "Unmodified da55660 native rendering and catalogue dependency, bound by native.sha256" +} diff --git a/om/allen-scene/native/allen_font.c b/om/allen-scene/native/allen_font.c new file mode 100644 index 0000000..78eab61 --- /dev/null +++ b/om/allen-scene/native/allen_font.c @@ -0,0 +1,325 @@ +/* allen_font.c -- Allen's stroke typeface; see allen_font.h. */ +#include "allen_font.h" + +/* Each glyph: "wN" (advance in design units), then pen commands: + * Mx,y move the pen + * Lx,y line from the pen to x,y + * Acx,cy,rx,ry,a0,a1 elliptical arc from angle a0 to a1 (degrees; 0 is + * right, 90 is down), starting fresh; the pen ends at a1 + * Dx,y a dot + * Every stroke has round caps and joins (distance to the centre line). */ +static const char *const glyphs[CK_AF_COUNT] = { + /* */ "w6", + /* ! */ "w6 M3,0 L3,14 D3,20", + /* " */ "w10 M3,0 L3,5 M7,0 L7,5", + /* # */ "w15 M6,2 L4,20 M11,2 L9,20 M2,8 L13,8 M1,14 L12,14", + /* $ */ "w15 A8,5,5,5,-30,-270 A8,15,5,5,270,510 M8,-2 L8,22", + /* % */ "w16 A4,4,2,3,0,360 A12,16,2,3,0,360 M13,1 L3,19", + /* & */ "w16 M14,20 L5,9 A7,5,3,4,150,400 L3,14 A7,15,4,5,180,60 L13,11", + /* ' */ "w6 M3,0 L3,5", + /* ( */ "w9 A10,10,6,12,240,120", + /* ) */ "w9 A-1,10,6,12,-60,60", + /* * */ "w14 M7,2 L7,10 M3,4 L11,8 M11,4 L3,8", + /* + */ "w14 M2,12 L12,12 M7,7 L7,17", + /* , */ "w6 M3,19 L2,23", + /* - */ "w11 M2,13 L9,13", + /* . */ "w6 D3,20", + /* / */ "w12 M10,0 L2,20", + /* 0 */ "w14 A7,10,5,10,0,360", + /* 1 */ "w14 M3,4 L8,0 L8,20", + /* 2 */ "w14 A7,6,5,6,200,400 L2,20 L12,20", + /* 3 */ "w14 A7,5,5,5,200,450 A7,15,5,5,270,520", + /* 4 */ "w14 M10,20 L10,0 L1,14 L13,14", + /* 5 */ "w14 M12,0 L4,0 L4,9 A7,14,5,6,235,520", + /* 6 */ "w14 A7,14,5,6,0,360 M10,0 L3,11", + /* 7 */ "w14 M2,0 L12,0 L5,20", + /* 8 */ "w14 A7,5,4,5,0,360 A7,15,5,5,0,360", + /* 9 */ "w14 A7,6,5,6,0,360 M4,20 L11,9", + /* : */ "w6 D3,8 D3,20", + /* ; */ "w6 D3,8 M3,19 L2,23", + /* < */ "w14 M12,6 L2,12 L12,18", + /* = */ "w14 M2,10 L12,10 M2,15 L12,15", + /* > */ "w14 M2,6 L12,12 L2,18", + /* ? */ "w14 A7,5,5,5,190,450 L7,14 D7,20", + /* @ */ "w19 A9,12,3,4,0,360 M12,8 L12,14 A14,14,2,2,180,0 A9,11,7,9,0,-300", + /* A */ "w16 M2,20 L8,0 L14,20 M4,13 L12,13", + /* B */ "w15 M2,0 L2,20 M2,0 L8,0 A8,5,4,5,270,450 L2,10 M2,10 L9,10 A9,15,4,5,270,450 L2,20", + /* C */ "w17 A9,10,7,10,45,315", + /* D */ "w16 M2,0 L2,20 M2,0 L6,0 A6,10,8,10,270,450 L2,20", + /* E */ "w14 M12,0 L2,0 L2,20 L12,20 M2,10 L10,10", + /* F */ "w13 M12,0 L2,0 L2,20 M2,10 L10,10", + /* G */ "w18 A9,10,7,10,-45,-360 M11,10 L16,10", + /* H */ "w16 M2,0 L2,20 M14,0 L14,20 M2,10 L14,10", + /* I */ "w6 M3,0 L3,20", + /* J */ "w13 M10,0 L10,14 A6,14,4,6,0,180", + /* K */ "w15 M2,0 L2,20 M13,0 L2,12 M6,8 L14,20", + /* L */ "w13 M2,0 L2,20 L12,20", + /* M */ "w20 M2,20 L2,0 L10,14 L18,0 L18,20", + /* N */ "w16 M2,20 L2,0 L14,20 L14,0", + /* O */ "w20 A10,10,8,10,0,360", + /* P */ "w15 M2,20 L2,0 L8,0 A8,5,5,5,270,450 L2,10", + /* Q */ "w20 A10,10,8,10,0,360 M12,14 L18,21", + /* R */ "w15 M2,20 L2,0 L8,0 A8,5,5,5,270,450 L2,10 M8,10 L14,20", + /* S */ "w16 A8,5,5,5,-30,-270 A8,15,5,5,270,510", + /* T */ "w16 M1,0 L15,0 M8,0 L8,20", + /* U */ "w16 M2,0 L2,13 A8,13,6,7,180,0 L14,0", + /* V */ "w16 M1,0 L8,20 L15,0", + /* W */ "w22 M1,0 L6,20 L11,0 L16,20 L21,0", + /* X */ "w16 M2,0 L14,20 M14,0 L2,20", + /* Y */ "w16 M1,0 L8,10 L15,0 M8,10 L8,20", + /* Z */ "w16 M2,0 L14,0 L2,20 L14,20", + /* [ */ "w9 M7,-1 L3,-1 L3,21 L7,21", + /* \ */ "w12 M2,0 L10,20", + /* ] */ "w9 M2,-1 L6,-1 L6,21 L2,21", + /* ^ */ "w12 M2,8 L6,1 L10,8", + /* _ */ "w14 M1,23 L13,23", + /* ` */ "w7 M2,0 L4,4", + /* a */ "w15 A7,14,5,6,0,360 M12,8 L12,20", + /* b */ "w15 M2,0 L2,20 A7,14,5,6,0,360", + /* c */ "w13 A7,14,5,6,40,320", + /* d */ "w15 A7,14,5,6,0,360 M12,0 L12,20", + /* e */ "w14 M2,14 L12,14 A7,14,5,6,0,-320", + /* f */ "w11 M5,20 L5,4 A9,4,4,4,180,300 M2,8 L10,8", + /* g */ "w15 A7,14,5,6,0,360 M12,8 L12,22 A7,22,5,5,0,150", + /* h */ "w15 M2,0 L2,20 A7,13,5,5,180,360 L12,20", + /* i */ "w6 M3,8 L3,20 D3,3", + /* j */ "w7 M4,8 L4,22 A0,22,4,5,0,120 D4,3", + /* k */ "w13 M2,0 L2,20 M11,8 L2,15 M5,13 L12,20", + /* l */ "w6 M3,0 L3,20", + /* m */ "w21 M2,8 L2,20 A6,12,4,4,180,360 L10,20 A14,12,4,4,180,360 L18,20", + /* n */ "w15 M2,8 L2,20 A7,13,5,5,180,360 L12,20", + /* o */ "w14 A7,14,5,6,0,360", + /* p */ "w15 M2,8 L2,27 A7,14,5,6,0,360", + /* q */ "w15 A7,14,5,6,0,360 M12,8 L12,27", + /* r */ "w10 M2,8 L2,20 A7,13,5,5,180,290", + /* s */ "w14 A7,11,4,3,-30,-270 A7,17,4,3,270,510", + /* t */ "w11 M5,2 L5,17 A8,17,3,3,180,40 M2,8 L10,8", + /* u */ "w15 M2,8 L2,15 A7,15,5,5,180,0 M12,8 L12,20", + /* v */ "w14 M2,8 L7,20 L12,8", + /* w */ "w20 M2,8 L6,20 L10,8 L14,20 L18,8", + /* x */ "w14 M2,8 L12,20 M12,8 L2,20", + /* y */ "w14 M2,8 L7,20 M12,8 L4,27", + /* z */ "w14 M2,8 L12,8 L2,20 L12,20", + /* { */ "w10 M8,-1 L6,0 L6,8 L4,10 L6,12 L6,20 L8,21", + /* | */ "w6 M3,-1 L3,23", + /* } */ "w10 M2,-1 L4,0 L4,8 L6,10 L4,12 L4,20 L2,21", + /* ~ */ "w14 M2,13 L5,11 L9,14 L12,12", +}; + +static const uint16_t sin_q[91] = { + 0, 286, 572, 857, 1143, 1428, 1713, 1997, 2280, 2563, 2845, 3126, 3406, 3686, 3964, + 4240, 4516, 4790, 5063, 5334, 5604, 5872, 6138, 6402, 6664, 6924, 7182, 7438, 7692, 7943, + 8192, 8438, 8682, 8923, 9162, 9397, 9630, 9860, 10087, 10311, 10531, 10749, 10963, 11174, 11381, + 11585, 11786, 11982, 12176, 12365, 12551, 12733, 12911, 13085, 13255, 13421, 13583, 13741, 13894, 14044, + 14189, 14330, 14466, 14598, 14726, 14849, 14968, 15082, 15191, 15296, 15396, 15491, 15582, 15668, 15749, + 15826, 15897, 15964, 16026, 16083, 16135, 16182, 16225, 16262, 16294, 16322, 16344, 16362, 16374, 16382, + 16384, +}; + +int32_t ck_af_sin(int32_t deg) +{ + deg %= 360; + if (deg < 0) + deg += 360; + if (deg <= 90) + return sin_q[deg]; + if (deg <= 180) + return sin_q[180 - deg]; + if (deg <= 270) + return -(int32_t)sin_q[deg - 180]; + return -(int32_t)sin_q[360 - deg]; +} + +int32_t ck_af_cos(int32_t deg) { return ck_af_sin(deg + 90); } + +uint64_t ck_af_isqrt(uint64_t v) +{ + uint64_t r = 0, bit = (uint64_t)1 << 62; + while (bit > v) + bit >>= 2; + while (bit) { + if (v >= r + bit) { + v -= r + bit; + r = (r >> 1) + bit; + } else { + r >>= 1; + } + bit >>= 2; + } + return r; +} + +static int idx(char c) +{ + unsigned char u = (unsigned char)c; + return u >= CK_AF_FIRST && u <= CK_AF_LAST ? u - CK_AF_FIRST : '?' - CK_AF_FIRST; +} + +void ck_af_face_init(ck_af_face *f, unsigned cap_px, unsigned weight, uint8_t *pool, size_t pool_len) +{ + f->s256 = cap_px * 256u / 20u; + f->hw256 = (uint32_t)((uint64_t)weight * f->s256 / 1000u); + f->pool = pool; + f->pool_len = pool_len; + f->pool_used = 0; + for (unsigned i = 0; i < CK_AF_COUNT; i++) + f->g[i] = (ck_af_glyph){0}; +} + +/* Reads a signed integer at *p; advances past it and one ',' if present. */ +static int num(const char **p) +{ + int neg = 0, v = 0; + if (**p == '-') { + neg = 1; + (*p)++; + } + while (**p >= '0' && **p <= '9') + v = v * 10 + (*(*p)++ - '0'); + if (**p == ',') + (*p)++; + return neg ? -v : v; +} + +uint32_t ck_af_advance(const ck_af_face *f, char c) +{ + const char *p = glyphs[idx(c)] + 1; /* past 'w' */ + return (uint32_t)num(&p) * f->s256; +} + +uint32_t ck_af_measure(const ck_af_face *f, const char *s, size_t n) +{ + uint64_t w = 0; + for (size_t i = 0; i < n && s[i]; i++) + w += ck_af_advance(f, s[i]); + return (uint32_t)((w + 255) / 256); +} + +#define SEG_MAX 160 +struct seg { + int32_t x0, y0, x1, y1; /* 1/256 px, relative to the pen; y up from the baseline is negative */ +}; + +/* Turns one glyph's commands into segments. Returns the count. */ +static unsigned segments(const ck_af_face *f, const char *p, struct seg *out) +{ + int32_t s = (int32_t)f->s256; + unsigned n = 0; + int32_t px = 0, py = 0; +#define PT_X(u) ((int32_t)(u) * s) +#define PT_Y(u) (((int32_t)(u) - 20) * s) + while (*p) { + char cmd = *p++; + if (cmd == ' ') + continue; + if (cmd == 'w') { + (void)num(&p); + } else if (cmd == 'M') { + int x = num(&p), y = num(&p); + px = PT_X(x); + py = PT_Y(y); + } else if (cmd == 'L' || cmd == 'D') { + int x = num(&p), y = num(&p); + int32_t nx = PT_X(x), ny = PT_Y(y); + if (cmd == 'D') + px = nx, py = ny; + if (n < SEG_MAX) + out[n++] = (struct seg){px, py, nx, ny}; + px = nx; + py = ny; + } else if (cmd == 'A') { + int cx = num(&p), cy = num(&p), rx = num(&p), ry = num(&p), a0 = num(&p), a1 = num(&p); + int span = a1 > a0 ? a1 - a0 : a0 - a1; + int steps = span / 9 < 2 ? 2 : span / 9; + int32_t lx = 0, ly = 0; + for (int k = 0; k <= steps; k++) { + int32_t a = a0 + (a1 - a0) * k / steps; + int32_t x = PT_X(cx) + (int32_t)((int64_t)rx * s * ck_af_cos(a) / 16384); + int32_t y = PT_Y(cy) + (int32_t)((int64_t)ry * s * ck_af_sin(a) / 16384); + if (k && n < SEG_MAX) + out[n++] = (struct seg){lx, ly, x, y}; + lx = x; + ly = y; + } + px = lx; + py = ly; + } + } +#undef PT_X +#undef PT_Y + return n; +} + +static int32_t floor_px(int32_t v) { return v >= 0 ? v / 256 : -((-v + 255) / 256); } + +const ck_af_glyph *ck_af_glyph_get(ck_af_face *f, char c) +{ + ck_af_glyph *g = &f->g[idx(c)]; + if (g->alpha || (g->w == 0 && g->h == 1)) /* h == 1, w == 0: an empty glyph already done */ + return g; + struct seg sg[SEG_MAX]; + unsigned n = segments(f, glyphs[idx(c)], sg); + if (n == 0) { + g->w = 0; + g->h = 1; + return g; + } + int32_t minx = sg[0].x0, maxx = minx, miny = sg[0].y0, maxy = miny; + for (unsigned i = 0; i < n; i++) { + int32_t xs[2] = {sg[i].x0, sg[i].x1}, ys[2] = {sg[i].y0, sg[i].y1}; + for (int k = 0; k < 2; k++) { + if (xs[k] < minx) minx = xs[k]; + if (xs[k] > maxx) maxx = xs[k]; + if (ys[k] < miny) miny = ys[k]; + if (ys[k] > maxy) maxy = ys[k]; + } + } + int32_t pad = (int32_t)f->hw256 + 256; + int32_t x0 = floor_px(minx - pad), y0 = floor_px(miny - pad); + int32_t x1 = floor_px(maxx + pad) + 1, y1 = floor_px(maxy + pad) + 1; + size_t w = (size_t)(x1 - x0), h = (size_t)(y1 - y0); + if (f->pool_len - f->pool_used < w * h) + return 0; + uint8_t *a = f->pool + f->pool_used; + int64_t hw = f->hw256; + for (size_t yy = 0; yy < h; yy++) { + int64_t py = (int64_t)(y0 + (int32_t)yy) * 256 + 128; + for (size_t xx = 0; xx < w; xx++) { + int64_t pxc = (int64_t)(x0 + (int32_t)xx) * 256 + 128; + int64_t best = INT64_MAX; + for (unsigned i = 0; i < n; i++) { + int64_t ax = sg[i].x0, ay = sg[i].y0, dx = sg[i].x1 - ax, dy = sg[i].y1 - ay; + int64_t qx = pxc - ax, qy = py - ay, len2 = dx * dx + dy * dy, ex, ey; + if (len2 == 0) { + ex = qx; + ey = qy; + } else { + int64_t t = qx * dx + qy * dy; /* projection, scaled by len2 */ + if (t <= 0) { + ex = qx; + ey = qy; + } else if (t >= len2) { + ex = qx - dx; + ey = qy - dy; + } else { + ex = qx - dx * t / len2; + ey = qy - dy * t / len2; + } + } + int64_t d2 = ex * ex + ey * ey; + if (d2 < best) + best = d2; + } + int64_t d = (int64_t)ck_af_isqrt((uint64_t)best); + int64_t cov = hw + 128 - d; /* 1/256 px of the pixel inside the stroke */ + a[yy * w + xx] = cov <= 0 ? 0 : cov >= 256 ? 255 : (uint8_t)(cov * 255 / 256); + } + } + f->pool_used += w * h; + g->w = (uint16_t)w; + g->h = (uint16_t)h; + g->ox = (int16_t)x0; + g->oy = (int16_t)y0; + g->alpha = a; + return g; +} diff --git a/om/allen-scene/native/allen_font.h b/om/allen-scene/native/allen_font.h new file mode 100644 index 0000000..13c3c0a --- /dev/null +++ b/om/allen-scene/native/allen_font.h @@ -0,0 +1,48 @@ +/* allen_font.h -- Allen's typeface: every printable ASCII character drawn as + * round-capped pen strokes (lines and elliptical arcs) on a design grid, and + * rasterized on demand into anti-aliased alpha masks at any size. Integer math + * only (the kernel builds -mgeneral-regs-only); no font files, no outside + * data. Pure: no MMIO, host tested in ui/tests/allen_ui_test.c. + * + * Design grid: cap height and ascenders at y=0, lowercase x-height at y=8, + * baseline at y=20, descenders to y=27; x grows right, y grows down. */ +#ifndef AIENOS_ALLEN_FONT_H +#define AIENOS_ALLEN_FONT_H +#include +#include + +#define CK_AF_FIRST 32 +#define CK_AF_LAST 126 +#define CK_AF_COUNT (CK_AF_LAST - CK_AF_FIRST + 1) + +typedef struct { + uint8_t *alpha; /* w*h coverage, 0..255; NULL when not rasterized yet */ + uint16_t w, h; + int16_t ox, oy; /* mask top-left relative to the pen on the baseline, px */ +} ck_af_glyph; + +typedef struct { + uint32_t s256; /* 1/256 px per design unit */ + uint32_t hw256; /* half the stroke width, 1/256 px */ + uint8_t *pool; /* mask storage, filled as glyphs are first used */ + size_t pool_len, pool_used; + ck_af_glyph g[CK_AF_COUNT]; +} ck_af_face; + +/* cap_px: cap height in pixels; weight: half the stroke width in + * thousandths of a design unit (1250 = regular). pool holds the masks. */ +void ck_af_face_init(ck_af_face *f, unsigned cap_px, unsigned weight, uint8_t *pool, size_t pool_len); +/* The mask for c (anything outside 32..126 draws as '?'); NULL only when the + * pool is full. Rasterized on first use. */ +const ck_af_glyph *ck_af_glyph_get(ck_af_face *f, char c); +/* Advance after c, 1/256 px. */ +uint32_t ck_af_advance(const ck_af_face *f, char c); +/* Width of the first n characters of s, whole px (rounded up). */ +uint32_t ck_af_measure(const ck_af_face *f, const char *s, size_t n); +/* Integer square root (floor). */ +uint64_t ck_af_isqrt(uint64_t v); +/* sin and cos of whole degrees (any sign), scaled by 16384. */ +int32_t ck_af_sin(int32_t deg); +int32_t ck_af_cos(int32_t deg); + +#endif diff --git a/om/allen-scene/native/chirp.c b/om/allen-scene/native/chirp.c new file mode 100644 index 0000000..d3e7329 --- /dev/null +++ b/om/allen-scene/native/chirp.c @@ -0,0 +1,192 @@ +/* chirp.c -- the startup sound; see chirp.h. + * + * Every frame is worked out from where it sits on the night's timeline. + * With L the share of the inspiral left (1 at CK_CHIRP_START_MS, 0 at the + * merger), the holes' orbit goes as 1 - L^(5/8); so does the sound's + * phase, scaled so it starts at CK_CHIRP_FROM_HZ, which makes its pitch go + * as L^(-3/8). Once the pitch reaches CK_CHIRP_TO_HZ (the last few + * milliseconds) it holds there through the merger and the fade. Loudness + * goes as L^(-1/4), which is pitch^(2/3), reaching CK_CHIRP_PEAK where the + * pitch stops rising. Phases are in 2^32ths of a cycle; L and its powers in + * Q30. */ +#include "chirp.h" + +#define F0_FRAME (CK_CHIRP_RATE / 1000u * (CK_CHIRP_START_MS - CK_CHIRP_IN_MS)) /* the sound comes in */ +#define F1_FRAME (CK_CHIRP_RATE / 1000u * CK_CHIRP_START_MS) /* the sweep begins */ +#define F2_FRAME (CK_CHIRP_RATE / 1000u * CK_NIGHT_MERGE_MS) /* the merger */ +#define Q30 (1ull << 30) +#define DECAY 1072996429ull /* exp(-1 / (30 ms * 48 kHz)) in Q30: the fade's time constant is 30 ms */ + +static int16_t sin_t[4096]; /* Q14 */ +static uint32_t cap_frame; /* the pitch stops rising here */ +static uint64_t cap_l14; /* L^(1/4) there */ +static uint64_t cap_phase; /* the phase there */ +static int ready; + +static uint64_t isqrt(uint64_t x) +{ + uint64_t r = 0, bit = 1ull << 62; + while (bit > x) + bit >>= 2; + while (bit) { + if (x >= r + bit) { + x -= r + bit; + r = (r >> 1) + bit; + } else { + r >>= 1; + } + bit >>= 2; + } + return r; +} + +/* L at a frame of the inspiral, and its eighth root (both Q30) */ +static uint64_t left_q30(uint32_t f) { return ((uint64_t)(F2_FRAME - f) << 30) / (F2_FRAME - F1_FRAME); } + +static uint64_t root8(uint64_t l) +{ + for (int i = 0; i < 3; i++) + l = isqrt(l << 30); + return l; +} + +static uint64_t mul(uint64_t a, uint64_t b) { return a * b >> 30; } + +/* phase over the inspiral before the cap: P1 + K (1 - L^(5/8)), K chosen so + * the pitch starts at CK_CHIRP_FROM_HZ: K = FROM_HZ * 8/5 * inspiral seconds */ +static uint64_t inspiral_phase(uint32_t f) +{ + uint64_t r = root8(left_q30(f)), l58 = mul(mul(mul(mul(r, r), r), r), r); + uint64_t p1 = ((uint64_t)CK_CHIRP_FROM_HZ * (F1_FRAME - F0_FRAME) << 32) / CK_CHIRP_RATE; + uint64_t k = (uint64_t)CK_CHIRP_FROM_HZ * 8 * (F2_FRAME - F1_FRAME); /* K * 5 * RATE */ + return p1 + ((k * (Q30 - l58) << 2) / (5ull * CK_CHIRP_RATE)); +} + +static void setup(void) +{ + const int64_t C = 1073740561, S = 1647099; /* cos, sin of a 4096th of a turn, Q30 */ + int64_t c = 1ll << 30, s = 0; + for (unsigned k = 0; k <= 1024; k++) { + int16_t v = k == 1024 ? 16384 : (int16_t)((s + (1 << 15)) >> 16); + sin_t[k] = v; + sin_t[2048 - k] = v; + sin_t[(2048 + k) & 4095] = (int16_t)-v; + sin_t[(4096 - k) & 4095] = (int16_t)-v; + int64_t nc = (c * C - s * S) >> 30, ns = (s * C + c * S) >> 30; + c = nc, s = ns; + } + /* the first frame where FROM_HZ * L^(-3/8) reaches TO_HZ, i.e. where + * L^(3/8) falls to FROM_HZ / TO_HZ (L^(3/8) only falls) */ + uint64_t want = ((uint64_t)CK_CHIRP_FROM_HZ << 30) / CK_CHIRP_TO_HZ; + uint32_t lo = F1_FRAME, hi = F2_FRAME; + while (lo < hi) { + uint32_t mid = lo + (hi - lo) / 2; + uint64_t r = root8(left_q30(mid)); + if (mul(mul(r, r), r) <= want) + hi = mid; + else + lo = mid + 1; + } + cap_frame = lo; + uint64_t r = root8(left_q30(lo)); + cap_l14 = mul(r, r); + cap_phase = inspiral_phase(lo); + ready = 1; +} + +static uint64_t phase_at(uint32_t f) +{ + if (f < F1_FRAME) + return ((uint64_t)CK_CHIRP_FROM_HZ * (f - F0_FRAME) << 32) / CK_CHIRP_RATE; + if (f < cap_frame) + return inspiral_phase(f); + return cap_phase + ((uint64_t)CK_CHIRP_TO_HZ * (f - cap_frame) << 32) / CK_CHIRP_RATE; +} + +static uint64_t decay_pow(uint32_t k) /* DECAY^k, Q30 */ +{ + uint64_t r = Q30, b = DECAY; + while (k) { + if (k & 1) + r = mul(r, b); + b = mul(b, b); + k >>= 1; + } + return r; +} + +uint32_t ck_chirp_level(uint32_t f) +{ + if (!ready) + setup(); + if (f < F0_FRAME || f >= CK_CHIRP_FRAMES) + return 0; + uint64_t steady = (uint64_t)CK_CHIRP_PEAK * cap_l14 >> 30; /* the level at L = 1 */ + if (f < F1_FRAME) { /* comes in smoothly (smoothstep) */ + uint64_t x = ((uint64_t)(f - F0_FRAME) << 16) / (F1_FRAME - F0_FRAME), s = x * x * (3ull * 65536 - 2 * x); + return (uint32_t)(steady * s >> 48); + } + if (f < cap_frame) { + uint64_t r = root8(left_q30(f)); + return (uint32_t)((uint64_t)CK_CHIRP_PEAK * cap_l14 / mul(r, r)); + } + if (f < F2_FRAME) + return CK_CHIRP_PEAK; + return (uint32_t)((uint64_t)CK_CHIRP_PEAK * decay_pow(f - F2_FRAME) >> 30); +} + +uint32_t ck_chirp_hz(uint32_t f) +{ + if (!ready) + setup(); + if (f < F0_FRAME || f >= CK_CHIRP_FRAMES) + return 0; + if (f < F1_FRAME) + return CK_CHIRP_FROM_HZ; + if (f >= cap_frame) + return CK_CHIRP_TO_HZ; + uint64_t r = root8(left_q30(f)); + return (uint32_t)(((uint64_t)CK_CHIRP_FROM_HZ << 30) / mul(mul(r, r), r)); +} + +void ck_chirp_fill(int16_t *out, uint32_t from, uint32_t n) +{ + if (!ready) + setup(); + for (uint32_t i = 0; i < n; i++) { + uint32_t f = from + i, a = ck_chirp_level(f); + int32_t v = 0; + if (a) { + uint32_t ph = (uint32_t)phase_at(f), k = ph >> 20, frac = ph >> 4 & 0xffffu; + int32_t s0 = sin_t[k], s1 = sin_t[(k + 1) & 4095]; + int32_t s = s0 + (int32_t)(((int64_t)(s1 - s0) * frac) >> 16); /* Q14 */ + v = (int32_t)(((int64_t)s * a) >> 14); + } + out[2 * i] = out[2 * i + 1] = (int16_t)v; + } +} + +/* The same chirp at 44.1 kHz for converters that take only that rate: frame + * j sits at 48 kHz frame j * 160 / 147, drawn as a straight line between the + * two 48 kHz frames either side (the chirp stays under 1000 Hz, far below + * either rate's limit). Each sample goes in the top 16 bits of a 32-bit slot, + * the layout a 24-bit converter reads (Linux: S32_LE with 24 bits used). */ +void ck_chirp_fill_441(int32_t *out, uint32_t from, uint32_t n) +{ + int16_t src[2 * 144]; + while (n) { + uint32_t m = n < 128u ? n : 128u, s0 = (uint32_t)((uint64_t)from * 160u / 147u); + uint32_t s1 = (uint32_t)((uint64_t)(from + m - 1) * 160u / 147u) + 1; + ck_chirp_fill(src, s0, s1 - s0 + 1); + for (uint32_t i = 0; i < m; i++) { + uint64_t at = (uint64_t)(from + i) * 160u; + uint32_t s = (uint32_t)(at / 147u) - s0, frac = (uint32_t)(at % 147u); + int32_t a = src[2 * s], b = src[2 * s + 2]; + int32_t v = (a * (int32_t)(147u - frac) + b * (int32_t)frac) / 147; + out[2 * i] = out[2 * i + 1] = (int32_t)((uint32_t)v << 16); + } + out += 2 * m; + from += m; + n -= m; + } +} diff --git a/om/allen-scene/native/chirp.h b/om/allen-scene/native/chirp.h new file mode 100644 index 0000000..359f0f4 --- /dev/null +++ b/om/allen-scene/native/chirp.h @@ -0,0 +1,42 @@ +/* chirp.h -- the startup sound: a quick "blirp", the last moment of the chirp + * two bodies make as they spiral into each other and merge (a gravitational + * wave), raised into hearing and timed to the night sky of the startup + * (ui/night.h). Silent until CK_CHIRP_RISE_MS before the merger; then it + * comes in over CK_CHIRP_IN_MS and sweeps up in pitch and loudness the way + * the real wave does (pitch as t^(-3/8), loudness as pitch^(2/3), t the time + * left), with its peak at the merger (CK_NIGHT_MERGE_MS); then a short + * ringing fade. Under a second in all. Made from that formula, no recorded + * sound. Integer only (the kernel builds with -mgeneral-regs-only), + * freestanding, no memory of its own beyond a sine table. Host tested in + * ui/tests/chirp_test.c. */ +#ifndef AIENOS_CHIRP_H +#define AIENOS_CHIRP_H +#include +#include "night.h" + +#define CK_CHIRP_RATE 48000u /* frames a second; each frame is a left and a right sample, 16 bits */ +#define CK_CHIRP_FROM_HZ 200u /* the pitch the sweep starts at */ +#define CK_CHIRP_TO_HZ 1000u /* the pitch at the merger, held through the fade */ +#define CK_CHIRP_PEAK 22937 /* 70% of full scale */ +#define CK_CHIRP_RISE_MS 600u /* the sweep up to the merger */ +#define CK_CHIRP_IN_MS 40u /* the sound comes in over this, just before the sweep */ +#define CK_CHIRP_START_MS (CK_NIGHT_MERGE_MS - CK_CHIRP_RISE_MS) +#define CK_CHIRP_END_MS (CK_NIGHT_MERGE_MS + 300u) /* the ring has died away */ +#define CK_CHIRP_FRAMES (CK_CHIRP_RATE / 1000u * CK_CHIRP_END_MS) + +/* Writes frames [from, from + n) as left, right pairs into out (2n samples), + * frame 0 being the night's 0 ms. Silent past CK_CHIRP_FRAMES. Any frame + * can be asked for in any order: each is worked out from the formula. */ +void ck_chirp_fill(int16_t *out, uint32_t from, uint32_t n); + +/* The pitch in Hz and the loudness (0..CK_CHIRP_PEAK) at a frame. */ +uint32_t ck_chirp_hz(uint32_t frame); +uint32_t ck_chirp_level(uint32_t frame); + +/* The chirp at 44.1 kHz instead: frames [from, from + n) of that rate, frame + * 0 the night's 0 ms, each sample in the top 16 bits of a 32-bit slot (a + * 24-bit converter's layout), left and right. */ +#define CK_CHIRP_RATE_441 44100u +#define CK_CHIRP_FRAMES_441 (CK_CHIRP_RATE_441 / 100u * CK_CHIRP_END_MS / 10u) +void ck_chirp_fill_441(int32_t *out, uint32_t from, uint32_t n); +#endif diff --git a/om/allen-scene/native/flow.c b/om/allen-scene/native/flow.c new file mode 100644 index 0000000..19942e6 --- /dev/null +++ b/om/allen-scene/native/flow.c @@ -0,0 +1,395 @@ +/* flow.c -- Allen's ink; see flow.h. */ +#include "flow.h" + +#define W ((int32_t)CK_FLOW_W) +#define H ((int32_t)CK_FLOW_H) +#define IX(i, j) ((i) + (W + 2) * (j)) +#define Q 65536 /* one, 16.16 */ +#define HALF 32768 + +/* How the water behaves (16.16 unless said): a little thick, so a push + * becomes a slow curl rather than a splash; ink spreads a little more than + * the water does; both fade on their own so the tank always comes to rest. */ +#define VISC_PER_MS 205 /* diffusion of velocity per ms (0.05 per 16 ms step) */ +#define INK_PER_MS 328 /* diffusion of ink per ms (0.08 per 16 ms step) */ +#define INK_FADE_PER_MS 33 /* 0.5 of the ink per second */ +#define VEL_FADE_PER_MS 59 /* 0.9 of the velocity per second */ +#define BLEND_MS 700u /* a mode's pull eases in or out over this long */ +#define SOLVE_STEPS 10 /* Gauss-Seidel sweeps for diffusion and pressure */ + +static int32_t mul(int32_t a, int32_t b) { return (int32_t)(((int64_t)a * b) >> 16); } + +static uint32_t rnd(ck_flow *f) +{ + f->rng ^= f->rng << 13; + f->rng ^= f->rng >> 17; + f->rng ^= f->rng << 5; + return f->rng; +} + +/* ---- the grid and the screen ---- */ + +/* A screen position to a grid position (16.16 cells, the border cell being 0). */ +static int32_t cell_x(const ck_flow *f, int32_t px) { return (int32_t)((((int64_t)px << 24) + f->cw / 2) / f->cw) + Q; } +static int32_t cell_y(const ck_flow *f, int32_t py) { return (int32_t)((((int64_t)py << 24) + f->ch / 2) / f->ch) + Q; } +/* px per second to cells per second */ +static int32_t cells_x(const ck_flow *f, int32_t vx) { return (int32_t)(((int64_t)vx << 24) / f->cw); } +static int32_t cells_y(const ck_flow *f, int32_t vy) { return (int32_t)(((int64_t)vy << 24) / f->ch); } + +/* The field sampled between cells (values sit at cell centres). */ +static int32_t sample(const int32_t *x, int32_t gx, int32_t gy) +{ + gx = ck_clamp(gx - HALF, 0, (W + 1) * Q - 1); + gy = ck_clamp(gy - HALF, 0, (H + 1) * Q - 1); + int32_t i = gx >> 16, j = gy >> 16, s1 = gx & 0xffff, t1 = gy & 0xffff, s0 = Q - s1, t0 = Q - t1; + int64_t a = (int64_t)x[IX(i, j)] * t0 + (int64_t)x[IX(i, j + 1)] * t1; + int64_t b = (int64_t)x[IX(i + 1, j)] * t0 + (int64_t)x[IX(i + 1, j + 1)] * t1; + return (int32_t)((a * s0 + b * s1) >> 32); +} + +/* ---- Stam's steps ---- */ + +/* The border: walls for the velocity (the part across the wall mirrors), continuation for a scalar. */ +static void set_bnd(int32_t *x, int which) +{ + for (int32_t i = 1; i <= W; i++) { + x[IX(i, 0)] = which == 2 ? -x[IX(i, 1)] : x[IX(i, 1)]; + x[IX(i, H + 1)] = which == 2 ? -x[IX(i, H)] : x[IX(i, H)]; + } + for (int32_t j = 1; j <= H; j++) { + x[IX(0, j)] = which == 1 ? -x[IX(1, j)] : x[IX(1, j)]; + x[IX(W + 1, j)] = which == 1 ? -x[IX(W, j)] : x[IX(W, j)]; + } + x[IX(0, 0)] = (x[IX(1, 0)] + x[IX(0, 1)]) / 2; + x[IX(0, H + 1)] = (x[IX(1, H + 1)] + x[IX(0, H)]) / 2; + x[IX(W + 1, 0)] = (x[IX(W, 0)] + x[IX(W + 1, 1)]) / 2; + x[IX(W + 1, H + 1)] = (x[IX(W, H + 1)] + x[IX(W + 1, H)]) / 2; +} + +/* x = (x0 + a * (the four neighbours)) / c, swept SOLVE_STEPS times. */ +static void lin_solve(int32_t *x, const int32_t *x0, int32_t a, int32_t c, int which) +{ + int64_t inv = ((int64_t)1 << 46) / c; /* one division per solve instead of one per cell */ + for (int k = 0; k < SOLVE_STEPS; k++) { + for (int32_t j = 1; j <= H; j++) + for (int32_t i = 1; i <= W; i++) { + int64_t sum = (int64_t)x[IX(i - 1, j)] + x[IX(i + 1, j)] + x[IX(i, j - 1)] + x[IX(i, j + 1)]; + int64_t num = (((int64_t)x0[IX(i, j)] << 16) + a * sum) >> 14; + x[IX(i, j)] = (int32_t)((num * inv) >> 32); + } + set_bnd(x, which); + } +} + +static void diffuse(int32_t *x, const int32_t *x0, int32_t a, int which) { lin_solve(x, x0, a, Q + 4 * a, which); } + +/* Each cell takes the value found where its water came from, dt seconds ago. */ +static void advect(int32_t *d, const int32_t *d0, const int32_t *u, const int32_t *v, int32_t dt, int which) +{ + for (int32_t j = 1; j <= H; j++) + for (int32_t i = 1; i <= W; i++) { + int32_t x = (i << 16) - mul(dt, u[IX(i, j)]), y = (j << 16) - mul(dt, v[IX(i, j)]); + x = ck_clamp(x, HALF, W * Q + HALF); + y = ck_clamp(y, HALF, H * Q + HALF); + int32_t i0 = x >> 16, j0 = y >> 16, s1 = x & 0xffff, t1 = y & 0xffff, s0 = Q - s1, t0 = Q - t1; + int64_t a = (int64_t)d0[IX(i0, j0)] * t0 + (int64_t)d0[IX(i0, j0 + 1)] * t1; + int64_t b = (int64_t)d0[IX(i0 + 1, j0)] * t0 + (int64_t)d0[IX(i0 + 1, j0 + 1)] * t1; + d[IX(i, j)] = (int32_t)((a * s0 + b * s1) >> 32); + } + set_bnd(d, which); +} + +/* Takes the divergence out of the velocity, so the water neither piles up nor + * vanishes anywhere: p and div are scratch. */ +static void project(int32_t *u, int32_t *v, int32_t *p, int32_t *div) +{ + for (int32_t j = 1; j <= H; j++) + for (int32_t i = 1; i <= W; i++) { + div[IX(i, j)] = -(u[IX(i + 1, j)] - u[IX(i - 1, j)] + v[IX(i, j + 1)] - v[IX(i, j - 1)]) / 2; + p[IX(i, j)] = 0; + } + set_bnd(div, 0); + set_bnd(p, 0); + lin_solve(p, div, Q, 4 * Q, 0); + for (int32_t j = 1; j <= H; j++) + for (int32_t i = 1; i <= W; i++) { + u[IX(i, j)] -= (p[IX(i + 1, j)] - p[IX(i - 1, j)]) / 2; + v[IX(i, j)] -= (p[IX(i, j + 1)] - p[IX(i, j - 1)]) / 2; + } + set_bnd(u, 1); + set_bnd(v, 2); +} + +static void copy_field(int32_t *d, const int32_t *s) +{ + for (size_t i = 0; i < CK_FLOW_CELLS; i++) + d[i] = s[i]; +} + +/* ---- what Allen does to the water ---- */ + +/* A push over a soft disc: velocity (vx, vy) and ink, both in grid units, strongest at the centre. */ +static void push(ck_flow *f, int32_t gx, int32_t gy, int32_t vx, int32_t vy, int32_t ink, int32_t r) +{ + int32_t i0 = ck_max(1, (gx - r) >> 16), i1 = ck_min(W, (gx + r) >> 16); + int32_t j0 = ck_max(1, (gy - r) >> 16), j1 = ck_min(H, (gy + r) >> 16); + for (int32_t j = j0; j <= j1; j++) + for (int32_t i = i0; i <= i1; i++) { + int64_t dx = (i << 16) + HALF - gx, dy = (j << 16) + HALF - gy; + int64_t d2 = (dx * dx + dy * dy) >> 16, r2 = ((int64_t)r * r) >> 16; + if (d2 >= r2) + continue; + uint32_t w = ck_exp_neg((uint32_t)(d2 * 3 * 256 / r2)); /* exp(-3 d^2 / r^2), 16.16 */ + f->u[IX(i, j)] += (int32_t)(((int64_t)vx * w) >> 16); + f->v[IX(i, j)] += (int32_t)(((int64_t)vy * w) >> 16); + f->d[IX(i, j)] = ck_min(Q, f->d[IX(i, j)] + (int32_t)(((int64_t)ink * w) >> 16)); + } +} + +/* The pull of each mode, each weighted by how far it has eased in (0..256), + * all added: a change of mode is a change of weights, never a jump. */ +static void forces(ck_flow *f, uint32_t dt_ms) +{ + int32_t cx = cell_x(f, f->cx), cy = cell_y(f, f->cy); + int32_t R = ck_max(Q / 2, (int32_t)(((int64_t)f->R << 24) / f->cw)); /* Allen's radius in cells */ + int32_t bx = cell_x(f, f->bx), by = cell_y(f, f->by); + uint32_t wi = f->weight[CK_FLOW_IDLE], wl = f->weight[CK_FLOW_LISTEN], wt = f->weight[CK_FLOW_THINK]; + uint32_t ws = f->weight[CK_FLOW_SPEAK]; + /* thinking deepens over the first four seconds */ + uint32_t deep = f->think_t ? 256 + ck_smooth(ck_prog(f->t, f->think_t, f->think_t + 4000)) * 3 / 4 : 256; + int32_t breath = ck_sin(f->t * 65536 / 7000); /* a slow swell, +-16384 */ + for (int32_t j = 1; j <= H; j++) + for (int32_t i = 1; i <= W; i++) { + int64_t dx = (i << 16) + HALF - cx, dy = (j << 16) + HALF - cy; + int64_t r = ck_isqrt((uint64_t)((dx * dx + dy * dy) >> 16)) << 8; /* 16.16 cells */ + if (r < Q / 8) + r = Q / 8; + int32_t tx = (int32_t)(-dy * Q / r), ty = (int32_t)(dx * Q / r); /* tangent, unit */ + int32_t rx = (int32_t)(dx * Q / r), ry = (int32_t)(dy * Q / r); /* outward, unit */ + /* a bell over the ring R..3.5R where the water turns */ + int64_t ring = r - 3 * R / 2; + uint32_t bell = r < 7 * R / 2 ? ck_exp_neg((uint32_t)(ring * ring * 512 / ((int64_t)R * R))) : 0; + int64_t ax = 0, ay = 0; /* cells per second per second, 16.16 */ + if (wi && bell) { /* idle: a slow turn with the breath */ + int64_t k = (int64_t)bell * wi >> 8; + int64_t turn = Q / 5 + (breath * (Q / 8) >> 14); + ax += (tx * turn >> 16) * k >> 16; + ay += (ty * turn >> 16) * k >> 16; + ax += (rx * (int64_t)(breath * (Q / 10) >> 14) >> 16) * k >> 16; + ay += (ry * (int64_t)(breath * (Q / 10) >> 14) >> 16) * k >> 16; + } + if (wt && bell) { /* thinking: the vortex, deepening, drawn a little inward */ + int64_t k = (int64_t)bell * wt * deep >> 16; + int64_t turn = 3 * Q / 2; + ax += (tx * turn >> 16) * k >> 16; + ay += (ty * turn >> 16) * k >> 16; + ax -= (rx * (int64_t)(Q / 4) >> 16) * k >> 16; + ay -= (ry * (int64_t)(Q / 4) >> 16) * k >> 16; + } + if (wl) { /* listening: a soft current from the bar up to Allen */ + int64_t lx = cx - bx, ly = cy - by, len = ck_isqrt((uint64_t)((lx * lx + ly * ly) >> 16)) << 8; + if (len > Q) { + int64_t px = (i << 16) + HALF - bx, py = (j << 16) + HALF - by; + int64_t along = (px * lx + py * ly) / len, across = (px * ly - py * lx) / len; + if (along > 0 && along < len) { + uint32_t near = ck_exp_neg((uint32_t)(across * across * 256 / ((int64_t)R * R))); + int64_t k = (int64_t)near * wl >> 8; + ax += (lx * Q / len * (Q / 2) >> 16) * k >> 16; + ay += (ly * Q / len * (Q / 2) >> 16) * k >> 16; + } + } + } + (void)ws; /* speaking pushes in rings as the words come (ck_flow_word) */ + f->u[IX(i, j)] += (int32_t)(ax * (int64_t)dt_ms / 1000); + f->v[IX(i, j)] += (int32_t)(ay * (int64_t)dt_ms / 1000); + } + /* ink from the heart: a trickle when idle, a stream when speaking */ + int32_t ink = (int32_t)(((int64_t)(wi * 6 + wl * 10 + ws * 60) * dt_ms) >> 8); + if (ink) + push(f, cx, cy, 0, 0, ink, R); + /* thinking: the ink wells up round him, where the vortex carries it, not under his own light */ + int32_t think_ink = (int32_t)(((int64_t)wt * 120 * deep / 256 * dt_ms) >> 8); + if (think_ink) + for (int k = 0; k < 8; k++) { + uint32_t a = (uint32_t)(f->t * 65536 / 9000) + (uint32_t)k * 8192; + push(f, cx + (int32_t)((int64_t)ck_cos(a) * 3 * R / 2 >> 14), cy + (int32_t)((int64_t)ck_sin(a) * 3 * R / 2 >> 14), 0, 0, + think_ink, R / 2); + } + /* a few motes of ink drift in from nowhere while he is awake, so the water is never empty */ + if ((wi || wl) && (rnd(f) & 15) == 0) + push(f, Q + (int32_t)(rnd(f) % (uint32_t)(W * Q)), Q + (int32_t)(rnd(f) % (uint32_t)(H * Q)), 0, 0, + Q / 40, R / 2); +} + +static void fade(int32_t *x, int32_t per_ms, uint32_t dt_ms) +{ + int32_t k = (int32_t)ck_min(Q, (int32_t)(per_ms * dt_ms)); + for (size_t i = 0; i < CK_FLOW_CELLS; i++) + x[i] -= mul(x[i], k); +} + +static void step(ck_flow *f, uint32_t dt_ms) +{ + int32_t dt = (int32_t)((dt_ms << 16) / 1000); + for (int m = 0; m < 5; m++) { /* the modes' weights ease toward where they should be */ + uint32_t want = m == f->mode ? 256 : 0, cur = f->weight[m], stepw = 256 * dt_ms / BLEND_MS; + stepw = stepw ? stepw : 1; + f->weight[m] = cur < want ? ck_min((int32_t)want, (int32_t)(cur + stepw)) + : ck_max((int32_t)want, (int32_t)cur - (int32_t)stepw); + } + forces(f, dt_ms); + /* velocity */ + copy_field(f->u0, f->u); + copy_field(f->v0, f->v); + diffuse(f->u, f->u0, (int32_t)(VISC_PER_MS * dt_ms), 1); + diffuse(f->v, f->v0, (int32_t)(VISC_PER_MS * dt_ms), 2); + project(f->u, f->v, f->u0, f->v0); + copy_field(f->u0, f->u); + copy_field(f->v0, f->v); + advect(f->u, f->u0, f->u0, f->v0, dt, 1); + advect(f->v, f->v0, f->u0, f->v0, dt, 2); + project(f->u, f->v, f->u0, f->v0); + /* ink */ + copy_field(f->d0, f->d); + diffuse(f->d, f->d0, (int32_t)(INK_PER_MS * dt_ms), 0); + copy_field(f->d0, f->d); + advect(f->d, f->d0, f->u, f->v, dt, 0); + uint32_t still = f->weight[CK_FLOW_SLEEP]; /* asleep the ink goes faster */ + fade(f->d, INK_FADE_PER_MS + (int32_t)(INK_FADE_PER_MS * 3 * still >> 8), dt_ms); + fade(f->u, VEL_FADE_PER_MS, dt_ms); + fade(f->v, VEL_FADE_PER_MS, dt_ms); + /* how fast each cell moves, for the colour: 2 cells per second and up is fully warm */ + for (size_t i = 0; i < CK_FLOW_CELLS; i++) { + int64_t s2 = ((int64_t)f->u[i] * f->u[i] + (int64_t)f->v[i] * f->v[i]) >> 16; + uint32_t s = (uint32_t)ck_isqrt((uint64_t)s2) << 8; /* 16.16 cells per second */ + uint32_t warm = s >= 2 * Q ? 256 : s * 256 / (2 * Q); + f->warm[i] = (uint16_t)(f->warm[i] + ((int32_t)warm - (int32_t)f->warm[i]) * (int32_t)dt_ms / 250); + } + f->steps++; +} + +/* ---- the interface ---- */ + +void ck_flow_init(ck_flow *f, int32_t w, int32_t h, int32_t cx, int32_t cy, int32_t R, int32_t bx, int32_t by, + uint32_t t) +{ + *f = (ck_flow){0}; + f->w = w, f->h = h; + f->cw = ck_max(256, w * 256 / W); + f->ch = ck_max(256, h * 256 / H); + f->cx = cx, f->cy = cy, f->R = R, f->bx = bx, f->by = by; + f->t = f->stepped = t; + f->mode = CK_FLOW_SLEEP; /* still water until he is awake */ + f->weight[CK_FLOW_SLEEP] = 256; + f->rng = 0x9e3779b9u ^ (uint32_t)t; +} + +void ck_flow_mode(ck_flow *f, int mode, uint32_t t) +{ + if (mode < 0 || mode > CK_FLOW_SLEEP || mode == f->mode) + return; + f->mode = mode; + f->think_t = mode == CK_FLOW_THINK ? (t ? t : 1) : 0; +} + +void ck_flow_key(ck_flow *f, uint32_t t) +{ + f->key_t = t; + int32_t gx = cell_x(f, f->bx), gy = cell_y(f, f->by); + int32_t lx = cell_x(f, f->cx) - gx, ly = cell_y(f, f->cy) - gy; + int64_t len = ck_isqrt((uint64_t)(((int64_t)lx * lx + (int64_t)ly * ly) >> 16)) << 8; + if (len < Q) + len = Q; + int32_t speed = 5 * Q / 2; /* cells per second, toward Allen */ + push(f, gx, gy, (int32_t)((int64_t)lx * speed / len), (int32_t)((int64_t)ly * speed / len), Q / 2, Q); +} + +void ck_flow_word(ck_flow *f, uint32_t t) +{ + f->word_t = t; + int32_t cx = cell_x(f, f->cx), cy = cell_y(f, f->cy); + int32_t R = ck_max(Q / 2, (int32_t)(((int64_t)f->R << 24) / f->cw)); + for (unsigned k = 0; k < 12; k++) { /* a ring of twelve pushes, outward */ + uint32_t a = k * 65536 / 12 + (rnd(f) & 2047); + int32_t ux = ck_cos(a) << 2, uy = ck_sin(a) << 2; /* unit, 16.16 */ + push(f, cx + (int32_t)((int64_t)ux * R / 2 >> 16), cy + (int32_t)((int64_t)uy * R / 2 >> 16), + (int32_t)((int64_t)ux * (3 * Q / 2) >> 16), (int32_t)((int64_t)uy * (3 * Q / 2) >> 16), Q / 6, R / 2); + } +} + +void ck_flow_touch(ck_flow *f, int32_t px, int32_t py, int32_t vx, int32_t vy, int32_t ink, int32_t r) +{ + push(f, cell_x(f, px), cell_y(f, py), cells_x(f, vx), cells_y(f, vy), ink, + ck_max(Q / 4, (int32_t)(((int64_t)r << 24) / f->cw))); +} + +void ck_flow_at(ck_flow *f, uint32_t t) +{ + f->t = t; + /* Catch up in fixed steps; after a long gap (the frame core was resting) start from now. */ + if (t - f->stepped > 8 * CK_FLOW_STEP_MS) + f->stepped = t - 8 * CK_FLOW_STEP_MS; + while (t - f->stepped >= CK_FLOW_STEP_MS) { + f->stepped += CK_FLOW_STEP_MS; + step(f, CK_FLOW_STEP_MS); + } +} + +void ck_flow_velocity(const ck_flow *f, int32_t px, int32_t py, int32_t *vx, int32_t *vy) +{ + int32_t gx = cell_x(f, px), gy = cell_y(f, py); + *vx = (int32_t)(((int64_t)sample(f->u, gx, gy) * f->cw) >> 24); + *vy = (int32_t)(((int64_t)sample(f->v, gx, gy) * f->ch) >> 24); +} + +void ck_flow_mark(ck_flow *f, void (*mark)(ck_rect)) +{ + for (int32_t j = 0; j <= H + 1; j++) + for (int32_t i = 0; i <= W + 1; i++) { + int32_t now = f->d[IX(i, j)], was = f->shown[IX(i, j)]; + int32_t warm = f->warm[IX(i, j)], warm_was = f->shown_warm[IX(i, j)]; + if (ck_abs(now - was) < Q / 400 && (now < Q / 200 || ck_abs(warm - warm_was) < 24)) + continue; + f->shown[IX(i, j)] = now; + f->shown_warm[IX(i, j)] = (uint16_t)warm; + /* the cell and one cell round it (the interpolation reaches that far) */ + ck_rect r = {(int32_t)(((int64_t)(i - 2) * f->cw) >> 8), (int32_t)(((int64_t)(j - 2) * f->ch) >> 8), + (int32_t)((3 * (int64_t)f->cw >> 8) + 2), (int32_t)((3 * (int64_t)f->ch >> 8) + 2)}; + mark(r); + } +} + +void ck_flow_draw(const ck_flow *f, ck_canvas *out, const ck_rect *r, uint32_t gain) +{ + ck_rect c = *r; + ck_rect all = {0, 0, out->w, out->h}; + if (!ck_clip(&c, &all)) + return; + const uint32_t cool = CK_RGB(64, 86, 196), warm = CK_RGB(255, 228, 196); + int64_t dgx = ((int64_t)1 << 24) / f->cw, dgy = ((int64_t)1 << 24) / f->ch; /* grid per pixel, 16.16 */ + int64_t gy = cell_y(f, c.y); + for (int32_t y = c.y; y < c.y + c.h; y++, gy += dgy) { + uint32_t *px = out->px + (size_t)y * (size_t)out->w; + int64_t gx = cell_x(f, c.x); + for (int32_t x = c.x; x < c.x + c.w; x++, gx += dgx) { + int32_t ink = sample(f->d, (int32_t)gx, (int32_t)gy); + if (ink < Q / 512) + continue; + uint32_t a = (uint32_t)(((int64_t)ink * gain) >> 16); + a = a > 230 ? 230 : a; + /* the colour: still water deep blue, moving water lit from within */ + int32_t gxx = ck_clamp((int32_t)gx - HALF, 0, (W + 1) * Q - 1), gyy = ck_clamp((int32_t)gy - HALF, 0, (H + 1) * Q - 1); + uint32_t w = f->warm[IX(gxx >> 16, gyy >> 16)]; + uint32_t col = ck_mix(cool, warm, w); + px[x] = ck_add(px[x], col, a); + } + } +} + +int64_t ck_flow_ink(const ck_flow *f) +{ + int64_t s = 0; + for (size_t i = 0; i < CK_FLOW_CELLS; i++) + s += f->d[i]; + return s; +} diff --git a/om/allen-scene/native/flow.h b/om/allen-scene/native/flow.h new file mode 100644 index 0000000..b29db82 --- /dev/null +++ b/om/allen-scene/native/flow.h @@ -0,0 +1,76 @@ +/* flow.h -- Allen's ink: a fluid that fills the screen around him. + * + * The whole screen is a shallow tank of water with a little luminous ink in + * it. What Allen does moves the water, and the ink shows the movement: + * idle a slow warm current turns round him, the ink drifts and thins. + * listening every key typed drops ink at the bar and lifts it toward him; + * the line you type flows up into him before he answers. + * thinking the water round him turns into a vortex, ink streams out of + * his heart along it; the longer he thinks, the deeper it turns. + * speaking each word pushes a ring of water out from the heart. + * asleep nothing pushes; the water stills and the ink fades. + * No state is ever cut to: forces ease in and out, and the water carries + * everything that was moving on until it settles. + * + * The solver is Stam's stable fluid (Jos Stam, "Real-Time Fluid Dynamics for + * Games", GDC 2003; "Stable Fluids", SIGGRAPH 1999): add sources, diffuse, + * move along the flow (semi-Lagrangian), make the velocity divergence free + * (a Gauss-Seidel pressure solve). It never blows up whatever the time step, + * which is what a screen that must never stutter needs. Everything is + * integer: cells, velocities and ink in 16.16 fixed point, on a coarse grid + * (CK_FLOW_W x CK_FLOW_H cells over the screen), drawn with bilinear + * interpolation so the ink has no edges. Freestanding, no allocation (the + * fields live in the struct), host tested in ui/tests/allen_ui_test.c. + * ck_flow_at moves it on (one caller); ck_flow_draw only reads, so several + * cores can draw different parts of the screen at once. */ +#ifndef AIENOS_FLOW_H +#define AIENOS_FLOW_H +#include +#include +#include "paint.h" + +#define CK_FLOW_W 64u +#define CK_FLOW_H 36u +#define CK_FLOW_CELLS ((CK_FLOW_W + 2u) * (CK_FLOW_H + 2u)) /* with the border cells */ + +enum { CK_FLOW_IDLE, CK_FLOW_LISTEN, CK_FLOW_THINK, CK_FLOW_SPEAK, CK_FLOW_SLEEP }; + +typedef struct { + int32_t w, h; /* the screen, px */ + int32_t cw, ch; /* one cell, 1/256 px (the grid covers the screen exactly) */ + int32_t cx, cy, R; /* Allen's centre and radius, px */ + int32_t bx, by; /* where typed lines start from (the bar), px */ + uint32_t t, stepped; /* now, and the time of the last solver step (ms) */ + int mode; + uint32_t weight[5]; /* how far each mode's pull has eased in, 0..256; they add up */ + uint32_t think_t, word_t, key_t; /* when thinking began (0: not), the last word, the last key */ + uint32_t rng; + /* the fields, 16.16: velocity in cells per second, ink 0..1 */ + int32_t u[CK_FLOW_CELLS], v[CK_FLOW_CELLS], d[CK_FLOW_CELLS]; + int32_t u0[CK_FLOW_CELLS], v0[CK_FLOW_CELLS], d0[CK_FLOW_CELLS]; + int32_t shown[CK_FLOW_CELLS]; /* the ink each cell showed at the last mark */ + uint16_t warm[CK_FLOW_CELLS]; /* how fast the water moves in each cell, 0..256, for the colour */ + uint16_t shown_warm[CK_FLOW_CELLS]; + uint32_t steps; +} ck_flow; + +/* The screen w x h, Allen at (cx, cy) with radius R, the bar's mouth at (bx, by). */ +void ck_flow_init(ck_flow *f, int32_t w, int32_t h, int32_t cx, int32_t cy, int32_t R, int32_t bx, int32_t by, + uint32_t t); +void ck_flow_mode(ck_flow *f, int mode, uint32_t t); +void ck_flow_key(ck_flow *f, uint32_t t); /* a key was typed: a drop at the bar, lifted toward Allen */ +void ck_flow_word(ck_flow *f, uint32_t t); /* a word was spoken: a ring from the heart */ +/* A push at (px, py): velocity (vx, vy) in px per second and ink (0..65536) over radius r px. */ +void ck_flow_touch(ck_flow *f, int32_t px, int32_t py, int32_t vx, int32_t vy, int32_t ink, int32_t r); +/* Moves the water to time t (ms); the solver steps at most every CK_FLOW_STEP_MS). */ +#define CK_FLOW_STEP_MS 16u +void ck_flow_at(ck_flow *f, uint32_t t); +/* The water's velocity at a point, px per second (for things that float on it). */ +void ck_flow_velocity(const ck_flow *f, int32_t px, int32_t py, int32_t *vx, int32_t *vy); +/* Calls mark(rect) for every cell whose ink changed enough to redraw since the last call. */ +void ck_flow_mark(ck_flow *f, void (*mark)(ck_rect)); +/* The ink into the part r of out (light added). gain scales the brightness (256 = as is). */ +void ck_flow_draw(const ck_flow *f, ck_canvas *out, const ck_rect *r, uint32_t gain); +/* Total ink in the tank, 16.16 (for tests: it rises when touched and fades when left). */ +int64_t ck_flow_ink(const ck_flow *f); +#endif diff --git a/om/allen-scene/native/mind.c b/om/allen-scene/native/mind.c new file mode 100644 index 0000000..427136d --- /dev/null +++ b/om/allen-scene/native/mind.c @@ -0,0 +1,266 @@ +/* mind.c -- Allen's presence; see mind.h. */ +#include "mind.h" + +#define S(v) ((int32_t)(((int64_t)(v) * (int64_t)m->k + 128) / 256)) +#define INNER 24u /* the last INNER points sit inside the sphere */ +#define TILT 3641u /* the upright axis leans toward the viewer by 20 degrees, in 65536ths */ + +static uint32_t rnd(ck_mind *m) +{ + m->rng ^= m->rng << 13; + m->rng ^= m->rng >> 17; + m->rng ^= m->rng << 5; + return m->rng; +} + +static int64_t dist2(const int16_t *a, const int16_t *b) +{ + int64_t dx = a[0] - b[0], dy = a[1] - b[1], dz = a[2] - b[2]; + return dx * dx + dy * dy + dz * dz; +} + +static int has_edge(const ck_mind *m, unsigned a, unsigned b) +{ + for (unsigned i = 0; i < m->ne; i++) + if ((m->ea[i] == a && m->eb[i] == b) || (m->ea[i] == b && m->eb[i] == a)) + return 1; + return 0; +} + +void ck_mind_init(ck_mind *m, int32_t cx, int32_t cy, uint32_t k, uint32_t born) +{ + *m = (ck_mind){0}; + m->cx = cx, m->cy = cy, m->k = k, m->born = born; + m->R = S(118); + m->rng = 0x9e3779b9u; + m->spin = 349; /* a turn in 48 s */ + unsigned outer = CK_MIND_NODES - INNER; + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + int64_t y, rr, x, z, len; + if (i < outer) { /* evenly spread over the sphere: a Fibonacci lattice */ + y = 16384 - (int64_t)(2 * i + 1) * 16384 / outer; + rr = (int64_t)ck_isqrt((uint64_t)(16384 * 16384 - y * y)); + uint32_t th = (uint32_t)(i * 25033u); /* the golden angle */ + x = rr * ck_cos(th) >> 14, z = rr * ck_sin(th) >> 14; + len = 16384 - 2950 + (int64_t)(ck_hash((int32_t)i, 1, 31) % 5900u); /* +-18%: a cloud, not a ball */ + } else { + uint32_t h1 = ck_hash((int32_t)i, 2, 31), h2 = ck_hash((int32_t)i, 3, 31); + y = 16384 - (int64_t)(h1 % 32768u); + rr = (int64_t)ck_isqrt((uint64_t)(16384 * 16384 - y * y)); + x = rr * ck_cos(h2) >> 14, z = rr * ck_sin(h2) >> 14; + len = 4915 + (int64_t)(ck_hash((int32_t)i, 4, 31) % 5734u); /* 0.30 .. 0.65 */ + } + m->home[i][0] = (int16_t)(x * len >> 14); + m->home[i][1] = (int16_t)(y * len >> 14); + m->home[i][2] = (int16_t)(z * len >> 14); + } + /* each point joined to its nearest two (the inner ones to three) */ + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + unsigned want = i < outer ? 2 : 3; + for (unsigned w = 0; w < want; w++) { + int best = -1; + int64_t bd = 0; + for (unsigned j = 0; j < CK_MIND_NODES; j++) { + if (j == i || has_edge(m, i, j)) + continue; + int64_t d = dist2(m->home[i], m->home[j]); + if (best < 0 || d < bd) + best = (int)j, bd = d; + } + if (best >= 0 && m->ne < CK_MIND_EDGES) + m->ea[m->ne] = (uint8_t)i, m->eb[m->ne] = (uint8_t)best, m->ne++; + } + } +} + +void ck_mind_mode(ck_mind *m, int mode, uint32_t t) +{ + (void)t; + m->mode = mode; +} + +static void push(uint32_t *ring, uint32_t t) +{ + for (unsigned i = 3; i > 0; i--) + ring[i] = ring[i - 1]; + ring[0] = t ? t : 1; +} + +void ck_mind_word(ck_mind *m, uint32_t t) { push(m->words, t); } +void ck_mind_key(ck_mind *m, uint32_t t) { push(m->keys, t); } +void ck_mind_voice(ck_mind *m, uint32_t level) { m->voice = level > 256 ? 256 : level; } + +static void spark(ck_mind *m, unsigned from) +{ + if (m->nspark >= CK_MIND_SPARKS || !m->ne) + return; + /* a thread leaving `from`, or any thread when from is out of range */ + unsigned e = rnd(m) % m->ne, tries = 0; + if (from < CK_MIND_NODES) + while (m->ea[e] != from && m->eb[e] != from && tries++ < m->ne) + e = (e + 1) % m->ne; + unsigned s = m->nspark++; + m->spark[s].e = (uint16_t)e; + m->spark[s].back = (uint8_t)(from < CK_MIND_NODES ? m->eb[e] == from : rnd(m) & 1); + m->spark[s].t0 = m->t; + m->spark[s].dur = (uint16_t)(m->mode == CK_MIND_THINK ? 240 + rnd(m) % 260 : 420 + rnd(m) % 480); +} + +static uint32_t toward(uint32_t cur, uint32_t want, uint32_t dt, uint32_t ms) +{ + int64_t d = (int64_t)want - cur, step = d * (int64_t)(dt < ms ? dt : ms) / (int64_t)ms; + if (step == 0 && d && dt) + step = d > 0 ? 1 : -1; + return (uint32_t)((int64_t)cur + step); +} + +static uint32_t pulse(int32_t off, int32_t width) /* (1 - (off/width)^2)^2, 0..256 */ +{ + if (off <= -width || off >= width) + return 0; + int64_t q = 256 - (int64_t)off * off * 256 / ((int64_t)width * width); + return (uint32_t)(q * q >> 8); +} + +void ck_mind_at(ck_mind *m, uint32_t t) +{ + uint32_t dt = t > m->t ? t - m->t : 0; + if (dt > 250) + dt = 250; /* a long pause is not a jump */ + m->t = t; + m->was = m->box; + if (t < m->born) { + m->alpha = 0; + m->box = (ck_rect){0, 0, 0, 0}; + return; + } + static const uint32_t spins[4] = {349, 520, 1400, 600}, squeezes[4] = {0, 4, 16, 0}, hearts[4] = {50, 70, 120, 80}, + rates[4] = {2, 6, 25, 12}; + int md = m->mode & 3; + m->spin = toward(m->spin, spins[md], dt, 700); + m->squeeze = toward(m->squeeze, squeezes[md], dt, 500); + uint32_t want_heart = hearts[md] + (md == CK_MIND_SPEAK ? m->voice * 120 / 256 : 0); + if (md == CK_MIND_THINK) + want_heart += (uint32_t)(16384 + ck_sin(t * 65536u / 900u)) * 30 >> 15; + m->heart = toward(m->heart, want_heart, dt, md == CK_MIND_SPEAK ? 80 : 400); + m->angle += m->spin * dt; + + /* sparks: born at the mode's rate; each that arrives lights its point, and while thinking may go on */ + uint32_t form = (uint32_t)ck_prog(t, m->born, m->born + CK_MIND_FORM_MS); + if (form >= 192) { + m->spawn += rates[md] * dt; + while (m->spawn >= 1000) { + m->spawn -= 1000; + spark(m, CK_MIND_NODES); + } + } + for (unsigned i = 0; i < m->nspark;) { + uint32_t age = t - m->spark[i].t0; + if (age < m->spark[i].dur) { + i++; + continue; + } + unsigned e = m->spark[i].e, to = m->spark[i].back ? m->ea[e] : m->eb[e]; + m->act[to] = 256; + m->spark[i] = m->spark[--m->nspark]; + if (md == CK_MIND_THINK ? rnd(m) % 100 < 70 : rnd(m) % 100 < 18) + spark(m, to); + } + for (unsigned i = 0; i < CK_MIND_NODES; i++) + m->act[i] = (uint16_t)(m->act[i] * (uint32_t)ck_exp_neg(dt * 256 / 260) >> 16); + + /* the shape: breathing, drawn in while thinking, and while being born gathered in from far out */ + int64_t scale = 65536 + ((int64_t)ck_sin(t * 65536u / 5500u) * 1966 >> 14) - (int64_t)m->squeeze * 65536 / 256; + uint32_t gather = ck_ease_out((int32_t)form); + scale = scale * (256 + (int64_t)(256 - gather) * 560 / 256) >> 8; /* 3.2 times out at the start */ + uint32_t swirl = (256 - gather) * (256 - gather) >> 8; /* an extra spiral turn that unwinds as it gathers */ + m->alpha = ck_smooth((int32_t)form * 3); + uint32_t a = (m->angle >> 8) + swirl * 256; + int64_t ca = ck_cos(a), sa = ck_sin(a), ct = ck_cos(TILT), st = ck_sin(TILT); + int64_t R16 = (int64_t)m->R * 16; + int32_t x0 = m->cx * 16, x1 = x0, y0 = m->cy * 16, y1 = y0; + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + int64_t x = m->home[i][0], y = m->home[i][1], z = m->home[i][2]; + int64_t rx = (x * ca - z * sa) >> 14, rz = (x * sa + z * ca) >> 14; /* turn about the upright axis */ + int64_t ry = (y * ct - rz * st) >> 14, fz = (y * st + rz * ct) >> 14; /* lean toward the viewer */ + int64_t persp = 16384 + fz * 3 / 16; /* nearer is a little larger */ + m->px[i] = (int32_t)(m->cx * 16 + 8 + (rx * persp >> 14) * R16 / 16384 * scale / 65536); + m->py[i] = (int32_t)(m->cy * 16 + 8 + (ry * persp >> 14) * R16 / 16384 * scale / 65536); + uint32_t nr = (uint32_t)((fz + 16384) * 256 / 32768); + m->near[i] = (uint16_t)(nr > 256 ? 256 : nr); + /* light from the pulses: words outward from the heart, keys upward from below */ + int64_t rad = (int64_t)ck_isqrt((uint64_t)(x * x + y * y + z * z)) * 256 / 16384; + uint32_t extra = 0; + for (unsigned w = 0; w < 4; w++) { + if (m->words[w] && t - m->words[w] < 900) { + uint32_t age = t - m->words[w]; + extra += pulse((int32_t)rad - (int32_t)(age * 300 / 600), 70) * (900 - age) / 900 * 150 >> 8; + } + if (m->keys[w] && t - m->keys[w] < 600) { + uint32_t age = t - m->keys[w]; + int32_t ky = 300 - (int32_t)(age * 600 / 500), ny = (int32_t)(y * 256 / 16384); + extra += pulse(ny - ky, 60) * (600 - age) / 600 * 90 >> 8; + } + } + uint32_t l = 34 + m->near[i] * m->near[i] / 256 * 180 / 256 + extra + m->act[i] * 120 / 256; + m->lum[i] = (uint16_t)(l > 256 ? 256 : l); + x0 = ck_min(x0, m->px[i]), x1 = ck_max(x1, m->px[i]); + y0 = ck_min(y0, m->py[i]), y1 = ck_max(y1, m->py[i]); + } + m->hx = m->cx * 16 + 8, m->hy = m->cy * 16 + 8; + m->hr = (int32_t)(R16 * 52 / 100 * scale / 65536); + int32_t halo = (int32_t)(R16 * 17 / 10 * ck_min((int32_t)(scale >> 8), 256) / 256); + int32_t pad = S(8) * 16; + x0 = ck_min(x0 - pad, m->hx - halo), x1 = ck_max(x1 + pad, m->hx + halo); + y0 = ck_min(y0 - pad, m->hy - halo), y1 = ck_max(y1 + pad, m->hy + halo); + m->box = (ck_rect){(x0 >> 4) - 1, (y0 >> 4) - 1, ((x1 - x0) >> 4) + 3, ((y1 - y0) >> 4) + 3}; +} + +ck_rect ck_mind_dirty(const ck_mind *m) { return ck_union(m->was, m->box); } + +void ck_mind_draw(const ck_mind *m, ck_canvas *out, const ck_rect *r) +{ + if (!m->alpha || !ck_meets(m->box, r)) + return; + uint32_t A = m->alpha, form = (uint32_t)ck_prog(m->t, m->born, m->born + CK_MIND_FORM_MS); + int64_t R16 = (int64_t)m->R * 16; + /* the halo: a faint blue light round the whole mind, swelling a little with the heart */ + ck_glow(out, r, m->hx, m->hy, (int32_t)(R16 * 17 / 10), CK_RGB(60, 74, 210), (52 + m->heart / 8) * A >> 8); + ck_glow(out, r, m->hx, m->hy, (int32_t)R16, CK_RGB(112, 92, 255), (30 + m->heart / 8) * A >> 8); + /* the threads, fading in once the points have mostly gathered */ + uint32_t ta = ck_smooth(((int32_t)form - 128) * 2) * A >> 8; + if (ta) + for (unsigned i = 0; i < m->ne; i++) { + unsigned a = m->ea[i], b = m->eb[i]; + uint32_t a0 = (m->lum[a] * (16u + m->near[a] * 60u / 256u) >> 8) * ta >> 8, + a1 = (m->lum[b] * (16u + m->near[b] * 60u / 256u) >> 8) * ta >> 8; + ck_thread(out, r, m->px[a], m->py[a], m->px[b], m->py[b], CK_RGB(120, 140, 255), a0, a1); + if (m->k > 320) /* a second strand on big screens, so the thread keeps its weight */ + ck_thread(out, r, m->px[a], m->py[a] + 16, m->px[b], m->py[b] + 16, CK_RGB(120, 140, 255), a0 / 2, + a1 / 2); + } + /* the points: pale blue-white, warming as they light */ + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + int32_t rad = (int32_t)((int64_t)S(3) * 16 * (160 + m->near[i] * 120 / 256) >> 8); + uint32_t c = ck_mix(CK_RGB(206, 222, 255), CK_RGB(255, 214, 160), m->act[i]); + ck_glow(out, r, m->px[i], m->py[i], rad * 3, c, (m->lum[i] * 50 >> 8) * A >> 8); + ck_glow(out, r, m->px[i], m->py[i], rad, c, m->lum[i] * A >> 8); + } + /* the sparks, each with a short fading tail */ + for (unsigned i = 0; i < m->nspark; i++) { + unsigned e = m->spark[i].e, a = m->ea[e], b = m->eb[e]; + if (m->spark[i].back) + a = m->eb[e], b = m->ea[e]; + int32_t f = (int32_t)((m->t - m->spark[i].t0) * 256u / m->spark[i].dur); + for (int k = 0; k < 3; k++) { + int32_t g = ck_clamp(f - k * 22, 0, 256); + int32_t x = m->px[a] + (int32_t)((int64_t)(m->px[b] - m->px[a]) * g >> 8); + int32_t y = m->py[a] + (int32_t)((int64_t)(m->py[b] - m->py[a]) * g >> 8); + ck_glow(out, r, x, y, S(5) * 16 - k * S(1) * 16, CK_RGB(255, 222, 176), (200 >> k) * A >> 8); + } + } + /* the heart: a warm light at the centre, and a small bright core */ + ck_glow(out, r, m->hx, m->hy, m->hr, CK_RGB(255, 210, 170), m->heart * 7 / 10 * A >> 8); + ck_glow(out, r, m->hx, m->hy, m->hr * 2 / 5, CK_RGB(255, 236, 214), (90 + m->heart) * A >> 8); + ck_glow(out, r, m->hx, m->hy, m->hr / 8, CK_RGB(255, 250, 240), 230 * A >> 8); +} diff --git a/om/allen-scene/native/mind.h b/om/allen-scene/native/mind.h new file mode 100644 index 0000000..ad99036 --- /dev/null +++ b/om/allen-scene/native/mind.h @@ -0,0 +1,76 @@ +/* mind.h -- Allen's presence: no face and no body, a mind drawn as light. + * + * About a hundred points of light sit on and inside a sphere, joined by fine + * threads into a network, turning slowly in three dimensions round a warm + * heart. Small sparks run along the threads from point to point; each one + * that arrives lights its point for a moment. How it moves is how Allen is: + * idle it breathes (a slow swell) and turns slowly; a few sparks. + * listening each key typed sends a soft wave of light up through it. + * thinking it draws in a little, turns faster, the heart brightens and + * sparks cascade through the whole network. + * speaking every word sends a pulse out from the heart, and the heart + * follows the voice. + * It is born from the light of the black holes' merger: the points start + * scattered wide and gather, spiralling, into the network. + * + * Integer only, freestanding. ck_mind_at moves it to a time (one caller); + * ck_mind_draw then only reads, so several processor cores can draw + * different parts of the screen at once. Host tested in + * ui/tests/allen_ui_test.c. */ +#ifndef AIENOS_MIND_H +#define AIENOS_MIND_H +#include +#include + +#include "paint.h" + +#define CK_MIND_NODES 120u +#define CK_MIND_EDGES 300u +#define CK_MIND_SPARKS 64u +#define CK_MIND_FORM_MS 3000u /* from born to fully gathered */ + +enum { CK_MIND_IDLE, CK_MIND_LISTEN, CK_MIND_THINK, CK_MIND_SPEAK }; + +typedef struct { + /* the shape, fixed at init */ + int32_t cx, cy, R; /* px */ + uint32_t k; + int16_t home[CK_MIND_NODES][3]; /* unit sphere, Q14 */ + uint8_t ea[CK_MIND_EDGES], eb[CK_MIND_EDGES]; + unsigned ne; + uint32_t born; /* ms */ + /* how it is, moved on by ck_mind_at */ + uint32_t t, rng, spawn; + int mode; + uint32_t angle; /* the turn so far, 1/256 of a 65536th */ + uint32_t spin, squeeze; /* eased toward the mode's: per-ms turn (same units), and 0..256 drawn in */ + uint32_t heart, voice; /* 0..256 */ + uint32_t words[4], keys[4]; /* when the last pulses began (ms; 0 none) */ + uint16_t act[CK_MIND_NODES]; /* how lit each point is, 0..256 */ + struct { + uint16_t e, dur; + uint8_t back; /* runs eb to ea */ + uint32_t t0; + } spark[CK_MIND_SPARKS]; + unsigned nspark; + /* the frame, worked out by ck_mind_at for ck_mind_draw */ + int32_t px[CK_MIND_NODES], py[CK_MIND_NODES]; /* 16ths of a pixel */ + uint16_t lum[CK_MIND_NODES], near[CK_MIND_NODES]; /* brightness 0..256; nearness 0..256 */ + uint32_t alpha; /* the whole figure, 0..256 */ + int32_t hx, hy, hr; /* the heart: 16ths of a pixel */ + ck_rect box, was; /* where it is now, and was the frame before */ +} ck_mind; + +/* (cx, cy) its centre, px; k the scale (1/256 px per design px); born the + * time it starts to gather (ms). */ +void ck_mind_init(ck_mind *m, int32_t cx, int32_t cy, uint32_t k, uint32_t born); +void ck_mind_mode(ck_mind *m, int mode, uint32_t t); +void ck_mind_word(ck_mind *m, uint32_t t); /* a word was spoken */ +void ck_mind_key(ck_mind *m, uint32_t t); /* a key was typed */ +void ck_mind_voice(ck_mind *m, uint32_t level); /* 0..256 */ +void ck_mind_at(ck_mind *m, uint32_t t); +/* The figure into the part r of out (light added). */ +void ck_mind_draw(const ck_mind *m, ck_canvas *out, const ck_rect *r); +/* What needs redrawing for this frame: where it was and where it is. */ +ck_rect ck_mind_dirty(const ck_mind *m); +#endif diff --git a/om/allen-scene/native/night.c b/om/allen-scene/native/night.c new file mode 100644 index 0000000..78b0c14 --- /dev/null +++ b/om/allen-scene/native/night.c @@ -0,0 +1,780 @@ +/* night.c -- the night sky and the merging black holes; see night.h. + * + * The sky is the real one (ui/sky_real.c, from ui/sky_data.c): the + * Milky Way from a photograph of the whole sky, worked out at a quarter of + * the screen's resolution (it is smooth anyway; the photograph's own + * stars are taken out), scaled up with a 4 x 4 ordered dither so the faint + * gradients show no bands; then the catalogue's stars, at full resolution, + * on top. + * + * Bent light: a point mass moves the image of a star seen at angle theta + * from it to where the star really is, beta = theta - E^2 / theta (E the + * Einstein radius). Each pixel shows the sky at its own beta (with both + * holes' pulls added), so stars behind a hole stretch into arcs round it and + * a second, inner image appears on the far side. The pull is eased to zero + * between 2.2 E and 4.4 E so the bent region has no edge. It is worked out + * exactly near the holes and on an 8-pixel grid (and interpolated) further + * out, where it is smooth. The ripple adds a displacement along the radius + * that stretches one way and squeezes the other (cos 2 theta), the pattern + * a gravitational wave makes. */ +#include "night.h" +#include "sky_real.h" + +#define S(v) ((int32_t)(((int64_t)(v) * (int64_t)n->k + 128) / 256)) +#define Q30 (1ull << 30) + +/* ---- the galaxies: the real ones in the view (sky_real.c) ---- */ + +static uint8_t band_t[256]; /* the sweeping band: ((1 + cos) / 2)^6, 0..255 */ +static uint32_t pow2_t[257]; /* 2^(k/256), Q16: for the dusk's distances without a square root per pixel */ + +static uint64_t pow2_q16(uint32_t x) /* 2^(x / 65536), Q16; x below 40 << 16 */ +{ + uint32_t n = x >> 16, f = x & 65535u, k = f >> 8, g = f & 255u; + uint64_t m = pow2_t[k] + ((uint64_t)(pow2_t[k + 1] - pow2_t[k]) * g >> 8); + return m << n; +} + +size_t ck_night_mem_bytes(uint32_t w, uint32_t h, uint32_t k) +{ + (void)k; + size_t n = (size_t)w * h * 4 + (size_t)(w / 4 + 1) * (h / 4 + 1) + 64; + for (unsigned i = 0; i < CK_NIGHT_GALAXIES; i++) { + ck_rect b = ck_sky_galaxy_bound(w, i); + n += (size_t)b.w * (size_t)b.h * 2; + } + return n; +} + +/* exp(-(v / width)^2), Q16 */ +static uint32_t gauss(int64_t v, int64_t width) /* exp(-(v/width)^2), Q16 */ +{ + int64_t q = v * 256 / (width ? width : 1); + if (q > 4095 || q < -4095) + return 0; + return ck_exp_neg((uint32_t)(q * q >> 8)); +} + +/* ---- the soft layer (the Milky Way): a quarter of the resolution, 16ths of a level ---- */ + +static void scale_up(ck_night *n, const uint16_t *q, int32_t qw) +{ + static const uint8_t bayer[16] = {0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5}; + for (int32_t y = 0; y < n->h; y++) { + int32_t qy = y >> 2, fy = y & 3; + const uint16_t *r0 = q + (size_t)qy * (size_t)qw * 3, *r1 = r0 + (size_t)qw * 3; + uint32_t *row = n->sky + (size_t)y * (size_t)n->w; + for (int32_t x = 0; x < n->w; x++) { + int32_t qx = x >> 2, fx = x & 3; + uint32_t d = bayer[(y & 3) * 4 + (x & 3)], c = 0; + for (int k = 0; k < 3; k++) { + uint32_t a = r0[qx * 3 + k] * (uint32_t)(4 - fx) + r0[qx * 3 + 3 + k] * (uint32_t)fx; + uint32_t b = r1[qx * 3 + k] * (uint32_t)(4 - fx) + r1[qx * 3 + 3 + k] * (uint32_t)fx; + uint32_t v = ((a * (uint32_t)(4 - fy) + b * (uint32_t)fy) / 16 + d) >> 4; + c = c << 8 | (v > 255 ? 255u : v); + } + row[x] = c; + } + } +} + +/* ---- coming out of the dark ---- */ + +static void appear_map(ck_night *n) +{ + int32_t ah = n->h / 4 + 1; + int64_t far = 0; + int32_t cs[4][2] = {{0, 0}, {n->w, 0}, {0, n->h}, {n->w, n->h}}; + for (int i = 0; i < 4; i++) { + int64_t dx = cs[i][0] - n->cx, dy = cs[i][1] - n->cy, d = (int64_t)ck_isqrt((uint64_t)(dx * dx + dy * dy)); + far = d > far ? d : far; + } + for (int32_t y = 0; y < ah; y++) + for (int32_t x = 0; x < n->aw; x++) { + int64_t px = (int64_t)x * 4, py = (int64_t)y * 4, dx = px - n->cx, dy = py - n->cy; + uint32_t a = ck_fbm((int32_t)(px * 640 / n->h), (int32_t)(py * 640 / n->h), 909, 4) >> 8; + uint32_t r = (uint32_t)((int64_t)ck_isqrt((uint64_t)(dx * dx + dy * dy)) * 255 / (far ? far : 1)); + n->appear[(size_t)y * (size_t)n->aw + (size_t)x] = (uint8_t)((a * 6 + r * 4) / 10); + } +} + +uint32_t ck_night_faded(const ck_night *n, int32_t x, int32_t y, uint32_t l) +{ + if (n->t >= CK_NIGHT_FADE_END_MS) + return 256; + x = ck_clamp(x, 0, n->w - 1), y = ck_clamp(y, 0, n->h - 1); + int32_t from = 300 + n->appear[(size_t)(y >> 2) * (size_t)n->aw + (size_t)(x >> 2)] * 12 + (int32_t)(255 - l) * 8; + int32_t dt = (int32_t)n->t - from; + return dt <= 0 ? 0 : dt >= 1365 ? 256 : ck_smooth(dt * 48 >> 8); +} + +static uint32_t fade_px(const ck_night *n, uint32_t c, int32_t x, int32_t y) +{ + uint32_t r = c >> 16 & 255, g = c >> 8 & 255, b = c & 255, l = r > g ? r : g; + l = l > b ? l : b; + uint32_t f = ck_night_faded(n, x, y, l); + return f >= 256 ? c : ck_scale(c, f); +} + +int ck_night_init(ck_night *n, uint32_t w, uint32_t h, uint32_t k, int32_t cx, int32_t cy, void *mem, size_t len, + void *scratch) +{ + if (!mem || !scratch || w < 64 || h < 64 || w > CK_NIGHT_W_MAX || len < ck_night_mem_bytes(w, h, k)) + return -1; + (void)ck_sin(0); /* the tables, before anything else could ask for them */ + for (unsigned i = 0; i < 256; i++) { + uint64_t c = (uint64_t)(16384 + ck_cos(i * 256u)) >> 1; /* Q14 */ + uint64_t c2 = c * c >> 14, c6 = (c2 * c2 >> 14) * c2 >> 14; + band_t[i] = (uint8_t)(c6 * 255 >> 14); + } + uint64_t e2 = 1ull << 30; /* 2^(k/256): one factor of 2^(1/256) (Q30) per step */ + for (unsigned i = 0; i < 256; i++) { + pow2_t[i] = (uint32_t)((e2 + (1u << 13)) >> 14); + e2 = e2 * 1076652777ull >> 30; + } + pow2_t[256] = 131072; + *n = (ck_night){0}; + n->w = (int32_t)w, n->h = (int32_t)h, n->k = k, n->cx = cx, n->cy = cy; + uint8_t *p = mem; + n->sky = (uint32_t *)p; + p += (size_t)w * h * 4; + n->appear = p; + n->aw = (int32_t)(w / 4 + 1); + p += (size_t)(w / 4 + 1) * (h / 4 + 1); + int32_t qw = (int32_t)(w / 4 + 2), qh = (int32_t)(h / 4 + 2); + n->view = ck_sky_the_view; /* default view: GW150914 region */ + ck_sky_milkyway_q(scratch, qw, qh, n->w, cx, cy, &n->view); + scale_up(n, scratch, qw); + ck_canvas cv = {n->sky, n->w, n->h}; + ck_sky_draw_stars(&cv, k, cx, cy, &n->view, n->tw, CK_NIGHT_TWINKLES, &n->ntw); + for (unsigned i = 0; i < CK_NIGHT_GALAXIES; i++) { + ck_night_galaxy *g = &n->gal[i]; + g->box = ck_sky_galaxy_box(w, h, cx, cy, &n->view, i); + g->light = p; + g->phase = p + (size_t)g->box.w * (size_t)g->box.h; + p += (size_t)g->box.w * (size_t)g->box.h * 2; + ck_sky_galaxy_maps(g, i, w, cx, cy, &n->view); + } + appear_map(n); + ck_night_at(n, 0); + return 0; +} + +/* ---- the black holes and the ripple at a time ---- */ + +static uint64_t root8(uint64_t l) /* l^(1/8), Q30 */ +{ + for (int i = 0; i < 3; i++) + l = ck_isqrt(l << 30); + return l; +} + +#define ORBIT_MS 5200u /* one turn of the wide orbit */ + +static uint32_t orbit_angle(uint32_t t, int32_t *sep16, int32_t a0) +{ + uint32_t spiral_from = (CK_NIGHT_SPIRAL_MS - CK_NIGHT_HOLES_MS) * 65536u / ORBIT_MS; + if (t < CK_NIGHT_SPIRAL_MS) { + *sep16 = a0; + return (t - CK_NIGHT_HOLES_MS) * 65536u / ORBIT_MS; + } + uint64_t left = ((uint64_t)(CK_NIGHT_MERGE_MS - t) << 30) / (CK_NIGHT_MERGE_MS - CK_NIGHT_SPIRAL_MS); + uint64_t r = root8(left), r2 = r * r >> 30, r5 = (r2 * r2 >> 30) * r >> 30; + *sep16 = (int32_t)((uint64_t)a0 * r2 >> 30); + /* the spiral's angle carries on at the wide orbit's speed: K (1 - L^(5/8)), K = 8/5 x its turns */ + uint64_t turns = (uint64_t)65536 * 8 * (CK_NIGHT_MERGE_MS - CK_NIGHT_SPIRAL_MS) / (5ull * ORBIT_MS); + return spiral_from + (uint32_t)(turns * (Q30 - r5) >> 30); +} + +void ck_night_at(ck_night *n, uint32_t t) +{ + n->t = t; + n->holes = 0; + n->falling = 0; + n->lens = (ck_rect){0, 0, 0, 0}; + n->ripple_w = 0; + int32_t e_full = S(60) * 16, rs_full = S(20) * 16, a0 = S(270) * 16; + int32_t cx = n->cx * 16 + 8, cy = n->cy * 16 + 8; + int32_t sep; + uint32_t last = orbit_angle(CK_NIGHT_MERGE_MS - 1, &sep, a0); + if (t >= CK_NIGHT_HOLES_MS && t < CK_NIGHT_MERGE_MS) { + uint32_t ang = orbit_angle(t, &sep, a0); + int32_t e = (int32_t)((int64_t)e_full * ck_smooth(ck_prog(t, CK_NIGHT_HOLES_MS, CK_NIGHT_HOLES_MS + 2600)) >> 8); + int32_t rs = (int32_t)((int64_t)rs_full * + ck_smooth(ck_prog(t, CK_NIGHT_HOLES_MS + 1400, CK_NIGHT_HOLES_MS + 3400)) >> 8); + int32_t hx = (int32_t)((int64_t)(sep / 2) * ck_cos(ang) >> 14); + int32_t hy = (int32_t)((int64_t)(sep / 2) * ck_sin(ang) >> 15); /* the orbit leans away: half as tall */ + n->hole[0] = (__typeof__(n->hole[0])){cx + hx, cy + hy, e, rs}; + n->hole[1] = (__typeof__(n->hole[1])){cx - hx, cy - hy, e, rs}; + n->holes = 2; + } else if (t >= CK_NIGHT_MERGE_MS && t < CK_NIGHT_GONE_MS) { + uint32_t tm = t - CK_NIGHT_MERGE_MS; + int32_t e = e_full * 362 / 256, rs0 = rs_full * 323 / 256, rs1 = rs_full * 2; + int32_t rs = rs0 + (int32_t)((int64_t)(rs1 - rs0) * ck_smooth(ck_prog(tm, 0, 180)) >> 8); + /* it rings: a quick wobble that dies away */ + int64_t wob = (int64_t)ck_sin(tm * 65536u / 95u) * ck_exp_neg(tm * 256u / 260u) >> 16; + rs += (int32_t)(rs * wob * 7 / 100 >> 14); + uint32_t keep = 256 - ck_smooth(ck_prog(t, CK_NIGHT_MERGE_MS + 900, CK_NIGHT_GONE_MS)); + n->hole[0] = (__typeof__(n->hole[0])){cx, cy, (int32_t)((int64_t)e * keep >> 8), + (int32_t)((int64_t)rs * (keep * keep >> 8) >> 8)}; + n->holes = 1; + } + for (unsigned i = 0; i < n->holes; i++) { + int32_t reach = (n->hole[i].e * 44 / 10 >> 4) + 2; + if (n->hole[i].e <= 0 && n->hole[i].rs <= 0) + continue; + reach = ck_max(reach, (n->hole[i].rs * 16 / 10 >> 4) + 2); + ck_rect b = {(n->hole[i].x >> 4) - reach, (n->hole[i].y >> 4) - reach, 2 * reach + 1, 2 * reach + 1}; + n->lens = ck_union(n->lens, b); + } + ck_rect all = {0, 0, n->w, n->h}; + if (n->lens.w && !ck_clip(&n->lens, &all)) + n->lens = (ck_rect){0, 0, 0, 0}; + if (t >= CK_NIGHT_MERGE_MS && t < CK_NIGHT_MERGE_MS + CK_NIGHT_RIPPLE_MS) { + uint32_t tr = t - CK_NIGHT_MERGE_MS; + int32_t w = ck_clamp(S(60), 4, 200), reach = w * 22 / 10; + int64_t far = 0; + int32_t cs[4][2] = {{0, 0}, {n->w, 0}, {0, n->h}, {n->w, n->h}}; + for (int i = 0; i < 4; i++) { + int64_t dx = cs[i][0] - n->cx, dy = cs[i][1] - n->cy, d = (int64_t)ck_isqrt((uint64_t)(dx * dx + dy * dy)); + far = d > far ? d : far; + } + far += reach; + n->ripple_r = (int32_t)(far * tr / CK_NIGHT_RIPPLE_MS); + n->ripple_w = w; + uint32_t env = ck_smooth(ck_prog(tr, 0, 220)) * + (256 - ck_smooth(ck_prog(tr, CK_NIGHT_RIPPLE_MS * 6 / 10, CK_NIGHT_RIPPLE_MS))) >> 8; + int64_t amp = (int64_t)S(6) * 16 * (256 - 150 * n->ripple_r / far) >> 8; + amp = amp * env >> 8; + int32_t lambda = ck_max(S(110), 8); + for (int32_t i = 0; i <= 2 * reach && i < 1024; i++) { + int32_t o = i - reach; + int64_t s = ck_sin((uint32_t)((int64_t)o * 65536 / lambda)); + n->ripple_disp[i] = (int32_t)((amp * s >> 14) * gauss(o, w) >> 16); + n->ripple_light[i] = (uint8_t)((uint64_t)gauss(o, w * 6 / 10) * env * 46 >> 24); + } + /* it stretches along the line the pair last lay on, and squeezes across it */ + n->ripple_c2 = ck_cos(2 * last); + n->ripple_s2 = ck_sin(2 * last); + } +} + +/* ---- drawing the base ---- */ + +static uint32_t lerp16(uint32_t a, uint32_t b, uint32_t f) /* f: 0..16 */ +{ + return ((((a & 0xff00ffu) * (16 - f) + (b & 0xff00ffu) * f) >> 4) & 0xff00ffu) | + ((((a & 0x00ff00u) * (16 - f) + (b & 0x00ff00u) * f) >> 4) & 0x00ff00u); +} + +/* the sky at (sx, sy), 16ths of a pixel (pixel i's centre at 16 i + 8) */ +static uint32_t sample(const ck_night *n, int32_t sx, int32_t sy) +{ + sx = ck_clamp(sx - 8, 0, (n->w - 1) * 16); + sy = ck_clamp(sy - 8, 0, (n->h - 1) * 16); + int32_t ix = sx >> 4, iy = sy >> 4, ix1 = ck_min(ix + 1, n->w - 1), iy1 = ck_min(iy + 1, n->h - 1); + const uint32_t *r0 = n->sky + (size_t)iy * (size_t)n->w, *r1 = n->sky + (size_t)iy1 * (size_t)n->w; + uint32_t fx = (uint32_t)sx & 15u, fy = (uint32_t)sy & 15u; + return lerp16(lerp16(r0[ix], r0[ix1], fx), lerp16(r1[ix], r1[ix1], fx), fy); +} + +/* the holes' pull on the light at (X, Y) (16ths of a pixel): added to (sx, sy), where the sky is read from */ +static void lens_at(const ck_night *n, int64_t X, int64_t Y, int64_t *sx, int64_t *sy) +{ + for (unsigned i = 0; i < n->holes; i++) { + int64_t e = n->hole[i].e, dx = X - n->hole[i].x, dy = Y - n->hole[i].y, d2 = dx * dx + dy * dy; + int64_t out = e * e * 1936 / 100, in = e * e * 484 / 100; /* (4.4 E)^2, (2.2 E)^2 */ + if (e <= 0 || d2 >= out) + continue; + if (d2 < 64) + d2 = 64; + int64_t f = e * e * 65536 / d2; + if (d2 > in) { + int64_t w = (out - d2) * 65536 / (out - in); + f = f * (w * w >> 16) >> 16; + } + *sx -= dx * f >> 16; + *sy -= dy * f >> 16; + } +} + +/* where (X, Y) (16ths of a pixel) looks in the sky: offset (ax, ay), and the ripple's own faint light */ +static void warp(const ck_night *n, int64_t X, int64_t Y, int32_t *ax, int32_t *ay, uint32_t *light) +{ + int64_t sx = 0, sy = 0; + *light = 0; + lens_at(n, X, Y, &sx, &sy); + if (n->ripple_w) { + int64_t dx = X - (n->cx * 16 + 8), dy = Y - (n->cy * 16 + 8), d2 = dx * dx + dy * dy; + int64_t r16 = (int64_t)ck_isqrt((uint64_t)d2), reach = n->ripple_w * 22 / 10; + int64_t i = (r16 >> 4) - n->ripple_r + reach; + if (r16 > 0 && i >= 0 && i <= 2 * reach && i < 1024) { + int64_t q = ((dx * dx - dy * dy) * n->ripple_c2 + 2 * dx * dy * n->ripple_s2) / d2; /* cos 2(theta - psi), Q14 */ + int64_t m = (int64_t)n->ripple_disp[i] * (5734 + (q * 10650 >> 14)) >> 14; + sx -= m * dx / r16; + sy -= m * dy / r16; + *light = n->ripple_light[i]; + } + } + *ax = (int32_t)sx; + *ay = (int32_t)sy; +} + +static uint32_t finish(const ck_night *n, uint32_t c, int32_t x, int32_t y, uint32_t light) +{ + if (n->t < CK_NIGHT_FADE_END_MS) + c = fade_px(n, c, x, y); + return light ? ck_add(c, CK_RGB(86, 108, 176), light) : c; +} + +/* a pixel close to a hole: the pull worked out exactly, then the shadow and its thin ring of light */ +static uint32_t near_px(const ck_night *n, int32_t x, int32_t y) +{ + int64_t X = (int64_t)x * 16 + 8, Y = (int64_t)y * 16 + 8; + int32_t ax, ay; + uint32_t light; + warp(n, X, Y, &ax, &ay, &light); + uint32_t c = finish(n, sample(n, (int32_t)X + ax, (int32_t)Y + ay), x, y, light); + for (unsigned i = 0; i < n->holes; i++) { + int64_t rs = n->hole[i].rs, dx = X - n->hole[i].x, dy = Y - n->hole[i].y, d2 = dx * dx + dy * dy; + if (rs <= 0 || d2 >= rs * rs * 9 / 4) + continue; + int32_t r = (int32_t)ck_isqrt((uint64_t)d2); + c = ck_mix(c, 0, ck_cover(r - (int32_t)rs)); + int32_t ring = ck_abs(r - (int32_t)(rs * 104 / 100)); + uint32_t a = ring < 22 ? (uint32_t)(22 - ring) * 6 : 0; + if (r > rs) + a += (uint32_t)((rs * 3 / 2 - r) * 46 / (rs / 2 + 1)) * (r < rs * 3 / 2); + c = ck_add(c, CK_RGB(255, 228, 196), a); + } + return c; +} + +static int near_hole(const ck_night *n, int32_t x, int32_t y) +{ + int64_t X = (int64_t)x * 16 + 8, Y = (int64_t)y * 16 + 8; + for (unsigned i = 0; i < n->holes; i++) { + int64_t reach = ck_max(n->hole[i].e, n->hole[i].rs * 3 / 2) + 8 * 16; + int64_t dx = X - n->hole[i].x, dy = Y - n->hole[i].y; + if (dx * dx + dy * dy < reach * reach) + return 1; + } + return 0; +} + +/* does the 8 x 8 block at (bx, by) meet the band the ripple bends? */ +static int in_ripple(const ck_night *n, int32_t bx, int32_t by) +{ + if (!n->ripple_w) + return 0; + int64_t reach = n->ripple_w * 22 / 10 + 1, lo = ck_max(0, n->ripple_r - (int32_t)reach), hi = n->ripple_r + reach; + int64_t nx = ck_clamp(n->cx, bx, bx + 8) - n->cx, ny = ck_clamp(n->cy, by, by + 8) - n->cy; + int64_t fx = ck_max(ck_abs(bx - n->cx), ck_abs(bx + 8 - n->cx)), fy = ck_max(ck_abs(by - n->cy), ck_abs(by + 8 - n->cy)); + return nx * nx + ny * ny <= hi * hi && fx * fx + fy * fy >= lo * lo; +} + +void ck_night_base(const ck_night *n, ck_canvas *out, const ck_rect *r) +{ + ck_rect d = *r, all = {0, 0, n->w, n->h}; + if (!ck_clip(&d, &all)) + return; + int fading = n->t < CK_NIGHT_FADE_END_MS; + for (int32_t y = d.y; y < d.y + d.h; y++) { + const uint32_t *src = n->sky + (size_t)y * (size_t)n->w; + uint32_t *dst = out->px + (size_t)y * (size_t)out->w; + if (fading) + for (int32_t x = d.x; x < d.x + d.w; x++) + dst[x] = fade_px(n, src[x], x, y); + else + for (int32_t x = d.x; x < d.x + d.w; x++) + dst[x] = src[x]; + } + if (!n->lens.w && !n->ripple_w) + return; + /* the bent parts, in 8 x 8 blocks on a grid fixed to the screen, so any split of r draws the same */ + for (int32_t by = d.y & ~7; by < d.y + d.h; by += 8) + for (int32_t bx = d.x & ~7; bx < d.x + d.w; bx += 8) { + ck_rect b = {bx, by, 8, 8}; + int lens = n->lens.w && ck_meets(b, &n->lens); + if (!lens && !in_ripple(n, bx, by)) + continue; + if (!ck_clip(&b, &d)) + continue; + if (lens && near_hole(n, bx + 4, by + 4)) { + for (int32_t y = b.y; y < b.y + b.h; y++) + for (int32_t x = b.x; x < b.x + b.w; x++) + out->px[(size_t)y * (size_t)out->w + (size_t)x] = near_px(n, x, y); + continue; + } + int32_t ax[4], ay[4]; + uint32_t li[4]; + for (int c = 0; c < 4; c++) + warp(n, ((int64_t)bx + (c & 1) * 8) * 16, ((int64_t)by + (c >> 1) * 8) * 16, &ax[c], &ay[c], &li[c]); + for (int32_t y = b.y; y < b.y + b.h; y++) { + int32_t wy = 2 * (y - by) + 1; + for (int32_t x = b.x; x < b.x + b.w; x++) { + int32_t wx = 2 * (x - bx) + 1; + int32_t w00 = (16 - wx) * (16 - wy), w10 = wx * (16 - wy), w01 = (16 - wx) * wy, w11 = wx * wy; + int32_t sx = (ax[0] * w00 + ax[1] * w10 + ax[2] * w01 + ax[3] * w11) >> 8; + int32_t sy = (ay[0] * w00 + ay[1] * w10 + ay[2] * w01 + ay[3] * w11) >> 8; + uint32_t l = (uint32_t)((int32_t)li[0] * w00 + (int32_t)li[1] * w10 + (int32_t)li[2] * w01 + + (int32_t)li[3] * w11) >> 8; + uint32_t c = sample(n, x * 16 + 8 + sx, y * 16 + 8 + sy); + out->px[(size_t)y * (size_t)out->w + (size_t)x] = finish(n, c, x, y, l); + } + } + } +} + +/* ---- the dusk: everything on the screen falls into one black hole ---- */ + +size_t ck_night_picture_bytes(uint32_t w, uint32_t h) +{ + size_t n = 64 + (size_t)w * h * 4; + for (unsigned i = 1; i < CK_NIGHT_LEVELS; i++) + n += (size_t)(w >> i) * (size_t)(h >> i) * 4 * 2; + return n; +} + +/* half the width and height of `from` (sw x sh) into to: the mean of each 2 x 2 */ +static void halve(const uint32_t *from, uint32_t sw, uint32_t sh, uint32_t *to) +{ + uint32_t dw = sw / 2, dh = sh / 2; + for (uint32_t y = 0; y < dh; y++) { + const uint32_t *r0 = from + (size_t)(2 * y) * sw, *r1 = r0 + sw; + uint32_t *d = to + (size_t)y * dw; + for (uint32_t x = 0; x < dw; x++) { + uint32_t a = r0[2 * x], b = r0[2 * x + 1], c = r1[2 * x], e = r1[2 * x + 1]; + /* red and blue summed together, green on its own: the sums do not run into each other */ + uint32_t rb = (((a & 0xff00ffu) + (b & 0xff00ffu) + (c & 0xff00ffu) + (e & 0xff00ffu)) >> 2) & 0xff00ffu; + uint32_t g = (((a & 0xff00u) + (b & 0xff00u) + (c & 0xff00u) + (e & 0xff00u)) >> 2) & 0xff00u; + d[x] = rb | g; + } + } +} + +void ck_night_picture_take(const ck_night *n, const uint32_t *from, void *mem, ck_night_picture *kept) +{ + uint32_t w = (uint32_t)n->w, h = (uint32_t)n->h, *p = mem; + size_t count = (size_t)w * h; + for (size_t i = 0; i < count; i++) + p[i] = from[i]; + kept->level[0] = p; + kept->sky[0] = n->sky; + p += count; + for (unsigned l = 1; l < CK_NIGHT_LEVELS; l++) { + uint32_t sw = w >> (l - 1), sh = h >> (l - 1); + halve(kept->level[l - 1], sw, sh, p); + kept->level[l] = p; + p += (size_t)(sw / 2) * (sh / 2); + halve(kept->sky[l - 1], sw, sh, p); + kept->sky[l] = p; + p += (size_t)(sw / 2) * (sh / 2); + } +} + +void ck_night_fall(ck_night *n, const ck_night_dusk *d) +{ + n->falling = 1; + n->dusk = *d; + int32_t cx = n->cx * 16 + 8, cy = n->cy * 16 + 8, rs = d->rs; + n->hole[0] = (__typeof__(n->hole[0])){cx, cy, d->e, rs}; + n->holes = 1; + n->ripple_w = 0; + n->lens = (ck_rect){0, 0, n->w, n->h}; + /* The disk and the ring, by distance from the hole, in 1024 steps out to 3.3 shadow radii. The disk is + * dark inside 1.15 radii, brightest at 1.5 and dies away beyond; its colour runs from warm white at the + * inner edge through gold to the blue of the sky's glow. The photon ring is a thin bright line at 1.06 + * radii, a pixel and a quarter each way (wider on a big screen). */ + n->disk_far = rs * 33 / 10 + 16; + int32_t in = rs * 115 / 100, peak = rs * 150 / 100, ring = rs * 106 / 100, hw = 20 + rs / 64; + for (unsigned i = 0; i < 1024; i++) { + int32_t r = (int32_t)((int64_t)n->disk_far * (int64_t)i / 1024); + uint32_t a = 0, c = CK_RGB(255, 222, 180); + if (r >= in && peak > in) { + if (r < peak) { + uint32_t u = (uint32_t)((int64_t)(r - in) * 256 / (peak - in)); + a = ck_smooth((int32_t)u) * 220 >> 8; + c = ck_mix(CK_RGB(255, 222, 180), CK_RGB(255, 212, 150), u); + } else { + uint32_t v = (uint32_t)((int64_t)(r - peak) * 256 / (rs / 2 + 1)); /* half radii past the peak, 256 each */ + a = (ck_exp_neg(v) >> 8) * 220 >> 8; + c = ck_mix(CK_RGB(255, 212, 150), CK_RGB(150, 170, 255), ck_smooth((int32_t)(v * 256 / 360))); + } + } + int32_t off = ck_abs(r - ring); + if (off < hw) { + uint32_t ar = (uint32_t)(hw - off) * 255 / (uint32_t)hw; + ar = ar * ar >> 8; + c = a + ar ? ck_mix(c, CK_RGB(255, 244, 228), ar * 256 / (a + ar)) : c; + a += ar; + } + a = a * d->disk >> 8; + n->disk_a[i] = (uint8_t)(a > 255 ? 255 : a); + n->disk_c[i] = c; + } +} + +/* a corner of the 8 x 8 grid during the dusk: where the picture is read from, and the distance to the hole */ +struct corner { + int32_t ax, ay; /* offset to the picture point shown here, 16ths of a pixel */ + int32_t sx, sy; /* that point itself, 16ths (for telling whether a block shows only the dark beyond the edge) */ + uint32_t crowd; /* how much brighter the crowded light is drawn, 256 = as it is */ + uint32_t h; /* log2 of the crowding of the area, Q16 */ + int32_t r; /* distance from the hole, 16ths of a pixel */ + int32_t inv; /* 2^28 / r */ + uint32_t vig; /* how much of the light the edges of the screen keep here, 0..256 */ +}; + +static void corner_at(const ck_night *n, int32_t x, int32_t y, struct corner *c) +{ + const ck_night_dusk *d = &n->dusk; + int64_t X = (int64_t)x * 16, Y = (int64_t)y * 16, dx = X - n->hole[0].x, dy = Y - n->hole[0].y; + int64_t d2 = dx * dx + dy * dy; + if (d2 < 256) + d2 = 256; + uint32_t l0 = ck_log2_q16((uint64_t)d2), l1 = ck_log2_q16((uint64_t)(d2 + d->fallen)), h = l1 - l0; + c->h = h; + uint64_t crowd = pow2_q16(h) >> 8; + c->crowd = crowd > d->crowd ? d->crowd : (uint32_t)crowd; + /* the picture point: the same direction turned by swirl per doubling, at the stretched distance */ + int64_t r = (int64_t)(pow2_q16(l0 >> 1) >> 16); /* the distance, 16ths, without a square root */ + uint32_t ang = (uint32_t)((uint64_t)d->swirl * (h >> 1) >> 16); + ang = (uint32_t)((int64_t)ang * d->calm / (d->calm + r)); + int64_t stretch = (int64_t)pow2_q16(h >> 1), cs = ck_cos(ang), sn = ck_sin(ang); + int64_t ux = (dx * cs - dy * sn) >> 14, uy = (dx * sn + dy * cs) >> 14; + int64_t sx = (ux * stretch >> 16) - dx, sy = (uy * stretch >> 16) - dy; + lens_at(n, X, Y, &sx, &sy); + /* far beyond the picture is still far beyond it: held where the block arithmetic stays in 32 bits */ + sx = sx > (1 << 22) ? (1 << 22) : sx < -(1 << 22) ? -(1 << 22) : sx; + sy = sy > (1 << 22) ? (1 << 22) : sy < -(1 << 22) ? -(1 << 22) : sy; + c->ax = (int32_t)sx; + c->ay = (int32_t)sy; + c->sx = (int32_t)X + c->ax; + c->sy = (int32_t)Y + c->ay; + c->r = (int32_t)r; + c->inv = (int32_t)((1 << 28) / (r > 0 ? r : 1)); + /* the edges go dark first: from `near` out to `far` the light falls off smoothly by up to `shade` */ + c->vig = 256 - (d->shade * ck_smooth(ck_prog((uint32_t)r, (uint32_t)d->near, (uint32_t)d->far)) >> 8); +} + +/* the kept picture at (sx, sy) (16ths of a pixel of copy l, w x h): the picture itself inside its edges, the + * sky mirrored in them beyond (so the stars flow in from past the screen), black further out than that. */ +static uint32_t sample_kept(const ck_night_picture *kept, unsigned l, int32_t w, int32_t h, int32_t sx, int32_t sy) +{ + const uint32_t *px = kept->level[l]; + int32_t W = (w - 1) * 16, H = (h - 1) * 16; + sx -= 8, sy -= 8; + if (sx < 0 || sy < 0 || sx >= W || sy >= H) { + sx = sx < 0 ? -sx : sx >= W ? 2 * W - sx : sx; + sy = sy < 0 ? -sy : sy >= H ? 2 * H - sy : sy; + if (sx < 0 || sy < 0 || sx >= W || sy >= H) + return 0; + px = kept->sky[l]; + } + int32_t ix = sx >> 4, iy = sy >> 4; + const uint32_t *r0 = px + (size_t)iy * (size_t)w, *r1 = r0 + w; + uint32_t fx = (uint32_t)sx & 15u, fy = (uint32_t)sy & 15u; + return lerp16(lerp16(r0[ix], r0[ix + 1], fx), lerp16(r1[ix], r1[ix + 1], fx), fy); +} + +/* c brightened g/256 times (g above 256), the excess warmer than the light itself */ +static uint32_t brighten(uint32_t c, uint32_t g) +{ + if (g <= 256 || !c) ``` The diff is longer than this page shows; the raw diff has all of it.