From 183f99a40bd7308da3e848de961ed32bb02624a5 Mon Sep 17 00:00:00 2001 From: tfrere Date: Thu, 3 Sep 2026 11:41:41 +0200 Subject: [PATCH] feat: title menu revamp, vendored deps, ghost relay fix - Title menu: split layout with live 3D duck (vitrine-style materialize shader), variant-tinted accents, unified boot spinner (assets + font + game core), duck hidden on narrow touch screens - Audio: new WebAudio sound system (sweeps synced to the tron shader, per-prop pitch scaling) - shipped disabled via SOUND_DISABLED until the sound design is finished; HUD mute toggle commented out accordingly - Supply chain: MuJoCo, onnxruntime-web and trystero vendored from npm instead of jsDelivr/esm.run CDNs (wasm assets bundled locally) - Ghosts: explicit healthy Nostr relay list; the appId-seeded default subset had rotted (dead/blocking/rate-limiting relays), silently breaking peer discovery in prod Co-authored-by: Cursor --- README.md | 2 + app/package-lock.json | 187 +++++++- app/package.json | 3 + app/public/assets/sfx/click_a.wav | 3 + app/public/assets/sfx/click_b.wav | 3 + app/public/assets/sfx/step_a.wav | 3 + app/public/assets/sfx/step_b.wav | 3 + app/public/assets/sfx/step_c.wav | 3 + app/public/assets/sfx/step_d.wav | 3 + app/public/assets/sfx/step_e.wav | 3 + app/public/assets/sfx/thump_a.wav | 3 + app/public/assets/sfx/thump_b.wav | 3 + app/public/assets/sfx/thump_c.wav | 3 + app/src/App.jsx | 31 +- app/src/game/arena.js | 33 ++ app/src/game/audio.js | 581 +++++++++++++++++++++++++ app/src/game/ceremony.js | 31 ++ app/src/game/game.js | 219 ++++++++-- app/src/game/ghosts.js | 22 +- app/src/game/vendor/zzfx.js | 60 +++ app/src/main.jsx | 12 +- app/src/ui/BiosOverlay.jsx | 7 + app/src/ui/Hud.jsx | 84 +++- app/src/ui/MenuDuck.jsx | 350 +++++++++++++++ app/src/ui/Preboot.jsx | 54 --- app/src/ui/Soundboard.jsx | 368 ++++++++++++++++ app/src/ui/TitleMenu.jsx | 697 ++++++++++++++++++++++-------- 27 files changed, 2463 insertions(+), 308 deletions(-) create mode 100644 app/public/assets/sfx/click_a.wav create mode 100644 app/public/assets/sfx/click_b.wav create mode 100644 app/public/assets/sfx/step_a.wav create mode 100644 app/public/assets/sfx/step_b.wav create mode 100644 app/public/assets/sfx/step_c.wav create mode 100644 app/public/assets/sfx/step_d.wav create mode 100644 app/public/assets/sfx/step_e.wav create mode 100644 app/public/assets/sfx/thump_a.wav create mode 100644 app/public/assets/sfx/thump_b.wav create mode 100644 app/public/assets/sfx/thump_c.wav create mode 100644 app/src/game/audio.js create mode 100644 app/src/game/vendor/zzfx.js create mode 100644 app/src/ui/MenuDuck.jsx delete mode 100644 app/src/ui/Preboot.jsx create mode 100644 app/src/ui/Soundboard.jsx diff --git a/README.md b/README.md index 97697ec..ede1d16 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,8 @@ Plug in a controller and the same mapping as the real robot runtime applies: - D-pad down: sit / stand toggle (legs only) - D-pad up: hold ~1 s to switch legs <-> rollers (the real robot uses a 3 s hold) - Right trigger: mouth (analog) + quack +- A: enter / resume the game while the title or pause overlay is up +- Menu/Start (or Select): exit back to the title overlay while in-game ## Multiplayer ghosts diff --git a/app/package-lock.json b/app/package-lock.json index f2b2929..8e590e6 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -1,21 +1,23 @@ { - "name": "app", + "name": "microduck-sandbox", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "app", + "name": "microduck-sandbox", "version": "1.0.0", - "license": "ISC", "dependencies": { "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@mui/material": "^9.3.1", + "@mujoco/mujoco": "^3.11.0", "@react-three/fiber": "^9.7.0", + "onnxruntime-web": "^1.27.0", "react": "^19.2.8", "react-dom": "^19.2.8", "three": "^0.164.1", + "trystero": "^0.25.3", "zustand": "^5.0.15" }, "devDependencies": { @@ -552,6 +554,21 @@ } } }, + "node_modules/@mujoco/mujoco": { + "version": "3.11.0", + "resolved": "https://registry.npmjs.org/@mujoco/mujoco/-/mujoco-3.11.0.tgz", + "integrity": "sha512-ZtBhIX8It5EZUcRfxalYTilSG52JYoItEOBYOXdkviwZWaZ8XBuuSuNBwnXqhV1VkXpWbpPc27vGdQsTiSVX3Q==", + "license": "Apache-2.0" + }, + "node_modules/@noble/secp256k1": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@noble/secp256k1/-/secp256k1-3.2.0.tgz", + "integrity": "sha512-Z3ZAWOTxJ0EuTuZTi7Y69iK7GgrLHh8sgm45lVDhg/b3Nk1TpAiKhick2KkZisHuupeepSkyIydN/J459SdX1w==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@oxc-project/types": { "version": "0.146.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.146.0.tgz", @@ -572,6 +589,63 @@ "url": "https://opencollective.com/popperjs" } }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, "node_modules/@react-three/fiber": { "version": "9.7.0", "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-9.7.0.tgz", @@ -882,6 +956,31 @@ "dev": true, "license": "MIT" }, + "node_modules/@trystero-p2p/core": { + "version": "0.25.3", + "resolved": "https://registry.npmjs.org/@trystero-p2p/core/-/core-0.25.3.tgz", + "integrity": "sha512-lQKNq/ha+vF6kQZrpaXJGzlzxLF/Fhizoy5dwJUYQlkqRrbPup/Jov2EpPX/CPr2X+f79HxVzonkeni3MxmCuQ==", + "license": "MIT" + }, + "node_modules/@trystero-p2p/nostr": { + "version": "0.25.3", + "resolved": "https://registry.npmjs.org/@trystero-p2p/nostr/-/nostr-0.25.3.tgz", + "integrity": "sha512-nZV9Fl/GXuhIkJSQ+wIkdMoRLO1oSTUL/+vZorukaojeAdOpT/61e8b9Vzbt8L1ktMTaGPEJHw2BG/B5BCwBuw==", + "license": "MIT", + "dependencies": { + "@noble/secp256k1": "^3.1.0", + "@trystero-p2p/core": "0.25.3" + } + }, + "node_modules/@types/node": { + "version": "26.4.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.1.tgz", + "integrity": "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.3.0" + } + }, "node_modules/@types/parse-json": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", @@ -1163,6 +1262,12 @@ "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==", "license": "MIT" }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1187,6 +1292,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC" + }, "node_modules/hasown": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", @@ -1574,6 +1685,12 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "license": "MIT" }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -1620,6 +1737,26 @@ "node": ">=0.10.0" } }, + "node_modules/onnxruntime-common": { + "version": "1.27.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.27.0.tgz", + "integrity": "sha512-3KxL5wIVqa8Ex08jxSzncm9CMgw8CjOFyOQ7SxvG9o0cVLlhTNKXyIQuTbtX4tGPJEf73OER2xrjt4HJSBL4ow==", + "license": "MIT" + }, + "node_modules/onnxruntime-web": { + "version": "1.27.0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.27.0.tgz", + "integrity": "sha512-ogDLsqIozHZwifPuN37OproAo0byX6t43/bP8GzeZWBWD6MOGExswFAx3up4NS/vvWBOg2u2PXomDt3rMmdQSg==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.27.0", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -1685,6 +1822,12 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, "node_modules/postcss": { "version": "8.5.26", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", @@ -1731,6 +1874,29 @@ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", "license": "MIT" }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/react": { "version": "19.2.8", "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", @@ -1931,6 +2097,21 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/trystero": { + "version": "0.25.3", + "resolved": "https://registry.npmjs.org/trystero/-/trystero-0.25.3.tgz", + "integrity": "sha512-mm6Mzmm10OXKfvOA0tUG6XXqlQDIPdHg0//mEqA4ayrtdqiie4ZQpSluEp6074L+dCtotCfCn/B/CWLWavZK6Q==", + "license": "MIT", + "dependencies": { + "@trystero-p2p/nostr": "0.25.3" + } + }, + "node_modules/undici-types": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", + "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", + "license": "MIT" + }, "node_modules/use-sync-external-store": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", diff --git a/app/package.json b/app/package.json index 2eae818..7c0af5d 100644 --- a/app/package.json +++ b/app/package.json @@ -12,10 +12,13 @@ "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@mui/material": "^9.3.1", + "@mujoco/mujoco": "^3.11.0", "@react-three/fiber": "^9.7.0", + "onnxruntime-web": "^1.27.0", "react": "^19.2.8", "react-dom": "^19.2.8", "three": "^0.164.1", + "trystero": "^0.25.3", "zustand": "^5.0.15" }, "devDependencies": { diff --git a/app/public/assets/sfx/click_a.wav b/app/public/assets/sfx/click_a.wav new file mode 100644 index 0000000..22a64b8 --- /dev/null +++ b/app/public/assets/sfx/click_a.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f32c69bad5518fc3c04fac976b3d50579acfe0699512c8ceee91140338add875 +size 590 diff --git a/app/public/assets/sfx/click_b.wav b/app/public/assets/sfx/click_b.wav new file mode 100644 index 0000000..9c5818b --- /dev/null +++ b/app/public/assets/sfx/click_b.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4edce0301e1be6d384a20384d6059fa589af454cd1f31b94bef0c2bf7c349bef +size 1038 diff --git a/app/public/assets/sfx/step_a.wav b/app/public/assets/sfx/step_a.wav new file mode 100644 index 0000000..1f6d0d5 --- /dev/null +++ b/app/public/assets/sfx/step_a.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6afd9783e72a73276e975d5baba29845835fa326002c31546651f0f6dfb6ebd +size 4622 diff --git a/app/public/assets/sfx/step_b.wav b/app/public/assets/sfx/step_b.wav new file mode 100644 index 0000000..0b7df78 --- /dev/null +++ b/app/public/assets/sfx/step_b.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ea5271e219a8c2bc91ec9e253b71714b22e44a7f3e3fd1f5c33cea3435118a7 +size 4698 diff --git a/app/public/assets/sfx/step_c.wav b/app/public/assets/sfx/step_c.wav new file mode 100644 index 0000000..47c6cf2 --- /dev/null +++ b/app/public/assets/sfx/step_c.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3bdc8a240a9d20b1215e7d24787e0c478373fcf02c4971c919151dbb7113ef4 +size 4924 diff --git a/app/public/assets/sfx/step_d.wav b/app/public/assets/sfx/step_d.wav new file mode 100644 index 0000000..1659948 --- /dev/null +++ b/app/public/assets/sfx/step_d.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bad640d37d62a21589aa363dcfc763546bd548da260ec371841dcfb2f47ee2a5 +size 4824 diff --git a/app/public/assets/sfx/step_e.wav b/app/public/assets/sfx/step_e.wav new file mode 100644 index 0000000..5deef4d --- /dev/null +++ b/app/public/assets/sfx/step_e.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b06c21370d2ffffad065cb0b1a6c54343ec130b9073d291769d24f6ca60e3bb +size 4994 diff --git a/app/public/assets/sfx/thump_a.wav b/app/public/assets/sfx/thump_a.wav new file mode 100644 index 0000000..49b87bd --- /dev/null +++ b/app/public/assets/sfx/thump_a.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fc501c13cb17d31b5db880c12326848a09afbdf194b771afbdcefd922a5607f +size 19066 diff --git a/app/public/assets/sfx/thump_b.wav b/app/public/assets/sfx/thump_b.wav new file mode 100644 index 0000000..fbb852d --- /dev/null +++ b/app/public/assets/sfx/thump_b.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27597d19b0ffc351f0a56b83c8ea7a76aae3c97e6aeb4a9fdb57ebe0400cfe81 +size 17794 diff --git a/app/public/assets/sfx/thump_c.wav b/app/public/assets/sfx/thump_c.wav new file mode 100644 index 0000000..51d8329 --- /dev/null +++ b/app/public/assets/sfx/thump_c.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46205843156b8d4923ed392f213ccc2a326b67881b3f67dc4c082958a52fdf4f +size 23954 diff --git a/app/src/App.jsx b/app/src/App.jsx index f1cc288..fb42460 100644 --- a/app/src/App.jsx +++ b/app/src/App.jsx @@ -1,7 +1,8 @@ // App shell: layers in z order - scene canvas (1), halftone (2), CRT (5), -// HUD + touch overlay (9-12), BIOS readout (20), title menu (30), preboot -// veil (40). Also owns the pre-game device detection (gamepad, touch) and -// the preboot -> title -> enter flow. +// HUD + touch overlay (9-12), BIOS readout (20), title menu (30). Also owns +// the pre-game device detection (gamepad, touch) and the title -> enter +// flow. The title menu carries its own loading gate (single central +// spinner), so no separate preboot veil. import { useEffect } from "react"; import GameCanvas from "./scene/GameCanvas.jsx"; import { Halftone, CrtOverlay } from "./ui/Overlays.jsx"; @@ -9,9 +10,7 @@ import Hud from "./ui/Hud.jsx"; import TouchOverlay from "./ui/TouchOverlay.jsx"; import BiosOverlay from "./ui/BiosOverlay.jsx"; import TitleMenu from "./ui/TitleMenu.jsx"; -import Preboot from "./ui/Preboot.jsx"; import { useGame } from "./store.js"; -import { signed } from "./game/signed.js"; export default function App() { useEffect(() => { @@ -42,26 +41,13 @@ export default function App() { window.addEventListener("touchstart", armTouch, { once: true, passive: true }); if (params.get("touch") === "1") armTouch(); - // Preboot veil: hold the title page until its logo and the fonts are - // in (grey spinner meanwhile), capped so a broken asset can never wall - // the menu off. ?boot=1 skips the title entirely - testing hook. + // The title menu opens right away and holds its own loading gate + // (central spinner) until logo, fonts, duck stage and game boot are + // in. ?boot=1 skips the title entirely - testing hook. if (params.get("boot") === "1") { useGame.setState({ prebootDone: true, entered: true, menuOpen: false }); } else { - const img = new Image(); - img.src = signed("./assets/duck-head-mark.webp"); - const imgReady = new Promise((res) => { - if (img.complete && img.naturalWidth) res(); - else { - img.addEventListener("load", res, { once: true }); - img.addEventListener("error", res, { once: true }); - } - }); - const fontsReady = document.fonts?.ready ?? Promise.resolve(); - const cap = new Promise((res) => setTimeout(res, 2500)); - Promise.race([Promise.all([imgReady, fontsReady]), cap]).then(() => { - useGame.setState({ prebootDone: true, menuOpen: true }); - }); + useGame.setState({ prebootDone: true, menuOpen: true }); } return () => { @@ -81,7 +67,6 @@ export default function App() { - ); } diff --git a/app/src/game/arena.js b/app/src/game/arena.js index 201efbd..f4f4a69 100644 --- a/app/src/game/arena.js +++ b/app/src/game/arena.js @@ -243,6 +243,39 @@ function makeWallGridMaterial(alongX) { }); } +// Entrance draw-in cue schedule, for the ceremony's per-line audio blips. +// Replicates the shaders' hashed stagger EXACTLY (same hash, same t0 / +// spread constants, same line ids as drawLine's floor(rs + 0.5)), so each +// blip lands the instant its line starts drawing. Times are normalized to +// the respective reveal (0..1); the ceremony maps them to seconds with its +// own grid/wall reveal durations. `u` is the line's jitter, reused by the +// audio side for per-line pitch variation. The four walls share one id +// space, so their lines draw (and blip) in unison - one cue each. +const jitHash = (x) => { + const s = Math.sin(x * 127.1) * 43758.5453; + return s - Math.floor(s); +}; +export function entranceLineCues() { + const grid = []; + const walls = []; + // Floor: 6 section lines per axis (world x in {-1.5..1.5} step 0.6 maps + // to ids -2..3); the z family is offset by 57 in the shader. + for (let i = -2; i <= 3; i++) { + const jx = jitHash(i); + const jz = jitHash(i + 57); + grid.push({ at: 0.00 + jx * 0.30, u: jx }); + grid.push({ at: 0.05 + jz * 0.30, u: jz }); + } + // Walls: one horizontal section line (the y = 0 base, id 0) and 6 + // verticals (ids -2..3 offset by 31), per the 0.25 m wall height. + walls.push({ at: 0.00 + jitHash(0) * 0.30, u: jitHash(0) }); + for (let i = -2; i <= 3; i++) { + const j = jitHash(i + 31); + walls.push({ at: 0.30 + j * 0.30, u: j }); + } + return { grid, walls }; +} + // The four wall planes at their inner faces (three coords: MJCF x -> x, // MJCF y -> -z). Returns the meshes plus their materials (the ceremony and // the per-frame focus update both need the material list). diff --git a/app/src/game/audio.js b/app/src/game/audio.js new file mode 100644 index 0000000..13e95cc --- /dev/null +++ b/app/src/game/audio.js @@ -0,0 +1,581 @@ +// Game audio: one shared AudioContext behind a master gain, three buses +// (ambient / sfx / voice). Plain functions and maps, no classes, matching +// the imperative game core. The voice bus carries the existing quack and +// wheee (the stars of the mix); sfx carries footsteps / ball thumps / UI +// clicks / the entrance sweep; ambient carries the arcade-room hum bed. +// +// Samples (CC0, Kenney.nl): footsteps and ball thumps from "Impact Sounds", +// UI clicks from "Interface Sounds" - trimmed to mono 22.05 kHz wav in +// public/assets/sfx/. The CRT entrance sweep, the ambient hum and the +// roller rumble are synthesized (oscillators + filtered noise): zero +// payload and a better fit for the retro DA. +// +// Spatialization is plain Web Audio: the context listener follows the +// camera every frame and cheap equalpower PannerNodes act as emitters on +// the duck and the ball (footsteps, thumps and the roller rumble pan and +// attenuate with the chase cam). Voice and UI stay non-spatial. +import { signed } from "./signed.js"; + +// ── Master kill switch ──────────────────────────────────────────────── +// Kill switch: flip to true to silence the whole mix (every public entry +// point early-returns, master gain pinned to 0, context never resumed). +// Node-returning helpers (busNode, createEmitter) keep building their +// graph either way so callers stay untouched. +const SOUND_DISABLED = true; + +// ── Context, master, buses ──────────────────────────────────────────── +const MASTER_LEVEL = 0.9; +const BUS_LEVELS = { ambient: 1, sfx: 0.9, voice: 1 }; +const MUTE_KEY = "microduck-muted"; +let ctx = null; +let master = null; +const buses = {}; // name -> GainNode +let muted = false; +try { muted = localStorage.getItem(MUTE_KEY) === "1"; } catch { /* private mode */ } + +function unlockOnce() { + if (ctx?.state === "suspended") ctx.resume().catch(() => {}); +} + +export function audioCtx() { + if (ctx) return ctx; + ctx = new (window.AudioContext ?? window.webkitAudioContext)(); + master = ctx.createGain(); + master.gain.value = SOUND_DISABLED || muted ? 0 : MASTER_LEVEL; + master.connect(ctx.destination); + for (const [name, level] of Object.entries(BUS_LEVELS)) { + const g = ctx.createGain(); + g.gain.value = level; + g.connect(master); + buses[name] = g; + } + // Autoplay policy: resume on the first user gesture (the Waddle-in + // click normally lands here; keyboard covers the ?boot=1 test path). + // While sound is disabled the context is never resumed, so the + // suspended-state guards below keep every one-shot silent too. + if (!SOUND_DISABLED) { + window.addEventListener("pointerdown", unlockOnce, { passive: true }); + window.addEventListener("keydown", unlockOnce); + } + return ctx; +} + +export function busNode(name) { + audioCtx(); + return buses[name]; +} + +// ── Master mute (HUD toggle, persisted) ─────────────────────────────── +// Ramped over ~50 ms instead of a hard cut; the sources keep running so +// unmuting picks the mix back up exactly where it was. +export const isMuted = () => muted; + +export function setMuted(next) { + if (SOUND_DISABLED) return; + muted = !!next; + try { localStorage.setItem(MUTE_KEY, muted ? "1" : "0"); } catch { /* private mode */ } + if (!ctx) return; + master.gain.setTargetAtTime(muted ? 0 : MASTER_LEVEL, ctx.currentTime, 0.017); +} + +// ── Sample bank (decode-once cache, random takes per name) ──────────── +const SFX_TAKES = { step: 5, thump: 3, click: 2 }; +const bufCache = new Map(); // url -> Promise + +function bufferFor(url) { + let p = bufCache.get(url); + if (!p) { + p = fetch(url) + .then((r) => r.arrayBuffer()) + .then((ab) => audioCtx().decodeAudioData(ab)); + bufCache.set(url, p); + } + return p; +} + +const takeUrl = (name, i) => signed(`./assets/sfx/${name}_${"abcde"[i]}.wav`); + +export function preloadSfx() { + if (SOUND_DISABLED) return; + for (const [name, n] of Object.entries(SFX_TAKES)) { + for (let i = 0; i < n; i++) bufferFor(takeUrl(name, i)).catch(() => {}); + } +} + +// Fire-and-forget one-shot. `out` routes to an emitter panner (spatial); +// otherwise the sound lands on the flat sfx bus. +export function playSfx(name, { gain = 1, rate = 1, out = null } = {}) { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") return; // pre-gesture: stay silent, don't queue + const take = (Math.random() * SFX_TAKES[name]) | 0; + bufferFor(takeUrl(name, take)).then((buf) => { + const src = c.createBufferSource(); + src.buffer = buf; + src.playbackRate.value = rate; + const g = c.createGain(); + g.gain.value = gain; + src.connect(g); + g.connect(out ?? buses.sfx); + src.onended = () => g.disconnect(); + src.start(); + }).catch(() => {}); +} + +// Decoded playback for arbitrary URLs (the colourway voice banks): same +// cache, routed to a bus - replaces the old HTMLAudio chirp path so the +// quack sits behind the master gain like everything else. +export function playUrl(url, { bus = "voice", gain = 1, rate = 1 } = {}) { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") return; + bufferFor(url).then((buf) => { + const src = c.createBufferSource(); + src.buffer = buf; + src.playbackRate.value = rate; + const g = c.createGain(); + g.gain.value = gain; + src.connect(g); + g.connect(buses[bus]); + src.onended = () => g.disconnect(); + src.start(); + }).catch(() => {}); +} + +export function uiClick() { + playSfx("click", { gain: 0.16, rate: 0.95 + Math.random() * 0.1 }); +} + +// ── Spatial listener + emitters ─────────────────────────────────────── +// Listener follows the three.js camera (three world coords). Emitters are +// equalpower panners: cheap, and plenty for "the duck is over there". +const _fwd = { x: 0, y: 0, z: -1 }; + +export function updateListener(camera) { + if (!ctx || ctx.state === "suspended") return; + const l = ctx.listener; + const e = camera.matrixWorld.elements; + // Camera forward = -Z column of the world matrix, up = +Y column. + _fwd.x = -e[8]; _fwd.y = -e[9]; _fwd.z = -e[10]; + const t = ctx.currentTime; + if (l.positionX) { + l.positionX.setTargetAtTime(e[12], t, 0.02); + l.positionY.setTargetAtTime(e[13], t, 0.02); + l.positionZ.setTargetAtTime(e[14], t, 0.02); + l.forwardX.setTargetAtTime(_fwd.x, t, 0.02); + l.forwardY.setTargetAtTime(_fwd.y, t, 0.02); + l.forwardZ.setTargetAtTime(_fwd.z, t, 0.02); + l.upX.setTargetAtTime(e[4], t, 0.02); + l.upY.setTargetAtTime(e[5], t, 0.02); + l.upZ.setTargetAtTime(e[6], t, 0.02); + } else { + l.setPosition(e[12], e[13], e[14]); + l.setOrientation(_fwd.x, _fwd.y, _fwd.z, e[4], e[5], e[6]); + } +} + +export function createEmitter({ refDistance = 0.6 } = {}) { + const c = audioCtx(); + const panner = c.createPanner(); + panner.panningModel = "equalpower"; + panner.distanceModel = "inverse"; + panner.refDistance = refDistance; + panner.rolloffFactor = 1.1; + panner.connect(buses.sfx); + return { + node: panner, + setPosition(x, y, z) { + if (panner.positionX) { + const t = c.currentTime; + panner.positionX.setTargetAtTime(x, t, 0.03); + panner.positionY.setTargetAtTime(y, t, 0.03); + panner.positionZ.setTargetAtTime(z, t, 0.03); + } else { + panner.setPosition(x, y, z); + } + }, + }; +} + +// ── Ambient bed (synthesized arcade-room hum) ───────────────────────── +// Mains hum (60 Hz + weak 120 Hz octave) plus a slow-breathing bed of +// lowpassed noise. Sits VERY low in the mix. The whole bed runs through a +// duck filter + duck gain automated when the pause/title overlay opens. +const AMBIENT_LEVEL = 0.05; +const AMBIENT_DUCKED = 0.018; +let ambient = null; // { duckGain, duckFilter } + +export function startAmbient() { + if (SOUND_DISABLED || ambient) return; + const c = audioCtx(); + const duckFilter = c.createBiquadFilter(); + duckFilter.type = "lowpass"; + duckFilter.frequency.value = 18000; + const duckGain = c.createGain(); + duckGain.gain.value = 0; // fade in below + duckFilter.connect(duckGain); + duckGain.connect(buses.ambient); + + const hum = c.createOscillator(); + hum.type = "sine"; + hum.frequency.value = 60; + const humG = c.createGain(); + humG.gain.value = 0.5; + hum.connect(humG); + humG.connect(duckFilter); + + const hum2 = c.createOscillator(); + hum2.type = "triangle"; + hum2.frequency.value = 120; + const hum2G = c.createGain(); + hum2G.gain.value = 0.14; + hum2.connect(hum2G); + hum2G.connect(duckFilter); + + const noise = c.createBufferSource(); + noise.buffer = noiseBuffer(c, 2.0); + noise.loop = true; + const noiseF = c.createBiquadFilter(); + noiseF.type = "lowpass"; + noiseF.frequency.value = 260; + const noiseG = c.createGain(); + noiseG.gain.value = 0.5; + noise.connect(noiseF); + noiseF.connect(noiseG); + noiseG.connect(duckFilter); + + // Slow breathing on the noise bed (~0.08 Hz) so the room feels alive. + const lfo = c.createOscillator(); + lfo.frequency.value = 0.08; + const lfoG = c.createGain(); + lfoG.gain.value = 0.15; + lfo.connect(lfoG); + lfoG.connect(noiseG.gain); + + hum.start(); + hum2.start(); + noise.start(); + lfo.start(); + duckGain.gain.setTargetAtTime(AMBIENT_LEVEL, c.currentTime, 1.2); + ambient = { duckGain, duckFilter }; +} + +export function setAmbientDucked(ducked) { + if (!ambient) return; + const t = ctx.currentTime; + ambient.duckGain.gain.setTargetAtTime(ducked ? AMBIENT_DUCKED : AMBIENT_LEVEL, t, 0.25); + ambient.duckFilter.frequency.setTargetAtTime(ducked ? 300 : 18000, t, 0.25); +} + +function noiseBuffer(c, seconds) { + const n = (c.sampleRate * seconds) | 0; + const buf = c.createBuffer(1, n, c.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < n; i++) d[i] = Math.random() * 2 - 1; + return buf; +} + +// ── Materialize sweeps (phase-locked to the wireframe FX) ───────────── +// fx-wireframe.js runs two overlapping passes over totalS seconds (duck: +// 0.9 s): a wireframe scan line over the first 2/3 and a trailing +// solidify line over the last 2/3, BOTH driven by the same ease-out +// (1 - (1-x)^2): the line launches at full speed and decelerates into +// the top. The pitch of each layer follows that exact curve (sampled +// into setValueCurveAtTime), so the sweep rushes then settles exactly +// like the line the player watches - not a straight climb through it. +// +// scan [0 .. 2/3 T] square, 150 -> 1500 Hz along the fx ease +// solid [1/3 T .. T] triangle an octave down, same curve, trailing +// T resolve: sine drop thunk + soft high ping +// +// Props reuse the same voice via playPropSweep: their fx stretches the +// timeline by sqrt(size) (see fx-wireframe REF_SPAN), so the duration +// itself encodes the target's size - the sweep divides its pitch by +// that stretch, and big objects (arcade cabinet) materialize DEEPER +// and longer while small ones chirp through quickly. +const FX_EASE = (x) => 1 - (1 - x) * (1 - x); // fx-wireframe's ease() +const FX_BASE_S = 0.9; // fx TOTAL_S before size stretch + +function easedPitchCurve(f0, f1, n = 48) { + const arr = new Float32Array(n); + for (let i = 0; i < n; i++) arr[i] = f0 * (f1 / f0) ** FX_EASE(i / (n - 1)); + return arr; +} + +// One materialize voice. level scales every layer; pitchK divides the +// whole sweep's register (bigger target = lower); shimmer + ping are the +// duck's hero garnish, props skip them. +function materializeSweep(c, { totalS, level = 1, pitchK = 1, hero = true }) { + const T = Math.max(0.3, totalS); + const t0 = c.currentTime + 0.01; + const scanEnd = t0 + T * (2 / 3); + const solidStart = t0 + T * (1 / 3); + const tEnd = t0 + T; + const k = 1 / pitchK; + + const out = c.createGain(); + out.gain.value = level; + const tone = c.createBiquadFilter(); + tone.type = "lowpass"; + tone.frequency.value = 5200; // tame the squares' buzz, keep the bite + tone.connect(out); + out.connect(buses.sfx); + + // Static tick right as the scan cues. + const tick = c.createBufferSource(); + tick.buffer = noiseBuffer(c, 0.06); + const tickF = c.createBiquadFilter(); + tickF.type = "highpass"; + tickF.frequency.value = 2500; + const tickG = c.createGain(); + tickG.gain.setValueAtTime(0.1, t0); + tickG.gain.exponentialRampToValueAtTime(0.001, t0 + 0.06); + tick.connect(tickF); + tickF.connect(tickG); + tickG.connect(out); + tick.start(t0); + + // Scan pass: rising square riding the scan line's exact ease-out. + const scan = c.createOscillator(); + scan.type = "square"; + scan.frequency.setValueCurveAtTime( + easedPitchCurve(150 * k, 1500 * k), t0, T * (2 / 3), + ); + const scanG = c.createGain(); + scanG.gain.setValueAtTime(0, t0); + scanG.gain.linearRampToValueAtTime(0.14, t0 + 0.03); + scanG.gain.setValueAtTime(0.14, scanEnd - 0.05); + scanG.gain.exponentialRampToValueAtTime(0.001, scanEnd + 0.08); + scan.connect(scanG); + scanG.connect(tone); + scan.start(t0); + scan.stop(scanEnd + 0.1); + + // Solidify pass: same eased climb an octave down, trailing like the + // second line, swelling as the target fills in solid. + const solid = c.createOscillator(); + solid.type = "triangle"; + solid.frequency.setValueCurveAtTime( + easedPitchCurve(85 * k, 760 * k), solidStart, T * (2 / 3), + ); + const solidG = c.createGain(); + solidG.gain.setValueAtTime(0, solidStart); + solidG.gain.linearRampToValueAtTime(0.08, solidStart + 0.06); + solidG.gain.linearRampToValueAtTime(0.16, tEnd - 0.05); + solidG.gain.exponentialRampToValueAtTime(0.001, tEnd + 0.06); + solid.connect(solidG); + solidG.connect(tone); + solid.start(solidStart); + solid.stop(tEnd + 0.1); + + if (hero) { + // Hologram shimmer: airy bandpassed noise, centre frequency easing + // up with the reveal like everything else. + const shimmer = c.createBufferSource(); + shimmer.buffer = noiseBuffer(c, T); + const shimF = c.createBiquadFilter(); + shimF.type = "bandpass"; + shimF.frequency.setValueCurveAtTime( + easedPitchCurve(1800 * k, 5200 * k), t0, T, + ); + shimF.Q.value = 1.2; + const shimG = c.createGain(); + shimG.gain.setValueAtTime(0, t0); + shimG.gain.linearRampToValueAtTime(0.05, t0 + 0.1); + shimG.gain.setValueAtTime(0.05, tEnd - 0.15); + shimG.gain.linearRampToValueAtTime(0, tEnd); + shimmer.connect(shimF); + shimF.connect(shimG); + shimG.connect(out); + shimmer.start(t0); + } + + // Resolve: pitch-drop thunk right when the solidify line clears the + // top and the real materials land. Deeper for bigger targets. + const thunk = c.createOscillator(); + thunk.type = "sine"; + thunk.frequency.setValueAtTime(170 * k, tEnd); + thunk.frequency.exponentialRampToValueAtTime(62 * k, tEnd + 0.13); + const thunkG = c.createGain(); + thunkG.gain.setValueAtTime(hero ? 0.3 : 0.22, tEnd); + thunkG.gain.exponentialRampToValueAtTime(0.001, tEnd + 0.22); + thunk.connect(thunkG); + thunkG.connect(out); + thunk.start(tEnd); + thunk.stop(tEnd + 0.25); + + if (hero) { + const ping = c.createOscillator(); + ping.type = "sine"; + ping.frequency.value = 1320; + const pingG = c.createGain(); + pingG.gain.setValueAtTime(0.07, tEnd); + pingG.gain.exponentialRampToValueAtTime(0.001, tEnd + 0.3); + ping.connect(pingG); + pingG.connect(out); + ping.start(tEnd); + ping.stop(tEnd + 0.32); + ping.onended = () => out.disconnect(); + } else { + thunk.onended = () => out.disconnect(); + } +} + +// The duck's hero sweep (entrance and every respawn scan-up). +export function playEntranceSweep(totalS = 0.9) { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") return; + materializeSweep(c, { totalS, level: 1, pitchK: 1, hero: true }); +} + +// One prop materializing (arcade cabinet, boombox...). The fx stretches +// its timeline by sqrt(size), so recover that stretch from the duration +// and drop the register by it: a 2.2 s cabinet sweeps ~2.5x deeper than +// the duck, a duck-sized prop sounds like a quieter duck. A tiny random +// detune keeps staggered props from phasing into one thick chord. +export function playPropSweep(totalS = 0.9) { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") return; + const durK = Math.max(1, totalS / FX_BASE_S); + const detune = 2 ** ((Math.random() - 0.5) * 0.16); + materializeSweep(c, { + totalS, + level: 0.4, + pitchK: durK * detune, + hero: false, + }); +} + +// ── BIOS / menu one-shots (synthesized, retro POST language) ────────── +// All guarded on a suspended context: the BIOS replay only starts after +// the enter click (the unlock gesture), but a gamepad-only entry can +// leave the context locked - then these simply stay silent. + +// Single POST beep, the classic "one beep = all good". +export function playBiosBeep() { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") return; + const t0 = c.currentTime + 0.01; + const osc = c.createOscillator(); + osc.type = "square"; + osc.frequency.value = 940; + const g = c.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(0.08, t0 + 0.008); + g.gain.setValueAtTime(0.08, t0 + 0.1); + g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.16); + osc.connect(g); + g.connect(buses.sfx); + osc.start(t0); + osc.stop(t0 + 0.18); + osc.onended = () => g.disconnect(); +} + +// Teletype tick, one per printed POST line. Whisper-level. +export function playBiosTick() { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") return; + const t0 = c.currentTime; + const osc = c.createOscillator(); + osc.type = "square"; + osc.frequency.value = 1750 + Math.random() * 350; + const g = c.createGain(); + g.gain.setValueAtTime(0.02, t0); + g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.018); + osc.connect(g); + g.connect(buses.sfx); + osc.start(t0); + osc.stop(t0 + 0.02); + osc.onended = () => g.disconnect(); +} + +// Menu-confirm bloop (Waddle in / Resume / pad A): two rising square +// notes, C5 -> G5. This rides the very gesture that unlocks the context, +// so a suspended context gets one resume-then-play attempt. +export function playConfirmBloop() { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") { + c.resume().then(() => confirmNow(c)).catch(() => {}); + return; + } + confirmNow(c); +} + +function confirmNow(c) { + const t0 = c.currentTime + 0.01; + const tone = c.createBiquadFilter(); + tone.type = "lowpass"; + tone.frequency.value = 4200; + tone.connect(buses.sfx); + const osc = c.createOscillator(); + osc.type = "square"; + osc.frequency.setValueAtTime(523, t0); + osc.frequency.setValueAtTime(784, t0 + 0.07); + const g = c.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(0.13, t0 + 0.01); + g.gain.setValueAtTime(0.13, t0 + 0.12); + g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.2); + osc.connect(g); + g.connect(tone); + osc.start(t0); + osc.stop(t0 + 0.22); + osc.onended = () => tone.disconnect(); +} + +// ── Entrance line blips ─────────────────────────────────────────────── +// One tiny tick per grid/wall section line as it starts drawing in. `u` +// is the line's own draw jitter (0..1), reused as pitch variation so the +// flurry chirps instead of machine-gunning. Very low in the mix. +export function playLineBlip(u = 0.5) { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (c.state === "suspended") return; + const t0 = c.currentTime; + const osc = c.createOscillator(); + osc.type = "triangle"; + osc.frequency.value = 1400 * 2 ** (u * 0.9); // ~1.4-2.6 kHz across lines + const g = c.createGain(); + g.gain.setValueAtTime(0.05, t0); + g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.05); + osc.connect(g); + g.connect(buses.sfx); + osc.start(t0); + osc.stop(t0 + 0.06); + osc.onended = () => g.disconnect(); +} + +// ── Roller rumble (synthesized rolling-noise loop) ──────────────────── +// Bandpassed noise on the duck emitter; gain and a slight pitch follow +// ground speed, silent at rest. Built lazily on first use. +let rumble = null; // { gain, src } + +export function setRumble(level, out = null) { + if (SOUND_DISABLED) return; + const c = audioCtx(); + if (!rumble) { + if (level <= 0) return; + const src = c.createBufferSource(); + src.buffer = noiseBuffer(c, 1.5); + src.loop = true; + const f = c.createBiquadFilter(); + f.type = "bandpass"; + f.frequency.value = 110; + f.Q.value = 0.8; + const g = c.createGain(); + g.gain.value = 0; + src.connect(f); + f.connect(g); + g.connect(out?.node ?? buses.sfx); + src.start(); + rumble = { gain: g, src }; + } + const t = c.currentTime; + rumble.gain.gain.setTargetAtTime(Math.min(1, level) * 0.22, t, 0.08); + rumble.src.playbackRate.setTargetAtTime(0.85 + 0.5 * Math.min(1, level), t, 0.12); +} diff --git a/app/src/game/ceremony.js b/app/src/game/ceremony.js index 1e6e4c2..81d7a4f 100644 --- a/app/src/game/ceremony.js +++ b/app/src/game/ceremony.js @@ -14,6 +14,8 @@ // rl.js injects the world (rig, grid, camera reset) and the lock/flash // callbacks; this file never touches MuJoCo. +import { entranceLineCues } from "./arena.js"; + export const CAM_RESET_S = 0.9; export const RESPAWN_SCAN_AT = 0.8; // cue scan-up at 80% of the camera glide @@ -29,6 +31,9 @@ export function createCeremony({ getRig, grid, wallMats, syncRig, startCameraReset, setLocked, flashReset, + onScanCue = () => {}, + onLineCue = () => {}, + onPropCue = () => {}, }) { const ENTRANCE_TOTAL_S = Math.max( ENTRANCE_GRID_S, @@ -36,6 +41,19 @@ export function createCeremony({ ENTRANCE_FX_START_S + fx.TOTAL_S, ); + // Per-line audio cues for the entrance draw-in: normalized reveal times + // from arena.js (exact same hashed stagger as the shaders), mapped onto + // this timeline's grid/wall reveal windows. Entrance-only: respawns + // never redraw the arena. + const cues = entranceLineCues(); + const lineCues = [ + ...cues.grid.map((c) => ({ at: c.at * ENTRANCE_GRID_S, u: c.u })), + ...cues.walls.map((c) => ({ + at: ENTRANCE_WALL_DELAY_S + c.at * ENTRANCE_WALL_S, u: c.u, + })), + ].sort((a, b) => a.at - b.at); + let lineCueIdx = lineCues.length; // parked until startEntrance + let fxRig = null; let fxPrev = null; // Decorative props (addPropFx): each owns a wireframe FX bound to its @@ -67,6 +85,9 @@ export function createCeremony({ fx.start(); fxPrev = performance.now(); propsCue(); + // Sound cue riding the same trigger as the visual scan; the duration + // lets the sweep span the materialize exactly. + onScanCue(fx.TOTAL_S); } function propsCue() { const now = performance.now(); @@ -105,6 +126,10 @@ export function createCeremony({ if (p.at === null || now < p.at) continue; if (!p.started) { p.fx.start(); + // Audio twin, cued the frame this prop's scan actually starts; + // TOTAL_S carries the size-stretched duration so the sound can + // match both length and register. + onPropCue(p.fx.TOTAL_S); p.started = true; p.prev = now; continue; @@ -130,6 +155,7 @@ export function createCeremony({ if (entranceT0 !== null || entranceDone) return; entranceT0 = performance.now(); entranceFxCued = false; + lineCueIdx = 0; grid.material.uniforms.uReveal.value = 0; for (const m of wallMats) m.uniforms.uReveal.value = 0; } @@ -137,6 +163,11 @@ export function createCeremony({ function driveEntrance() { if (entranceT0 === null) return; const t = (performance.now() - entranceT0) / 1000; + // Fire the per-line blips as their lines start drawing in. + while (lineCueIdx < lineCues.length && lineCues[lineCueIdx].at <= t) { + onLineCue(lineCues[lineCueIdx].u); + lineCueIdx++; + } grid.material.uniforms.uReveal.value = clamp01(t / ENTRANCE_GRID_S); const wallR = clamp01((t - ENTRANCE_WALL_DELAY_S) / ENTRANCE_WALL_S); for (const m of wallMats) m.uniforms.uReveal.value = wallR; diff --git a/app/src/game/game.js b/app/src/game/game.js index 560f8fd..29acc8b 100644 --- a/app/src/game/game.js +++ b/app/src/game/game.js @@ -48,18 +48,25 @@ import { GamepadSource } from "./controls/gamepad.js"; import { TouchSource } from "./controls/touch.js"; import * as fx from "./fx/fx-wireframe.js"; import { createCeremony, CAM_RESET_S } from "./ceremony.js"; +import { + audioCtx, busNode, preloadSfx, playSfx, playUrl, updateListener, + createEmitter, startAmbient, setAmbientDucked, playEntranceSweep, + playPropSweep, playLineBlip, setRumble, +} from "./audio.js"; import { createBallActor } from "./ball-actor.js"; import { initGhosts } from "./ghosts.js"; import { makeInfiniteGrid, makeArenaWalls } from "./arena.js"; import { createBallVisual } from "./ball-visual.js"; import { useGame, gameApi, bootLine, bootNote, bootHalt } from "../store.js"; -// Physics + inference runtimes stay on the CDN, exactly like the pre-Vite -// app: mujoco.js resolves its .wasm sidecar relative to its own URL, and -// onnxruntime fetches its wasm from wasmPaths - neither ever touches the -// bundle. @vite-ignore keeps Rollup's static analysis out of it. -const MUJOCO_URL = "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@3.11.0/mujoco.js"; -const ORT_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.27.0/dist/ort.min.mjs"; +// Physics + inference runtimes are vendored npm dependencies (no CDN): +// everything visitors execute is built from package-lock-verified +// tarballs and served from the Space itself, closing the jsDelivr +// supply-chain surface. The .wasm binaries ride the bundle as hashed +// assets via Vite ?url imports; the JS modules stay dynamic imports so +// they land in their own lazy chunks like before. +import mujocoWasmUrl from "@mujoco/mujoco/mujoco.wasm?url"; +import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.wasm?url"; let bootStarted = false; @@ -123,15 +130,20 @@ async function boot({ scene, camera, renderer }) { ); }; - // ── Runtimes (CDN) ────────────────────────────────────────────────── + // ── Runtimes (vendored, lazy chunks) ───────────────────────────────── const [{ default: loadMujocoFactory }, ort] = await traced( "RUNTIME MODULES", Promise.all([ - import(/* @vite-ignore */ MUJOCO_URL), - import(/* @vite-ignore */ ORT_URL), + import("@mujoco/mujoco"), + // wasm-only build: the sessions only ever use the "wasm" execution + // provider, and the default entry would emit the 26 MB WebGPU (jsep) + // wasm into the dist for nothing. + import("onnxruntime-web/wasm"), ]), ); - ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.27.0/dist/"; + // The bundler build embeds its JS loader; only the .wasm binary is + // fetched at runtime, from our own hashed asset. + ort.env.wasm.wasmPaths = { wasm: ortWasmUrl }; ort.env.wasm.numThreads = 1; // static hosting sends no COOP/COEP headers // ── MJCF preparation ──────────────────────────────────────────────── @@ -243,7 +255,11 @@ async function boot({ scene, camera, renderer }) { // ── Boot physics + policy in parallel with the render rig ──────────── const [mujoco, { xml, meshFiles }, k] = await Promise.all([ - traced("MUJOCO WASM", loadMujocoFactory()), + traced("MUJOCO WASM", loadMujocoFactory({ + // Emscripten sidecar resolution: point at the Vite-emitted asset + // instead of a path relative to the module's own URL. + locateFile: (p) => (p.endsWith(".wasm") ? mujocoWasmUrl : p), + })), traced("PHYSICS MJCF", buildPhysicsXml("robot_allcollisions.xml")), traced("KINEMATICS", loadKinematics(`${MODEL_DIR}/kinematics.json`)), ]); @@ -348,6 +364,10 @@ async function boot({ scene, camera, renderer }) { standKeyId: mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_KEY.value, "STAND"), ballQposAdr: model.jnt("ball_freejoint").qposadr, ballDofAdr: model.jnt("ball_freejoint").dofadr, + // Foot bodies for the footstep audio heuristic (-1 when a variant + // has no ankles, e.g. if a future model renames them). + ankleIds: ["ankle_left", "ankle_right"].map( + (n) => mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY.value, n)), // Unactuated hinges (the roller variant's 4 passive wheels): not in // the obs or ctrl, but synced to the render rig so the wheels spin. extraJoints: kin.bodies @@ -356,8 +376,8 @@ async function boot({ scene, camera, renderer }) { }; } // Active-variant address block, swapped wholesale by activateLoco. - let { qposAdr, dofAdr, gyroAdr, trunkId, standKeyId, ballQposAdr, ballDofAdr, extraJoints } = - resolveAddrs(model, k); + let { qposAdr, dofAdr, gyroAdr, trunkId, standKeyId, ballQposAdr, ballDofAdr, extraJoints, + ankleIds } = resolveAddrs(model, k); // Locomotion variants stay resident once built (model + data + rig + // addresses); legs is registered when its render rig resolves below. @@ -678,6 +698,130 @@ async function boot({ scene, camera, renderer }) { return null; } + // ── Sim-driven audio (footsteps / roller rumble / ball impacts) ────── + // Footsteps use a per-foot height heuristic instead of MuJoCo contacts + // (the WASM bindings expose no contact array): each ankle's height + // RELATIVE to the lower ankle (the planted foot approximates the local + // ground, so the measure self-calibrates on the relief terrain), with + // lift/contact hysteresis and a per-foot debounce. Tap gain scales with + // the landing speed. Rollers get a speed-following rumble loop instead, + // and the ball thumps on velocity deltas between control steps. + const STEP_LIFT = 0.012; // m above the planted foot = foot in swing + const STEP_CONTACT = 0.005; // m: dropping below this while in swing = step + const STEP_DEBOUNCE_MS = 130; + const stepFeet = [ + { air: false, prevZ: 0, lastAt: 0 }, + { air: false, prevZ: 0, lastAt: 0 }, + ]; + const duckEmitter = createEmitter({ refDistance: 0.5 }); + const ballEmitter = createEmitter({ refDistance: 0.5 }); + const ballPrevV = [0, 0, 0]; + let ballPrevValid = false; + let ballThumpAt = 0; + // Body bumps: trunk velocity deltas gated on obstacle proximity (walls + // or prop collider footprints) so the walking gait's own accelerations + // (comparable in magnitude to a slow wall hit) never false-trigger. + // Duller than the ball thumps: same samples pitched way down. + const BUMP_DV = 0.35; // m/s per control step + const BUMP_DEBOUNCE_MS = 300; // rubbing a wall must not machine-gun + const BUMP_WALL_PAD = 0.16; // trunk half-width-ish reach to a wall + const bumpZones = propColliders().map((c) => { + const [px, py] = c.pos.split(" ").map(Number); + const [sx, sy] = c.size.split(" ").map(Number); + return { x: px, y: py, r: Math.hypot(sx, sy) + 0.14 }; + }); + const bumpPrevV = [0, 0, 0]; + let bumpPrevValid = false; + let bumpAt = 0; + function nearObstacle(x, y) { + if (Math.max(Math.abs(x), Math.abs(y)) > ARENA_HALF - BUMP_WALL_PAD) return true; + for (const z of bumpZones) { + if (Math.hypot(x - z.x, y - z.y) < z.r) return true; + } + return false; + } + + function stepAudioSim() { + const now = performance.now(); + if (loco === "legs" && !inputLocked && ankleIds[0] >= 0 && ankleIds[1] >= 0) { + const xpos = data.xpos; + const zL = xpos[ankleIds[0] * 3 + 2]; + const zR = xpos[ankleIds[1] * 3 + 2]; + const ground = Math.min(zL, zR); + for (let i = 0; i < 2; i++) { + const f = stepFeet[i]; + const z = i === 0 ? zL : zR; + const rel = z - ground; + const vz = (z - f.prevZ) / CTRL_DT; + f.prevZ = z; + if (rel > STEP_LIFT) { + f.air = true; + } else if (f.air && rel < STEP_CONTACT && vz < -0.02 && + now - f.lastAt > STEP_DEBOUNCE_MS) { + f.air = false; + f.lastAt = now; + const u = Math.min(1, Math.abs(vz) / 0.35); + playSfx("step", { + gain: 0.12 + 0.14 * u, + rate: 0.9 + Math.random() * 0.25, + out: duckEmitter.node, + }); + } + } + } + // Roller rumble: gain and slight pitch follow ground speed. + const speed = Math.hypot(data.qvel[0], data.qvel[1]); + setRumble( + loco === "rollers" && !inputLocked ? Math.min(1, speed / 0.5) : 0, + duckEmitter, + ); + // Body bumps: trunk |dv| against a nearby wall/prop. The proximity + // gate keeps gait/kick jerks (which rival slow wall hits) silent. + if (!inputLocked) { + const v = data.qvel; + if (bumpPrevValid) { + const dv = Math.hypot(v[0] - bumpPrevV[0], v[1] - bumpPrevV[1], v[2] - bumpPrevV[2]); + if (dv > BUMP_DV && now - bumpAt > BUMP_DEBOUNCE_MS && + nearObstacle(data.qpos[0], data.qpos[1])) { + bumpAt = now; + const u = Math.min(1, (dv - BUMP_DV) / 1.5); + playSfx("thump", { + gain: 0.12 + 0.3 * u, + rate: 0.55 + 0.15 * u + Math.random() * 0.06, // way below the ball's range + out: duckEmitter.node, + }); + } + } + bumpPrevV[0] = v[0]; bumpPrevV[1] = v[1]; bumpPrevV[2] = v[2]; + bumpPrevValid = true; + } else { + bumpPrevValid = false; + } + // Ball impacts: |dv| between control steps. Gravity alone accounts for + // ~0.2 m/s per 20 ms step; the 0.5 threshold clears it and rolling noise. + if (ballActive) { + const v = data.qvel; + const b = ballDofAdr; + if (ballPrevValid) { + const dv = Math.hypot( + v[b] - ballPrevV[0], v[b + 1] - ballPrevV[1], v[b + 2] - ballPrevV[2]); + if (dv > 0.5 && now - ballThumpAt > 90) { + ballThumpAt = now; + const u = Math.min(1, (dv - 0.5) / 3.5); // full at kick-grade hits + playSfx("thump", { + gain: 0.14 + 0.4 * u, + rate: 1.25 - 0.45 * u + Math.random() * 0.08, + out: ballEmitter.node, + }); + } + } + ballPrevV[0] = v[b]; ballPrevV[1] = v[b + 1]; ballPrevV[2] = v[b + 2]; + ballPrevValid = true; + } else { + ballPrevValid = false; + } + } + async function controlStep() { driveRelief(CTRL_DT); // kinematic terrain, written before the physics steps // Settle phase: ctrl frozen on the pose held at the fall (approximates @@ -694,6 +838,7 @@ async function boot({ scene, camera, renderer }) { applyGrabForce(); // mouse perturbation, fresh velocity every substep mujoco.mj_step(model, data); } + stepAudioSim(); // footsteps / rumble / ball thumps off the fresh state const death = poseIsDead(); if (death === "exploded") { @@ -925,7 +1070,7 @@ async function boot({ scene, camera, renderer }) { loco = name; scene.remove(rig.placer); ({ model, data, rig, trunkGroup, qposAdr, dofAdr, gyroAdr, trunkId, - standKeyId, ballQposAdr, ballDofAdr, extraJoints } = L); + standKeyId, ballQposAdr, ballDofAdr, extraJoints, ankleIds } = L); // The rig may have been built (or last shown) under another colourway. applyVariant(rig, currentVariant); scene.add(rig.placer); @@ -992,8 +1137,29 @@ async function boot({ scene, camera, renderer }) { if (!v && ball && !ballActive) spawnBall({ fromQueue: true }); }, flashReset: () => {}, + // Audio twins of the wireframe materialize FX (entrance and respawns): + // the duck's hero sweep spans the FX's exact duration and follows its + // ease-out; each prop's scan gets its own smaller, size-pitched sweep + // the frame it starts; each arena line drawing in gets a tiny blip. + onScanCue: (durS) => playEntranceSweep(durS), + onPropCue: (durS) => playPropSweep(durS), + onLineCue: (u) => playLineBlip(u), }); + // ── Ambient bed lifecycle ───────────────────────────────────────────── + // The Waddle-in click latches `entered` and doubles as the unlock + // gesture; the hum starts there and ducks whenever the pause/title + // overlay comes back up. fireImmediately covers ?boot=1 (already + // entered by the time the game boots). + useGame.subscribe((s) => s.entered, (entered) => { + if (!entered) return; + audioCtx(); + preloadSfx(); + startAmbient(); + }, { fireImmediately: true }); + useGame.subscribe((s) => s.menuOpen, (open) => setAmbientDucked(open), + { fireImmediately: true }); + const { group: ballGroup, mesh: ballMesh } = createBallVisual(renderer); scene.add(ballGroup); ball = createBallActor({ @@ -1291,19 +1457,12 @@ async function boot({ scene, camera, renderer }) { let padJaw = 0; const CHIRP_TAKES = "abcdefghijkl"; const VOICE_BANK = { classic: "duck1", charcoal: "duck2", purple: "duck3", blue: "duck4" }; - const chirpCache = new Map(); function playChirp() { const bank = VOICE_BANK[currentVariant] ?? "duck1"; const take = CHIRP_TAKES[(Math.random() * CHIRP_TAKES.length) | 0]; - const url = signed(`./assets/voices/${bank}/chirp_${take}.wav`); - let a = chirpCache.get(url); - if (!a) { - a = new Audio(url); - a.volume = 0.7; - chirpCache.set(url, a); - } - a.currentTime = 0; - a.play().catch(() => {}); + // Decoded through the shared context on the voice bus (used to be a + // bare HTMLAudio element outside the master gain). + playUrl(signed(`./assets/voices/${bank}/chirp_${take}.wav`), { gain: 0.7 }); } const quackLoud = () => { quackAt = performance.now(); @@ -1385,7 +1544,7 @@ async function boot({ scene, camera, renderer }) { } async function startWheee() { stopWheee({ silent: true }); // a re-press replaces the current ride - wheeeCtx ??= new (window.AudioContext ?? window.webkitAudioContext)(); + wheeeCtx ??= audioCtx(); // shared game context, ride lands on the voice bus if (wheeeCtx.state === "suspended") wheeeCtx.resume().catch(() => {}); const bank = VOICE_BANK[currentVariant] ?? "duck1"; const take = WHEEE_TAKES[(Math.random() * WHEEE_TAKES.length) | 0]; @@ -1399,7 +1558,7 @@ async function boot({ scene, camera, renderer }) { } if (wheeeRide !== ride) return; // released (or replaced) during decode const gain = wheeeCtx.createGain(); - gain.connect(wheeeCtx.destination); + gain.connect(busNode("voice")); const t0 = wheeeCtx.currentTime + 0.02; // The loop is steady-state audio (no authored attack): a ~20 ms fade-in // makes a clean note onset instead of a click. Constant gain after that. @@ -1548,6 +1707,14 @@ async function boot({ scene, camera, renderer }) { syncRig(); syncJaw(); ghosts?.update(); + // Spatial audio follows the movers: listener on the camera, emitters + // on the duck trunk and the ball (MJCF Z-up -> three Y-up). + updateListener(camera); + duckEmitter.setPosition(data.qpos[0], data.qpos[2], -data.qpos[1]); + if (ballActive) { + const q = data.qpos; + ballEmitter.setPosition(q[ballQposAdr], q[ballQposAdr + 2], -q[ballQposAdr + 1]); + } controls.update(); updateChaseCam(); ceremony.drive(); diff --git a/app/src/game/ghosts.js b/app/src/game/ghosts.js index d4f3b53..c718a05 100644 --- a/app/src/game/ghosts.js +++ b/app/src/game/ghosts.js @@ -9,9 +9,23 @@ // on the private Space those need the ?__sign JWT that only rl.js knows // how to append, so all rig helpers arrive through init parameters. -const TRYSTERO_URL = "https://esm.run/trystero@0.25.3/nostr"; const APP_ID = "microduck-sandbox"; const ROOM = "lobby"; +// Explicit relay list instead of Trystero's default appId-seeded pick. +// The deterministic subset that "microduck-sandbox" draws from the default +// pool rotted away (2026-09 audit: 3 relays dead, 1 rejecting ephemeral +// events, 1 rate-limiting), which silently killed ghost discovery in prod. +// These were verified live to accept AND route Trystero's ephemeral +// events; the warnOnRelayFailure path logs any that decay later. +const RELAY_URLS = [ + "wss://relay.damus.io", + "wss://nos.lol", + "wss://nostr.tegila.com.br", + "wss://staging.yabu.me", + "wss://social.amanah.eblessing.co", + "wss://relay-rpi.edufeed.org", + "wss://strfry.shock.network", +]; const MAX_GHOSTS = 3; const SEND_HZ = 15; const GHOST_OPACITY = 0.35; @@ -73,8 +87,10 @@ export async function initGhosts(env) { }; let room; try { - const { joinRoom } = await import(/* @vite-ignore */ TRYSTERO_URL); - room = joinRoom({ appId: APP_ID }, ROOM); + // Vendored npm dep (was esm.run); dynamic so it stays a lazy chunk + // loaded only when the ghost session actually starts. + const { joinRoom } = await import("trystero/nostr"); + room = joinRoom({ appId: APP_ID, relayConfig: { urls: RELAY_URLS } }, ROOM); } catch (e) { console.warn("ghosts disabled (signaling unavailable):", e); return noop; diff --git a/app/src/game/vendor/zzfx.js b/app/src/game/vendor/zzfx.js new file mode 100644 index 0000000..5672d26 --- /dev/null +++ b/app/src/game/vendor/zzfx.js @@ -0,0 +1,60 @@ +/* eslint-disable */ +// ZzFX - Zuper Zmall Zound Zynth - v1.3.2 by Frank Force +// https://github.com/KilledByAPixel/ZzFX +// +// MIT License - Copyright (c) 2019 Frank Force +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software. The above copyright notice and this +// permission notice shall be included in all copies or substantial portions +// of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +// KIND. +// +// Local adaptation (soundboard experiment): the upstream ZzFXMicro build +// creates its own AudioContext and plays straight to the hardware output. +// This build splits synthesis (zzfxG, byte-for-byte the upstream v1.3.2 +// sample generator) from playback (zzfxP), and playback goes through a +// caller-provided AudioContext + destination node, so candidate sounds ride +// the game's shared master gain / sfx bus like the runtime sounds do. + +export const zzfxR = 44100; // sample rate +export const zzfxV = 0.3; // default volume scale + +// Generate samples for a ZzFX sound. Parameter order: +// volume, randomness, frequency, attack, sustain, release, shape, shapeCurve, +// slide, deltaSlide, pitchJump, pitchJumpTime, repeatTime, noise, modulation, +// bitCrush, delay, sustainVolume, decay, tremolo, filter +export const zzfxG = (p=1,k=.05,b=220,e=0,r=0,t=.1,q=0,D=1,u=0,y=0,v=0,z=0,l=0,E=0,A=0,F=0,c=0,w=1,m=0,B=0,N=0)=>{ + let M=Math,d=2*M.PI,R=zzfxR,G=u*=500*d/R/R,C=b*=(1-k+2*k*M.random(k=[]))*d/R, + g=0,H=0,a=0,n=1,I=0,J=0,f=0,h=N<0?-1:1,x=d*h*N*2/R,L=M.cos(x),Z=M.sin,K=Z(x)/4,O=1+K, + X=-2*L/O,Y=(1-K)/O,P=(1+h*L)/2/O,Q=-(h+L)/O,S=P,T=0,U=0,V=0,W=0; + e=R*e+9;m*=R;r*=R;t*=R;c*=R;y*=500*d/R**3;A*=d/R;v*=d/R;z*=R;l=R*l|0;p*=zzfxV; + for(h=e+m+r+t+c|0;aa?0:(az&&(b+=v,C+=v,n=0), + !l||++I%l||(b=C,u=G,n=n||1); + return k; +}; + +// Play generated samples through the given context/destination. +export function zzfxP(ctx, destination, samples) { + const buf = ctx.createBuffer(1, samples.length, zzfxR); + buf.getChannelData(0).set(samples); + const src = ctx.createBufferSource(); + src.buffer = buf; + src.connect(destination); + src.start(); + return src; +} + +// Convenience: synthesize + play in one call. +export const zzfx = (ctx, destination, ...params) => zzfxP(ctx, destination, zzfxG(...params)); diff --git a/app/src/main.jsx b/app/src/main.jsx index 9145fd1..29eb2c4 100644 --- a/app/src/main.jsx +++ b/app/src/main.jsx @@ -1,8 +1,14 @@ +import { lazy, Suspense } from "react"; import { createRoot } from "react-dom/client"; import { ThemeProvider } from "@mui/material/styles"; import CssBaseline from "@mui/material/CssBaseline"; import { theme } from "./theme.js"; -import App from "./App.jsx"; + +// ?soundboard=1: standalone audio A/B experiment page instead of the game +// (lazy on both sides so the soundboard never pulls the game bundle in). +const App = new URLSearchParams(location.search).get("soundboard") === "1" + ? lazy(() => import("./ui/Soundboard.jsx")) + : lazy(() => import("./App.jsx")); // Build tag: bump to change the bundle's content hash, e.g. to bust a stale // edge-cached asset URL on the HF Space. @@ -14,6 +20,8 @@ console.info(`Microduck build ${BUILD_TAG}`); createRoot(document.getElementById("root")).render( - + + + , ); diff --git a/app/src/ui/BiosOverlay.jsx b/app/src/ui/BiosOverlay.jsx index d643bef..065e955 100644 --- a/app/src/ui/BiosOverlay.jsx +++ b/app/src/ui/BiosOverlay.jsx @@ -9,6 +9,7 @@ import { useEffect, useRef, useState } from "react"; import Box from "@mui/material/Box"; import { keyframes } from "@mui/material/styles"; import { useGame, gameApi, bootLog } from "../store.js"; +import { playBiosBeep, playBiosTick } from "../game/audio.js"; import { INK, MONO } from "../theme.js"; const postBlink = keyframes` @@ -48,6 +49,10 @@ export default function BiosOverlay() { const store = useGame.getState; setVisible(true); useGame.setState({ biosVisible: true }); + // POST beep: the replay only starts after the enter click (the audio + // unlock gesture), and the synth no-ops if the context is still locked + // (gamepad-only entry). + playBiosBeep(); const postEl = postRef.current; // Seeded LCG: the replay rhythm is random-feeling but identical on // every load - real POST screens burst through most checks and stall @@ -64,6 +69,7 @@ export default function BiosOverlay() { if (entry.halt) el.className = "halt"; postEl.appendChild(el); els.set(entry, el); + playBiosTick(); // whisper-level teletype tick per printed line if (entry.status === null && !bootDone && !failed) { // Honest mode: show the stage label and hold while it's really // in flight, cursor blinking via CSS. @@ -113,6 +119,7 @@ export default function BiosOverlay() { const ready = document.createElement("div"); ready.textContent = "READY."; postEl.appendChild(ready); + playBiosTick(); await sleep(500); setOff(true); // Wait out the 0.45 s opacity transition BEFORE cueing the draw-in: diff --git a/app/src/ui/Hud.jsx b/app/src/ui/Hud.jsx index e2e4442..41daf9e 100644 --- a/app/src/ui/Hud.jsx +++ b/app/src/ui/Hud.jsx @@ -19,6 +19,7 @@ import Box from "@mui/material/Box"; import { keyframes } from "@mui/material/styles"; import { useGame, gameApi } from "../store.js"; import { VARIANT_LABELS, VARIANT_SWATCH_HEX } from "../game/variants.js"; +import { uiClick, isMuted, setMuted } from "../game/audio.js"; import { ORANGE, MONO } from "../theme.js"; import { ANTON, COMIC_INK, CREAM } from "./comic.jsx"; @@ -157,6 +158,34 @@ function HudPlate({ caption, captionSide = "left", captionFill = "cream", childr ); } +// Speaker icon in the same square-stroke language as the back arrow: +// body + cone always, waves when live, a hard ink cross when muted. +function SpeakerIcon({ muted }) { + return ( + + + {muted ? ( + + ) : ( + <> + + + + )} + + ); +} + function BackArrowIcon() { return ( useGame.setState({ menuOpen: true })} + onClick={() => { uiClick(); useGame.setState({ menuOpen: true }); }} sx={{ ...hudHitSx, "&:hover": { @@ -231,9 +260,12 @@ function BackButton() { ); } -const SHOP_URL = "https://store.pollen-robotics.com/collections/microduck"; +export const SHOP_URL = "https://store.pollen-robotics.com/collections/microduck"; -function PreorderButton() { +// Exported: the title/pause overlay renders the same plate in the same +// spot, so the pause fade reads as the button staying put, not two +// different buttons swapping. +export function PreorderButton({ sx }) { const locoWant = useGame((s) => s.locoWant); const text = useScramble(locoWant === "rollers" ? "Pre-order pack" : "Pre-order"); return ( @@ -241,13 +273,14 @@ function PreorderButton() { caption="Shop" captionSide="right" captionFill="orange" - sx={{ position: "fixed", top: "1.25rem", right: "1.5rem", zIndex: 10 }} + sx={{ position: "fixed", top: "1.25rem", right: "1.5rem", zIndex: 10, ...sx }} > uiClick()} sx={{ ...hudHitSx, background: ORANGE, @@ -301,7 +334,7 @@ function Quickbar() { title={label} aria-label={`${label} colours`} aria-pressed={selected} - onClick={() => gameApi.setVariant?.(name)} + onClick={() => { uiClick(); gameApi.setVariant?.(name); }} sx={{ appearance: "none", width: CELL_H, // square cell inside frame + padding @@ -351,7 +384,7 @@ function Quickbar() { component="button" type="button" aria-pressed={selected} - onClick={() => gameApi.requestLoco?.(name)} + onClick={() => { uiClick(); gameApi.requestLoco?.(name); }} sx={{ ...hudHitSx, px: "1.05rem", @@ -370,10 +403,49 @@ function Quickbar() { })} + {/* Sound is fully disabled for now (SOUND_DISABLED in audio.js); + re-enable this toggle together with that flag. */} + {/* */} ); } +// Mute / unmute panel: same cartouche language as the other groups. The +// toggle ramps audio.js's master gain (~50 ms) and persists; unmuting +// plays the HUD click as confirmation (muting stays silent, obviously). +function SoundToggle() { + const [muted, setMutedState] = useState(isMuted); + const toggle = () => { + const next = !muted; + setMuted(next); + setMutedState(next); + if (!next) uiClick(); + }; + return ( + + + + + + ); +} + function Telemetry() { const t = useGame((s) => s.telemetry); const odo = t.odo < 1000 ? `${t.odo.toFixed(1)}M` : `${(t.odo / 1000).toFixed(2)}KM`; diff --git a/app/src/ui/MenuDuck.jsx b/app/src/ui/MenuDuck.jsx new file mode 100644 index 0000000..f6144ab --- /dev/null +++ b/app/src/ui/MenuDuck.jsx @@ -0,0 +1,350 @@ +// Title-menu duck stage: the simulated twin, sitting on the title screen +// like the vitrine landing's colour module - head aims at the pointer +// (idle glances at the camera when it's quiet), click/tap quacks. No +// physics, no policies: just the shared rig posed and micro-animated. +// +// Why a separate rig instead of showing the game scene: the boot +// dramaturgy keeps the in-game duck hidden until the BIOS readout cues +// the entrance scan-up, so the title screen needs its own duck. Geometry +// is free anyway - duck.js caches the GLB module-wide, so this rig and +// the game's share the same buffers. +// +// The stage is a lazy module singleton: built once on first open, then +// re-attached on every pause. The rAF loop only runs while attached. +import { useEffect, useRef } from "react"; +import Box from "@mui/material/Box"; +import * as THREE from "three"; +import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js"; +import { + loadKinematics, buildRig, setJoint, setJawOpen, applyPose, + SITTING_POSE, groundFullBody, MODEL_DIR, +} from "../game/duck.js"; +import { VARIANTS, DEFAULT_VARIANT, materialHookFor, applyVariant } from "../game/variants.js"; +import { createWireframeFx } from "../game/fx/fx-wireframe.js"; +import { playUrl } from "../game/audio.js"; +import { signed } from "../game/signed.js"; +import { useGame } from "../store.js"; + +// Aim calibration, verbatim from the vitrine's duck3d/scene.js: positive +// head_pitch is head-down on the mjlab model, so screen-up subtracts. +const SIGN_YAW = 1; +const SIGN_PITCH = -1; +const SPREAD_YAW = 0.55; // rad of head yaw across half the stage width +const SPREAD_PITCH = 0.32; // rad of head pitch across half the stage height + +// Quack envelope: openness eases toward a target instead of replaying a +// fixed curve, so clicking mid-quack never snaps the jaw backwards. +const QUACK_HOLD_S = 0.3; +const QUACK_ATTACK_TAU = 0.04; +const QUACK_RELEASE_TAU = 0.09; + +// The vitrine's aim framing, loosened for the menu column: the duck fills +// ~2/3 of the frame height instead of edge to edge. The look height is +// tuned WITH the zoom to put the feet (y=0) ~18% above the frame's bottom +// edge - floating well clear of the shortcut strip. +const CAM_POS = [0.28, 0.2, 0.43]; +const CAM_LOOK = [0, 0.122, 0]; +const CAM_ZOOM = 0.78; +const FOV_DEG = 32; + +// Same voice banks as the game's quack (game.js VOICE_BANK). +const VOICE_BANK = { classic: "duck1", charcoal: "duck2", purple: "duck3", blue: "duck4" }; +const CHIRP_TAKES = "abcdefghijkl"; + +const clamp = (x, a, b) => Math.min(b, Math.max(a, x)); +const rand = (a, b) => a + Math.random() * (b - a); + +let stagePromise = null; +let liveStage = null; +let stageReady = false; + +function getStage() { + if (!stagePromise) { + stagePromise = buildStage() + .then((s) => { + liveStage = s; + stageReady = true; + return s; + }) + .catch((e) => { + // Still flip ready: the title screen must not spin forever when + // WebGL / assets fail - it just shows without the duck. + stageReady = true; + throw e; + }); + } + return stagePromise; +} + +// Title-screen loading gate: the menu holds a spinner until the stage's +// assets are in (kinematics + GLB + rig build), so the content reveal +// and the duck's entrance scan cue together instead of the duck popping +// into an already-settled screen. +export const preloadMenuDuck = () => getStage(); +export const isMenuDuckReady = () => stageReady; + +async function buildStage() { + const scene = new THREE.Scene(); + const camera = new THREE.PerspectiveCamera(FOV_DEG, 1, 0.05, 20); + camera.position.set( + ...CAM_LOOK.map((l, i) => l + (CAM_POS[i] - l) / CAM_ZOOM), + ); + camera.lookAt(...CAM_LOOK); + + const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); + renderer.setClearColor(0x000000, 0); + renderer.setPixelRatio(Math.min(2, window.devicePixelRatio)); + // Same output pipeline the variant palette was calibrated against. + renderer.toneMapping = THREE.ACESFilmicToneMapping; + const el = renderer.domElement; + el.style.position = "absolute"; + el.style.inset = "0"; + el.style.width = "100%"; + el.style.height = "100%"; + // Anti-flicker: invisible until the first frame has been presented. + el.style.opacity = "0"; + el.style.transition = "opacity 0.45s ease"; + + const pmrem = new THREE.PMREMGenerator(renderer); + scene.environment = pmrem.fromScene(new RoomEnvironment()).texture; + scene.environmentIntensity = 0.25; + + // Vitrine light rig: strong white key, soft fill, warm orange rim. + scene.add(new THREE.AmbientLight(0xffffff, 0.45)); + const key = new THREE.DirectionalLight(0xffffff, 1.25); + key.position.set(2, 4, 2); + scene.add(key); + const fill = new THREE.DirectionalLight(0xffffff, 0.4); + fill.position.set(-2, 2, 1.5); + scene.add(fill); + const rim = new THREE.DirectionalLight(0xffb366, 0.7); + rim.position.set(0, 3, -2); + scene.add(rim); + + const k = await loadKinematics(`${MODEL_DIR}/kinematics.json`); + let appliedVariant = useGame.getState().variant ?? DEFAULT_VARIANT; + if (!VARIANTS[appliedVariant]) appliedVariant = DEFAULT_VARIANT; + const rig = await buildRig(k, { + materialForMesh: materialHookFor(VARIANTS[appliedVariant]), + }); + // Face the camera: MJCF forward is +X; the placer yaw turns it to +Z. + rig.placer.rotation.y = -Math.PI / 2; + scene.add(rig.placer); + applyPose(rig, SITTING_POSE); + groundFullBody(rig); + + // Vitrine-style entrance: the duck materializes with the wireframe + // scan-up the first time the menu shows. Hidden (clip at floor level) + // until the stage is attached, then start() cues the scan; once done + // the fx restores the real materials and is dropped for good - pause + // reopens show the solid duck immediately. + // + // Shader pre-warm: the scan cycles through three material states, each + // compiling its GPU program on the frame it first renders - the plain + // PBR originals (restored when the scan finishes), the per-mesh clip + // clones (unique customProgramCacheKey each, so ~30 separate PBR + // compiles), and the wireframe ShaderMaterial (only drawn once the + // scan is running). Left alone, those compiles land mid-animation as + // driver-timed freezes. The canvas is still detached and invisible + // here, so render each state once now: solid first, then a mid-scan + // frame (wires on, clones clipping), then rewind to hidden. + renderer.render(scene, camera); + let entranceFx = createWireframeFx(); + entranceFx.init({ THREE, scene, root: rig.placer, camera, renderer, hidden: true }); + entranceFx.setProgress(0.5); + renderer.render(scene, camera); + entranceFx.setProgress(0); + let entranceStarted = false; + + const headPivot = rig.joints.get("head_yaw").body; + const headWorld = new THREE.Vector3(); + const camDir = new THREE.Vector3(); + + // ── Pointer → aim state ─────────────────────────────────────────────── + const ndc = new THREE.Vector2(0, 0); + let mountEl = null; + let lastT = 0; + let lastMouseT = -Infinity; + let hasFocus = document.hasFocus(); + let mouseInside = true; + let az = 0, el2 = 0; + let attention = 0; + const o1 = rand(0, 6.3), o2 = rand(0, 6.3); + let quackHoldUntil = -Infinity; + let quackOpen = 0; + + const onPointerMove = (e) => { + if (!mountEl) return; + const r = mountEl.getBoundingClientRect(); + if (!r.width || !r.height) return; + ndc.x = clamp(((e.clientX - r.left) / r.width) * 2 - 1, -2, 2); + ndc.y = clamp(-(((e.clientY - r.top) / r.height) * 2 - 1), -2, 2); + lastMouseT = lastT; + mouseInside = true; + }; + const onBlur = () => { hasFocus = false; }; + const onFocus = () => { hasFocus = true; }; + const onMouseLeave = () => { mouseInside = false; }; + const onMouseEnter = () => { mouseInside = true; }; + // Any click on the title screen quacks, not just the stage box: the + // overlay owns the whole viewport while the menu is up, and the quack + // never swallows the event (buttons underneath still do their thing). + const onPointerDown = () => quack(); + + function quack() { + quackHoldUntil = lastT + QUACK_HOLD_S; + const bank = VOICE_BANK[appliedVariant] ?? "duck1"; + const take = CHIRP_TAKES[(Math.random() * CHIRP_TAKES.length) | 0]; + // The click that lands here is a user gesture, so this also unlocks + // the shared AudioContext on the very first interaction. + playUrl(signed(`./assets/voices/${bank}/chirp_${take}.wav`), { gain: 0.7 }); + } + + function step(dt, t) { + lastT = t; + headPivot.getWorldPosition(headWorld); + camDir.copy(camera.position).sub(headWorld); + const azCam = Math.atan2(camDir.x, camDir.z); + const elCam = Math.atan2(camDir.y, Math.hypot(camDir.x, camDir.z)); + + // Attention 0..1: eases toward 1 while the page is focused, the + // pointer is around and moved recently; lazy camera glances otherwise. + const engaged = hasFocus && mouseInside && t - lastMouseT < 3.0; + attention += ((engaged ? 1 : 0) - attention) * (1 - Math.exp(-dt / 0.3)); + + const azAim = azCam + ndc.x * SPREAD_YAW; + const elAim = elCam * 0.5 + ndc.y * SPREAD_PITCH; + const azIdle = azCam + 0.45 * Math.sin(0.21 * t + o1) * Math.sin(0.09 * t + o2) * 2; + const elIdle = elCam * 0.5 + 0.1 * Math.sin(0.4 * t + o2); + const azT = azIdle + (azAim - azIdle) * attention; + const elT = elIdle + (elAim - elIdle) * attention; + const kSmooth = 1 - Math.exp(-dt * (2.5 + 7.5 * attention)); + az += (azT - az) * kSmooth; + el2 += (elT - el2) * kSmooth; + + const breathe = Math.sin(t * 1.4) * 0.025; + setJoint(rig, "neck_pitch", SITTING_POSE.neck_pitch + breathe); + setJoint(rig, "head_yaw", SIGN_YAW * az); + setJoint(rig, "head_pitch", SITTING_POSE.head_pitch + SIGN_PITCH * el2); + setJoint(rig, "head_roll", 0.3 * SIGN_YAW * (az - azCam)); + + const quackTarget = t < quackHoldUntil ? 1 : 0; + const tau = quackTarget > quackOpen ? QUACK_ATTACK_TAU : QUACK_RELEASE_TAU; + quackOpen += (quackTarget - quackOpen) * (1 - Math.exp(-dt / tau)); + setJawOpen(rig, quackOpen); + + if (entranceFx) { + if (!entranceStarted) { + entranceFx.start(); + entranceStarted = true; + } + entranceFx.update(dt); + if (entranceFx.isDone()) { + entranceFx.dispose(); + entranceFx = null; + } + } + + // Colourway follows the in-game duck (store.variant), fading live. + // Deferred while the entrance scan holds its clip-material clones: + // an applyVariant mid-scan would repaint clones that get thrown away + // on restore. The sync lands on the first frame after the scan. + const v = useGame.getState().variant; + if (!entranceFx && v !== appliedVariant && VARIANTS[v]) { + appliedVariant = v; + applyVariant(rig, v); + } + + renderer.render(scene, camera); + if (el.style.opacity === "0") el.style.opacity = "1"; + } + + // ── Attach / detach (rAF only runs while a mount hosts the canvas) ──── + let raf = 0; + let prevNow = 0; + const loop = (now) => { + raf = requestAnimationFrame(loop); + const dt = Math.min((now - prevNow) / 1000, 0.05); + prevNow = now; + step(dt, now / 1000); + }; + + function resize() { + if (!mountEl) return; + const w = mountEl.clientWidth; + const h = mountEl.clientHeight; + if (!w || !h) return; + camera.aspect = w / h; + camera.updateProjectionMatrix(); + renderer.setSize(w, h); + } + const resizeObserver = new ResizeObserver(resize); + + function attach(mount) { + if (!mount || mountEl === mount) return; + detach(); + mountEl = mount; + mount.appendChild(el); + resizeObserver.observe(mount); + resize(); + window.addEventListener("pointermove", onPointerMove); + window.addEventListener("pointerdown", onPointerDown); + window.addEventListener("blur", onBlur); + window.addEventListener("focus", onFocus); + document.addEventListener("mouseleave", onMouseLeave); + document.addEventListener("mouseenter", onMouseEnter); + prevNow = performance.now(); + raf = requestAnimationFrame(loop); + } + function detach() { + if (!mountEl) return; + cancelAnimationFrame(raf); + resizeObserver.disconnect(); + window.removeEventListener("pointermove", onPointerMove); + window.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("blur", onBlur); + window.removeEventListener("focus", onFocus); + document.removeEventListener("mouseleave", onMouseLeave); + document.removeEventListener("mouseenter", onMouseEnter); + el.remove(); + mountEl = null; + } + + const stage = { attach, detach, quack, step }; + // Deterministic hook for automated verification, same spirit as the + // game's window.rl: rAF pauses in background tabs, so tests drive + // frames by hand. + window.__menuDuck = stage; + return stage; +} + +export default function MenuDuck({ sx }) { + const hostRef = useRef(null); + + useEffect(() => { + let disposed = false; + getStage() + .then((stage) => { + if (disposed) return; + if (hostRef.current) stage.attach(hostRef.current); + }) + .catch((e) => console.warn("menu duck disabled:", e)); + return () => { + disposed = true; + liveStage?.detach(); + }; + }, []); + + return ( + + ); +} diff --git a/app/src/ui/Preboot.jsx b/app/src/ui/Preboot.jsx deleted file mode 100644 index 281cb67..0000000 --- a/app/src/ui/Preboot.jsx +++ /dev/null @@ -1,54 +0,0 @@ -// Pre-boot veil: covers everything until the title page's logo and fonts -// are in, so the menu never pops in half-assembled. Light grey spinner, -// centered on the ink. -import { useEffect, useState } from "react"; -import Box from "@mui/material/Box"; -import { keyframes } from "@mui/material/styles"; -import { useGame } from "../store.js"; -import { INK } from "../theme.js"; - -const spin = keyframes`to { transform: rotate(360deg); }`; - -export default function Preboot() { - const prebootDone = useGame((s) => s.prebootDone); - const [gone, setGone] = useState(false); - - useEffect(() => { - if (!prebootDone) return; - const t = setTimeout(() => setGone(true), 300); - return () => clearTimeout(t); - }, [prebootDone]); - - if (gone) return null; - return ( - - - - ); -} diff --git a/app/src/ui/Soundboard.jsx b/app/src/ui/Soundboard.jsx new file mode 100644 index 0000000..7b4b221 --- /dev/null +++ b/app/src/ui/Soundboard.jsx @@ -0,0 +1,368 @@ +// Soundboard experiment page (?soundboard=1): trigger and A/B-compare every +// game sound - the CURRENT runtime implementation (straight from audio.js, +// exact same code paths, non-spatial) against a ZzFX-synthesized candidate. +// Throwaway experiment: plain CSS, no game boot, additive only. +import { useEffect, useRef, useState } from "react"; +import { + audioCtx, busNode, preloadSfx, playSfx, playUrl, uiClick, + startAmbient, setRumble, playEntranceSweep, playPropSweep, playLineBlip, + playBiosBeep, playBiosTick, playConfirmBloop, +} from "../game/audio.js"; +import { signed } from "../game/signed.js"; +import { zzfx } from "../game/vendor/zzfx.js"; + +// Bus levels mirrored from audio.js BUS_LEVELS; the master volume slider +// rescales the (module-private) bus gains through busNode(), which is safe +// here because the game never mounts on this page. +const BUS_DEFAULTS = { ambient: 1, sfx: 0.9, voice: 1 }; + +// ZzFX candidate presets. Parameter order: +// [volume, randomness, frequency, attack, sustain, release, shape, shapeCurve, +// slide, deltaSlide, pitchJump, pitchJumpTime, repeatTime, noise, modulation, +// bitCrush, delay, sustainVolume, decay, tremolo, filter] +// Shapes: 0 sin, 1 triangle, 2 saw, 3 tan, 4 noise, 5 square (duty=shapeCurve/2). +export const ZZFX_PRESETS = { + // Soft noise-burst tap, quick pitch drop, mirrors the Kenney step takes. + footstepTap: [1.4, .3, 120, .001, .01, .05, 4, 1.9, -12, , , , , 1.3, , .1, , .5, .02], + // Duller, breathier alternative take (more noise, lower). + footstepSoft: [1.1, .4, 85, .001, .008, .04, 4, 2.2, -8, , , , , 2, , .2, , .45, .015], + // Round sine drop with a fast slide: hollow bouncing-ball body. + ballThump: [2, .15, 210, .002, .02, .16, 0, 2.4, -30, , , , , .3, , , , .8, .08], + // Same family an octave-ish down, more noise: duller body bump. + bodyBump: [1.7, .2, 90, .002, .03, .19, 0, 2.9, -15, , , , , 1, , .3, , .7, .11], + // Tiny triangle tick around 1.1 kHz. + uiClick: [.5, .2, 1100, .001, .005, .02, 1, 1.4, , , , , , , , , , .6, .01], + // Two rising square notes C5 -> G5 (pitchJump +261 Hz at 70 ms). + confirmBloop: [.7, 0, 523, .005, .12, .08, 5, 1, , , 261, .07, , , , , , .8, .02], + // Classic single POST beep, steady 940 Hz square. + biosBeep: [.4, 0, 940, .004, .1, .05, 5, 1, , , , , , , , , , .9, .01], + // Whisper teletype tick, high square with slight randomness. + biosTick: [.25, .2, 1850, .001, .004, .014, 5, 1, , , , , , , , , , .5, .005], + // Per-line scan chirp ~1.9 kHz triangle; randomness spreads the flurry. + scanBlip: [.35, .25, 1900, .001, .01, .04, 1, 1, , , , , , , , , , .6, .01], + // Rising saw sweep + noise shimmer + long release: sweep approximation. + entranceSweep: [1, 0, 150, .05, .5, .3, 2, 1, 11, .4, , , , .35, , .15, , .8, .2], +}; + +// Resume-then-run wrapper: every trigger lands in a user gesture, so a +// suspended context gets one resume attempt before the sound fires (the +// runtime helpers silently no-op on a suspended context). +async function armed(fn) { + const c = audioCtx(); + if (c.state === "suspended") { + try { await c.resume(); } catch { return; } + } + fn(); +} + +// ZzFX candidates land on the sfx bus: same master gain as the runtime. +const playZ = (params) => zzfx(audioCtx(), busNode("sfx"), ...params); + +const CHIRP_TAKES = "abcdefghijkl"; + +export default function Soundboard() { + const [vol, setVol] = useState(1); + const [ambientOn, setAmbientOn] = useState(false); + const [rumbleOn, setRumbleOn] = useState(false); + const [wheeeOn, setWheeeOn] = useState(false); + const wheeeRide = useRef(null); + const chirpIdx = useRef(0); + + useEffect(() => { + audioCtx(); + preloadSfx(); + }, []); + + // Master volume: rescale all three bus gains (ambient stays at 0 while + // its loop toggle is off - startAmbient() has no runtime stop hook, so + // the toggle gates the whole ambient bus instead). + useEffect(() => { + audioCtx(); + for (const [name, base] of Object.entries(BUS_DEFAULTS)) { + const scale = name === "ambient" && !ambientOn ? 0 : vol; + busNode(name).gain.value = base * scale; + } + }, [vol, ambientOn]); + + const toggleAmbient = () => armed(() => { + if (!ambientOn) startAmbient(); + setAmbientOn((v) => !v); + }); + + const toggleRumble = () => armed(() => { + setRumble(rumbleOn ? 0 : 0.7); + setRumbleOn((v) => !v); + }); + + // Wheee reference loop: minimal version of the game's ride (loop take a, + // voice bus, short fades). Token in the ref guards the decode race. + const toggleWheee = () => armed(async () => { + const c = audioCtx(); + const ride = wheeeRide.current; + if (ride) { + wheeeRide.current = null; + setWheeeOn(false); + if (ride.src) { + ride.gain.gain.setTargetAtTime(0, c.currentTime, 0.05); + try { ride.src.stop(c.currentTime + 0.3); } catch { /* ended */ } + } + return; + } + const next = {}; + wheeeRide.current = next; + setWheeeOn(true); + let buf; + try { + const res = await fetch(signed("./assets/voices/duck1/wheee_loop_a.wav")); + buf = await c.decodeAudioData(await res.arrayBuffer()); + } catch { + if (wheeeRide.current === next) { wheeeRide.current = null; setWheeeOn(false); } + return; + } + if (wheeeRide.current !== next) return; // toggled off during decode + const gain = c.createGain(); + gain.connect(busNode("voice")); + const t0 = c.currentTime + 0.02; + gain.gain.setValueAtTime(0, t0); + gain.gain.linearRampToValueAtTime(0.7, t0 + 0.02); + const src = c.createBufferSource(); + src.buffer = buf; + src.loop = true; + src.connect(gain); + src.start(t0); + Object.assign(next, { src, gain }); + }); + + const playQuack = () => { + const take = CHIRP_TAKES[chirpIdx.current++ % CHIRP_TAKES.length]; + playUrl(signed(`./assets/voices/duck1/chirp_${take}.wav`), { gain: 0.7 }); + }; + + // One-shot rows: name, category, note, current trigger, zzfx candidates. + const rows = [ + { + name: "Footstep", cat: "sampled", note: "step_a-e, random take, in-game gain/rate spread", + current: () => playSfx("step", { gain: 0.2, rate: 0.9 + Math.random() * 0.25 }), + zz: [["tap", ZZFX_PRESETS.footstepTap], ["soft", ZZFX_PRESETS.footstepSoft]], + }, + { + name: "Ball thump", cat: "sampled", note: "thump_a-c, mid-strength kick", + current: () => playSfx("thump", { gain: 0.34, rate: 1.05 + Math.random() * 0.08 }), + zz: [["thump", ZZFX_PRESETS.ballThump]], + }, + { + name: "Body bump", cat: "sampled", note: "thump takes pitched down to ~0.57", + current: () => playSfx("thump", { gain: 0.27, rate: 0.57 + Math.random() * 0.06 }), + zz: [["bump", ZZFX_PRESETS.bodyBump]], + }, + { + name: "UI click", cat: "sampled", note: "click_a/b via uiClick()", + current: () => uiClick(), + zz: [["click", ZZFX_PRESETS.uiClick]], + }, + { + name: "Confirm bloop", cat: "synth", note: "menu confirm, C5 -> G5 squares", + current: () => playConfirmBloop(), + zz: [["bloop", ZZFX_PRESETS.confirmBloop]], + }, + { + name: "BIOS beep", cat: "synth", note: "POST beep, 940 Hz square", + current: () => playBiosBeep(), + zz: [["beep", ZZFX_PRESETS.biosBeep]], + }, + { + name: "BIOS tick", cat: "synth", note: "teletype tick per POST line", + current: () => playBiosTick(), + zz: [["tick", ZZFX_PRESETS.biosTick]], + }, + { + name: "Scan blip", cat: "synth", note: "per-line entrance blip, random pitch", + current: () => playLineBlip(Math.random()), + zz: [["blip", ZZFX_PRESETS.scanBlip]], + }, + { + name: "Entrance sweep", cat: "synth", note: "3-layer materialize sweep + thunk + ping (0.9 s)", + current: () => playEntranceSweep(0.9), + zz: [["sweep", ZZFX_PRESETS.entranceSweep]], + }, + { + name: "Prop sweep (small)", cat: "synth", note: "duck-sized prop materialize (0.9 s, quieter, no garnish)", + current: () => playPropSweep(0.9), + zz: null, + }, + { + name: "Prop sweep (cabinet)", cat: "synth", note: "big prop: size-stretched 2.2 s, register dropped by the stretch", + current: () => playPropSweep(2.2), + zz: null, + }, + { + name: "Quack", cat: "voice", note: "reference only, chirp takes a-l round-robin", + current: playQuack, + zz: null, + }, + ]; + + const loops = [ + { + name: "Ambient bed", cat: "synth", note: "arcade-room hum loop; ZzFX n/a (already synth)", + on: ambientOn, toggle: toggleAmbient, + }, + { + name: "Roller rumble", cat: "synth", note: "rolling-noise loop at 0.7 speed; ZzFX n/a (already synth)", + on: rumbleOn, toggle: toggleRumble, + }, + { + name: "Wheee", cat: "voice", note: "reference only, loop take a on the voice bus", + on: wheeeOn, toggle: toggleWheee, + }, + ]; + + return ( +
+ +
+

Microduck Soundboard

+

+ A/B: current runtime implementation vs ZzFX candidate. First click unlocks audio. +

+ +
+ +
+
+ SoundCategoryCurrentZzFX candidate +
+ {rows.map((r) => ( +
+ + {r.name} + {r.note} + + {r.cat} + + + + + {r.zz + ? r.zz.map(([label, params]) => ( + + )) + : n/a (voice reference)} + +
+ ))} +
+ +

Loops

+
+ {loops.map((l) => ( +
+ + {l.name} + {l.note} + + {l.cat} + + + + n/a +
+ ))} +
+
+ ); +} + +const CSS = ` +/* The game's index.html pins body { overflow: hidden } for the canvas; + this page is a document, so re-enable normal scrolling. */ +html, body { height: auto; overflow: auto; } +#root { height: auto; } +.sb-root { + min-height: 100vh; + background: #faf8f2; + color: #101018; + font: 15px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + padding: 2.2rem clamp(1rem, 5vw, 4rem) 4rem; +} +.sb-head h1 { + font-family: 'Anton', 'Arial Narrow', Impact, sans-serif; + font-size: clamp(2rem, 5vw, 3.2rem); + text-transform: uppercase; + letter-spacing: 0.02em; + margin: 0; + color: #101018; + -webkit-text-stroke: 1px #101018; +} +.sb-sub { margin: 0.3rem 0 1.2rem; opacity: 0.75; } +.sb-vol { + display: inline-flex; align-items: center; gap: 0.7rem; + border: 2px solid #101018; background: #fff; + padding: 0.5rem 0.9rem; box-shadow: 4px 4px 0 #101018; + margin-bottom: 1.6rem; font-weight: 700; +} +.sb-vol input { accent-color: #ff7a2f; width: 200px; } +.sb-h2 { + font-family: 'Anton', 'Arial Narrow', Impact, sans-serif; + text-transform: uppercase; margin: 2rem 0 0.6rem; +} +.sb-grid { border: 2px solid #101018; background: #fff; box-shadow: 6px 6px 0 #101018; } +.sb-row { + display: grid; + grid-template-columns: minmax(220px, 1.6fr) 110px 130px minmax(160px, 1fr); + align-items: center; gap: 0.8rem; + padding: 0.55rem 0.9rem; + border-bottom: 1px solid rgba(16, 16, 24, 0.18); +} +.sb-row:last-child { border-bottom: none; } +.sb-row-head { + font-weight: 700; text-transform: uppercase; font-size: 12px; + background: #101018; color: #faf8f2; +} +.sb-name { display: flex; flex-direction: column; font-weight: 700; } +.sb-name small { font-weight: 400; opacity: 0.6; font-size: 11px; } +.sb-cat { + font-style: normal; font-size: 11px; font-weight: 700; + text-transform: uppercase; padding: 2px 7px; border: 1.5px solid #101018; +} +.sb-cat-sampled { background: #ffe9db; } +.sb-cat-synth { background: #e5eeff; } +.sb-cat-voice { background: #fff3b0; } +.sb-btn { + font: inherit; font-weight: 700; text-transform: uppercase; font-size: 12px; + border: 2px solid #101018; padding: 0.35rem 0.9rem; cursor: pointer; + box-shadow: 3px 3px 0 #101018; background: #faf8f2; color: #101018; + margin: 2px 6px 2px 0; +} +.sb-btn:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 #101018; } +.sb-btn:focus-visible { outline: 3px solid #ff7a2f; outline-offset: 2px; } +.sb-btn-zz { background: #ff7a2f; color: #101018; } +.sb-btn-cur.sb-on { background: #101018; color: #faf8f2; } +.sb-na { opacity: 0.5; font-size: 12px; } +@media (max-width: 700px) { + .sb-row { grid-template-columns: 1fr; gap: 0.3rem; } + .sb-row-head { display: none; } +} +`; diff --git a/app/src/ui/TitleMenu.jsx b/app/src/ui/TitleMenu.jsx index 0f345fc..2ea320d 100644 --- a/app/src/ui/TitleMenu.jsx +++ b/app/src/ui/TitleMenu.jsx @@ -13,8 +13,11 @@ import Typography from "@mui/material/Typography"; import { keyframes, styled } from "@mui/material/styles"; import { useGame } from "../store.js"; import { signed } from "../game/signed.js"; +import { playConfirmBloop } from "../game/audio.js"; import { INK, ORANGE, MONO } from "../theme.js"; -import { ComicButton, ComicTitle, HalftoneRamp, ANTON } from "./comic.jsx"; +import { ComicButton, ComicTitle, HalftoneRamp, ANTON, CREAM } from "./comic.jsx"; +import MenuDuck, { preloadMenuDuck, isMenuDuckReady } from "./MenuDuck.jsx"; +import { PreorderButton } from "./Hud.jsx"; const rowIn = keyframes` from { transform: translateY(12px); opacity: 0; } @@ -24,7 +27,15 @@ const brandIn = keyframes` from { transform: translateY(10px) scale(0.94); opacity: 0; } to { transform: none; opacity: 1; } `; - +// Title-screen blink for the "press Enter" prompt - a soft pulse, not a +// hard arcade strobe, so it invites rather than nags. +const promptPulse = keyframes` + from { opacity: 0.8; } + to { opacity: 0.18; } +`; +const spin = keyframes` + to { transform: rotate(360deg); } +`; // One soft ease, small travel, ~80 ms between rows - staged, not showy. const row = (delay, name = rowIn) => ({ animation: `${name} 0.55s cubic-bezier(0.22, 1, 0.36, 1) both`, @@ -49,37 +60,60 @@ const Kbd = styled("kbd")(({ round }) => ({ boxShadow: "0 0 0 2px rgba(255, 255, 255, 0.82)", })); -const TILES = { +// Arcade-style cheat strip pinned at the bottom of the title screen: one +// keycap group + label per move, scannable in a second. The CTA is the +// screen's centre of gravity - players enter first and learn in game. +const SHORTCUTS = { kb: [ - { caps: "cluster-arrows", name: "Move", hint: "arrows or ZQSD" }, - { caps: ["A", "E"], name: "Kick", hint: "left / right" }, - { caps: ["R"], name: "Sit", hint: "tap again to stand" }, - { caps: ["G"], name: "Pick up", hint: "beak to the ground" }, - { caps: ["C"], name: "Camera", hint: "toggle chase" }, - { caps: ["Space"], name: "Reset", hint: "fresh start" }, + { caps: ["\u2191\u2190\u2193\u2192"], name: "Move" }, + { caps: ["A", "E"], name: "Kick" }, + { caps: ["R"], name: "Sit" }, + { caps: ["G"], name: "Pick up" }, + { caps: ["C"], name: "Camera" }, + { caps: ["Space"], name: "Reset" }, ], pad: [ - { caps: ["LS"], name: "Move", hint: "left stick" }, - { caps: ["LB", "RB"], name: "Kick", hint: "left / right" }, - { caps: ["Y"], name: "Head", hint: "sticks move the head" }, - { caps: ["RS"], name: "Camera", hint: "orbit" }, - { caps: ["X", "\u2193"], name: "Sit", hint: "tap again to stand" }, + { caps: ["LS"], name: "Move" }, + { caps: ["LB", "RB"], name: "Kick" }, + { caps: ["Y"], name: "Head" }, + { caps: ["RS"], name: "Camera" }, + { caps: ["X", "\u2193"], name: "Sit" }, ], touch: [ - { caps: ["Stick"], name: "Move", hint: "left thumb" }, - { caps: ["A"], round: true, name: "Kick", hint: "tap it" }, - { caps: ["B"], round: true, name: "Quack", hint: "hold for beak" }, + { caps: ["Stick"], name: "Move" }, + { caps: ["A"], round: true, name: "Kick" }, + { caps: ["B"], round: true, name: "Quack" }, ], }; const HINTS = { - kb: "drag to orbit \u00b7 scroll to zoom", + kb: "ZQSD works too \u00b7 drag to orbit \u00b7 scroll to zoom", pad: "A ground pick \u00b7 RT quack \u00b7 hold LT wheee \u00b7 R3 chase", touch: "drag to orbit \u00b7 pinch to zoom", }; +// Per-colourway screen accent: the title fill and the halftone pool +// follow the duck on stage. Cream keeps the landing's brand orange (the +// classic duck's trim colour); lavender and sky use the press-kit swatch +// hexes (shared with the vitrine picker); graphite's swatch is too dark +// for type on ink, so it wears the palette's light warm gray instead. +const VARIANT_ACCENTS = { + classic: ORANGE, + charcoal: "#b9b5ae", + purple: "#bfa9cf", + blue: "#a9dbe8", +}; + +// #rrggbb -> rgba() at the halftone's alpha. +const tint = (hex, a) => + `rgba(${parseInt(hex.slice(1, 3), 16)}, ${parseInt(hex.slice(3, 5), 16)}, ${parseInt(hex.slice(5, 7), 16)}, ${a})`; + function closeMenu() { useGame.setState({ menuOpen: false }); if (!useGame.getState().entered) useGame.setState({ entered: true }); + // Menu-confirm bloop. On the first entry the `entered` latch above has + // just created the shared AudioContext inside this very gesture, so the + // bloop rides the unlock (the synth resume-retries if still suspended). + playConfirmBloop(); } export default function TitleMenu() { @@ -87,9 +121,101 @@ export default function TitleMenu() { const entered = useGame((s) => s.entered); const padConnected = useGame((s) => s.padConnected); const touchMode = useGame((s) => s.touchMode); + const variant = useGame((s) => s.variant); + const bootDone = useGame((s) => s.bootDone); + const bootFailed = useGame((s) => s.bootFailed); const [closing, setClosing] = useState(false); const prevOpen = useRef(menuOpen); + // Touch devices and narrow (mobile-sized) screens skip the 3D stage + // entirely: no duck column, and the GLB is never even downloaded. The + // width check matches the layout's md breakpoint, so the stage never + // renders where the column would stack under the text anyway. Everyone + // else holds a spinner until the stage's assets are in, so the content + // reveal and the duck's entrance scan cue together. The stage is a + // module singleton, so pause reopens resolve instantly (no second + // spinner). + const [wide, setWide] = useState( + () => window.matchMedia("(min-width: 900px)").matches, + ); + useEffect(() => { + const mq = window.matchMedia("(min-width: 900px)"); + const onChange = () => setWide(mq.matches); + mq.addEventListener("change", onChange); + return () => mq.removeEventListener("change", onChange); + }, []); + const showDuck = !touchMode && wide; + const [duckReady, setDuckReady] = useState(isMenuDuckReady); + useEffect(() => { + if (!showDuck || duckReady) return; + let on = true; + preloadMenuDuck() + .catch(() => {}) + .then(() => { if (on) setDuckReady(true); }); + return () => { on = false; }; + }, [showDuck, duckReady]); + + // The display face too: Anton is the screen's voice (title, CTA, + // strip) and would otherwise FOUT in after the reveal. It loads + // lazily on first use, so nudge it explicitly - the content is gated + // and would never request it. Timeout so a stuck font never wedges + // the menu behind the spinner. + const [fontsReady, setFontsReady] = useState( + () => !!document.fonts?.check?.("1rem Anton"), + ); + useEffect(() => { + if (fontsReady) return; + let on = true; + const done = () => { if (on) setFontsReady(true); }; + const anton = document.fonts?.load + ? document.fonts.load("1rem Anton") + : Promise.resolve(); + const allFonts = document.fonts?.ready ?? Promise.resolve(); + Promise.all([anton, allFonts]).then(done, done); + const t = setTimeout(done, 4000); + return () => { on = false; clearTimeout(t); }; + }, [fontsReady]); + + // The brand lockup images too (formerly the preboot veil's job): the + // corner chrome is part of the gated reveal, so the logo must not pop + // in after it. Capped so a broken asset never wedges the menu. + const [brandReady, setBrandReady] = useState(false); + useEffect(() => { + if (brandReady) return; + let on = true; + const done = () => { if (on) setBrandReady(true); }; + const load = (src) => + new Promise((res) => { + const img = new Image(); + img.src = signed(src); + if (img.complete && img.naturalWidth) res(); + else { + img.addEventListener("load", res, { once: true }); + img.addEventListener("error", res, { once: true }); + } + }); + Promise.all([ + load("./assets/duck-head-mark.webp"), + load("./assets/duck-head-mark-open.webp"), + ]).then(done, done); + const t = setTimeout(done, 2500); + return () => { on = false; clearTimeout(t); }; + }, [brandReady]); + + // The game core too: it boots eagerly behind the title screen (MuJoCo + // WASM, scene geometry, policy sessions), saturating the main thread + // in ~10-40 ms chunks for a couple of seconds. Revealing the menu + // mid-boot made the duck's entrance scan stutter (profiled: the scan + // window sat inside the boot's busy region), so the spinner holds + // until the boot settles - the reveal then animates on a free thread + // and Waddle-in is instant. bootFailed releases the gate: the halt + // screen owns the viewport at that point. + const ready = + (duckReady || !showDuck) && + fontsReady && + brandReady && + (bootDone || bootFailed); + // Keep the overlay mounted through the 0.35 s closing fade. useEffect(() => { const was = prevOpen.current; @@ -124,12 +250,65 @@ export default function TitleMenu() { return () => window.removeEventListener("keydown", onKey); }, []); + // Gamepad twin of the handler above: A (button 0) enters / resumes + // through the same closeMenu() as the CTA click; Start (9) or Select (8) + // reopens the overlay in-game, like Escape. Polled with a light rAF loop + // because the game's own gamepad source only exists once the core has + // booted (and its actions are game-facing). Edge state persists across + // the open/close transition, so one press fires exactly one action. + useEffect(() => { + const prev = { enter: false, menu: false }; + // The A press that closes the menu is applied one frame LATE on + // purpose: closing unlocks the game inputs synchronously, and the + // in-game gamepad source polls in the same rAF round - if it sees the + // press only after the unlock, its own A edge fires (groundPick). The + // one-frame delay guarantees it polls the press at least once while + // the pause lock still gates it, so by the unlock frame its edge + // state already knows the button is down and the entering press is + // swallowed. + let enterPending = false; + let raf; + const poll = () => { + raf = requestAnimationFrame(poll); + if (enterPending) { + enterPending = false; + if (useGame.getState().menuOpen) closeMenu(); + } + // Same pad preference as controls/gamepad.js: standard mapping first. + const pads = [...(navigator.getGamepads?.() ?? [])].filter((p) => p && p.connected); + const gp = pads.find((p) => p.mapping === "standard") ?? pads[0]; + if (!gp) { + prev.enter = false; + prev.menu = false; + return; + } + const enter = !!gp.buttons[0]?.pressed; + const menu = !!(gp.buttons[9]?.pressed || gp.buttons[8]?.pressed); + const enterEdge = enter && !prev.enter; + const menuEdge = menu && !prev.menu; + prev.enter = enter; + prev.menu = menu; + const s = useGame.getState(); + if (enterEdge && s.menuOpen) { + enterPending = true; + return; + } + if (menuEdge && !s.menuOpen && s.entered && !s.biosVisible) + useGame.setState({ menuOpen: true }); + }; + raf = requestAnimationFrame(poll); + return () => cancelAnimationFrame(raf); + }, []); + if (!menuOpen && !closing) return null; // A plugged-in gamepad wins over the touch tutorial. const tutorialVariant = padConnected ? "pad" : touchMode ? "touch" : "kb"; - const tiles = TILES[tutorialVariant]; + const shortcuts = SHORTCUTS[tutorialVariant]; const ctaLabel = entered ? "Resume" : "Waddle in"; + // Blinking key prompt under the CTA; touch has no key to press. + const enterHint = padConnected ? "press A" : touchMode ? null : "press Enter"; + const accent = VARIANT_ACCENTS[variant] ?? ORANGE; return ( + {/* Corner chrome, shared grammar with the vitrine header (drawn + duck head, top-left) and the in-game HUD (pre-order, top-right): + the title screen wears the same screen furniture as the game. + Gated with the rest of the reveal so the loading state is a + single centered spinner on bare ink. */} + {ready && ( - {/* Vitrine brand lockup: drawn duck head + name. Hovering swaps to - the open-beak frame, same hard sprite swap as the vitrine. */} + {/* The open frame's canvas (460x333) is a hair wider/taller + than the closed one (454x269); offsets pin the head while + the jaw hangs below. */} + + + + Microduck + + + )} + + {/* The in-game HUD's shop plate, verbatim: same component, same + fixed spot, so pausing never swaps it for a lookalike. */} + {ready && } + + {/* Loading gate: one centered spinner on bare ink until logo, + fonts, the duck stage's assets and the game boot are all in - + then the whole composition (corner chrome included) reveals at + once (row stagger + entrance scan). */} + {!ready && ( + + + - - {/* The open frame's canvas (460x333) is a hair wider/taller - than the closed one (454x269); offsets pin the head while - the jaw hangs below. */} - - + Loading + + )} + {/* Split title screen: brand + CTA column on the left, the live + duck stage on the right (stacked on narrow screens). The row + stretches to fill the space between the corner chrome and the + bottom strip, so the duck stands ON the strip's rule - the + screen has a floor instead of elements floating mid-air. */} + {ready && ( + <> + + {/* The landing hero's mistracked-VHS treatment: orange fill with ink drop + chroma ghosts, hollow echo line below. */} + {/* CTA + key prompt travel as one block so the prompt stays + centred under the button whatever the column's alignment. */} - {tiles.map((t) => ( - - - {t.caps === "cluster-arrows" ? ( - - - {"\u2191"} - - - {"\u2190"} - {"\u2193"} - {"\u2192"} - - - ) : ( - - {t.caps.map((c) => ( - {c} - ))} - - )} - - - {t.name} - - - {t.hint} - - - ))} - - - - {HINTS[tutorialVariant]} - - - + {/* Pad prompt: ink circle with the A face button, shown while a + gamepad is connected - it mirrors the A-to-enter binding of + the poll loop above. Decorative; the text label carries the + meaning. */} + {padConnected && ( + + A + + )} {ctaLabel} + + {enterHint && ( + + + {enterHint} + + + )} + + {/* Right column: the duck's simulated twin, live - head follows the + pointer, click quacks. Its colourway tracks the in-game duck. No + backdrop, no fake shadow: the render alone, standing on the + bottom strip's rule like a character select. Touch devices skip + the stage entirely (no column, no GLB download). */} + {showDuck && ( + + + + )} + + + {/* Bottom cheat strip: every move on one wrapping line, arcade + instruction-card style. Reference material, not the main event - + it sits at the screen's bottom edge, out of the CTA's way. */} + + + {shortcuts.map((s) => ( + + + {s.caps.map((c) => ( + {c} + ))} + + + {s.name} + + + ))} + + + + {HINTS[tutorialVariant]} + + + + )} ); }