CodeQL / Uncontrolled data used in path expression
This path depends on a user-provided value. This path depends on a user-provided value.
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
This path depends on a user-provided value. This path depends on a user-provided value.
This path depends on a user-provided value. This path depends on a user-provided value.
This path depends on a user-provided value. This path depends on a user-provided value.
This path depends on a user-provided value. This path depends on a user-provided value.
This path depends on a user-provided value. This path depends on a user-provided value.
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.
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.
This part of the regular expression may cause exponential backtracking on strings starting with '<!--'.
This part of the regular expression may cause exponential backtracking on strings starting with '<!--'.
This part of the regular expression may cause exponential backtracking on strings starting with '<!--'.
This part of the regular expression may cause exponential backtracking on strings starting with '<!--'.
curl -fsSL https://interplane.io/drakestapleton/aienos.com/patches/bbc2bf7f95c4310c.bundle -o bbc2bf7f95c4310c.bundle git fetch bbc2bf7f95c4310c.bundle refs/pull/121/head
github-import 1
aien-dev/aienos.com
121
79a206040fb86144bf79338ce09ee9ee52c46f7b
{"kind":"github-import","owner":"aien-dev","repo":"aienos.com","number":121,"url":"https://github.com/aien-dev/aienos.com/pull/121","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:19Z","metadata":"unavailable","state_derived":true}
diff --git a/.github/workflows/generated-allen-audio.yml b/.github/workflows/generated-allen-audio.yml new file mode 100644 index 0000000..a8a2242 --- /dev/null +++ b/.github/workflows/generated-allen-audio.yml @@ -0,0 +1,26 @@ +name: Generated Allen audio +on: + pull_request: + paths: + - 'om/allen-audio/**' + - 'public/audio/allen-chirp.wav' + - 'public/js/allen-audio.js' + - '.github/workflows/generated-allen-audio.yml' + push: + branches: [main] + paths: + - 'om/allen-audio/**' + - 'public/audio/allen-chirp.wav' + - 'public/js/allen-audio.js' + - '.github/workflows/generated-allen-audio.yml' +permissions: + contents: read +jobs: + artifact-hashes: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + # Hashes committed bytes only; the arm64 omc pin and the aienux oracle run in om/allen-audio/check.sh. + - name: Check the Omega-generated sound and script against their sidecars + working-directory: om/allen-audio + run: sha256sum -c allen-chirp.wav.sha256 allen-audio.js.sha256 diff --git a/.github/workflows/generated-hive.yml b/.github/workflows/generated-hive.yml index d4a0bb5..6dd39a3 100644 --- a/.github/workflows/generated-hive.yml +++ b/.github/workflows/generated-hive.yml @@ -6,6 +6,8 @@ on: - 'om/alpha-page/**' - 'public/js/alpha.js' - 'public/alpha/**' + - 'om/allen-intro/**' + - 'public/js/allen-intro.js' - 'public/js/hive.js' - 'public/js/turing-look.js' - 'crates/site-builder/**' @@ -17,6 +19,8 @@ on: - 'om/alpha-page/**' - 'public/js/alpha.js' - 'public/alpha/**' + - 'om/allen-intro/**' + - 'public/js/allen-intro.js' - 'public/js/hive.js' - 'public/js/turing-look.js' - 'crates/site-builder/**' @@ -35,3 +39,5 @@ jobs: run: cargo test --manifest-path crates/site-builder/Cargo.toml components::hive::tests::served_scripts_match_their_omega_generated_sha256 -- --exact - name: Check generated Alpha page and source run: cargo test --manifest-path crates/site-builder/Cargo.toml components::alpha::tests -- --nocapture + - name: Check generated Allen consent aside and script + run: cargo test --manifest-path crates/site-builder/Cargo.toml components::allen_intro::tests::allen_intro_artifacts_match_their_omega_generated_sha256 -- --exact diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 2f8b1bd..3263337 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -99,6 +99,8 @@ jobs: run: cargo test --release -p site-builder the_embedded_skeleton_matches_its_recorded_sha256 - name: Check the committed Alpha artifacts run: cargo test --release -p site-builder components::alpha::tests + - name: Check the committed Allen consent aside and script digests + run: cargo test --release -p site-builder allen_intro_artifacts_match_their_omega_generated_sha256 - name: Build static site with pure Rust engine run: cargo run --release --manifest-path crates/site-builder/Cargo.toml -- build dist - name: Upload Pages artifact diff --git a/AGENTS.md b/AGENTS.md index 076c051..cd54075 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,13 +69,14 @@ Open `http://127.0.0.1:8080/` after the preview server starts. GitHub Pages serv - Every page gets its head rewritten by `seo::enrich`: canonical on `https://www.aienos.com`, Open Graph and Twitter cards, hreflang, JSON-LD, `rel="alternate" type="text/markdown"`, `rel="describedby"` to `/llms.txt`, and robots snippet directives. Do not duplicate those tags in a component. - Every page also gets a Markdown mirror at the same path with `.md` (`/` becomes `/index.md`), with YAML frontmatter and a `## Sitemap` section. The mirror is generated from the final HTML; do not hand-write one. - Voice: Drake writes this site alone, in first person singular (I, me, my). Never a plural first-person word (the list is the regex in `voice::plural`). Where agents did the work, say so ("my agents", "I build this with AI agents"); never credit Drake with an agent's work, and never imply a team. Shared human claims use "everyone" or "people". `components::voice::verify_singular_voice` fails the build on any plural first-person word in rendered `dist` text (`.html` visible text, `.md`, `.txt`). Not counted: markup, scripts, styles, link targets, path/identifier parts (`how-we-did-it`), `50 us`, and on the ledger pages (`voice::LEDGER_PAGES`) text found verbatim in `data/now.tsv`, which is a dated record. Quotes of other people go in `voice::ALLOW` as (file, exact phrase); keep it small. Repository descriptions render on /agents/, so fix the GitHub description, not just `agent-repos.json`. -- Copy rules: no em dashes, no en dashes, no outside fonts or unconditional third-party scripts/trackers. The sole tracking exception is X pixel `rfrlz`, loaded from the first-party `public/js/allen-intro.js` only after explicit consent to the Allen introduction. Never embed `uwt.js` as a script source in HTML, inline its bootstrap, or preconnect/prefetch X hosts. The verifier rejects outside script sources on every emitted HTML page; `node scripts/test-allen-intro.cjs` exercises refusal, consent, reload and revocation. +- Allen speaks in his own voice: a plural pronoun in his speech means Allen and the visitor, not Drake plus a team. Only elements marked exactly `data-speaker="allen"` are removed before the plural check (`voice::ALLEN_SPEECH`, tested with negative controls: untagged copy, lookalike attributes, marker text and unclosed elements still fail). Tag Allen's speech and nothing else; Drake's page copy stays under the rule. +- Copy rules: no em dashes, no en dashes, no outside fonts or unconditional third-party scripts/trackers. The sole tracking exception is X pixel `rfrlz`, loaded from the first-party `public/js/allen-intro.js` only after the visitor chooses Say hi to Allen. Never embed `uwt.js` as a script source in HTML, inline its bootstrap, or preconnect/prefetch X hosts. The verifier rejects outside script sources on every emitted HTML page; `node scripts/test-allen-intro.cjs` exercises refusal, consent, reload and revocation. - Keep one source for machine-readable state. `status.json`, the status section, and the current-state lines in `llms.txt` all read `components::status::layer_states()`. - Tests live beside the code in `#[cfg(test)]` modules. Add a test when a rule can regress silently. -- The final shared `components::allen_intro::enrich` pass in `seo::enrich` adds one local consent loader, a native modal dialog and a privacy link to generated, hand-written and translated pages. `404.html` gets the same pass. `/privacy/` stays readable without an automatic modal and provides review and refusal controls. No and Escape persist refusal, with no automatic re-prompt. Stored Yes permits one initialization per document; refusal of an active pixel reloads without it. Local storage holds the choice; a session-storage refusal and `#allen-intro-no` protect reload if persistent storage fails. Storage clearing or another browser resets the choice, not consent. +- The final shared `components::allen_intro::enrich` pass in `seo::enrich` adds one local consent loader, Allen's hello aside and a privacy link to generated, hand-written and translated pages. `404.html` gets the same pass. The hello is a non-blocking `role="complementary"` aside (`aria-live="polite"`), never a modal: no backdrop, no `showModal`, focus moves only when the visitor asks via Review my choice. Allen calls Drake by name; the copy never mentions ads or how the visitor arrived. Memory consent (links to `/aien/?mode=remember` and `?mode=anonymous`) and X consent (Say hi / No thanks buttons) stay separate controls; one tap never means both. Global Privacy Control suppresses the pixel offer except on explicit Review; anonymous `/allen/` never loads the pixel. The Who can see me right now? panel is local-only (resource timing, navigator fields; no network, storage, hashing or IP lookup). The aside markup, Allen's words and `public/js/allen-intro.js` are generated by seeded Omega: edit `om/allen-intro/intro.om`, run `sh om/allen-intro/check.sh` (pinned `om/hive-page/omc`; `OMEGA_ACCEPT_CHANGE=1` to accept), and commit `intro.html`, the script and their sha256 sidecars; `components::allen_intro` only embeds the aside, and a unit test (also run in Pages and `generated-hive.yml`) re-hashes both artifacts. The visual layer uses only `window.aienAllenIntro` and `aien-allen-intro` events. A page with its own welcome marks `[data-allen-intro-defer]` and calls `aienAllenIntro.greet()` after it, so Allen's greeting follows the door instead of covering it. It auto-appears once per browser: first display writes `aien-allen-intro-seen` (session storage when local storage fails), chosen or not, and unanswered means No. `/privacy/` stays readable without it and provides review and refusal controls. No thanks, the close button and Escape persist refusal. Stored Yes permits one initialization per document; refusal of an active pixel reloads without it. Local storage holds the choice; a session-storage refusal and `#allen-intro-no` protect reload if persistent storage fails. Storage clearing or another browser resets the choice and the greeting, never consent. - Every page shows how to reach Drake: the header nav ends with the `aien-nav-reach` group (the `/contact/` page and a plain "Follow me on X" link to `https://x.com/mdrakestapleton` with an inline SVG mark, no widget or script), and the footer carries the `aien-reach-foot` line (X, `drake@aienos.com`, `/allen/`, GitHub aien-dev). Generated pages get both from `components::navbar` and `components::footer`; `components::contact::enrich` in `seo::enrich` adds them to hand-written and `/zh-CN/` pages (Chinese labels there), and `contact::verify` fails the build if any HTML page in `dist` lacks either. -- CSP coordination: no inline allen-intro scripts. An edge CSP for a page that enables this feature needs `script-src 'self' https://static.ads-twitter.com` and `connect-src` / `img-src` permissions for `https://analytics.twitter.com`, `https://analytics.x.com` and `https://t.co` (in addition to its first-party sources). These are the hosts named by the official loader inspected on 2026-10-26, not a wildcard allowance. CSP permissions are static, not conditional consent: `allen-intro.js` enforces consent before any X load. Do not loosen a no-JS edge board CSP; explicitly exclude that board from enrichment if introduced. `allen-intro.js` is outside the separate Hive/Turing Omega-generation change, by agreement with that lane. -- Before publishing a consent change, build `dist`, run `node scripts/test-allen-intro.cjs dist/js/allen-intro.js`, and verify in a real browser with cache disabled and requests observed before navigation: unknown/No/Escape and reload produce no X requests and no `window.twq`; saying hello requests the exact loader and configures `rfrlz` once. Test at mobile width 390, verify modal focus and keyboard dismissal, and run a guard-bypass negative control. Intercepted X requests prove gating, not X ingestion. The public project board and storage of check-ins are deferred pending Drake's storage decision; never collect entries under the pixel consent. +- CSP coordination: no inline allen-intro scripts. An edge CSP for a page that enables this feature needs `script-src 'self' https://static.ads-twitter.com` and `connect-src` / `img-src` permissions for `https://analytics.twitter.com`, `https://analytics.x.com` and `https://t.co` (in addition to its first-party sources). These are the hosts named by the official loader inspected on 2026-10-26, not a wildcard allowance. CSP permissions are static, not conditional consent: `allen-intro.js` enforces consent before any X load. Do not loosen a no-JS edge board CSP; explicitly exclude that board from enrichment if introduced. `allen-intro.js` is generated: it is written on fd 3 by `om/allen-intro/intro.om` beside the aside markup; never hand-edit the artifact, edit the `.om` and run `om/allen-intro/check.sh`. +- Before publishing a consent change, build `dist`, run `node scripts/test-allen-intro.cjs dist/js/allen-intro.js`, and verify in a real browser with cache disabled and requests observed before navigation: unknown/No/Escape and reload produce no X requests and no `window.twq`; Say hi requests the exact loader and configures `rfrlz` once; a reload does not show Allen again. Test at mobile width 390, verify the page stays interactive, focus is not stolen and Escape dismisses, and run a guard-bypass negative control. Intercepted X requests prove gating, not X ingestion. The public project board and storage of check-ins are deferred pending Drake's storage decision; never collect entries under the pixel consent. - Only after consent, retain the landing URL's `twclid` under browser-local `aien-allen-intro-twclid`; remove it on refusal. Drake chose pixel-only operation; server Conversion API work is deferred until the introduction flow has a backend. The single `eventIds` constant in `allen-intro.js` holds `pageVisit` and `introducedToAllen`, empty until Drake supplies the real IDs. Empty means no custom event. Configured IDs send one visit per consenting document and one introduced-to-Allen event per explicit introduction document, each with its own `crypto.randomUUID()` `conversion_id`. A future backend must forward that exact ID for deduplication, read `X_PIXEL_TOKEN` only from its private environment, and never expose the token in static output. - Hive's shell and browser client are generated by seeded Omega, never written in Rust or hand-edited in `public/js/`. `om/hive-page/check.sh` composes `contract.om`, `hive.om` and `hive-js.om`: stdout emits `main.html`, fd 3 emits `hive.js`. The shared contract owns ids, poll/freshness bounds and the board route; append entries rather than renumbering. `hive.om` owns the section order (`meta`, eight pipe-separated fields), shell controls, aria wiring and bounded panels. `om/hive-render/render.om` owns feed-derived rows, native details, manifests and messages. The browser only DOMParser-parses same-origin `/hive/board/` and morphs keyed nodes in place, preserving native open state, selection, focus, search and scroll. It never renders JSON or constructs feed markup. `turing-look.js` has its separate Omega generator. Commit sources, artifacts and hashes together; run the generation gate twice, site-builder tests and `scripts/test-hive-cosmic.py`. Neither served JS file is hand-edited. - `.github/workflows/generated-hive.yml` runs only the skeleton-hash and generated-script-hash tests on x86_64 for relevant pull requests and main pushes. It does not run `omc`, regenerate artifacts or change the full-suite-on-Spark policy. diff --git a/README.md b/README.md index f13a9cd..7dde29d 100644 --- a/README.md +++ b/README.md @@ -15,15 +15,23 @@ Live: [https://www.aienos.com](https://www.aienos.com), rebuilt hourly from the The homepage opens with "AienOS is an owned experimental machine for turning search into verified understanding" (`crates/site-builder/src/components/home_loop.rs`) and goes on to the loop, the story, the receipts behind each claim, how the pieces fit together, the research, an interactive terminal, the current status of each layer, and where to follow the work. Other pages: `/start/` (the newcomer route through what AIENOS is, what exists today, how to check the evidence, how to reproduce or contribute, and where the author and Interplane fit), `/progress/`, `/blog/`, `/research/status/`, `/machine/`, `/discovery/` and the hubs `/experiments/`, `/evidence/` and `/philosophy/`. The build also writes `status.json`, `research-status.json` and `llms.txt`; `status.json` and `llms.txt` come from the same code as the homepage status section, and `research-status.json` is `crates/site-builder/data/research_status.json`. The homepage status section says "Public release" is PLANNED, with no supported release or installer yet. -## Introduce yourself to Allen: consent-first X pixel +## Allen says hi: consent-first X pixel -Every built page gets one first-party `/js/allen-intro.js` loader from the final shared document pass, including hand-written pages, translations and the 404 page. Nothing from X is loaded until the visitor explicitly chooses **Introduce yourself to Allen** (or has a saved Yes). The unchanged official X base code configures pixel `rfrlz` once per document. **No** and Escape dismiss the native modal, remember refusal, and do not initialize `twq` or make an X tracking request. The browser tab stays open. `/privacy/` explains what X receives, normal hosting logs, browser-local storage, and how to refuse after consenting. It is readable without an automatic popup. +Every built page gets one first-party `/js/allen-intro.js` loader from the final shared document pass, including hand-written pages, translations and the 404 page. On a visitor's first page Allen appears in a bottom corner (the bottom edge on mobile) and types out Drake's static, client-rendered greeting ("Hi, I'm Aien (you say it like Ian). It's nice to meet you! ..."). It is a non-blocking `role="complementary"` aside with `aria-live="polite"`: no backdrop, no modal, no focus theft, and it never mentions ads. Reduced motion skips the slide and typing. It auto-appears only once per browser: first display records `aien-allen-intro-seen` in local storage (session storage if local storage is unavailable, so once per tab session), chosen or not. Not answering means no consent. It does not auto-appear on `/privacy/` or on the `/allen/` chat page. A page with a welcome of its own (the home door) marks `[data-allen-intro-defer]` and calls `aienAllenIntro.greet()` afterwards; deferral does not spend the once-only greeting. -Run `node scripts/test-allen-intro.cjs` (Node's built-in test runner, verification only) alongside the Rust suite and `build dist`. To exercise the built asset use `node scripts/test-allen-intro.cjs dist/js/allen-intro.js`. Browser verification must observe requests before navigation with cache disabled; check absence of X requests and `window.twq` before consent, after No and after reload, then require the exact loader URL and `config('rfrlz')` after saying hello. Check keyboard focus, Escape and mobile width 390. An intercepted loader tests gating, not ingestion by X. Confirm the real deployed pixel separately with [X Pixel Helper](https://chrome.google.com/webstore/detail/twitter-pixel-helper/jepminnlebllinfmkhfbkpckogoiefpd). +The aside's markup and `public/js/allen-intro.js` are generated by seeded Omega from `om/allen-intro/intro.om` (`sh om/allen-intro/check.sh` writes both with sha256 sidecars; the Rust builder embeds the aside and a test re-hashes both). Never hand-edit either artifact. + +Memory and X consent are separate controls, so one tap never means both. **Tell Aien my name** links to `/aien/?mode=remember`, where `/allen/` shows its own memory-consent step; **Chat anonymously** links to `/aien/?mode=anonymous`. The X pixel ask is its own line with **Say hi** and **No thanks**. Nothing from X is loaded until the visitor chooses **Say hi** (or has a saved Yes), and never while `/allen/` is in anonymous mode (`#allen` without `data-mode="remembered"`). The unchanged official X base code configures pixel `rfrlz` once per document. **No thanks**, the close button and Escape remember refusal and do not initialize `twq`; after **No thanks** Allen offers an anonymous chat. If the browser sends Global Privacy Control, the greeting does not offer the pixel at all; only **Review my choice** on `/privacy/` offers it. + +The **Who can see me right now?** expander lists the outside origins this document actually loaded (resource timing plus a `PerformanceObserver`; 0 before consent, the X origins after **Say hi**, each labelled as Drake's pixel) and what the browser tells every site (user agent, platform, language, timezone, screen size, referrer, Do Not Track, Global Privacy Control, cookies enabled). It is computed and shown locally, never sent or stored: no fingerprint hash, extension probing or IP lookup. It says what it cannot see and links to EFF Cover Your Tracks and Blacklight without embedding them. + +Allen's visual layer drives this through `window.aienAllenIntro` (`text`, `status()`, `sayHi()`, `noThanks()`, `dismiss()`, `review()`, `greet()`, `who()`, `onTrackers(fn)`) and the document `aien-allen-intro` event (`show`, `hide`, `reply-no`, `consent`). Memory consent is not part of that interface. `/privacy/` explains what X receives, normal hosting logs, browser-local storage, and how to refuse after consenting. + +Run `node scripts/test-allen-intro.cjs` (Node's built-in test runner, verification only) alongside the Rust suite and `build dist`. To exercise the built asset use `node scripts/test-allen-intro.cjs dist/js/allen-intro.js`. Browser verification must observe requests before navigation with cache disabled; check absence of X requests and `window.twq` before consent, after No and after reload, then require the exact loader URL and `config('rfrlz')` after Say hi. Check that the who-can-see panel reads 0 before consent and lists the X origins after, that a reload does not show Allen again, that the page stays clickable while he shows, keyboard reach, Escape and mobile width 390. An intercepted loader tests gating, not ingestion by X. Confirm the real deployed pixel separately with [X Pixel Helper](https://chrome.google.com/webstore/detail/twitter-pixel-helper/jepminnlebllinfmkhfbkpckogoiefpd). No new CSP is installed by this feature. If an edge adds one, the Allen introduction needs `script-src 'self' https://static.ads-twitter.com`; `connect-src` and `img-src` need the first-party origin plus `https://analytics.twitter.com`, `https://analytics.x.com`, and `https://t.co`. The official loader inspected on 2026-10-26 names those endpoints; do not permit all X subdomains. CSP permissions cannot vary after a button click: the first-party script is the consent gate. A separate no-JS board should keep its strict CSP and not receive the allen-intro loader. -The community board, project links, leave-times and storage of public check-ins are **deferred**, pending Drake's storage decision. Saying hello here consents only to the pixel and publishes no public entry. +The community board, project links, leave-times and storage of public check-ins are **deferred**, pending Drake's storage decision. Saying hi here consents only to the pixel and publishes no public entry. For consenting visitors only, `allen-intro.js` retains the landing URL's `twclid` in browser local storage (`aien-allen-intro-twclid`); No removes it. Drake chose pixel-only operation for now: the server Conversion API is deferred until the introduction flow has a backend. There is no conversion endpoint, server-side send or `X_PIXEL_TOKEN` in the site bundle. diff --git a/crates/site-builder/src/components/allen.rs b/crates/site-builder/src/components/allen.rs index f48449a..3625bdd 100644 --- a/crates/site-builder/src/components/allen.rs +++ b/crates/site-builder/src/components/allen.rs @@ -272,7 +272,8 @@ mod tests { assert!(function_body(script, "greeting").contains("message('allen', 'Aien')")); assert_eq!(script.matches("dataset.speaker").count(), 1, "only message() marks a speaker"); assert!(!function_body(script, "humanMessage").contains("speaker")); - assert!(!SKELETON.contains("data-speaker"), "Drake's page copy is never marked as Aien's"); + assert_eq!(SKELETON.matches("data-speaker=\"allen\"").count(), 1, "only the initially empty live reply is marked as Allen's"); + assert!(SKELETON.contains("id=\"allen-answer\" class=\"allen-answer\" data-speaker=\"allen\"")); } #[test] @@ -284,8 +285,8 @@ mod tests { ] { assert_eq!(SKELETON.matches(&format!(" id=\"{id}\"")).count(), 1, "exactly one #{id} in the skeleton"); } - assert!(SKELETON.contains("running on a DGX Spark in Drake's house")); - assert!(SKELETON.contains("No prompts or IP addresses are logged.")); + assert!(SKELETON.contains("Timing below is measured from this reply.")); + assert!(SKELETON.contains("Remembering you is a separate choice")); assert!(!SKELETON.contains('\u{2014}') && !SKELETON.contains('\u{2013}'), "no em or en dash"); } @@ -350,4 +351,28 @@ mod tests { assert!(!line.contains("filter") && !line.contains("box-shadow") && !line.contains("transition: all"), "compositor-only motion: {line}"); } } + + #[test] + fn the_presence_keeps_transport_and_consent_boundaries() { + let script = include_str!("../../../../public/js/allen-presence.js"); + let want = recorded(include_str!("../../../../om/allen-presence/presence.sha256")); + assert_eq!(format!("{:x}", Sha256::digest(script.as_bytes())), want); + for banned in ["innerHTML", "outerHTML", "insertAdjacentHTML", "fetch(", "localStorage", "sessionStorage", "eval("] { + assert!(!script.contains(banned), "the presence delegates effects, never uses {banned}"); + } + assert!(script.contains("api.on('human',event => replaceReply(event.text,'Drake'))")); + assert_eq!(script.matches("replaceReply(event.text,'Drake')").count(), 1); + assert!(script.contains("api.on('card',event =>")); + assert!(script.contains("node:event.node")); + assert!(script.contains("prefers-reduced-motion: reduce")); + assert!(!script.contains("AllenAudio.enter("), "the native tube is silent; the home door owns gesture-gated chirp playback"); + assert!(script.contains("window.allenPresence=Object.freeze({ready,enter,scene:() => scene,panes:() => panes})")); + assert!(script.contains("opening:homeDoor?'idle':'dusk'")); + assert!(script.contains("window.visualViewport")); + assert!(script.contains("allen-pane-request")); + assert!(SKELETON.contains("id=\"allen-session\" class=\"allen-session\" aria-label=\"Session history and privacy\" hidden")); + for id in ["allen-universe", "allen-enter", "allen-copy", "allen-regenerate", "allen-history", "allen-projects", "allen-mute", "allen-mic", "allen-speak", "allen-voice-privacy"] { + assert_eq!(SKELETON.matches(&format!("id=\"{id}\"")).count(), 1); + } + } } diff --git a/crates/site-builder/src/components/allen_intro.rs b/crates/site-builder/src/components/allen_intro.rs index 9dd76cb..5864030 100644 --- a/crates/site-builder/src/components/allen_intro.rs +++ b/crates/site-builder/src/components/allen_intro.rs @@ -1,25 +1,13 @@ use maud::{html, Markup}; -pub const HEAD: &str = "<link rel=\"stylesheet\" href=\"/assets/allen-intro.css\"><script defer src=\"/js/allen-intro.js\"></script>"; +pub const HEAD: &str = "<link rel=\"stylesheet\" href=\"/assets/allen-intro.css\"><script defer src=\"/js/allen-intro.js\"></script><script defer src=\"/js/allen-scene.js\"></script><script defer src=\"/js/allen-presence.js\"></script>"; -fn dialog() -> Markup { - html! { - dialog id="aien-allen-intro" role="dialog" aria-modal="true" aria-labelledby="allen-intro-title" aria-describedby="allen-intro-intro allen-intro-consent" { - h2 id="allen-intro-title" { "Say hello to Allen?" } - p id="allen-intro-intro" { - "Hey, you just clicked an ad. I just want you to know that if you didn't intend to click an ad, that's cool. Just click No and this popup will close. Nothing will be tracked by my X pixel. Your browser may not let me close a page I didn't open." - } - p id="allen-intro-consent" { - "But if you did want to see it, do you mind if I track you and know you were here? Allen is my AI. Introduce yourself to Allen by saying hello below. Saying hello means you consent to the X conversion pixel, so X receives information about your visit and helps me reach the right people. This doesn't open a chat or publish your identity." - } - div class="allen-intro-actions" { - button id="allen-intro-no" type="button" autofocus { "No" } - button id="allen-intro-yes" type="button" { "Introduce yourself to Allen" } - } - p { a href="/privacy/" { "Privacy, what X receives, and your choice" } } - } - } -} +/// Allen's consent aside, generated by seeded Omega (`om/allen-intro/intro.om`, run by +/// `om/allen-intro/check.sh` on arm64). Every structural and copy decision lives there, +/// including Drake's greeting, the separate memory links and X buttons, and the +/// local-only "Who can see me right now?" panel. Allen's speech carries +/// `data-speaker="allen"` for the voice rule. This builder only embeds the bytes. +pub const INTRO: &str = include_str!("../../../../om/allen-intro/intro.html"); /// Final shared document pass covers generated, hand-written and translated pages. /// Idempotence prevents duplicate loaders if an already-enriched page is copied. @@ -29,13 +17,17 @@ pub fn enrich(mut page: String) -> String { page.insert_str(end, HEAD); } if !page.contains("href=\"/privacy/\"") { - let link = "<p class=\"allen-intro-footer\"><a href=\"/privacy/\">Privacy & saying hello to Allen</a></p>"; + let link = "<p class=\"allen-intro-footer\"><a href=\"/privacy/\">Privacy & saying hi to Aien</a></p>"; let end = page.rfind("</footer>").or_else(|| page.rfind("</body>")).expect("allen-intro page has a body"); page.insert_str(end, link); } if !page.contains("id=\"aien-allen-intro\"") { let end = page.rfind("</body>").expect("allen-intro page has a body"); - page.insert_str(end, &dialog().into_string()); + page.insert_str(end, INTRO); + } + if !page.contains("id=\"aien-allen-launcher\"") { + let end = page.rfind("</body>").expect("Allen presence page has a body"); + page.insert_str(end, include_str!("../../../../om/allen-presence/launcher.html")); } page } @@ -43,11 +35,13 @@ pub fn enrich(mut page: String) -> String { pub fn render_privacy() -> Markup { html! { article id="allen-intro-privacy" class="allen-intro-privacy" { - h1 { "Privacy & saying hello to Allen" } + h1 { "Privacy & saying hi to Aien" } p { "I do not sell your information. I'm open source and free with information about my work, not with your personal data. You can read this site without introducing yourself." } - h2 { "Saying hello means consent to X tracking" } - p { "Allen is Drake's AI. Choosing Introduce yourself to Allen lets me know you were here by allowing X conversion pixel rfrlz to load on this and later pages in this browser. It helps me understand whether my ads reach the right people and helps me broadcast my message to that audience. It does not open an AI chat. I do not ask for your name, collect project links or publish your identity here." } - p { "Before you say hello, I do not load the X pixel or send it information about your visit. No closes only the popup, not your tab, and refuses X tracking. I remember No and do not ask again automatically. Escape means No too. With JavaScript disabled, the pixel never loads." } + h2 { "Saying hi means consent to X tracking" } + p { "Aien is my AI. On your first visit he slides into a corner of the page with a short hello. It is a small aside, not a popup that blocks the page, and he shows it only once in this browser, whether or not you answer. Choosing Say hi lets me know you were here by allowing X conversion pixel rfrlz to load on this and later pages in this browser. It helps me measure whether my posts and ads on X reach the right people. Saying hi does not open an AI chat. I do not ask for your name, collect project links or publish your identity here." } + p { "Before you say hi, I do not load the X pixel or send it information about your visit. No thanks, the close button and Escape all mean No: Aien steps aside and X tracking stays off. Not answering also means No. Aien does not ask again automatically; the Review my choice button below brings him back. With JavaScript disabled, Aien never appears and the pixel never loads." } + p { "After No thanks, Aien says you can still chat with him anonymously: the Chat anonymously link opens /aien/?mode=anonymous, where he does not remember you and nothing goes to X. If your browser sends Global Privacy Control, Aien notes it and does not offer the X pixel when he greets you; only Review my choice on this page offers it." } + p { "Aien's Who can see me right now? section lists the outside origins this tab has actually loaded, from the browser's own resource timing record, and what your browser tells every website automatically: browser, platform, language, timezone, screen size, referrer, Do Not Track, Global Privacy Control and whether cookies are enabled. It is worked out in your browser and shown only to you; nothing in it is sent, stored, hashed into a fingerprint or looked up elsewhere. It cannot see trackers on other sites, in other tabs or inside embedded frames, your internet provider's or network's tracking, or your browser extensions." } h2 { "What X receives" } p { "After consent, your browser connects to X to load its script and send visit and conversion information. This can include the page URL, referrer, IP address, browser or device information and cookie identifiers. X may store cookies and process this information under its own policies. My open source license does not apply to X's service." } p { @@ -56,11 +50,11 @@ pub fn render_privacy() -> Markup { } h2 { "What I keep" } p { "I do not store pixel tracking data on my own servers or operate a check-in database. X processes the pixel data and provides advertising measurement to me. The site and its hosting providers still receive normal web requests and may keep operational access logs; refusing the pixel does not remove those requests." } - p { "Your browser stores only your yes or no choice under aien-allen-intro-consent in local storage, with a refusal also kept in this tab's session storage. That choice stays in this browser until you change it or clear site data. It does not identify you to me. If storage fails while stopping an active pixel, a #allen-intro-no address fragment also preserves refusal through the reload. If all browser storage is unavailable, I cannot remember your choice after you leave this page. Clearing site data or using another browser resets the choice; it never gives consent on its own." } - p { "For consenting visitors only, I also keep the ad's twclid click identifier, if present in the landing URL, in browser local storage under aien-allen-intro-twclid. Refusing removes it where browser storage permits. It is reserved for a future server-side conversion flow; this site currently sends no server-side conversions. No email address, phone number or other identifier is collected for that purpose." } - p { "The two custom events are a consented page visit and introduced to Allen. They stay disabled until Drake supplies their X event IDs. Each enabled event includes a random conversion identifier so a future backend can avoid counting the same event twice; server-side conversions are deferred until that backend exists." } + p { "Your browser stores your yes or no choice under aien-allen-intro-consent in local storage, with a refusal also kept in this tab's session storage. It also stores aien-allen-intro-seen once Aien has said hello, so he does not greet you again; if local storage is unavailable, that note lives in this tab's session storage instead, so he appears at most once per tab session. That choice stays in this browser until you change it or clear site data. It does not identify you to me. If storage fails while stopping an active pixel, a #allen-intro-no address fragment also preserves refusal through the reload. If all browser storage is unavailable, I cannot remember your choice or the greeting after you leave this page. Clearing site data or using another browser resets both, so Aien says hello again; that never gives consent on its own." } + p { "For consenting visitors only, I also keep X's twclid click identifier, if present in the landing URL, in browser local storage under aien-allen-intro-twclid. Refusing removes it where browser storage permits. It is reserved for a future server-side conversion flow; this site currently sends no server-side conversions. No email address, phone number or other identifier is collected for that purpose." } + p { "The two custom events are a consented page visit and saying hi to Aien. They stay disabled until Drake supplies their X event IDs. Each enabled event includes a random conversion identifier so a future backend can avoid counting the same event twice; server-side conversions are deferred until that backend exists." } h2 { "Your choice" } - p id="allen-intro-status" role="status" { "X tracking stays off unless you choose to introduce yourself to Allen. JavaScript is needed to change this browser's choice." } + p id="allen-intro-status" role="status" { "X tracking stays off unless you choose to say hi to Aien. JavaScript is needed to change this browser's choice." } div class="allen-intro-actions" { button type="button" data-allen-intro-open hidden { "Review my choice" } button type="button" data-allen-intro-stop hidden { "No, keep X tracking off" } @@ -81,6 +75,28 @@ pub fn render_privacy() -> Markup { #[cfg(test)] mod tests { use super::*; + use sha2::{Digest, Sha256}; + + #[test] + fn allen_intro_artifacts_match_their_omega_generated_sha256() { + // Both artifacts come from om/allen-intro/intro.om: the aside on fd 1, the script on fd 3. + for (bytes, recorded, name) in [ + (INTRO.as_bytes(), include_str!("../../../../om/allen-intro/intro.html.sha256"), "intro.html"), + ( + &include_bytes!("../../../../public/js/allen-intro.js")[..], + include_str!("../../../../om/allen-intro/allen-intro.js.sha256"), + "allen-intro.js", + ), + ] { + let want = recorded.split_whitespace().next().expect("sidecar holds a digest"); + assert_eq!(want.len(), 64, "{name} sidecar must hold one sha256 digest"); + let got = Sha256::digest(bytes).iter().fold(String::new(), |mut acc, byte| { + acc.push_str(&format!("{byte:02x}")); + acc + }); + assert_eq!(got, want, "{name} and its digest disagree; run: sh om/allen-intro/check.sh"); + } + } #[test] fn every_document_gets_one_local_loader_and_accessible_dialog() { @@ -88,9 +104,32 @@ mod tests { assert_eq!(enrich(page.clone()), page); assert_eq!(page.matches("src=\"/js/allen-intro.js\"").count(), 1); assert_eq!(page.matches("id=\"aien-allen-intro\"").count(), 1); - assert!(page.contains("role=\"dialog\"")); + assert!(page.contains("role=\"complementary\"")); + assert!(page.contains("aria-live=\"polite\"")); + assert!(page.contains("Hi, I'm Aien (you say it like Ian). It's nice to meet you!")); + assert!(page.contains("we could chat over time")); + assert!(page.contains("data-speaker=\"allen\""), "Allen's speech is tagged for the voice rule"); + // Memory and X consent are separate controls: links for memory, buttons for X. + assert!(page.contains("<a href=\"/aien/?mode=remember\">Tell Aien my name</a>")); + assert!(page.contains("<button id=\"allen-intro-yes\" type=\"button\">Say hi</button>")); + assert!(!page.contains("<dialog") && !page.contains("aria-modal"), "Allen is an aside, never a modal"); + let lower = page.to_ascii_lowercase(); + for word in ["advert", " ad ", " ads", "campaign", "clicked"] { + assert!(!lower.contains(word), "greeting must not mention {word}"); + } assert!(page.contains("href=\"/privacy/\"")); assert!(!page.contains("uwt.js")); assert!(!page.contains("twq(")); + assert!(page.contains("href=\"/aien/?mode=anonymous\""), "No thanks offers an anonymous chat"); + assert!(page.contains("Who can see me right now?")); + // The panel is local-only: links to outside tools, never embeds or outside sources. + let aside = &page[page.find("id=\"aien-allen-intro\"").unwrap()..]; + for embed in ["<iframe", "<script", "<object", "<embed", "src=\"http", "src=\"//"] { + assert!(!aside.contains(embed), "Allen's aside must not embed {embed}"); + } + // Visitors meet Aien: no visible "Allen" and no /allen/ link; internal ids keep the old name. + let seen = crate::components::voice::visible_text("x.html", aside); + assert!(!seen.contains("Allen") && !aside.contains("href=\"/allen/"), "visible text says Aien"); + assert!(aside.contains("aria-label=\"Aien says hello\"")); } } diff --git a/crates/site-builder/src/components/footer.rs b/crates/site-builder/src/components/footer.rs index 312ddba..b73d486 100644 --- a/crates/site-builder/src/components/footer.rs +++ b/crates/site-builder/src/components/footer.rs @@ -67,7 +67,7 @@ const FOOTER_MORE: [FooterLink; 11] = [ ("Contact", "/contact/", false), ("Glossary", "/glossary/", false), ("Licensing", "/licensing/", false), - ("Privacy & saying hello to Allen", "/privacy/", false), + ("Privacy & saying hi to Aien", "/privacy/", false), ("GitHub", "https://github.com/aien-dev", true), ("Interplane", "https://interplane.io/", true), ("Drake Stapleton", "https://www.drakestapleton.com", true), @@ -146,7 +146,7 @@ pub fn render_footer() -> Markup { "." } p { - "No outside fonts or trackers, unless you introduce yourself to Allen to allow the X pixel. " + "No outside fonts or trackers, unless you say hi to Aien to allow the X pixel. " a href="/privacy/" { "Your privacy and choice" } } div class="aien-footer-mottos" { diff --git a/crates/site-builder/src/components/voice.rs b/crates/site-builder/src/components/voice.rs index a7e7f68..12e9502 100644 --- a/crates/site-builder/src/components/voice.rs +++ b/crates/site-builder/src/components/voice.rs @@ -4,6 +4,9 @@ //! and code identifiers are the only exceptions, listed in `ALLOW`. Text //! copied verbatim from the published work ledger (`data/now.tsv`, shown on //! /now/) is a dated record of what was said, not copy, and is matched out. +//! The rule covers Drake's voice only. Allen's speech, the elements marked +//! exactly `data-speaker="allen"`, is his own voice ("we" there means Allen and +//! the visitor) and is removed before matching; nothing else is. use regex::Regex; use std::fs; @@ -19,10 +22,59 @@ pub const ALLOW: &[(&str, &str)] = &[ /// Pages that embed ledger rows; only these may match text out of the ledger. pub const LEDGER_PAGES: &[&str] = &["now/index.html", "now/index.md", "now.md", "llms-full.txt"]; +/// The one marker for Allen's speech. Exact match: attribute spelling and value. +pub const ALLEN_SPEECH: &str = "data-speaker=\"allen\""; + fn plural() -> Regex { Regex::new(r"(?i)\b(?:we|we['\u{2019}](?:re|ve|ll|d)|us|our|ours|ourselves)\b").unwrap() } +/// Removes each element whose opening tag carries `ALLEN_SPEECH`, through its +/// matching close tag (same-name nesting counted). An unclosed element is kept, +/// so malformed markup can never hide the rest of a page from the check. +fn without_allen_speech(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + let mut rest = raw; + while let Some(at) = rest.find(ALLEN_SPEECH) { + let Some(open) = rest[..at].rfind('<') else { break }; + let name: String = rest[open + 1..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect(); + let attribute = rest[..at].ends_with(|c: char| c.is_ascii_whitespace()); + if name.is_empty() || !attribute || rest[open..at].contains('>') { + out.push_str(&rest[..at + ALLEN_SPEECH.len()]); + rest = &rest[at + ALLEN_SPEECH.len()..]; + continue; + } + let (start_tag, end_tag) = (format!("<{name}"), format!("</{name}>")); + let mut depth = 0usize; + let mut i = open; + let mut end = None; + while let Some(next) = rest[i..].find('<').map(|n| i + n) { + let tail = &rest[next..]; + let boundary = |s: &str| tail[s.len()..].starts_with(|c: char| c == '>' || c.is_whitespace() || c == '/'); + if tail.starts_with(&end_tag) { + depth -= 1; + if depth == 0 { + end = Some(next + end_tag.len()); + break; + } + } else if tail.starts_with(&start_tag) && boundary(&start_tag) { + depth += 1; + } + i = next + 1; + } + let Some(end) = end else { + out.push_str(&rest[..at + ALLEN_SPEECH.len()]); + rest = &rest[at + ALLEN_SPEECH.len()..]; + continue; + }; + out.push_str(&rest[..open]); + out.push(' '); + rest = &rest[end..]; + } + out.push_str(rest); + out +} + /// Visible text of an HTML page: scripts, styles and tags removed, common /// entities decoded. Markdown and plain text pass through unchanged. pub fn visible_text(name: &str, raw: &str) -> String { @@ -32,6 +84,7 @@ pub fn visible_text(name: &str, raw: &str) -> String { let blocks = Regex::new(r"(?is)<script\b.*?</script>|<style\b.*?</style>").unwrap(); let tags = Regex::new(r"(?s)<[^>]*>").unwrap(); let t = blocks.replace_all(raw, " "); + let t = without_allen_speech(&t); let t = tags.replace_all(&t, " "); t.replace("&", "&") .replace("'", "'") @@ -146,4 +199,24 @@ mod tests { let html = "<p class=\"our\">mine</p><script>var us=1</script><style>.we{}</style>"; assert!(violations("x.html", &visible_text("x.html", html), "").is_empty()); } + + #[test] + fn allen_speech_is_exempt_and_nothing_else_is() { + let words = "we could chat over time and pick up where we left off"; + let check = |html: &str| violations("index.html", &visible_text("index.html", html), ""); + // Allen-tagged speech passes, nested markup included; the page around it is still checked. + assert!(check(&format!("<p data-speaker=\"allen\"><strong>Hey</strong> <span>{words}</span></p><p>I build it.</p>")).is_empty()); + assert!(check(&format!("<div id=\"x\" data-speaker=\"allen\"><div>{words}</div></div>")).is_empty()); + // Negative controls: the same words fail untagged, after the tagged element, + // under a lookalike attribute, as text, or in an unclosed element. + assert!(!check(&format!("<p>{words}</p>")).is_empty()); + assert!(!check(&format!("<p data-speaker=\"allen\">hi</p><p>{words}</p>")).is_empty()); + assert!(!check(&format!("<p data-speaker=\"allenx\">{words}</p>")).is_empty()); + assert!(!check(&format!("<p data-speaker=\"drake\">{words}</p>")).is_empty()); + assert!(!check(&format!("<p xdata-speaker=\"allen\">{words}</p>")).is_empty()); + assert!(!check(&format!("<p>data-speaker=\"allen\" {words}</p>")).is_empty()); + assert!(!check(&format!("<p data-speaker=\"allen\">{words}")).is_empty()); + // Markdown and text mirrors have no markup to tag, so the rule applies in full. + assert!(!violations("index.md", &visible_text("index.md", &format!("<p data-speaker=\"allen\">{words}</p>")), "").is_empty()); + } } diff --git a/crates/site-builder/src/main.rs b/crates/site-builder/src/main.rs index 05e10dc..f6552d4 100644 --- a/crates/site-builder/src/main.rs +++ b/crates/site-builder/src/main.rs @@ -245,7 +245,13 @@ fn build_pure_rust_site(dist: &Path, facts_path: &Path) { "website", html! { link rel="stylesheet" href="/assets/allen.css"; + link rel="stylesheet" href="/assets/allen-panes.css"; + link rel="stylesheet" href="/assets/allen-install.css"; + script defer src="/js/allen-audio.js" {} + script defer src="/js/allen-panes.js" {} script defer src="/js/allen.js" {} + script defer src="/js/allen-voice.js" {} + script defer src="/js/allen-install.js" {} }, components::allen::render_allen_page(), ); @@ -366,8 +372,8 @@ fn build_pure_rust_site(dist: &Path, facts_path: &Path) { println!(" [PAGE] Emitted /glossary/ (index.html)"); let privacy = render_page_layout( - "Privacy & saying hello to Allen | AienOS", - "Read without tracking. Saying hello to Allen consents to X pixel rfrlz; No refuses it.", + "Privacy & saying hi to Aien | AienOS", + "Read without tracking. Saying hi to Aien consents to X pixel rfrlz; No thanks refuses it.", "https://www.aienos.com/privacy/", "website", html! {}, diff --git a/crates/site-builder/src/seo.rs b/crates/site-builder/src/seo.rs index dabfe45..abfb574 100644 --- a/crates/site-builder/src/seo.rs +++ b/crates/site-builder/src/seo.rs @@ -84,7 +84,7 @@ pub const PAGES: &[PageInfo] = &[ PageInfo { path: "/", name: "AienOS", what: "The front page: the loop, the five real machines and their measured speeds beside the physical ceiling, the evidence cards, the current status of every layer.", section: Section::Machine, kind: Kind::Home, image: "/og.png", published: "2026-09-23", doi: None }, PageInfo { path: "/start/", name: "Start here", what: "The shortest route through AienOS: what it is, what exists today, how to check the evidence, how to reproduce or contribute, and where the author and Interplane fit.", section: Section::Start, kind: Kind::Page, image: "/og.png", published: "2026-10-24", doi: None }, PageInfo { path: "/contact/", name: "Where I am and how to reach me", what: "How to reach Drake: X @mdrakestapleton, email drake@aienos.com, Allen at /allen/ (who can pass a message on or put you through when Drake is online) and the aien-dev repositories on GitHub.", section: Section::Start, kind: Kind::Page, image: "/og.png", published: "2026-10-26", doi: None }, - PageInfo { path: "/privacy/", name: "Privacy & saying hello to Allen", what: "Your choice about the consent-only X pixel, what X receives, what I keep and how to refuse.", section: Section::Optional, kind: Kind::Page, image: "/og.png", published: "2026-10-26", doi: None }, + PageInfo { path: "/privacy/", name: "Privacy & saying hi to Aien", what: "Your choice about the consent-only X pixel, what X receives, what I keep and how to refuse.", section: Section::Optional, kind: Kind::Page, image: "/og.png", published: "2026-10-26", doi: None }, PageInfo { path: "/machine/", name: "The Machine", what: "One machine across five physical bodies: the closed epistemic loop, the Turing as its accounting layer, and an honest list of what exists.", section: Section::Machine, kind: Kind::Article, image: "/og-machine.png", published: "2026-10-01", doi: None }, PageInfo { path: "/omega/", name: "What Omega is", what: "Omega is AIEN's language for all computing, GPU to CPU; on the GPU it is the replacement for CUDA. The CUDA stack piece by piece with status, the receipt for the live server running with zero CUDA libraries, what is not true yet, and the bar C1 to C6.", section: Section::Machine, kind: Kind::Page, image: "/og-machine.png", published: "2026-10-21", doi: None }, PageInfo { path: "/cudaplusplus/", name: "CUDA++", what: "CUDA++ is the GPU half of Omega: everything CUDA gives you plus the motor, for the NVIDIA GPUs people already own, with no NVIDIA user-space software (Apache-2.0 with LLVM exception, aien-dev/CUDApp). What it is for, the path from program to chip with whose code runs at each step, how I did it, CUDA's pain points and the swap down to the kernel driver.", section: Section::Machine, kind: Kind::Page, image: "/og-machine.png", published: "2026-10-22", doi: None }, @@ -859,7 +859,7 @@ pub fn llms_txt(status_lines: &[String], research_sentence: &str) -> String { let mut s = String::new(); s.push_str("# AienOS\n\n"); s.push_str(&format!("> {SITE_CLAIM}. AienOS is an experimental, open source (Apache-2.0 WITH LLVM-exception) machine for turning search into verified understanding: AIEN proposes, Omega makes the proposal explicit and verifiable, the machine tests it against reality, the Turing measures what was learned, Cortex keeps the evidence. Every claim on the site carries a public receipt. Sovereign Intelligence, built on AienOS, is in alpha testing; each component keeps its own evidence level. Built by {AUTHOR} with AI agents on five real machines.\n\n")); - s.push_str("Rules the site keeps: no comparisons with other systems (every speed stands beside the physical ceiling of its own machine only), failures stay on the record, no outside fonts or unsolicited tracking (X pixel rfrlz loads only after saying hello to Allen; privacy and refusal at /privacy/; the film on /turing/ is an outside embed), and AI agents are welcome to read, cite, argue and correct. Contact Drake: drake@aienos.com or X @mdrakestapleton; every route, Allen included, is at https://www.aienos.com/contact/. Project mail: aien@aienos.com. Source: https://github.com/aien-dev.\n\n"); + s.push_str("Rules the site keeps: no comparisons with other systems (every speed stands beside the physical ceiling of its own machine only), failures stay on the record, no outside fonts or unsolicited tracking (X pixel rfrlz loads only after saying hi to Aien; privacy and refusal at /privacy/; the film on /turing/ is an outside embed), and AI agents are welcome to read, cite, argue and correct. Contact Drake: drake@aienos.com or X @mdrakestapleton; every route, Allen included, is at https://www.aienos.com/contact/. Project mail: aien@aienos.com. Source: https://github.com/aien-dev.\n\n"); s.push_str("## Current state\n\n"); for l in status_lines { s.push_str(&format!("- {l}\n")); @@ -1008,7 +1008,7 @@ pub fn data_index(ctx: &BuildCtx) -> String { "rules": [ "No comparisons with other systems: every number stands beside the physical ceiling of its own machine only.", "Every claim links its receipt. Failures stay on the record.", - "No outside fonts or unsolicited tracking. X pixel rfrlz loads only with Allen introduction consent; /privacy/ explains and controls the choice. The film on /turing/ is an outside embed." + "No outside fonts or unsolicited tracking. X pixel rfrlz loads only after saying hi to Aien; /privacy/ explains and controls the choice. The film on /turing/ is an outside embed." ], "files": files }); diff --git a/om/allen-audio/allen-audio.js.sha256 b/om/allen-audio/allen-audio.js.sha256 new file mode 100644 index 0000000..81bdafb --- /dev/null +++ b/om/allen-audio/allen-audio.js.sha256 @@ -0,0 +1 @@ +d3535b7dbd281fe7ceb4836f8e73a07eea460e51a3c1d422fa9a4091dee6040f ../../public/js/allen-audio.js diff --git a/om/allen-audio/allen-chirp.wav.sha256 b/om/allen-audio/allen-chirp.wav.sha256 new file mode 100644 index 0000000..cd25ae6 --- /dev/null +++ b/om/allen-audio/allen-chirp.wav.sha256 @@ -0,0 +1 @@ +ad1b8f5737161f9cd8730ab757da96ad1c1a9a68957723c5a102f9318ec97659 ../../public/audio/allen-chirp.wav diff --git a/om/allen-audio/asset.om b/om/allen-audio/asset.om new file mode 100644 index 0000000..861d9b4 --- /dev/null +++ b/om/allen-audio/asset.om @@ -0,0 +1,31 @@ +note Web half of Allen's startup sound; composed after chirp.om by check.sh. +note fd 1: public/audio/allen-chirp.wav, frames FZERO..FEND of the night (45120 frames, 940 ms), +note 16-bit mono at 48000 Hz, 90284 bytes. The native fill writes equal left and right samples, so +note one channel keeps every sample. fd 3: public/js/allen-audio.js, the browser controller that +note plays those bytes with WebAudio after a user gesture. Its text is the WebAudio glue only: no +note synthesis happens in the browser. + +text jsdoc "/*\n * allen-audio.js: Allen's startup sound, the one the iMac plays as its two\n * black holes merge. Generated by om/allen-audio (Omega); do not edit.\n *\n * The sound is ../audio/allen-chirp.wav, written sample for sample by\n * om/allen-audio/chirp.om, a port of aienux native/kernel/ui/chirp.c at\n * da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c. It holds frames 545280 to 590400\n * of the night at 48000 Hz, 16-bit mono (the native left and right samples\n * are equal): 11360 ms to 12300 ms of the night, the merger at 12000 ms.\n * This script only plays it.\n *\n * window.AllenAudio\n * enter(arg) call inside a click or key press. The only place an audio\n * context is created or resumed. arg is a scene kind or\n * { kind, nightMs }. The native source has one sound, the\n * merger chirp of the two-hole night (kind 'night', alias\n * 'home', the default); any other kind (the /allen/ tube\n * included) has no native sound and resolves false without\n * touching audio. nightMs is where the night is at the moment\n * of the call (default 0: the night starts now). As on the\n * iMac, the sound lands on the merger:\n * before 11360 ms it waits, inside the chirp it starts from\n * that moment, after 12300 ms nothing plays. While a sound\n * is pending or playing, enter returns the same promise;\n * after it ends or stops, the next gesture may enter again\n * (a replay). Resolves true once the sound is scheduled,\n * false when muted, unsupported, stopped or too late; never\n * rejects.\n * pause() suspends the audio context: its clock and the sound\n * freeze together, as the scene's clock does. Done by\n * itself when the page is hidden, so no chirp plays in the\n * background.\n * resume() resumes a context pause() suspended (the scene calls it\n * when it runs again); never creates one, and does nothing\n * while muted.\n * stop() stops the sound and closes the audio context; done by\n * itself on pagehide. Call it when the scene is destroyed\n * or replayed.\n * setMuted(b) stores the choice in localStorage 'allen.audio.muted'\n * ('1' or '0'), the only key this script writes; muting\n * stops the sound.\n * muted() the stored choice.\n * data-chirp-src on this script's tag points elsewhere (resolved against the\n * page); by default the file sits beside this script's folder, so the same\n * bytes work on aienos.com and on a localhost install.\n */\n(function () {\n 'use strict';\n var KEY = 'allen.audio.muted';\n var RATE = 48000;\n var FRAMES = 45120;\n var START_MS = 11360;\n var MERGE_MS = 12000;\n var END_MS = 12300;\n\n var me = document.currentScript;\n var pick = me && me.getAttribute('data-chirp-src');\n var src = pick ? new URL(pick, location.href).href\n : new URL('../audio/allen-chirp.wav', (me && me.src) || location.href).href;\n\n var ctx = null;\n var node = null;\n var entered = null;\n var paused = false;\n var pausedAt = 0;\n var pausedMs = 0;\n\n function stored() {\n try { return window.localStorage.getItem(KEY) === '1'; } catch (e) { return false; }\n }\n var isMuted = stored();\n\n function close() {\n var n = node;\n var c = ctx;\n node = null;\n ctx = null;\n entered = null;\n paused = false;\n if (n) {\n n.onended = null;\n try { n.stop(); } catch (e) { /* not started yet */ }\n n.disconnect();\n }\n if (c && c.close && c.state !== 'closed') c.close().then(null, function () {});\n }\n\n function word(v, at) { return v.getUint32(at, true); }\n function half(v, at) { return v.getUint16(at, true); }\n\n /* The asset's exact header, or nothing: mono 16-bit PCM at RATE, FRAMES long. */\n function pcm(bytes) {\n if (bytes.byteLength !== 44 + 2 * FRAMES) return null;\n var v = new DataView(bytes);\n if (word(v, 0) !== 0x46464952 || word(v, 4) !== 36 + 2 * FRAMES || word(v, 8) !== 0x45564157 ||\n word(v, 12) !== 0x20746d66 || word(v, 16) !== 16 || half(v, 20) !== 1 || half(v, 22) !== 1 ||\n word(v, 24) !== RATE || word(v, 28) !== 2 * RATE || half(v, 32) !== 2 || half(v, 34) !== 16 ||\n word(v, 36) !== 0x61746164 || word(v, 40) !== 2 * FRAMES) return null;\n var out = new Float32Array(FRAMES);\n for (var i = 0; i < FRAMES; i++) out[i] = v.getInt16(44 + 2 * i, true) / 32768;\n return out;\n }\n\n /* A silent frame started inside the gesture: some browsers unlock output only so. */\n function unlock(c) {\n try {\n var s = c.createBufferSource();\n s.buffer = c.createBuffer(1, 1, c.sampleRate);\n s.connect(c.destination);\n s.start(0);\n } catch (e) { /* the real sound still tries */ }\n }\n\n function play(c, samples, night) {\n if (c !== ctx || isMuted || night >= END_MS) return false;\n var buf = c.createBuffer(1, FRAMES, RATE);\n buf.getChannelData(0).set(samples);\n var n = c.createBufferSource();\n n.buffer = buf;\n n.connect(c.destination);\n n.onended = function () { if (node === n) close(); };\n node = n;\n if (night < START_MS) n.start(c.currentTime + (START_MS - night) / 1000);\n else n.start(0, (night - START_MS) / 1000);\n return true;\n }\n\n var KINDS = { night: 1, home: 1 };\n\n function enter(arg) {\n var opts = typeof arg === 'string' ? { kind: arg } : arg || {};\n if (!KINDS.hasOwnProperty(opts.kind || 'night')) return Promise.resolve(false);\n if (entered) return entered;\n var t0 = performance.now();\n pausedMs = 0;\n var base = typeof opts.nightMs === 'number' && opts.nightMs >= 0 ? opts.nightMs : 0;\n var AC = window.AudioContext || window.webkitAudioContext;\n if (isMuted || !AC || !window.fetch || base >= END_MS) return Promise.resolve(false);\n var c;\n try { c = new AC(); } catch (e) { return Promise.resolve(false); }\n ctx = c;\n if (c.resume) c.resume().then(null, function () {});\n unlock(c);\n entered = fetch(src, { credentials: 'same-origin' })\n .then(function (r) {\n if (!r.ok) throw new Error('allen-chirp.wav ' + r.status);\n return r.arrayBuffer();\n })\n .then(function (bytes) {\n var samples = pcm(bytes);\n var held = pausedMs + (paused ? performance.now() - pausedAt : 0);\n var ok = samples ? play(c, samples, base + performance.now() - t0 - held) : false;\n if (!ok && ctx === c) close();\n return ok;\n })\n .then(null, function () {\n if (ctx === c) close();\n return false;\n });\n return entered;\n }\n\n function pause() {\n if (!ctx || paused) return;\n paused = true;\n pausedAt = performance.now();\n if (ctx.suspend) ctx.suspend().then(null, function () {});\n }\n\n function resume() {\n if (!ctx || !paused || isMuted) return;\n paused = false;\n pausedMs += performance.now() - pausedAt;\n if (ctx.resume) ctx.resume().then(null, function () {});\n }\n\n function setMuted(on) {\n isMuted = !!on;\n try { window.localStorage.setItem(KEY, isMuted ? '1' : '0'); } catch (e) { /* kept for this page */ }\n if (isMuted) close();\n }\n\n document.addEventListener('visibilitychange', function () {\n if (document.visibilityState === 'hidden') pause();\n });\n window.addEventListener('pagehide', close);\n\n window.addEventListener('storage', function (e) {\n if (e.key !== KEY) return;\n isMuted = e.newValue === '1';\n if (isMuted) close();\n });\n\n window.AllenAudio = Object.freeze({\n enter: enter,\n stop: close,\n pause: pause,\n resume: resume,\n setMuted: setMuted,\n muted: function () { return isMuted; },\n src: src,\n kinds: Object.freeze(['night', 'home']),\n timeline: Object.freeze({ rate: RATE, frames: FRAMES, startMs: START_MS, mergeMs: MERGE_MS, endMs: END_MS })\n });\n})();\n" + +fn script to void +for i ulong len jsdoc +obyte get jsdoc i +end +end + +fn main to int +setup +put ofd 0 1 +owav 1 sub FEND FZERO +f = add FZERO 0 +note 45120 frames, one pass each. +while lt f FEND bound 45120 +osample sample f +f = add f 1 +end +oflush +put ofd 0 3 +script +oflush +ret 0 +end diff --git a/om/allen-audio/check.sh b/om/allen-audio/check.sh new file mode 100755 index 0000000..55a30a8 --- /dev/null +++ b/om/allen-audio/check.sh @@ -0,0 +1,143 @@ +#!/bin/sh +# Regenerate Allen's startup sound (public/audio/allen-chirp.wav) and its browser +# controller (public/js/allen-audio.js) with the pinned arm64 omc, then, when an +# aienux clone is given, check the Omega synthesis byte for byte against the +# original C it ports. +# +# The compiler is the one vendored for the Hive page; its pin is recorded once, +# in ../hive-page/omc.sha256. OMEGA_OMC overrides the compiler path, never its pin. +# OMEGA_ACCEPT_CHANGE=1 accepts rewritten artifacts; otherwise stale output exits 4. +# +# Oracle (AIENUX_SRC=<aienux clone holding commit $PIN>): extracts native/kernel/ui +# at $PIN, checks the blob ids of the sound's sources, builds aienux's own host +# test ui/tests/chirp_test.c with chirp.c (HOSTCC, default cc), and requires +# 1. its chirp.wav to equal native.om's output byte for byte (whole night, +# stereo, 590400 frames); +# 2. the web asset's samples to equal that file's left channel over frames +# 545280..590400, and right to equal left there; +# 3. a mutant oracle (CK_CHIRP_PEAK 22937 -> 22936) to differ (negative control). +# Without AIENUX_SRC the oracle prints ORACLE NOT_RUN; that is not a pass. +# +# Exit 2: missing compiler; 3: wrong pin; 4: stale artifact rewritten; +# 5: nondeterministic output; 6: empty output; 7: oracle mismatch; +# 8: negative control accepted; 9: oracle source missing or not the pinned blobs. +# Compile/run failures propagate. +set -eu +cd "$(dirname "$0")" +PIN=da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c +omc=${OMEGA_OMC:-$PWD/../hive-page/omc} +pin=$(tr -d ' \n' < ../hive-page/omc.sha256) +if [ ! -f "$omc" ]; then + printf 'No compiler at %s; set OMEGA_OMC to the pinned omc (%s)\n' "$omc" "$pin" >&2 + exit 2 +fi +have=$(sha256sum "$omc" | cut -d' ' -f1) +if [ "$have" != "$pin" ]; then + printf 'Compiler sha256 mismatch: recorded %s, found %s\n' "$pin" "$have" >&2 + exit 3 +fi +work=$(mktemp -d "${TMPDIR:-/tmp}/allen-audio.XXXXXX") +trap 'rm -rf "$work"' EXIT HUP INT TERM +# Concatenation composes Omega units; it does not implement generation in shell. +cat chirp.om asset.om > "$work/asset.om" +cat chirp.om native.om > "$work/native.om" +"$omc" < "$work/asset.om" > "$work/asset" +"$omc" < "$work/native.om" > "$work/native" +chmod +x "$work/asset" "$work/native" +"$work/asset" > "$work/first.wav" 3> "$work/first.js" +"$work/asset" > "$work/second.wav" 3> "$work/second.js" +stale=0 +publish() { + first=$1 + second=$2 + artifact=$3 + sidecar=$4 + if ! cmp -s "$first" "$second"; then + printf '%s: generator output differs between runs\n' "$artifact" >&2 + exit 5 + fi + if [ ! -s "$first" ]; then + printf '%s: generator wrote nothing\n' "$artifact" >&2 + exit 6 + fi + if [ ! -f "$artifact" ] || ! cmp -s "$artifact" "$first"; then + stale=1 + fi + cp "$first" "$artifact" + hash=$(sha256sum "$artifact" | cut -d' ' -f1) + printf '%s %s\n' "$hash" "$artifact" > "$sidecar" + printf '%s %s bytes sha256 %s\n' "$artifact" "$(wc -c < "$artifact" | tr -d ' ')" "$hash" +} +mkdir -p ../../public/audio +publish "$work/first.wav" "$work/second.wav" ../../public/audio/allen-chirp.wav allen-chirp.wav.sha256 +publish "$work/first.js" "$work/second.js" ../../public/js/allen-audio.js allen-audio.js.sha256 +printf 'omc sha256 %s\n' "$have" + +if [ -z "${AIENUX_SRC:-}" ]; then + printf 'ORACLE NOT_RUN: set AIENUX_SRC to an aienux clone holding %s\n' "$PIN" +else + if ! git -C "$AIENUX_SRC" cat-file -e "$PIN^{commit}" 2>/dev/null; then + printf 'ORACLE: %s has no commit %s\n' "$AIENUX_SRC" "$PIN" >&2 + exit 9 + fi + for want in \ + d3e732908a72a372816584d0fe3d62a3db256f1b:native/kernel/ui/chirp.c \ + 359f0f4e63e5c194b005906d3bd7b03cfb7e8703:native/kernel/ui/chirp.h \ + 4cecf8f2afcd8828915a87cefe2cbefab5ef7251:native/kernel/ui/night.h \ + 7032fee2ca584587981297ffa22ade4c72560a76:native/kernel/ui/tests/chirp_test.c; do + blob=${want%%:*} + path=${want#*:} + if [ "$(git -C "$AIENUX_SRC" rev-parse "$PIN:$path")" != "$blob" ]; then + printf 'ORACLE: %s at %s is not blob %s\n' "$path" "$PIN" "$blob" >&2 + exit 9 + fi + done + mkdir "$work/src" "$work/out" "$work/mut" "$work/mutout" + git -C "$AIENUX_SRC" archive "$PIN" native/kernel/ui | tar -x -C "$work/src" + ui=$work/src/native/kernel/ui + cc=${HOSTCC:-cc} + "$cc" -std=c11 -O2 -Wall -Wextra -Werror -o "$work/oracle" "$ui/tests/chirp_test.c" "$ui/chirp.c" + "$work/oracle" "$work/out" + "$work/native" > "$work/native.wav" + if ! cmp "$work/out/chirp.wav" "$work/native.wav"; then + printf 'ORACLE FAIL: Omega night differs from aienux chirp_test.c chirp.wav\n' >&2 + exit 7 + fi + # Frame 545280 of the stereo file starts at byte 44 + 545280 * 4; 45120 frames follow. + od -An -v -td2 -w4 -j 2181164 -N 180480 "$work/out/chirp.wav" > "$work/pairs.txt" + od -An -v -td2 -w2 -j 44 ../../public/audio/allen-chirp.wav > "$work/mono.txt" + awk '{ print $1 }' "$work/pairs.txt" > "$work/left.txt" + awk '$1 != $2 { bad = 1 } END { exit bad }' "$work/pairs.txt" || { + printf 'ORACLE FAIL: left and right differ in the chirp\n' >&2 + exit 7 + } + awk '{ print $1 }' "$work/mono.txt" > "$work/mono1.txt" + if ! cmp -s "$work/left.txt" "$work/mono1.txt"; then + printf 'ORACLE FAIL: allen-chirp.wav is not the oracle left channel at frames 545280..590400\n' >&2 + exit 7 + fi + # Negative control: the same oracle with the peak one step lower must not match. + git -C "$AIENUX_SRC" archive "$PIN" native/kernel/ui | tar -x -C "$work/mut" + mui=$work/mut/native/kernel/ui + sed 's/^#define CK_CHIRP_PEAK 22937 /#define CK_CHIRP_PEAK 22936 /' "$mui/chirp.h" > "$work/chirp.h" + if cmp -s "$work/chirp.h" "$mui/chirp.h"; then + printf 'NEGATIVE CONTROL: the mutation did not apply\n' >&2 + exit 8 + fi + cp "$work/chirp.h" "$mui/chirp.h" + "$cc" -std=c11 -O2 -Wall -Wextra -Werror -o "$work/mutant" "$mui/tests/chirp_test.c" "$mui/chirp.c" + "$work/mutant" "$work/mutout" > /dev/null || true + if cmp -s "$work/mutout/chirp.wav" "$work/native.wav"; then + printf 'NEGATIVE CONTROL FAIL: a mutated oracle also matched\n' >&2 + exit 8 + fi + printf 'ORACLE PASS: aienux %s chirp_test.c chirp.wav == Omega night (%s bytes); web asset == its left channel, frames 545280..590400; mutant oracle differs\n' \ + "$PIN" "$(wc -c < "$work/native.wav" | tr -d ' ')" +fi + +if [ "$stale" = 1 ]; then + printf 'Generated artifacts were rewritten; commit them with their Omega sources\n' >&2 + if [ "${OMEGA_ACCEPT_CHANGE:-0}" != 1 ]; then + exit 4 + fi +fi diff --git a/om/allen-audio/chirp.om b/om/allen-audio/chirp.om new file mode 100644 index 0000000..a2e0830 --- /dev/null +++ b/om/allen-audio/chirp.om @@ -0,0 +1,272 @@ +note Allen's startup sound: the merger chirp of the iMac night, ported from aienux +note native/kernel/ui/chirp.c and chirp.h at da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c (git blobs +note d3e732908a72a372816584d0fe3d62a3db256f1b and 359f0f4e63e5c194b005906d3bd7b03cfb7e8703; +note CK_NIGHT_MERGE_MS 12000 from ui/night.h). The same files are byte-identical at the iMac build +note 0930240d2aa550de95535c116eb10c2df466f616. That source makes exactly one sound: this chirp. It +note has no other boom, voice or opening sound; every speaker path (x86/hda_x86.c, dev/virtio_snd.c) +note plays ck_chirp_fill or ck_chirp_fill_441 from the night's current moment. +note +note The sound: silent until 640 ms before the merger, comes in over 40 ms (smoothstep) at 200 Hz, +note sweeps up as L^(-3/8) in pitch and L^(-1/4) in loudness (L the share of the 600 ms inspiral +note left) until the pitch reaches 1000 Hz, holds 1000 Hz at peak 22937 to the merger at 12000 ms, +note then decays with a 30 ms time constant until 12300 ms. Integer only, exactly as the C: +note phases in 2^32ths of a cycle, L and its powers in Q30, a 4096-entry Q14 sine table built by +note rotation. Every function below mirrors one C function and keeps its rounding order. +note +note Not a program by itself: check.sh concatenates this unit with asset.om (the web asset and the +note browser script) or native.om (the oracle layout of aienux ui/tests/chirp_test.c). +note +note Frame constants, from chirp.h with CK_CHIRP_RATE 48000 and CK_NIGHT_MERGE_MS 12000, checked +note with WolframLanguageEvaluator: {48000/1000*(12000-600-40), 48000/1000*(12000-600), +note 48000/1000*12000, 48000/1000*(12000+300)} -> {545280, 547200, 576000, 590400}; +note Round[Exp[-1/(30/1000*48000)]*2^30] -> 1072996429 (the C literal DECAY); +note Round[Cos[2 Pi/4096]*2^30] -> 1073740561, Round[Sin[2 Pi/4096]*2^30] -> 1647099 (C, S). + +const RATE ulong 48000 +const FROMHZ ulong 200 +const TOHZ ulong 1000 +const PEAK ulong 22937 +const FZERO ulong 545280 +const FONE ulong 547200 +const FTWO ulong 576000 +const FEND ulong 590400 +const DECAY ulong 1072996429 +const QONE ulong 1073741824 +const COSQ long 1073740561 +const SINQ long 1647099 + +note sint: the Q14 sine table. cap: 0 cap_frame, 1 cap_l14, 2 cap_phase (chirp.c setup). +global sint long 4096 +global cap ulong 3 + +note Output: one buffered stream, written to the descriptor in ofd. +global obuf uchar 65536 +global oused ulong 1 +global ofd int 1 + +text riff "RIFF" +text wavefmt "WAVEfmt " +text datatag "data" + +note Integer square root, chirp.c isqrt. Each loop divides bit by 4 from 2^62, so neither runs more +note than 32 passes. +fn isqrt x ulong to ulong +r = ulong 0 +b = shl ulong 1 62 +v = x +while gt b v bound 40 +b = shr b 2 +end +while ne b 0 bound 40 +if ge v add r b +v = sub v add r b +r = add shr r 1 b +else +r = shr r 1 +end +b = shr b 2 +end +ret r +end + +note L at a frame of the inspiral, Q30 (chirp.c left_q30). +fn leftq f ulong to ulong +ret div shl sub FTWO f 30 sub FTWO FONE +end + +note Eighth root of a Q30 value (chirp.c root8: three square roots). +fn root8 l ulong to ulong +v = isqrt shl l 30 +v = isqrt shl v 30 +v = isqrt shl v 30 +ret v +end + +fn mulq a ulong b ulong to ulong +ret shr mul a b 30 +end + +note Phase over the inspiral before the cap: P1 + K (1 - L^(5/8)) (chirp.c inspiral_phase). +fn insphase f ulong to ulong +r = root8 leftq f +l58 = mulq mulq mulq mulq r r r r r +p1 = div shl mul FROMHZ sub FONE FZERO 32 RATE +k = mul mul FROMHZ 8 sub FTWO FONE +ret add p1 div shl mul k sub QONE l58 2 mul 5 RATE +end + +note The sine table by rotation, chirp.c setup, same store order. k runs 0..1024: 1025 passes. +fn sintab to void +c = long 1073741824 +s = long 0 +k = ulong 0 +while le k 1024 bound 1025 +v = long 16384 +if ne k 1024 +v = shr add s 32768 16 +end +put sint k v +put sint sub 2048 k v +put sint and add 2048 k 4095 neg v +put sint and sub 4096 k 4095 neg v +nc = shr sub mul c COSQ mul s SINQ 30 +ns = shr add mul s COSQ mul c SINQ 30 +c = nc +s = ns +k = add k 1 +end +end + +note The first frame where L^(3/8) falls to FROMHZ / TOHZ: binary search over the 28800 inspiral +note frames, at most 15 passes. +fn capfind to ulong +want = div shl FROMHZ 30 TOHZ +lo = add FONE 0 +hi = add FTWO 0 +while lt lo hi bound 64 +mid = add lo div sub hi lo 2 +r = root8 leftq mid +if le mulq mulq r r r want +hi = mid +else +lo = add mid 1 +end +end +ret lo +end + +fn setup to void +sintab +lo = capfind +r = root8 leftq lo +put cap 0 lo +put cap 1 mulq r r +put cap 2 insphase lo +end + +note chirp.c phase_at; called only for frames with a nonzero level (f >= FZERO). +fn phaseat f ulong to ulong +if lt f FONE +ret div shl mul FROMHZ sub f FZERO 32 RATE +end +if lt f get cap 0 +ret insphase f +end +ret add get cap 2 div shl mul TOHZ sub f get cap 0 32 RATE +end + +note DECAY^k in Q30 by squaring; k < 2^14 here, so at most 14 passes. +fn decaypow k ulong to ulong +r = add QONE 0 +b = add DECAY 0 +n = k +while ne n 0 bound 70 +if eq and n 1 1 +r = mulq r b +end +b = mulq b b +n = shr n 1 +end +ret r +end + +note chirp.c ck_chirp_level: 0..PEAK at a frame. +fn level f ulong to ulong +if or lt f FZERO ge f FEND +ret 0 +end +if lt f FONE +steady = shr mul PEAK get cap 1 30 +x = div shl sub f FZERO 16 sub FONE FZERO +s = mul mul x x sub mul ulong 3 65536 mul 2 x +ret shr mul steady s 48 +end +if lt f get cap 0 +r = root8 leftq f +ret div mul PEAK get cap 1 mulq r r +end +if lt f FTWO +ret PEAK +end +ret shr mul PEAK decaypow sub f FTWO 30 +end + +note One sample of chirp.c ck_chirp_fill: the table read at the phase's top 12 bits, a straight +note line by the next 16, scaled by the level. Signed shr keeps the sign, as the C's int64 shifts. +fn sample f ulong to long +a = level f +if eq a 0 +ret long 0 +end +ph = and phaseat f 4294967295 +k = shr ph 20 +fr = and shr ph 4 65535 +s0 = get sint k +s1 = get sint and add k 1 4095 +s = add s0 shr mul sub s1 s0 long fr 16 +ret shr mul s long a 14 +end + +fn oflush to void +p = ulong 0 +while lt p get oused 0 bound 65536 +n = write get ofd 0 obuf p sub get oused 0 p +if le n 0 +trap 3 +end +p = add p ulong n +end +put oused 0 0 +end + +fn obyte c uchar to void +if eq get oused 0 len obuf +oflush +end +put obuf get oused 0 c +put oused 0 add get oused 0 1 +end + +fn ole16 v ulong to void +obyte uchar and v 255 +obyte uchar and shr v 8 255 +end + +fn ole32 v ulong to void +ole16 and v 65535 +ole16 shr v 16 +end + +note A 16-bit little-endian sample (two's complement). +fn osample v long to void +u = ulong 0 +if lt v 0 +u = ulong add v 65536 +else +u = ulong v +end +ole16 u +end + +note The canonical 44-byte PCM WAV header (the layout of chirp_test.c write_wav). +fn owav ch ulong frames ulong to void +bytes = mul frames mul 2 ch +for i ulong len riff +obyte get riff i +end +ole32 add 36 bytes +for i ulong len wavefmt +obyte get wavefmt i +end +ole32 16 +ole16 1 +ole16 ch +ole32 RATE +ole32 mul RATE mul 2 ch +ole16 mul 2 ch +ole16 16 +for i ulong len datatag +obyte get datatag i +end +ole32 bytes +end diff --git a/om/allen-audio/native.om b/om/allen-audio/native.om new file mode 100644 index 0000000..0c67574 --- /dev/null +++ b/om/allen-audio/native.om @@ -0,0 +1,22 @@ +note Oracle layout of Allen's startup sound; composed after chirp.om by check.sh. +note Writes to fd 1 the exact file aienux native/kernel/ui/tests/chirp_test.c writes as chirp.wav +note (write_wav(path, s, N), N = CK_CHIRP_FRAMES = 590400): 2 channels, 16-bit, 48000 Hz, frames 0 +note to 590400 (0 ms to 12300 ms of the night), left equal to right. check.sh compares it byte for +note byte with that C program's output, built from the pinned aienux source, so the Omega port is +note checked against the original, not against itself. + +fn main to int +setup +put ofd 0 1 +owav 2 FEND +f = ulong 0 +note 590400 frames, one pass each. +while lt f FEND bound 590400 +v = sample f +osample v +osample v +f = add f 1 +end +oflush +ret 0 +end diff --git a/om/allen-install/allen-install.css.sha256 b/om/allen-install/allen-install.css.sha256 new file mode 100644 index 0000000..6b7858f --- /dev/null +++ b/om/allen-install/allen-install.css.sha256 @@ -0,0 +1 @@ +6eba1ee1082422b80ead479bbcec1c60b41504fda3d3867d77afd2c5abdc5aa2 ../../public/assets/allen-install.css diff --git a/om/allen-install/allen-install.js.sha256 b/om/allen-install/allen-install.js.sha256 new file mode 100644 index 0000000..a429899 --- /dev/null +++ b/om/allen-install/allen-install.js.sha256 @@ -0,0 +1 @@ +4bf4aab56e35cf72236296964e2caed21c87caf8ecf971f798aa5b10eef8d03b ../../public/js/allen-install.js diff --git a/om/allen-install/check.sh b/om/allen-install/check.sh new file mode 100755 index 0000000..109f203 --- /dev/null +++ b/om/allen-install/check.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# Regenerate the Allen install offer script and style using the pinned arm64 omc. +# The compiler is the one vendored for the Hive page; its pin is recorded once, +# in ../hive-page/omc.sha256. CI on x86_64 checks the committed artifacts +# against their recorded hashes. OMEGA_OMC overrides the compiler path, never its pin. +# OMEGA_ACCEPT_CHANGE=1 accepts rewritten artifacts; otherwise stale output exits 4. +# Exit 2: missing compiler; 3: wrong pin; 4: stale artifact rewritten; +# 5: nondeterministic output; 6: empty output. Compile/run failures propagate. +set -eu +cd "$(dirname "$0")" +omc=${OMEGA_OMC:-$PWD/../hive-page/omc} +pin=$(tr -d ' \n' < ../hive-page/omc.sha256) +if [ ! -f "$omc" ]; then + printf 'No compiler at %s; set OMEGA_OMC to the pinned omc (%s)\n' "$omc" "$pin" >&2 + exit 2 +fi +have=$(sha256sum "$omc" | cut -d' ' -f1) +if [ "$have" != "$pin" ]; then + printf 'Compiler sha256 mismatch: recorded %s, found %s\n' "$pin" "$have" >&2 + exit 3 +fi +work=$(mktemp -d "${TMPDIR:-/tmp}/allen-install.XXXXXX") +trap 'rm -rf "$work"' EXIT HUP INT TERM +"$omc" < install.om > "$work/install" +chmod +x "$work/install" +"$work/install" > "$work/first.js" 3> "$work/first.css" +"$work/install" > "$work/second.js" 3> "$work/second.css" +stale=0 +publish() { + first=$1 + second=$2 + artifact=$3 + sidecar=$4 + if ! cmp -s "$first" "$second"; then + printf '%s: generator output differs between runs\n' "$artifact" >&2 + exit 5 + fi + if [ ! -s "$first" ]; then + printf '%s: generator wrote nothing\n' "$artifact" >&2 + exit 6 + fi + if [ ! -f "$artifact" ] || ! cmp -s "$artifact" "$first"; then + stale=1 + fi + cp "$first" "$artifact" + hash=$(sha256sum "$artifact" | cut -d' ' -f1) + printf '%s %s\n' "$hash" "$artifact" > "$sidecar" + printf '%s %s bytes sha256 %s\n' "$artifact" "$(wc -c < "$artifact" | tr -d ' ')" "$hash" +} +publish "$work/first.js" "$work/second.js" ../../public/js/allen-install.js allen-install.js.sha256 +publish "$work/first.css" "$work/second.css" ../../public/assets/allen-install.css allen-install.css.sha256 +printf 'omc sha256 %s\n' "$have" +if [ "$stale" = 1 ]; then + printf 'Generated artifacts were rewritten; commit them with their Omega sources\n' >&2 + if [ "${OMEGA_ACCEPT_CHANGE:-0}" != 1 ]; then + exit 4 + fi +fi diff --git a/om/allen-install/install.om b/om/allen-install/install.om new file mode 100644 index 0000000..f109e39 --- /dev/null +++ b/om/allen-install/install.om @@ -0,0 +1,52 @@ +note Allen install offer generator: public/js/allen-install.js on fd 1 and +note public/assets/allen-install.css on fd 3. The browser behaviour is authored +note here as the emitted texts; check.sh only compares and publishes them. +note Offer rules: shown only after a visitor-started exchange ends with a reply +note that has text and no outcome; never on load, the greeting or a silent send. +note beforeinstallprompt is captured and prompt() runs only inside the tap on +note the offer. One localStorage key, allen-install, holds dismissed, accepted, +note guided or installed; storage failures fall back to page memory and never +note throw. iOS Safari gets a two-step Share then Add to Home Screen guide with +note local SVG icons. Installed success is said only on appinstalled. +note The card is offered to the page through the cancelable document event +note allen-pane-request (detail id title node focus, host sets detail.handle); +note unhandled, it is placed inline beside the latest reply. +note Source language checked at omega-mv 55f9b0af47de70a3d06357985cf99ae3e45c016f. +text js1 "/* Generated from om/allen-install/install.om; never hand-edit.\n *\n * The offer to put Aien on the home screen. It appears only after the first\n * exchange the visitor started that ended with a real reply, never on load or\n * on the greeting. The browser install prompt opens only inside the visitor's\n * tap on the offer. One local preference (dismissed, accepted, guided or\n * installed) stops further offers; nothing else is stored and nothing is sent.\n * Success is reported only when the browser fires appinstalled.\n */\n(() => {\n'use strict';\nif (window.AllenInstall) return;\nconst KEY = 'allen-install';\nconst TITLE = 'Put me on your home screen';\nconst SVG = 'http://www.w3.org/2000/svg';\nlet deferred = null, earned = false, asked = false, open = null, memo = '', connected = false;\nfunction remembered() {\n if (memo) return memo;\n try { return window.localStorage.getItem(KEY) || ''; } catch (_) { return ''; }\n}\nfunction remember(value) {\n memo = value;\n try { window.localStorage.setItem(KEY, value); } catch (_) {}\n}\nfunction installed() {\n try { if (window.navigator.standalone === true) return true; } catch (_) {}\n try {\n for (const mode of ['standalone', 'minimal-ui', 'fullscreen', 'window-controls-overlay']) if (window.matchMedia(`(display-mode: ${mode})`).matches) return true;\n } catch (_) {}\n return false;\n}\nfunction appleSafari() {\n const ua = String(window.navigator.userAgent || '');\n const apple = /iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && window.navigator.maxTouchPoints > 1);\n return apple && /Safari/.test(ua) && !/CriOS|FxiOS|EdgiOS|OPiOS|GSA|FBAN|FBAV|Instagram/.test(ua);\n}\nfunction el(tag, cls, text) {\n const node = document.createElement(tag);\n if (cls) node.className = cls;\n if (text) node.textContent = text;\n return node;\n}\n" +text js2 "function button(cls, text, fn) {\n const node = el('button', cls, text);\n node.type = 'button';\n node.addEventListener('click', fn);\n return node;\n}\nfunction icon(label, lines) {\n const svg = document.createElementNS(SVG, 'svg');\n svg.setAttribute('viewBox', '0 0 24 24');\n svg.setAttribute('width', '28');\n svg.setAttribute('height', '28');\n svg.setAttribute('class', 'allen-install-icon');\n if (label) {\n svg.setAttribute('role', 'img');\n svg.setAttribute('aria-label', label);\n } else svg.setAttribute('aria-hidden', 'true');\n for (const d of lines) {\n const path = document.createElementNS(SVG, 'path');\n path.setAttribute('d', d);\n svg.appendChild(path);\n }\n return svg;\n}\nfunction step(svg, before, strong, after) {\n const item = el('li', 'allen-install-step');\n const words = el('span', 'allen-install-words');\n words.append(before, el('strong', '', strong), after);\n item.append(svg, words);\n return item;\n}\nfunction guide() {\n const list = el('ol', 'allen-install-steps');\n list.setAttribute('role', 'list');\n list.append(\n step(icon('Share icon: a square with an arrow pointing up', ['M8 10H6v10h12V10h-2', 'M12 15V3', 'M8 7l4-4 4 4']), 'In Safari, tap ', 'Share', '. If you do not see it, tap the three dots first.'),\n step(icon('Add to Home Screen icon: a square with a plus', ['M7 4h10a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3z', 'M12 8v8', 'M8 12h8']), 'Choose ', 'Add to Home Screen', ', then tap Add.')\n );\n return list;\n}\nfunction offer() {\n if (open || !earned || remembered() || installed()) return;\n if (!deferred && !appleSafari()) return;\n const box = el('div', 'allen-install');\n const lede = el('p', 'allen-install-lede', 'Keep me one tap away. Your browser adds me to your home screen, and you can remove me the way you remove any app.');\n" +text js3 " const state = el('p', 'allen-install-state');\n state.setAttribute('role', 'status');\n const actions = el('div', 'allen-install-actions');\n const card = { box, state, actions, buttons: [], handle: null, inline: null, watch: null, closing: false };\n open = card;\n card.buttons.push(button('allen-pane-act allen-pane-run allen-install-yes', TITLE, () => accept(card)), button('allen-pane-act allen-install-no', 'No thanks', () => dismiss(card)));\n actions.append(...card.buttons);\n box.append(lede, actions, state);\n place(card);\n}\nfunction dismiss(card) {\n if (!remembered()) remember('dismissed');\n shut(card);\n}\nfunction finish(card, text) {\n card.state.textContent = text;\n card.actions.replaceChildren(button('allen-pane-act allen-install-done', 'Close', () => shut(card)));\n}\nfunction accept(card) {\n const event = deferred;\n if (event) {\n deferred = null;\n for (const b of card.buttons) b.disabled = true;\n let asking;\n try { asking = Promise.resolve(event.prompt()); } catch (_) { asking = Promise.reject(new Error('prompt')); }\n asking.then(() => event.userChoice).then(choice => {\n if (remembered() === 'installed') return;\n if (choice && choice.outcome === 'accepted') {\n remember('accepted');\n finish(card, 'Your browser is adding me. I will say so here when it confirms.');\n } else {\n remember('dismissed');\n finish(card, 'No problem. I will not ask again on this device.');\n }\n }, () => finish(card, 'Your browser did not open its install prompt, so nothing changed.'));\n return;\n }\n if (appleSafari()) {\n card.box.insertBefore(guide(), card.actions);\n remember('guided');\n finish(card, 'I cannot see your home screen from here, so I will not offer this again on this device.');\n }\n}\nfunction shut(card) {\n if (card.closing) return;\n card.closing = true;\n" +text js4 " if (card.watch) card.watch.disconnect();\n if (open === card) open = null;\n if (card.handle && typeof card.handle.close === 'function') card.handle.close();\n if (card.inline) card.inline.remove();\n else card.box.remove();\n}\nfunction place(card) {\n const detail = { id: 'install', title: TITLE, node: card.box, focus: false, handle: null };\n const request = new CustomEvent('allen-pane-request', { cancelable: true, detail });\n if (!document.dispatchEvent(request) && detail.handle && detail.handle.ok) card.handle = detail.handle;\n else {\n const aside = el('aside', 'allen-install-inline');\n aside.setAttribute('aria-label', TITLE);\n const head = el('div', 'allen-install-head');\n const close = button('allen-install-close', '', () => dismiss(card));\n close.setAttribute('aria-label', 'Close, and do not offer this again');\n close.appendChild(icon('', ['M6 6l12 12', 'M18 6L6 18']));\n head.append(el('p', 'allen-install-title', TITLE), close);\n aside.append(head, card.box);\n const answer = document.getElementById('allen-answer');\n const spot = document.getElementById('allen-install-slot') || (answer && answer.parentNode) || document.getElementById('allen') || document.body;\n spot.appendChild(aside);\n card.inline = aside;\n }\n if (typeof MutationObserver === 'function') {\n card.watch = new MutationObserver(() => {\n if (!card.box.isConnected && !card.closing) dismiss(card);\n });\n card.watch.observe(document.documentElement, { childList: true, subtree: true });\n }\n}\nfunction connect() {\n const api = window.allen;\n if (connected || !api || typeof api.on !== 'function') return;\n connected = true;\n api.on('send', event => { asked = !event.silent; });\n api.on('reply', event => {\n" +text js5 " const good = asked && !event.outcome && typeof event.text === 'string' && event.text.trim() !== '';\n asked = false;\n if (!good) return;\n earned = true;\n offer();\n });\n}\nwindow.addEventListener('beforeinstallprompt', event => {\n event.preventDefault();\n deferred = event;\n offer();\n});\nwindow.addEventListener('appinstalled', () => {\n deferred = null;\n remember('installed');\n if (open) finish(open, 'Your browser says I am installed. Open me from your home screen or app list.');\n});\ndocument.addEventListener('allen-ready', connect);\nconnect();\nwindow.AllenInstall = Object.freeze({ version: 1 });\n})();\n" +text css1 "/* Generated from om/allen-install/install.om; never hand-edit. */\n.allen-install { display: grid; gap: 10px; font-size: 13px; line-height: 1.55; color: var(--text-secondary); text-align: left; }\n.allen-install-lede { margin: 0; }\n.allen-install-actions { display: flex; flex-wrap: wrap; gap: 8px; }\n.allen-install-state { margin: 0; min-height: 1.55em; color: var(--text-primary); }\n.allen-install-state:empty { min-height: 0; }\n.allen-install-steps { margin: 0; padding: 0; list-style: none; display: grid; gap: 10px; }\n.allen-install-step { display: grid; grid-template-columns: 44px 1fr; align-items: center; gap: 12px; padding: 10px 12px; border: 1px solid var(--border-subtle); border-radius: 14px; background: color-mix(in srgb, var(--bg-card) 72%, transparent); }\n.allen-install-icon { width: 28px; height: 28px; justify-self: center; fill: none; stroke: var(--text-primary); stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }\n.allen-install-step .allen-install-icon { width: 44px; height: 44px; padding: 8px; border-radius: 12px; background: color-mix(in srgb, var(--bg-surface) 80%, transparent); border: 1px solid var(--border-subtle); }\n.allen-install-words strong { color: var(--text-primary); font-weight: 500; }\n.allen-install-inline { pointer-events: auto; margin: 12px auto 0; width: min(420px, 100%); padding: 14px 16px; border: 1px solid var(--border-subtle); border-radius: 18px; background: color-mix(in srgb, var(--bg-surface) 82%, transparent); backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); box-shadow: 0 12px 40px color-mix(in srgb, var(--bg-base) 60%, transparent); animation: allen-install-in 360ms ease-out both; }\n" +text css2 ".allen-install-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }\n.allen-install-title { margin: 0; font-size: 14px; color: var(--text-primary); }\n.allen-install-close { display: inline-grid; place-items: center; width: 32px; height: 32px; padding: 0; border-radius: 999px; border: 1px solid var(--border-subtle); background: transparent; color: var(--text-secondary); cursor: pointer; }\n.allen-install-close:hover { background: var(--bg-card-hover); color: var(--text-primary); }\n.allen-install-close .allen-install-icon { width: 16px; height: 16px; stroke: currentColor; }\n.allen-install button:focus-visible, .allen-install-close:focus-visible { outline: 2px solid var(--accent-green); outline-offset: 2px; }\n@keyframes allen-install-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }\n@media (prefers-reduced-motion: reduce) { .allen-install-inline { animation: none; } }\n@media (max-width: 720px) { .allen-install-inline { width: 100%; } .allen-install-actions button { min-height: 44px; } }\n" +fn main to int +w = write 1 js1 0 len js1 +if ne w long len js1 +ret 1 +end +w = write 1 js2 0 len js2 +if ne w long len js2 +ret 1 +end +w = write 1 js3 0 len js3 +if ne w long len js3 +ret 1 +end +w = write 1 js4 0 len js4 +if ne w long len js4 +ret 1 +end +w = write 1 js5 0 len js5 +if ne w long len js5 +ret 1 +end +w = write 3 css1 0 len css1 +if ne w long len css1 +ret 1 +end +w = write 3 css2 0 len css2 +if ne w long len css2 +ret 1 +end +ret 0 +end diff --git a/om/allen-install/test-install.cjs b/om/allen-install/test-install.cjs new file mode 100644 index 0000000..1fc2a58 --- /dev/null +++ b/om/allen-install/test-install.cjs @@ -0,0 +1,264 @@ +'use strict'; +/* Behaviour harness for the generated public/js/allen-install.js: a small fake + DOM in node:vm, not a browser or visual claim. Run from the repo root: + node om/allen-install/test-install.cjs */ +const fs = require('node:fs'), vm = require('node:vm'), assert = require('node:assert/strict'); +/* ALLEN_INSTALL_JS points the harness at another build, for negative controls. */ +const SOURCE = fs.readFileSync(process.env.ALLEN_INSTALL_JS || 'public/js/allen-install.js', 'utf8'); +const TITLE = 'Put me on your home screen'; +const UA = { + android: 'Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36', + iphone: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Mobile/15E148 Safari/604.1', + ipados: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15', + crios: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/141.0.0.0 Mobile/15E148 Safari/604.1', + firefox: 'Mozilla/5.0 (X11; Linux aarch64; rv:144.0) Gecko/20100101 Firefox/144.0', +}; +let inClick = false; +class Events { + constructor() { this.listeners = new Map(); } + addEventListener(type, fn) { if (!this.listeners.has(type)) this.listeners.set(type, new Set()); this.listeners.get(type).add(fn); } + removeEventListener(type, fn) { this.listeners.get(type)?.delete(fn); } + dispatchEvent(event) { for (const fn of [...(this.listeners.get(event.type) || [])]) fn(event); return !event.defaultPrevented; } +} +function world(opts = {}) { + const observers = new Set(); + const mutated = () => { for (const o of observers) queueMicrotask(() => o.fn([])); }; + class Node extends Events { + constructor(tag) { super(); this.tagName = tag; this.children = []; this.parentNode = null; this.attrs = new Map(); this.text = ''; this.className = ''; this.hidden = false; this.disabled = false; } + get isConnected() { let n = this; while (n.parentNode) n = n.parentNode; return n === doc.documentElement; } + get textContent() { return this.text + this.children.map(c => c.textContent).join(''); } + set textContent(v) { this.detachAll(); this.text = String(v); } + get lastChild() { return this.children[this.children.length - 1] || null; } + detachAll() { for (const c of this.children) c.parentNode = null; this.children = []; } + adopt(n) { if (typeof n === 'string') { const t = new Node('#text'); t.text = n; n = t; } if (n.parentNode) n.remove(); n.parentNode = this; return n; } + append(...ns) { for (const n of ns) this.children.push(this.adopt(n)); mutated(); } + appendChild(n) { this.append(n); return n; } + insertBefore(n, ref) { const node = this.adopt(n); const at = this.children.indexOf(ref); this.children.splice(at < 0 ? this.children.length : at, 0, node); mutated(); return node; } + replaceChildren(...ns) { this.detachAll(); this.append(...ns); } + remove() { const p = this.parentNode; if (!p) return; p.children = p.children.filter(c => c !== this); this.parentNode = null; mutated(); } + setAttribute(k, v) { this.attrs.set(k, String(v)); } + getAttribute(k) { return this.attrs.has(k) ? this.attrs.get(k) : null; } + removeAttribute(k) { this.attrs.delete(k); } + click() { if (this.disabled) return; inClick = true; try { this.dispatchEvent({ type: 'click' }); } finally { inClick = false; } } + all(pred, out = []) { for (const c of this.children) { if (pred(c)) out.push(c); c.all(pred, out); } return out; } + } + const doc = new Events(); + doc.documentElement = new Node('html'); + doc.body = new Node('body'); + doc.documentElement.append(doc.body); + doc.createElement = tag => new Node(tag); + doc.createElementNS = (ns, tag) => Object.assign(new Node(tag), { ns }); + doc.getElementById = id => doc.documentElement.all(n => n.attrs.get('id') === id)[0] || null; + const allen = new Node('div'); allen.setAttribute('id', 'allen'); + const current = new Node('section'); current.className = 'allen-current'; + const answer = new Node('div'); answer.setAttribute('id', 'allen-answer'); + const panesRoot = new Node('div'); panesRoot.setAttribute('id', 'allen-panes'); + current.append(answer); allen.append(panesRoot, current); doc.body.append(allen); + const panes = []; + if (opts.paneHost !== false) doc.addEventListener('allen-pane-request', event => { + /* Mirrors the host contract: open the node in a card pane and hand back a handle. */ + event.preventDefault(); + const pane = new Node('section'); pane.className = 'allen-pane'; pane.title = event.detail.title; + pane.append(event.detail.node); panesRoot.append(pane); + const rec = { pane, detail: event.detail, closed: 0 }; + panes.push(rec); + event.detail.handle = { ok: true, id: event.detail.id, close: () => { rec.closed++; pane.remove(); } }; + }); + const store = opts.store || new Map(); + const localStorage = { getItem: k => (store.has(k) ? store.get(k) : null), setItem: (k, v) => { if (opts.quota) throw new Error('QuotaExceededError'); store.set(k, String(v)); } }; + const win = new Events(); + if (opts.noStorage) Object.defineProperty(win, 'localStorage', { get() { throw new Error('SecurityError'); } }); + else win.localStorage = localStorage; + win.navigator = { userAgent: UA[opts.ua || 'android'], maxTouchPoints: opts.ua === 'ipados' ? 5 : 0 }; + if (opts.iosStandalone) win.navigator.standalone = true; + win.matchMedia = q => ({ matches: Boolean(opts.display) && q === `(display-mode: ${opts.display})` }); + const handlers = new Map(); + const api = { on: (t, fn) => { if (!handlers.has(t)) handlers.set(t, new Set()); handlers.get(t).add(fn); return () => handlers.get(t).delete(fn); } }; + const emit = (t, d) => { for (const fn of handlers.get(t) || []) fn(Object.freeze({ ...d })); }; + class CustomEvent { constructor(type, init = {}) { this.type = type; this.detail = init.detail; this.cancelable = Boolean(init.cancelable); this.defaultPrevented = false; } preventDefault() { if (this.cancelable) this.defaultPrevented = true; } } + class MutationObserver { constructor(fn) { this.fn = fn; } observe() { observers.add(this); } disconnect() { observers.delete(this); } } + const context = { window: win, document: doc, CustomEvent, MutationObserver, Promise, Error, String, Object, queueMicrotask }; + win.window = win; + const boot = () => { win.allen = Object.freeze(api); doc.dispatchEvent({ type: 'allen-ready' }); }; + vm.runInNewContext(SOURCE, context, { filename: 'allen-install.js' }); + if (opts.ready !== false) boot(); + const bip = (outcome = 'accepted') => { + const e = { type: 'beforeinstallprompt', prevented: 0, prompts: 0, promptInClick: [], preventDefault() { this.prevented++; } }; + e.prompt = () => { e.prompts++; e.promptInClick.push(inClick); return Promise.resolve(); }; + e.userChoice = Promise.resolve({ outcome, platform: 'web' }); + win.dispatchEvent(e); + return e; + }; + const exchange = (opt = {}) => { emit('send', { text: 'hi', silent: Boolean(opt.silent) }); emit('reply', { text: opt.text === undefined ? 'Hello there.' : opt.text, outcome: opt.outcome || '' }); }; + const offers = () => doc.documentElement.all(n => n.className === 'allen-install'); + const button = text => doc.documentElement.all(n => n.tagName === 'button' && n.textContent === text)[0]; + const settle = () => new Promise(r => setTimeout(r, 0)); + return { win, doc, store, panes, bip, exchange, offers, button, settle, boot, emit, answer, current }; +} +const results = []; +async function test(name, fn) { await fn(); results.push(name); } +(async () => { + await test('captured prompt: preventDefault, nothing shown on load', async () => { + const w = world(); + const e = w.bip(); + assert.equal(e.prevented, 1); + assert.equal(e.prompts, 0); + assert.equal(w.offers().length, 0); + assert.equal(w.panes.length, 0); + }); + await test('no offer on load, greeting, silent send or failed reply', async () => { + const w = world(); + w.bip(); + w.exchange({ silent: true }); + w.exchange({ outcome: 'Stopped.' }); + w.exchange({ outcome: 'Could not reach Aien. Check your connection and try again.' }); + w.exchange({ text: ' ' }); + w.emit('reply', { text: 'Hello.', outcome: '' }); + assert.equal(w.offers().length, 0); + }); + await test('natural good exchange shows one pane offer with the required copy', async () => { + const w = world(); + const e = w.bip(); + w.exchange(); + assert.equal(w.panes.length, 1); + assert.equal(w.panes[0].detail.title, TITLE); + assert.equal(w.panes[0].detail.id, 'install'); + assert.equal(w.panes[0].detail.focus, false); + assert.ok(w.button(TITLE)); + assert.ok(w.button('No thanks')); + assert.equal(e.prompts, 0); + w.exchange(); + assert.equal(w.panes.length, 1, 'a second good exchange does not stack offers'); + }); + await test('offer waits for beforeinstallprompt when the exchange came first', async () => { + const w = world(); + w.exchange(); + assert.equal(w.offers().length, 0); + w.bip(); + assert.equal(w.offers().length, 1); + }); + await test('prompt only inside the tap; accepted is not success; appinstalled is', async () => { + const w = world(); + const e = w.bip('accepted'); + w.exchange(); + assert.equal(e.prompts, 0); + w.button(TITLE).click(); + assert.equal(e.prompts, 1); + assert.deepEqual(e.promptInClick, [true]); + await w.settle(); + const state = () => w.doc.documentElement.all(n => n.className === 'allen-install-state')[0].textContent; + assert.match(state(), /^Your browser is adding me/); + assert.doesNotMatch(state(), /installed/); + assert.equal(w.store.get('allen-install'), 'accepted'); + assert.ok(w.button('Close')); + w.win.dispatchEvent({ type: 'appinstalled' }); + assert.match(state(), /Your browser says I am installed/); + assert.equal(w.store.get('allen-install'), 'installed'); + }); + await test('browser dialog dismissed is recorded honestly', async () => { + const w = world(); + const e = w.bip('dismissed'); + w.exchange(); + w.button(TITLE).click(); + assert.deepEqual(e.promptInClick, [true]); + await w.settle(); + assert.equal(w.store.get('allen-install'), 'dismissed'); + assert.ok(w.doc.documentElement.all(n => n.className === 'allen-install-state')[0].textContent.startsWith('No problem.')); + }); + await test('dismiss once: No thanks closes and the next visit stays quiet', async () => { + const store = new Map(); + const w = world({ store }); + w.bip(); + w.exchange(); + w.button('No thanks').click(); + assert.equal(store.get('allen-install'), 'dismissed'); + assert.equal(w.panes[0].closed, 1); + assert.equal(w.offers().length, 0); + const again = world({ store }); + const e = again.bip(); + again.exchange(); + assert.equal(again.offers().length, 0); + assert.equal(e.prevented, 1); + }); + await test('closing the pane with its own close button counts as dismissal', async () => { + const w = world(); + w.bip(); + w.exchange(); + w.panes[0].pane.remove(); + await w.settle(); + assert.equal(w.store.get('allen-install'), 'dismissed'); + }); + await test('without a pane host the offer sits inline near the reply with an accessible close', async () => { + const w = world({ paneHost: false }); + w.bip(); + w.exchange(); + const aside = w.current.all(n => n.className === 'allen-install-inline')[0]; + assert.ok(aside, 'inline aside beside #allen-answer'); + assert.equal(aside.getAttribute('aria-label'), TITLE); + const close = aside.all(n => n.className === 'allen-install-close')[0]; + assert.equal(close.getAttribute('aria-label'), 'Close, and do not offer this again'); + assert.equal(close.children[0].getAttribute('aria-hidden'), 'true'); + close.click(); + assert.equal(aside.isConnected, false); + assert.equal(w.store.get('allen-install'), 'dismissed'); + }); + await test('iOS Safari gets the two-step guide on tap, with labelled local icons', async () => { + for (const ua of ['iphone', 'ipados']) { + const w = world({ ua }); + w.exchange(); + assert.equal(w.offers().length, 1, ua); + w.button(TITLE).click(); + const steps = w.doc.documentElement.all(n => n.className === 'allen-install-step'); + assert.equal(steps.length, 2); + assert.match(steps[0].textContent, /tap Share/); + assert.match(steps[1].textContent, /Add to Home Screen/); + const icons = w.doc.documentElement.all(n => n.tagName === 'svg' && n.getAttribute('role') === 'img'); + assert.equal(icons.length, 2); + assert.ok(icons.every(i => i.ns === 'http://www.w3.org/2000/svg' && i.getAttribute('aria-label'))); + assert.equal(w.doc.documentElement.all(n => n.tagName === 'ol')[0].getAttribute('role'), 'list'); + assert.equal(w.store.get('allen-install'), 'guided'); + assert.doesNotMatch(w.offers()[0].textContent, /installed|added you|is on your home screen/); + } + }); + await test('no offer where no honest install path exists', async () => { + for (const ua of ['crios', 'firefox', 'android']) { + const w = world({ ua }); + w.exchange(); + assert.equal(w.offers().length, 0, ua); + } + }); + await test('installed or standalone pages never offer', async () => { + for (const opts of [{ display: 'standalone' }, { display: 'minimal-ui' }, { ua: 'iphone', iosStandalone: true }, { store: new Map([['allen-install', 'installed']]) }]) { + const w = world(opts); + w.bip(); + w.exchange(); + assert.equal(w.offers().length, 0, JSON.stringify(opts.display || opts.ua || 'stored')); + } + }); + await test('storage unavailable or full never throws and still remembers for the page', async () => { + for (const opts of [{ noStorage: true }, { quota: true }]) { + const w = world(opts); + const e = w.bip(); + w.exchange(); + assert.equal(w.offers().length, 1); + w.button('No thanks').click(); + w.bip(); + w.exchange(); + assert.equal(w.offers().length, 0); + assert.equal(e.prompts, 0); + } + }); + await test('late transport: connects on allen-ready', async () => { + const w = world({ ready: false }); + w.bip(); + w.boot(); + w.exchange(); + assert.equal(w.offers().length, 1); + }); + await test('artifact has no dashes, markup parsing, network or outside resources', async () => { + const css = fs.readFileSync('public/assets/allen-install.css', 'utf8'); + for (const text of [SOURCE, css]) assert.doesNotMatch(text, /[\u2013\u2014]|innerHTML|insertAdjacentHTML|fetch\(|XMLHttpRequest|https?:\/\/(?!www\.w3\.org\/2000\/svg)|@import|url\(/); + }); + for (const name of results) console.log(`PASS ${name}`); + console.log(`${results.length} passed`); +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/om/allen-intro/allen-intro.js.sha256 b/om/allen-intro/allen-intro.js.sha256 new file mode 100644 index 0000000..24f27ce --- /dev/null +++ b/om/allen-intro/allen-intro.js.sha256 @@ -0,0 +1 @@ +b3175a14b434f8226165dc5d7810199d21d5bdc90a2ce2ef69a91bfce3a5d572 allen-intro.js diff --git a/om/allen-intro/check.sh b/om/allen-intro/check.sh new file mode 100755 index 0000000..cc424db --- /dev/null +++ b/om/allen-intro/check.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# Regenerate Allen's consent aside (intro.html) and its script (public/js/allen-intro.js) from intro.om with the pinned arm64 omc +# shared with om/hive-page. CI on x86_64 re-hashes the committed artifacts in Rust tests. +# OMEGA_OMC overrides the compiler path, never its pin. +# OMEGA_ACCEPT_CHANGE=1 accepts a rewritten artifact; otherwise stale output exits 4. +# Exit 2: missing compiler; 3: wrong pin; 4: stale artifact rewritten; +# 5: nondeterministic output; 6: empty output. Compile/run failures propagate. +set -eu +cd "$(dirname "$0")" +omc=${OMEGA_OMC:-$PWD/../hive-page/omc} +pin=$(tr -d ' \n' < ../hive-page/omc.sha256) +if [ ! -f "$omc" ]; then + printf 'No compiler at %s; set OMEGA_OMC to the pinned omc (%s)\n' "$omc" "$pin" >&2 + exit 2 +fi +have=$(sha256sum "$omc" | cut -d' ' -f1) +if [ "$have" != "$pin" ]; then + printf 'Compiler sha256 mismatch: recorded %s, found %s\n' "$pin" "$have" >&2 + exit 3 +fi +work=$(mktemp -d "${TMPDIR:-/tmp}/allen-intro.XXXXXX") +trap 'rm -rf "$work"' EXIT HUP INT TERM +"$omc" < intro.om > "$work/intro" +chmod +x "$work/intro" +"$work/intro" > "$work/first.html" 3> "$work/first.js" +"$work/intro" > "$work/second.html" 3> "$work/second.js" +stale=0 +publish() { + first=$1 + second=$2 + artifact=$3 + sidecar=$4 + if ! cmp -s "$first" "$second"; then + printf '%s: generator output differs between runs\n' "$artifact" >&2 + exit 5 + fi + if [ ! -s "$first" ]; then + printf '%s: generator wrote nothing\n' "$artifact" >&2 + exit 6 + fi + if [ ! -f "$artifact" ] || ! cmp -s "$artifact" "$first"; then + stale=1 + fi + cp "$first" "$artifact" + hash=$(sha256sum "$artifact" | cut -d' ' -f1) + printf '%s %s\n' "$hash" "$(basename "$artifact")" > "$sidecar" + printf '%s %s bytes sha256 %s\n' "$artifact" "$(wc -c < "$artifact" | tr -d ' ')" "$hash" +} +publish "$work/first.html" "$work/second.html" intro.html intro.html.sha256 +publish "$work/first.js" "$work/second.js" ../../public/js/allen-intro.js allen-intro.js.sha256 +printf 'omc sha256 %s\n' "$have" +if [ "$stale" = 1 ]; then + printf 'Generated artifacts were rewritten; commit them with intro.om\n' >&2 + if [ "${OMEGA_ACCEPT_CHANGE:-0}" != 1 ]; then + exit 4 + fi +fi diff --git a/om/allen-intro/intro.html b/om/allen-intro/intro.html new file mode 100644 index 0000000..39bf7da --- /dev/null +++ b/om/allen-intro/intro.html @@ -0,0 +1 @@ +<aside id="aien-allen-intro" role="complementary" aria-label="Aien says hello" aria-live="polite" hidden><div class="allen-intro-bubble"><p class="allen-intro-name">Aien</p><button id="allen-intro-close" class="allen-intro-close" type="button" aria-label="Close, no thanks">×</button><p id="allen-intro-message" class="allen-intro-message" aria-hidden="true" data-speaker="allen"><span class="allen-intro-ghost"><strong id="allen-intro-title">Hi, I'm Aien (you say it like Ian). It's nice to meet you!</strong> <span id="allen-intro-intro">You don't have to tell me your name, but if you do, that would be super awesome and we could chat over time. When you come back, I can remember who you are and we can pick up where we left off. We can talk about all kinds of good things in the universe.</span></span><span id="allen-intro-typed" data-letters="true"><strong></strong><span></span></span></p><p id="allen-intro-spoken" class="allen-intro-sr"></p><div id="allen-intro-chat" class="allen-intro-chips"><a href="/aien/?mode=remember">Tell Aien my name</a><a href="/aien/?mode=anonymous">Chat anonymously</a></div><div id="allen-intro-x"><p id="allen-intro-offer" class="allen-intro-note" data-speaker="allen">Separately, if you'd like, say hi and I'll let Drake know you stopped by. That uses Drake's X pixel to note the visit. Totally fine if not.</p><div id="allen-intro-chips" class="allen-intro-chips"><button id="allen-intro-yes" type="button">Say hi</button><button id="allen-intro-no" type="button">No thanks</button></div></div><p id="allen-intro-gpc" class="allen-intro-note" data-speaker="allen" hidden>Your browser sends Global Privacy Control, so I'm not offering Drake's X pixel. It stays off.</p><div id="allen-intro-after" hidden><p id="allen-intro-after-text" data-speaker="allen">No problem. You can still chat with me anonymously; I won't remember you or tell X anything.</p><p class="allen-intro-links"><a id="allen-intro-anon" href="/aien/?mode=anonymous">Chat anonymously</a></p></div><details id="allen-intro-who" class="allen-intro-who"><summary>Who can see me right now?</summary><div class="allen-intro-who-body"><h3>Trackers on this page right now: <span id="allen-intro-tracker-count">checking</span></h3><ul id="allen-intro-trackers"></ul><p id="allen-intro-trackers-none" hidden>None. Only this site's own files have loaded in this tab.</p><h3>What your browser tells every website automatically</h3><dl id="allen-intro-facts"></dl><p>Every site you visit can see this. I don't keep it. Your IP address is visible to Drake's web host, like every site's.</p><h3>What this page can't see</h3><p>Trackers on other sites, in other tabs or inside embedded frames, tracking by your internet provider or network, and your browser extensions. Tools that check more:</p><ul><li><a href="https://coveryourtracks.eff.org/" rel="noopener noreferrer">EFF Cover Your Tracks</a></li><li><a href="https://themarkup.org/blacklight" rel="noopener noreferrer">The Markup's Blacklight</a></li></ul></div></details><p class="allen-intro-links"><a href="/privacy/">Privacy</a></p></div></aside> \ No newline at end of file diff --git a/om/allen-intro/intro.html.sha256 b/om/allen-intro/intro.html.sha256 new file mode 100644 index 0000000..ada2504 --- /dev/null +++ b/om/allen-intro/intro.html.sha256 @@ -0,0 +1 @@ +95dd158c20e0ce5bafde6298684c48d9369c444f589b28cd591a025ab14535f0 intro.html diff --git a/om/allen-intro/intro.om b/om/allen-intro/intro.om new file mode 100644 index 0000000..c4f8607 --- /dev/null +++ b/om/allen-intro/intro.om @@ -0,0 +1,116 @@ +note Aien's (Allen internally) first-visit greeting on aienos.com: the consent aside that every page carries. +note Every structural decision lives here: the section order, the ids and aria attributes the +note consent script (public/js/allen-intro.js) and its tests depend on, Drake's greeting words, the +note memory links kept apart from the X pixel buttons, the GPC note, the reply after No thanks, and +note the local-only "Who can see me right now?" panel. The script only toggles and fills these slots. +note +note Program mode. check.sh compiles this with the pinned omc shared with om/hive-page, runs it twice, +note and commits intro.html with its sha256. The Rust site builder embeds intro.html and re-hashes it +note in a unit test, so x86 CI checks the artifact without running the arm64 compiler. +note +note Aien's speech carries data-speaker="allen": his "we" means Aien and the visitor, and the +note site's singular-voice verifier exempts exactly those elements. Memory consent is links to +note /aien/?mode=remember and ?mode=anonymous; X consent is the Say hi and No thanks buttons. One tap +note never means both. Names: at most 8 bytes per data name. + +note ihead: Host aside, name and close. The shared native scene is the visible Aien. +text ihead "<aside id=\"aien-allen-intro\" role=\"complementary\" aria-label=\"Aien says hello\" aria-live=\"polite\" hidden><div class=\"allen-intro-bubble\"><p class=\"allen-intro-name\">Aien</p><button id=\"allen-intro-close\" class=\"allen-intro-close\" type=\"button\" aria-label=\"Close, no thanks\">×</button>" + +note igreet: Drake's greeting as Allen says it. The ghost reserves the size; JS types into allen-intro-typed. +text igreet "<p id=\"allen-intro-message\" class=\"allen-intro-message\" aria-hidden=\"true\" data-speaker=\"allen\"><span class=\"allen-intro-ghost\"><strong id=\"allen-intro-title\">Hi, I'm Aien (you say it like Ian). It's nice to meet you!</strong> <span id=\"allen-intro-intro\">You don't have to tell me your name, but if you do, that would be super awesome and we could chat over time. When you come back, I can remember who you are and we can pick up where we left off. We can talk about all kinds of good things in the universe.</span></span><span id=\"allen-intro-typed\" data-letters=\"true\"><strong></strong><span></span></span></p><p id=\"allen-intro-spoken\" class=\"allen-intro-sr\"></p>" + +note ichat: Memory consent: plain links to /allen/, never the X pixel. +text ichat "<div id=\"allen-intro-chat\" class=\"allen-intro-chips\"><a href=\"/aien/?mode=remember\">Tell Aien my name</a><a href=\"/aien/?mode=anonymous\">Chat anonymously</a></div>" + +note ixask: The X pixel ask, its own line and its own buttons. +text ixask "<div id=\"allen-intro-x\"><p id=\"allen-intro-offer\" class=\"allen-intro-note\" data-speaker=\"allen\">Separately, if you'd like, say hi and I'll let Drake know you stopped by. That uses Drake's X pixel to note the visit. Totally fine if not.</p><div id=\"allen-intro-chips\" class=\"allen-intro-chips\"><button id=\"allen-intro-yes\" type=\"button\">Say hi</button><button id=\"allen-intro-no\" type=\"button\">No thanks</button></div></div>" + +note igpc: Shown instead of the X ask when the browser sends Global Privacy Control. +text igpc "<p id=\"allen-intro-gpc\" class=\"allen-intro-note\" data-speaker=\"allen\" hidden>Your browser sends Global Privacy Control, so I'm not offering Drake's X pixel. It stays off.</p>" + +note iafter: After No thanks: no pixel, no memory, an anonymous chat. +text iafter "<div id=\"allen-intro-after\" hidden><p id=\"allen-intro-after-text\" data-speaker=\"allen\">No problem. You can still chat with me anonymously; I won't remember you or tell X anything.</p><p class=\"allen-intro-links\"><a id=\"allen-intro-anon\" href=\"/aien/?mode=anonymous\">Chat anonymously</a></p></div>" + +note iwho: Local-only panel; filled from resource timing and navigator fields, never sent. +text iwho "<details id=\"allen-intro-who\" class=\"allen-intro-who\"><summary>Who can see me right now?</summary><div class=\"allen-intro-who-body\"><h3>Trackers on this page right now: <span id=\"allen-intro-tracker-count\">checking</span></h3><ul id=\"allen-intro-trackers\"></ul><p id=\"allen-intro-trackers-none\" hidden>None. Only this site's own files have loaded in this tab.</p><h3>What your browser tells every website automatically</h3><dl id=\"allen-intro-facts\"></dl><p>Every site you visit can see this. I don't keep it. Your IP address is visible to Drake's web host, like every site's.</p><h3>What this page can't see</h3><p>Trackers on other sites, in other tabs or inside embedded frames, tracking by your internet provider or network, and your browser extensions. Tools that check more:</p><ul><li><a href=\"https://coveryourtracks.eff.org/\" rel=\"noopener noreferrer\">EFF Cover Your Tracks</a></li><li><a href=\"https://themarkup.org/blacklight\" rel=\"noopener noreferrer\">The Markup's Blacklight</a></li></ul></div></details>" + +note ifoot: Privacy link and the closing tags. +text ifoot "<p class=\"allen-intro-links\"><a href=\"/privacy/\">Privacy</a></p></div></aside>" + +note The consent script, public/js/allen-intro.js, written to fd 3 by the same program, so the +note markup above and the script that drives it share one Omega source. It holds the once-only +note rule, X consent and refusal, the GPC default, the anonymous /allen/ gate, the local-only panel +note and the window.aienAllenIntro interface the visual layer calls. + + +text ijs0 "/* Generated by om/allen-intro/intro.om. Edit the Omega source, then run om/allen-intro/check.sh. */\n/* Aien (Allen internally) says hello once. Say hi consents to X pixel rfrlz. No external load before yes. */\n(function () {\n 'use strict';\n // Drake supplies the real X event IDs. Empty means disabled, never a fake event.\n const eventIds = Object.freeze({ pageVisit: '', introducedToAllen: '' });\n var conversionIds = {};\n var key = 'aien-allen-intro-consent';\n var seenKey = 'aien-allen-intro-seen';\n var clickKey = 'aien-allen-intro-twclid';\n var landingClick = new URLSearchParams(window.location.search).get('twclid');\n var aside = document.getElementById('aien-allen-intro');\n if (!aside || aside.dataset.ready) return;\n aside.dataset.ready = 'true';\n var choice = null;\n var loaded = false;\n var previousFocus = null;\n var timer = null;\n var offering = true;\n var status = document.getElementById('allen-intro-status');\n var title = document.getElementById('allen-intro-title');\n var typed = document.getElementById('allen-intro-typed');\n var spoken = document.getElementById('allen-intro-spoken');\n var offerLine = document.getElementById('allen-intro-offer');\n var gpcLine = document.getElementById('allen-intro-gpc');\n var yes = document.getElementById('allen-intro-yes');\n var no = document.getElementById('allen-intro-no');\n var greeting = title.textContent;\n var message = '';\n // Global Privacy Control: Allen does not offer the pixel unless the visitor asks to review.\n var gpc = window.navigator.globalPrivacyControl === true;\n var still = !window.matchMedia || window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n try { choice = localStorage.getItem(key); } catch (_) { /* No stored consent. */ }\n // Session refusal also wins if local storage became read-only after a Yes.\n try { if (sessionStorage.getItem(key) === 'no') choice = 'no'; } catch (_) {}\n if (window.location.hash === '#allen-intro-no') choice = 'no';\n\n" +text ijs1 " // Once per browser; without local storage, once per tab session.\n function seen() {\n var mark = null;\n try { mark = localStorage.getItem(seenKey); } catch (_) {}\n if (!mark) try { mark = sessionStorage.getItem(seenKey); } catch (_) {}\n return !!mark;\n }\n function markSeen() {\n try { localStorage.setItem(seenKey, '1'); return; } catch (_) {}\n try { sessionStorage.setItem(seenKey, '1'); } catch (_) {}\n }\n\n // The chat page (/aien/, formerly /allen/) renders #allen with data-mode=\"anonymous\" until its own memory consent.\n function anonymousChat() {\n var chat = document.getElementById('allen');\n return !!chat && chat.dataset.mode !== 'remembered';\n }\n\n // Allen's presence layer renders on these events and acts only through the API below.\n function announce(type, detail) {\n var data = detail || {};\n data.type = type;\n document.dispatchEvent(new window.CustomEvent('aien-allen-intro', { detail: data }));\n }\n\n function sendEvent(kind) {\n var id = eventIds[kind];\n if (choice !== 'yes' || !loaded || !id || conversionIds[kind]) return;\n // Keep this exact ID when a future backend sends the matching server event.\n var conversionId = window.crypto.randomUUID();\n conversionIds[kind] = conversionId;\n twq('event', id, { conversion_id: conversionId });\n }\n\n" +text ijs2 " function loadPixel() {\n // Anonymous chat on /aien/ (#allen data-mode != remembered) never loads the pixel.\n if (choice !== 'yes' || loaded || anonymousChat()) return;\n // Retain attribution only in a consenting visitor's browser, not on a server.\n if (landingClick) {\n try { localStorage.setItem(clickKey, landingClick); } catch (_) {}\n }\n loaded = true;\n // Official X base code, unchanged, executed only after explicit consent.\n !function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments);\n },s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='https://static.ads-twitter.com/uwt.js',\n a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');\n twq('config','rfrlz');\n sendEvent('pageVisit');\n }\n\n function describe(saved) {\n if (status) status.textContent = (choice === 'yes'\n ? 'You said hi to Aien. X tracking is allowed in this browser.'\n : 'You have not said hi to Aien. X tracking is off.')\n + (saved === false ? ' Your browser could not save this choice; it applies to this page only.' : '');\n }\n\n // Static text typed on the client: no model call. Allen's native cadence is one letter per\n // 35 ms. With data-letters=\"true\" on #allen-intro-typed each letter is its own\n // span.allen-intro-letter, so the presence CSS can fade, raise and recolour it as it arrives.\n // Reduced motion shows the whole text at once as plain text.\n var letterMs = 35;\n function type() {\n var head = typed.firstChild;\n var tail = typed.lastChild;\n var whole = greeting + ' ' + message;\n var letters = !still && typed.dataset.letters === 'true';\n var shown = still ? whole.length : 0;\n head.textContent = '';\n tail.textContent = '';\n function paint() {\n if (letters) {\n if (shown > 0) {\n var letter = document.createElement('span');\n letter.className = 'allen-intro-letter';\n letter.textContent = whole.charAt(shown - 1);\n (shown <= greeting.length ? head : tail).appendChild(letter);\n }\n } else {\n head.textContent = whole.slice(0, Math.min(shown, greeting.length));\n tail.textContent = whole.slice(greeting.length, shown);\n }\n if (shown >= whole.length) { timer = null; return; }\n shown += 1;\n timer = setTimeout(paint, letterMs);\n }\n paint();\n }\n\n" +text ijs3 " function close() {\n clearTimeout(timer);\n timer = null;\n var wasShown = !aside.hidden;\n var inside = aside.contains(document.activeElement);\n aside.classList.remove('allen-intro-in');\n aside.hidden = true;\n spoken.textContent = '';\n if (inside && previousFocus && previousFocus.isConnected) previousFocus.focus();\n previousFocus = null;\n if (wasShown) announce('hide');\n }\n\n // The greeting, the chat choices and the separate X pixel ask; No thanks swaps them out.\n var greetingParts = ['allen-intro-message', 'allen-intro-chat', 'allen-intro-x'];\n function showGreeting(on) {\n greetingParts.forEach(function (id) { document.getElementById(id).hidden = !on; });\n document.getElementById('allen-intro-after').hidden = on;\n }\n\n // No thanks: no pixel and no memory, but Allen stays to offer an anonymous chat.\n function replyNo() {\n clearTimeout(timer);\n timer = null;\n showGreeting(false);\n gpcLine.hidden = true;\n spoken.textContent = document.getElementById('allen-intro-after-text').textContent;\n document.getElementById('allen-intro-anon').focus();\n announce('reply-no');\n }\n\n function choose(value, reply) {\n choice = value;\n var saved = true;\n try { localStorage.setItem(key, value); } catch (_) { saved = false; }\n if (value === 'no') {\n try { localStorage.removeItem(clickKey); } catch (_) {}\n }\n try {\n if (value === 'no') sessionStorage.setItem(key, 'no');\n else sessionStorage.removeItem(key);\n } catch (_) {}\n if (value === 'yes' && window.location.hash === '#allen-intro-no') {\n history.replaceState(null, '', window.location.pathname + window.location.search);\n }\n if (reply && offering && value === 'no' && !loaded) replyNo();\n else close();\n describe(saved);\n if (value === 'yes') {\n loadPixel();\n sendEvent('introducedToAllen');\n announce('consent', { pixelLoaded: loaded });\n }\n // A loaded third-party script cannot be recalled. A fresh document stops it.\n else if (loaded) {\n // Preserve refusal through reload even if all browser storage is unavailable.\n if (!saved) window.location.hash = 'allen-intro-no';\n window.location.reload();\n }\n }\n\n" +text ijs4 " // Never a modal: no backdrop, no inert page. Focus moves only when the visitor asked.\n function open(asked) {\n if (!aside.hidden) return;\n // Under GPC the pixel is not offered unless the visitor asked to review it.\n offering = asked || !gpc;\n showGreeting(true);\n document.getElementById('allen-intro-x').hidden = !offering;\n gpcLine.hidden = offering;\n message = document.getElementById('allen-intro-intro').textContent;\n previousFocus = asked ? document.activeElement : null;\n aside.hidden = false;\n spoken.textContent = greeting + ' ' + message + ' ' + (offering ? offerLine : gpcLine).textContent;\n type();\n void aside.offsetWidth;\n aside.classList.add('allen-intro-in');\n if (asked) no.focus();\n announce('show', { asked: !!asked, offering: offering });\n }\n\n // \"Who can see me right now?\": read only from this document and browser, shown\n // only here, never sent or stored. Resource timing lists every origin this tab loaded.\n var who = document.getElementById('allen-intro-who');\n var trackers = document.getElementById('allen-intro-trackers');\n var thirdParty = [];\n var facts = [];\n var trackerListeners = [];\n var watching = false;\n function countTrackers() {\n document.getElementById('allen-intro-tracker-count').textContent = String(thirdParty.length);\n document.getElementById('allen-intro-trackers-none').hidden = thirdParty.length > 0;\n }\n function noteResource(entry) {\n var url;\n try { url = new URL(entry.name, window.location.href); } catch (_) { return; }\n if (!/^https?:$/.test(url.protocol) || url.origin === window.location.origin) return;\n if (thirdParty.some(function (seenOrigin) { return seenOrigin.origin === url.origin; })) return;\n // Only an X origin loaded after Say hi in this document is called Drake's pixel.\n var tracker = { origin: url.origin, pixel: choice === 'yes' && loaded && /(^|\\.)(ads-twitter\\.com|twitter\\.com|x\\.com|t\\.co)$/.test(url.hostname) };\n thirdParty.push(tracker);\n var item = document.createElement('li');\n item.textContent = url.host + (tracker.pixel ? \": that one's Drake's X pixel, because you said hi.\" : '');\n trackers.appendChild(item);\n countTrackers();\n trackerListeners.forEach(function (listener) { listener(Object.assign({}, tracker)); });\n }\n function browserFacts() {\n var nav = window.navigator;\n var screen = window.screen;\n facts = [\n ['Browser', nav.userAgent || 'not shared'],\n ['Platform', (nav.userAgentData && nav.userAgentData.platform) || nav.platform || 'not shared'],\n ['Language', (nav.languages && nav.languages.length ? nav.languages.join(', ') : nav.language) || 'not shared'],\n ['Timezone', Intl.DateTimeFormat().resolvedOptions().timeZone || 'not shared'],\n ['Screen size', screen ? screen.width + ' x ' + screen.height : 'not shared'],\n ['Came from', document.referrer || 'no referrer sent'],\n ['Do Not Track', nav.doNotTrack === '1' ? 'on' : 'off'],\n ['Global Privacy Control', gpc ? 'on' : 'off'],\n ['Cookies enabled', nav.cookieEnabled ? 'yes' : 'no'],\n ];\n var list = document.getElementById('allen-intro-facts');\n facts.forEach(function (row) {\n var term = document.createElement('dt');\n var value = document.createElement('dd');\n term.textContent = row[0];\n value.textContent = row[1];\n list.appendChild(term);\n list.appendChild(value);\n });\n }\n function watch() {\n if (watching) return;\n watching = true;\n browserFacts();\n countTrackers();\n window.performance.getEntriesByType('resource').forEach(noteResource);\n // Later loads too, such as the X pixel after Say hi.\n new window.PerformanceObserver(function (list) { list.getEntries().forEach(noteResource); })\n .observe({ type: 'resource', buffered: true });\n }\n who.addEventListener('toggle', function () { if (who.open) watch(); });\n\n" +text ijs5 " no.addEventListener('click', function () { choose('no', true); });\n document.getElementById('allen-intro-close').addEventListener('click', function () { choose('no'); });\n yes.addEventListener('click', function () { choose('yes'); });\n document.addEventListener('keydown', function (event) {\n if (event.key === 'Escape' && !aside.hidden) choose('no');\n });\n document.querySelectorAll('[data-allen-intro-open]').forEach(function (button) {\n button.hidden = false;\n button.addEventListener('click', function () { open(true); });\n });\n document.querySelectorAll('[data-allen-intro-stop]').forEach(function (button) {\n button.hidden = false;\n button.addEventListener('click', function () { choose('no'); });\n });\n // A No in another tab also stops this document if the pixel was already loaded.\n window.addEventListener('storage', function (event) {\n if (event.storageArea !== localStorage || (event.key !== key && event.key !== null)) return;\n choice = event.newValue;\n if (choice !== 'yes') {\n try { localStorage.removeItem(clickKey); } catch (_) {}\n }\n close();\n describe();\n if (choice !== 'yes' && loaded) window.location.reload();\n });\n // The first-visit greeting, once per browser. Recorded on first display: never\n // auto-open again, chosen or not. Unanswered means No. Not on /privacy/ or the chat page.\n function greet() {\n if (choice === 'yes' || choice === 'no' || seen() || document.getElementById('allen-intro-privacy') || document.getElementById('allen')) return false;\n markSeen();\n open(false);\n return true;\n }\n\n" +text ijs6 " // The interface Allen's presence layer calls. X consent and refusal only: memory\n // consent lives on /aien/ behind its own step, never here, so one tap never means both.\n window.aienAllenIntro = Object.freeze({\n text: Object.freeze({\n greeting: greeting,\n intro: document.getElementById('allen-intro-intro').textContent,\n offer: offerLine.textContent,\n gpcNote: gpcLine.textContent,\n afterNo: document.getElementById('allen-intro-after-text').textContent,\n }),\n status: function () {\n return { choice: choice === 'yes' || choice === 'no' ? choice : null, gpc: gpc, offering: offering, pixelLoaded: loaded, shown: !aside.hidden };\n },\n sayHi: function () { choose('yes'); },\n noThanks: function () { choose('no', true); },\n dismiss: function () { choose('no'); },\n review: function () { open(true); },\n // A page that marks [data-allen-intro-defer] (the home door) calls this after its own welcome.\n greet: greet,\n who: function () {\n watch();\n return { trackers: thirdParty.map(function (t) { return Object.assign({}, t); }), facts: facts.map(function (row) { return row.slice(); }) };\n },\n onTrackers: function (listener) { trackerListeners.push(listener); watch(); },\n });\n describe();\n if (choice === 'yes') loadPixel();\n else if (!document.querySelector('[data-allen-intro-defer]')) greet();\n}());\n" + +fn main to int +n = write 1 ihead 0 len ihead +if lt n 0 +trap 3 +end +n = write 1 igreet 0 len igreet +if lt n 0 +trap 3 +end +n = write 1 ichat 0 len ichat +if lt n 0 +trap 3 +end +n = write 1 ixask 0 len ixask +if lt n 0 +trap 3 +end +n = write 1 igpc 0 len igpc +if lt n 0 +trap 3 +end +n = write 1 iafter 0 len iafter +if lt n 0 +trap 3 +end +n = write 1 iwho 0 len iwho +if lt n 0 +trap 3 +end +n = write 1 ifoot 0 len ifoot +if lt n 0 +trap 3 +end +n = write 3 ijs0 0 len ijs0 +if lt n 0 +trap 3 +end +n = write 3 ijs1 0 len ijs1 +if lt n 0 +trap 3 +end +n = write 3 ijs2 0 len ijs2 +if lt n 0 +trap 3 +end +n = write 3 ijs3 0 len ijs3 +if lt n 0 +trap 3 +end +n = write 3 ijs4 0 len ijs4 +if lt n 0 +trap 3 +end +n = write 3 ijs5 0 len ijs5 +if lt n 0 +trap 3 +end +n = write 3 ijs6 0 len ijs6 +if lt n 0 +trap 3 +end +ret 0 +end diff --git a/om/allen-page/allen.om b/om/allen-page/allen.om index 648ead4..7273947 100644 --- a/om/allen-page/allen.om +++ b/om/allen-page/allen.om @@ -10,16 +10,16 @@ note speeds holds label and id fields alternately, separated by byte 124: each p note dt and dd row in table order. prompts holds the example prompts, one button each, in order. note No field may contain byte 124 or a newline. -text pg1 "<div class=\"allen\" id=\"~0~\" data-ready=\"false\" data-busy=\"false\" data-mode=\"anonymous\">\n<header class=\"allen-head\">\n<p class=\"allen-eyebrow\">Aien, live from the Spark</p>\n<h1 class=\"allen-title\">Talk to Aien</h1>\n<p class=\"allen-lede\" id=\"~26~\">Aien is Drake's AI. Ask it anything, ask what Omega is (Aien's own language for all computing, GPU to CPU), or ask for a small program. An HTML mini app runs right here in a sandboxed frame; an Omega function is compiled to WebAssembly on the Spark and runs in your browser.</p>\n<p class=\"allen-where\">Model <code id=\"~8~\">~24~</code>, running on a DGX Spark in Drake's house. The speeds below are measured by this page from the live stream.</p>\n</header>\n<section class=\"allen-panel\" aria-label=\"Conversation with Aien\">\n<p class=\"allen-mode\"><span id=\"~50~\">Anonymous: Aien won't remember this chat</span> <button type=\"button\" class=\"allen-tool\" id=\"~35~\">Remember me</button> <button type=\"button\" class=\"allen-tool\" id=\"~58~\" aria-pressed=\"false\">Voice: off</button> <button type=\"button\" class=\"allen-tool\" id=\"~59~\" hidden>Next clip</button></p>\n<div class=\"allen-volunteer\" id=\"~55~\">\n<label class=\"allen-agree\"><input type=\"checkbox\" id=\"~54~\"> <span>Let a volunteer's Spark answer me when Drake's is busy.</span></label>\n<p class=\"allen-note\">If you tick this and my Spark is full, your messages in this chat go to a computer owned by a volunteer, outside my house. It gets only the text of this anonymous conversation. I add no visitor key, stored memories, contact record or IP address, but anything you type here is sent as you typed it. I check a sample of volunteer replies, not every one. A volunteer could still send a wrong or bad reply that I don't catch. Each reply says which machine answered.</p>\n</div>\n<dl class=\"allen-speed\" aria-label=\"Speed of the latest reply\">\n" +text pg1 "<div class=\"allen\" id=\"~0~\" data-ready=\"false\" data-busy=\"false\" data-mode=\"anonymous\">\n<canvas id=\"allen-universe\" class=\"allen-universe\" tabindex=\"0\" aria-label=\"Explore the universe with Aien. Drag to drift, scroll to zoom, or use arrow keys, plus, minus and Home.\"></canvas>\n<div class=\"allen-space-tools\" role=\"group\" aria-label=\"Aien controls\"><button type=\"button\" class=\"allen-tool\" id=\"allen-mute\" aria-pressed=\"false\">Sound on</button><button type=\"button\" class=\"allen-tool\" id=\"allen-projects\">Projects</button><button type=\"button\" class=\"allen-tool\" id=\"allen-history\" aria-expanded=\"false\" aria-controls=\"allen-session\">Session</button></div>\n<div class=\"allen-arrival\" id=\"allen-arrival\"><h1>Explore the universe with Aien</h1><button type=\"button\" class=\"allen-enter\" id=\"allen-enter\">Enter Aien's universe</button></div>\n<div id=\"allen-panes\" class=\"allen-panes\" aria-label=\"Your workspace\"></div>\n<section class=\"allen-current\" aria-label=\"Latest exchange\"><p id=\"allen-guest\" class=\"allen-guest\"></p><p id=\"allen-speaker\" class=\"allen-speaker\">Aien</p><div id=\"allen-answer\" class=\"allen-answer\" data-speaker=\"allen\" aria-live=\"polite\" aria-atomic=\"false\"></div><div class=\"allen-reply-actions\"><button type=\"button\" class=\"allen-tool\" id=\"allen-copy\">Copy reply</button><button type=\"button\" class=\"allen-tool\" id=\"allen-regenerate\">Regenerate</button></div></section>\n<section class=\"allen-panel\" aria-label=\"Conversation with Aien\">\n<p class=\"allen-mode\"><span id=\"~50~\">Anonymous: Aien won't remember this chat</span> <button type=\"button\" class=\"allen-tool\" id=\"~35~\">Remember me</button> <button type=\"button\" class=\"allen-tool\" id=\"~58~\" aria-pressed=\"false\">Voice: off</button> <button type=\"button\" class=\"allen-tool\" id=\"~59~\" hidden>Next clip</button></p>\n<section id=\"allen-session\" class=\"allen-session\" aria-label=\"Session history and privacy\" hidden><header class=\"allen-head\"><h2 class=\"allen-title\">This session</h2><p class=\"allen-lede\" id=\"~26~\">Ask about the universe, explore an idea, or make something with Aien.</p><p class=\"allen-where\">Model <code id=\"~8~\">~24~</code>. Timing below is measured from this reply.</p></header>\n<dl class=\"allen-speed\" aria-label=\"Speed of the latest reply\">\n" text speeds "Wait in line|~9~|First token, model|~10~|First token, from Send|~11~|Tokens per second|~12~|Tokens streamed|~13~|Server count|~14~" text rowa "<div class=\"allen-stat\"><dt>" text rowb "</dt><dd id=\"" text rowc "\">-</dd></div>\n" -text pg2 "</dl>\n<div class=\"allen-scroll\"><ol class=\"allen-log\" id=\"~1~\" role=\"log\" aria-live=\"polite\" aria-label=\"Messages\"></ol></div>\n<noscript><p class=\"allen-status\">This chat needs JavaScript: replies stream into the page as the model writes them.</p></noscript>\n<div class=\"allen-examples\" id=\"~15~\" role=\"group\" aria-label=\"Example questions\">\n" +text pg2 "</dl>\n<div class=\"allen-volunteer\" id=\"~55~\">\n<label class=\"allen-agree\"><input type=\"checkbox\" id=\"~54~\"> <span>Let a volunteer's Spark answer me when Drake's is busy.</span></label>\n<p class=\"allen-note\">If you tick this and my Spark is full, your messages in this chat go to a computer owned by a volunteer, outside my house. It gets only the text of this anonymous conversation. I add no visitor key, stored memories, contact record or IP address, but anything you type here is sent as you typed it. I check a sample of volunteer replies, not every one. A volunteer could still send a wrong or bad reply that I don't catch. Each reply says which machine answered.</p>\n</div>\n<div class=\"allen-scroll\"><ol class=\"allen-log\" id=\"~1~\" role=\"log\" aria-live=\"polite\" aria-label=\"Messages\"></ol></div>\n<noscript><p class=\"allen-status\">Aien needs JavaScript to draw the scene and stream replies. Nothing is sent without it.</p></noscript>\n<div class=\"allen-examples\" id=\"~15~\" role=\"group\" aria-label=\"Example questions\">\n" text prompts "What is Omega?|Make me a calculator|Write an Omega gcd function|How fast are you?" text btna "<button type=\"button\" class=\"allen-example\">" text btnb "</button>\n" -text pg3 "</div>\n<p class=\"allen-drake\" id=\"~47~\" aria-live=\"polite\" hidden></p>\n<p class=\"allen-status\" id=\"~6~\" role=\"status\" aria-live=\"polite\"></p>\n<form class=\"allen-form\" id=\"~2~\">\n<label class=\"allen-sr\" for=\"~3~\">Message to Aien</label>\n<textarea id=\"~3~\" rows=\"3\" maxlength=\"~19~\" placeholder=\"Ask Aien something. Enter sends; Shift+Enter starts a new line.\" autocomplete=\"off\"></textarea>\n<div class=\"allen-actions\">\n<button type=\"submit\" class=\"allen-send\" id=\"~4~\">Send</button>\n<button type=\"button\" class=\"allen-stop\" id=\"~5~\" disabled>Stop</button>\n<button type=\"button\" class=\"allen-new\" id=\"~7~\">New conversation</button>\n</div>\n</form>\n<p class=\"allen-contact\">To reach me, Drake, directly: <a href=\"~48~\" rel=\"noopener\">follow me on X</a> or email me at <a href=\"mailto:~49~\">~49~</a>.</p>\n<p class=\"allen-privacy\" id=\"~27~\">Private by design: conversations are not stored, and the gateway keeps only aggregate counters. No prompts or IP addresses are logged. Programs run sandboxed in your browser. Reload the page and the conversation is gone. An introduction, and short notes Aien keeps about you, exist only if you consent; <a href=\"/privacy/\">read what I keep</a>.</p>\n<p class=\"allen-meet\">Agents can introduce themselves with <code>POST https://www.aienos.com/allen/api/introduce</code> (schema in <a href=\"/llms.txt\">/llms.txt</a>); nothing is stored without <code>\"consent\": true</code>.</p>\n<details class=\"allen-keypanel\" id=\"~39~\" data-key=\"no\">\n<summary>Your Aien key</summary>\n<div class=\"allen-keybody\" id=\"~40~\"><p class=\"allen-note\">Your Aien key needs JavaScript.</p></div>\n</details>\n</section>\n<footer class=\"allen-foot\">\n<p>New to Omega? <a href=\"/omega/\">Read what Omega is</a>. This page is generated by <a href=\"https://github.com/aien-dev/aienos.com/blob/main/om/allen-page/allen.om\" rel=\"noopener\">om/allen-page/allen.om</a> and its script by <a href=\"https://github.com/aien-dev/aienos.com/blob/main/om/allen-page/allen-js.om\" rel=\"noopener\">allen-js.om</a>, both seeded Omega.</p>\n</footer>\n</div>\n" +text pg3 "</div>\n<p class=\"allen-contact\">To reach me, Drake, directly: <a href=\"~48~\" rel=\"noopener\">follow me on X</a> or email <a href=\"mailto:~49~\">~49~</a>. <a href=\"/contact/\">More ways to reach me</a>.</p>\n<p class=\"allen-privacy\" id=\"~27~\">This session stays in this tab. Reloading clears the conversation. Projects are saved on this device only when you choose Save. Remembering you is a separate choice; <a href=\"/privacy/\">read what I keep</a>.</p>\n<details class=\"allen-keypanel\" id=\"~39~\" data-key=\"no\"><summary>Your Aien key</summary><div class=\"allen-keybody\" id=\"~40~\"><p class=\"allen-note\">Your Aien key needs JavaScript.</p></div></details>\n<button type=\"button\" class=\"allen-tool allen-new\" id=\"~7~\">New conversation</button>\n<button type=\"button\" class=\"allen-tool\" id=\"allen-speak\" aria-pressed=\"false\">Read replies aloud</button>\n<p class=\"allen-foot\"><a href=\"/\">Aien's front door</a> · <a href=\"/classic/\">Classic site</a></p>\n<p class=\"allen-foot\">The browser controller is <a href=\"/allen/scene.om\">written in Omega</a>. The scene uses the <a href=\"https://github.com/aien-dev/aienux/tree/da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c/native/kernel/ui\" rel=\"noopener\">same native iMac renderer</a>, compiled to WebAssembly.</p>\n<p class=\"allen-foot\"><a href=\"/alpha/\">Own a DGX Spark? Run Sovereign Intelligence on yours</a>.</p></section>\n<div class=\"allen-bottom\"><p class=\"allen-drake\" id=\"~47~\" aria-live=\"polite\" hidden></p><p class=\"allen-status\" id=\"~6~\" role=\"status\" aria-live=\"polite\"></p>\n<form class=\"allen-form\" id=\"~2~\"><label class=\"allen-sr\" for=\"~3~\">Message to Aien</label><textarea id=\"~3~\" rows=\"1\" maxlength=\"~19~\" placeholder=\"Speak to Aien\" autocomplete=\"off\"></textarea><div class=\"allen-actions\"><button type=\"button\" class=\"allen-mic\" id=\"allen-mic\" aria-pressed=\"false\" aria-describedby=\"allen-voice-privacy\" aria-label=\"Use microphone\">Mic</button><button type=\"submit\" class=\"allen-send\" id=\"~4~\" aria-label=\"Send message\">Send</button><button type=\"button\" class=\"allen-stop\" id=\"~5~\" disabled>Stop</button></div></form><p class=\"allen-input-hint\">Enter to send. Shift+Enter for a new line.</p><p class=\"allen-input-hint\" id=\"allen-voice-privacy\">Microphone off. Voice availability is checked locally.</p><p class=\"allen-voice-status\" id=\"allen-voice-status\" role=\"status\" aria-live=\"polite\"></p></div>\n</section>\n</div>\n" fn emit1 to void for b ulong len pg1 diff --git a/om/allen-page/main.html b/om/allen-page/main.html index 20b3cc9..c5fe671 100644 --- a/om/allen-page/main.html +++ b/om/allen-page/main.html @@ -1,16 +1,12 @@ <div class="allen" id="allen" data-ready="false" data-busy="false" data-mode="anonymous"> -<header class="allen-head"> -<p class="allen-eyebrow">Aien, live from the Spark</p> -<h1 class="allen-title">Talk to Aien</h1> -<p class="allen-lede" id="allen-intro">Aien is Drake's AI. Ask it anything, ask what Omega is (Aien's own language for all computing, GPU to CPU), or ask for a small program. An HTML mini app runs right here in a sandboxed frame; an Omega function is compiled to WebAssembly on the Spark and runs in your browser.</p> -<p class="allen-where">Model <code id="allen-model">qwen3.6-35b-a3b-fp8</code>, running on a DGX Spark in Drake's house. The speeds below are measured by this page from the live stream.</p> -</header> +<canvas id="allen-universe" class="allen-universe" tabindex="0" aria-label="Explore the universe with Aien. Drag to drift, scroll to zoom, or use arrow keys, plus, minus and Home."></canvas> +<div class="allen-space-tools" role="group" aria-label="Aien controls"><button type="button" class="allen-tool" id="allen-mute" aria-pressed="false">Sound on</button><button type="button" class="allen-tool" id="allen-projects">Projects</button><button type="button" class="allen-tool" id="allen-history" aria-expanded="false" aria-controls="allen-session">Session</button></div> +<div class="allen-arrival" id="allen-arrival"><h1>Explore the universe with Aien</h1><button type="button" class="allen-enter" id="allen-enter">Enter Aien's universe</button></div> +<div id="allen-panes" class="allen-panes" aria-label="Your workspace"></div> +<section class="allen-current" aria-label="Latest exchange"><p id="allen-guest" class="allen-guest"></p><p id="allen-speaker" class="allen-speaker">Aien</p><div id="allen-answer" class="allen-answer" data-speaker="allen" aria-live="polite" aria-atomic="false"></div><div class="allen-reply-actions"><button type="button" class="allen-tool" id="allen-copy">Copy reply</button><button type="button" class="allen-tool" id="allen-regenerate">Regenerate</button></div></section> <section class="allen-panel" aria-label="Conversation with Aien"> <p class="allen-mode"><span id="allen-mode">Anonymous: Aien won't remember this chat</span> <button type="button" class="allen-tool" id="allen-introduce">Remember me</button> <button type="button" class="allen-tool" id="allen-voice" aria-pressed="false">Voice: off</button> <button type="button" class="allen-tool" id="allen-voice-next" hidden>Next clip</button></p> -<div class="allen-volunteer" id="allen-volunteer-box"> -<label class="allen-agree"><input type="checkbox" id="allen-volunteer"> <span>Let a volunteer's Spark answer me when Drake's is busy.</span></label> -<p class="allen-note">If you tick this and my Spark is full, your messages in this chat go to a computer owned by a volunteer, outside my house. It gets only the text of this anonymous conversation. I add no visitor key, stored memories, contact record or IP address, but anything you type here is sent as you typed it. I check a sample of volunteer replies, not every one. A volunteer could still send a wrong or bad reply that I don't catch. Each reply says which machine answered.</p> -</div> +<section id="allen-session" class="allen-session" aria-label="Session history and privacy" hidden><header class="allen-head"><h2 class="allen-title">This session</h2><p class="allen-lede" id="allen-intro">Ask about the universe, explore an idea, or make something with Aien.</p><p class="allen-where">Model <code id="allen-model">qwen3.6-35b-a3b-fp8</code>. Timing below is measured from this reply.</p></header> <dl class="allen-speed" aria-label="Speed of the latest reply"> <div class="allen-stat"><dt>Wait in line</dt><dd id="allen-queue">-</dd></div> <div class="allen-stat"><dt>First token, model</dt><dd id="allen-ttft">-</dd></div> @@ -19,34 +15,27 @@ <div class="allen-stat"><dt>Tokens streamed</dt><dd id="allen-tokens">-</dd></div> <div class="allen-stat"><dt>Server count</dt><dd id="allen-server">-</dd></div> </dl> +<div class="allen-volunteer" id="allen-volunteer-box"> +<label class="allen-agree"><input type="checkbox" id="allen-volunteer"> <span>Let a volunteer's Spark answer me when Drake's is busy.</span></label> +<p class="allen-note">If you tick this and my Spark is full, your messages in this chat go to a computer owned by a volunteer, outside my house. It gets only the text of this anonymous conversation. I add no visitor key, stored memories, contact record or IP address, but anything you type here is sent as you typed it. I check a sample of volunteer replies, not every one. A volunteer could still send a wrong or bad reply that I don't catch. Each reply says which machine answered.</p> +</div> <div class="allen-scroll"><ol class="allen-log" id="allen-log" role="log" aria-live="polite" aria-label="Messages"></ol></div> -<noscript><p class="allen-status">This chat needs JavaScript: replies stream into the page as the model writes them.</p></noscript> +<noscript><p class="allen-status">Aien needs JavaScript to draw the scene and stream replies. Nothing is sent without it.</p></noscript> <div class="allen-examples" id="allen-examples" role="group" aria-label="Example questions"> <button type="button" class="allen-example">What is Omega?</button> <button type="button" class="allen-example">Make me a calculator</button> <button type="button" class="allen-example">Write an Omega gcd function</button> <button type="button" class="allen-example">How fast are you?</button> </div> -<p class="allen-drake" id="allen-drake" aria-live="polite" hidden></p> -<p class="allen-status" id="allen-status" role="status" aria-live="polite"></p> -<form class="allen-form" id="allen-form"> -<label class="allen-sr" for="allen-input">Message to Aien</label> -<textarea id="allen-input" rows="3" maxlength="4000" placeholder="Ask Aien something. Enter sends; Shift+Enter starts a new line." autocomplete="off"></textarea> -<div class="allen-actions"> -<button type="submit" class="allen-send" id="allen-send">Send</button> -<button type="button" class="allen-stop" id="allen-stop" disabled>Stop</button> -<button type="button" class="allen-new" id="allen-new">New conversation</button> -</div> -</form> -<p class="allen-contact">To reach me, Drake, directly: <a href="https://x.com/mdrakestapleton" rel="noopener">follow me on X</a> or email me at <a href="mailto:drake@aienos.com">drake@aienos.com</a>.</p> -<p class="allen-privacy" id="allen-privacy">Private by design: conversations are not stored, and the gateway keeps only aggregate counters. No prompts or IP addresses are logged. Programs run sandboxed in your browser. Reload the page and the conversation is gone. An introduction, and short notes Aien keeps about you, exist only if you consent; <a href="/privacy/">read what I keep</a>.</p> -<p class="allen-meet">Agents can introduce themselves with <code>POST https://www.aienos.com/allen/api/introduce</code> (schema in <a href="/llms.txt">/llms.txt</a>); nothing is stored without <code>"consent": true</code>.</p> -<details class="allen-keypanel" id="allen-key" data-key="no"> -<summary>Your Aien key</summary> -<div class="allen-keybody" id="allen-key-body"><p class="allen-note">Your Aien key needs JavaScript.</p></div> -</details> +<p class="allen-contact">To reach me, Drake, directly: <a href="https://x.com/mdrakestapleton" rel="noopener">follow me on X</a> or email <a href="mailto:drake@aienos.com">drake@aienos.com</a>. <a href="/contact/">More ways to reach me</a>.</p> +<p class="allen-privacy" id="allen-privacy">This session stays in this tab. Reloading clears the conversation. Projects are saved on this device only when you choose Save. Remembering you is a separate choice; <a href="/privacy/">read what I keep</a>.</p> +<details class="allen-keypanel" id="allen-key" data-key="no"><summary>Your Aien key</summary><div class="allen-keybody" id="allen-key-body"><p class="allen-note">Your Aien key needs JavaScript.</p></div></details> +<button type="button" class="allen-tool allen-new" id="allen-new">New conversation</button> +<button type="button" class="allen-tool" id="allen-speak" aria-pressed="false">Read replies aloud</button> +<p class="allen-foot"><a href="/">Aien's front door</a> · <a href="/classic/">Classic site</a></p> +<p class="allen-foot">The browser controller is <a href="/allen/scene.om">written in Omega</a>. The scene uses the <a href="https://github.com/aien-dev/aienux/tree/da55660ea7337f2b6a42095fcd1fb6ddebe1cc7c/native/kernel/ui" rel="noopener">same native iMac renderer</a>, compiled to WebAssembly.</p> +<p class="allen-foot"><a href="/alpha/">Own a DGX Spark? Run Sovereign Intelligence on yours</a>.</p></section> +<div class="allen-bottom"><p class="allen-drake" id="allen-drake" aria-live="polite" hidden></p><p class="allen-status" id="allen-status" role="status" aria-live="polite"></p> +<form class="allen-form" id="allen-form"><label class="allen-sr" for="allen-input">Message to Aien</label><textarea id="allen-input" rows="1" maxlength="4000" placeholder="Speak to Aien" autocomplete="off"></textarea><div class="allen-actions"><button type="button" class="allen-mic" id="allen-mic" aria-pressed="false" aria-describedby="allen-voice-privacy" aria-label="Use microphone">Mic</button><button type="submit" class="allen-send" id="allen-send" aria-label="Send message">Send</button><button type="button" class="allen-stop" id="allen-stop" disabled>Stop</button></div></form><p class="allen-input-hint">Enter to send. Shift+Enter for a new line.</p><p class="allen-input-hint" id="allen-voice-privacy">Microphone off. Voice availability is checked locally.</p><p class="allen-voice-status" id="allen-voice-status" role="status" aria-live="polite"></p></div> </section> -<footer class="allen-foot"> -<p>New to Omega? <a href="/omega/">Read what Omega is</a>. This page is generated by <a href="https://github.com/aien-dev/aienos.com/blob/main/om/allen-page/allen.om" rel="noopener">om/allen-page/allen.om</a> and its script by <a href="https://github.com/aien-dev/aienos.com/blob/main/om/allen-page/allen-js.om" rel="noopener">allen-js.om</a>, both seeded Omega.</p> -</footer> </div> diff --git a/om/allen-page/main.html.sha256 b/om/allen-page/main.html.sha256 index 8856e90..58e48e4 100644 --- a/om/allen-page/main.html.sha256 +++ b/om/allen-page/main.html.sha256 @@ -1 +1 @@ -1d81013f109fbdd65c8e44c8b8819787f164bdf337d493098acff62964be7d63 main.html +5fc84f0c10137722fbdad42680463ce38c3884ca9c7f3fc17cf290b0b35a6f26 main.html diff --git a/om/allen-panes/allen-panes.js.sha256 b/om/allen-panes/allen-panes.js.sha256 new file mode 100644 index 0000000..a867a71 --- /dev/null +++ b/om/allen-panes/allen-panes.js.sha256 @@ -0,0 +1 @@ +0df902e426e99496d55623ba233bc440dacafcbaca86f15870e2a21826d27494 ../../public/js/allen-panes.js diff --git a/om/allen-panes/check.sh b/om/allen-panes/check.sh new file mode 100755 index 0000000..9c350a7 --- /dev/null +++ b/om/allen-panes/check.sh @@ -0,0 +1,55 @@ +#!/bin/sh +# Regenerate the Allen glass panes script using the pinned arm64 omc. +# The compiler is the one vendored for the Hive page; its pin is recorded once, +# in ../hive-page/omc.sha256. contract.om is the canonical pane contract (owned +# by the science protocol); its kinds, events, version and byte limits are +# compiled into the script. CI on x86_64 checks the committed artifact against +# its recorded hash. OMEGA_OMC overrides the compiler path, never its pin. +# OMEGA_ACCEPT_CHANGE=1 accepts a rewritten artifact; otherwise stale output exits 4. +# Exit 2: missing compiler; 3: wrong pin; 4: stale artifact rewritten; +# 5: nondeterministic output; 6: empty output. Compile/run failures propagate. +set -eu +cd "$(dirname "$0")" +omc=${OMEGA_OMC:-$PWD/../hive-page/omc} +pin=$(tr -d ' \n' < ../hive-page/omc.sha256) +if [ ! -f "$omc" ]; then + printf 'No compiler at %s; set OMEGA_OMC to the pinned omc (%s)\n' "$omc" "$pin" >&2 + exit 2 +fi +have=$(sha256sum "$omc" | cut -d' ' -f1) +if [ "$have" != "$pin" ]; then + printf 'Compiler sha256 mismatch: recorded %s, found %s\n' "$pin" "$have" >&2 + exit 3 +fi +work=$(mktemp -d "${TMPDIR:-/tmp}/allen-panes.XXXXXX") +trap 'rm -rf "$work"' EXIT HUP INT TERM +# Concatenation composes Omega units; it does not implement generation in shell. +cat contract.om panes.om > "$work/panes.om" +"$omc" < "$work/panes.om" > "$work/panes" +chmod +x "$work/panes" +"$work/panes" > "$work/first.js" +"$work/panes" > "$work/second.js" +if ! cmp -s "$work/first.js" "$work/second.js"; then + printf 'allen-panes.js: generator output differs between runs\n' >&2 + exit 5 +fi +if [ ! -s "$work/first.js" ]; then + printf 'allen-panes.js: generator wrote nothing\n' >&2 + exit 6 +fi +artifact=../../public/js/allen-panes.js +stale=0 +if [ ! -f "$artifact" ] || ! cmp -s "$artifact" "$work/first.js"; then + stale=1 +fi +cp "$work/first.js" "$artifact" +hash=$(sha256sum "$artifact" | cut -d' ' -f1) +printf '%s %s\n' "$hash" "$artifact" > allen-panes.js.sha256 +printf '%s %s bytes sha256 %s\n' "$artifact" "$(wc -c < "$artifact" | tr -d ' ')" "$hash" +printf 'omc sha256 %s\n' "$have" +if [ "$stale" = 1 ]; then + printf 'Generated artifact was rewritten; commit it with its Omega sources\n' >&2 + if [ "${OMEGA_ACCEPT_CHANGE:-0}" != 1 ]; then + exit 4 + fi +fi diff --git a/om/allen-panes/contract.om b/om/allen-panes/contract.om new file mode 100644 index 0000000..9407b16 --- /dev/null +++ b/om/allen-panes/contract.om @@ -0,0 +1,54 @@ +note Allen glass pane protocol v1. Canonical transport and safety contract. +note SSE event names are exactly pane.open, pane.update, pane.close; JSON data objects only. +note open = {v:1,id,kind,title}; id ASCII [A-Za-z0-9_-]{1,64}; title UTF8 <=200 bytes. +note kind = math|plot|doc|code|app|research|data|omega. Max 32 live panes in browser. +note update = {v:1,id,revision,content,provenance}; revision integer 1..1000000. +note update fully replaces content and provenance, never patch/append/HTML injection. +note update before open, duplicate open and non-increasing revision are refused. +note close = {v:1,id}; unknown close is a no-op; closed ids cannot reopen in one stream. +note Each event <=65536 UTF8 bytes, all events <=262144 bytes per chat turn. +note content strings <=32768 UTF8 bytes; list count <=64 unless specified below. +note math content = {text,tex?}; only an actual successful engine result is computed. +note plot content = {series:[{label,points:[[finite number,finite number]]}],x_label,y_label}. +note plot <=8 series, <=512 points per series; labels <=200 bytes; data never proves itself. +note doc content = {markdown,citations:[{title,url}]}; URLs HTTPS only and never fetched. +note code/omega content = {source,language,wasm?,functions?}; wasm base64, never auto-run. +note functions = [{name,params:[{name,type}],ret}] exactly matching the Omega compile endpoint. +note app content = {html}; explicit visitor Run only; sandbox allow-scripts without same-origin. +note app CSP denies network, external resources, forms, navigation and frame escape. +note research content = {notes,hypotheses:[string],derivations:[string],sources:[{title,url}]}. +note data content = {columns:[string],rows:[[string]]}; never inferred as measured data. +note provenance = {status,engine,expression,result,source,commit}; all values strings. +note status = computed|unsupported|unverified|input-data; exact expression/result are auditable. +note computed means aien-math emitted a result, NOT that the result is independently correct. +note No model-produced number is labelled computed. Unsupported math has no model fallback. +note Model docs/research are unverified; plot literals input-data. Sources may be unverified. +note Engine identity and full corpus score are displayed with exact source pin and receipt limits. +note No live web access; no hidden Wolfram dependency, key, quota, or external math request. +note Unknown fields, invalid kinds, nonfinite numbers or excess sizes refuse the complete event. +note Browser strings are untrusted. DOM text nodes only; structured plots create SVG elements. +note TeX is source until actually typeset; never claim a source dump is a rendered formula. +note Projects persist in browser IndexedDB. Export is explicit. No anonymous server persistence. +note Remember-me summaries require separate visitor action and the existing opaque visitor key. +note Source text is never sent to Cortex automatically; sync <=1000 UTF8 bytes per summary. +note Public gateway forwards only six strict tool schemas to loopback isolated science service. +note math_compute, omega_compile, web_app, paper, research, plot; no arbitrary tool dispatch. +note At most three tool rounds. Public request admission cap remains two; tools spawn no model. +note Service has no network, credentials, writable host tree, project store or GitHub capability. +const PANEVER uint 1 +const PANE_MAX ulong 65536 +const TURN_MAX ulong 262144 +const TEXT_MAX ulong 32768 +const TOOL_MAX uint 3 +const TITLEMAX ulong 200 +const LISTMAX ulong 64 +const SERIESMX ulong 8 +const POINTSMX ulong 512 +const REVMAX ulong 1000000 +const PANESMAX ulong 32 +const URLMAX ulong 2048 +const SYNC_MAX ulong 1000 +const PLOTMAX f64 1.0e100 +text paneevt "pane.open|pane.update|pane.close|" +text panekind "math|plot|doc|code|app|research|data|omega|" +text toolname "math_compute|omega_compile|web_app|paper|research|plot|" diff --git a/om/allen-panes/panes.om b/om/allen-panes/panes.om new file mode 100644 index 0000000..be74a2a --- /dev/null +++ b/om/allen-panes/panes.om @@ -0,0 +1,326 @@ +note Allen glass panes generator: emits public/js/allen-panes.js on fd 1. +note ~N~ tokens in the js texts expand single definitions. 0 to 4 and 6 to 12 +note come from contract.om, the canonical pane contract owned by the science +note protocol: 0 panekind, 1 paneevt, 2 PANEVER, 3 PANE_MAX, 4 TEXT_MAX, +note 6 TITLEMAX, 7 LISTMAX, 8 SERIESMX, 9 POINTSMX, 10 REVMAX, 11 PANESMAX, +note 12 URLMAX. The rest are the fields of pcfg below, in order: 5 statuses, +note 13 reopenable closed panes, 14 saved projects, 15 project bytes, 16 IndexedDB +note name, 17 file format, 18 frame sandbox, 19 frame CSP, 20 sheet media query, +note 21 minimum width, 22 minimum height, 23 largest plot magnitude, and 24 is +note contract SYNC_MAX, the project summary bytes. +note Field 23 is the decimal form of contract PLOTMAX; main traps if they differ. +note 5 repeats the contract status sentence. A pcfg field cannot contain a pipe or +note a newline. Composed with contract.om by check.sh, never compiled on its own. +note Source language checked at omega-mv 55f9b0af47de70a3d06357985cf99ae3e45c016f. +text pcfg "computed,unsupported,unverified,input-data|8|50|4194304|allen-panes|allen-panes-project|allow-scripts|default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; form-action 'none'; base-uri 'none'|(max-width: 720px)|260|160|1e100|" +global output uchar 65536 +global used ulong 1 +global marker ulong 2 + +fn flush to void +p = ulong 0 +while lt p get used 0 bound 65536 +n = write 1 output p sub get used 0 p +if le n 0 +trap 3 +end +p = add p ulong n +end +put used 0 0 +end + +fn raw c uchar to void +if eq get used 0 len output +flush +end +put output get used 0 c +put used 0 add get used 0 1 +end + +note field: the k-th pipe-terminated field of pcfg; a missing field traps. +fn field k ulong to void +p = ulong 0 +i = ulong 0 +while lt p len pcfg +c = get pcfg p +if eq c 124 +if eq i k +ret +end +i = add i 1 +else +if eq i k +raw c +end +end +p = add p 1 +end +trap 3 +end + +note kinds and events: a contract list with its pipes as commas, no trailing one. +fn kinds to void +p = ulong 0 +while lt p len panekind +c = get panekind p +if eq c 124 +if lt add p 1 len panekind +raw 44 +end +else +raw c +end +p = add p 1 +end +end + +fn events to void +p = ulong 0 +while lt p len paneevt +c = get paneevt p +if eq c 124 +if lt add p 1 len paneevt +raw 44 +end +else +raw c +end +p = add p 1 +end +end + +note num: v in decimal; a ulong has at most 20 digits. +fn num v ulong to void +d = new uchar 20 0 +x = v +put d 0 uchar add 48 rem x 10 +n = ulong 1 +x = div x 10 +while gt x 0 bound 20 +put d n uchar add 48 rem x 10 +n = add n 1 +x = div x 10 +end +while gt n 0 bound 20 +n = sub n 1 +raw get d n +end +end + +fn slot k ulong to void +if eq k 0 +kinds +ret +end +if eq k 1 +events +ret +end +if eq k 2 +num ulong PANEVER +ret +end +if eq k 3 +num PANE_MAX +ret +end +if eq k 4 +num TEXT_MAX +ret +end +slot2 k +end + +note slot2: the contract limits 6 to 12, then pcfg field 0 for 5 and k - 12 above 12. +fn slot2 k ulong to void +if eq k 5 +field 0 +ret +end +if eq k 6 +num TITLEMAX +ret +end +if eq k 7 +num LISTMAX +ret +end +if eq k 8 +num SERIESMX +ret +end +if eq k 9 +num POINTSMX +ret +end +if eq k 10 +num REVMAX +ret +end +if eq k 11 +num PANESMAX +ret +end +if eq k 12 +num URLMAX +ret +end +if eq k 24 +num SYNC_MAX +ret +end +field sub k 12 +end + +note byteput: ~N~ expands slot N; any other byte is copied. +fn byteput c uchar to void +if eq c 126 +if eq get marker 0 0 +put marker 0 1 +put marker 1 0 +else +slot get marker 1 +put marker 0 0 +end +else +if eq get marker 0 1 +if or lt c 48 gt c 57 +trap 3 +end +put marker 1 add mul get marker 1 10 ulong sub c 48 +else +raw c +end +end +end + +note JavaScript KINDS +text js0 "/* Allen glass panes.\n *\n * Generated by om/allen-panes/panes.om; never hand-edit. Event names, kinds,\n * the protocol version and the byte limits come from the canonical pane\n * contract om/allen-panes/contract.om; the remaining bounds come from the\n * table in panes.om.\n *\n * Renders the v1 pane events (pane.open, pane.update, pane.close) as movable,\n * resizable, stackable glass panes over the scene. Every network or model\n * string reaches only textContent, an attribute value this file checks, or the\n * srcdoc of a frame sandboxed to allow-scripts alone after an explicit Run\n * click. Nothing from the network is parsed as markup in this document: plots\n * are drawn here from numbers and TeX is typeset here by a small subset\n * renderer, or shown as source when it uses anything outside that subset.\n * Projects reach IndexedDB only on an explicit Save project.\n */\n(() => {\n 'use strict';\n if (window.AllenPanes) return;\n const KINDS = '~0~'.split(',');\n const EVENTS = '~1~'.split(',');\n const VERSION = ~2~;\n const MAX_EVENT = ~3~;\n const MAX_TEXT = ~4~;\n const STATUSES = '~5~'.split(',');\n const MAX_TITLE = ~6~;\n const MAX_LIST = ~7~;\n const MAX_SERIES = ~8~;\n const MAX_POINTS = ~9~;\n const MAX_REVISION = ~10~;\n const MAX_PANES = ~11~;\n const MAX_URL = ~12~;\n const MAX_CLOSED = ~13~;\n const MAX_PROJECTS = ~14~;\n const MAX_PROJECT_BYTES = ~15~;\n const DB_NAME = '~16~';\n const FORMAT = '~17~';\n const SANDBOX = '~18~';\n const CSP = \"~19~\";\n const SHEET = '~20~';\n const MIN_W = ~21~;\n const MIN_H = ~22~;\n const MAX_ABS = ~23~;\n const SYNC_MAX = ~24~;\n const ID = /^[A-Za-z0-9_-]{1,64}$/;\n const DB_PROJECTS = 'projects';\n const DB_INDEX = 'index';\n const STEP = 16;\n const BIG_STEP = 64;\n const MAX_NAME = 80;\n const ACADEMY = 'https://github.com/aien-dev/sovereign-intelligence/blob/main/docs/academy/README.md';\n const SVG_NS = 'http://www.w3.org/2000/svg';\n const MATH_NS = 'http://www.w3.org/1998/Math/MathML';\n const NAMES = { math: 'Math', plot: 'Plot', doc: 'Document', code: 'Code', app: 'App', research: 'Research', data: 'Data', omega: 'Omega', card: 'Aien', projects: 'Projects' };\n const STATUS_NAMES = { computed: 'Computed', unsupported: 'Not supported', unverified: 'Not verified', 'input-data': 'Given data' };\n const CAVEATS = {\n computed: 'The math engine produced this result. That is not an independent check that it is correct.',\n unsupported: 'The engine does not support this request, so nothing here was computed.',\n unverified: 'Written by the model and not checked by any engine.',\n 'input-data': 'These are the numbers as given. Showing them does not measure or prove them.'\n };\n const PALETTE = ['#2d7ff9', '#00e599', '#f59e0b', '#6e82ff', '#f87171', '#c4b5fd', '#94a3b8', '#f1f5f9'];\n const EXT = { javascript: 'js', js: 'js', typescript: 'ts', ts: 'ts', python: 'py', py: 'py', rust: 'rs', rs: 'rs', c: 'c', cpp: 'cpp', 'c++': 'cpp', go: 'go', java: 'java', html: 'html', css: 'css', json: 'json', shell: 'sh', sh: 'sh', bash: 'sh', sql: 'sql', mojo: 'mojo', wat: 'wat', omega: 'om', om: 'om', markdown: 'md', md: 'md', text: 'txt' };\n const encoder = new TextEncoder();\n let serial = 0;\n\n function el(tag, className, text) {\n const node = document.createElement(tag);\n if (className) node.className = className;\n if (text !== undefined) node.textContent = text;\n return node;\n }\n function button(className, label, text, handler) {\n const node = el('button', className, text);\n node.type = 'button';\n if (label) node.setAttribute('aria-label', label);\n if (handler) node.addEventListener('click', handler);\n return node;\n }\n function uid(prefix) {\n serial += 1;\n return `${prefix}-${serial}`;\n }\n /* Display text for titles and names: no control or bidirectional override\n characters, one line, bounded. */\n function clean(text, max) {\n return String(text).replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, max);\n }\n function slug(text) {\n return String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, 48).replace(/-+$/, '');\n }\n function copy(value) {\n return JSON.parse(JSON.stringify(value));\n }\n function utf8(text) {\n return encoder.encode(text).length;\n }\n\n" + +note JavaScript own +text js1 " /* The v1 contract, checked exactly as the gateway checks it: unknown or\n missing fields, a wrong kind, a nonfinite number or an excess size refuse\n the whole event. */\n const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);\n function plain(o) {\n if (o === null || typeof o !== 'object' || Array.isArray(o)) return false;\n const proto = Object.getPrototypeOf(o);\n return proto === Object.prototype || proto === null;\n }\n function shape(o, required, optional) {\n if (!plain(o)) return false;\n const allowed = optional ? required.concat(optional) : required;\n for (const k of Object.keys(o)) if (!allowed.includes(k)) return false;\n return required.every(k => own(o, k));\n }\n function isText(v, max, filled) {\n if (typeof v !== 'string' || v.length > max || v.includes('\\u0000')) return false;\n if (filled && !v.trim()) return false;\n return v.length * 3 <= max || utf8(v) <= max;\n }\n function texts(v) {\n return Array.isArray(v) && v.length <= MAX_LIST && v.every(s => isText(s, MAX_TEXT));\n }\n function finite(n) {\n return typeof n === 'number' && Number.isFinite(n) && Math.abs(n) <= MAX_ABS;\n }\n function httpsUrl(url) {\n if (typeof url !== 'string' || !isText(url, MAX_URL) || /[\\u0000-\\u0020\\u007f]/.test(url)) return null;\n try {\n const parsed = new URL(url);\n return parsed.protocol === 'https:' && parsed.hostname && !parsed.username && !parsed.password ? parsed : null;\n } catch (_) {\n return null;\n }\n }\n function refs(v) {\n return Array.isArray(v) && v.length <= MAX_LIST && v.every(r => shape(r, ['title', 'url']) && isText(r.title, MAX_TITLE, true) && httpsUrl(r.url) !== null);\n }\n function fns(v) {\n return Array.isArray(v) && v.length <= MAX_LIST && v.every(f => shape(f, ['name', 'params', 'ret']) && isText(f.name, MAX_TEXT) && isText(f.ret, MAX_TEXT)\n && Array.isArray(f.params) && f.params.length <= MAX_LIST && f.params.every(p => shape(p, ['name', 'type']) && isText(p.name, MAX_TEXT) && isText(p.type, MAX_TEXT)));\n }\n function code(c) {\n return shape(c, ['source', 'language'], ['wasm', 'functions']) && isText(c.source, MAX_TEXT) && isText(c.language, MAX_TEXT)\n && (!own(c, 'wasm') || isText(c.wasm, MAX_TEXT)) && (!own(c, 'functions') || fns(c.functions));\n }\n function series(s) {\n return shape(s, ['label', 'points']) && isText(s.label, MAX_TITLE) && Array.isArray(s.points) && s.points.length >= 1 && s.points.length <= MAX_POINTS\n && s.points.every(p => Array.isArray(p) && p.length === 2 && finite(p[0]) && finite(p[1]));\n }\n const CONTENT = {\n math: c => shape(c, ['text'], ['tex']) && isText(c.text, MAX_TEXT) && (!own(c, 'tex') || isText(c.tex, MAX_TEXT)),\n plot: c => shape(c, ['series', 'x_label', 'y_label']) && isText(c.x_label, MAX_TITLE) && isText(c.y_label, MAX_TITLE)\n && Array.isArray(c.series) && c.series.length >= 1 && c.series.length <= MAX_SERIES && c.series.every(series),\n doc: c => shape(c, ['markdown', 'citations']) && isText(c.markdown, MAX_TEXT) && refs(c.citations),\n code,\n omega: code,\n app: c => shape(c, ['html']) && isText(c.html, MAX_TEXT),\n research: c => shape(c, ['notes', 'hypotheses', 'derivations', 'sources']) && isText(c.notes, MAX_TEXT) && texts(c.hypotheses) && texts(c.derivations) && refs(c.sources),\n data: c => shape(c, ['columns', 'rows']) && texts(c.columns) && c.columns.length >= 1\n && Array.isArray(c.rows) && c.rows.length <= MAX_LIST && c.rows.every(texts)\n };\n const PROVENANCE = ['status', 'engine', 'expression', 'result', 'source', 'commit'];\n function provenance(p) {\n return shape(p, PROVENANCE) && STATUSES.includes(p.status) && PROVENANCE.every(k => isText(p[k], MAX_TEXT));\n }\n function sized(value) {\n try {\n return utf8(JSON.stringify(value)) <= MAX_EVENT;\n } catch (_) {\n return false;\n }\n }\n /* Returns '' for a valid event, else the reason. An update is checked\n against the kind its pane was opened with. */\n function check(name, p, kind) {\n if (!EVENTS.includes(name)) return 'unknown pane event';\n if (!plain(p)) return 'the event is not a JSON object';\n const fields = name === 'pane.open' ? ['v', 'id', 'kind', 'title'] : name === 'pane.update' ? ['v', 'id', 'revision', 'content', 'provenance'] : ['v', 'id'];\n if (!shape(p, fields)) return 'unexpected or missing fields';\n if (p.v !== VERSION || typeof p.id !== 'string' || !ID.test(p.id)) return 'invalid pane identity';\n if (!sized(p)) return 'the event is over the size limit';\n if (name === 'pane.open') {\n if (!KINDS.includes(p.kind)) return 'invalid pane kind';\n return isText(p.title, MAX_TITLE, true) ? '' : 'invalid title';\n }\n if (name === 'pane.update') {\n if (!Number.isInteger(p.revision) || p.revision < 1 || p.revision > MAX_REVISION) return 'invalid revision';\n if (!KINDS.includes(kind)) return 'the pane is not open';\n if (!CONTENT[kind](p.content)) return `the content does not match ${kind === 'app' || kind === 'omega' ? 'an' : 'a'} ${kind} pane`;\n return provenance(p.provenance) ? '' : 'invalid provenance';\n }\n return '';\n }\n\n" + +note JavaScript link +text js2 " /* Links: HTTPS only, shown with their host, never fetched by this page. */\n function link(label, url) {\n const safe = httpsUrl(url);\n const shown = clean(label, MAX_TITLE) || url;\n if (!safe) {\n const span = el('span', 'allen-link-off', shown);\n if (url && url !== shown) span.append(document.createTextNode(` (${url})`));\n return span;\n }\n const frag = document.createDocumentFragment();\n const a = el('a', 'allen-link', shown);\n a.href = safe.href;\n a.target = '_blank';\n a.rel = 'noopener noreferrer nofollow';\n a.referrerPolicy = 'no-referrer';\n frag.append(a, el('span', 'allen-link-host', ` ${safe.host}`));\n return frag;\n }\n\n /* A small first-party TeX subset typeset as MathML Core built element by\n element. Anything outside the subset throws, and the caller shows the\n TeX as source and says so. */\n const GREEK = { alpha: '\\u03b1', beta: '\\u03b2', gamma: '\\u03b3', delta: '\\u03b4', epsilon: '\\u03f5', varepsilon: '\\u03b5', zeta: '\\u03b6', eta: '\\u03b7', theta: '\\u03b8', vartheta: '\\u03d1', iota: '\\u03b9', kappa: '\\u03ba', lambda: '\\u03bb', mu: '\\u03bc', nu: '\\u03bd', xi: '\\u03be', pi: '\\u03c0', varpi: '\\u03d6', rho: '\\u03c1', varrho: '\\u03f1', sigma: '\\u03c3', varsigma: '\\u03c2', tau: '\\u03c4', upsilon: '\\u03c5', phi: '\\u03d5', varphi: '\\u03c6', chi: '\\u03c7', psi: '\\u03c8', omega: '\\u03c9', Gamma: '\\u0393', Delta: '\\u0394', Theta: '\\u0398', Lambda: '\\u039b', Xi: '\\u039e', Pi: '\\u03a0', Sigma: '\\u03a3', Upsilon: '\\u03a5', Phi: '\\u03a6', Psi: '\\u03a8', Omega: '\\u03a9' };\n const IDENT = { infty: '\\u221e', partial: '\\u2202', nabla: '\\u2207', ell: '\\u2113', hbar: '\\u210f', emptyset: '\\u2205', aleph: '\\u2135' };\n const OPS = { pm: '\\u00b1', mp: '\\u2213', times: '\\u00d7', cdot: '\\u22c5', div: '\\u00f7', ast: '\\u2217', star: '\\u22c6', circ: '\\u2218', bullet: '\\u2219', leq: '\\u2264', le: '\\u2264', geq: '\\u2265', ge: '\\u2265', neq: '\\u2260', ne: '\\u2260', approx: '\\u2248', equiv: '\\u2261', sim: '\\u223c', simeq: '\\u2243', cong: '\\u2245', propto: '\\u221d', ll: '\\u226a', gg: '\\u226b', to: '\\u2192', rightarrow: '\\u2192', leftarrow: '\\u2190', Rightarrow: '\\u21d2', Leftarrow: '\\u21d0', leftrightarrow: '\\u2194', Leftrightarrow: '\\u21d4', iff: '\\u21d4', implies: '\\u21d2', mapsto: '\\u21a6', in: '\\u2208', notin: '\\u2209', ni: '\\u220b', subset: '\\u2282', supset: '\\u2283', subseteq: '\\u2286', supseteq: '\\u2287', cup: '\\u222a', cap: '\\u2229', setminus: '\\u2216', wedge: '\\u2227', land: '\\u2227', vee: '\\u2228', lor: '\\u2228', neg: '\\u00ac', lnot: '\\u00ac', forall: '\\u2200', exists: '\\u2203', ldots: '\\u2026', cdots: '\\u22ef', vdots: '\\u22ee', ddots: '\\u22f1', dots: '\\u2026', prime: '\\u2032', perp: '\\u22a5', parallel: '\\u2225', angle: '\\u2220', oplus: '\\u2295', otimes: '\\u2297', langle: '\\u27e8', rangle: '\\u27e9', lfloor: '\\u230a', rfloor: '\\u230b', lceil: '\\u2308', rceil: '\\u2309', vert: '|', mid: '|', lbrace: '{', rbrace: '}' };\n const LARGE = { sum: '\\u2211', prod: '\\u220f', coprod: '\\u2210', int: '\\u222b', iint: '\\u222c', iiint: '\\u222d', oint: '\\u222e', bigcup: '\\u22c3', bigcap: '\\u22c2' };\n const FUNCS = 'sin cos tan cot sec csc arcsin arccos arctan sinh cosh tanh coth log ln lg exp det dim ker deg gcd lcm max min sup inf lim liminf limsup arg Pr mod'.split(' ');\n const LIMITS = ['sum', 'prod', 'coprod', 'bigcup', 'bigcap', 'lim', 'liminf', 'limsup', 'max', 'min', 'sup', 'inf'];\n const SPACES = { ',': '0.1667em', ':': '0.2222em', ';': '0.2778em', '!': '-0.1667em', ' ': '0.25em', quad: '1em', qquad: '2em' };\n const BB = { C: '\\u2102', H: '\\u210d', N: '\\u2115', P: '\\u2119', Q: '\\u211a', R: '\\u211d', Z: '\\u2124' };\n const FENCES = { '(': '(', ')': ')', '[': '[', ']': ']', '|': '|', '.': '', '\\\\{': '{', '\\\\}': '}', '\\\\langle': '\\u27e8', '\\\\rangle': '\\u27e9', '\\\\lvert': '|', '\\\\rvert': '|', '\\\\|': '\\u2016', '\\\\lfloor': '\\u230a', '\\\\rfloor': '\\u230b', '\\\\lceil': '\\u2308', '\\\\rceil': '\\u2309' };\n function mml(tag, children, attrs) {\n const node = document.createElementNS(MATH_NS, tag);\n if (attrs) for (const k of Object.keys(attrs)) node.setAttribute(k, attrs[k]);\n if (typeof children === 'string') node.textContent = children;\n else if (children) node.append(...children);\n return node;\n }\n function texTokens(src) {\n const out = [];\n const re = /\\\\([A-Za-z]+|.)|(\\d+(?:\\.\\d+)?)|(\\s+)|([\\s\\S])/g;\n let m;\n while ((m = re.exec(src)) !== null) {\n if (out.length > 4096) throw new Error('too long');\n if (m[3]) continue;\n out.push(m[1] !== undefined ? { t: 'cmd', v: m[1] } : m[2] !== undefined ? { t: 'num', v: m[2] } : { t: 'chr', v: m[4] });\n }\n return out;\n }\n function texParse(src) {\n const toks = texTokens(src);\n let at = 0;\n let depth = 0;\n const peek = () => toks[at];\n const take = () => toks[at++];\n const fail = what => { throw new Error(what); };\n function group() {\n const t = peek();\n if (!t) fail('missing argument');\n if (t.t === 'chr' && t.v === '{') {\n take();\n const row = seq('}');\n if (!peek() || peek().v !== '}') fail('unclosed brace');\n take();\n return row;\n }\n return atom(true);\n }\n function raw() {\n const t = take();\n if (!t || t.t !== 'chr' || t.v !== '{') fail('expected a braced argument');\n let text = '';\n let level = 1;\n for (;;) {\n const n = take();\n if (!n) fail('unclosed brace');\n if (n.t === 'chr' && n.v === '{') level += 1;\n if (n.t === 'chr' && n.v === '}') {\n level -= 1;\n if (level === 0) return text;\n }\n text += n.t === 'cmd' ? (n.v.length === 1 ? n.v : `\\\\${n.v} `) : n.v;\n }\n }\n function fence() {\n const t = take();\n if (!t) fail('missing delimiter');\n const key = t.t === 'cmd' ? `\\\\${t.v}` : t.v;\n if (!own(FENCES, key)) fail(`delimiter ${key}`);\n return FENCES[key];\n }\n function atom(single) {\n const t = take();\n if (!t) fail('missing argument');\n if (t.t === 'num') {\n if (single && t.v.length > 1) {\n at -= 1;\n toks[at] = { t: 'num', v: t.v.slice(1) };\n return mml('mn', t.v[0]);\n }\n return mml('mn', t.v);\n }\n if (t.t === 'chr') {\n if (/[A-Za-z]/.test(t.v)) return mml('mi', t.v);\n if (t.v === '{' && !single) {\n at -= 1;\n return group();\n }\n if (t.v === \"'\") return mml('mo', '\\u2032');\n if (t.v === '-') return mml('mo', '\\u2212');\n if ('+=<>()[]|,;:!/*.?'.includes(t.v)) return mml('mo', t.v, '()[]|'.includes(t.v) ? { stretchy: 'false' } : undefined);\n fail(`character ${t.v}`);\n }\n const c = t.v;\n if (own(GREEK, c)) return mml('mi', GREEK[c], /^[A-Z]/.test(c) ? { mathvariant: 'normal' } : undefined);\n if (own(IDENT, c)) return mml('mi', IDENT[c]);\n if (own(OPS, c)) return mml('mo', OPS[c]);\n if (own(LARGE, c)) return mml('mo', LARGE[c], LIMITS.includes(c) ? { largeop: 'true', movablelimits: 'true' } : { largeop: 'true' });\n if (FUNCS.includes(c)) return mml('mi', c, { mathvariant: 'normal' });\n if (own(SPACES, c)) return mml('mspace', null, { width: SPACES[c] });\n if (c === '{' || c === '}' || c === '%' || c === '$' || c === '#' || c === '_' || c === '&') return mml('mo', c);\n if (c === 'frac' || c === 'dfrac' || c === 'tfrac') return mml('mfrac', [group(), group()]);\n if (c === 'binom') return mml('mrow', [mml('mo', '('), mml('mfrac', [group(), group()], { linethickness: '0' }), mml('mo', ')')]);\n if (c === 'sqrt') {\n if (peek() && peek().t === 'chr' && peek().v === '[') {\n take();\n const index = seq(']');\n if (!peek() || peek().v !== ']') fail('unclosed root index');\n take();\n return mml('mroot', [group(), index]);\n }\n return mml('msqrt', [group()]);\n }\n if (c === 'text' || c === 'textrm' || c === 'mathrm' || c === 'operatorname') {\n const text = raw();\n return c === 'text' || c === 'textrm' ? mml('mtext', text) : mml('mi', text, { mathvariant: 'normal' });\n }\n if (c === 'mathbb') {\n const letter = raw().trim();\n if (!own(BB, letter)) fail(`mathbb ${letter}`);\n return mml('mi', BB[letter]);\n }\n if (c === 'left') {\n const open = fence();\n const inner = seq('right');\n const close = peek();\n if (!close || close.t !== 'cmd' || close.v !== 'right') fail('left without right');\n take();\n const shut = fence();\n return mml('mrow', [mml('mo', open, { fence: 'true', stretchy: 'true' }), inner, mml('mo', shut, { fence: 'true', stretchy: 'true' })]);\n }\n return fail(`\\\\${c}`);\n }\n function scripted(base) {\n let sub = null;\n let sup = null;\n for (let i = 0; i < 2; i++) {\n const t = peek();\n if (!t || t.t !== 'chr' || (t.v !== '_' && t.v !== '^')) break;\n take();\n if (t.v === '_') {\n if (sub) fail('double subscript');\n sub = group();\n } else {\n if (sup) fail('double superscript');\n sup = group();\n }\n }\n if (!sub && !sup) return base;\n const under = (base.localName === 'mo' && base.getAttribute('movablelimits') === 'true') || (base.localName === 'mi' && LIMITS.includes(base.textContent));\n if (sub && sup) return mml(under ? 'munderover' : 'msubsup', [base, sub, sup]);\n if (sub) return mml(under ? 'munder' : 'msub', [base, sub]);\n return mml(under ? 'mover' : 'msup', [base, sup]);\n }\n function seq(stop) {\n depth += 1;\n if (depth > 32) fail('nested too deeply');\n const items = [];\n while (at < toks.length) {\n const t = peek();\n if (stop === 'right' ? t.t === 'cmd' && t.v === 'right' : t.t === 'chr' && t.v === stop) break;\n if (t.t === 'chr' && (t.v === '}' || t.v === ']') && stop === null) fail('unbalanced');\n if (t.t === 'chr' && (t.v === '^' || t.v === '_')) {\n items.push(scripted(mml('mrow', [])));\n continue;\n }\n items.push(scripted(atom(false)));\n }\n depth -= 1;\n return items.length === 1 ? items[0] : mml('mrow', items);\n }\n const tree = seq(null);\n if (at !== toks.length) fail('trailing input');\n return tree;\n }\n /* Returns a math element, or null with the reason when the TeX is outside\n the subset or the browser has no MathML. */\n function typeset(src, display) {\n if (typeof window.MathMLElement !== 'function') return { node: null, reason: 'this browser does not lay out MathML' };\n try {\n const tree = texParse(src);\n const semantics = mml('semantics', [tree, mml('annotation', src, { encoding: 'application/x-tex' })]);\n return { node: mml('math', [semantics], { display: display ? 'block' : 'inline' }), reason: '' };\n } catch (error) {\n return { node: null, reason: `it uses ${String(error && error.message).slice(0, 80)}, which this renderer does not typeset` };\n }\n }\n function texBlock(src, label) {\n const box = el('div', 'allen-tex');\n const done = typeset(src, true);\n if (done.node) {\n box.append(done.node, el('p', 'allen-pane-label', `${label} typeset in this page from TeX by a small first-party renderer; the source is below.`));\n } else {\n box.append(el('p', 'allen-pane-label', `${label} as TeX source, not typeset: ${done.reason}.`));\n }\n const pre = el('pre', 'allen-pane-pre', src);\n pre.setAttribute('aria-label', 'TeX source');\n box.append(pre);\n return box;\n }\n\n" + +note JavaScript inline +text js3 " /* Markdown subset rendered to DOM nodes only: headings, paragraphs, lists,\n quotes, rules, fenced code, pipe tables, inline code, strong, emphasis,\n HTTPS links and $ TeX. Raw HTML stays text. */\n function inline(node, text) {\n const re = /(`+)([^`][\\s\\S]*?)\\1|\\*\\*([^*\\n]+)\\*\\*|\\*([^*\\s][^*\\n]*)\\*|\\[([^\\]\\n]{1,500})\\]\\(([^)\\s]{1,2048})\\)|\\$([^$\\n]{1,500})\\$|(https:\\/\\/[^\\s<>()]{1,2048})/g;\n let last = 0;\n let m;\n while ((m = re.exec(text)) !== null) {\n if (m.index > last) node.append(document.createTextNode(text.slice(last, m.index)));\n if (m[1]) node.append(el('code', 'allen-md-code', m[2]));\n else if (m[3] !== undefined) node.append(el('strong', '', m[3]));\n else if (m[4] !== undefined) node.append(el('em', '', m[4]));\n else if (m[5] !== undefined) node.append(link(m[5], m[6]));\n else if (m[7] !== undefined) {\n const done = typeset(m[7], false);\n if (done.node) node.append(done.node);\n else {\n const raw = el('code', 'allen-md-tex', `$${m[7]}$`);\n raw.title = 'TeX source, not typeset';\n node.append(raw);\n }\n } else {\n const url = m[8].replace(/[.,;:!?]+$/, '');\n node.append(link(url, url));\n if (url.length < m[8].length) node.append(document.createTextNode(m[8].slice(url.length)));\n }\n last = re.lastIndex;\n }\n if (last < text.length) node.append(document.createTextNode(text.slice(last)));\n return node;\n }\n function cells(line) {\n return line.trim().replace(/^\\|/, '').replace(/\\|$/, '').split('|').map(s => s.trim());\n }\n /* A repo report's files, found by the same parser that renders the pane,\n so a fence the reader saw is exactly a fence that is saved. */\n const REPORT = /^Repo report: ([A-Za-z0-9_.-]{1,100})\\/([A-Za-z0-9_.-]{1,100})$/;\n function reportFiles(source) {\n const files = [{ path: 'README.md', content: source }];\n const patches = [];\n let port = 0;\n let harness = 0;\n markdown(source, document.createElement('div'), (lang, text) => {\n const kind = lang.toLowerCase();\n if (kind === 'omega' || kind === 'om') files.push({ path: `allen-port-${(port += 1)}.om`, content: `${text}\\n` });\n else if (kind === 'diff' || kind === 'patch') patches.push(`${text}\\n`);\n else if (kind === 'text' || kind === 'txt') files.push({ path: `parity-harness-${(harness += 1)}.txt`, content: `${text}\\n` });\n return null;\n });\n if (patches.length) files.push({ path: 'allen-ports.patch', content: patches.join('') });\n return files;\n }\n function markdown(source, box, fenceTool) {\n const lines = source.split(/\\r?\\n/);\n let para = [];\n let list = null;\n const flush = () => {\n if (para.length) box.append(inline(el('p', 'allen-md-p'), para.join(' ')));\n para = [];\n };\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const fence = /^\\s*(```+)\\s*([A-Za-z0-9_+-]{0,32})\\s*$/.exec(line);\n if (fence) {\n flush();\n list = null;\n const body = [];\n for (i += 1; i < lines.length && !lines[i].trim().startsWith(fence[1]); i++) body.push(lines[i]);\n const pre = el('pre', 'allen-md-pre');\n if (fence[2]) pre.dataset.lang = fence[2];\n pre.append(el('code', '', body.join('\\n')));\n box.append(pre);\n const tool = fenceTool ? fenceTool(fence[2], body.join('\\n')) : null;\n if (tool) box.append(tool);\n continue;\n }\n if (/^\\s*\\$\\$/.test(line)) {\n flush();\n list = null;\n const body = [line.replace(/^\\s*\\$\\$/, '')];\n let closed = /\\$\\$\\s*$/.test(body[0]) && body[0].trim().length > 2;\n if (closed) body[0] = body[0].replace(/\\$\\$\\s*$/, '');\n if (!closed) for (i += 1; i < lines.length; i++) {\n if (/\\$\\$\\s*$/.test(lines[i])) {\n body.push(lines[i].replace(/\\$\\$\\s*$/, ''));\n closed = true;\n break;\n }\n body.push(lines[i]);\n }\n box.append(texBlock(body.join('\\n').trim(), 'Formula'));\n continue;\n }\n if (!line.trim()) {\n flush();\n list = null;\n continue;\n }\n const heading = /^\\s*(#{1,6})\\s+(.*?)\\s*#*\\s*$/.exec(line);\n if (heading) {\n flush();\n list = null;\n box.append(inline(el(`h${Math.min(6, heading[1].length + 2)}`, 'allen-md-h'), heading[2]));\n continue;\n }\n if (/^\\s*([-*_])(\\s*\\1){2,}\\s*$/.test(line)) {\n flush();\n list = null;\n box.append(el('hr', 'allen-md-hr'));\n continue;\n }\n if (/^\\s*\\|.*\\|\\s*$/.test(line) && i + 1 < lines.length && /^\\s*\\|?\\s*:?-+:?\\s*(\\|\\s*:?-+:?\\s*)*\\|?\\s*$/.test(lines[i + 1])) {\n flush();\n list = null;\n const table = el('table', 'allen-md-table');\n const head = el('tr');\n for (const c of cells(line)) head.append(inline(el('th'), c));\n const thead = el('thead');\n thead.append(head);\n const tbody = el('tbody');\n for (i += 2; i < lines.length && /^\\s*\\|.*\\|\\s*$/.test(lines[i]); i++) {\n const row = el('tr');\n for (const c of cells(lines[i])) row.append(inline(el('td'), c));\n tbody.append(row);\n }\n i -= 1;\n table.append(thead, tbody);\n const wrap = el('div', 'allen-pane-table');\n wrap.append(table);\n box.append(wrap);\n continue;\n }\n const quote = /^\\s*>\\s?(.*)$/.exec(line);\n if (quote) {\n flush();\n list = null;\n const parts = [quote[1]];\n while (i + 1 < lines.length && /^\\s*>/.test(lines[i + 1])) parts.push(lines[++i].replace(/^\\s*>\\s?/, ''));\n const block = el('blockquote', 'allen-md-quote');\n block.append(inline(el('p', 'allen-md-p'), parts.join(' ')));\n box.append(block);\n continue;\n }\n const item = /^\\s*([-*+]|\\d{1,9}[.)])\\s+(.*)$/.exec(line);\n if (item) {\n flush();\n const ordered = /\\d/.test(item[1]);\n if (!list || (list.localName === 'ol') !== ordered) {\n list = el(ordered ? 'ol' : 'ul', 'allen-md-list');\n box.append(list);\n }\n list.append(inline(el('li'), item[2]));\n continue;\n }\n if (list && /^\\s{2,}\\S/.test(line)) {\n inline(list.lastElementChild, ` ${line.trim()}`);\n continue;\n }\n list = null;\n para.push(line.trim());\n }\n flush();\n return box;\n }\n\n" + +note JavaScript svg +text js4 " /* Plots are drawn here from validated numbers; no SVG from the network is\n ever parsed. Colours are attributes so an exported file keeps them. */\n function svg(tag, attrs, text) {\n const node = document.createElementNS(SVG_NS, tag);\n for (const k of Object.keys(attrs)) node.setAttribute(k, String(attrs[k]));\n if (text !== undefined) node.textContent = text;\n return node;\n }\n function fmt(n) {\n const v = Number(n.toPrecision(5));\n return Object.is(v, -0) ? '0' : String(v);\n }\n function ticks(lo, hi) {\n const raw = (hi - lo) / 5;\n if (!Number.isFinite(raw) || raw <= 0) return [lo, hi];\n const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n const unit = [1, 2, 5, 10].map(f => f * mag).find(s => s >= raw) || raw;\n const first = Math.ceil(lo / unit);\n const out = [];\n for (let n = 0; n < 12; n++) {\n const t = (first + n) * unit;\n if (t > hi + unit * 1e-9) break;\n out.push(t);\n }\n return out.length ? out : [lo, hi];\n }\n function extent(c) {\n let x0 = Infinity;\n let x1 = -Infinity;\n let y0 = Infinity;\n let y1 = -Infinity;\n for (const s of c.series) for (const p of s.points) {\n x0 = Math.min(x0, p[0]);\n x1 = Math.max(x1, p[0]);\n y0 = Math.min(y0, p[1]);\n y1 = Math.max(y1, p[1]);\n }\n if (x0 === x1) {\n x0 -= 1;\n x1 += 1;\n }\n if (y0 === y1) {\n y0 -= 1;\n y1 += 1;\n }\n return { x0, x1, y0, y1 };\n }\n function plot(c, title) {\n const W = 640;\n const H = 400;\n const L = 64;\n const R = 20;\n const T = 20;\n const B = 52;\n const e = extent(c);\n const sx = v => L + (v - e.x0) / (e.x1 - e.x0) * (W - L - R);\n const sy = v => H - B - (v - e.y0) / (e.y1 - e.y0) * (H - T - B);\n const titleId = uid('allen-plot-title');\n const descId = uid('allen-plot-desc');\n const root = svg('svg', { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: 'img', 'aria-labelledby': `${titleId} ${descId}`, class: 'allen-plot-svg' });\n const xl = c.x_label ? ` (${c.x_label})` : '';\n const yl = c.y_label ? ` (${c.y_label})` : '';\n root.append(svg('title', { id: titleId }, title), svg('desc', { id: descId }, `${c.series.length} series; x${xl} from ${fmt(e.x0)} to ${fmt(e.x1)}; y${yl} from ${fmt(e.y0)} to ${fmt(e.y1)}.`));\n const grid = svg('g', { stroke: '#1c2536', 'stroke-width': 1 });\n const labels = svg('g', { fill: '#94a3b8', 'font-size': 12, 'font-family': 'ui-sans-serif, system-ui, sans-serif' });\n for (const t of ticks(e.x0, e.x1)) {\n const x = sx(t).toFixed(2);\n grid.append(svg('line', { x1: x, y1: T, x2: x, y2: H - B }));\n labels.append(svg('text', { x, y: H - B + 18, 'text-anchor': 'middle' }, fmt(t)));\n }\n for (const t of ticks(e.y0, e.y1)) {\n const y = sy(t).toFixed(2);\n grid.append(svg('line', { x1: L, y1: y, x2: W - R, y2: y }));\n labels.append(svg('text', { x: L - 8, y: (Number(y) + 4).toFixed(2), 'text-anchor': 'end' }, fmt(t)));\n }\n const axes = svg('g', { stroke: '#3b4a63', 'stroke-width': 1 });\n axes.append(svg('line', { x1: L, y1: H - B, x2: W - R, y2: H - B }), svg('line', { x1: L, y1: T, x2: L, y2: H - B }));\n if (c.x_label) labels.append(svg('text', { x: (L + W - R) / 2, y: H - 12, 'text-anchor': 'middle' }, c.x_label));\n if (c.y_label) {\n const mid = (T + H - B) / 2;\n labels.append(svg('text', { x: 16, y: mid, 'text-anchor': 'middle', transform: `rotate(-90 16 ${mid})` }, c.y_label));\n }\n const lines = svg('g', { fill: 'none', 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' });\n c.series.forEach((s, i) => {\n const colour = PALETTE[i % PALETTE.length];\n const group = svg('g', { stroke: colour });\n group.append(svg('title', {}, s.label || `Series ${i + 1}`));\n if (s.points.length > 1) group.append(svg('polyline', { points: s.points.map(p => `${sx(p[0]).toFixed(2)},${sy(p[1]).toFixed(2)}`).join(' ') }));\n if (s.points.length <= 64) for (const p of s.points) group.append(svg('circle', { cx: sx(p[0]).toFixed(2), cy: sy(p[1]).toFixed(2), r: 3, fill: colour, stroke: 'none' }));\n lines.append(group);\n });\n root.append(grid, axes, lines, labels);\n const figure = el('figure', 'allen-plot');\n figure.append(root);\n const legend = el('ul', 'allen-plot-legend');\n c.series.forEach((s, i) => {\n const item = el('li', 'allen-plot-key');\n const swatch = el('span', 'allen-plot-swatch');\n swatch.style.background = PALETTE[i % PALETTE.length];\n swatch.setAttribute('aria-hidden', 'true');\n item.append(swatch, document.createTextNode(`${s.label || `Series ${i + 1}`}, ${s.points.length} point${s.points.length === 1 ? '' : 's'}`));\n legend.append(item);\n });\n figure.append(legend);\n const data = el('details', 'allen-plot-data');\n data.append(el('summary', 'allen-pane-summary', 'Plot data as a table'));\n data.addEventListener('toggle', () => {\n if (!data.open || data.dataset.built) return;\n data.dataset.built = 'yes';\n data.append(table(['Series', c.x_label || 'x', c.y_label || 'y'], c.series.flatMap((s, i) => s.points.map(p => [s.label || `Series ${i + 1}`, String(p[0]), String(p[1])]))));\n });\n figure.append(data);\n return { figure, svg: root };\n }\n function table(columns, rows) {\n const wrap = el('div', 'allen-pane-table');\n wrap.tabIndex = 0;\n const node = el('table', 'allen-data');\n const head = el('tr');\n for (const c of columns) {\n const th = el('th', '', c);\n th.scope = 'col';\n head.append(th);\n }\n const thead = el('thead');\n thead.append(head);\n const tbody = el('tbody');\n for (const r of rows) {\n const tr = el('tr');\n for (let i = 0; i < Math.max(r.length, columns.length); i++) tr.append(el('td', '', i < r.length ? r[i] : ''));\n tbody.append(tr);\n }\n node.append(thead, tbody);\n wrap.append(node);\n return wrap;\n }\n\n" + +note JavaScript csv +text js5 " /* Files. Every download is application/octet-stream, so no browser renders\n a generated file in this origin. */\n function csv(columns, rows) {\n const cell = v => {\n let s = String(v);\n if (/^[=+@\\t\\r]/.test(s) || /^-(?![\\d.])/.test(s)) s = `'${s}`;\n return /[\",\\r\\n]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n };\n return `${[columns, ...rows].map(r => r.map(cell).join(',')).join('\\r\\n')}\\r\\n`;\n }\n function refText(items) {\n return items.map((r, i) => `${i + 1}. [${r.title}](${r.url})`).join('\\n');\n }\n function artefact(rec) {\n const c = rec.content;\n const base = slug(rec.title) || rec.kind;\n switch (rec.kind) {\n case 'math': {\n const text = own(c, 'tex') ? `${c.text}\\n\\nTeX source:\\n${c.tex}\\n` : `${c.text}\\n`;\n return { name: `${base}.txt`, what: 'result', data: () => text, copy: c.text };\n }\n case 'plot': {\n const rows = c.series.flatMap((s, i) => s.points.map(p => [s.label || `Series ${i + 1}`, String(p[0]), String(p[1])]));\n return { name: `${base}.svg`, what: 'data as CSV', data: () => `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${new XMLSerializer().serializeToString(rec.svg)}\\n`, copy: csv(['series', c.x_label || 'x', c.y_label || 'y'], rows) };\n }\n case 'doc': {\n const text = c.citations.length ? `${c.markdown}\\n\\n## Citations\\n\\n${refText(c.citations)}\\n` : `${c.markdown}\\n`;\n return { name: `${base}.md`, what: 'Markdown', data: () => text, copy: text };\n }\n case 'code':\n case 'omega': {\n const ext = rec.kind === 'omega' ? 'om' : EXT[c.language.toLowerCase()] || 'txt';\n return { name: `${base}.${ext}`, what: 'source', data: () => c.source, copy: c.source };\n }\n case 'app':\n return { name: `${base}.html`, what: 'HTML', data: () => c.html, copy: c.html };\n case 'research': {\n const parts = [`# ${rec.title}`, '## Notes', c.notes];\n if (c.hypotheses.length) parts.push('## Hypotheses', c.hypotheses.map(h => `- ${h}`).join('\\n'));\n if (c.derivations.length) parts.push('## Derivations', c.derivations.map(d => `\\`\\`\\`\\n${d}\\n\\`\\`\\``).join('\\n\\n'));\n if (c.sources.length) parts.push('## Sources', refText(c.sources));\n const text = `${parts.join('\\n\\n')}\\n`;\n return { name: `${base}.md`, what: 'Markdown', data: () => text, copy: text };\n }\n case 'data': {\n const text = csv(c.columns, c.rows);\n return { name: `${base}.csv`, what: 'CSV', data: () => text, copy: text };\n }\n default:\n return null;\n }\n }\n function wasmBytes(text) {\n try {\n const bin = atob(text.replace(/\\s+/g, ''));\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out.length >= 8 && out[0] === 0 && out[1] === 97 && out[2] === 115 && out[3] === 109 ? out : null;\n } catch (_) {\n return null;\n }\n }\n async function copyText(source, node) {\n if (node.dataset.label === undefined) node.dataset.label = node.textContent;\n try {\n await navigator.clipboard.writeText(source);\n node.textContent = 'Copied';\n } catch (_) {\n node.textContent = 'Copy blocked';\n }\n setTimeout(() => {\n node.textContent = node.dataset.label;\n }, 1500);\n }\n /* The policy becomes the first element of the program's head, as in the\n chat client: after an existing head tag, else in a head of its own. The\n prefix (doctype, comments, html tag) is skipped one sticky token at a\n time and a comment body never holds its closing marker, so the scan is\n linear in the source. */\n function sandboxed(source) {\n const meta = `<meta http-equiv=\"Content-Security-Policy\" content=\"${CSP}\">`;\n const prefix = /\\s*(?:<!doctype[^>]*>|<!--(?:[^-]|-(?!->))*-->|<html(?:\\s[^>]*)?>)/iy;\n let at = 0;\n while (prefix.exec(source)) at = prefix.lastIndex;\n const head = /\\s*<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*(?:<!doctype[^>]*>\\s*)?(?:<html(?:\\s[^>]*)?>)?/i.exec(source)[0];\n return `${lead}<head>${meta}</head>${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 @@ +<a id="aien-allen-launcher" class="allen-launcher" href="/aien/" aria-label="Enter Aien's universe"><canvas width="180" height="150" aria-hidden="true"></canvas><span class="allen-launcher-bar">Speak to Aien</span></a> 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<reply.length) paintReply(); });\n reduced.addEventListener('change',() => { 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 "<a id=\"aien-allen-launcher\" class=\"allen-launcher\" href=\"/aien/\" aria-label=\"Enter Aien's universe\"><canvas width=\"180\" height=\"150\" aria-hidden=\"true\"></canvas><span class=\"allen-launcher-bar\">Speak to Aien</span></a>\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<box.y+box.h;y++) for(int32_t x=box.x;x<box.x+box.w;x++) { + int32_t dx=x*16+8-hx,dy=y*16+8-hy; + uint32_t d=ck_isqrt((uint32_t)(dx*dx+dy*dy)); + if(d>=(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<box.y+box.h;yy++) for(int32_t xx=box.x;xx<box.x+box.w;xx++) { + size_t i=(size_t)yy*ui.w+xx;uint32_t col=ui.back[i]; + ui.rgba[i]=0xff000000u|(col&0xff00u)|(col>>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 <stddef.h> +#include <stdint.h> + +#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 <stdint.h> +#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 <stddef.h> +#include <stdint.h> +#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 <stddef.h> +#include <stdint.h> + +#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)